@indiegems/gem-web-sdk 10.3.1 → 10.4.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 hc=Object.defineProperty;var fc=(n,e)=>{for(var t in e)hc(n,t,{get:e[t],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:10.3.1]";function Ni(){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 bc(n,e){return e!==void 0?!e:n==="chain_exhausted"}var it=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 le(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 le("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 le("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=_c(o),a=o?.retryable;throw t===this.generation&&this.enter(bc(i,typeof a=="boolean"?a:void 0)?"lost":"degraded",i),o instanceof le?o:new le(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)}},le=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 _c(n){if(n instanceof le)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}},Gr=["if-match","if-none-match"],Ui=4096;function vc(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n)){let o=t.toLowerCase();if(!Gr.includes(o)||r===void 0)continue;let i=typeof r=="string"?wc(r):r;if(typeof i!="string"||i.length>Ui||!kc(i))throw new oe(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Ui} 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 wc(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 kc(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 Sc(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 Bi(n,e){let t=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=vc(o.headers),a=Sc(o),s=Object.freeze({...o,headers:i,...a===void 0?{}:{bytes:a}}),l=await e.tokenSource.get(),d=await n(s,l);if(d.status!==401||!t)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),u=await n(s,m);if(u.status===401)throw e.tokenSource.close("unavailable"),new le("unavailable","the server refused a freshly minted token");return u}}}function Dr(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return btoa(Rc(e))}function _n(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 $r(n){return new TextDecoder().decode(_n(n))}function Rc(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,o,i,a){super(`${t} (${r}): ${o}`);this.reason=t;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Hi=new WeakMap;function Wi(n){return Hi.get(n)??{}}var xc=new Set([408,429,500,502,503,504]),Ac=6e4;function Pc(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 Ne=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,...At(o)},o.replaySafe===true)}async post(e,t,r,o={}){return this.send({method:"POST",path:e,body:t,signal:r,...At(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,...At(o)},o.replaySafe===true);return {bytes:Ec(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,...At(o)},o.replaySafe===true)}async delete(e,t,r={}){return this.send({method:"DELETE",path:e,signal:t,...At(r)},r.replaySafe===true)}async send(e,t){return (await this.sendRaw(e,t)).body}async sendRaw(e,t){let r=t?Pc(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw Vi(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw Vi(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(le.isAuthError(l)||oe.isRefusal(l)||e.signal?.aborted||Tc(l))throw l;o=new L("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=Cc(a);if(!xc.has(a.status))throw s;o=s;}throw o??new L("unavailable",0,"no attempt was made")}backoff(e,t,r){if(r?.aborted)return Promise.resolve();let o=t?.retryAfterSeconds,i=o!==void 0?o*1e3:2**(e-1)*250,a=2**(e-1)*250,s=Math.min(Math.max(i,a),Ac);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,s),u=true,m&&d.clearTimeout(p);})}};function Ec(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 At(n){return {...n.keepalive===void 0?{}:{keepalive:n.keepalive},...n.ifMatch===void 0?{}:{headers:{"if-match":n.ifMatch}}}}function Vi(n){return n.reason!==void 0?n.reason:new DOMException("The operation was aborted.","AbortError")}function Tc(n){let e=n?.name;return e==="AbortError"||e==="TimeoutError"}function Cc(n){let e=Mc(n),t=Lc(n.body),r={...t===void 0?{}:{details:t},...n.invocationId===void 0?{}:{invocationId:n.invocationId}};return Object.keys(r).length>0&&Hi.set(e,r),e}var Ic=new Map([["insufficient_funds","insufficient_funds"]]);function Mc(n){let{status:e,body:t}=n,r=Oc(t),o=n.retryAfterSeconds??Dc(t),i=Gc(t),a=i===void 0?void 0:Ic.get(i);if(a!==void 0)return new L(a,e,r,void 0,i);switch(e){case 304:return new L("not_modified",e,r);case 400:case 422:return new L("invalid",e,r,void 0,i);case 403:return new L("forbidden",e,r,void 0,i);case 404:return new L("not_found",e,r,void 0,i);case 402:return new L("insufficient_funds",e,r,void 0,i);case 409:return new L("conflict",e,r,void 0,i);case 412:return new L("precondition_failed",e,r,void 0,i);case 413:return new L("too_large",e,r,void 0,i);case 429:return new L("rate_limited",e,r,o,i);default:return new L("unavailable",e,r,o,i)}}function Oc(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 Lc(n){let t=n?.error?.details;return t===null?void 0:t}function Gc(n){let t=n?.error?.code;return typeof t=="string"&&t.length>0?t:void 0}function Dc(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 Ki(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function Ji(n,e,t,r,o,i){let a=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/add`;return n.client.post(a,o,i?.signal)}async function zi(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function Yi(n,e,t){let r=`/v1/games/${v(n.gameId())}/matchmaking/tickets/${v(e)}`;return n.client.delete(r,t?.signal)}async function Xi(n,e,t,r,o,i){let a=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/claim`;return n.client.post(a,o,i?.signal)}async function Qi(n,e,t){return n.client.post("/v1/characters",e,t?.signal)}async function Zi(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/orders/batch`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ea(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/orders`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ta(n,e,t){let r=`/v1/games/${v(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function na(n,e,t,r,o){let i=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.delete(i,o?.signal)}async function ra(n,e,t,r,o){let i=`/v1/saves/${v(e)}/${v(t)}/${v(r)}`;return n.client.delete(i,o?.signal)}async function oa(n,e,t,r){let o=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.delete(o,r?.signal)}async function ia(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/recipes/execute`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function aa(n,e,t,r,o,i){let a=`/v1/saves/${v(e)}/${v(t)}/${v(r)}/finalize`;return n.client.post(a,o,i?.signal)}async function sa(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 la(n,e,t){let r=`/v1/characters/${v(e)}`;return n.client.get(r,t?.signal)}async function da(n,e,t){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function ca(n,e,t,r,o){let i=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function ua(n,e,t,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function ma(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/items/${v(r)}`;return n.client.get(i,o?.signal)}async function pa(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 a=i.toString(),s=`/v1/leaderboards/${v(e)}/${v(t)}/${v(r)}`+(a?`?${a}`:"");return n.client.get(s,o?.signal)}async function ga(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/orders/${v(r)}`;return n.client.get(i,o?.signal)}async function ya(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}`;return n.client.get(i,o?.signal)}async function ha(n,e,t,r,o,i){let a=`/v1/inventory/${v(e)}/${v(t)}/catalogs/${v(r)}/recipes/${v(o)}/availability`;return n.client.get(a,i?.signal)}async function fa(n,e,t,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(t)}/recipe-usage`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Fr(n,e,t,r,o){let i=`/v1/saves/${v(e)}/${v(t)}/${v(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function ba(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/${v(e)}/friends`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function _a(n,e,t){let r=`/v1/showcase/friends/${v(e)}`;return n.client.get(r,t?.signal)}async function va(n,e,t){let r=`/v1/inbox/friend-challenges/${v(e)}`;return n.client.get(r,t?.signal)}async function wa(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/${v(e)}`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function ka(n,e){let t=`/v1/games/${v(n.gameId())}/players/me/earn-allowance`;return n.client.get(t,e?.signal)}async function vn(n,e){return n.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Sa(n,e,t){let r=`/v1/profiles/players/${v(e)}`;return n.client.get(r,t?.signal)}async function Ra(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 xa(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 Aa(n,e,t,r){let o=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.get(o,r?.signal)}async function Pa(n,e){return n.client.get("/v1/characters/slots",e?.signal)}async function Ea(n,e,t){let r=`/v1/inventory/transfers/${v(e)}`;return n.client.get(r,t?.signal)}async function Ta(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 Ca(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 Ia(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Ma(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/platform-funded-game-inventory-purchases`;return n.client.post(i,r,o?.signal)}async function Oa(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function La(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 Ga(n,e){return n.client.get("/v1/characters",e?.signal)}async function Da(n,e,t,r){let o=`/v1/settings/${v(e)}/${v(t)}`;return n.client.get(o,r?.signal)}async function $a(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(t)}/orders`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Fa(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${v(e)}/${v(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function qa(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 ja(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 Na(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 Ua(n,e,t){let r=`/v1/inbox/friend-challenges/${v(e)}/answered`;return n.client.post(r,void 0,t?.signal)}async function Ba(n,e,t,r){let o=`/v1/games/${v(n.gameId())}/matches/${v(e)}/end`;return n.client.post(o,t,r?.signal)}async function Va(n,e,t,r,o,i){let a=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/max`;return n.client.post(a,o,i?.signal)}async function Ha(n,e,t,r,o,i){let a=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Wa(n,e,t,r,o){let i=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.put(i,r,o?.signal)}async function Ka(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/rewarded-placements/${v(r)}/availability`;return n.client.get(i,o?.signal)}async function Ja(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function za(n,e,t,r){let o=`/v1/characters/${v(e)}`;return n.client.patch(o,t,r?.signal)}async function Ya(n,e,t,r,o,i){let a=`/v1/saves/${v(e)}/${v(t)}/${v(r)}/upload-url`;return n.client.post(a,o,i?.signal,{replaySafe:true})}async function Xa(n,e,t,r,o,i){let a=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/reset`;return n.client.post(a,o,i?.signal)}async function Qa(n,e,t){let r=`/v1/characters/${v(e)}`;return n.client.delete(r,t?.signal)}var N="gem-web-bridge",kn={min:1,max:1},at=65536,Za=8,wn=5e3,es=1024;function ts(n){return Object.freeze(Object.assign(Object.create(null),n))}var ns=ts({"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.controlsDeclare":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}),Sn="__malformed";var $c=ts({"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","gem.controlsDeclare":"controls"}),Fc=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function rs(n){let e=$c[n];if(e!==void 0)return e;for(let[t,r]of Fc)if(n.startsWith(t))return r}function jr(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 qc(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 jc(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Nc(n){return /^[a-z_]+$/.test(n)}function qr(n,e,t){if(e>Za)return `nesting deeper than ${Za}`;if(++t.nodes>wn)return `more than ${wn} values`;if(t.bytes>at)return `over the ${at} byte limit`;if(n==null)return t.bytes+=4,null;let r=typeof n;if(r==="boolean")return t.bytes+=5,null;if(r==="number")return t.bytes+=8,null;if(r==="string")return t.bytes+=n.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let o=n;if(t.seen.has(o))return "a repeated or cyclic object reference";if(t.seen.add(o),Array.isArray(n)){if(n.length>es)return `an array of ${n.length} entries, over the ${es} limit`;t.bytes+=2;for(let s of n){let l=qr(s,e+1,t);if(l)return l}return null}let i=Object.getPrototypeOf(n);if(i!==Object.prototype&&i!==null)return "a value that is not a plain object";t.bytes+=2;let a=n;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++t.nodes>wn)return `more than ${wn} values`;if(t.bytes+=s.length*3+4,t.bytes>at)return `over the ${at} byte limit`;let l=qr(a[s],e+1,t);if(l)return l}return null}function Uc(n){let e={nodes:0,bytes:0,seen:new Set},t=qr(n,0,e);return t?`message contains ${t}`:e.bytes>at?`message is over the ${at} byte limit`:null}var Bc={origin:[jr,"not a well-formed origin"],url:[qc,"not a safe absolute http(s) URL"],bcp47:[jc,"not a well-formed BCP 47 tag"],code:[Nc,"not a code of lower-case letters and underscores"]};function os(n,e,t){for(let r of e){let o=t===""?r.n:`${t}.${r.n}`,i=n[r.n];if(i==null){if(r.o)continue;return `${o}: required`}let a=is(i,r,o);if(a)return a}return null}function is(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]=Bc[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`:os(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 a=is(i,r,o);if(a)return a}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}var as=Object.create(null);function E(n,e){return as[n]=t=>{let r=Uc(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let o=t;return o.gem!==N?"gem: wrong protocol marker":o.type!==n?`type: expected ${n}`:os(o,e,"")}}E("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}]);E("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}}]);E("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}]);E("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}]);E("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}]}]);E("gem.pause",[{n:"paused",k:"b"}]);E("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}]);E("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}]}}]);E("gem.earnAllowanceChanged",[]);E("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}]}}]);E("gem.deviceSettings",[{n:"settings",k:"j",o:1}]);E("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}]);E("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"]}]);E("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}]);E("gem.seatedEvent",[{n:"roomId",k:"s",max:64}]);E("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}]);E("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"}]);E("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}]);E("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}]);E("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}]);E("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}]);E("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}]);E("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}]);E("gem.requestContext",[]);E("gem.gameContext",[{n:"context",k:"j"}]);E("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]);E("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}]);E("gem.partyRequest",[{n:"requestId",k:"s",max:64}]);E("gem.ready",[]);E("gem.engaged",[]);E("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}]);E("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}]);E("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}]);E("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}]);E("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}]);E("gem.exit",[{n:"reason",k:"s",o:1,max:64}]);E("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}]);E("gem.requestFullscreen",[{n:"enabled",k:"b"}]);E("gem.audioState",[{n:"muted",k:"b"}]);E("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}]}]);E("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}]);E("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}]);E("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}]}}]);E("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}]);E("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}]}}]);E("gem.requestAvatarPicker",[]);E("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}]);E("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5}]);E("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}]);E("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}]);E("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}]);E("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}]);E("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}]);E("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}]);E("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}]);E("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}]);E("gem.requestSignIn",[{n:"requestId",k:"s",max:64}]);E("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}]);E("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}]);E("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}]);var Rn=Object.freeze(as);var ge={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},Pt=class{constructor(e=ge){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=ns[e];if(t===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??t,a=Math.max(0,r-o),s=Math.min(t,i+a*t/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function Nr(n,e){return n.toLowerCase()===e.toLowerCase()}function xn(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function ss(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:xn(t.hostname)&&xn(r.hostname)}function ls(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 An=class{constructor(e,t){this.inventory=e;this.resolveCurrencyId=t;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,t={}){let o=(await this.inventory.snapshot({buckets:t.buckets})).currencies.data,i=o.find(s=>s.currencyId===e),a;return !i&&this.resolveCurrencyId&&(a=await this.resolveCurrencyId(e).catch(()=>{}),a!==void 0&&(i=o.find(s=>s.currencyId===a))),{currencyId:i?i.currencyId:a??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function Br(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 ds="inventory",st=n=>typeof n=="number"?n:0,Et=n=>typeof n=="string"?n:"";function Ur(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 cs(n){let e=n??{};return {itemDefinitionId:Et(e.item_definition_id),instanceId:Et(e.instance_id),quantity:st(e.quantity),acquiredAt:st(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function Vc(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {currencies:Ur(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(a=>{let s=a??{};return {bucket:Et(s.bucket),balance:st(s.balance)}}):void 0;return {currencyId:Et(o.currency_id),total:st(o.total),...i===void 0?{}:{buckets:i}}}),items:Ur(e.items,cs),progressions:Ur(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:Et(o.progression_definition_id),currentValue:st(o.current_value),completionCount:st(o.completion_count),isCompleted:o.is_completed===true,...Br(o)}}),...t===void 0?{}:{etag:t}}}var Pn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;snapshot(e={}){let t=e.buckets?`${ds}#buckets`:ds;return this.cache.read(t,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,t){let r=await this.snapshot();if(r.items.nextCursor===void 0){let i=r.items.data.filter(a=>a.itemDefinitionId===e);if(i.length>0)return i}let o=await ma(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Array.isArray(o)?o.map(cs):[]}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 ua(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 Vc(t)}};var Hc={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},Wc=new Set(Object.keys(Hc));function us(n){return typeof n=="string"&&Wc.has(n)?n:"error"}var Ge=class extends RangeError{constructor(t,r){super(r);this.code=t;this.name="PurchaseRefusal";}code;retryable=false};var Z=n=>typeof n=="string"?n:"",Kc=n=>typeof n=="string"?n:Z(n&&typeof n=="object"?n.type:void 0),Se=n=>typeof n=="number"?n:0;function Jc(n){let e=n??{};return {prerequisiteType:Z(e.prerequisite_type),referenceId:Z(e.reference_id),required:Se(e.required),current:Se(e.current)}}function Tt(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {orderId:Z(e.order_id),status:Z(e.status),...t===void 0?{}:{etag:t}}}function En(){return crypto.randomUUID()}var zc="recipe-usage",ms=100;function Tn(n){let e=n??{};switch(e.type){case "currency":return {kind:"currency",currencyId:Z(e.currency_id),bucket:Z(e.bucket),delta:Se(e.delta),balanceAfter:Se(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:Z(e.item_definition_id),instanceId:Z(e.instance_id),delta:Se(e.delta),quantityAfter:Se(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:Z(e.progression_definition_id),delta:Se(e.delta),valueAfter:Se(e.value_after),completed:e.completed===true};default:return {kind:"other",type:Z(e.type)}}}function Yc(n){let e=n??{},t=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:Z(e.entry_id),...t===void 0?{}:{rarityTier:t},rollNumber:Se(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(Tn):[]}}function Xc(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(Yc):void 0;return {orderId:Z(e.order_id),status:Z(e.status),...t===void 0?{}:{etag:t},granted:Array.isArray(e.granted)?e.granted.map(Tn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(Tn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(Tn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Qc(n){let e=n??{},t=e.price??{};return {payment:"platform_currency",orderId:Z(e.target_order_id)||Z(e.source_order_id),status:Z(e.status),purchaseId:Z(e.purchase_id),sourceOrderId:Z(e.source_order_id),price:{currencyId:Z(t.platform_currency_id),amount:Se(t.price)}}}function Zc(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:Z(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 ps(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 Cn=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(()=>ea(this.api,this.entity.type,this.entity.id,{operations:e.map(ps),source:t.source??"play",nonce:En()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return Tt(r)}async createMany(e,t={}){return this.write(()=>Zi(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(ps),nonce:En()})),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 ha(this.api,this.entity.type,this.entity.id,e,t,r===void 0?{}:{signal:r})??{},a=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,s=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(Jc):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>Kc(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(zc,[],async()=>{let t=await fa(this.api,this.entity.type,this.entity.id,{limit:ms})??{},r=Array.isArray(t.usages)?t.usages:[];return {usages:r.map(Zc),truncated:r.length>=ms}})}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(()=>ia(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:En()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return {payment:"configured",...Xc(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([Ra(this.api,t.signal===void 0?{}:{signal:t.signal}),vn(this.api,t.signal===void 0?{}:{signal:t.signal})]),i=e.payment.currencySlug.toLowerCase(),a=o.currencies.find(u=>u.currency_id.toLowerCase()===i||u.slug.toLowerCase()===i);if(a===void 0){let u=o.currencies.map(p=>p.slug);throw new Ge("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let s=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(s===void 0)throw new Ge("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=s.platform_prices.find(u=>u.platform_currency_id===a.currency_id);if(l===void 0){let u=g=>o.currencies.find(y=>y.currency_id===g)?.slug??g,p=s.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new Ge("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${a.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Ge("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>Ma(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:a.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:En(),confirmation:"none"},t.signal===void 0?{}:{signal:t.signal}));return Qc(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(()=>Ji(this.api,this.entity.type,this.entity.id,e,{amount:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Tt(o)}async maxProgression(e,t,r){let o=await this.write(()=>Va(this.api,this.entity.type,this.entity.id,e,{value:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Tt(o)}async claimProgression(e,t){let r=await this.write(()=>Xi(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Tt(r)}async resetProgression(e,t){let r=await this.write(()=>Xa(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Tt(r)}async write(e){return this.cache.invalidate(),e()}};var Vr=n=>typeof n=="string"?n:"",eu=n=>typeof n=="number"?n:0;function gs(n){let e=n??{};return {orderId:Vr(e.order_id),status:Vr(e.status),source:Vr(e.source),createdAt:eu(e.created_at)}}var In=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e={}){let r=await $a(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(gs):[],...o===void 0?{}:{nextCursor:o}}}async get(e,t){let r=await ga(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return gs(r)}};var ys=n=>typeof n=="number"?n:0,tu=n=>typeof n=="string"?n:"";function nu(n){let e=n??{};return {progressionDefinitionId:tu(e.progression_definition_id),currentValue:ys(e.current_value),completionCount:ys(e.completion_count),isCompleted:e.is_completed===true,...Br(e)}}var Mn=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 ya(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return nu(i)}catch{return o??null}}};var On=class{constructor(e,t){this.clock=e;this.identity=t;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,t,r,o){this.rebind();let i=t.length===0,a=i?e:e+"\0"+t.join("\0"),s=this.slots.get(a);if(s){let u=s.filledAt;if(u!==void 0&&(o===void 0||this.clock.now()-u<=o))return Promise.resolve(s.value);if(s.inFlight)return s.inFlight}let l=s??{};this.slots.set(a,l);let d=this.generation,m=r().then(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(a)===l&&this.slots.delete(a));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function Hr(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 Wr(n){try{let e=Hr(await n.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ie=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemSaveError";}reason},ru=3e4,hs="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",ou=/^[A-Za-z0-9_]{1,64}$/;function Re(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(!ou.test(n)||n.startsWith("_"))throw new TypeError(`${JSON.stringify(n)} is not a usable save key: ${e}.`);return n}function fs(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 Kr(n,e){return n.aborted&&e?.aborted!==true}var iu=new Set(["x-ms-blob-type"]),au=/^[ -~]+$/;function su(n,e){if(n==null)return {};if(typeof n!="object"||Array.isArray(n))throw new ie("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(!iu.has(i))throw new ie("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"||!au.test(o))throw new ie("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 ie("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);t[i]=o;}return t}function Jr(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 zr(n){return n?.reason==="not_found"}var Ln=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 ie("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 ie("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,t,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),a=fs(r.signal,i);try{let s=await Ya(this.api,this.entity.type,this.entity.id,Re(e),{size_bytes:t.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:a.signal});if(typeof s.upload_url!="string"||typeof s.session_id!="string")throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=su(s.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(s.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:t,credentials:"omit",signal:a.signal});}catch(u){throw Kr(a.signal,r.signal)?this.timeout("upload",i):new ie("upload_failed",`${hs} for PUT. Underlying error: ${u}`)}if(!d.ok){let u=await Wr(d);throw new ie("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 Jr(await aa(this.api,this.entity.type,this.entity.id,Re(e),{session_id:s.session_id},{signal:a.signal}))}catch(s){throw this.rethrow(s,r.signal,a.signal,"save",i)}finally{a.release();}}async get(e,t={}){let r=await this.getBytes(e,t);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new ie("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=fs(t.signal,r);try{let i;try{let l=await Fr(this.api,this.entity.type,this.entity.id,Re(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(zr(l))return null;throw l}if(typeof i.download_url!="string")throw new ie("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),s;try{s=await a(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw Kr(o.signal,t.signal)?this.timeout("download",r):new ie("download_failed",`${hs} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await Wr(s);throw new ie("download_failed",`the save download answered ${s.status}. `+(s.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await s.arrayBuffer())}catch(i){throw this.rethrow(i,t.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,t={}){try{let r=await Fr(this.api,this.entity.type,this.entity.id,Re(e),{...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}});return r.modified?Jr(r.body):null}catch(r){if(zr(r))return null;throw r}}async list(e={}){let t=await Fa(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(Jr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,t){try{await ra(this.api,this.entity.type,this.entity.id,Re(e),{...t===void 0?{}:{signal:t}});}catch(r){if(!zr(r))throw r}}budget(e){return e??this.options.timeoutMs??ru}timeout(e,t){return new ie("save_timeout",`the save ${e} did not finish within ${t}ms`)}rethrow(e,t,r,o,i){return e instanceof ie?e:Kr(r,t)?this.timeout(o,i):e}};function lu(n){try{return $r(n)}catch{return n}}function Yr(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"?lu(t.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof t.updated_at=="number"?t.updated_at:0}}var Gn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e){let r=(await Da(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>Yr(o)):[]}async get(e,t={}){try{let r=await ca(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?Yr(r.body,r.etag):null}catch(r){if(bs(r))return null;throw r}}async put(e,t,r={}){let o=await Ha(this.api,this.entity.type,this.entity.id,e,{value:Dr(t)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Yr(o)}async delete(e,t){try{await na(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});}catch(r){if(!bs(r))throw r}}};function bs(n){return n?.reason==="not_found"}function Dn(n,e,t={}){let r=new On(ge,t.identity);t.onInventoryChanged&&r.onInvalidate(t.onInventoryChanged);let o=new Pn(n,e,r);return {settings:new Gn(n,e),inventory:o,saves:new Ln(n,e,t.saves??{}),currencies:new An(o,t.resolveCurrencyId),mutations:new Cn(n,e,r),orders:new In(n,e),progressions:new Mn(n,e,o)}}var Xr={type:"players",id:"me"};var Ue=n=>typeof n=="string"?n:"",lt=n=>typeof n=="number"?n:0;function $n(n,e){let t=e??{},r=Ue(t.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...n(r),id:r,playerId:Ue(t.player_id),gameId:Ue(t.game_id),channel:Ue(t.channel)||"release",name:Ue(t.name),slotIndex:lt(t.slot_index),isActive:t.is_active!==false,createdAt:Ue(t.created_at),updatedAt:Ue(t.updated_at)}}var Fn=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=Dn(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 Ga(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>$n(this.scope,o)):[]}async get(e,t){let r=await la(this.api,e,t===void 0?{}:{signal:t});return $n(this.scope,r)}async create(e){let t=await Qi(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return $n(this.scope,t)}async update(e,t,r){let o=await za(this.api,e,{name:t},r===void 0?{}:{signal:r});return $n(this.scope,o)}async delete(e,t){await Qa(this.api,e,t===void 0?{}:{signal:t});}async slots(e){let r=await Pa(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:lt(r?.total_slots),availableSlots:lt(r?.available_slots),activeCharacterCount:lt(r?.active_character_count),defaultMaxSlots:lt(r?.default_max_slots),purchasedExtraSlots:lt(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 Oe(n){return new ye(n)}var dt={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 qn(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:Oe(t)},createdAt:ct(e.created_at),expiresAt:ct(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function du(){return crypto.randomUUID()}var jn=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 Ia(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:du()},e.signal===void 0?{}:{signal:e.signal});return qn(t)}async list(e={}){let r=await Na(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(qn):[],...o===void 0?{}:{nextCursor:o}}}async get(e,t){let r=await Ea(this.api,e,t===void 0?{}:{signal:t});return qn(r)}async accept(e,t){return this.resolve(()=>Ki(this.api,e,t===void 0?{}:{signal:t}))}async reject(e,t){return this.resolve(()=>Ja(this.api,e,t===void 0?{}:{signal:t}))}async cancel(e,t){return this.resolve(()=>zi(this.api,e,t===void 0?{}:{signal:t}))}async resolve(e){return this.inventory.invalidate(),qn(await e())}};var cu=n=>typeof n=="string"?n:"",uu=n=>typeof n=="string"&&n?n:void 0,mu=n=>typeof n=="number"?n:void 0;function _s(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 pu(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=mu(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=cu(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 a=t("currencies");a.forEach((l,d)=>o(l??{},"currencies",d));let s=n;return {...s,version:r,hash:typeof s.hash=="string"?s.hash:"",items:i,currencies:a,catalogs:t("catalogs"),loot_tables:t("loot_tables"),affix_pools:t("affix_pools"),progressions:t("progressions"),game_room_templates:t("game_room_templates"),kv:typeof s.kv=="object"&&s.kv!==null&&!Array.isArray(s.kv)?s.kv:{},item:_s(i),currency:_s(a)}}var ce=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemConfigError";}reason},vs=10*1024*1024,ws=15e3,ks=new Set(["dev","test","release"]);function gu(n){if(!ks.has(n))throw new ce("config_channel_unknown",`the play token names channel "${n}", which is not one of ${[...ks].join(", ")}. gem-api would reject the assignment read.`);return n}var Nn=n=>typeof n=="number"?n:0,Qr=n=>typeof n=="string"?n:"";function yu(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:Qr(o.entry_id),weight:Nn(o.weight),dropRate:Nn(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:Qr(e.loot_table_id),name:Qr(e.name),rollCount:Nn(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Nn(e.total_weight),entries:t}}var Un=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 a=(async()=>{let s=await da(this.api,e,t===void 0?{}:{signal:t});return yu(s)})().catch(s=>{throw o?.get(e)===a&&o.delete(e),s});return o.set(e,a),a}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??ws),t;try{let l=await sa(this.api,gu(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=uu(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??ws}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=>Hr(d)).catch(()=>"");throw new ce("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await i.text();if(a.length>vs)throw new ce("config_too_large",`the config document is ${a.length} bytes, over the ${vs} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new ce("config_malformed",`config document is not JSON: ${String(l)}`)}return pu(s)}};var Ss=400,xe=n=>typeof n=="string"?n:"",hu=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Be(n){let e=xe(n);if(!hu.test(e))return 0;let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):0}var fu=/^[0-9a-f]{1,64}$/,bu=/^[0-9a-f]{16}$/,_u=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,vu=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Zr(n){let e=xe(n),t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return;let[r,o,i]=[Number(t[1]),Number(t[2]),Number(t[3])],a=new Date(Date.UTC(r,o-1,i));return a.getUTCFullYear()===r&&a.getUTCMonth()===o-1&&a.getUTCDate()===i?e:void 0}var wu=4096,ku=new TextEncoder;function Su(n){let e=xe(n.challenge_data),t=xe(n.challenge_data_hash);return e===""||!bu.test(t)?{}:ku.encode(e).length>wu?{}:{data:e,dataHash:t}}function Ru(n){let e=n??{},t=Be(e.period_start_at),r=Be(e.period_ends_at);if(t===0||r===0)return;let o=xe(e.slug),i=xe(e.seed),a=Zr(e.period_local_date),s=xe(e.boundary),l=xe(e.reset_time);return {id:xe(e.progression_definition_id),...o===""?{}:{slug:o},window:xe(e.window),periodStartAt:t,periodEndsAt:r,...a===void 0?{}:{periodLocalDate:a},boundary:_u.test(s)?s:"",resetTime:vu.test(l)?l:"",seed:fu.test(i)?i:"",...Su(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 Bn(n){let e=n??{};return Array.isArray(e.challenges)?e.challenges.map(Ru).filter(t=>t!==void 0):[]}var Ct=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:t}=e;ut(t);let r=await La(this.#e,{...t===void 0?{}:{periods_back:t},...e.signal===void 0?{}:{signal:e.signal}});return Bn(r)}};function Ve(n){return typeof n=="string"&&n!==""?n:void 0}var Rs=new Set(["localhost","127.0.0.1","[::1]"]);function eo(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:"&&Rs.has(t.hostname)))return e}function xu(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},o=Ve(r.item_id),i=eo(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function _e(n){let e=n??{},t=Ve(e.player_id),r=Ve(e.display_name),o=Ve(e.discriminator),i=Ve(e.display_tag),a=Ve(e.avatar_icon_id),s=eo(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:Oe(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:Oe(i)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:xu(e.badges)}}var Au=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Pu(n){if(n===void 0)return;let e=eo(n);if(e===void 0)return;let t=new URL(e);return Rs.has(t.hostname)||Au.has(t.origin)?e:void 0}var xs=100,Es=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function to(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"||!Es.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 Ts(n){let e=typeof n.period_id=="string"?n.period_id:"";if(!Es.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,Mt=n=>typeof n=="string"?n:void 0,Eu=n=>typeof n=="number"?n:void 0,Cs={player:"players",character:"characters"};function Tu(n,e){let t=n??{},r=Mt(t.entity_id),o=typeof t.entity_type=="string"&&Object.hasOwn(Cs,t.entity_type)?t.entity_type:void 0,i=Is(t.stats),a=t.properties!==null&&typeof t.properties=="object"?t.properties:void 0,s=e?t.is_viewer===true:void 0;return {..._e(t),rank:mt(t.rank),occurredAt:mt(t.occurred_at),...s===void 0?{}:{isViewer:s},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...a===void 0?{}:{properties:a}}}function As(n,e){let t=n??{},r=Mt(t.bucket_1),o=Mt(t.bucket_2),i=Eu(t.update_frequency_seconds),a=Ts(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(s=>Tu(s,e)):[],generatedAt:mt(t.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...a===void 0?{}:{period:a}}}function Ps(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n;if(!Number.isFinite(e.rank))return;let t=Is(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 Is(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 Cu(n,e,t){let r=n??{},o=Mt(r.bucket_1),i=Mt(r.bucket_2),a=Ts(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(Ps).filter(s=>s!==void 0):[],personalBest:Ps(r.personal_best)??null,totalRuns:mt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:mt(r.generated_at),...a===void 0?{}:{period:a}}}var Ot=class{#e;constructor(e){this.#e=e;}async get(e,t={}){let r=to(t),o=await wa(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 As(o,false)}async friends(e,t={}){let r=to(t),o=await ba(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 As(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>xs)throw new TypeError(`limit must be an integer between 1 and ${xs}, got ${String(l)}`)}let i=to(o),a=await pa(this.#e,e,Cs[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}}),s=t==="player"&&r==="me"&&It((a??{}).entity_id)||r;return Cu(a,t,s)}};var Vn=n=>typeof n=="string"?n:"",no=n=>typeof n=="number"?n:0;function Ms(n){let e=n??{};return {playerId:Vn(e.player_id),key:Vn(e.key),value:e.value,updatedAt:no(e.updated_at)}}function Iu(n){let e=n??{};return {..._e(e),playerId:Vn(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:no(e.updated_at)}}function Mu(n){return n?.reason==="not_found"}var Lt=class{constructor(e,t){this.api=e;this.selfPlayerId=t;}api;selfPlayerId;async friends(e,t={}){let o=await _a(this.api,Re(e),{...t.signal===void 0?{}:{signal:t.signal}})??{};return {key:Vn(o.key),entries:Array.isArray(o.entries)?o.entries.map(Iu):[],generatedAt:no(o.generated_at)}}async of(e,t,r={}){try{return Ms(await Aa(this.api,e,Re(t),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(Mu(o))return null;throw o}}async set(e,t,r={}){if(Re(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 Ms(await Wa(this.api,o,e,{value:t},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,t={}){let r=await this.selfPlayerId();await oa(this.api,r,Re(e),{...t.signal===void 0?{}:{signal:t.signal}});}};var Ou="gemChallenge",Os=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ls(n){if(!(typeof n!="string"||n===""))try{return new URLSearchParams(n).get(Ou)??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,o]of Object.entries(t))o!==void 0&&Object.assign(this,{[r]:o});}},Hn=n=>typeof n=="string"?n:void 0;function Gs(n){let e=n??{};return {..._e(e),playerId:Hn(e.player_id)??""}}function Ds(n){let e=n.has_more===true?Hn(n.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function Lu(n){let e=n??{};return {friends:Array.isArray(e.data)?e.data.map(Gs):[],...Ds(e)}}var ro=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0;function Gu(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 $s(n){let e=n??{},t=ro(e.opened_at),r=ro(e.answered_at);return {id:Hn(e.item_id)??"",from:Gs(e.sender),template:Hn(e.template)??"",params:Gu(e.params),createdAt:ro(e.created_at)??0,...t===void 0?{}:{openedAt:t},...r===void 0?{}:{answeredAt:r}}}function Du(n){let e=n??{};return {challenges:Array.isArray(e.data)?e.data.map($s):[],...Ds(e)}}function $u(n){let e=n;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Gt=class{#e;#n;#i;constructor(e,t={}){this.#e=e,this.#n=t.challenge,this.#i=t.launchedChallengeId;}async list(e={}){let t=await ja(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Lu(t)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let t=await qa(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Du(t)}async launchedChallenge(e={}){let t=this.#i;if(t===void 0||!Os.test(t))return null;try{return $s(await va(this.#e,t,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if($u(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!Os.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 Ua(this.#e,e);}};var Fu=0;function Ae(){try{return crypto.randomUUID()}catch{let n=Math.random().toString(36).slice(2,10);return `local-${String(++Fu)}-${String(Date.now())}-${n}`}}var qu=12e4,Fs=8,ju=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Nu=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Dt(n,e,t={}){return new He(new L("invalid",400,e,void 0,n),t)}function Uu(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Bu(n){let{playerId:e,template:t,params:r}=n??{};if(typeof e!="string"||!ju.test(e))return {error:Dt("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof t!="string"||!Nu.test(t))return {error:Dt("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(!Uu(r))return {error:Dt("param_invalid","params must be a plain object of strings and integers")};let o={},i=Object.keys(r);for(let a of i){let s=r[a];if(typeof s=="string"||typeof s=="number"&&Number.isSafeInteger(s)){Object.defineProperty(o,a,{value:s,enumerable:true,writable:true,configurable:true});continue}return {error:Dt("param_invalid",`params.${a} must be a string or a safe integer`,{param:a})}}return i.length>Fs?{error:Dt("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(Fs)}`)}:{playerId:e,template:t,params:o}}function Vu(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 Hu(n){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(n.outcome)?n.outcome:"unknown"}function qs(n){let e=new Map;return {challenge(t){if(!n.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=Bu(t);if("error"in r)return Promise.reject(r.error);let o=`challenge-${Ae()}`;return new Promise((i,a)=>{let s={},l=m=>{e.delete(o)&&(n.clock.clearTimeout(s.timer),"error"in m?a(m.error):i(m.outcome));};e.set(o,l),s.timer=n.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},n.timeoutMs??qu);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 (${Hu(t)}) for an unknown requestId: `+JSON.stringify(t.requestId));return}r(Vu(t));}}}var Wn=n=>typeof n=="string"?n:void 0;function Wu(n){let e=n??{},t=Wn(e.currency_id);if(t===void 0||t==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Wn(e.slug)??"",currencyId:t,balance:r,access:e.access==="spend"?"spend":"read"}}var Kn=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await vn(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=Wu(i);a!==void 0&&o.push(a);}return o}},oo=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.floor(n):0;function Ku(n){let e=n??{},t=Wn(e.currency_id);if(t===void 0||t==="")return;let r=oo(e.limit),o=Math.min(oo(e.earned),r),i=Math.min(oo(e.remaining),r-o),a=e.period_days,s=typeof a=="number"&&Number.isInteger(a)&&a>=1?a:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Wn(e.currency_slug)??"",currencyId:t,limit:r,earned:o,remaining:i,period:e.period==="day"?"day":"window",periodDays:s,...d===void 0?{}:{resetsAt:d}}}function js(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 Jn=class{#e;#n;#i;constructor(e,t,r){this.#e=e,this.#n=t,this.#i=r;}async get(e={}){let r=(await ka(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=Ku(i);a!==void 0&&o.push(a);}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)??(()=>{})}},$t=class{currencies;earnAllowance;constructor(e,t,r){this.currencies=new Kn(e),this.earnAllowance=new Jn(e,t,r);}};var io=n=>typeof n=="string"?n:"",Ns=n=>typeof n=="number"?n:0;function Ju(n){let e=n??{};return {key:io(e.key),visibility:io(e.visibility),value:e.value,updatedAt:Ns(e.updated_at)}}function zu(n){let e=n??{};return {..._e(e),playerId:io(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Ju):[],generatedAt:Ns(e.generated_at)}}function Yu(n){return n?.reason==="not_found"}var Ft=class{#e;constructor(e){this.#e=e;}async of(e,t={}){try{return zu(await Sa(this.#e,e,{...t.signal===void 0?{}:{signal:t.signal}}))}catch(r){if(Yu(r))return null;throw r}}};var Xu=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]]),zn=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:Xu.get(this.code))??super.retryable}},We=class{#e;constructor(e){this.#e=e;}async invoke(e,t={}){let r=Qu(e),o;try{o=await this.#e(r,t.signal===void 0?{}:{signal:t.signal});}catch(i){throw i instanceof L?em(i):i}return Zu(o)}};function Qu(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 Zu(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 em(n){let{details:e,invocationId:t}=Wi(n),o=e?.untrusted?.message,i=e?.reason;return new zn(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 tm=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],ao="gem_";function Us(n){return n.startsWith(ao)}var Bs=1e4,Vs=50,nm=500,rm=65536-4*1024,om=24*1024;function Hs(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 Ws=n=>typeof n=="number"?n:0,im=n=>typeof n=="string"?n:"";function so(n=0){return {accepted:0,rejected:[],dropped:n,duplicate:false}}function am(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(o=>{let i=o??{};return {index:Ws(i.index),code:im(i.code)}}):[];return {accepted:Ws(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function lo(){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 sm(n){return n?.retryable===true}var qt=class{#e;#n;#i;#y;#t=[];#h={};#a=0;#s=null;#f=false;#b=false;#_=false;#r=false;#v=null;#l=null;#d=false;#o=false;#m=false;#w=false;#k=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#i=Math.max(Bs,e.options?.flushIntervalMs??Bs),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??nm));}track(e,t={}){if(!(!this.#n||this.#r)){if(Us(e)){this.#k||(this.#k=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.#S(e,Hs({...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 so();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.")),so();if(this.#R(),this.#t.length===0)return so();let r=e.keepalive===true;this.#u();let o=this.#t.splice(0,this.#A(r)),i=this.#a;this.#a=0;let a=Math.round(this.#e.clock.now()),s={batch_id:lo(),sent_at_ms:a,events:o.map(d=>Ks(d,a))},l={client:this.#e.client(),gameId:()=>t};this.#_=true;try{let d=await Ca(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=am(d,i);return this.#P(m),m}catch(d){throw sm(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.#_=false,this.#t.length>0&&this.#c();}}trackPlatform(e,t={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#S(e,Hs(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:lo(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Vs?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}#S(e,t){let{dimensions:r,measures:o}=t;for(this.#R();this.#t.length>=this.#y;)this.#t.shift(),this.#a+=1;this.#t.push({uid:lo(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=Vs?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?om:rm,r=Math.min(this.#t.length,100),o=128;for(let i=0;i<r;i+=1){let a=this.#t[i];if(a===void 0)break;if(o+=JSON.stringify(Ks(a,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.#_||(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);}#R(){let e=this.#T();e===null||e===""||(this.#v!==null&&this.#v!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#d=false),this.#v=e);}#P(e){for(let t of e.rejected)this.#g(`[gem] analytics: an event was refused (${t.code}). `+lm(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 Ks(n,e){return {event_uid:n.uid,name:n.name,offset_ms:Math.round(n.atMs)-e,dimensions:n.dimensions,measures:n.measures}}function lm(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 me(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=me(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var dm=2e3,cm=5e3;function zs(n){let e=[],t=false,r=null,o=new Map,i=()=>{if(e.length>0)return Promise.resolve(e);if(t)return Promise.resolve([]);if(!n.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=u=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(u));},m=n.clock.setTimeout(()=>{t=true,a([]);},n.timeoutMs??dm);});return r={promise:s,settle:a},s};return {resolveList:i,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(a=>a[0])},refresh(a){return !Js(e,a)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{o.delete(d)&&(n.clock.clearTimeout(l),s(m));};o.set(d,a),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??cm);})},accept(a,s){let l=jt(s),d=me(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...o])Js(m,p)||u(m);}}}}function Js(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var um=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=um.has(t),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var Ys=["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"],mm=new Set(Ys);function pt(n){return typeof n=="string"&&mm.has(n)?n:"unknown"}var Yn="webrtc_dedicated",po=["universal","mobile","web"];var pm="p2p_unavailable",gm="capacity_unavailable",ym=2,Xs=3e4,Qs=1e3,Zs=2e4;async function go(n){let e=me(n.clusterTargetId),t=n.nextClusterTarget,r=0,o=n.clock??ge,i=n.retry??{},a=i.budgetMs??Xs,s=i.maxDelayMs??Zs,l=i.initialDelayMs??Qs,d=o.now(),m=d+a,u=0;for(;;){u++;try{let p=await bo(n.signal,"while allocating",()=>n.client.post(`${nl(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!hm(p)||a<=0)throw p;if(p.status===503&&p.code===pm)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===gm?r+1:0,t!==void 0&&r>=ym){let x=t;t=void 0;let P=me(await x());P!==void 0&&(e=P,r=0);}let g=Math.min(s,l*2**(u-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),k=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+k>m)throw fm(n,p,u,o.now()-d,a);if(i.onWaiting?.({attempt:u,elapsedMs:o.now()-d,budgetMs:a,nextAttemptInMs:k,status:p.status,message:p.message}),await Xn(o,k,n.signal),n.signal?.aborted)throw mo("while waiting to allocate")}}}function hm(n){return n instanceof L?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function fm(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 bm=12e4,_m=1e3;async function yo(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??_m,o=n.timeoutMs??bm,i=e.now()+o,a=el(n),s={seen:n.knownToExist===true};for(;;){let l=await tl(n,a,s);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 Xn(e,r,n.signal);}}async function ho(n){return (await tl(n,el(n),{seen:n.knownToExist===true})).outcome}function el(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${nl(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function tl(n,e,t){let{matchId:r}=n,o=n.clock.now(),i;try{i=await bo(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(a){if(a instanceof L&&a.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(t.seen=true,i.status==="ready")return {status:"ready",outcome:vm(r,i,o)};if(i.status==="failed"){let a=i.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:pt(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function fo(n){let e=await bo(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 bo(n,e,t){if(n?.aborted)throw mo(e);try{return await t()}catch(r){throw n?.aborted?mo(e,r):r}}function mo(n,e){return new w("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function vm(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 nl(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function Xn(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 rl(n){return typeof n=="string"&&n.trim()!==""}function Qn(n,e){return rl(n)?n.trim():rl(e)?e:null}var Zn="0.1.0-beta",ol="0-beta",gt="web",wm=/^(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 km(n){let e=wm.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function il(n,e){let t=Sm(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:Zn};let o=km(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 '${Zn}' for it.`);if(o!==ol)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${ol}' 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 '${Zn}' for it.`);return {...n,platform:t,engineVersion:r}}function Sm(n,e){if(n===void 0||n===gt)return gt;if(!po.includes(n))throw new w("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${po.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${gt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${gt}' 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.`),gt}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:al(e.queued_at),expiresAt:al(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function al(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var Rm=3,sl=1e3,er=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((i,a)=>{this.resolve=i,this.reject=a;});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?sl:Math.max(sl,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<Rm){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 xm="join",Am="welcome",Pm="rejected",ll=25e3,Em=1e3,_o=1;function vo(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var Tm={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 wo(n){let e=typeof n=="string"?n:"unknown";return new w(Tm[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,a=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??ll),s=t.setTimeout(()=>b(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(a,Em)),l=k=>{let x=k.data;if(typeof x!="string"){u(x);return}let P;try{P=JSON.parse(x);}catch{u(x);return}if(i){u(x);return}if(P.t===Am){let _=vo(P.heartbeat_interval);y({...typeof P.player_id=="string"?{playerId:P.player_id}:{},...typeof P.match_id=="string"?{matchId:P.match_id}:{},..._===void 0?{}:{heartbeatIntervalMs:_}});return}if(P.t===Pm){b(wo(P.reason));return}u(x);},d=()=>{b(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{b(new w("aborted","the caller aborted during the join exchange"));},u=k=>{i&&n.onMessage?.(k);},p=()=>{t.clearTimeout(s),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=k=>{i=true,p(),n.onMessage===void 0&&g(),r({welcome:k,detach:g});},b=k=>{i||(i=true,p(),g(),o(k));};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:xm,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:_o}:{}}));}catch(k){b(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(k)}`,{cause:k}));}})}var Ke=1,Bt=2,ko=4,xo=8,Cm=2,Im=1e3,Ao="heartbeat timeout",Vt="gem-uu",tr=2,cl="gem_transports";function yt(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Mm(r)||e.includes(r)||e.push(r);}return e}function Mm(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function Ht(n,e){if(typeof n!="object"||n===null)return null;let t=n[cl];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 nr(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var ul=new TextEncoder,ml=new TextDecoder;function Po(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function Eo(n){let e=0;return n?.reliable===false&&(e|=Ke),n?.ordered===false&&(e|=Bt),e}function To(n){return {reliable:(n&Ke)===0,ordered:(n&Bt)===0}}var Co={reliable:true,ordered:true};function pl(n){return JSON.stringify({t:"join",credential:n,wire:tr,heartbeat:_o})}function gl(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=vo(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"?wo(e.reason):new w("join_refused","the server answered the join out of protocol")}function rr(){return typeof globalThis.WebTransport=="function"&&Io===null}function or(){return Io}var Io=null;var dl="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Om(n){let e=_n(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 So=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 a=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function Ro(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 s=globalThis.WebTransport;if(s===void 0)throw new w("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new s(n.url):new s(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Om(n.certHashBase64)}]});}let r=t,o=s=>{try{r.close();}catch{}throw s},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(Io=dl,o(new w("connection_failed",`${dl}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new w("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return o(new w("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(Ro(ko,ul.encode(pl(n.credential))));let u=new So,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),a]);if(y.done||y.value===void 0)return o(new w("connection_failed","the control stream closed before the join was answered"));for(let b of u.push(y.value)){g=gl(ml.decode(b.payload));break}}return {link:Lm(r,m,p,u,n.log??(y=>console.warn(y)),hl(g,n.clock)),welcome:g}}catch(s){return o(s)}}function Lm(n,e,t,r,o,i){let a,s,l=false,d=y=>{if(!l){l=true,m.stop();try{n.close();}catch{}s?.(y);}},m=Oo(i,()=>d(Ao)),u=(y,b)=>{m.heard(),(y&xo)===0&&a!==void 0&&((y&ko)!==0?a(ml.decode(b),Co):a(b,To(y)));};(async()=>{try{for(;;){let y=await t.read();if(y.done||y.value===void 0)break;for(let b of r.push(y.value))u(b.flags,b.payload);}}catch{}d("stream closed");})();let p,g;try{let y=n.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let b=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let k=await b.read();if(k.done||k.value===void 0)break;let x=k.value;x.byteLength!==0&&u((x[0]??0)|Ke|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 (${nr(y)}); unreliable sends ride the stream`);}return n.closed.then(y=>d(yl(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,b){if(l)return;if(typeof y=="string"){e.write(Ro(ko,ul.encode(y))).catch(()=>d("write failed"));return}let k=Eo(b);if((k&Ke)!==0&&g!==void 0){let x=Po(k,y),P=p?.maxDatagramSize;if(P===void 0||x.byteLength<=P){g.write(x).catch(()=>{});return}}e.write(Ro(k,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function Mo(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 a=false,s=setTimeout(()=>{a||(a=true,r.close(),i(new w("timeout","websocket did not come up in time")));},e),l=g=>{a||(a=true,clearTimeout(s),r.close(),i(g));},d=()=>{r.send(pl(n.credential));},m=g=>{if(a)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let y;try{y=gl(g.data);}catch(b){l(b);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),o({link:Gm(r,hl(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 yl(n){return typeof n=="string"&&n.length>0?n:void 0}function hl(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function Oo(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Im)*Cm,o=t.now(),i=null,a=()=>{i=null;let s=t.now()-o;if(s>=r){e();return}i=t.setTimeout(a,r-s);};return i=t.setTimeout(a,r),{heard:()=>{o=t.now();},stop:()=>{i!==null&&(t.clearTimeout(i),i=null);}}}function Gm(n,e){let t,r,o=false,i=s=>{if(!o){o=true,a.stop();try{n.close();}catch{}r?.(s);}},a=Oo(e,()=>i(Ao));return n.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){t?.(s.data,Co);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&xo)===0&&t?.(l.slice(1),To(d));})),n.addEventListener("close",(s=>i(yl(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!o){if(typeof s=="string"){n.send(s);return}n.send(Po(Eo(l),s));}},onMessage(s){t=s;},onClose(s){r=s;},close(){i("closed");}}}function Lo(n,e,t,r){let o,i,a=false,s=t,l=u=>{if(!a){a=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}i?.(u);}},d=Oo(r,()=>l(Ao)),m=(u,p)=>{if(d.heard(),typeof u=="string"){o?.(u,Co);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let y=g[0]??0;(y&xo)===0&&o?.(g.slice(1),To(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}`);})),s!==void 0){let u=s;u.addEventListener("message",(p=>m(p.data,Ke|Bt))),u.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(u,p){if(a)return;if(typeof u=="string"){n.send(u);return}let g=Eo(p),y=Po(g,u);if((g&Ke)!==0&&s!==void 0&&s.readyState==="open"){s.send(y);return}n.send(y);},onMessage(u){o=u;},onClose(u){i=u;},close(){l("closed");}}}function $o(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let o=Go(r);o!==void 0&&(e[t]=o);}return e}function Fo(n){if(Array.isArray(n))return n.map(Dm).filter(e=>!!e)}function Go(n){if(Do(n)||Array.isArray(n)&&n.every(Do))return n}function Do(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Dm(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Go(e.fixed),r=Go(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},...ht("description",$m(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Do)?{allowed:e.allowed}:{},...ht("min",Kt(e.min)),...ht("max",Kt(e.max)),...ht("minItems",Kt(e.min_items)),...ht("maxItems",Kt(e.max_items)),...ht("maxLength",Kt(e.max_length))}}function $m(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 ht(n,e){return e===void 0?{}:{[n]:e}}function Ee(n){let e=n??{},t=Y(e.id)??Y(e.game_room_id);if(t===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(fl):[];return {id:t,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...ve("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...ve("roomArgs",$o(e.room_args)),...ve("roomArgsTemplate",Fo(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",...ve("region",Y(e.region)),...ve("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,...ve("matchId",Y(e.match_id)),version:Pe(e.version)??0,...ve("templateId",Y(e.template_id)),roomType:Y(e.game_room_type)??"Standard",...ve("transports",yt(e.transports)??void 0),createdAt:Pe(e.created_at)??0,updatedAt:Pe(e.updated_at)??0,...ve("startedAt",Pe(e.started_at))}}function fl(n){let e=n??{};return {..._e(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Pe(e.joined_at)??0,...ve("groupId",Y(e.group_id)),...ve("platform",Y(e.platform))}}function ir(n){let e=n??{};return {id:Y(e.id)??Y(e.game_room_id)??"",gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:Pe(e.created_at)??0}}function Y(n){return typeof n=="string"&&n.length>0?n:void 0}function Pe(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function ve(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(ir),...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(ir)}))}create(e,t,r){return Fm(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(Ee)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(Ee)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Jt(r)},t.signal).then(Ee)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Jt(r)},t.signal).then(Ee)}quickJoin(e,t,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...Jt(t)},e.signal).then(Ee)}createTicket(e,t,r=[]){return ta(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 Ta(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):Yi(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(Ee)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(Ee)}kick(e,t,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(t)}`,{},r).then(()=>this.get(e,r))}transferHost(e,t,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(t)}`,{},r).then(Ee)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}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 Fm(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 qm(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var jm=1e3,Nm=3e3,Um=6e4,Bm=2,bl=new Set(["game_room_closed","game_room_gone"]),Vm=12e4,Hm=5e3,Wm=new Set(["invalid_cluster_target","capacity_unavailable"]),Km=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function jo(n){return new qo(n)}var qo=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 a=>{let s=await this.afterRefusedClusters(a,i);if(s[0]===void 0||s[0]===i[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(o,"created"),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=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),i=await this.run("quickJoin",async()=>{let a=await t;return o(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||kl(l,a))throw s;return o(l)})});return this.enter(i,"joined"),this.askForLocalServer(i),i}async queueForMatch(e){this.assertNotQueued("queueForMatch"),zm(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("queueForMatch",async()=>{let a=await t;return this.api.createTicket(r,this.version("queueForMatch"),a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||kl(l,a))throw s;return this.api.createTicket(r,this.version("queueForMatch"),l)})}),i=new er({clock:this.options.clock,first:o,heartbeat:a=>this.track(this.api.heartbeatTicket(a)),cancel:(a,s)=>this.track(this.api.cancelTicket(a,s)),seat:a=>this.enterMatchedRoom(a),onSettled:()=>{this.ticketWatch===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 L&&o.reason==="not_found"){let i=this.heldMatchId;if(i!==null){let a=await this.askWhyEnded(i,e);this.endMatch(i,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",o),o}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let o=await this.askWhyEnded(r,e);o!==null&&this.endMatch(r,o,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let o=this.takeHint(e),i;try{i=await this.track(this.onceGameIdKnown(()=>ho({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(a){return a instanceof L&&a.reason==="not_found"?o??null:(this.reportError("reconcile",a),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.reason}takeHint(e){let t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=pt(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=me(t.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,u)=>go({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=()=>s(i,[a]).catch(async m=>{if(o!==void 0||!vl(m))throw m;let u=await this.nextCluster([a],true);if(u===void 0)throw m;return s(u,[a,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 yo({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,!bl.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(!Je()){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<jm){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(qm(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Je()){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(()=>ho({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,!bl.has(o.reason)),this.track(this.reconcile().catch(()=>{}));return}if(o?.status==="failed"){this.abandonReconnect(e.matchId,o.reason),this.settleFailed(o.matchId,o.reason);return}if(o?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(o);let i;try{i=await t.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),i="failed";}if(e.done||this.reconnect!==e)return;if(i==="closed"){this.finishReconnect();return}if(i==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new 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||!Wm.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&&Je())){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(),!!Je())){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 ar)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 ar)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??Hm}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=Qn(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 il({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return jt(await this.options.resolveClusterTargets());let e=me(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !vl(e)||t.length===0?[]:jt(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=a=>a.find(s=>!e.includes(s)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!t?i:r(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 L)||e.reason!=="conflict"||!Km.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 o;try{o=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(o.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 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 L?{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(s=>[s.playerId,s])),o=new Map(e.members.map(s=>[s.playerId,s])),i=this.playerId();for(let s of o.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!o.has(s)){if(s===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of o){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=Jm(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(o=>{if(!r.signal.aborted)try{this.settleOutcome(o);}catch{}}).catch(o=>{r.signal.aborted||this.reportError("pollMatchStatus",o);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??Vm;return new Promise((o,i)=>{let a=u=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},s=this.emitter.on("matchAllocationStarted",u=>a(()=>o(u))),l=this.emitter.on("matchFailed",(u,p)=>a(()=>i(new w("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>a(()=>i(new w("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>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??Nm}pushedInterval(){return this.options.pushedPollIntervalMs??Um}pushed(){return this.options.clock.now()-this.lastPushAt<Bm*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 Je(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var ar=["visibilitychange","focus","pageshow","online"];function Jm(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||_l(n)!==_l(e)}function _l(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function vl(n){return n instanceof L&&n.code==="invalid_cluster_target"}var wl=8;function zm(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=wl&&n.every(t=>typeof t=="string"&&t.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${wl} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function kl(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Ym=["p2p","dedicated","unknown"],No=["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 o=Xm(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 Xm(n,e,t){let r=Math.floor(t/1e3);return n.filter(o=>No.includes(o.type)).slice(0,100).map(o=>{let i=Qm(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function Qm(n){if(n!==void 0)return Ym.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 o=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:sr(o.credential)??"",hostFingerprint:sr(o.host_fingerprint)??"",hostEpoch:lr(o.host_epoch)??0,expiresAt:(lr(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:sr(d.username)??"",credential:sr(d.credential)??""});}let a=lr(o.expires_at),s=lr(o.ttl_seconds);return {iceServers:i,expiresAt:a!==void 0?a*1e3:Date.now()+(s??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function sr(n){return typeof n=="string"&&n.length>0?n:void 0}function lr(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var Zm=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=Zm.has(t);}reason;retryable};var Sl=10240,Rl=2048,ep=new TextEncoder;function xl(n){return ep.encode(n).length}function De(n,e){let t=o=>{throw new w("invalid_sdp",`the ${e} ${o}`)},r=xl(n);r>=Sl&&t(`is ${r} bytes, over the ${Sl} 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=xl(o);i>Rl&&t(`has a ${i}-byte line, over the ${Rl} limit`);}}function dr(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 cr=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 tp=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function bt(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=ur(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function ur(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 tp.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 Uo=5e3,np=12e4+Uo,rp=1024,op=6e4,ip=1e4,Al=64*1024,Pl=5;function Bo(n){let e=new Map,t=-1/0,r=null,o=(()=>{let s;try{s=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return s.username!==""||s.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:s.href,shown:`${s.protocol}//${s.host}`}})(),i=()=>{let s=n.subtle??globalThis.crypto?.subtle;if(!s)throw new 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 s},a=async()=>{if(!o.ok)throw new G("keys_unavailable",o.reason);let s=n.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await s(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ip)});}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>Al)throw new G("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${Al} 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>Pl)throw new G("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Pl} 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(s){let l=e.get(s);if(l)return l;if(!o.ok)throw new G("keys_unavailable",o.reason);if(r)return await r,e.get(s)??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<op?null:(t=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??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>=rp){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+np),true}};function Tl(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 El(n){try{let e=new TextDecoder().decode(Tl(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function Vo(n,e,t,r,o){let i=$=>{throw new G("peer_unauthenticated",`the peer's join credential is not usable: ${$}`)},a=n.split(".");a.length!==3&&i("it is not a three-part JWT");let[s,l,d]=a,m=El(s);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let 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(`${s}.${l}`),b;try{b=Tl(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,b,y)||i("its signature does not verify");let x=El(l);x===null&&i("its payload does not decode");let P=x,_=$=>typeof P[$]=="string"?P[$]:"",S=$=>typeof P[$]=="number"&&Number.isFinite(P[$])?P[$]:NaN;_("iss")!==o.issuer&&i("it was issued by someone else"),_("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),_("match_id")!==e.matchId&&i("it is for another match"),_("game_id")!==e.gameId&&i("it is for another game");let T=S("exp")*1e3,C=S("nbf")*1e3;(!Number.isFinite(T)||e.now>T+Uo)&&i("it has expired"),Number.isFinite(C)&&e.now<C-Uo&&i("it is not valid yet");let V=_("role");V!=="host"&&V!=="client"&&i("it names no usable role");let B=S("host_epoch");B!==e.hostEpoch&&i("it names a different host epoch");let K=ur(_("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=ur(_("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 M=_("jti");M.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(M,e.now)||i("it has already been used");let O=_("sub");return O.length===0&&i("it names no player"),{playerId:O.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:B,role:V,fingerprint:K,hostFingerprint:A,jti:M,expiresAt:T}}function Ho(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 Wo(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 Ko(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function Jo(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 Cl(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 Il(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 zo={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 Yo(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 Ol=1,cp=3e4,Ll=2e3,up=5e3,Gl=6e4,mp=8,Qo=class{constructor(e=mp){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;}},pp=new Qo,gp=8,yp=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??Bo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new cr;links=new Map;replays=new Zt;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Ol+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??cp;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),o=me(this.options.clusterTargetId);if(o!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,o,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Xo(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let i=this.options.clock.setTimeout(()=>{this.fail(new 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),a=()=>this.fail(new G("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new 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=ae(e.playerId),r=ae(e.hostPlayerId),o=mr(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,Ol),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");De(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,o=r===void 0?null:bt(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??pp,a=()=>this.closed||e!==this.credentialGeneration,s=up;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,u;if(m===409)u=Ll;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=s,s=Math.min(s*2,Gl)),u=Math.min(Math.max(u,Ll),Gl);}else throw d;if(!await this.waitForCredential(u,a))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=ae(e.fromPlayerId),r=ae(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=gp){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=ae(e.sessionId);if(o!==null&&this.answeredSessions.get(t)===o)return;De(r,"offer"),this.refuseMedia(r,"offer");let i=bt(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 a=this.links.get(t);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(t,this.nextPeerId++);s.remoteFingerprint=i,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new G("invalid_sdp","the browser produced an answer with no SDP");De(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=ae(e.fromPlayerId),r=ae(e.sdp);if(t===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||t!==this.hostPlayerId)return;De(r,"answer"),this.refuseMedia(r,"answer");let i=bt(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=ae(e.fromPlayerId),r=ae(e.candidate);if(t===null||r===null)return;let o=this.links.get(t);if(!o)return;let i=ae(e.sdpMid),a=mr(e.sdpMLineIndex)??mr(e.sdpMLineIndexAlt),s={candidate:r,...i===null?{}:{sdpMid:i},...a===null?{}:{sdpMLineIndex:a}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(s);return}await o.connection.addIceCandidate(s);}onPeerLeft(e){let t=ae(e.playerId);if(t===null)return;let r=ae(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=ae(e.hostPlayerId),r=mr(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:t,hostEpoch:r,...ae(e.reason)===null?{}:{reason:ae(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=ae(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=ae(e.code)??"unknown",r=ae(e.message)??"the platform refused a signaling message";this.report_(new G("signaling_failed",`${t}: ${r}`));}openLink(e,t){let o=(this.options.peerConnectionFactory??Yo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Le){let g=o.createDataChannel(p,zo[p]);g.binaryType="arraybuffer",i[p]=g;}let a={playerId:e,assignedPeerId:t,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",s),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",u),i.reliable.addEventListener("message",m),a.detachHandshake=()=>{i.reliable.removeEventListener("open",u),i.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),o.removeEventListener("icecandidate",s),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new 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(Ho({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=Jo(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(Il(r.reason),Cl(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=bt(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 Vo(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:o,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof G&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Xo(a)),s&&this.fail(a);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Wo({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(Ko(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)Dl(e.channels[o]);Dl(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",Xo(e),{cause:e}));}count(e){this.counted||!yp.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(dr(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 ae(n){return typeof n=="string"&&n.length>0?n:null}function mr(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function Xo(n){return n instanceof Error?n.message:String(n)}function Dl(n){try{n.close();}catch{}}var hp=100,fp=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??hp)){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??fp));}};function H(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function $e(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function _t(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function $l(n){return typeof n=="boolean"?n:void 0}var he=H(64),an=$e(0,2147483647);function Zo(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=he(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 vp=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=_t("disconnected","failed","closed")(e.iceState),r=$e(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",_t("initial","ice_restart","full_reconnect")),W("sdp_hash","sdpHash",H(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[J("peer_id","peerId",he),J("sdp","sdp",H(10240)),J("assigned_peer_id","assignedPeerId",$e(0,4294967295)),W("sdp_hash","sdpHash",H(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[J("peer_id","peerId",he),J("candidate","candidate",H(512)),W("sdp_mid","sdpMid",H(64)),W("sdp_mline_index","sdpMLineIndex",$e(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",vp)]}}));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",he),J("hostPlayerId","host_player_id",he),J("hostEpoch","host_epoch",an),W("members","members",Zo)],offer:[J("fromPlayerId","from_player_id",he),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",_t("initial","ice_restart","full_reconnect"))],answer:[J("fromPlayerId","from_player_id",he),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",$e(0,4294967295))],ice:[J("fromPlayerId","from_player_id",he),J("candidate","candidate",H(512)),W("sdpMid","sdp_mid",H(64)),W("sdpMLineIndex","sdp_m_line_index",$e(0,255)),W("sdpMLineIndexAlt","sdp_mline_index",$e(0,255))],peerJoined:[J("playerId","player_id",he)],peerLeft:[J("playerId","player_id",he),W("reason","reason",H(64))],migration:[J("hostPlayerId","new_host_player_id",he),J("hostEpoch","host_epoch",an),W("reason","reason",H(64)),W("kickedPlayerIds","kicked_player_ids",Zo),W("migrationComplete","migration_complete",$l)],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 Ye="webrtc_p2p";function ql(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=me(r.clusterTargetId),i=o??me(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...o===void 0?{}:{clusterTargetId:o},...r.signal===void 0?{}:{signal:r.signal}});let a=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==Ye)throw new G("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${Ye}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new on({bridge:n.bridge,matchId:a.matchId,clock:n.clock}),l=new rn({api:e,clock:n.clock,matchId:a.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await tn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(a.matchId,l),l.on("matchEnded",()=>t.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(a.matchId),l.close(),d}return l}}}function jl(n){let{analytics:e,rooms:t}=n,r=n.target??globalThis,o=n.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let s=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",s),i.push(()=>r.removeEventListener?.("pagehide",s));let l=()=>e.setHidden(!Je());for(let d of ar)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(!Je());}let a=new Map;return i.push(t.on("matchReady",s=>{let l=s.protocol===Ye?"p2p":"dedicated";a.set(s.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(t.on("matchEnded",s=>{let l=a.get(s.matchId);l!==void 0&&(a.delete(s.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let s of i.splice(0))try{s();}catch{}a.clear();}}var Nl=["pointerdown","keydown"];function Ul(n,e=globalThis){let t=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},a=()=>{if(!r){r=true,i();for(let g of Nl)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},s=()=>{if(!(t||r)){t=true,a();try{n();}catch{}}};function l(g){g?.isTrusted===true&&s();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(b=>b.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(o=null,!(t||r)){if(d()){s();return}m()&&(o=e.requestAnimationFrame?.(u)??null);}};function p(){o===null&&!t&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of Nl)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:a}}async function pr(n,e,t,r){let o=await t;return n.mark(e)&&r&&r(`[gem] boot: ${n.timeline()}`),o}function ei(n,e){let t=false;return async r=>{let o=await r;return !t&&e&&(t=true,e(`[gem] boot: ${n.timeline()}`)),o}}function ti(n={}){let e=n.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),t=[],r=new Set;return {marks:t,mark(o,i){return r.has(o)?false:(r.add(o),t.push({name:o,at:i??e()}),true)},timeline(){let o=[...t].sort((i,a)=>i.at-a.at);return o.map((i,a)=>{let s=o[a-1],l=s===void 0?"":` (+${Math.round(i.at-s.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var wp="GemWebSdkHandshake";var kp=()=>Date.now();function Bl(n,e,t={}){let r=n[wp];if(r===void 0)return null;let o=t.ttlMs??9500,i=t.now??kp,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,u=i()-o;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var ni=false;async function Kl(n,e,t,r){if(ni){e.close(),t("busy",true);return}ni=true;let o=null;try{let i=await Rp(n,r);if(typeof i=="string"){e.close(),t(i,Sp(i));return}o=i;let s=await(r.encodeRef??(l=>Ep(l,r)))(o);if(o.close(),o=null,s===null){e.close(),t("failed",!0);return}if(s.size>Pp){e.close(),t("too_large",!1);return}e.postMessage(s);}catch(i){e.close(),t("failed",true),console.error("[gem] screenshot capture failed",i);}finally{ni=false,o?.close();}}function Sp(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 Rp(n,e){if(e.handler){let i=await e.handler(n);return i===null?"declined":Vl(i,n)}if(!e.useDefaultStrategy)return "not_wired";let t=e.documentRef??globalThis.document;if(!t)return "no_source";let r=Ap(t);if(!r)return "no_source";let o=xp(r);if(o!==null)return o;try{return Vl(await createImageBitmap(r),n)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function xp(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 Ap(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 Vl(n,e){let{maxWidth:t,maxHeight:r}=e;if(n.width<=t&&n.height<=r)return n;let o=Math.min(t/n.width,r/n.height),i=Math.max(1,Math.floor(n.width*o)),a=Math.max(1,Math.floor(n.height*o));try{let s=await createImageBitmap(n,{resizeWidth:i,resizeHeight:a,resizeQuality:"high"});return n.close(),s}catch{return n.close(),"too_large"}}var Pp=8*1024*1024,Hl="image/webp",Wl=.92;async function Ep(n,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(n.width,n.height),a=i.getContext("2d");if(a){a.drawImage(n,0,0);let s=await i.convertToBlob({type:Hl,quality:Wl});if(s&&s.size>0)return s}}}catch{}let t=e.documentRef??globalThis.document;if(!t)return null;let r=t.createElement("canvas");r.width=n.width,r.height=n.height;let o=r.getContext("2d");return !o||(o.drawImage(n,0,0),typeof r.toBlob!="function")?null:await new Promise(i=>{r.toBlob(a=>i(a),Hl,Wl);})}async function Jl(n,e){if(!e)return;let t;try{t=await Tp(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 Tp(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 zl=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Yl(n=globalThis){let t=n[zl];if(t!==void 0)return t;let r=false,o=()=>r,i=[],a=Cp(n,o);a!==null&&i.push(a);let s=Ip(n,o);s!==null&&i.push(s);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let u of i)u();}}};return Object.defineProperty(n,zl,{value:l,configurable:true}),l}function Cp(n,e){let t=n.AudioNode?.prototype,r=n.AudioDestinationNode;if(t===void 0||r===void 0)return null;let o=n.OfflineAudioContext,i=t.connect,a=t.disconnect,s=new Map,l=m=>{let 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=s.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,i.call(p,m),s.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=s.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...g)}catch{}}return a.apply(this,u)},()=>{for(let[m,u]of s){if(m.state==="closed"){s.delete(m);continue}try{l(u);}catch{}}}}function Ip(n,e){let t=n.HTMLMediaElement;if(t===void 0)return null;let r=t.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,a=o?.set;if(i===void 0||a===void 0)return null;let s=r.play,l=new WeakMap,d=new WeakSet,m=new Set,u=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),a.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),u(this);}}),r.play=function(){try{u(this);}catch{}return s.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{a.call(g,(l.get(g)??!1)||e());}catch{}}}}var Mp=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Op=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Lp=`${Mp}${Op}`,ri=new WeakSet;function Xl(n=globalThis.document){if(n==null||ri.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(Lp),n.adoptedStyleSheets=[...n.adoptedStyleSheets,r],ri.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"),ri.add(n),"inline")}catch{return null}}function Ql(n){let e=n.windowMs??1e3,t=n.realm??globalThis,r=false,o=false,i=false,a=null,s=null,l=null,d=[],m=()=>r&&!o&&!i,u=()=>{s=null,l=null,d=[];},p=b=>{if(a=null,!m()){u();return}if(l!==null&&d.push(b-l),l=b,s===null)s=b;else {let k=b-s;k>=e&&d.length>0&&(n.report(Gp(d,k)),s=b,d=[]);}g();},g=()=>{let b=t.requestAnimationFrame;typeof b=="function"&&(a=b.call(t,p));},y=()=>{if(m()){a===null&&(u(),g());return}a!==null&&(t.cancelAnimationFrame?.call(t,a),a=null),u();};return {setRequested(b){r=b,y();},setPaused(b){o=b,y();},get running(){return a!==null},dispose(){i=true,y();}}}function Gp(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 gr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function ed(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function td(n,e){n!==null&&(n.style.setProperty(gr.top,`${e.top}px`),n.style.setProperty(gr.right,`${e.right}px`),n.style.setProperty(gr.bottom,`${e.bottom}px`),n.style.setProperty(gr.left,`${e.left}px`));}var Zl=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 nd(){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 Dp(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,a=o?r.x+r.width:e?e.width-r.x:r.width,s=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(a)),l.height=Math.max(l.height,Math.ceil(s));}return t}function rd(n,e,t){if(n===null)return;let r=Dp(e,t);for(let o of ["tl","tr","bl","br"])n.style.setProperty(Zl[o].width,`${r[o].width}px`),n.style.setProperty(Zl[o].height,`${r[o].height}px`);}var $p=3e4,yr=class extends Error{retryable;reason;constructor(e,t,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=t;}};function od(n){let e=n.clock??ge,t=n.timeoutMs??$p,r=new Map,o=new Map,i=0,a=s=>{let l=r.get(s);return l?(r.delete(s),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return n.bridge.parentSupports("localHost")},ensure(s){if(!n.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(s);if(l)return l;let d=new Promise((m,u)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(s),u(new yr("timeout",true,`the embedder did not answer a local-server request for room ${s} within ${String(t)}ms`));},t);r.set(p,{room:s,resolve:m,reject:u,timer:g}),n.bridge.requestLocalServer(p,s)||(a(p),m());});return o.set(s,d),d.catch(()=>{}),d},accept(s){a(s.requestId)?.resolve();},refuse(s){let l=a(s.requestId);l&&l.reject(new yr(s.reason,s.retryable,s.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var sn={url:"https://downloads.indiegems.games/sdk/v10.3.1/gem-web-sdk.devtools.min.js",integrity:"sha384-DrnQN/rTG6pYD7nsf6TtgHDoDay42o/Fd//0ZdIlqEU6nfwblufRXhQnC1SBdDK5"};var wt=null;function Fp(){return wt!==null||(wt=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){wt=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=()=>{wt=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);})),wt}function id(n,e){let t=null,r=0;async function o(i){if(t!==null)return true;let a=++r;if(!e())return false;let s=await Fp();return !e()||a!==r?false:(t!==null||(t=s.mount(n(),{openedBy:i,text:dt,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 qp=1e4,ad={reason:"unavailable",retryable:false};function sd(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??qp);},a=(d,m)=>{let u=s(d);u&&m(u);},s=d=>{let m=e.get(d);return m?(e.delete(d),n.clock.clearTimeout(m.timer),m):null},l=new it({clock:n.clock,onStateChange:n.onStateChange,request:d=>new Promise((m,u)=>{let p=n.bridge.currentState;if(p==="refused"||p==="closed"){u(ad);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)){a(d.requestId,u=>u.resolve(m));return}l.accept(m);},onDenied(d){a(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,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()])a(m,u=>u.reject(ad));},get identity(){return t},get gameVersion(){return r}}}function jp(n){let e=n.lastIndexOf("@");return (e===-1?n:`***@${n.slice(e+1)}`).slice(0,200)}var Np=new Set(Gr);function Up(n){if(!n)return {};let e={};for(let[t,r]of Object.entries(n))Np.has(t.toLowerCase())&&(e[t.toLowerCase()]=r);return e}function hr(n){let e=n.fetch??globalThis.fetch.bind(globalThis);return Bi(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"?jp(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,b=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new oe(`the ${b} puts credentials in the URL, which cannot be fetched (${t.method} ${i.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(n.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,y);let a=t.bytes,s=t.bytes===void 0?void 0:"application/octet-stream";try{t.body!==void 0&&(a=JSON.stringify(t.body),s="application/json");}catch(g){throw new 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}`,...s===void 0?{}:{"content-type":s},...Up(t.headers)},body:a,signal:t.signal,...t.keepalive===void 0?{}:{keepalive:t.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(t.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),u=Bp(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 Bp(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 Vp=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),ii="embedder_relay_unavailable",Hp="embedder_no_relay",Wp=new Set([ii]),ai=new Set([Hp]),ln=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new oi(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(Kp(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 Kp(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new w(Jp(n),r,{platformCode:n})}function Jp(n){return n===void 0||Wp.has(n)?"signaling_failed":ai.has(n)?"offer_refused":Vp.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var oi=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 a=()=>{s(),i(new w("aborted","the caller aborted the signaling exchange"));},s=()=>{t?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),o(d);},refuse:d=>{s(),i(d);}};this.teardown=s,t?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof 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 ld="match_ended:",dd="server_shutdown:",cd="kicked:",zp=123;function Yp(n){if(typeof n!="string"||n.length===0||n.length>zp)return {kind:"other"};if(n.startsWith(ld)){let e=pt(n.slice(ld.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(dd)?{kind:"server_shutdown",cause:n.slice(dd.length)}:n.startsWith(cd)?{kind:"kicked",detail:n.slice(cd.length)}:{kind:"other"}}function si(n,e,t){let r=Yp(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 li(){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 Xp=3e3,Qp=1e4,Zp=15e3;async function fr(n){let e=n.peerConnection;try{md(n,"before the handshake started"),di(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let a of n.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});n.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await ng(e,n),di(n);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new w("invalid_sdp","the offer carried no SDP");De(o,"offer"),ud(o,"offer");let i=await tg(n,o);if(di(n),typeof i?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return De(i.sdp,"answer"),ud(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await rg(t,n),md(n,"before the channel opened"),t}catch(t){throw e.close(),eg(t)}}function eg(n){return n instanceof w?n:yd(n)?Xe():new w("connection_failed",hd(n),{cause:n})}function ud(n,e){if(dr(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 tg(n,e){let t=n.exchangeTimeoutMs??Qp,r=gd(n,t),o=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(i=>{throw i instanceof w?i:yd(i)?Xe():new w("signaling_failed",hd(i),{cause:i})});return og(o,n,r,()=>r.exhausted?ci("while the offer was in flight"):new w("timeout",`no answer arrived within ${t}ms`))}function ng(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let o=()=>{t.clearTimeout(a),n.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{n.iceGatheringState==="complete"&&o();},a=t.setTimeout(o,e.gatherTimeoutMs??Xp);n.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function rg(n,e){if(e.signal?.aborted)return Promise.reject(Xe());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??Zp,o=gd(e,r);return new Promise((i,a)=>{let s=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),i();},d=g=>{s(),a(new w("connection_failed","the data channel failed before it opened",pd(g)===void 0?void 0:{cause:pd(g)}));},m=()=>{s(),a(Xe());},u=()=>{s(),a(o.exhausted?ci("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 gd(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 og(n,e,t,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(Xe()):new Promise((a,s)=>{let l=u=>{o.clearTimeout(m),i?.removeEventListener("abort",d),u();},d=()=>l(()=>s(Xe())),m=o.setTimeout(()=>l(()=>s(r())),t.ms);i?.addEventListener("abort",d),n.then(u=>l(()=>a(u)),u=>l(()=>s(u)));})}function md(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw ci(`already ${e}`)}function ci(n){return new w("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function di(n){if(n.signal?.aborted)throw Xe()}function Xe(){return new w("aborted","the caller aborted the connection attempt")}function yd(n){return n?.name==="AbortError"}function pd(n){return n?.error}function hd(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 Rd(n){let{client:e,clock:t,rooms:r}=n,o=n.signaling??li,i=n.log??(_=>console.warn(_)),a=new ft({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(_,S)=>{let T=s.get(_)??new Set;T.add(S),s.set(_,T);},d=(_,S)=>{let T=s.get(_);T!==void 0&&(T.delete(S),T.size===0&&s.delete(_));},m=async _=>{if(r.isHost&&!mi(r)&&r.currentRoom?.matchId===void 0){let S=me(_.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},..._.retry===void 0?{}:{retry:_.retry},..._.signal===void 0?{}:{signal:_.signal}});}return kd(r.matchConnectionState==="suspended"?await r.reconnectToMatch(ui(_)):await r.awaitMatch(ui(_)))},u=async _=>kd(await r.pollMatchStatus(ui(_))),p=async(_,S)=>{let T=false;try{let C=await m(_),V=r.currentRoom?.transports;if(V!==void 0&&!V.includes("webrtc"))throw new w("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=_.peerConnection??Sd();T=!0;let K=await fr({peerConnection:B,signaling:S,clock:t,matchId:C.matchId,credentialExpiresAt:C.credentialExpiresAt,...br(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),A=null;if(_.presentCredential!==!1)try{A=await Ut({channel:K,clock:t,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,...br(_,"onMessage","signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(M){throw we(K),we(B),M}return pg(r,C,K,B,S,_.reportDisconnect!==!1,_.reportConnected!==!1,A,{remember:l,forget:d},_.onMatchEnded)}catch(C){throw T&&wd(a,C),we(S),C}},g=async(_,S,T,C,V,B)=>{if(_==="webtransport"){let U=C?.webtransport;if(U===void 0)throw new w("misconfigured","webtransport is not advertised");let j={credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,clock:t};if(typeof U.named_url=="string"&&U.named_url!==""){let ee=Math.max(Math.floor(B/2),1e3);try{return await Wt({url:U.named_url,timeoutMs:ee,log:i,...j})}catch(de){if(or()!==null)throw de;return i(`[gem] webtransport named dial failed (${nr(de)}); retrying the pinned dial`),Wt({url:U.url,certHashBase64:U.cert_sha256_b64,timeoutMs:ee,log:i,...j})}}return Wt({url:U.url,certHashBase64:U.cert_sha256_b64,timeoutMs:B,...j})}if(_==="websocket"){let U=C?.websocket;if(U===void 0)throw new w("misconfigured","websocket is not advertised");return Mo({url:U.url,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,clock:t,timeoutMs:B})}let K=S.peerConnection??Sd(),A,M=await fr({peerConnection:K,signaling:V,clock:t,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,extraChannels:[{label:Vt,ordered:false,maxRetransmits:0}],onExtraChannel:(U,j)=>{U===Vt&&(A=j);},...br(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:sg}:{}}),O;try{O=await Ut({channel:M,clock:t,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,wire:tr,heartbeat:!0,...br(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(U){throw we(M),we(K),U}let $=O.welcome.heartbeatIntervalMs;return {link:Lo(M,K,A,$===void 0?void 0:{clock:t,intervalMs:$}),welcome:O.welcome,channel:M,peerConnection:K}},y=(_,S,T,C,V)=>{let B=false,K;C.link.onClose($=>{!B&&_.reportDisconnect!==false&&si(r,S.matchId,$),K?.($);}),_.reportDisconnect!==false&&_.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let A={transport:C.link.transport,send:($,U)=>C.link.send($,U),onMessage:$=>C.link.onMessage($),onClose:$=>{K=$;},close:()=>C.link.close()},M=()=>{B||(B=true,we(C.link),we(V));},O=$=>{if(!B){try{_.onMatchEnded?.($);}catch{}M();}};return l(S.matchId,O),{matchId:S.matchId,transport:T,link:A,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:C.welcome,...C.channel===void 0?{}:{channel:C.channel},...C.peerConnection===void 0?{}:{peerConnection:C.peerConnection},close(){d(S.matchId,O),M();}}},b=async(_,S)=>{let T=r.currentRoom?.id,C=r.gameId,V=()=>({advert:Ht(r.currentRoom?.settings,_),template:r.currentRoom?.transports??null});if(T===void 0||C===null)return V();try{let B=await e.get(`/v2/games/${encodeURIComponent(C)}/game-rooms/${encodeURIComponent(T)}`,S);return {advert:Ht(B.settings,_),template:yt(B.transports)??r.currentRoom?.transports??null}}catch{return V()}},k=(_,S)=>{let T=_??fd;return S.length===0?T:T.filter(C=>S.includes(C))},x=async(_,S,T)=>{try{let C=await m(_),{advert:V,template:B}=await b(C.matchId,_.signal),K=k(B,S),A=K.filter(X=>cg(X,V)),M=or();if(M!==null&&K.includes("webtransport")&&V?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${M} (learned on an earlier dial in this page)`),A.length===0){let X=B===null?`the default order (${fd.join(", ")})`:`the room template's transports (${B.join(", ")||"none"})`;throw new w("misconfigured",`none of ${X}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let O=_.transportAttemptTimeoutMs??ag,$=()=>_.deadlineAt===void 0?1/0:_.deadlineAt-t.now(),U=X=>n.signalingReady===void 0||X<=0?Promise.resolve(!0):n.signalingReady(X),j=[],ee=[];for(let X of A){if($()<_d){i(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}ee.length>0&&C.credentialExpiresAt-t.now()<vd&&(C=await u(_)),ee.push(X);let Fe=!1,ke=!1,be={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&_.redial===!0){let z=Math.min(bd,$());await U(z)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(z)}ms; offering anyway`);}let Ie=Math.max(Math.min(O,$()),_d);try{return y(_,C,X,await g(X,_,C,V,T,Ie),T)}catch(z){let Q=z instanceof w?z:new w("connection_failed",z instanceof Error?z.message:String(z),{cause:z});if(X==="webrtc"&&wd(a,Q),(Q.reason==="credential_expired"||Q.reason==="credential_reused")&&!Fe){Fe=!0,C=await u(_);continue}if(X==="webrtc"&&Q.reason==="signaling_failed"&&Q.platformCode===ii&&!ke){ke=!0;let se=Math.min(bd,$());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(se)}ms for the socket before offering again`),await U(se))continue}if(Q.reason==="join_rate_limited"){let se=dg(be,Math.random,$());if(se!==null){if(be.attempts+=1,be.waitedMs+=se,i(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(se)}ms before presenting again (retry ${be.attempts} of ${Ad.maxAttempts})`),await Xn(t,se,_.signal),_.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");C.credentialExpiresAt-t.now()<vd&&(C=await u(_));continue}}if(lg.has(Q.reason)||Q.reason==="credential_expired"||X==="webrtc"&&xd(Q)){i(`[gem] ${X} rung failed (${Q.reason}): ${nr(Q.cause??Q)} \u2014 `+(ee.length<A.length?`falling through to ${A[ee.length]}`:"no rungs left")),j.push(Q);break}throw i(`[gem] ${X} rung refused the session (${Q.reason}): ${Q.message}`),Q}}}let de=j[j.length-1];throw de===void 0?new w("timeout",`the reconnect budget ran out before any transport (${A.join(", ")}) could be tried`):new w(de.reason,`every transport tried (${ee.join(", ")}) failed; the last said: ${de.message}`,{cause:j,platformCode:de.platformCode})}catch(C){throw we(T),C}};return {listClusterTargets:async(_={})=>fo({client:e,..._}),handleMatchEnded(_,S){let T=s.get(_);if(T!==void 0){s.delete(_);for(let C of T)C(S);}},connect:(async(_={})=>{let S=_.signaling??o();return _.transports===void 0?p(_,S):x(_,_.transports,S)})}}var fd=["webtransport","webrtc","websocket"],ag=1e4,sg=5e3,bd=3e3,_d=1e3,vd=1e4,lg=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function xd(n){return n.platformCode!==void 0&&ai.has(n.platformCode)}var Ad={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function dg(n,e=Math.random,t=1/0){let r=Ad;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 cg(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&rr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||ug(e.websocket.url)}function ug(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return xn(e)}function ui(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var mg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function wd(n,e){e instanceof w&&(!mg.has(e.reason)&&!xd(e)||n.report([{type:"connection_failures_total",value:1}]));}function pg(n,e,t,r,o,i,a,s,l,d){let m=false,u=()=>{m||si(n,e.matchId,void 0);};i&&(t.addEventListener("close",u),a&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",u),s?.detach(),we(t),we(r),we(o));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function mi(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function kd(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!==Yn)throw new w("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${Yn}' 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 Sd(){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 we(n){try{n.close();}catch{}}function br(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var gg=1e4;function Pd(n,e){if(typeof n.serverToken!="function"||typeof n.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let t=a=>({token:a.token,expiresAt:a.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new it({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((a,s)=>{let l=e.clock.setTimeout(()=>{r=null,s({reason:"unavailable",retryable:true});},e.timeoutMs??gg);r={resolve:d=>{e.clock.clearTimeout(l),a(d);},reject:s,timer:l};})}),i=n.onServerToken(a=>{let s=t(a),l=r;if(l){r=null,l.resolve(s);return}o.accept(s);});return {source:o,dispose(){i(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var gi={};fc(gi,{acceptTransfer:()=>yg,addEntityProgression:()=>hg,adminAction:()=>fg,cancelInventoryTransfer:()=>bg,claimEntityProgressionRewards:()=>_g,closeGameRoom:()=>vg,createEntityBatchOrder:()=>wg,createEntityOrder:()=>kg,createSession:()=>Sg,deleteEntityGameSetting:()=>Rg,deleteEntitySave:()=>xg,deleteSession:()=>Ag,deleteShowcaseValue:()=>Pg,executeEntityRecipe:()=>Eg,finalizeSaveUpload:()=>Tg,getChannelAssignment:()=>Cg,getDropRates:()=>Ig,getEntityCurrency:()=>Mg,getEntityGameSetting:()=>Og,getEntityInventory:()=>Lg,getEntityInventoryItem:()=>Gg,getEntityLeaderboard:()=>Dg,getEntityOrder:()=>$g,getEntityProgression:()=>Fg,getEntityRecipeAvailability:()=>qg,getEntityRecipeUsage:()=>jg,getEntitySave:()=>Ng,getEvent:()=>Ug,getGameRoomV2:()=>Bg,getLeaderboard:()=>Vg,getPlayerGameProfile:()=>Hg,getPurchaseCatalog:()=>Wg,getResolvedTemplate:()=>Kg,getRoomArgs:()=>Jg,getShowcaseValue:()=>zg,getTransferDetails:()=>Yg,ingestAnalyticsEvents:()=>pi,initiateInventoryTransfer:()=>Xg,invokeFunction:()=>Qg,kickPlayer:()=>Zg,listChallenges:()=>ey,listEntityGameSettings:()=>ty,listEntityOrders:()=>ny,listEntityProgressions:()=>ry,listEntitySaves:()=>oy,listEvents:()=>iy,listGameRooms:()=>ay,listResolvedTemplates:()=>sy,listTransfers:()=>ly,maxEntityProgression:()=>dy,putEntityGameSetting:()=>cy,putRoomArgs:()=>uy,putShowcaseValue:()=>my,rejectTransfer:()=>py,reportMatchPlayers:()=>gy,requestSaveUploadUrl:()=>yy,resetEntityProgression:()=>hy,setMatchBackfill:()=>fy,simulateEntityOrder:()=>by,transferHostV2:()=>_y,updateGameRoomV2:()=>vy});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 yg(n,e,t){let r=`/v1/inventory/transfers/${f(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function hg(n,e,t,r,o,i){let a=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/add`;return n.client.post(a,o,i?.signal)}async function fg(n,e,t,r){let o=`/v1/voice/sessions/${f(e)}/admin`;return n.client.post(o,t,r?.signal)}async function bg(n,e,t){let r=`/v1/inventory/transfers/${f(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function _g(n,e,t,r,o,i){let a=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/claim`;return n.client.post(a,o,i?.signal)}async function vg(n,e,t){let r=`/v1/games/${f(n.gameId())}/game-rooms/${f(e)}`;return n.client.delete(r,t?.signal)}async function wg(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 kg(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 Sg(n,e,t){return n.client.post("/v1/voice/sessions",e,t?.signal)}async function Rg(n,e,t,r,o){let i=`/v1/settings/${f(e)}/${f(t)}/${f(r)}`;return n.client.delete(i,o?.signal)}async function xg(n,e,t,r,o){let i=`/v1/saves/${f(e)}/${f(t)}/${f(r)}`;return n.client.delete(i,o?.signal)}async function Ag(n,e,t){let r=`/v1/voice/sessions/${f(e)}`;return n.client.delete(r,t?.signal)}async function Pg(n,e,t,r){let o=`/v1/showcase/players/${f(e)}/${f(t)}`;return n.client.delete(o,r?.signal)}async function Eg(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 Tg(n,e,t,r,o,i){let a=`/v1/saves/${f(e)}/${f(t)}/${f(r)}/finalize`;return n.client.post(a,o,i?.signal)}async function Cg(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 Ig(n,e,t){let r=`/v1/inventory/loot-tables/${f(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function Mg(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 Og(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 Lg(n,e,t,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${f(e)}/${f(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Gg(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 Dg(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 a=i.toString(),s=`/v1/leaderboards/${f(e)}/${f(t)}/${f(r)}`+(a?`?${a}`:"");return n.client.get(s,o?.signal)}async function $g(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 Fg(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 qg(n,e,t,r,o,i){let a=`/v1/inventory/${f(e)}/${f(t)}/catalogs/${f(r)}/recipes/${f(o)}/availability`;return n.client.get(a,i?.signal)}async function jg(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${f(e)}/${f(t)}/recipe-usage`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Ng(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 Ug(n,e,t){let r=`/v1/events/${f(e)}`;return n.client.get(r,t?.signal)}async function Bg(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 Vg(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 Hg(n,e,t){let r=`/v1/profiles/players/${f(e)}`;return n.client.get(r,t?.signal)}async function Wg(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 Kg(n,e,t){let r=`/v1/game-room-templates/${f(e)}`;return n.client.get(r,t?.signal)}async function Jg(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 zg(n,e,t,r){let o=`/v1/showcase/players/${f(e)}/${f(t)}`;return n.client.get(o,r?.signal)}async function Yg(n,e,t){let r=`/v1/inventory/transfers/${f(e)}`;return n.client.get(r,t?.signal)}async function pi(n,e,t){let r=`/v1/games/${f(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{replaySafe:true})}async function Xg(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Qg(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function Zg(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 ey(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 ty(n,e,t,r){let o=`/v1/settings/${f(e)}/${f(t)}`;return n.client.get(o,r?.signal)}async function ny(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${f(e)}/${f(t)}/orders`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function ry(n,e,t,r){let o=`/v1/inventory/${f(e)}/${f(t)}/progressions`;return n.client.get(o,r?.signal)}async function oy(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${f(e)}/${f(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function iy(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 ay(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 sy(n,e){return n.client.get("/v1/game-room-templates",e?.signal)}async function ly(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 dy(n,e,t,r,o,i){let a=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/max`;return n.client.post(a,o,i?.signal)}async function cy(n,e,t,r,o,i){let a=`/v1/settings/${f(e)}/${f(t)}/${f(r)}`;return n.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function uy(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 my(n,e,t,r,o){let i=`/v1/showcase/players/${f(e)}/${f(t)}`;return n.client.put(i,r,o?.signal)}async function py(n,e,t){let r=`/v1/inventory/transfers/${f(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function gy(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 yy(n,e,t,r,o,i){let a=`/v1/saves/${f(e)}/${f(t)}/${f(r)}/upload-url`;return n.client.post(a,o,i?.signal,{replaySafe:true})}async function hy(n,e,t,r,o,i){let a=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/reset`;return n.client.post(a,o,i?.signal)}async function fy(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 by(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 _y(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 vy(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 wy=1e4,ky=50,Sy=1e3,Ry=65536-4*1024,Ed=n=>typeof n=="number"?n:0,xy=n=>typeof n=="string"?n:"";function Td(){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 Ay(n){return n?.retryable===true}function Py(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(o=>{let i=o??{};return {index:Ed(i.index),code:xy(i.code)}}):[];return {accepted:Ed(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function Cd(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 Id(n){let e=Math.max(1,Math.floor(n.maxQueue??Sy)),t={client:n.client,gameId:()=>n.gameId},r=[],o=0,i=null,a=false,s=false,l=false,d=false,m=b=>{n.log?.(b);},u=()=>{i!==null&&(n.clock.clearTimeout(i),i=null);},p=()=>{i!==null||a||s||(i=n.clock.setTimeout(()=>{i=null,y().catch(()=>{});},wy));},g=()=>{let b=Math.min(r.length,100),k=128;for(let x=0;x<b;x+=1){let P=r[x];if(P===void 0)break;if(k+=JSON.stringify(Cd(P,0)).length+1,k>Ry)return Math.max(1,x)}return b};async function y(b){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};u();let k=r.splice(0,g()),x=o;o=0;let P=Math.round(n.clock.now()),_={batch_id:Td(),sent_at_ms:P,events:k.map(S=>Cd(S,P))};s=true;try{let S=await pi(t,_,b===void 0?void 0:{signal:b}),T=Py(S,x);for(let C of T.rejected)m(`[gem] analytics: an event was refused (${C.code}). See the analytics_events section of your game config.`);return T}catch(S){if(Ay(S))for(r=[...k,...r],o+=x;r.length>e;)r.shift(),o+=1;else m(`[gem] analytics: ${k.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(S)}`);throw S}finally{s=false,r.length>0&&p();}}return {track(b,k,x={}){if(a)return;if(typeof b!="string"||b===""){d||(d=true,m(`[gem] analytics: '${k}' 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(k.startsWith(ao)){l||(l=true,m(`[gem] analytics: '${k}' 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 P={},_={};for(let[S,T]of Object.entries(x))typeof T=="string"?P[S]=T:typeof T=="number"&&Number.isFinite(T)&&(_[S]=T);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:Td(),playerId:b,name:k,atMs:n.clock.now(),dimensions:P,measures:_}),r.length>=ky?y().catch(()=>{}):p();},flush:b=>y(b),get pending(){return r.length},dispose(){a=true,u(),r=[],o=0;}}}function Md(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 Bn(i)}}}function Ey(n){let e={};for(let[t,r]of Object.entries(gi))if(typeof r=="function"){let o=r;e[t]=(...i)=>o(n,...i);}return e}function Od(n,e={}){let t=e.clock??ge,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=Pd(n,{clock:t,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=hr({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:n.gameId,channel:n.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),a=new Ne({transport:i,clock:t}),s={gameId:n.gameId,channel:n.channel,matchId:n.matchId,...n.gameRoomId===void 0?{}:{gameRoomId:n.gameRoomId}},l=Ey({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=n.endMatch,u=n.log,p=Id({client:a,clock:t,gameId:s.gameId,...typeof u=="function"?{log:y=>u.call(n,y)}:{}});return {identity:s,client:a,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(n);},setBackfill:async(y,b)=>{let k=await l.setMatchBackfill(s.matchId,{open:y.open,...y.seats===void 0?{}:{seats:y.seats}},b===void 0?{}:{signal:b});return {open:k.open,seats:k.seats??null}},reportPlayers:async(y,b)=>(await l.reportMatchPlayers(s.matchId,{players:y.map(x=>({player_id:x.playerId,state:x.state}))},b===void 0?{}:{signal:b})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new We(l.invokeFunction),challenges:Md(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let b=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),k=b.modified?b.body:void 0;if(k?.room_args==null||k.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:k.room_args,room_args_template:k.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function Qe(n){return n?.reliable!==false?"reliable":n?.ordered!==false?"ordered":"unreliable"}function kt(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 Ty=5e3,Ld=3e4,Gd=2e3,Cy=1e4,Dd=1;async function $d(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}`),a=typeof n=="function"?n():n,s=Promise.resolve(),l=true,d=false,m=(h,I)=>{l&&(s=s.then(async()=>{if(!d)try{await I();}catch(q){i(`the bundle's ${h} handler threw: ${Ze(q)}. Serving continues.`);}}));},u=true,p,g,y,b=h=>{if(!u)return;u=false,m("leave",()=>a.leave?.(r,{cause:h??"left"}));let I=g;I&&queueMicrotask(()=>I(h));},k={send(h,I){if(!u)return;let q=kt(Qe(I));m("message",()=>a.message?.(r,h,typeof h=="string",{reliable:q.reliable,ordered:q.ordered}));},onMessage(h){p=h;},onClose(h){g=h;},close(){b("closed");}},x=(h,I)=>{if(!u)return;let q=kt(Qe(I));queueMicrotask(()=>{u&&p?.(h,q);});},P=new Map,_=h=>{let I=[];for(let q of Le){let te=h.channels[q];try{te.binaryType="arraybuffer";}catch{}let Me=kt(q),qe=xr=>{let je=_r(xr?.data);je!==null&&m("message",()=>a.message?.(h.playerId,je.data,je.isText,{reliable:Me.reliable,ordered:Me.ordered}));};te.addEventListener("message",qe),I.push(()=>te.removeEventListener("message",qe));}P.get(h.playerId)?.forEach(q=>q()),P.set(h.playerId,I);},S=h=>{P.get(h)?.forEach(I=>I()),P.delete(h);},T=new Set,C=new Map,V=(h,I,q)=>({playerNumber:h.assignedPeerId,transport:"webrtc_p2p",...I?{rejoin:true}:{},...q?{superseded:true}:{}}),B=h=>{let I=P.has(h.playerId),q=T.has(h.playerId);T.add(h.playerId),_(h),I&&m("leave",()=>a.leave?.(h.playerId,{cause:"superseded"})),m("join",()=>a.join?.(h.playerId,V(h,q,I)));},K=new Set,A=(h,I,q)=>{if(h===r){x(I,q);return}let te=t.peer(h);if(te===null){let Me=C.get(h);if(Me!==void 0&&e.clock.now()-Me<Gd)return;K.has(h)||(K.add(h),i(`send to '${h}' dropped: no such connected player`));return}te.send(dn(I),Qe(q));},M={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 I of t.peers)h.push(I.playerId);return h},profile(h){let I=e.room()?.members.find(q=>q.playerId===h);if(!(!I||I.displayName===void 0))return {displayName:dt.toPlain(I.displayName),...I.displayTag===void 0?{}:{displayTag:dt.toPlain(I.displayTag)},...I.discriminator===void 0?{}:{discriminator:I.discriminator}}},playerNumber(h){return h===r?Dd:t.peer(h)?.assignedPeerId},send(h,I,q){A(h,I,q);},broadcast(h,I){let q=I?.except;u&&r!==q&&x(h,I);for(let te of t.peers)te.playerId!==q&&te.send(dn(h),Qe(I));},async endMatch(){let h=await Ie();return h.answer!=="ok"&&i(h.cause),h.answer},kick(h,I){if(h===r){b(I??"kicked");return}t.kick(h).catch(q=>{i(`kick of '${h}' failed: ${Ze(q)}`);});},log(h){i(h);},warn(h){i(`\u26A0 ${h}`);}},O=()=>{},$=new Promise(h=>{O=h;}),U=[],j=null,ee=async(h,I)=>{l=false;let q=s.then(async()=>{try{await a.shutdown(h);}catch(te){i(`the bundle's shutdown threw: ${Ze(te)}`);}});s=q,await q,se();for(let te of U.splice(0))te();for(let te of [...P.keys()])S(te);b(I);},de=(h,I)=>j||(j=(async()=>{await ee(I,h),t.close(),O();})(),j),X=()=>j||(j=(async()=>{await ee({reason:"signal"},"left"),await t.leave().catch(h=>i(`leaving the match failed: ${Ze(h)}`)),O();})(),j),Fe=()=>j||(j=(async()=>{l=false;let h=await Ie();h.answer==="ok"?(await ee({reason:"match_ended",platform_reason:"explicit"},"match ended"),t.close()):(i(`${h.cause}; leaving instead`),await ee({reason:"signal"},"left"),await t.leave().catch(I=>i(`leaving the match failed: ${Ze(I)}`))),O();})(),j),ke=null,be=()=>(ke??=Od(M,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),ke),Ie=async()=>{try{return await Ba({client:be().client,gameId:()=>M.gameId},M.matchId,{},{signal:AbortSignal.timeout(Ty)}),{answer:"ok"}}catch(h){return h instanceof L&&(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: ${Ze(h)}`}}},z=null,Q=false,se=()=>{Q=true,z!==null&&(e.clock.clearTimeout(z),z=null);},gn=async()=>{if(z=null,!Q){try{await be().client.post(`/v1/games/${encodeURIComponent(M.gameId)}/matches/${encodeURIComponent(M.matchId)}/heartbeat`,void 0,AbortSignal.timeout(Cy));}catch(h){if(h instanceof L&&(h.reason==="forbidden"||h.reason==="not_found")){i(`the platform no longer holds this match under this host (${h.reason}); heartbeats stop`),se();return}i(`heartbeat failed: ${Ze(h)}`);}Q||(z=e.clock.setTimeout(()=>{gn();},Ld));}},Rt=()=>{Q||z!==null||(z=e.clock.setTimeout(()=>{gn();},Ld));};{let h=O;O=()=>{se(),ke?.dispose(),ke=null,h();};}let tt=Promise.resolve().then(()=>a.init(M));s=tt.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:Dd,transport:"loopback"})),U.push(t.on("peerJoined",B)),U.push(t.on("peerLeft",(h,I)=>{S(h);let q=e.clock.now();for(let[te,Me]of C)q-Me>=Gd&&C.delete(te);C.set(h,q),K.delete(h),m("leave",()=>a.leave?.(h,{cause:I}));})),U.push(t.on("error",h=>{i(`\u26A0 session error: ${h.message}`);})),U.push(t.on("matchEnded",h=>{j||yi(y,h),de("match ended",{reason:"match_ended",platform_reason:h});})),U.push(t.on("hostChanged",h=>{h!==r&&de("host migrated",{reason:"host_migrated"});}));for(let h of t.peers)B(h);try{await tt,Rt();}catch(h){l=false,se(),d=true;for(let I of U.splice(0))I();for(let I of [...P.keys()])S(I);throw t.leave().catch(()=>{}),O(),h}return {matchId:t.matchId,localLink:k,onMatchEnded(h){y=h;},end:Fe,leave:X,stop:h=>de(h,{reason:"stopped"}),done:$}}function yi(n,e){try{n?.(e);}catch{}}function Ze(n){return n instanceof Error?n.message:String(n)}function hi(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 Fd(n){let e=new Map,t=n.autoReconnect===true,{rooms:r}=n,o=new Map,i=async s=>{r.isHost&&!mi(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...s.signal===void 0?{}:{signal:s.signal}});let l={...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},a=s=>({...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0?{}:{clusterTargetId:s.clusterTargetId}});return {async serve(s,l={}){let d=await i(l);if(d.protocol!==Ye)return hi("dedicated",d.matchId);let m=n.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return hi("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(a(l)),g=await $d(s,{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(s={}){let l=await i(s),d=s.onMatchEnded;if(l.protocol===Ye){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Ly(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(),b=async()=>n.p2p.connect({...a(s),certificate:y}),k=await b(),x=Dy(k,b,d,P=>{r.notifyMatchDisconnected(P).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),t);return t&&(e.set(k.matchId,{redial:x.redial,abandon:x.abandon}),x.onClosed(()=>{e.get(k.matchId)?.abandon===x.abandon&&e.delete(k.matchId);})),x}let m=async(g=null)=>await n.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:s.transports??[]}),u=await m(),p=Gy(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(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var qd="link_closed",Iy="host_unreachable",My=new Set(["failed","closed"]);function Oy(n){return My.has(n)?qd:Iy}function Ly(n,e,t){let r=e.localLink;e.onMatchEnded(t);let o="connected";r.onClose(()=>{o="closed";});let i;return {matchId:n,protocol:"loopback",get state(){return o},send:(a,s)=>r.send(a,s),onMessage:a=>r.onMessage(a),onClose:a=>{i=a,r.onClose(s=>{o="closed",i?.(s);});},close:()=>r.close()}}function Gy(n,e,t,r){let o=n.matchId,i=n,a="connected",s,l,d=[],m=false,u=false,p=y=>{if(a!=="closed"){a="closed";for(let b of d.splice(0))b();l?.(y);}},g=y=>{y.link.onMessage((b,k)=>s?.(b,k)),y.link.onClose(b=>{if(y!==i||a==="closed")return;if(m||!r){p(b);return}let k=t.matchSession;if(k.phase==="suspended"&&k.matchId===o){a="suspended";return}p(b);});};return g(n),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return a},send(y,b){a==="connected"&&i.link.send(y,b);},onMessage(y){s=y;},onClose(y){l=y;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(a==="closed"||m)return "closed";if(u)return "connected";u=true;let b;try{b=await e(y===void 0?{}:{deadlineAt:y});}finally{u=false;}return m||a==="closed"?(b.close(),"closed"):(i=b,g(b),a="connected",t.notifyMatchConnected(o),"connected")},abandon(y){a!=="closed"&&(a==="connected"&&i.close(),p(y));},onClosed(y){a==="closed"?y():d.push(y);}}}function Dy(n,e,t,r,o,i=false){let a=n.matchId,s=n,l,d,m=[],u=[],p=[],g=false,y=false,b=false,k=false,x="connected",P=A=>{if(g)return;g=true,x="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 M=d;M&&queueMicrotask(()=>M(A));},_=A=>{for(let M of m.splice(0))M();for(let M of Le){let O=A.channels[M];try{O.binaryType="arraybuffer";}catch{}let $=kt(M),U=j=>{let ee=_r(j?.data);ee!==null&&l?.(ee.data,$);};O.addEventListener("message",U),m.push(()=>O.removeEventListener("message",U));}},S=()=>s.peer(s.hostPlayerId),T=A=>{if(!(g||s.isHost)&&x!=="suspended"){if(r?.(A),i){x="suspended";return}P(A);}},C=A=>{for(let M of Le){let O=A.channels[M];if(typeof O.addEventListener!="function")continue;let $=()=>{S()===A&&T(qd);};O.addEventListener("close",$),m.push(()=>O.removeEventListener?.("close",$));}},V=A=>{_(A),C(A),!g&&(x="connected",o?.());},B=A=>{for(let M of u.splice(0))M();u.push(A.on("migrating",()=>{k=true;})),u.push(A.on("hostChanged",M=>{if(k=false,M===A.playerId){P("host_migrated_here");return}let O=S();O!==null&&V(O);})),u.push(A.on("peerJoined",M=>{M.playerId===A.hostPlayerId&&V(M);})),u.push(A.on("matchEnded",M=>{g||yi(t,M),P(M);})),u.push(A.on("peerLeft",(M,O)=>{M===A.hostPlayerId&&T(Oy(O));}));};B(s);let K=S();return K!==null&&V(K),{matchId:a,protocol:"p2p",get state(){return x},send(A,M){x==="connected"&&S()?.send(dn(A),Qe(M));},onMessage(A){l=A;},onClose(A){d=A;},close(){y=true,P("closed"),s.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||b)return "connected";if(k)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");b=true;let A;try{for(let O of m.splice(0))O();for(let O of u.splice(0))O();s.close(),A=await e();}finally{b=false;}if(g)return y?A.leave().catch(()=>{}):A.close(),"closed";s=A,B(s);let M=S();if(M===null)throw s.close(),new G("connection_failed","this peer rejoined the match but the host never answered with a link");return V(M),"connected"},abandon(A){P(A);},onClosed(A){g?A():p.push(A);}}}function fi(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(o=>{let i={},a=l=>{t.delete(r)&&(n.clock.clearTimeout(i.timer),o(l));};t.set(r,a),i.timer=n.clock.setTimeout(()=>a(void 0),n.timeoutMs??2e3);let s=false;try{s=n.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,o){t.get(r)?.(o);}}}var $y=12e4;function et(n,e){return {outcome:n,reason:e}}function jd(n){let e=false,t=new Map;return {api:{request(r){if(!n.bridge.parentSupports("purchases"))return Promise.resolve(et("unavailable","error"));if(e)return Promise.resolve(et("declined","busy"));let o=`purchase-${Ae()}`;return new Promise(i=>{let a={},s=d=>{t.delete(o)&&(e=false,n.clock.clearTimeout(a.timer),i(d));};e=true,t.set(o,s),a.timer=n.clock.setTimeout(()=>s(et("unavailable","error")),n.timeoutMs??$y);let l=false;try{l=n.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(et("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(et(o,us(r.reason)));return}let a=r.purchaseId;if(a===void 0){n.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),i(et("unavailable","error"));return}(async()=>{let s;try{s=await n.confirm(a);}catch{s="unknown";}if(s==="granted"){i({outcome:"ok",purchaseId:a});return}s==="absent"&&n.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(a)),i(et("unavailable","error"));})();}}}async function Nd(n,e){try{return (await xa(n,e)).granted?"granted":"absent"}catch(t){return t instanceof L&&t.reason==="not_found"?"absent":"unknown"}}var Fy=6e5;function Ud(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-${Ae()}`;return e=new Promise(o=>{let i={},a=l=>{t.delete(r)&&(e=null,n.clock.clearTimeout(i.timer),o(l));};t.set(r,a),i.timer=n.clock.setTimeout(()=>{a({outcome:"unavailable"});},n.timeoutMs??Fy);let s=false;try{s=n.bridge.requestSignIn(r);}catch{}s||a({outcome:"unavailable"});}),e}},settle(r){let o=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",i=t.get(r.requestId);if(i===void 0){n.onDropped?.(`gem.signInResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var qy=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),jy=["utm_"];function Bd(n){return qy.has(n)||jy.some(e=>n.startsWith(e))}var Vd=16,Hd=512,Ny=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Uy=/[\p{Cc}\p{Cf}]/u,By=/\p{Cs}/u,Te="[gem] gem.share.request:";function Wd(n){let{frame:e,log:t}=n,r=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,i=a=>{t!==null&&(t===void 0?console.warn(a):t(a));};return {get available(){return o()!==null},request(a){let s=o();if(s===null)throw new Error(`${Te} the arcade does not handle share here \u2014 check gem.share.available first`);if(a!==void 0&&(typeof a!="object"||a===null))throw new TypeError(`${Te} pass { params }, or nothing`);let l=a?.params===void 0?{}:a.params;if(!Vy(l))throw new TypeError(`${Te} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>Vd)throw new TypeError(`${Te} at most ${Vd} params; got ${d.length}`);let m=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!Ny.test(u))throw new TypeError(`${Te} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Bd(u))throw new TypeError(`${Te} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Te} param ${g}: values must be strings`);if(p.length>Hd)throw new TypeError(`${Te} param ${g}: a value is at most ${Hd} characters`);if(Uy.test(p))throw new TypeError(`${Te} param ${g}: control and format characters are not allowed`);if(By.test(p))throw new TypeError(`${Te} param ${g}: a value must be well-formed text`);m.push({key:u,value:p});}!s.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 Vy(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var Jy="(any-pointer: coarse)";function zy(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 Kd(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,a=new Set,s=()=>typeof o?.vibrate!="function"||r.matchMedia===void 0?false:(i??=r.matchMedia(Jy),i.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,u)=>{a.has(m)||(a.add(m),t!==null&&(t===void 0?console.warn(u):t(u)));};return {get available(){return s()||l()},vibrate(m){let u=s();if(!u&&!l())return false;let p=zy(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 Yy=["lookSensitivity","gamepadLookSensitivity","invertLookY","touchMovement"];function vr(n){let e={};if(typeof n=="object"&&n!==null)for(let t of Yy){let r=n[t];(r==="player"||r==="game")&&(e[t]=r);}return e}var St=Math.PI/180,Ce=Object.freeze({touch:Object.freeze({yaw:1*St,pitch:.66*St}),mouse:Object.freeze({yaw:.5*St,pitch:.5*.77*St}),stick:Object.freeze({yaw:240*St,pitch:240*.77*St}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),bi="[gem.controls]",_i=Object.freeze({yaw:0,pitch:0}),wr=n=>Number.isFinite(n)?n:0,Jd=(n,e)=>({yaw:n+0,pitch:e+0});function zd(n){let e=wr(n),t=(Math.abs(e)-Ce.stickDeadzone)/(1-Ce.stickDeadzone),r=Ce.stickCurve,o=(Math.exp(r*t)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,o))+0}function Xy(n){let e=Math.min(1,2*Math.abs(n)/Math.PI);return (1-Math.pow(e,.75))*(1-Ce.touchPitchMin)+Ce.touchPitchMin}function Yd(n,e){if(n===void 0)return {};if(typeof n!="object"||n===null)throw new TypeError(`${bi} ${e} takes an options object`);let t=n;for(let r of ["sensitivity","gamepadSensitivity"]){let o=t[r];if(o!==void 0&&!(typeof o=="number"&&Number.isFinite(o)&&o>0))throw new TypeError(`${bi} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(o)}`)}if(t.invertY!==void 0&&typeof t.invertY!="boolean")throw new TypeError(`${bi} ${e}: invertY must be a boolean; got ${String(t.invertY)}`);return t}function Qy(n,e){let t=Yd(e,"look()"),r=t.sensitivity,o=t.gamepadSensitivity,i=t.invertY,a=s=>i??s?.invertLookY??false;return {fromPointer(s,l,d,m){let u=wr(s),p=wr(l);if(u===0&&p===0)return _i;let g=n(),y=r??(g===null?void 0:g.lookSensitivity/100)??1,b=d==="touch"||d==="pen",k=b?Ce.touch:Ce.mouse,x=u*k.yaw*y,P=-p*k.pitch*y;return a(g)&&(P=-P),b&&m!==void 0&&Number.isFinite(m)&&P*m>0&&(P*=Xy(m)),Jd(x,P)},fromStick(s,l,d){let m=wr(d);if(m<=0)return _i;let u=zd(s),p=zd(l);if(u===0&&p===0)return _i;let g=n(),y=o??(g===null?void 0:g.gamepadLookSensitivity/100)??1,b=u*Ce.stick.yaw*m*y,k=-p*Ce.stick.pitch*m*y;return a(g)&&(k=-k),Jd(b,k)},set(s){let l=Yd(s,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(o=l.gamepadSensitivity),"invertY"in l&&(i=l.invertY);}}}function Xd(n){return {declare:e=>n.declare(e),look:e=>Qy(n.recommended,e),LOOK_BASE:Ce}}var Zy=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Qd(n){if(typeof n!="string"||!Zy.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 Zd(n,e){let t=typeof n=="object"&&n!==null?n:{},r=Qd(t.resets_at),o=r===void 0?{}:{resetsAt:r};if(t.declared!==true)return {...cn(),...o};let i=t.remaining_today,a=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):void 0,s=t.next_eligible_at,l=Qd(s),d=t.held_limit_reached===true,m=s!=null,u=i!=null&&a===void 0;return {declared:true,grantable:t.grantable===true&&e&&a!==0&&!u&&!m&&!d,...a===void 0?{}:{remainingToday:a},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...o}}var eh=18e4,vi=32,th=/^[a-z0-9_-]+$/,nh="rewarded_requires_user_gesture";function rh(){let n=globalThis.navigator?.userActivation?.isActive;return typeof n=="boolean"?n:void 0}var oh=1e3;function ih(){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 a=o[i]?.timestamp;if(typeof a=="number"&&r-a>=0&&r-a<=oh)return true}return false}var ec=1e4;function ah(n){return n==="interstitial"||n==="rewarded"}function tc(n){return typeof n=="string"&&n!==""&&n.length<=vi&&th.test(n)}function sh(n){let e=typeof n=="object"&&n!==null?n:{};return [e.name,e.reason,e.status].join()}function kr(n){return typeof n=="string"?JSON.stringify(n):typeof n}function nc(n){let e=false,t=new Map,r=new Map,o=new Set,i=d=>{try{n.onDropped?.(d);}catch{}},a=false,s=d=>{if(a)return;a=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={},b=_=>y.done===true?false:(y.done=true,n.clock.clearTimeout(y.timer),g(_),true),k=(_,S)=>{!b(cn())||o.has(_)||(o.add(_),i(`gem.ads.rewardedStatus("${d}") answered not grantable: ${S}. Said once.`));},x=_=>{k(sh(_),`the read failed (${_ instanceof Error?_.message:kr(_)})`);},P;try{P=Promise.resolve(m(d,AbortSignal.timeout(ec)));}catch(_){P=Promise.reject(_);}y.timer=n.clock.setTimeout(()=>{k("timeout","no answer within 10 s");},ec),P.then(_=>{try{b(Zd(_,n.bridge.parentSupports("ads")));}catch(S){x(S);}},x);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return tc(d)?l(d):(i(`gem.ads.rewardedStatus(${kr(d)}) answered not grantable: a placement is 1..${String(vi)} 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(!tc(m)||!ah(u))return i(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${kr(m)}, format ${kr(u)}. A placement is 1..${String(vi)} 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??rh)();}catch{g=void 0;}if(g===false)try{(n.recentGamepadInput??ih)()===!0&&(g=!0);}catch{}if(g===false){let y=`${nh}: 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),s(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${Ae()}`;return new Promise(g=>{let y={},b=x=>{t.delete(p)&&(e=false,n.clock.clearTimeout(y.timer),g(x));};e=true,t.set(p,b),y.timer=n.clock.setTimeout(()=>{b({outcome:"unavailable"});},n.timeoutMs??eh);let k=false;try{k=n.bridge.requestAd(p,m,u);}catch{}k||b({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 wi=16384;function rc(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:lh(e)}function lh(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 dh=1e4,ch=5e3;function oc(n){let e=null,t=false,r=[],o=new Map,i=()=>{for(let a of r.splice(0))a();};return {api:{get current(){return e},wait(a=ch){return t?Promise.resolve(e):new Promise(s=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{n.clock.clearTimeout(m),l(),s(e);},m=n.clock.setTimeout(()=>{l(),s(e);},a);r.push(d);})},put(a){if(!n.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let s=rc(a);if(s===null)return n.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(s>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(a)),d=`device-settings-${Ae()}`;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??dh);let g=false;try{g=n.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(a){let s=a.settings;e=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,t=true,i();},settle(a){let s=a.outcome==="stored"||a.outcome==="too_large"?a.outcome:"unavailable",l=o.get(a.requestId);if(l===void 0){n.onDropped?.(`gem.deviceSettings.result (${s}) for an unknown requestId: `+JSON.stringify(a.requestId));return}l(s);}}}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 uh=/^[a-z0-9][a-z0-9_-]{0,39}$/;function mh(n){return typeof n=="string"&&uh.test(n)}function Sr(n){if(n===null||mh(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 ic(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function ki(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(a=>a.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 ac(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function ph(n){let e=n.untrusted,t=Oe(e.displayName),r=e.displayTag||e.displayHandle,o=r?Oe(r):void 0,i=n.discriminator||n.displayTag,a=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,s=n.avatarIconUrl||n.avatarUrl,l=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),a&&(d.discriminator=a),o&&(d.displayTag=o),s&&(d.avatarIconUrl=d.avatarUrl=s),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 gh=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??ge,this.inbound=new Pt(this.clock),this.outbound=new Pt(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>Nr(s,e.origin))||ss(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=Rn["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!Nr(o.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${o.embedder}' but arrived from '${e.origin}'`),false;let i=e.ports?.[0];if(!i)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=ls(kn,o.versions);return a===null?(i.onmessage=null,i.postMessage({gem:N,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=a,i.onmessage=s=>this.receive(s.data,s.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:N,type:"gem.handshake.accept",v:a,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:N,type:"gem.ready"});}settled(e=gh){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:N,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:N,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:N,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:N,type:"gem.exit"}:{gem:N,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:N,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:N,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:N,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:N,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:N,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:ic(e.origin.x),y:ic(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:N,type:"gem.portraitBorders"}:{gem:N,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:N,type:"gem.walletDisplay",...ki(e,t?.only)})}declareControls(e){return this.state!=="connected"||!this.parentSupports("controls")?false:this.send({gem:N,type:"gem.controlsDeclare",uses:vr(e)})}setMenu(e,t){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:N,type:"gem.menu",...Rr(e,t)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:N,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:N,type:"gem.requestAvatarPicker"})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:N,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:N,type:"gem.frameStats",fps:ac(e.fps,1e3),frameTimeP95Ms:ac(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:N,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:N,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:N,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:N,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,o,i,a){return this.send({gem:N,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,t){return this.send({gem:N,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:N,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:N,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,o){return this.send({gem:N,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(Sn)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(Sn)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(Sn)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:N,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=Rn[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||sc(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=Rn[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=rs(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let a=o(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.menuSelect":this.options.onMenuSelect?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return sc(t.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(ph(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:N,type:"gem.screenshot.denied",reason:e,retryable:t});}};function sc(n){for(let e of n)try{e?.close?.();}catch{}}var lc="https://api.gemarcade.com";function Si(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 yh=new Set(["localhost","127.0.0.1","[::1]"]);function dc(n){let e=Si(n);if(e!==null)return e;let t=new URL(n);return t.protocol==="http:"&&!yh.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 fh=Object.freeze(["https://gemarcade.com","https://meme-games.com","http://gemarcade.localhost","gemarcade://localhost"]),bh=lc,cc=8e3,Ri=15e3,_h=9e4,vh=1/0,wh=8e3,kh=5e3,Sh=5e3;async function Rh(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 a=()=>{let d=r.indexOf(s);d>=0&&r.splice(d,1);},s=d=>{n.clearTimeout(l),a(),i(d);},l=n.setTimeout(()=>{a(),i(e);},o);r.push(s);})}}}function PR(n={}){let e=n.clock??ge,t=n.log===void 0?c=>console.info(c):n.log,r=n.baseUrl??void 0;if(r!=null){let c=Si(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=Ls(typeof window>"u"?void 0:window.location?.search),i=ti();i.mark("sdk created");let a=()=>Qn(ne.gameVersion,n.clientVersion?.gameVersion),s=new qt({client:()=>rt,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,environment:()=>{let c=a();return {sdk_version:Ni(),...c===null?{}:{game_version:c}}},...n.analytics===void 0?{}:{options:n.analytics},log:t}),l=Ul(()=>{i.mark("engaged"),s.release(),F.reportEngaged();},typeof window>"u"?{}:window),d=c=>{if(c===false)return null;let R=c?.attempts??vh,D=c?.budgetMs??_h;return !(R>0)||!(D>0)?null:{attempts:R,budgetMs:D,maxDelayMs:c?.maxDelayMs??wh}},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"||!jr(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([...fh,...p])]),b=pn(e),k=pn(e),x=pn(e),P=js(t),_=pn(e),S=n.manageAudio===false?null:Yl();n.selectableText!==true&&Xl();let T=null,C=()=>{T!==null&&(k.current!==null&&k.current.muted===T||F.reportMuted(T));},V,B,K=-1/0,A=null,M=()=>{if(V===void 0||A!==null||V===B)return;let c=K+1e3-e.now();if(c>0){A=e.setTimeout(()=>{A=null,M();},c);return}F.showPortraitBorders(V)&&(B=V,K=e.now());},O=null,$=null,U=()=>{if(O===null)return false;let c=JSON.stringify(ki(O.visible,O.only));return c===$?F.parentSupports("walletDisplay"):F.setWalletVisible(O.visible,O)?($=c,true):false},j=null,ee=null,de=null,X=null,Fe=()=>{if(de===null)return false;let c=JSON.stringify(de);return c===X?F.parentSupports("controls"):F.declareControls(de)?(X=c,true):false},ke=()=>{if(j===null)return false;let c=typeof j.onSettings=="function",R=JSON.stringify(Rr(c,j.items));return R===ee?F.parentSupports("gameMenu"):F.setMenu(c,j.items)?(ee=R,true):false},be=Ql({report:c=>F.reportFrameStats(c)}),Ie=false,z=id(()=>ji,()=>Ie),Q=c=>{let R=Ie&&!c,D=Ie!==c;if(Ie=c,R&&z.close(),!!D)try{n.onDevToolsPermissionChange?.(c);}catch(re){t?.(`[gem] onDevToolsPermissionChange threw: ${re instanceof Error?re.message:String(re)}`),queueMicrotask(()=>{throw re});}},se=r??bh,gn=r!==void 0,Rt,tt=c=>(t?.(`[gem] token refused: ${c}`),n.onError?.("internal",c),false),h=(c,R)=>{if(c===void 0)return R!==void 0?tt("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=dc(c);return D!==null?tt(`the embedder named an API root that cannot be used: ${D}. Its value is withheld here rather than written to logs.`):Rt!==void 0&&Rt!==c?tt("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."):(Rt=c,gn||(se=c),true)},I=window.location?.origin,q=null,te=-1/0,Me=2e3,qe=new Set,xr=c=>q!==false?Promise.resolve(true):new Promise(R=>{let D=e.setTimeout(()=>{qe.delete(re),R(false);},c),re=()=>{e.clearTimeout(D),qe.delete(re),R(true);};qe.add(re);}),je=()=>{},Ar=null,F=new mn({allowedEmbedders:y,...typeof I=="string"&&I!==""?{selfOrigin:I}:{},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","controls","gameMenu","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...n.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:c=>{Ar=c,n.onRefused?.(c);},...n.onError===void 0?{}:{onError:n.onError},onStateChange:c=>{ne.onBridgeState(c),c!=="connected"&&be.setRequested(false),$=null,ee=null,X=null,B=void 0,c==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Ar===null?"":` (${Ar})`)+", 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."),je()),c==="connected"&&(i.mark("bridge connected"),uc(),C(),M(),U(),ke(),Fe(),F.unbiddenLaunch&&!l.engaged&&s.hold(),s.startSession(),l.engaged&&F.reportEngaged()),n.onStateChange?.(c);},onPlayer:c=>{b.set(c),n.onPlayer?.(c);},onPrefs:c=>{let R={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,lookSensitivity:c.recommended.lookSensitivity??100,gamepadLookSensitivity:c.recommended.gamepadLookSensitivity??100,invertLookY:c.recommended.invertLookY??false,touchMovement:c.recommended.touchMovement==="fixed"?"fixed":"floating"})};k.set(R),S?.setMuted(R.muted),be.setRequested(R.showFrameStats&&F.parentSupports("frameStats")),n.onPrefs?.(R);},onCohorts:c=>{let R=Object.freeze(c.cohorts.map(D=>Object.freeze({experimentId:D.experimentId,variantKey:D.variantKey})));x.set(R),n.onCohorts?.(R);},onEarnAllowanceChanged:()=>P.emit(),onViewport:c=>{let R=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(re=>Object.freeze({x:re.x,y:re.y,width:re.width,height:re.height})))});_.set(R);let D=ed();td(D,R.insets),rd(D,R.reserved,nd()),n.onViewport?.(R);},onPause:c=>{s.setPaused(c.paused),be.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=>{s.endSession(c.reason),n.onWillTerminate?.({reason:c.reason,graceMs:c.graceMs});},onToken:c=>{let R=c.garden;if(Q(c.allowDevTools===true),!h(c.apiBaseUrl,R))return;let D=c;ne.onToken(D);let re=ne.identity;re&&(Pr.set(re),Ai||(Ai=true,ue.reconcileSeats().catch(()=>{}))),Pi.push({token:D.token,expiresAt:D.expiresAt});},onTokenDenied:c=>{Q(false),ne.onDenied(c);},onScreenshot:(c,R,D)=>{Kl(c,R,D,{...n.onScreenshot===void 0?{}:{handler:n.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Jl(F,n.onFeedbackContext);},onDevtools:c=>{c==="close"?z.close():c==="open"?z.openFrom("platform").catch(()=>{}):z.isOpen?z.close():z.openFrom("platform").catch(()=>{});},onRoomEvent:c=>ue.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=>ue.handleSeated(c.roomId),onAutoStartFailedEvent:c=>ue.handleAutoStartFailed(c.roomId,c.code),onSocketState:c=>{let R=q;if(q=c.connected,c.connected)for(let re of [...qe])re();if(!c.connected||R===true)return;let D=e.now();D-te<Me||(te=D,ue.reconcile().catch(()=>{}));},onSignalEvent:c=>{let R=typeof c.data=="object"&&c.data!==null&&!Array.isArray(c.data)?c.data:{};ot.handleSignalEvent(c.matchId,c.event,R),c.event==="matchEnded"&&ue.reconcile({matchId:c.matchId,...typeof R.reason=="string"?{reason:R.reason}:{}}).catch(()=>{});},onDedicatedEvent:c=>{c.event==="matchEnded"&&(xt.handleMatchEnded(c.matchId,c.reason),ue.reconcile({matchId:c.matchId,...c.reason===void 0?{}:{reason:c.reason}}).catch(()=>{})),xi.handleEvent(c);},onClusterTarget:c=>fn.accept(c.clusterTargetId,c.clusterTargetIds),onLocalServer:c=>bn.accept(c),onLocalServerDenied:c=>bn.refuse(c),onPartyResult:c=>Ti.settle(c.requestId,c.partyId),onPurchaseResult:c=>Ii.settle(c),onDeviceSettings:c=>{hn.receive(c),n.onDeviceSettings?.(hn.api.current);},onDeviceSettingsResult:c=>hn.settle(c),onAdResult:c=>Oi.settle(c),onSignInResult:c=>Li.settle(c),onFriendChallengeResult:c=>Gi.settle(c)}),xi=new ln({bridge:F}),Pr=pn(e);je=()=>{Pr.release(),b.release(),x.release();},F.currentState==="refused"&&je();let Ai=false,Er=new Set,yn,Pi={current:()=>yn,subscribe:c=>(Er.add(c),yn!==void 0&&c(yn),()=>Er.delete(c)),push:c=>{yn=c;for(let R of [...Er])try{R(c);}catch(D){t?.(`[gem] a server-token listener threw: ${D instanceof Error?D.message:String(D)}`);}}},ne=sd({bridge:F,clock:e,onStateChange:(c,R)=>{if(c==="ready"){if(i.mark("token ready")){let D=i.marks.find(re=>re.name==="token ready")?.at;s.trackPlatform("gem_boot_ready",D===void 0?{}:{boot_ms:Math.max(0,Math.round(D))});}}else c==="lost"&&(i.mark("token lost"),s.trackPlatform("gem_auth_lost"));n.onAuthStateChange?.(c,R);}}),Ei=()=>{let c=ne.identity;return !c||ne.source.currentState==="lost"?null:`${c.playerId}\0${c.gameId}\0${c.channel}`},uc=()=>{i.mark("token requested"),ne.source.get().catch(()=>{});},Ti=fi({bridge:F,clock:e}),Ci={},Ii=jd({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c),confirm:async c=>Ci.confirm?.(c)??"unknown"}),hn=oc({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c)}),Mi={},Oi=nc({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c),readAvailability:(c,R)=>Mi.read?.(c,R)??Promise.reject(new Error("the gem-api client is not built yet")),log:n.log}),Li=Ud({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c)}),Gi=qs({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c)}),fn=zs({bridge:F,clock:e}),bn=od({bridge:F,clock:e}),Tr=c=>{let R=F.handleWindowMessage({data:c.data,origin:c.origin,source:c.source,ports:c.ports});return R&&window.removeEventListener("message",Tr),R};window.addEventListener("message",Tr);let nt=Bl(window,Tr),mc=nt?.capture,Cr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Cr?.domInteractive!==void 0&&Cr.domInteractive>0&&i.mark("document parsed",Cr.domInteractive),mc?.late&&t?.("[gem] the early-handshake capture installed after this document finished loading, so a handshake posted at iframe load may already have been missed. Load the capture script ahead of everything else in the document.");let Ir=n.handshakeWarningMs;Ir!==null&&t&&e.setTimeout(()=>{let c=nt===null?"no capture script ran":`capture: ${nt.delivered} offer(s) delivered, ${nt.stale} stale, ${nt.capture.dropped} evicted${nt.capture.late?", installed late":""}`;if(F.currentState==="connected"){t(`[gem] handshake connected. boot: ${i.timeline()} \xB7 ${c}`);return}t(`[gem] no completed handshake after ${Ir??cc}ms (bridge state: ${F.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);},Ir??cc);let pc=hr({get baseUrl(){return se},tokenSource:ne.source,get defaultQuery(){let c=ne.identity;return c?{game_id:c.gameId,channel:c.channel}:{}}}),rt=new Ne({transport:pc,clock:e}),pe={client:rt,gameId:()=>ne.identity?.gameId??""};Ci.confirm=c=>Nd(pe,c),Mi.read=(c,R)=>Ka(pe,"players","me",c,{signal:R});let gc=()=>ne.identity?.channel??"release",Di=new Un(pe,gc),$i=async c=>(await Di.load())?.currency(c)?.id??void 0,Fi=Dn(pe,Xr,{identity:Ei,resolveCurrencyId:$i}),Mr=async c=>{let R=await Pr.wait(c);if(R)return R;throw F.currentState==="refused"?new le("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 le("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).")},Or=d(n.autoReconnect),ue=jo({client:rt,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,awaitGameId:async()=>(await Mr(Ri)).gameId,resolveParty:Ti.resolve,resolveClusterTargets:fn.resolveList,refreshClusterTargets:fn.refresh,ensureLocalServer:bn.ensure,localHostAvailable:bn.available,...n.clientVersion===void 0?{}:{clientVersion:n.clientVersion},platformGameVersion:()=>ne.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},...Or===null?{}:{autoReconnect:{...Or,redial:(c,R)=>Lr.redialMatch(c,R),abandon:(c,R)=>Lr.abandonMatch(c,R)}}});m(ue),jl({analytics:s,rooms:ue});let ot=ql({client:rt,clock:e,rooms:ue,bridge:F,gameId:()=>ne.identity?.gameId??"",baseUrl:()=>se,resolveClusterTarget:fn.resolve,boot:i,...n.log===void 0?{}:{log:n.log}}),qi=ei(i,t),xt=Rd({client:rt,clock:e,rooms:ue,signaling:()=>xi.channel(),signalingReady:xr,log:t??(()=>{})}),Lr=Fd({rooms:ue,p2p:{connect:c=>qi(ot.connect(c)),session:c=>ot.session(c)},dedicated:{connect:(c=>pr(i,"welcome",xt.connect(c),t))},clock:e,identity:()=>ne.identity,apiBaseUrl:()=>se,tokens:Pi,room:()=>ue.currentRoom,autoReconnect:Or!==null,...n.log===void 0?{}:{log:n.log}}),yc=async()=>(await Mr(Ri)).playerId,ji={client:rt,boot:i,get identity(){return ne.identity},awaitIdentity:(c=Ri)=>Mr(c),awaitBridge:c=>F.settled(c),get player(){return b.current},awaitPlayer:(c=kh)=>b.wait(c),me:Fi,characters:new Fn(pe,void 0,Ei,$i),transfers:new jn(pe,Xr,Fi.inventory),gameConfig:Di,purchases:Ii.api,deviceSettings:hn.api,ads:Oi.api,account:Li.api,share:Wd({frame:F,log:n.log}),vibration:Kd({frame:F,log:n.log}),get avatarPickerAvailable(){return F.currentState==="connected"&&F.parentSupports("avatarPicker")},openAvatarPicker:()=>F.requestAvatarPicker(),controls:Xd({declare:c=>(de=vr(c),Fe()),recommended:()=>k.current?.recommended??null}),analytics:s,leaderboards:new Ot(pe),challenges:new Ct(pe),showcase:new Lt(pe,yc),friends:new Gt(pe,{challenge:Gi.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new $t(pe,P,t),profiles:new Ft(pe),functions:new We((c,R)=>Oa(pe,c,R)),get prefs(){return k.current},get cohorts(){return x.current},get viewport(){return _.current},awaitCohorts:(c=Sh)=>x.wait(c),reportMuted:c=>{T=!!c,C();},showPortraitBorders:c=>{let R=Sr(c);R!==void 0&&(V=R,M());},cueReward:c=>F.cueReward(c),setWalletVisible:(c,R)=>{let D=Array.isArray(R?.only)?[...R.only]:void 0;return O=D===void 0?{visible:c===true}:{visible:c===true,only:D},U()},setMenu:c=>(j={...typeof c?.onSettings=="function"?{onSettings:c.onSettings}:{},...Array.isArray(c?.items)?{items:c.items.map(R=>({...R}))}:{}},ke()),exit:c=>Rh(ue,F,c,s),frame:F,devtools:z,rooms:ue,dedicatedServer:{listClusterTargets:c=>xt.listClusterTargets(c),connect:(c=>pr(i,"welcome",xt.connect(c),t)),handleMatchEnded:(c,R)=>xt.handleMatchEnded(c,R)},p2p:{handleSignalEvent:(c,R,D)=>ot.handleSignalEvent(c,R,D),session:c=>ot.session(c),connect:c=>qi(ot.connect(c))},match:Lr};return ji}
2
- export{fh as ARCADE_EMBEDDERS,qt as AnalyticsApi,le as AuthError,Ct as ChallengesApi,wi as DEVICE_SETTINGS_MAX_BYTES,w as DedicatedServerError,He as FriendChallengeError,Gt as FriendsApi,We as FunctionsApi,L as GemApiError,Ne as GemClient,ce as GemConfigError,mn as GemFrame,zn as GemFunctionError,ie as GemSaveError,un as GemUnframedError,Ot as LeaderboardsApi,Ss as MAX_PERIODS_BACK,tm as PLATFORM_EVENTS,$t as PlatformApi,Kn as PlatformCurrenciesApi,Jn as PlatformEarnAllowanceApi,ye as PlayerText,Ft as ProfilesApi,Ge as PurchaseRefusal,Lt as ShowcaseApi,oe as TransportRefusal,Vt as UNRELIABLE_CHANNEL_LABEL,Oe as asPlayerText,ti as createBootTimeline,PR as createGem,Rh as leaveAndExit,_e as mapIdentity,pr as markOnResolve,Pu as platformIconUrl,Ut as presentJoinCredential,yt as readTemplateTransports,Ht as readTransportAdvert,ei as reportOnResolve,dt as text,rr as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.game.js.map
1
+ var bc=Object.defineProperty;var _c=(n,e)=>{for(var t in e)bc(n,t,{get:e[t],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:10.4.0]";function Ui(){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 vc(n,e){return e!==void 0?!e:n==="chain_exhausted"}var it=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new se(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new se("chain_exhausted","the token chain reached its ceiling");return this.refresh(this.nextReason())}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}refresh(e){if(this.inFlight)return this.inFlight;let t=this.generation;this.enter("pending");let r=this.options.request(e).then(o=>{if(t!==this.generation)throw new se("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=wc(o),a=o?.retryable;throw t===this.generation&&this.enter(vc(i,typeof a=="boolean"?a:void 0)?"lost":"degraded",i),o instanceof se?o:new se(i,String(o))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,t){this.failure=t??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,t));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},se=class n extends Error{constructor(t,r){super(`auth ${t}: ${r}`);this.reason=t;this.name="AuthError";}reason;static isAuthError(t){if(t instanceof n)return true;let r=t;return r?.name==="AuthError"&&typeof r.reason=="string"}};function wc(n){if(n instanceof se)return n.reason;let e=n?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var 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}},Dr=["if-match","if-none-match"],Bi=4096;function kc(n){if(!n)return;let e={};for(let[t,r]of Object.entries(n)){let o=t.toLowerCase();if(!Dr.includes(o)||r===void 0)continue;let i=typeof r=="string"?Sc(r):r;if(typeof i!="string"||i.length>Bi||!Rc(i))throw new oe(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Bi} 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 Sc(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 Rc(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 xc(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 Vi(n,e){let t=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=kc(o.headers),a=xc(o),s=Object.freeze({...o,headers:i,...a===void 0?{}:{bytes:a}}),l=await e.tokenSource.get(),d=await n(s,l);if(d.status!==401||!t)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),u=await n(s,m);if(u.status===401)throw e.tokenSource.close("unavailable"),new se("unavailable","the server refused a freshly minted token");return u}}}function $r(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return btoa(Ac(e))}function _n(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 Fr(n){return new TextDecoder().decode(_n(n))}function Ac(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,a){super(`${t} (${r}): ${o}`);this.reason=t;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Wi=new WeakMap;function Ki(n){return Wi.get(n)??{}}var Pc=new Set([408,429,500,502,503,504]),Ec=6e4;function Tc(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 je=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,...At(o)},o.replaySafe===true)}async post(e,t,r,o={}){return this.send({method:"POST",path:e,body:t,signal:r,...At(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,...At(o)},o.replaySafe===true);return {bytes:Cc(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,...At(o)},o.replaySafe===true)}async delete(e,t,r={}){return this.send({method:"DELETE",path:e,signal:t,...At(r)},r.replaySafe===true)}async send(e,t){return (await this.sendRaw(e,t)).body}async sendRaw(e,t){let r=t?Tc(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw Hi(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw Hi(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(se.isAuthError(l)||oe.isRefusal(l)||e.signal?.aborted||Ic(l))throw l;o=new O("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=Mc(a);if(!Pc.has(a.status))throw s;o=s;}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,a=2**(e-1)*250,s=Math.min(Math.max(i,a),Ec);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,s),u=true,m&&d.clearTimeout(p);})}};function Cc(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 At(n){return {...n.keepalive===void 0?{}:{keepalive:n.keepalive},...n.ifMatch===void 0?{}:{headers:{"if-match":n.ifMatch}}}}function Hi(n){return n.reason!==void 0?n.reason:new DOMException("The operation was aborted.","AbortError")}function Ic(n){let e=n?.name;return e==="AbortError"||e==="TimeoutError"}function Mc(n){let e=Lc(n),t=Dc(n.body),r={...t===void 0?{}:{details:t},...n.invocationId===void 0?{}:{invocationId:n.invocationId}};return Object.keys(r).length>0&&Wi.set(e,r),e}var Oc=new Map([["insufficient_funds","insufficient_funds"]]);function Lc(n){let{status:e,body:t}=n,r=Gc(t),o=n.retryAfterSeconds??Fc(t),i=$c(t),a=i===void 0?void 0:Oc.get(i);if(a!==void 0)return new O(a,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 Gc(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 Dc(n){let t=n?.error?.details;return t===null?void 0:t}function $c(n){let t=n?.error?.code;return typeof t=="string"&&t.length>0?t:void 0}function Fc(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 Ji(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function zi(n,e,t,r,o,i){let a=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/add`;return n.client.post(a,o,i?.signal)}async function Yi(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function Xi(n,e,t){let r=`/v1/games/${v(n.gameId())}/matchmaking/tickets/${v(e)}`;return n.client.delete(r,t?.signal)}async function Qi(n,e,t,r,o,i){let a=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/claim`;return n.client.post(a,o,i?.signal)}async function Zi(n,e,t){return n.client.post("/v1/characters",e,t?.signal)}async function ea(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/orders/batch`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ta(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/orders`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function na(n,e,t){let r=`/v1/games/${v(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function ra(n,e,t,r,o){let i=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.delete(i,o?.signal)}async function oa(n,e,t,r,o){let i=`/v1/saves/${v(e)}/${v(t)}/${v(r)}`;return n.client.delete(i,o?.signal)}async function ia(n,e,t,r){let o=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.delete(o,r?.signal)}async function aa(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/recipes/execute`;return n.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function sa(n,e,t,r,o,i){let a=`/v1/saves/${v(e)}/${v(t)}/${v(r)}/finalize`;return n.client.post(a,o,i?.signal)}async function la(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 da(n,e,t){let r=`/v1/characters/${v(e)}`;return n.client.get(r,t?.signal)}async function ca(n,e,t){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function ua(n,e,t,r,o){let i=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function ma(n,e,t,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function pa(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/items/${v(r)}`;return n.client.get(i,o?.signal)}async function ga(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 a=i.toString(),s=`/v1/leaderboards/${v(e)}/${v(t)}/${v(r)}`+(a?`?${a}`:"");return n.client.get(s,o?.signal)}async function ya(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/orders/${v(r)}`;return n.client.get(i,o?.signal)}async function ha(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}`;return n.client.get(i,o?.signal)}async function fa(n,e,t,r,o,i){let a=`/v1/inventory/${v(e)}/${v(t)}/catalogs/${v(r)}/recipes/${v(o)}/availability`;return n.client.get(a,i?.signal)}async function ba(n,e,t,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(t)}/recipe-usage`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function qr(n,e,t,r,o){let i=`/v1/saves/${v(e)}/${v(t)}/${v(r)}`;return n.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function _a(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/${v(e)}/friends`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function va(n,e,t){let r=`/v1/showcase/friends/${v(e)}`;return n.client.get(r,t?.signal)}async function wa(n,e,t){let r=`/v1/inbox/friend-challenges/${v(e)}`;return n.client.get(r,t?.signal)}async function ka(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/${v(e)}`+(o?`?${o}`:"");return n.client.get(i,t?.signal)}async function Sa(n,e){let t=`/v1/games/${v(n.gameId())}/players/me/earn-allowance`;return n.client.get(t,e?.signal)}async function vn(n,e){return n.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Ra(n,e,t){let r=`/v1/profiles/players/${v(e)}`;return n.client.get(r,t?.signal)}async function xa(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 Aa(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 Pa(n,e,t,r){let o=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.get(o,r?.signal)}async function Ea(n,e){return n.client.get("/v1/characters/slots",e?.signal)}async function Ta(n,e,t){let r=`/v1/inventory/transfers/${v(e)}`;return n.client.get(r,t?.signal)}async function Ca(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 Ia(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 Ma(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function Oa(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/platform-funded-game-inventory-purchases`;return n.client.post(i,r,o?.signal)}async function La(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function Ga(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 Da(n,e){return n.client.get("/v1/characters",e?.signal)}async function $a(n,e,t,r){let o=`/v1/settings/${v(e)}/${v(t)}`;return n.client.get(o,r?.signal)}async function Fa(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(t)}/orders`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function qa(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${v(e)}/${v(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function ja(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 Na(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 Ua(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 Ba(n,e,t){let r=`/v1/inbox/friend-challenges/${v(e)}/answered`;return n.client.post(r,void 0,t?.signal)}async function Va(n,e,t,r){let o=`/v1/games/${v(n.gameId())}/matches/${v(e)}/end`;return n.client.post(o,t,r?.signal)}async function Ha(n,e,t,r,o,i){let a=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/max`;return n.client.post(a,o,i?.signal)}async function Wa(n,e,t,r,o,i){let a=`/v1/settings/${v(e)}/${v(t)}/${v(r)}`;return n.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ka(n,e,t,r,o){let i=`/v1/showcase/players/${v(e)}/${v(t)}`;return n.client.put(i,r,o?.signal)}async function Ja(n,e,t,r,o){let i=`/v1/inventory/${v(e)}/${v(t)}/rewarded-placements/${v(r)}/availability`;return n.client.get(i,o?.signal)}async function za(n,e,t){let r=`/v1/inventory/transfers/${v(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function Ya(n,e,t,r){let o=`/v1/characters/${v(e)}`;return n.client.patch(o,t,r?.signal)}async function Xa(n,e,t,r,o,i){let a=`/v1/saves/${v(e)}/${v(t)}/${v(r)}/upload-url`;return n.client.post(a,o,i?.signal,{replaySafe:true})}async function Qa(n,e,t,r,o,i){let a=`/v1/inventory/${v(e)}/${v(t)}/progressions/${v(r)}/reset`;return n.client.post(a,o,i?.signal)}async function Za(n,e,t){let r=`/v1/characters/${v(e)}`;return n.client.delete(r,t?.signal)}var N="gem-web-bridge",kn={min:1,max:1},at=65536,es=8,wn=5e3,ts=1024;function ns(n){return Object.freeze(Object.assign(Object.create(null),n))}var rs=ns({"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.controlsDeclare":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}),Sn="__malformed";var qc=ns({"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","gem.controlsDeclare":"controls"}),jc=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function os(n){let e=qc[n];if(e!==void 0)return e;for(let[t,r]of jc)if(n.startsWith(t))return r}function Nr(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 Nc(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 Uc(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Bc(n){return /^[a-z_]+$/.test(n)}function jr(n,e,t){if(e>es)return `nesting deeper than ${es}`;if(++t.nodes>wn)return `more than ${wn} values`;if(t.bytes>at)return `over the ${at} 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>ts)return `an array of ${n.length} entries, over the ${ts} limit`;t.bytes+=2;for(let s of n){let l=jr(s,e+1,t);if(l)return l}return null}let i=Object.getPrototypeOf(n);if(i!==Object.prototype&&i!==null)return "a value that is not a plain object";t.bytes+=2;let a=n;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++t.nodes>wn)return `more than ${wn} values`;if(t.bytes+=s.length*3+4,t.bytes>at)return `over the ${at} byte limit`;let l=jr(a[s],e+1,t);if(l)return l}return null}function Vc(n){let e={nodes:0,bytes:0,seen:new Set},t=jr(n,0,e);return t?`message contains ${t}`:e.bytes>at?`message is over the ${at} byte limit`:null}var Hc={origin:[Nr,"not a well-formed origin"],url:[Nc,"not a safe absolute http(s) URL"],bcp47:[Uc,"not a well-formed BCP 47 tag"],code:[Bc,"not a code of lower-case letters and underscores"]};function is(n,e,t){for(let r of e){let o=t===""?r.n:`${t}.${r.n}`,i=n[r.n];if(i==null){if(r.o)continue;return `${o}: required`}let a=as(i,r,o);if(a)return a}return null}function as(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]=Hc[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`:is(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 a=as(i,r,o);if(a)return a}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}var ss=Object.create(null);function E(n,e){return ss[n]=t=>{let r=Vc(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let o=t;return o.gem!==N?"gem: wrong protocol marker":o.type!==n?`type: expected ${n}`:is(o,e,"")}}E("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}]);E("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}}]);E("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}]);E("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}]);E("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}]}]);E("gem.pause",[{n:"paused",k:"b"}]);E("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"},{n:"graphicsQuality",k:"s",o:1,max:16,f:"code"},{n:"graphicsQualityAuto",k:"b",o:1}]}]);E("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}]}}]);E("gem.earnAllowanceChanged",[]);E("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}]}}]);E("gem.deviceSettings",[{n:"settings",k:"j",o:1}]);E("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}]);E("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"]}]);E("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}]);E("gem.seatedEvent",[{n:"roomId",k:"s",max:64}]);E("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}]);E("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"}]);E("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}]);E("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}]);E("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}]);E("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}]);E("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}]);E("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}]);E("gem.requestContext",[]);E("gem.gameContext",[{n:"context",k:"j"}]);E("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]);E("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}]);E("gem.partyRequest",[{n:"requestId",k:"s",max:64}]);E("gem.ready",[]);E("gem.engaged",[]);E("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}]);E("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}]);E("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}]);E("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}]);E("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}]);E("gem.exit",[{n:"reason",k:"s",o:1,max:64}]);E("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}]);E("gem.requestFullscreen",[{n:"enabled",k:"b"}]);E("gem.audioState",[{n:"muted",k:"b"}]);E("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}]}]);E("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}]);E("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}]);E("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}]}}]);E("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}]);E("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}]}}]);E("gem.requestAvatarPicker",[]);E("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}]);E("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5}]);E("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}]);E("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}]);E("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}]);E("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}]);E("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}]);E("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}]);E("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}]);E("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}]);E("gem.requestSignIn",[{n:"requestId",k:"s",max:64}]);E("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}]);E("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}]);E("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}]);var Rn=Object.freeze(ss);var ge={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},Pt=class{constructor(e=ge){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=rs[e];if(t===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??t,a=Math.max(0,r-o),s=Math.min(t,i+a*t/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function Ur(n,e){return n.toLowerCase()===e.toLowerCase()}function xn(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function ls(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:xn(t.hostname)&&xn(r.hostname)}function ds(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 An=class{constructor(e,t){this.inventory=e;this.resolveCurrencyId=t;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,t={}){let o=(await this.inventory.snapshot({buckets:t.buckets})).currencies.data,i=o.find(s=>s.currencyId===e),a;return !i&&this.resolveCurrencyId&&(a=await this.resolveCurrencyId(e).catch(()=>{}),a!==void 0&&(i=o.find(s=>s.currencyId===a))),{currencyId:i?i.currencyId:a??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function Vr(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 cs="inventory",st=n=>typeof n=="number"?n:0,Et=n=>typeof n=="string"?n:"";function Br(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 us(n){let e=n??{};return {itemDefinitionId:Et(e.item_definition_id),instanceId:Et(e.instance_id),quantity:st(e.quantity),acquiredAt:st(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function Wc(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {currencies:Br(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(a=>{let s=a??{};return {bucket:Et(s.bucket),balance:st(s.balance)}}):void 0;return {currencyId:Et(o.currency_id),total:st(o.total),...i===void 0?{}:{buckets:i}}}),items:Br(e.items,us),progressions:Br(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:Et(o.progression_definition_id),currentValue:st(o.current_value),completionCount:st(o.completion_count),isCompleted:o.is_completed===true,...Vr(o)}}),...t===void 0?{}:{etag:t}}}var Pn=class{constructor(e,t,r){this.api=e;this.entity=t;this.cache=r;}api;entity;cache;snapshot(e={}){let t=e.buckets?`${cs}#buckets`:cs;return this.cache.read(t,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,t){let r=await this.snapshot();if(r.items.nextCursor===void 0){let i=r.items.data.filter(a=>a.itemDefinitionId===e);if(i.length>0)return i}let o=await pa(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return Array.isArray(o)?o.map(us):[]}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 ma(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 Wc(t)}};var Kc={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},Jc=new Set(Object.keys(Kc));function ms(n){return typeof n=="string"&&Jc.has(n)?n:"error"}var De=class extends RangeError{constructor(t,r){super(r);this.code=t;this.name="PurchaseRefusal";}code;retryable=false};var te=n=>typeof n=="string"?n:"",zc=n=>typeof n=="string"?n:te(n&&typeof n=="object"?n.type:void 0),Re=n=>typeof n=="number"?n:0;function Yc(n){let e=n??{};return {prerequisiteType:te(e.prerequisite_type),referenceId:te(e.reference_id),required:Re(e.required),current:Re(e.current)}}function Tt(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0;return {orderId:te(e.order_id),status:te(e.status),...t===void 0?{}:{etag:t}}}function En(){return crypto.randomUUID()}var Xc="recipe-usage",ps=100;function Tn(n){let e=n??{};switch(e.type){case "currency":return {kind:"currency",currencyId:te(e.currency_id),bucket:te(e.bucket),delta:Re(e.delta),balanceAfter:Re(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:te(e.item_definition_id),instanceId:te(e.instance_id),delta:Re(e.delta),quantityAfter:Re(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:te(e.progression_definition_id),delta:Re(e.delta),valueAfter:Re(e.value_after),completed:e.completed===true};default:return {kind:"other",type:te(e.type)}}}function Qc(n){let e=n??{},t=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:te(e.entry_id),...t===void 0?{}:{rarityTier:t},rollNumber:Re(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(Tn):[]}}function Zc(n){let e=n??{},t=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(Qc):void 0;return {orderId:te(e.order_id),status:te(e.status),...t===void 0?{}:{etag:t},granted:Array.isArray(e.granted)?e.granted.map(Tn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(Tn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(Tn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function eu(n){let e=n??{},t=e.price??{};return {payment:"platform_currency",orderId:te(e.target_order_id)||te(e.source_order_id),status:te(e.status),purchaseId:te(e.purchase_id),sourceOrderId:te(e.source_order_id),price:{currencyId:te(t.platform_currency_id),amount:Re(t.price)}}}function tu(n){let e=n??{},t=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:te(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...t===void 0?{}:{lastUsedAt:t},...r===void 0?{}:{cooldownExpiresAt:r}}}function gs(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 Cn=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(()=>ta(this.api,this.entity.type,this.entity.id,{operations:e.map(gs),source:t.source??"play",nonce:En()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return Tt(r)}async createMany(e,t={}){return this.write(()=>ea(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(gs),nonce:En()})),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 fa(this.api,this.entity.type,this.entity.id,e,t,r===void 0?{}:{signal:r})??{},a=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,s=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(Yc):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>zc(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(Xc,[],async()=>{let t=await ba(this.api,this.entity.type,this.entity.id,{limit:ps})??{},r=Array.isArray(t.usages)?t.usages:[];return {usages:r.map(tu),truncated:r.length>=ps}})}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(()=>aa(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:En()},{...t.ifMatch===void 0?{}:{ifMatch:t.ifMatch},...t.signal===void 0?{}:{signal:t.signal}}));return {payment:"configured",...Zc(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([xa(this.api,t.signal===void 0?{}:{signal:t.signal}),vn(this.api,t.signal===void 0?{}:{signal:t.signal})]),i=e.payment.currencySlug.toLowerCase(),a=o.currencies.find(u=>u.currency_id.toLowerCase()===i||u.slug.toLowerCase()===i);if(a===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 s=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(s===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=s.platform_prices.find(u=>u.platform_currency_id===a.currency_id);if(l===void 0){let u=g=>o.currencies.find(y=>y.currency_id===g)?.slug??g,p=s.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 ${a.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new De("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>Oa(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:a.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:En(),confirmation:"none"},t.signal===void 0?{}:{signal:t.signal}));return eu(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(()=>zi(this.api,this.entity.type,this.entity.id,e,{amount:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Tt(o)}async maxProgression(e,t,r){let o=await this.write(()=>Ha(this.api,this.entity.type,this.entity.id,e,{value:t,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Tt(o)}async claimProgression(e,t){let r=await this.write(()=>Qi(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Tt(r)}async resetProgression(e,t){let r=await this.write(()=>Qa(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},t===void 0?{}:{signal:t}));return Tt(r)}async write(e){return this.cache.invalidate(),e()}};var Hr=n=>typeof n=="string"?n:"",nu=n=>typeof n=="number"?n:0;function ys(n){let e=n??{};return {orderId:Hr(e.order_id),status:Hr(e.status),source:Hr(e.source),createdAt:nu(e.created_at)}}var In=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e={}){let r=await Fa(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(ys):[],...o===void 0?{}:{nextCursor:o}}}async get(e,t){let r=await ya(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return ys(r)}};var hs=n=>typeof n=="number"?n:0,ru=n=>typeof n=="string"?n:"";function ou(n){let e=n??{};return {progressionDefinitionId:ru(e.progression_definition_id),currentValue:hs(e.current_value),completionCount:hs(e.completion_count),isCompleted:e.is_completed===true,...Vr(e)}}var Mn=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 ha(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});return ou(i)}catch{return o??null}}};var On=class{constructor(e,t){this.clock=e;this.identity=t;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,t,r,o){this.rebind();let i=t.length===0,a=i?e:e+"\0"+t.join("\0"),s=this.slots.get(a);if(s){let u=s.filledAt;if(u!==void 0&&(o===void 0||this.clock.now()-u<=o))return Promise.resolve(s.value);if(s.inFlight)return s.inFlight}let l=s??{};this.slots.set(a,l);let d=this.generation,m=r().then(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(a)===l&&this.slots.delete(a));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function Wr(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 Kr(n){try{let e=Wr(await n.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ie=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemSaveError";}reason},iu=3e4,fs="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",au=/^[A-Za-z0-9_]{1,64}$/;function xe(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(!au.test(n)||n.startsWith("_"))throw new TypeError(`${JSON.stringify(n)} is not a usable save key: ${e}.`);return n}function bs(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 Jr(n,e){return n.aborted&&e?.aborted!==true}var su=new Set(["x-ms-blob-type"]),lu=/^[ -~]+$/;function du(n,e){if(n==null)return {};if(typeof n!="object"||Array.isArray(n))throw new ie("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(!su.has(i))throw new ie("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"||!lu.test(o))throw new ie("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 ie("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);t[i]=o;}return t}function zr(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 Yr(n){return n?.reason==="not_found"}var Ln=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 ie("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 ie("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,t,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),a=bs(r.signal,i);try{let s=await Xa(this.api,this.entity.type,this.entity.id,xe(e),{size_bytes:t.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:a.signal});if(typeof s.upload_url!="string"||typeof s.session_id!="string")throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=du(s.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(s.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:t,credentials:"omit",signal:a.signal});}catch(u){throw Jr(a.signal,r.signal)?this.timeout("upload",i):new ie("upload_failed",`${fs} for PUT. Underlying error: ${u}`)}if(!d.ok){let u=await Kr(d);throw new ie("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 zr(await sa(this.api,this.entity.type,this.entity.id,xe(e),{session_id:s.session_id},{signal:a.signal}))}catch(s){throw this.rethrow(s,r.signal,a.signal,"save",i)}finally{a.release();}}async get(e,t={}){let r=await this.getBytes(e,t);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new ie("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=bs(t.signal,r);try{let i;try{let l=await qr(this.api,this.entity.type,this.entity.id,xe(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(Yr(l))return null;throw l}if(typeof i.download_url!="string")throw new ie("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),s;try{s=await a(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw Jr(o.signal,t.signal)?this.timeout("download",r):new ie("download_failed",`${fs} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await Kr(s);throw new ie("download_failed",`the save download answered ${s.status}. `+(s.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await s.arrayBuffer())}catch(i){throw this.rethrow(i,t.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,t={}){try{let r=await qr(this.api,this.entity.type,this.entity.id,xe(e),{...t.signal===void 0?{}:{signal:t.signal},...t.ifNoneMatch===void 0?{}:{ifNoneMatch:t.ifNoneMatch}});return r.modified?zr(r.body):null}catch(r){if(Yr(r))return null;throw r}}async list(e={}){let t=await qa(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(zr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,t){try{await oa(this.api,this.entity.type,this.entity.id,xe(e),{...t===void 0?{}:{signal:t}});}catch(r){if(!Yr(r))throw r}}budget(e){return e??this.options.timeoutMs??iu}timeout(e,t){return new ie("save_timeout",`the save ${e} did not finish within ${t}ms`)}rethrow(e,t,r,o,i){return e instanceof ie?e:Jr(r,t)?this.timeout(o,i):e}};function cu(n){try{return Fr(n)}catch{return n}}function Xr(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"?cu(t.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof t.updated_at=="number"?t.updated_at:0}}var Gn=class{constructor(e,t){this.api=e;this.entity=t;}api;entity;async list(e){let r=(await $a(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>Xr(o)):[]}async get(e,t={}){try{let r=await ua(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?Xr(r.body,r.etag):null}catch(r){if(_s(r))return null;throw r}}async put(e,t,r={}){let o=await Wa(this.api,this.entity.type,this.entity.id,e,{value:$r(t)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Xr(o)}async delete(e,t){try{await ra(this.api,this.entity.type,this.entity.id,e,t===void 0?{}:{signal:t});}catch(r){if(!_s(r))throw r}}};function _s(n){return n?.reason==="not_found"}function Dn(n,e,t={}){let r=new On(ge,t.identity);t.onInventoryChanged&&r.onInvalidate(t.onInventoryChanged);let o=new Pn(n,e,r);return {settings:new Gn(n,e),inventory:o,saves:new Ln(n,e,t.saves??{}),currencies:new An(o,t.resolveCurrencyId),mutations:new Cn(n,e,r),orders:new In(n,e),progressions:new Mn(n,e,o)}}var Qr={type:"players",id:"me"};var Ne=n=>typeof n=="string"?n:"",lt=n=>typeof n=="number"?n:0;function $n(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:lt(t.slot_index),isActive:t.is_active!==false,createdAt:Ne(t.created_at),updatedAt:Ne(t.updated_at)}}var Fn=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=Dn(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 Da(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>$n(this.scope,o)):[]}async get(e,t){let r=await da(this.api,e,t===void 0?{}:{signal:t});return $n(this.scope,r)}async create(e){let t=await Zi(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return $n(this.scope,t)}async update(e,t,r){let o=await Ya(this.api,e,{name:t},r===void 0?{}:{signal:r});return $n(this.scope,o)}async delete(e,t){await Za(this.api,e,t===void 0?{}:{signal:t});}async slots(e){let r=await Ea(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:lt(r?.total_slots),availableSlots:lt(r?.available_slots),activeCharacterCount:lt(r?.active_character_count),defaultMaxSlots:lt(r?.default_max_slots),purchasedExtraSlots:lt(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 Me(n){return new ye(n)}var dt={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 qn(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:Me(t)},createdAt:ct(e.created_at),expiresAt:ct(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function uu(){return crypto.randomUUID()}var jn=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 Ma(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:uu()},e.signal===void 0?{}:{signal:e.signal});return qn(t)}async list(e={}){let r=await Ua(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(qn):[],...o===void 0?{}:{nextCursor:o}}}async get(e,t){let r=await Ta(this.api,e,t===void 0?{}:{signal:t});return qn(r)}async accept(e,t){return this.resolve(()=>Ji(this.api,e,t===void 0?{}:{signal:t}))}async reject(e,t){return this.resolve(()=>za(this.api,e,t===void 0?{}:{signal:t}))}async cancel(e,t){return this.resolve(()=>Yi(this.api,e,t===void 0?{}:{signal:t}))}async resolve(e){return this.inventory.invalidate(),qn(await e())}};var mu=n=>typeof n=="string"?n:"",pu=n=>typeof n=="string"&&n?n:void 0,gu=n=>typeof n=="number"?n:void 0;function vs(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 yu(n){if(typeof n!="object"||n===null||Array.isArray(n))throw new le("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 le("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=gu(e.version);if(r===void 0)throw new le("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let u=mu(l.id);if(!u)throw new le("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 a=t("currencies");a.forEach((l,d)=>o(l??{},"currencies",d));let s=n;return {...s,version:r,hash:typeof s.hash=="string"?s.hash:"",items:i,currencies:a,catalogs:t("catalogs"),loot_tables:t("loot_tables"),affix_pools:t("affix_pools"),progressions:t("progressions"),game_room_templates:t("game_room_templates"),kv:typeof s.kv=="object"&&s.kv!==null&&!Array.isArray(s.kv)?s.kv:{},item:vs(i),currency:vs(a)}}var le=class extends Error{constructor(t,r){super(r);this.reason=t;this.name="GemConfigError";}reason},ws=10*1024*1024,ks=15e3,Ss=new Set(["dev","test","release"]);function hu(n){if(!Ss.has(n))throw new le("config_channel_unknown",`the play token names channel "${n}", which is not one of ${[...Ss].join(", ")}. gem-api would reject the assignment read.`);return n}var Nn=n=>typeof n=="number"?n:0,Zr=n=>typeof n=="string"?n:"";function fu(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:Zr(o.entry_id),weight:Nn(o.weight),dropRate:Nn(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:Zr(e.loot_table_id),name:Zr(e.name),rollCount:Nn(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Nn(e.total_weight),entries:t}}var Un=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 le("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let o=this.dropRatesByConfig.get(r);o===void 0&&(o=new Map,this.dropRatesByConfig.set(r,o));let i=o.get(e);if(i!==void 0)return i;let a=(async()=>{let s=await ca(this.api,e,t===void 0?{}:{signal:t});return fu(s)})().catch(s=>{throw o?.get(e)===a&&o.delete(e),s});return o.set(e,a),a}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??ks),t;try{let l=await la(this.api,hu(this.channel()),{signal:e});if(!l.modified)throw new le("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");t=l.body;}catch(l){if(l instanceof le)throw l;if(l?.reason==="not_found")return null;throw l}let r=pu(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 le("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??ks}ms`):new le("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=>Wr(d)).catch(()=>"");throw new le("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await i.text();if(a.length>ws)throw new le("config_too_large",`the config document is ${a.length} bytes, over the ${ws} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new le("config_malformed",`config document is not JSON: ${String(l)}`)}return yu(s)}};var Rs=400,Ae=n=>typeof n=="string"?n:"",bu=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Ue(n){let e=Ae(n);if(!bu.test(e))return 0;let t=Date.parse(e);return Number.isFinite(t)?Math.floor(t/1e3):0}var _u=/^[0-9a-f]{1,64}$/,vu=/^[0-9a-f]{16}$/,wu=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,ku=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function eo(n){let e=Ae(n),t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return;let[r,o,i]=[Number(t[1]),Number(t[2]),Number(t[3])],a=new Date(Date.UTC(r,o-1,i));return a.getUTCFullYear()===r&&a.getUTCMonth()===o-1&&a.getUTCDate()===i?e:void 0}var Su=4096,Ru=new TextEncoder;function xu(n){let e=Ae(n.challenge_data),t=Ae(n.challenge_data_hash);return e===""||!vu.test(t)?{}:Ru.encode(e).length>Su?{}:{data:e,dataHash:t}}function Au(n){let e=n??{},t=Ue(e.period_start_at),r=Ue(e.period_ends_at);if(t===0||r===0)return;let o=Ae(e.slug),i=Ae(e.seed),a=eo(e.period_local_date),s=Ae(e.boundary),l=Ae(e.reset_time);return {id:Ae(e.progression_definition_id),...o===""?{}:{slug:o},window:Ae(e.window),periodStartAt:t,periodEndsAt:r,...a===void 0?{}:{periodLocalDate:a},boundary:wu.test(s)?s:"",resetTime:ku.test(l)?l:"",seed:_u.test(i)?i:"",...xu(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 Bn(n){let e=n??{};return Array.isArray(e.challenges)?e.challenges.map(Au).filter(t=>t!==void 0):[]}var Ct=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:t}=e;ut(t);let r=await Ga(this.#e,{...t===void 0?{}:{periods_back:t},...e.signal===void 0?{}:{signal:e.signal}});return Bn(r)}};function Be(n){return typeof n=="string"&&n!==""?n:void 0}var xs=new Set(["localhost","127.0.0.1","[::1]"]);function to(n){let e=Be(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:"&&xs.has(t.hostname)))return e}function Pu(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},o=Be(r.item_id),i=to(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function be(n){let e=n??{},t=Be(e.player_id),r=Be(e.display_name),o=Be(e.discriminator),i=Be(e.display_tag),a=Be(e.avatar_icon_id),s=to(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:Me(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:Me(i)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:Pu(e.badges)}}var Eu=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Tu(n){if(n===void 0)return;let e=to(n);if(e===void 0)return;let t=new URL(e);return xs.has(t.hostname)||Eu.has(t.origin)?e:void 0}var As=100,Ts=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function no(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"||!Ts.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 Cs(n){let e=typeof n.period_id=="string"?n.period_id:"";if(!Ts.test(e))return;let t=eo(n.period_local_date),r=Ue(n.period_start_at),o=Ue(n.period_ends_at),i=r>0&&o>0;return {id:e,...t===void 0?{}:{localDate:t},...i?{startAt:r,endsAt:o}:{},opensAt:Ue(n.opens_at),closesAt:Ue(n.closes_at),final:n.final===true}}var It=n=>typeof n=="string"?n:"",mt=n=>typeof n=="number"?n:0,Mt=n=>typeof n=="string"?n:void 0,Cu=n=>typeof n=="number"?n:void 0,Is={player:"players",character:"characters"};function Iu(n,e){let t=n??{},r=Mt(t.entity_id),o=typeof t.entity_type=="string"&&Object.hasOwn(Is,t.entity_type)?t.entity_type:void 0,i=Ms(t.stats),a=t.properties!==null&&typeof t.properties=="object"?t.properties:void 0,s=e?t.is_viewer===true:void 0;return {...be(t),rank:mt(t.rank),occurredAt:mt(t.occurred_at),...s===void 0?{}:{isViewer:s},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...a===void 0?{}:{properties:a}}}function Ps(n,e){let t=n??{},r=Mt(t.bucket_1),o=Mt(t.bucket_2),i=Cu(t.update_frequency_seconds),a=Cs(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(s=>Iu(s,e)):[],generatedAt:mt(t.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...a===void 0?{}:{period:a}}}function Es(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=n;if(!Number.isFinite(e.rank))return;let t=Ms(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 Ms(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 Mu(n,e,t){let r=n??{},o=Mt(r.bucket_1),i=Mt(r.bucket_2),a=Cs(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(Es).filter(s=>s!==void 0):[],personalBest:Es(r.personal_best)??null,totalRuns:mt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:mt(r.generated_at),...a===void 0?{}:{period:a}}}var Ot=class{#e;constructor(e){this.#e=e;}async get(e,t={}){let r=no(t),o=await ka(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 Ps(o,false)}async friends(e,t={}){let r=no(t),o=await _a(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 Ps(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>As)throw new TypeError(`limit must be an integer between 1 and ${As}, got ${String(l)}`)}let i=no(o),a=await ga(this.#e,e,Is[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}}),s=t==="player"&&r==="me"&&It((a??{}).entity_id)||r;return Mu(a,t,s)}};var Vn=n=>typeof n=="string"?n:"",ro=n=>typeof n=="number"?n:0;function Os(n){let e=n??{};return {playerId:Vn(e.player_id),key:Vn(e.key),value:e.value,updatedAt:ro(e.updated_at)}}function Ou(n){let e=n??{};return {...be(e),playerId:Vn(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:ro(e.updated_at)}}function Lu(n){return n?.reason==="not_found"}var Lt=class{constructor(e,t){this.api=e;this.selfPlayerId=t;}api;selfPlayerId;async friends(e,t={}){let o=await va(this.api,xe(e),{...t.signal===void 0?{}:{signal:t.signal}})??{};return {key:Vn(o.key),entries:Array.isArray(o.entries)?o.entries.map(Ou):[],generatedAt:ro(o.generated_at)}}async of(e,t,r={}){try{return Os(await Pa(this.api,e,xe(t),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(Lu(o))return null;throw o}}async set(e,t,r={}){if(xe(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 Os(await Ka(this.api,o,e,{value:t},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,t={}){let r=await this.selfPlayerId();await ia(this.api,r,xe(e),{...t.signal===void 0?{}:{signal:t.signal}});}};var Gu="gemChallenge",Ls=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Gs(n){if(!(typeof n!="string"||n===""))try{return new URLSearchParams(n).get(Gu)??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});}},Hn=n=>typeof n=="string"?n:void 0;function Ds(n){let e=n??{};return {...be(e),playerId:Hn(e.player_id)??""}}function $s(n){let e=n.has_more===true?Hn(n.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function Du(n){let e=n??{};return {friends:Array.isArray(e.data)?e.data.map(Ds):[],...$s(e)}}var oo=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0;function $u(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 Fs(n){let e=n??{},t=oo(e.opened_at),r=oo(e.answered_at);return {id:Hn(e.item_id)??"",from:Ds(e.sender),template:Hn(e.template)??"",params:$u(e.params),createdAt:oo(e.created_at)??0,...t===void 0?{}:{openedAt:t},...r===void 0?{}:{answeredAt:r}}}function Fu(n){let e=n??{};return {challenges:Array.isArray(e.data)?e.data.map(Fs):[],...$s(e)}}function qu(n){let e=n;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Gt=class{#e;#n;#i;constructor(e,t={}){this.#e=e,this.#n=t.challenge,this.#i=t.launchedChallengeId;}async list(e={}){let t=await Na(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Du(t)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let t=await ja(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Fu(t)}async launchedChallenge(e={}){let t=this.#i;if(t===void 0||!Ls.test(t))return null;try{return Fs(await wa(this.#e,t,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(qu(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!Ls.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 Ba(this.#e,e);}};var ju=0;function Pe(){try{return crypto.randomUUID()}catch{let n=Math.random().toString(36).slice(2,10);return `local-${String(++ju)}-${String(Date.now())}-${n}`}}var Nu=12e4,qs=8,Uu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Bu=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Dt(n,e,t={}){return new Ve(new O("invalid",400,e,void 0,n),t)}function Vu(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Hu(n){let{playerId:e,template:t,params:r}=n??{};if(typeof e!="string"||!Uu.test(e))return {error:Dt("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof t!="string"||!Bu.test(t))return {error:Dt("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(!Vu(r))return {error:Dt("param_invalid","params must be a plain object of strings and integers")};let o={},i=Object.keys(r);for(let a of i){let s=r[a];if(typeof s=="string"||typeof s=="number"&&Number.isSafeInteger(s)){Object.defineProperty(o,a,{value:s,enumerable:true,writable:true,configurable:true});continue}return {error:Dt("param_invalid",`params.${a} must be a string or a safe integer`,{param:a})}}return i.length>qs?{error:Dt("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(qs)}`)}:{playerId:e,template:t,params:o}}function Wu(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 Ku(n){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(n.outcome)?n.outcome:"unknown"}function js(n){let e=new Map;return {challenge(t){if(!n.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=Hu(t);if("error"in r)return Promise.reject(r.error);let o=`challenge-${Pe()}`;return new Promise((i,a)=>{let s={},l=m=>{e.delete(o)&&(n.clock.clearTimeout(s.timer),"error"in m?a(m.error):i(m.outcome));};e.set(o,l),s.timer=n.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},n.timeoutMs??Nu);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 (${Ku(t)}) for an unknown requestId: `+JSON.stringify(t.requestId));return}r(Wu(t));}}}var Wn=n=>typeof n=="string"?n:void 0;function Ju(n){let e=n??{},t=Wn(e.currency_id);if(t===void 0||t==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Wn(e.slug)??"",currencyId:t,balance:r,access:e.access==="spend"?"spend":"read"}}var Kn=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await vn(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=Ju(i);a!==void 0&&o.push(a);}return o}},io=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.floor(n):0;function zu(n){let e=n??{},t=Wn(e.currency_id);if(t===void 0||t==="")return;let r=io(e.limit),o=Math.min(io(e.earned),r),i=Math.min(io(e.remaining),r-o),a=e.period_days,s=typeof a=="number"&&Number.isInteger(a)&&a>=1?a:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Wn(e.currency_slug)??"",currencyId:t,limit:r,earned:o,remaining:i,period:e.period==="day"?"day":"window",periodDays:s,...d===void 0?{}:{resetsAt:d}}}function Ns(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 Jn=class{#e;#n;#i;constructor(e,t,r){this.#e=e,this.#n=t,this.#i=r;}async get(e={}){let r=(await Sa(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=zu(i);a!==void 0&&o.push(a);}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)??(()=>{})}},$t=class{currencies;earnAllowance;constructor(e,t,r){this.currencies=new Kn(e),this.earnAllowance=new Jn(e,t,r);}};var ao=n=>typeof n=="string"?n:"",Us=n=>typeof n=="number"?n:0;function Yu(n){let e=n??{};return {key:ao(e.key),visibility:ao(e.visibility),value:e.value,updatedAt:Us(e.updated_at)}}function Xu(n){let e=n??{};return {...be(e),playerId:ao(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Yu):[],generatedAt:Us(e.generated_at)}}function Qu(n){return n?.reason==="not_found"}var Ft=class{#e;constructor(e){this.#e=e;}async of(e,t={}){try{return Xu(await Ra(this.#e,e,{...t.signal===void 0?{}:{signal:t.signal}}))}catch(r){if(Qu(r))return null;throw r}}};var Zu=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]]),zn=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:Zu.get(this.code))??super.retryable}},He=class{#e;constructor(e){this.#e=e;}async invoke(e,t={}){let r=em(e),o;try{o=await this.#e(r,t.signal===void 0?{}:{signal:t.signal});}catch(i){throw i instanceof O?nm(i):i}return tm(o)}};function em(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 tm(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 nm(n){let{details:e,invocationId:t}=Ki(n),o=e?.untrusted?.message,i=e?.reason;return new zn(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 rm=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],so="gem_";function Bs(n){return n.startsWith(so)}var Vs=1e4,Hs=50,om=500,im=65536-4*1024,am=24*1024;function Ws(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 Ks=n=>typeof n=="number"?n:0,sm=n=>typeof n=="string"?n:"";function lo(n=0){return {accepted:0,rejected:[],dropped:n,duplicate:false}}function lm(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(o=>{let i=o??{};return {index:Ks(i.index),code:sm(i.code)}}):[];return {accepted:Ks(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function co(){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 dm(n){return n?.retryable===true}var qt=class{#e;#n;#i;#y;#t=[];#h={};#a=0;#s=null;#f=false;#b=false;#_=false;#r=false;#v=null;#l=null;#d=false;#o=false;#m=false;#w=false;#k=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#i=Math.max(Vs,e.options?.flushIntervalMs??Vs),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??om));}track(e,t={}){if(!(!this.#n||this.#r)){if(Bs(e)){this.#k||(this.#k=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.#S(e,Ws({...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 lo();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.")),lo();if(this.#R(),this.#t.length===0)return lo();let r=e.keepalive===true;this.#u();let o=this.#t.splice(0,this.#A(r)),i=this.#a;this.#a=0;let a=Math.round(this.#e.clock.now()),s={batch_id:co(),sent_at_ms:a,events:o.map(d=>Js(d,a))},l={client:this.#e.client(),gameId:()=>t};this.#_=true;try{let d=await Ia(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=lm(d,i);return this.#P(m),m}catch(d){throw dm(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.#_=false,this.#t.length>0&&this.#c();}}trackPlatform(e,t={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#S(e,Ws(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:co(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Hs?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}#S(e,t){let{dimensions:r,measures:o}=t;for(this.#R();this.#t.length>=this.#y;)this.#t.shift(),this.#a+=1;this.#t.push({uid:co(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=Hs?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?am:im,r=Math.min(this.#t.length,100),o=128;for(let i=0;i<r;i+=1){let a=this.#t[i];if(a===void 0)break;if(o+=JSON.stringify(Js(a,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.#_||(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);}#R(){let e=this.#T();e===null||e===""||(this.#v!==null&&this.#v!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#d=false),this.#v=e);}#P(e){for(let t of e.rejected)this.#g(`[gem] analytics: an event was refused (${t.code}). `+cm(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 cm(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 me(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=me(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var um=2e3,mm=5e3;function Ys(n){let e=[],t=false,r=null,o=new Map,i=()=>{if(e.length>0)return Promise.resolve(e);if(t)return Promise.resolve([]);if(!n.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=u=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(u));},m=n.clock.setTimeout(()=>{t=true,a([]);},n.timeoutMs??um);});return r={promise:s,settle:a},s};return {resolveList:i,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(a=>a[0])},refresh(a){return !zs(e,a)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{o.delete(d)&&(n.clock.clearTimeout(l),s(m));};o.set(d,a),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??mm);})},accept(a,s){let l=jt(s),d=me(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...o])zs(m,p)||u(m);}}}}function zs(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var pm=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=pm.has(t),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var Xs=["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"],gm=new Set(Xs);function pt(n){return typeof n=="string"&&gm.has(n)?n:"unknown"}var Yn="webrtc_dedicated",go=["universal","mobile","web"];var ym="p2p_unavailable",hm="capacity_unavailable",fm=2,Qs=3e4,Zs=1e3,el=2e4;async function yo(n){let e=me(n.clusterTargetId),t=n.nextClusterTarget,r=0,o=n.clock??ge,i=n.retry??{},a=i.budgetMs??Qs,s=i.maxDelayMs??el,l=i.initialDelayMs??Zs,d=o.now(),m=d+a,u=0;for(;;){u++;try{let p=await _o(n.signal,"while allocating",()=>n.client.post(`${rl(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!bm(p)||a<=0)throw p;if(p.status===503&&p.code===ym)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===hm?r+1:0,t!==void 0&&r>=fm){let x=t;t=void 0;let A=me(await x());A!==void 0&&(e=A,r=0);}let g=Math.min(s,l*2**(u-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),k=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+k>m)throw _m(n,p,u,o.now()-d,a);if(i.onWaiting?.({attempt:u,elapsedMs:o.now()-d,budgetMs:a,nextAttemptInMs:k,status:p.status,message:p.message}),await Xn(o,k,n.signal),n.signal?.aborted)throw po("while waiting to allocate")}}}function bm(n){return n instanceof O?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function _m(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 vm=12e4,wm=1e3;async function ho(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??wm,o=n.timeoutMs??vm,i=e.now()+o,a=tl(n),s={seen:n.knownToExist===true};for(;;){let l=await nl(n,a,s);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 Xn(e,r,n.signal);}}async function fo(n){return (await nl(n,tl(n),{seen:n.knownToExist===true})).outcome}function tl(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${rl(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function nl(n,e,t){let{matchId:r}=n,o=n.clock.now(),i;try{i=await _o(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(a){if(a instanceof O&&a.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(t.seen=true,i.status==="ready")return {status:"ready",outcome:km(r,i,o)};if(i.status==="failed"){let a=i.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:pt(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function bo(n){let e=await _o(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 _o(n,e,t){if(n?.aborted)throw po(e);try{return await t()}catch(r){throw n?.aborted?po(e,r):r}}function po(n,e){return new w("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function km(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 rl(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function Xn(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 ol(n){return typeof n=="string"&&n.trim()!==""}function Qn(n,e){return ol(n)?n.trim():ol(e)?e:null}var Zn="0.1.0-beta",il="0-beta",gt="web",Sm=/^(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 Rm(n){let e=Sm.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function al(n,e){let t=xm(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:Zn};let o=Rm(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 '${Zn}' for it.`);if(o!==il)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${il}' 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 '${Zn}' for it.`);return {...n,platform:t,engineVersion:r}}function xm(n,e){if(n===void 0||n===gt)return gt;if(!go.includes(n))throw new w("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${go.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${gt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${gt}' 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.`),gt}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:sl(e.queued_at),expiresAt:sl(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function sl(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var Am=3,ll=1e3,er=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((i,a)=>{this.resolve=i,this.reject=a;});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?ll:Math.max(ll,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<Am){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 Pm="join",Em="welcome",Tm="rejected",dl=25e3,Cm=1e3,vo=1;function wo(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var Im={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 ko(n){let e=typeof n=="string"?n:"unknown";return new w(Im[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,a=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??dl),s=t.setTimeout(()=>b(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(a,Cm)),l=k=>{let x=k.data;if(typeof x!="string"){u(x);return}let A;try{A=JSON.parse(x);}catch{u(x);return}if(i){u(x);return}if(A.t===Em){let _=wo(A.heartbeat_interval);y({...typeof A.player_id=="string"?{playerId:A.player_id}:{},...typeof A.match_id=="string"?{matchId:A.match_id}:{},..._===void 0?{}:{heartbeatIntervalMs:_}});return}if(A.t===Tm){b(ko(A.reason));return}u(x);},d=()=>{b(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{b(new w("aborted","the caller aborted during the join exchange"));},u=k=>{i&&n.onMessage?.(k);},p=()=>{t.clearTimeout(s),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=k=>{i=true,p(),n.onMessage===void 0&&g(),r({welcome:k,detach:g});},b=k=>{i||(i=true,p(),g(),o(k));};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:Pm,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:vo}:{}}));}catch(k){b(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(k)}`,{cause:k}));}})}var We=1,Bt=2,So=4,Ao=8,Mm=2,Om=1e3,Po="heartbeat timeout",Vt="gem-uu",tr=2,ul="gem_transports";function yt(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Lm(r)||e.includes(r)||e.push(r);}return e}function Lm(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function Ht(n,e){if(typeof n!="object"||n===null)return null;let t=n[ul];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 nr(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var ml=new TextEncoder,pl=new TextDecoder;function Eo(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function To(n){let e=0;return n?.reliable===false&&(e|=We),n?.ordered===false&&(e|=Bt),e}function Co(n){return {reliable:(n&We)===0,ordered:(n&Bt)===0}}var Io={reliable:true,ordered:true};function gl(n){return JSON.stringify({t:"join",credential:n,wire:tr,heartbeat:vo})}function yl(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=wo(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"?ko(e.reason):new w("join_refused","the server answered the join out of protocol")}function rr(){return typeof globalThis.WebTransport=="function"&&Mo===null}function or(){return Mo}var Mo=null;var cl="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Gm(n){let e=_n(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 Ro=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 a=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function xo(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 s=globalThis.WebTransport;if(s===void 0)throw new w("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new s(n.url):new s(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Gm(n.certHashBase64)}]});}let r=t,o=s=>{try{r.close();}catch{}throw s},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(Mo=cl,o(new w("connection_failed",`${cl}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new w("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return o(new w("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(xo(So,ml.encode(gl(n.credential))));let u=new Ro,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),a]);if(y.done||y.value===void 0)return o(new w("connection_failed","the control stream closed before the join was answered"));for(let b of u.push(y.value)){g=yl(pl.decode(b.payload));break}}return {link:Dm(r,m,p,u,n.log??(y=>console.warn(y)),fl(g,n.clock)),welcome:g}}catch(s){return o(s)}}function Dm(n,e,t,r,o,i){let a,s,l=false,d=y=>{if(!l){l=true,m.stop();try{n.close();}catch{}s?.(y);}},m=Lo(i,()=>d(Po)),u=(y,b)=>{m.heard(),(y&Ao)===0&&a!==void 0&&((y&So)!==0?a(pl.decode(b),Io):a(b,Co(y)));};(async()=>{try{for(;;){let y=await t.read();if(y.done||y.value===void 0)break;for(let b of r.push(y.value))u(b.flags,b.payload);}}catch{}d("stream closed");})();let p,g;try{let y=n.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let b=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let k=await b.read();if(k.done||k.value===void 0)break;let x=k.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 (${nr(y)}); unreliable sends ride the stream`);}return n.closed.then(y=>d(hl(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,b){if(l)return;if(typeof y=="string"){e.write(xo(So,ml.encode(y))).catch(()=>d("write failed"));return}let k=To(b);if((k&We)!==0&&g!==void 0){let x=Eo(k,y),A=p?.maxDatagramSize;if(A===void 0||x.byteLength<=A){g.write(x).catch(()=>{});return}}e.write(xo(k,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function Oo(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 a=false,s=setTimeout(()=>{a||(a=true,r.close(),i(new w("timeout","websocket did not come up in time")));},e),l=g=>{a||(a=true,clearTimeout(s),r.close(),i(g));},d=()=>{r.send(gl(n.credential));},m=g=>{if(a)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let y;try{y=yl(g.data);}catch(b){l(b);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),o({link:$m(r,fl(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 hl(n){return typeof n=="string"&&n.length>0?n:void 0}function fl(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function Lo(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Om)*Mm,o=t.now(),i=null,a=()=>{i=null;let s=t.now()-o;if(s>=r){e();return}i=t.setTimeout(a,r-s);};return i=t.setTimeout(a,r),{heard:()=>{o=t.now();},stop:()=>{i!==null&&(t.clearTimeout(i),i=null);}}}function $m(n,e){let t,r,o=false,i=s=>{if(!o){o=true,a.stop();try{n.close();}catch{}r?.(s);}},a=Lo(e,()=>i(Po));return n.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){t?.(s.data,Io);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Ao)===0&&t?.(l.slice(1),Co(d));})),n.addEventListener("close",(s=>i(hl(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!o){if(typeof s=="string"){n.send(s);return}n.send(Eo(To(l),s));}},onMessage(s){t=s;},onClose(s){r=s;},close(){i("closed");}}}function Go(n,e,t,r){let o,i,a=false,s=t,l=u=>{if(!a){a=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}i?.(u);}},d=Lo(r,()=>l(Po)),m=(u,p)=>{if(d.heard(),typeof u=="string"){o?.(u,Io);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let y=g[0]??0;(y&Ao)===0&&o?.(g.slice(1),Co(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}`);})),s!==void 0){let u=s;u.addEventListener("message",(p=>m(p.data,We|Bt))),u.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(u,p){if(a)return;if(typeof u=="string"){n.send(u);return}let g=To(p),y=Eo(g,u);if((g&We)!==0&&s!==void 0&&s.readyState==="open"){s.send(y);return}n.send(y);},onMessage(u){o=u;},onClose(u){i=u;},close(){l("closed");}}}function Fo(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let o=Do(r);o!==void 0&&(e[t]=o);}return e}function qo(n){if(Array.isArray(n))return n.map(Fm).filter(e=>!!e)}function Do(n){if($o(n)||Array.isArray(n)&&n.every($o))return n}function $o(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Fm(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Do(e.fixed),r=Do(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},...ht("description",qm(e.description)),...Array.isArray(e.allowed)&&e.allowed.every($o)?{allowed:e.allowed}:{},...ht("min",Kt(e.min)),...ht("max",Kt(e.max)),...ht("minItems",Kt(e.min_items)),...ht("maxItems",Kt(e.max_items)),...ht("maxLength",Kt(e.max_length))}}function qm(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 ht(n,e){return e===void 0?{}:{[n]:e}}function Te(n){let e=n??{},t=Q(e.id)??Q(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(bl):[];return {id:t,gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:Ee(e.max_players)??0,memberCount:Ee(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,..._e("joinCode",Q(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},..._e("roomArgs",Fo(e.room_args)),..._e("roomArgsTemplate",qo(e.room_args_template)),gameChannel:Q(e.game_channel)??"release",..._e("region",Q(e.region)),..._e("clusterTargetId",Q(e.cluster_target_id)),selfHosted:e.self_hosted===true,..._e("matchId",Q(e.match_id)),version:Ee(e.version)??0,..._e("templateId",Q(e.template_id)),roomType:Q(e.game_room_type)??"Standard",..._e("transports",yt(e.transports)??void 0),createdAt:Ee(e.created_at)??0,updatedAt:Ee(e.updated_at)??0,..._e("startedAt",Ee(e.started_at))}}function bl(n){let e=n??{};return {...be(e),playerId:Q(e.player_id)??"",isReady:e.is_ready===true,role:Q(e.role)??"member",joinedAt:Ee(e.joined_at)??0,..._e("groupId",Q(e.group_id)),..._e("platform",Q(e.platform))}}function ir(n){let e=n??{};return {id:Q(e.id)??Q(e.game_room_id)??"",gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:Ee(e.max_players)??0,memberCount:Ee(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Q(e.game_channel)??"release",roomType:Q(e.game_room_type)??"Standard",createdAt:Ee(e.created_at)??0}}function Q(n){return typeof n=="string"&&n.length>0?n:void 0}function Ee(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function _e(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(ir),...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(ir)}))}create(e,t,r){return jm(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(Te)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(Te)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Jt(r)},t.signal).then(Te)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Jt(r)},t.signal).then(Te)}quickJoin(e,t,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...Jt(t)},e.signal).then(Te)}createTicket(e,t,r=[]){return na(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 Ca(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):Xi(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(Te)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(Te)}kick(e,t,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(t)}`,{},r).then(()=>this.get(e,r))}transferHost(e,t,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(t)}`,{},r).then(Te)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}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 jm(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 Nm(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Um=1e3,Bm=3e3,Vm=6e4,Hm=2,_l=new Set(["game_room_closed","game_room_gone"]),Wm=12e4,Km=5e3,Jm=new Set(["invalid_cluster_target","capacity_unavailable"]),zm=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function No(n){return new jo(n)}var jo=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 a=>{let s=await this.afterRefusedClusters(a,i);if(s[0]===void 0||s[0]===i[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(o,"created"),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=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),i=await this.run("quickJoin",async()=>{let a=await t;return o(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||Sl(l,a))throw s;return o(l)})});return this.enter(i,"joined"),this.askForLocalServer(i),i}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Xm(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("queueForMatch",async()=>{let a=await t;return this.api.createTicket(r,this.version("queueForMatch"),a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||Sl(l,a))throw s;return this.api.createTicket(r,this.version("queueForMatch"),l)})}),i=new er({clock:this.options.clock,first:o,heartbeat:a=>this.track(this.api.heartbeatTicket(a)),cancel:(a,s)=>this.track(this.api.cancelTicket(a,s)),seat:a=>this.enterMatchedRoom(a),onSettled:()=>{this.ticketWatch===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 a=await this.askWhyEnded(i,e);this.endMatch(i,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",o),o}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let o=await this.askWhyEnded(r,e);o!==null&&this.endMatch(r,o,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let o=this.takeHint(e),i;try{i=await this.track(this.onceGameIdKnown(()=>fo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(a){return a instanceof O&&a.reason==="not_found"?o??null:(this.reportError("reconcile",a),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.reason}takeHint(e){let t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=pt(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=me(t.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,u)=>yo({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=()=>s(i,[a]).catch(async m=>{if(o!==void 0||!wl(m))throw m;let u=await this.nextCluster([a],true);if(u===void 0)throw m;return s(u,[a,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 ho({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,!_l.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<Um){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(Nm(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(()=>fo({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,!_l.has(o.reason)),this.track(this.reconcile().catch(()=>{}));return}if(o?.status==="failed"){this.abandonReconnect(e.matchId,o.reason),this.settleFailed(o.matchId,o.reason);return}if(o?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(o);let i;try{i=await t.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),i="failed";}if(e.done||this.reconnect!==e)return;if(i==="closed"){this.finishReconnect();return}if(i==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new 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||!Jm.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 ar)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 ar)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??Km}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=Qn(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 al({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return jt(await this.options.resolveClusterTargets());let e=me(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !wl(e)||t.length===0?[]:jt(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=a=>a.find(s=>!e.includes(s)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!t?i:r(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"||!zm.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(s=>[s.playerId,s])),o=new Map(e.members.map(s=>[s.playerId,s])),i=this.playerId();for(let s of o.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!o.has(s)){if(s===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of o){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=Ym(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(o=>{if(!r.signal.aborted)try{this.settleOutcome(o);}catch{}}).catch(o=>{r.signal.aborted||this.reportError("pollMatchStatus",o);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??Wm;return new Promise((o,i)=>{let a=u=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},s=this.emitter.on("matchAllocationStarted",u=>a(()=>o(u))),l=this.emitter.on("matchFailed",(u,p)=>a(()=>i(new w("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>a(()=>i(new w("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>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??Bm}pushedInterval(){return this.options.pushedPollIntervalMs??Vm}pushed(){return this.options.clock.now()-this.lastPushAt<Hm*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 ar=["visibilitychange","focus","pageshow","online"];function Ym(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||vl(n)!==vl(e)}function vl(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function wl(n){return n instanceof O&&n.code==="invalid_cluster_target"}var kl=8;function Xm(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=kl&&n.every(t=>typeof t=="string"&&t.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${kl} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function Sl(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Qm=["p2p","dedicated","unknown"],Uo=["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 o=Zm(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 Zm(n,e,t){let r=Math.floor(t/1e3);return n.filter(o=>Uo.includes(o.type)).slice(0,100).map(o=>{let i=ep(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function ep(n){if(n!==void 0)return Qm.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 o=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:sr(o.credential)??"",hostFingerprint:sr(o.host_fingerprint)??"",hostEpoch:lr(o.host_epoch)??0,expiresAt:(lr(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:sr(d.username)??"",credential:sr(d.credential)??""});}let a=lr(o.expires_at),s=lr(o.ttl_seconds);return {iceServers:i,expiresAt:a!==void 0?a*1e3:Date.now()+(s??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function sr(n){return typeof n=="string"&&n.length>0?n:void 0}function lr(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var tp=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=tp.has(t);}reason;retryable};var Rl=10240,xl=2048,np=new TextEncoder;function Al(n){return np.encode(n).length}function $e(n,e){let t=o=>{throw new w("invalid_sdp",`the ${e} ${o}`)},r=Al(n);r>=Rl&&t(`is ${r} bytes, over the ${Rl} 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=Al(o);i>xl&&t(`has a ${i}-byte line, over the ${xl} limit`);}}function dr(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 cr=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 rp=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function bt(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=ur(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function ur(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 rp.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 Bo=5e3,op=12e4+Bo,ip=1024,ap=6e4,sp=1e4,Pl=64*1024,El=5;function Vo(n){let e=new Map,t=-1/0,r=null,o=(()=>{let s;try{s=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return s.username!==""||s.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:s.href,shown:`${s.protocol}//${s.host}`}})(),i=()=>{let s=n.subtle??globalThis.crypto?.subtle;if(!s)throw new 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 s},a=async()=>{if(!o.ok)throw new G("keys_unavailable",o.reason);let s=n.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await s(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(sp)});}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>Pl)throw new G("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${Pl} 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>El)throw new G("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${El} 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(s){let l=e.get(s);if(l)return l;if(!o.ok)throw new G("keys_unavailable",o.reason);if(r)return await r,e.get(s)??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<ap?null:(t=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??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>=ip){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+op),true}};function Cl(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 Tl(n){try{let e=new TextDecoder().decode(Cl(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function Ho(n,e,t,r,o){let i=D=>{throw new G("peer_unauthenticated",`the peer's join credential is not usable: ${D}`)},a=n.split(".");a.length!==3&&i("it is not a three-part JWT");let[s,l,d]=a,m=Tl(s);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let 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(`${s}.${l}`),b;try{b=Cl(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,b,y)||i("its signature does not verify");let x=Tl(l);x===null&&i("its payload does not decode");let A=x,_=D=>typeof A[D]=="string"?A[D]:"",S=D=>typeof A[D]=="number"&&Number.isFinite(A[D])?A[D]:NaN;_("iss")!==o.issuer&&i("it was issued by someone else"),_("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),_("match_id")!==e.matchId&&i("it is for another match"),_("game_id")!==e.gameId&&i("it is for another game");let C=S("exp")*1e3,T=S("nbf")*1e3;(!Number.isFinite(C)||e.now>C+Bo)&&i("it has expired"),Number.isFinite(T)&&e.now<T-Bo&&i("it is not valid yet");let J=_("role");J!=="host"&&J!=="client"&&i("it names no usable role");let U=S("host_epoch");U!==e.hostEpoch&&i("it names a different host epoch");let H=ur(_("fingerprint"));H===null&&i("its fingerprint claim is malformed"),Qt(H,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let P=ur(_("host_fingerprint"));P===null&&i("its host fingerprint claim is malformed"),Qt(P,e.hostFingerprint)||i("it was issued against a different host certificate");let I=_("jti");I.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(I,e.now)||i("it has already been used");let L=_("sub");return L.length===0&&i("it names no player"),{playerId:L.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:U,role:J,fingerprint:H,hostFingerprint:P,jti:I,expiresAt:C}}function Wo(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 Ko(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 Jo(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function zo(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 Il(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 Ml(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 Yo={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Oe=["reliable","ordered","unreliable"];function Xo(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 Ll=1,mp=3e4,Gl=2e3,pp=5e3,Dl=6e4,gp=8,Zo=class{constructor(e=gp){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;}},yp=new Zo,hp=8,fp=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??Vo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new cr;links=new Map;replays=new Zt;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Ll+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??mp;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),o=me(this.options.clusterTargetId);if(o!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,o,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Qo(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let i=this.options.clock.setTimeout(()=>{this.fail(new 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),a=()=>this.fail(new G("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new 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=ae(e.playerId),r=ae(e.hostPlayerId),o=mr(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,Ll),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");$e(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,o=r===void 0?null:bt(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??yp,a=()=>this.closed||e!==this.credentialGeneration,s=pp;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,u;if(m===409)u=Gl;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=s,s=Math.min(s*2,Dl)),u=Math.min(Math.max(u,Gl),Dl);}else throw d;if(!await this.waitForCredential(u,a))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=ae(e.fromPlayerId),r=ae(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=hp){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=ae(e.sessionId);if(o!==null&&this.answeredSessions.get(t)===o)return;$e(r,"offer"),this.refuseMedia(r,"offer");let i=bt(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 a=this.links.get(t);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(t,this.nextPeerId++);s.remoteFingerprint=i,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new G("invalid_sdp","the browser produced an answer with no SDP");$e(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=ae(e.fromPlayerId),r=ae(e.sdp);if(t===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||t!==this.hostPlayerId)return;$e(r,"answer"),this.refuseMedia(r,"answer");let i=bt(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=ae(e.fromPlayerId),r=ae(e.candidate);if(t===null||r===null)return;let o=this.links.get(t);if(!o)return;let i=ae(e.sdpMid),a=mr(e.sdpMLineIndex)??mr(e.sdpMLineIndexAlt),s={candidate:r,...i===null?{}:{sdpMid:i},...a===null?{}:{sdpMLineIndex:a}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(s);return}await o.connection.addIceCandidate(s);}onPeerLeft(e){let t=ae(e.playerId);if(t===null)return;let r=ae(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=ae(e.hostPlayerId),r=mr(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:t,hostEpoch:r,...ae(e.reason)===null?{}:{reason:ae(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=ae(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=ae(e.code)??"unknown",r=ae(e.message)??"the platform refused a signaling message";this.report_(new G("signaling_failed",`${t}: ${r}`));}openLink(e,t){let o=(this.options.peerConnectionFactory??Xo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Oe){let g=o.createDataChannel(p,Yo[p]);g.binaryType="arraybuffer",i[p]=g;}let a={playerId:e,assignedPeerId:t,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",s),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",u),i.reliable.addEventListener("message",m),a.detachHandshake=()=>{i.reliable.removeEventListener("open",u),i.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),o.removeEventListener("icecandidate",s),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new 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(Wo({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=zo(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(Ml(r.reason),Il(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=bt(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 Ho(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:o,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof G&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Qo(a)),s&&this.fail(a);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Ko({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(Jo(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 Oe)$l(e.channels[o]);$l(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",Qo(e),{cause:e}));}count(e){this.counted||!fp.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(dr(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 ae(n){return typeof n=="string"&&n.length>0?n:null}function mr(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function Qo(n){return n instanceof Error?n.message:String(n)}function $l(n){try{n.close();}catch{}}var bp=100,_p=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??bp)){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??_p));}};function B(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function Fe(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function _t(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Fl(n){return typeof n=="boolean"?n:void 0}var he=B(64),an=Fe(0,2147483647);function ei(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=he(t);typeof r=="string"&&e.push(r);}return e}function z(n,e,t){return {to:n,from:e,read:t,required:true}}function V(n,e,t){return {to:n,from:e,read:t,required:false}}var kp=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=_t("disconnected","failed","closed")(e.iceState),r=Fe(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:[z("sdp","sdp",B(10240)),z("signaling_intent","intent",_t("initial","ice_restart","full_reconnect")),V("sdp_hash","sdpHash",B(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[z("peer_id","peerId",he),z("sdp","sdp",B(10240)),z("assigned_peer_id","assignedPeerId",Fe(0,4294967295)),V("sdp_hash","sdpHash",B(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[z("peer_id","peerId",he),z("candidate","candidate",B(512)),V("sdp_mid","sdpMid",B(64)),V("sdp_mline_index","sdpMLineIndex",Fe(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[z("host_epoch","hostEpoch",an)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[z("host_epoch","hostEpoch",an),V("evidence","evidence",kp)]}}));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:[z("playerId","player_id",he),z("hostPlayerId","host_player_id",he),z("hostEpoch","host_epoch",an),V("members","members",ei)],offer:[z("fromPlayerId","from_player_id",he),z("sdp","sdp",B(10240)),V("sessionId","signaling_session_id",B(128)),V("sdpHash","sdp_hash",B(128)),V("iceUfrag","ice_ufrag",B(64)),V("intent","signaling_intent",_t("initial","ice_restart","full_reconnect"))],answer:[z("fromPlayerId","from_player_id",he),z("sdp","sdp",B(10240)),V("sessionId","signaling_session_id",B(128)),V("sdpHash","sdp_hash",B(128)),V("iceUfrag","ice_ufrag",B(64)),V("assignedPeerId","assigned_peer_id",Fe(0,4294967295))],ice:[z("fromPlayerId","from_player_id",he),z("candidate","candidate",B(512)),V("sdpMid","sdp_mid",B(64)),V("sdpMLineIndex","sdp_m_line_index",Fe(0,255)),V("sdpMLineIndexAlt","sdp_mline_index",Fe(0,255))],peerJoined:[z("playerId","player_id",he)],peerLeft:[z("playerId","player_id",he),V("reason","reason",B(64))],migration:[z("hostPlayerId","new_host_player_id",he),z("hostEpoch","host_epoch",an),V("reason","reason",B(64)),V("kickedPlayerIds","kicked_player_ids",ei),V("migrationComplete","migration_complete",Fl)],matchEnded:[V("reason","reason",B(64))],error:[V("code","code",B(64)),V("message","message",B(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 jl(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=me(r.clusterTargetId),i=o??me(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...o===void 0?{}:{clusterTargetId:o},...r.signal===void 0?{}:{signal:r.signal}});let a=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==ze)throw new G("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${ze}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new on({bridge:n.bridge,matchId:a.matchId,clock:n.clock}),l=new rn({api:e,clock:n.clock,matchId:a.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await tn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(a.matchId,l),l.on("matchEnded",()=>t.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(a.matchId),l.close(),d}return l}}}function Nl(n){let{analytics:e,rooms:t}=n,r=n.target??globalThis,o=n.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let s=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",s),i.push(()=>r.removeEventListener?.("pagehide",s));let l=()=>e.setHidden(!Ke());for(let d of ar)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 a=new Map;return i.push(t.on("matchReady",s=>{let l=s.protocol===ze?"p2p":"dedicated";a.set(s.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(t.on("matchEnded",s=>{let l=a.get(s.matchId);l!==void 0&&(a.delete(s.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let s of i.splice(0))try{s();}catch{}a.clear();}}var Ul=["pointerdown","keydown"];function Bl(n,e=globalThis){let t=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},a=()=>{if(!r){r=true,i();for(let g of Ul)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},s=()=>{if(!(t||r)){t=true,a();try{n();}catch{}}};function l(g){g?.isTrusted===true&&s();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(b=>b.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(o=null,!(t||r)){if(d()){s();return}m()&&(o=e.requestAnimationFrame?.(u)??null);}};function p(){o===null&&!t&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of Ul)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:a}}async function pr(n,e,t,r){let o=await t;return n.mark(e)&&r&&r(`[gem] boot: ${n.timeline()}`),o}function ti(n,e){let t=false;return async r=>{let o=await r;return !t&&e&&(t=true,e(`[gem] boot: ${n.timeline()}`)),o}}function ni(n={}){let e=n.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),t=[],r=new Set;return {marks:t,mark(o,i){return r.has(o)?false:(r.add(o),t.push({name:o,at:i??e()}),true)},timeline(){let o=[...t].sort((i,a)=>i.at-a.at);return o.map((i,a)=>{let s=o[a-1],l=s===void 0?"":` (+${Math.round(i.at-s.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var Sp="GemWebSdkHandshake";var Rp=()=>Date.now();function Vl(n,e,t={}){let r=n[Sp];if(r===void 0)return null;let o=t.ttlMs??9500,i=t.now??Rp,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,u=i()-o;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var ri=false;async function Jl(n,e,t,r){if(ri){e.close(),t("busy",true);return}ri=true;let o=null;try{let i=await Ap(n,r);if(typeof i=="string"){e.close(),t(i,xp(i));return}o=i;let s=await(r.encodeRef??(l=>Cp(l,r)))(o);if(o.close(),o=null,s===null){e.close(),t("failed",!0);return}if(s.size>Tp){e.close(),t("too_large",!1);return}e.postMessage(s);}catch(i){e.close(),t("failed",true),console.error("[gem] screenshot capture failed",i);}finally{ri=false,o?.close();}}function xp(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 Ap(n,e){if(e.handler){let i=await e.handler(n);return i===null?"declined":Hl(i,n)}if(!e.useDefaultStrategy)return "not_wired";let t=e.documentRef??globalThis.document;if(!t)return "no_source";let r=Ep(t);if(!r)return "no_source";let o=Pp(r);if(o!==null)return o;try{return Hl(await createImageBitmap(r),n)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function Pp(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 Ep(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 Hl(n,e){let{maxWidth:t,maxHeight:r}=e;if(n.width<=t&&n.height<=r)return n;let o=Math.min(t/n.width,r/n.height),i=Math.max(1,Math.floor(n.width*o)),a=Math.max(1,Math.floor(n.height*o));try{let s=await createImageBitmap(n,{resizeWidth:i,resizeHeight:a,resizeQuality:"high"});return n.close(),s}catch{return n.close(),"too_large"}}var Tp=8*1024*1024,Wl="image/webp",Kl=.92;async function Cp(n,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(n.width,n.height),a=i.getContext("2d");if(a){a.drawImage(n,0,0);let s=await i.convertToBlob({type:Wl,quality:Kl});if(s&&s.size>0)return s}}}catch{}let t=e.documentRef??globalThis.document;if(!t)return null;let r=t.createElement("canvas");r.width=n.width,r.height=n.height;let o=r.getContext("2d");return !o||(o.drawImage(n,0,0),typeof r.toBlob!="function")?null:await new Promise(i=>{r.toBlob(a=>i(a),Wl,Kl);})}async function zl(n,e){if(!e)return;let t;try{t=await Ip(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 Ip(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 Yl=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Xl(n=globalThis){let t=n[Yl];if(t!==void 0)return t;let r=false,o=()=>r,i=[],a=Mp(n,o);a!==null&&i.push(a);let s=Op(n,o);s!==null&&i.push(s);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let u of i)u();}}};return Object.defineProperty(n,Yl,{value:l,configurable:true}),l}function Mp(n,e){let t=n.AudioNode?.prototype,r=n.AudioDestinationNode;if(t===void 0||r===void 0)return null;let o=n.OfflineAudioContext,i=t.connect,a=t.disconnect,s=new Map,l=m=>{let 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=s.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,i.call(p,m),s.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=s.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...g)}catch{}}return a.apply(this,u)},()=>{for(let[m,u]of s){if(m.state==="closed"){s.delete(m);continue}try{l(u);}catch{}}}}function Op(n,e){let t=n.HTMLMediaElement;if(t===void 0)return null;let r=t.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,a=o?.set;if(i===void 0||a===void 0)return null;let s=r.play,l=new WeakMap,d=new WeakSet,m=new Set,u=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),a.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),u(this);}}),r.play=function(){try{u(this);}catch{}return s.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{a.call(g,(l.get(g)??!1)||e());}catch{}}}}var Lp=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Gp=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Dp=`${Lp}${Gp}`,oi=new WeakSet;function Ql(n=globalThis.document){if(n==null||oi.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(Dp),n.adoptedStyleSheets=[...n.adoptedStyleSheets,r],oi.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"),oi.add(n),"inline")}catch{return null}}function Zl(n){let e=n.windowMs??1e3,t=n.realm??globalThis,r=false,o=false,i=false,a=null,s=null,l=null,d=[],m=()=>r&&!o&&!i,u=()=>{s=null,l=null,d=[];},p=b=>{if(a=null,!m()){u();return}if(l!==null&&d.push(b-l),l=b,s===null)s=b;else {let k=b-s;k>=e&&d.length>0&&(n.report($p(d,k)),s=b,d=[]);}g();},g=()=>{let b=t.requestAnimationFrame;typeof b=="function"&&(a=b.call(t,p));},y=()=>{if(m()){a===null&&(u(),g());return}a!==null&&(t.cancelAnimationFrame?.call(t,a),a=null),u();};return {setRequested(b){r=b,y();},setPaused(b){o=b,y();},get running(){return a!==null},dispose(){i=true,y();}}}function $p(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 gr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function td(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function nd(n,e){n!==null&&(n.style.setProperty(gr.top,`${e.top}px`),n.style.setProperty(gr.right,`${e.right}px`),n.style.setProperty(gr.bottom,`${e.bottom}px`),n.style.setProperty(gr.left,`${e.left}px`));}var ed=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 rd(){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 Fp(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,a=o?r.x+r.width:e?e.width-r.x:r.width,s=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(a)),l.height=Math.max(l.height,Math.ceil(s));}return t}function od(n,e,t){if(n===null)return;let r=Fp(e,t);for(let o of ["tl","tr","bl","br"])n.style.setProperty(ed[o].width,`${r[o].width}px`),n.style.setProperty(ed[o].height,`${r[o].height}px`);}var qp=3e4,yr=class extends Error{retryable;reason;constructor(e,t,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=t;}};function id(n){let e=n.clock??ge,t=n.timeoutMs??qp,r=new Map,o=new Map,i=0,a=s=>{let l=r.get(s);return l?(r.delete(s),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return n.bridge.parentSupports("localHost")},ensure(s){if(!n.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(s);if(l)return l;let d=new Promise((m,u)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(s),u(new yr("timeout",true,`the embedder did not answer a local-server request for room ${s} within ${String(t)}ms`));},t);r.set(p,{room:s,resolve:m,reject:u,timer:g}),n.bridge.requestLocalServer(p,s)||(a(p),m());});return o.set(s,d),d.catch(()=>{}),d},accept(s){a(s.requestId)?.resolve();},refuse(s){let l=a(s.requestId);l&&l.reject(new yr(s.reason,s.retryable,s.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var sn={url:"https://downloads.indiegems.games/sdk/v10.4.0/gem-web-sdk.devtools.min.js",integrity:"sha384-2/iBkR02Syzm8MshMfniIJTC0/r4qCQMbAHSatSyxHF4WMBKV6VsLXoDBe/HX3BI"};var wt=null;function jp(){return wt!==null||(wt=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){wt=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=()=>{wt=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);})),wt}function ad(n,e){let t=null,r=0;async function o(i){if(t!==null)return true;let a=++r;if(!e())return false;let s=await jp();return !e()||a!==r?false:(t!==null||(t=s.mount(n(),{openedBy:i,text:dt,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 Np=1e4,sd={reason:"unavailable",retryable:false};function ld(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??Np);},a=(d,m)=>{let u=s(d);u&&m(u);},s=d=>{let m=e.get(d);return m?(e.delete(d),n.clock.clearTimeout(m.timer),m):null},l=new it({clock:n.clock,onStateChange:n.onStateChange,request:d=>new Promise((m,u)=>{let p=n.bridge.currentState;if(p==="refused"||p==="closed"){u(sd);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)){a(d.requestId,u=>u.resolve(m));return}l.accept(m);},onDenied(d){a(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,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()])a(m,u=>u.reject(sd));},get identity(){return t},get gameVersion(){return r}}}function Up(n){let e=n.lastIndexOf("@");return (e===-1?n:`***@${n.slice(e+1)}`).slice(0,200)}var Bp=new Set(Dr);function Vp(n){if(!n)return {};let e={};for(let[t,r]of Object.entries(n))Bp.has(t.toLowerCase())&&(e[t.toLowerCase()]=r);return e}function hr(n){let e=n.fetch??globalThis.fetch.bind(globalThis);return Vi(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"?Up(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,b=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new oe(`the ${b} puts credentials in the URL, which cannot be fetched (${t.method} ${i.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(n.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,y);let a=t.bytes,s=t.bytes===void 0?void 0:"application/octet-stream";try{t.body!==void 0&&(a=JSON.stringify(t.body),s="application/json");}catch(g){throw new 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}`,...s===void 0?{}:{"content-type":s},...Vp(t.headers)},body:a,signal:t.signal,...t.keepalive===void 0?{}:{keepalive:t.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(t.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),u=Hp(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 Hp(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 Wp=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),ai="embedder_relay_unavailable",Kp="embedder_no_relay",Jp=new Set([ai]),si=new Set([Kp]),ln=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new ii(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(zp(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 zp(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new w(Yp(n),r,{platformCode:n})}function Yp(n){return n===void 0||Jp.has(n)?"signaling_failed":si.has(n)?"offer_refused":Wp.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var ii=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 a=()=>{s(),i(new w("aborted","the caller aborted the signaling exchange"));},s=()=>{t?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),o(d);},refuse:d=>{s(),i(d);}};this.teardown=s,t?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof 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 dd="match_ended:",cd="server_shutdown:",ud="kicked:",Xp=123;function Qp(n){if(typeof n!="string"||n.length===0||n.length>Xp)return {kind:"other"};if(n.startsWith(dd)){let e=pt(n.slice(dd.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(cd)?{kind:"server_shutdown",cause:n.slice(cd.length)}:n.startsWith(ud)?{kind:"kicked",detail:n.slice(ud.length)}:{kind:"other"}}function li(n,e,t){let r=Qp(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 di(){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 Zp=3e3,eg=1e4,tg=15e3;async function fr(n){let e=n.peerConnection;try{pd(n,"before the handshake started"),ci(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let a of n.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});n.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await og(e,n),ci(n);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new w("invalid_sdp","the offer carried no SDP");$e(o,"offer"),md(o,"offer");let i=await rg(n,o);if(ci(n),typeof i?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return $e(i.sdp,"answer"),md(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await ig(t,n),pd(n,"before the channel opened"),t}catch(t){throw e.close(),ng(t)}}function ng(n){return n instanceof w?n:hd(n)?Ye():new w("connection_failed",fd(n),{cause:n})}function md(n,e){if(dr(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 rg(n,e){let t=n.exchangeTimeoutMs??eg,r=yd(n,t),o=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(i=>{throw i instanceof w?i:hd(i)?Ye():new w("signaling_failed",fd(i),{cause:i})});return ag(o,n,r,()=>r.exhausted?ui("while the offer was in flight"):new w("timeout",`no answer arrived within ${t}ms`))}function og(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let o=()=>{t.clearTimeout(a),n.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{n.iceGatheringState==="complete"&&o();},a=t.setTimeout(o,e.gatherTimeoutMs??Zp);n.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function ig(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??tg,o=yd(e,r);return new Promise((i,a)=>{let s=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),i();},d=g=>{s(),a(new w("connection_failed","the data channel failed before it opened",gd(g)===void 0?void 0:{cause:gd(g)}));},m=()=>{s(),a(Ye());},u=()=>{s(),a(o.exhausted?ui("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 yd(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 ag(n,e,t,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(Ye()):new Promise((a,s)=>{let l=u=>{o.clearTimeout(m),i?.removeEventListener("abort",d),u();},d=()=>l(()=>s(Ye())),m=o.setTimeout(()=>l(()=>s(r())),t.ms);i?.addEventListener("abort",d),n.then(u=>l(()=>a(u)),u=>l(()=>s(u)));})}function pd(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw ui(`already ${e}`)}function ui(n){return new w("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function ci(n){if(n.signal?.aborted)throw Ye()}function Ye(){return new w("aborted","the caller aborted the connection attempt")}function hd(n){return n?.name==="AbortError"}function gd(n){return n?.error}function fd(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:[z("sdp","sdp",B(10240)),V("sessionId","session_id",B(64))],error:[V("code","code",B(64)),V("message","message",B(256))],matchEnded:[V("reason","reason",B(64))]}));function xd(n){let{client:e,clock:t,rooms:r}=n,o=n.signaling??di,i=n.log??(_=>console.warn(_)),a=new ft({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(_,S)=>{let C=s.get(_)??new Set;C.add(S),s.set(_,C);},d=(_,S)=>{let C=s.get(_);C!==void 0&&(C.delete(S),C.size===0&&s.delete(_));},m=async _=>{if(r.isHost&&!pi(r)&&r.currentRoom?.matchId===void 0){let S=me(_.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},..._.retry===void 0?{}:{retry:_.retry},..._.signal===void 0?{}:{signal:_.signal}});}return Sd(r.matchConnectionState==="suspended"?await r.reconnectToMatch(mi(_)):await r.awaitMatch(mi(_)))},u=async _=>Sd(await r.pollMatchStatus(mi(_))),p=async(_,S)=>{let C=false;try{let T=await m(_),J=r.currentRoom?.transports;if(J!==void 0&&!J.includes("webrtc"))throw new w("misconfigured",`the room template offers (${J.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 U=_.peerConnection??Rd();C=!0;let H=await fr({peerConnection:U,signaling:S,clock:t,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...br(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),P=null;if(_.presentCredential!==!1)try{P=await Ut({channel:H,clock:t,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...br(_,"onMessage","signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(I){throw ve(H),ve(U),I}return yg(r,T,H,U,S,_.reportDisconnect!==!1,_.reportConnected!==!1,P,{remember:l,forget:d},_.onMatchEnded)}catch(T){throw C&&kd(a,T),ve(S),T}},g=async(_,S,C,T,J,U)=>{if(_==="webtransport"){let j=T?.webtransport;if(j===void 0)throw new w("misconfigured","webtransport is not advertised");let W={credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:t};if(typeof j.named_url=="string"&&j.named_url!==""){let Y=Math.max(Math.floor(U/2),1e3);try{return await Wt({url:j.named_url,timeoutMs:Y,log:i,...W})}catch(de){if(or()!==null)throw de;return i(`[gem] webtransport named dial failed (${nr(de)}); retrying the pinned dial`),Wt({url:j.url,certHashBase64:j.cert_sha256_b64,timeoutMs:Y,log:i,...W})}}return Wt({url:j.url,certHashBase64:j.cert_sha256_b64,timeoutMs:U,...W})}if(_==="websocket"){let j=T?.websocket;if(j===void 0)throw new w("misconfigured","websocket is not advertised");return Oo({url:j.url,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:t,timeoutMs:U})}let H=S.peerConnection??Rd(),P,I=await fr({peerConnection:H,signaling:J,clock:t,matchId:C.matchId,credentialExpiresAt:C.credentialExpiresAt,extraChannels:[{label:Vt,ordered:false,maxRetransmits:0}],onExtraChannel:(j,W)=>{j===Vt&&(P=W);},...br(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:dg}:{}}),L;try{L=await Ut({channel:I,clock:t,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,wire:tr,heartbeat:!0,...br(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(j){throw ve(I),ve(H),j}let D=L.welcome.heartbeatIntervalMs;return {link:Go(I,H,P,D===void 0?void 0:{clock:t,intervalMs:D}),welcome:L.welcome,channel:I,peerConnection:H}},y=(_,S,C,T,J)=>{let U=false,H;T.link.onClose(D=>{!U&&_.reportDisconnect!==false&&li(r,S.matchId,D),H?.(D);}),_.reportDisconnect!==false&&_.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let P={transport:T.link.transport,send:(D,j)=>T.link.send(D,j),onMessage:D=>T.link.onMessage(D),onClose:D=>{H=D;},close:()=>T.link.close()},I=()=>{U||(U=true,ve(T.link),ve(J));},L=D=>{if(!U){try{_.onMatchEnded?.(D);}catch{}I();}};return l(S.matchId,L),{matchId:S.matchId,transport:C,link:P,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(S.matchId,L),I();}}},b=async(_,S)=>{let C=r.currentRoom?.id,T=r.gameId,J=()=>({advert:Ht(r.currentRoom?.settings,_),template:r.currentRoom?.transports??null});if(C===void 0||T===null)return J();try{let U=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(C)}`,S);return {advert:Ht(U.settings,_),template:yt(U.transports)??r.currentRoom?.transports??null}}catch{return J()}},k=(_,S)=>{let C=_??bd;return S.length===0?C:C.filter(T=>S.includes(T))},x=async(_,S,C)=>{try{let T=await m(_),{advert:J,template:U}=await b(T.matchId,_.signal),H=k(U,S),P=H.filter(X=>mg(X,J)),I=or();if(I!==null&&H.includes("webtransport")&&J?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${I} (learned on an earlier dial in this page)`),P.length===0){let X=U===null?`the default order (${bd.join(", ")})`:`the room template's transports (${U.join(", ")||"none"})`;throw new w("misconfigured",`none of ${X}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let L=_.transportAttemptTimeoutMs??lg,D=()=>_.deadlineAt===void 0?1/0:_.deadlineAt-t.now(),j=X=>n.signalingReady===void 0||X<=0?Promise.resolve(!0):n.signalingReady(X),W=[],Y=[];for(let X of P){if(D()<vd){i(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}Y.length>0&&T.credentialExpiresAt-t.now()<wd&&(T=await u(_)),Y.push(X);let Le=!1,we=!1,ke={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&_.redial===!0){let Z=Math.min(_d,D());await j(Z)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Z)}ms; offering anyway`);}let Ge=Math.max(Math.min(L,D()),vd);try{return y(_,T,X,await g(X,_,T,J,C,Ge),C)}catch(Z){let K=Z instanceof w?Z:new w("connection_failed",Z instanceof Error?Z.message:String(Z),{cause:Z});if(X==="webrtc"&&kd(a,K),(K.reason==="credential_expired"||K.reason==="credential_reused")&&!Le){Le=!0,T=await u(_);continue}if(X==="webrtc"&&K.reason==="signaling_failed"&&K.platformCode===ai&&!we){we=!0;let ce=Math.min(_d,D());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ce)}ms for the socket before offering again`),await j(ce))continue}if(K.reason==="join_rate_limited"){let ce=ug(ke,Math.random,D());if(ce!==null){if(ke.attempts+=1,ke.waitedMs+=ce,i(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ce)}ms before presenting again (retry ${ke.attempts} of ${Pd.maxAttempts})`),await Xn(t,ce,_.signal),_.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-t.now()<wd&&(T=await u(_));continue}}if(cg.has(K.reason)||K.reason==="credential_expired"||X==="webrtc"&&Ad(K)){i(`[gem] ${X} rung failed (${K.reason}): ${nr(K.cause??K)} \u2014 `+(Y.length<P.length?`falling through to ${P[Y.length]}`:"no rungs left")),W.push(K);break}throw i(`[gem] ${X} rung refused the session (${K.reason}): ${K.message}`),K}}}let de=W[W.length-1];throw de===void 0?new w("timeout",`the reconnect budget ran out before any transport (${P.join(", ")}) could be tried`):new w(de.reason,`every transport tried (${Y.join(", ")}) failed; the last said: ${de.message}`,{cause:W,platformCode:de.platformCode})}catch(T){throw ve(C),T}};return {listClusterTargets:async(_={})=>bo({client:e,..._}),handleMatchEnded(_,S){let C=s.get(_);if(C!==void 0){s.delete(_);for(let T of C)T(S);}},connect:(async(_={})=>{let S=_.signaling??o();return _.transports===void 0?p(_,S):x(_,_.transports,S)})}}var bd=["webtransport","webrtc","websocket"],lg=1e4,dg=5e3,_d=3e3,vd=1e3,wd=1e4,cg=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Ad(n){return n.platformCode!==void 0&&si.has(n.platformCode)}var Pd={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function ug(n,e=Math.random,t=1/0){let r=Pd;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 mg(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&rr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||pg(e.websocket.url)}function pg(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return xn(e)}function mi(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var gg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function kd(n,e){e instanceof w&&(!gg.has(e.reason)&&!Ad(e)||n.report([{type:"connection_failures_total",value:1}]));}function yg(n,e,t,r,o,i,a,s,l,d){let m=false,u=()=>{m||li(n,e.matchId,void 0);};i&&(t.addEventListener("close",u),a&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",u),s?.detach(),ve(t),ve(r),ve(o));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function pi(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Sd(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!==Yn)throw new w("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${Yn}' 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 Rd(){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 ve(n){try{n.close();}catch{}}function br(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var hg=1e4;function Ed(n,e){if(typeof n.serverToken!="function"||typeof n.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let t=a=>({token:a.token,expiresAt:a.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new it({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((a,s)=>{let l=e.clock.setTimeout(()=>{r=null,s({reason:"unavailable",retryable:true});},e.timeoutMs??hg);r={resolve:d=>{e.clock.clearTimeout(l),a(d);},reject:s,timer:l};})}),i=n.onServerToken(a=>{let s=t(a),l=r;if(l){r=null,l.resolve(s);return}o.accept(s);});return {source:o,dispose(){i(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var yi={};_c(yi,{acceptTransfer:()=>fg,addEntityProgression:()=>bg,adminAction:()=>_g,cancelInventoryTransfer:()=>vg,claimEntityProgressionRewards:()=>wg,closeGameRoom:()=>kg,createEntityBatchOrder:()=>Sg,createEntityOrder:()=>Rg,createSession:()=>xg,deleteEntityGameSetting:()=>Ag,deleteEntitySave:()=>Pg,deleteSession:()=>Eg,deleteShowcaseValue:()=>Tg,executeEntityRecipe:()=>Cg,finalizeSaveUpload:()=>Ig,getChannelAssignment:()=>Mg,getDropRates:()=>Og,getEntityCurrency:()=>Lg,getEntityGameSetting:()=>Gg,getEntityInventory:()=>Dg,getEntityInventoryItem:()=>$g,getEntityLeaderboard:()=>Fg,getEntityOrder:()=>qg,getEntityProgression:()=>jg,getEntityRecipeAvailability:()=>Ng,getEntityRecipeUsage:()=>Ug,getEntitySave:()=>Bg,getEvent:()=>Vg,getGameRoomV2:()=>Hg,getLeaderboard:()=>Wg,getPlayerGameProfile:()=>Kg,getPurchaseCatalog:()=>Jg,getResolvedTemplate:()=>zg,getRoomArgs:()=>Yg,getShowcaseValue:()=>Xg,getTransferDetails:()=>Qg,ingestAnalyticsEvents:()=>gi,initiateInventoryTransfer:()=>Zg,invokeFunction:()=>ey,kickPlayer:()=>ty,listChallenges:()=>ny,listEntityGameSettings:()=>ry,listEntityOrders:()=>oy,listEntityProgressions:()=>iy,listEntitySaves:()=>ay,listEvents:()=>sy,listGameRooms:()=>ly,listResolvedTemplates:()=>dy,listTransfers:()=>cy,maxEntityProgression:()=>uy,putEntityGameSetting:()=>my,putRoomArgs:()=>py,putShowcaseValue:()=>gy,rejectTransfer:()=>yy,reportMatchPlayers:()=>hy,requestSaveUploadUrl:()=>fy,resetEntityProgression:()=>by,setMatchBackfill:()=>_y,simulateEntityOrder:()=>vy,transferHostV2:()=>wy,updateGameRoomV2:()=>ky});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 fg(n,e,t){let r=`/v1/inventory/transfers/${f(e)}/accept`;return n.client.post(r,void 0,t?.signal)}async function bg(n,e,t,r,o,i){let a=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/add`;return n.client.post(a,o,i?.signal)}async function _g(n,e,t,r){let o=`/v1/voice/sessions/${f(e)}/admin`;return n.client.post(o,t,r?.signal)}async function vg(n,e,t){let r=`/v1/inventory/transfers/${f(e)}/cancel`;return n.client.post(r,void 0,t?.signal)}async function wg(n,e,t,r,o,i){let a=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/claim`;return n.client.post(a,o,i?.signal)}async function kg(n,e,t){let r=`/v1/games/${f(n.gameId())}/game-rooms/${f(e)}`;return n.client.delete(r,t?.signal)}async function Sg(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 Rg(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 xg(n,e,t){return n.client.post("/v1/voice/sessions",e,t?.signal)}async function Ag(n,e,t,r,o){let i=`/v1/settings/${f(e)}/${f(t)}/${f(r)}`;return n.client.delete(i,o?.signal)}async function Pg(n,e,t,r,o){let i=`/v1/saves/${f(e)}/${f(t)}/${f(r)}`;return n.client.delete(i,o?.signal)}async function Eg(n,e,t){let r=`/v1/voice/sessions/${f(e)}`;return n.client.delete(r,t?.signal)}async function Tg(n,e,t,r){let o=`/v1/showcase/players/${f(e)}/${f(t)}`;return n.client.delete(o,r?.signal)}async function Cg(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 Ig(n,e,t,r,o,i){let a=`/v1/saves/${f(e)}/${f(t)}/${f(r)}/finalize`;return n.client.post(a,o,i?.signal)}async function Mg(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 Og(n,e,t){let r=`/v1/inventory/loot-tables/${f(e)}/drop-rates`;return n.client.get(r,t?.signal)}async function Lg(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 Gg(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 Dg(n,e,t,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${f(e)}/${f(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function $g(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 Fg(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 a=i.toString(),s=`/v1/leaderboards/${f(e)}/${f(t)}/${f(r)}`+(a?`?${a}`:"");return n.client.get(s,o?.signal)}async function qg(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 jg(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 Ng(n,e,t,r,o,i){let a=`/v1/inventory/${f(e)}/${f(t)}/catalogs/${f(r)}/recipes/${f(o)}/availability`;return n.client.get(a,i?.signal)}async function Ug(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${f(e)}/${f(t)}/recipe-usage`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function Bg(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 Vg(n,e,t){let r=`/v1/events/${f(e)}`;return n.client.get(r,t?.signal)}async function Hg(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 Wg(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 Kg(n,e,t){let r=`/v1/profiles/players/${f(e)}`;return n.client.get(r,t?.signal)}async function Jg(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 zg(n,e,t){let r=`/v1/game-room-templates/${f(e)}`;return n.client.get(r,t?.signal)}async function Yg(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 Xg(n,e,t,r){let o=`/v1/showcase/players/${f(e)}/${f(t)}`;return n.client.get(o,r?.signal)}async function Qg(n,e,t){let r=`/v1/inventory/transfers/${f(e)}`;return n.client.get(r,t?.signal)}async function gi(n,e,t){let r=`/v1/games/${f(n.gameId())}/analytics/events`;return n.client.post(r,e,t?.signal,{replaySafe:true})}async function Zg(n,e,t){return n.client.post("/v1/inventory/transfers",e,t?.signal)}async function ey(n,e,t){return n.client.postBytes("/v1/functions/invoke",e,t?.signal)}async function ty(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 ny(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 ry(n,e,t,r){let o=`/v1/settings/${f(e)}/${f(t)}`;return n.client.get(o,r?.signal)}async function oy(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${f(e)}/${f(t)}/orders`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function iy(n,e,t,r){let o=`/v1/inventory/${f(e)}/${f(t)}/progressions`;return n.client.get(o,r?.signal)}async function ay(n,e,t,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${f(e)}/${f(t)}`+(i?`?${i}`:"");return n.client.get(a,r?.signal)}async function sy(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 ly(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 dy(n,e){return n.client.get("/v1/game-room-templates",e?.signal)}async function cy(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 uy(n,e,t,r,o,i){let a=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/max`;return n.client.post(a,o,i?.signal)}async function my(n,e,t,r,o,i){let a=`/v1/settings/${f(e)}/${f(t)}/${f(r)}`;return n.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function py(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 gy(n,e,t,r,o){let i=`/v1/showcase/players/${f(e)}/${f(t)}`;return n.client.put(i,r,o?.signal)}async function yy(n,e,t){let r=`/v1/inventory/transfers/${f(e)}/reject`;return n.client.post(r,void 0,t?.signal)}async function hy(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 fy(n,e,t,r,o,i){let a=`/v1/saves/${f(e)}/${f(t)}/${f(r)}/upload-url`;return n.client.post(a,o,i?.signal,{replaySafe:true})}async function by(n,e,t,r,o,i){let a=`/v1/inventory/${f(e)}/${f(t)}/progressions/${f(r)}/reset`;return n.client.post(a,o,i?.signal)}async function _y(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 vy(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 wy(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 ky(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 Sy=1e4,Ry=50,xy=1e3,Ay=65536-4*1024,Td=n=>typeof n=="number"?n:0,Py=n=>typeof n=="string"?n:"";function Cd(){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 Ey(n){return n?.retryable===true}function Ty(n,e){let t=n??{},r=Array.isArray(t.rejected)?t.rejected.map(o=>{let i=o??{};return {index:Td(i.index),code:Py(i.code)}}):[];return {accepted:Td(t.accepted),rejected:r,dropped:e,duplicate:t.duplicate===true}}function Id(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 Md(n){let e=Math.max(1,Math.floor(n.maxQueue??xy)),t={client:n.client,gameId:()=>n.gameId},r=[],o=0,i=null,a=false,s=false,l=false,d=false,m=b=>{n.log?.(b);},u=()=>{i!==null&&(n.clock.clearTimeout(i),i=null);},p=()=>{i!==null||a||s||(i=n.clock.setTimeout(()=>{i=null,y().catch(()=>{});},Sy));},g=()=>{let b=Math.min(r.length,100),k=128;for(let x=0;x<b;x+=1){let A=r[x];if(A===void 0)break;if(k+=JSON.stringify(Id(A,0)).length+1,k>Ay)return Math.max(1,x)}return b};async function y(b){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};u();let k=r.splice(0,g()),x=o;o=0;let A=Math.round(n.clock.now()),_={batch_id:Cd(),sent_at_ms:A,events:k.map(S=>Id(S,A))};s=true;try{let S=await gi(t,_,b===void 0?void 0:{signal:b}),C=Ty(S,x);for(let T of C.rejected)m(`[gem] analytics: an event was refused (${T.code}). See the analytics_events section of your game config.`);return C}catch(S){if(Ey(S))for(r=[...k,...r],o+=x;r.length>e;)r.shift(),o+=1;else m(`[gem] analytics: ${k.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(S)}`);throw S}finally{s=false,r.length>0&&p();}}return {track(b,k,x={}){if(a)return;if(typeof b!="string"||b===""){d||(d=true,m(`[gem] analytics: '${k}' 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(k.startsWith(so)){l||(l=true,m(`[gem] analytics: '${k}' 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 A={},_={};for(let[S,C]of Object.entries(x))typeof C=="string"?A[S]=C:typeof C=="number"&&Number.isFinite(C)&&(_[S]=C);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:Cd(),playerId:b,name:k,atMs:n.clock.now(),dimensions:A,measures:_}),r.length>=Ry?y().catch(()=>{}):p();},flush:b=>y(b),get pending(){return r.length},dispose(){a=true,u(),r=[],o=0;}}}function Od(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 Bn(i)}}}function Cy(n){let e={};for(let[t,r]of Object.entries(yi))if(typeof r=="function"){let o=r;e[t]=(...i)=>o(n,...i);}return e}function Ld(n,e={}){let t=e.clock??ge,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=Ed(n,{clock:t,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=hr({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:n.gameId,channel:n.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),a=new je({transport:i,clock:t}),s={gameId:n.gameId,channel:n.channel,matchId:n.matchId,...n.gameRoomId===void 0?{}:{gameRoomId:n.gameRoomId}},l=Cy({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=n.endMatch,u=n.log,p=Md({client:a,clock:t,gameId:s.gameId,...typeof u=="function"?{log:y=>u.call(n,y)}:{}});return {identity:s,client:a,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(n);},setBackfill:async(y,b)=>{let k=await l.setMatchBackfill(s.matchId,{open:y.open,...y.seats===void 0?{}:{seats:y.seats}},b===void 0?{}:{signal:b});return {open:k.open,seats:k.seats??null}},reportPlayers:async(y,b)=>(await l.reportMatchPlayers(s.matchId,{players:y.map(x=>({player_id:x.playerId,state:x.state}))},b===void 0?{}:{signal:b})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new He(l.invokeFunction),challenges:Od(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let b=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),k=b.modified?b.body:void 0;if(k?.room_args==null||k.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:k.room_args,room_args_template:k.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function Xe(n){return n?.reliable!==false?"reliable":n?.ordered!==false?"ordered":"unreliable"}function kt(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 Iy=5e3,Gd=3e4,Dd=2e3,My=1e4,$d=1;async function Fd(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}`),a=typeof n=="function"?n():n,s=Promise.resolve(),l=true,d=false,m=(h,M)=>{l&&(s=s.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,b=h=>{if(!u)return;u=false,m("leave",()=>a.leave?.(r,{cause:h??"left"}));let M=g;M&&queueMicrotask(()=>M(h));},k={send(h,M){if(!u)return;let q=kt(Xe(M));m("message",()=>a.message?.(r,h,typeof h=="string",{reliable:q.reliable,ordered:q.ordered}));},onMessage(h){p=h;},onClose(h){g=h;},close(){b("closed");}},x=(h,M)=>{if(!u)return;let q=kt(Xe(M));queueMicrotask(()=>{u&&p?.(h,q);});},A=new Map,_=h=>{let M=[];for(let q of Oe){let ee=h.channels[q];try{ee.binaryType="arraybuffer";}catch{}let Se=kt(q),gn=tt=>{let Rt=_r(tt?.data);Rt!==null&&m("message",()=>a.message?.(h.playerId,Rt.data,Rt.isText,{reliable:Se.reliable,ordered:Se.ordered}));};ee.addEventListener("message",gn),M.push(()=>ee.removeEventListener("message",gn));}A.get(h.playerId)?.forEach(q=>q()),A.set(h.playerId,M);},S=h=>{A.get(h)?.forEach(M=>M()),A.delete(h);},C=new Set,T=new Map,J=(h,M,q)=>({playerNumber:h.assignedPeerId,transport:"webrtc_p2p",...M?{rejoin:true}:{},...q?{superseded:true}:{}}),U=h=>{let M=A.has(h.playerId),q=C.has(h.playerId);C.add(h.playerId),_(h),M&&m("leave",()=>a.leave?.(h.playerId,{cause:"superseded"})),m("join",()=>a.join?.(h.playerId,J(h,q,M)));},H=new Set,P=(h,M,q)=>{if(h===r){x(M,q);return}let ee=t.peer(h);if(ee===null){let Se=T.get(h);if(Se!==void 0&&e.clock.now()-Se<Dd)return;H.has(h)||(H.add(h),i(`send to '${h}' dropped: no such connected player`));return}ee.send(dn(M),Xe(q));},I={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:dt.toPlain(M.displayName),...M.displayTag===void 0?{}:{displayTag:dt.toPlain(M.displayTag)},...M.discriminator===void 0?{}:{discriminator:M.discriminator}}},playerNumber(h){return h===r?$d:t.peer(h)?.assignedPeerId},send(h,M,q){P(h,M,q);},broadcast(h,M){let q=M?.except;u&&r!==q&&x(h,M);for(let ee of t.peers)ee.playerId!==q&&ee.send(dn(h),Xe(M));},async endMatch(){let h=await Ge();return h.answer!=="ok"&&i(h.cause),h.answer},kick(h,M){if(h===r){b(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=()=>{},D=new Promise(h=>{L=h;}),j=[],W=null,Y=async(h,M)=>{l=false;let q=s.then(async()=>{try{await a.shutdown(h);}catch(ee){i(`the bundle's shutdown threw: ${Qe(ee)}`);}});s=q,await q,ce();for(let ee of j.splice(0))ee();for(let ee of [...A.keys()])S(ee);b(M);},de=(h,M)=>W||(W=(async()=>{await Y(M,h),t.close(),L();})(),W),X=()=>W||(W=(async()=>{await Y({reason:"signal"},"left"),await t.leave().catch(h=>i(`leaving the match failed: ${Qe(h)}`)),L();})(),W),Le=()=>W||(W=(async()=>{l=false;let h=await Ge();h.answer==="ok"?(await Y({reason:"match_ended",platform_reason:"explicit"},"match ended"),t.close()):(i(`${h.cause}; leaving instead`),await Y({reason:"signal"},"left"),await t.leave().catch(M=>i(`leaving the match failed: ${Qe(M)}`))),L();})(),W),we=null,ke=()=>(we??=Ld(I,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),we),Ge=async()=>{try{return await Va({client:ke().client,gameId:()=>I.gameId},I.matchId,{},{signal:AbortSignal.timeout(Iy)}),{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)}`}}},Z=null,K=false,ce=()=>{K=true,Z!==null&&(e.clock.clearTimeout(Z),Z=null);},qe=async()=>{if(Z=null,!K){try{await ke().client.post(`/v1/games/${encodeURIComponent(I.gameId)}/matches/${encodeURIComponent(I.matchId)}/heartbeat`,void 0,AbortSignal.timeout(My));}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`),ce();return}i(`heartbeat failed: ${Qe(h)}`);}K||(Z=e.clock.setTimeout(()=>{qe();},Gd));}},xr=()=>{K||Z!==null||(Z=e.clock.setTimeout(()=>{qe();},Gd));};{let h=L;L=()=>{ce(),we?.dispose(),we=null,h();};}let et=Promise.resolve().then(()=>a.init(I));s=et.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:$d,transport:"loopback"})),j.push(t.on("peerJoined",U)),j.push(t.on("peerLeft",(h,M)=>{S(h);let q=e.clock.now();for(let[ee,Se]of T)q-Se>=Dd&&T.delete(ee);T.set(h,q),H.delete(h),m("leave",()=>a.leave?.(h,{cause:M}));})),j.push(t.on("error",h=>{i(`\u26A0 session error: ${h.message}`);})),j.push(t.on("matchEnded",h=>{W||hi(y,h),de("match ended",{reason:"match_ended",platform_reason:h});})),j.push(t.on("hostChanged",h=>{h!==r&&de("host migrated",{reason:"host_migrated"});}));for(let h of t.peers)U(h);try{await et,xr();}catch(h){l=false,ce(),d=true;for(let M of j.splice(0))M();for(let M of [...A.keys()])S(M);throw t.leave().catch(()=>{}),L(),h}return {matchId:t.matchId,localLink:k,onMatchEnded(h){y=h;},end:Le,leave:X,stop:h=>de(h,{reason:"stopped"}),done:D}}function hi(n,e){try{n?.(e);}catch{}}function Qe(n){return n instanceof Error?n.message:String(n)}function fi(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 qd(n){let e=new Map,t=n.autoReconnect===true,{rooms:r}=n,o=new Map,i=async s=>{r.isHost&&!pi(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...s.signal===void 0?{}:{signal:s.signal}});let l={...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},a=s=>({...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0?{}:{clusterTargetId:s.clusterTargetId}});return {async serve(s,l={}){let d=await i(l);if(d.protocol!==ze)return fi("dedicated",d.matchId);let m=n.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return fi("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(a(l)),g=await Fd(s,{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(s={}){let l=await i(s),d=s.onMatchEnded;if(l.protocol===ze){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Dy(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(),b=async()=>n.p2p.connect({...a(s),certificate:y}),k=await b(),x=Fy(k,b,d,A=>{r.notifyMatchDisconnected(A).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),t);return t&&(e.set(k.matchId,{redial:x.redial,abandon:x.abandon}),x.onClosed(()=>{e.get(k.matchId)?.abandon===x.abandon&&e.delete(k.matchId);})),x}let m=async(g=null)=>await n.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:s.transports??[]}),u=await m(),p=$y(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(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var jd="link_closed",Oy="host_unreachable",Ly=new Set(["failed","closed"]);function Gy(n){return Ly.has(n)?jd:Oy}function Dy(n,e,t){let r=e.localLink;e.onMatchEnded(t);let o="connected";r.onClose(()=>{o="closed";});let i;return {matchId:n,protocol:"loopback",get state(){return o},send:(a,s)=>r.send(a,s),onMessage:a=>r.onMessage(a),onClose:a=>{i=a,r.onClose(s=>{o="closed",i?.(s);});},close:()=>r.close()}}function $y(n,e,t,r){let o=n.matchId,i=n,a="connected",s,l,d=[],m=false,u=false,p=y=>{if(a!=="closed"){a="closed";for(let b of d.splice(0))b();l?.(y);}},g=y=>{y.link.onMessage((b,k)=>s?.(b,k)),y.link.onClose(b=>{if(y!==i||a==="closed")return;if(m||!r){p(b);return}let k=t.matchSession;if(k.phase==="suspended"&&k.matchId===o){a="suspended";return}p(b);});};return g(n),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return a},send(y,b){a==="connected"&&i.link.send(y,b);},onMessage(y){s=y;},onClose(y){l=y;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(a==="closed"||m)return "closed";if(u)return "connected";u=true;let b;try{b=await e(y===void 0?{}:{deadlineAt:y});}finally{u=false;}return m||a==="closed"?(b.close(),"closed"):(i=b,g(b),a="connected",t.notifyMatchConnected(o),"connected")},abandon(y){a!=="closed"&&(a==="connected"&&i.close(),p(y));},onClosed(y){a==="closed"?y():d.push(y);}}}function Fy(n,e,t,r,o,i=false){let a=n.matchId,s=n,l,d,m=[],u=[],p=[],g=false,y=false,b=false,k=false,x="connected",A=P=>{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 I=d;I&&queueMicrotask(()=>I(P));},_=P=>{for(let I of m.splice(0))I();for(let I of Oe){let L=P.channels[I];try{L.binaryType="arraybuffer";}catch{}let D=kt(I),j=W=>{let Y=_r(W?.data);Y!==null&&l?.(Y.data,D);};L.addEventListener("message",j),m.push(()=>L.removeEventListener("message",j));}},S=()=>s.peer(s.hostPlayerId),C=P=>{if(!(g||s.isHost)&&x!=="suspended"){if(r?.(P),i){x="suspended";return}A(P);}},T=P=>{for(let I of Oe){let L=P.channels[I];if(typeof L.addEventListener!="function")continue;let D=()=>{S()===P&&C(jd);};L.addEventListener("close",D),m.push(()=>L.removeEventListener?.("close",D));}},J=P=>{_(P),T(P),!g&&(x="connected",o?.());},U=P=>{for(let I of u.splice(0))I();u.push(P.on("migrating",()=>{k=true;})),u.push(P.on("hostChanged",I=>{if(k=false,I===P.playerId){A("host_migrated_here");return}let L=S();L!==null&&J(L);})),u.push(P.on("peerJoined",I=>{I.playerId===P.hostPlayerId&&J(I);})),u.push(P.on("matchEnded",I=>{g||hi(t,I),A(I);})),u.push(P.on("peerLeft",(I,L)=>{I===P.hostPlayerId&&C(Gy(L));}));};U(s);let H=S();return H!==null&&J(H),{matchId:a,protocol:"p2p",get state(){return x},send(P,I){x==="connected"&&S()?.send(dn(P),Xe(I));},onMessage(P){l=P;},onClose(P){d=P;},close(){y=true,A("closed"),s.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||b)return "connected";if(k)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");b=true;let P;try{for(let L of m.splice(0))L();for(let L of u.splice(0))L();s.close(),P=await e();}finally{b=false;}if(g)return y?P.leave().catch(()=>{}):P.close(),"closed";s=P,U(s);let I=S();if(I===null)throw s.close(),new G("connection_failed","this peer rejoined the match but the host never answered with a link");return J(I),"connected"},abandon(P){A(P);},onClosed(P){g?P():p.push(P);}}}function bi(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(o=>{let i={},a=l=>{t.delete(r)&&(n.clock.clearTimeout(i.timer),o(l));};t.set(r,a),i.timer=n.clock.setTimeout(()=>a(void 0),n.timeoutMs??2e3);let s=false;try{s=n.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,o){t.get(r)?.(o);}}}var qy=12e4;function Ze(n,e){return {outcome:n,reason:e}}function Nd(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-${Pe()}`;return new Promise(i=>{let a={},s=d=>{t.delete(o)&&(e=false,n.clock.clearTimeout(a.timer),i(d));};e=true,t.set(o,s),a.timer=n.clock.setTimeout(()=>s(Ze("unavailable","error")),n.timeoutMs??qy);let l=false;try{l=n.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(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,ms(r.reason)));return}let a=r.purchaseId;if(a===void 0){n.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),i(Ze("unavailable","error"));return}(async()=>{let s;try{s=await n.confirm(a);}catch{s="unknown";}if(s==="granted"){i({outcome:"ok",purchaseId:a});return}s==="absent"&&n.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(a)),i(Ze("unavailable","error"));})();}}}async function Ud(n,e){try{return (await Aa(n,e)).granted?"granted":"absent"}catch(t){return t instanceof O&&t.reason==="not_found"?"absent":"unknown"}}var jy=6e5;function Bd(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-${Pe()}`;return e=new Promise(o=>{let i={},a=l=>{t.delete(r)&&(e=null,n.clock.clearTimeout(i.timer),o(l));};t.set(r,a),i.timer=n.clock.setTimeout(()=>{a({outcome:"unavailable"});},n.timeoutMs??jy);let s=false;try{s=n.bridge.requestSignIn(r);}catch{}s||a({outcome:"unavailable"});}),e}},settle(r){let o=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",i=t.get(r.requestId);if(i===void 0){n.onDropped?.(`gem.signInResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var Ny=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),Uy=["utm_"];function Vd(n){return Ny.has(n)||Uy.some(e=>n.startsWith(e))}var Hd=16,Wd=512,By=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Vy=/[\p{Cc}\p{Cf}]/u,Hy=/\p{Cs}/u,Ce="[gem] gem.share.request:";function Kd(n){let{frame:e,log:t}=n,r=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,i=a=>{t!==null&&(t===void 0?console.warn(a):t(a));};return {get available(){return o()!==null},request(a){let s=o();if(s===null)throw new Error(`${Ce} the arcade does not handle share here \u2014 check gem.share.available first`);if(a!==void 0&&(typeof a!="object"||a===null))throw new TypeError(`${Ce} pass { params }, or nothing`);let l=a?.params===void 0?{}:a.params;if(!Wy(l))throw new TypeError(`${Ce} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>Hd)throw new TypeError(`${Ce} at most ${Hd} params; got ${d.length}`);let m=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!By.test(u))throw new TypeError(`${Ce} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Vd(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>Wd)throw new TypeError(`${Ce} param ${g}: a value is at most ${Wd} characters`);if(Vy.test(p))throw new TypeError(`${Ce} param ${g}: control and format characters are not allowed`);if(Hy.test(p))throw new TypeError(`${Ce} param ${g}: a value must be well-formed text`);m.push({key:u,value:p});}!s.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 Wy(n){if(typeof n!="object"||n===null||Array.isArray(n))return false;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}var Yy="(any-pointer: coarse)";function Xy(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 Jd(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,a=new Set,s=()=>typeof o?.vibrate!="function"||r.matchMedia===void 0?false:(i??=r.matchMedia(Yy),i.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,u)=>{a.has(m)||(a.add(m),t!==null&&(t===void 0?console.warn(u):t(u)));};return {get available(){return s()||l()},vibrate(m){let u=s();if(!u&&!l())return false;let p=Xy(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 Qy=["lookSensitivity","gamepadLookSensitivity","invertLookY","touchMovement"];function vr(n){let e={};if(typeof n=="object"&&n!==null)for(let t of Qy){let r=n[t];(r==="player"||r==="game")&&(e[t]=r);}return e}var St=Math.PI/180,Ie=Object.freeze({touch:Object.freeze({yaw:1*St,pitch:.66*St}),mouse:Object.freeze({yaw:.5*St,pitch:.5*.77*St}),stick:Object.freeze({yaw:240*St,pitch:240*.77*St}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),_i="[gem.controls]",vi=Object.freeze({yaw:0,pitch:0}),wr=n=>Number.isFinite(n)?n:0,zd=(n,e)=>({yaw:n+0,pitch:e+0});function Yd(n){let e=wr(n),t=(Math.abs(e)-Ie.stickDeadzone)/(1-Ie.stickDeadzone),r=Ie.stickCurve,o=(Math.exp(r*t)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,o))+0}function Zy(n){let e=Math.min(1,2*Math.abs(n)/Math.PI);return (1-Math.pow(e,.75))*(1-Ie.touchPitchMin)+Ie.touchPitchMin}function Xd(n,e){if(n===void 0)return {};if(typeof n!="object"||n===null)throw new TypeError(`${_i} ${e} takes an options object`);let t=n;for(let r of ["sensitivity","gamepadSensitivity"]){let o=t[r];if(o!==void 0&&!(typeof o=="number"&&Number.isFinite(o)&&o>0))throw new TypeError(`${_i} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(o)}`)}if(t.invertY!==void 0&&typeof t.invertY!="boolean")throw new TypeError(`${_i} ${e}: invertY must be a boolean; got ${String(t.invertY)}`);return t}function eh(n,e){let t=Xd(e,"look()"),r=t.sensitivity,o=t.gamepadSensitivity,i=t.invertY,a=s=>i??s?.invertLookY??false;return {fromPointer(s,l,d,m){let u=wr(s),p=wr(l);if(u===0&&p===0)return vi;let g=n(),y=r??(g===null?void 0:g.lookSensitivity/100)??1,b=d==="touch"||d==="pen",k=b?Ie.touch:Ie.mouse,x=u*k.yaw*y,A=-p*k.pitch*y;return a(g)&&(A=-A),b&&m!==void 0&&Number.isFinite(m)&&A*m>0&&(A*=Zy(m)),zd(x,A)},fromStick(s,l,d){let m=wr(d);if(m<=0)return vi;let u=Yd(s),p=Yd(l);if(u===0&&p===0)return vi;let g=n(),y=o??(g===null?void 0:g.gamepadLookSensitivity/100)??1,b=u*Ie.stick.yaw*m*y,k=-p*Ie.stick.pitch*m*y;return a(g)&&(k=-k),zd(b,k)},set(s){let l=Xd(s,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(o=l.gamepadSensitivity),"invertY"in l&&(i=l.invertY);}}}function Qd(n){return {declare:e=>n.declare(e),look:e=>eh(n.recommended,e),LOOK_BASE:Ie}}function Zd(n,e){return n==null?e?"low":"medium":n==="low"||n==="high"?n:"medium"}var th=/(?:Z|[+-]\d{2}:?\d{2})$/i;function ec(n){if(typeof n!="string"||!th.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 tc(n,e){let t=typeof n=="object"&&n!==null?n:{},r=ec(t.resets_at),o=r===void 0?{}:{resetsAt:r};if(t.declared!==true)return {...cn(),...o};let i=t.remaining_today,a=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):void 0,s=t.next_eligible_at,l=ec(s),d=t.held_limit_reached===true,m=s!=null,u=i!=null&&a===void 0;return {declared:true,grantable:t.grantable===true&&e&&a!==0&&!u&&!m&&!d,...a===void 0?{}:{remainingToday:a},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...o}}var nh=18e4,wi=32,rh=/^[a-z0-9_-]+$/,oh="rewarded_requires_user_gesture";function ih(){let n=globalThis.navigator?.userActivation?.isActive;return typeof n=="boolean"?n:void 0}var ah=1e3;function sh(){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 a=o[i]?.timestamp;if(typeof a=="number"&&r-a>=0&&r-a<=ah)return true}return false}var nc=1e4;function lh(n){return n==="interstitial"||n==="rewarded"}function rc(n){return typeof n=="string"&&n!==""&&n.length<=wi&&rh.test(n)}function dh(n){let e=typeof n=="object"&&n!==null?n:{};return [e.name,e.reason,e.status].join()}function kr(n){return typeof n=="string"?JSON.stringify(n):typeof n}function oc(n){let e=false,t=new Map,r=new Map,o=new Set,i=d=>{try{n.onDropped?.(d);}catch{}},a=false,s=d=>{if(a)return;a=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={},b=_=>y.done===true?false:(y.done=true,n.clock.clearTimeout(y.timer),g(_),true),k=(_,S)=>{!b(cn())||o.has(_)||(o.add(_),i(`gem.ads.rewardedStatus("${d}") answered not grantable: ${S}. Said once.`));},x=_=>{k(dh(_),`the read failed (${_ instanceof Error?_.message:kr(_)})`);},A;try{A=Promise.resolve(m(d,AbortSignal.timeout(nc)));}catch(_){A=Promise.reject(_);}y.timer=n.clock.setTimeout(()=>{k("timeout","no answer within 10 s");},nc),A.then(_=>{try{b(tc(_,n.bridge.parentSupports("ads")));}catch(S){x(S);}},x);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return rc(d)?l(d):(i(`gem.ads.rewardedStatus(${kr(d)}) answered not grantable: a placement is 1..${String(wi)} 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(!rc(m)||!lh(u))return i(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${kr(m)}, format ${kr(u)}. A placement is 1..${String(wi)} 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??ih)();}catch{g=void 0;}if(g===false)try{(n.recentGamepadInput??sh)()===!0&&(g=!0);}catch{}if(g===false){let y=`${oh}: 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),s(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${Pe()}`;return new Promise(g=>{let y={},b=x=>{t.delete(p)&&(e=false,n.clock.clearTimeout(y.timer),g(x));};e=true,t.set(p,b),y.timer=n.clock.setTimeout(()=>{b({outcome:"unavailable"});},n.timeoutMs??nh);let k=false;try{k=n.bridge.requestAd(p,m,u);}catch{}k||b({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 ki=16384;function ic(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:ch(e)}function ch(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 uh=1e4,mh=5e3;function ac(n){let e=null,t=false,r=[],o=new Map,i=()=>{for(let a of r.splice(0))a();};return {api:{get current(){return e},wait(a=mh){return t?Promise.resolve(e):new Promise(s=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{n.clock.clearTimeout(m),l(),s(e);},m=n.clock.setTimeout(()=>{l(),s(e);},a);r.push(d);})},put(a){if(!n.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let s=ic(a);if(s===null)return n.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(s>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(a)),d=`device-settings-${Pe()}`;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??uh);let g=false;try{g=n.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(a){let s=a.settings;e=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,t=true,i();},settle(a){let s=a.outcome==="stored"||a.outcome==="too_large"?a.outcome:"unavailable",l=o.get(a.requestId);if(l===void 0){n.onDropped?.(`gem.deviceSettings.result (${s}) for an unknown requestId: `+JSON.stringify(a.requestId));return}l(s);}}}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 ph=/^[a-z0-9][a-z0-9_-]{0,39}$/;function gh(n){return typeof n=="string"&&ph.test(n)}function Sr(n){if(n===null||gh(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 sc(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Si(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(a=>a.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 lc(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function yh(n){let e=n.untrusted,t=Me(e.displayName),r=e.displayTag||e.displayHandle,o=r?Me(r):void 0,i=n.discriminator||n.displayTag,a=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,s=n.avatarIconUrl||n.avatarUrl,l=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),a&&(d.discriminator=a),o&&(d.displayTag=o),s&&(d.avatarIconUrl=d.avatarUrl=s),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 hh=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??ge,this.inbound=new Pt(this.clock),this.outbound=new Pt(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>Ur(s,e.origin))||ls(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=Rn["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!Ur(o.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${o.embedder}' but arrived from '${e.origin}'`),false;let i=e.ports?.[0];if(!i)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=ds(kn,o.versions);return a===null?(i.onmessage=null,i.postMessage({gem:N,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=a,i.onmessage=s=>this.receive(s.data,s.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:N,type:"gem.handshake.accept",v:a,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:N,type:"gem.ready"});}settled(e=hh){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:N,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:N,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:N,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:N,type:"gem.exit"}:{gem:N,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:N,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:N,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:N,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:N,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:N,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:sc(e.origin.x),y:sc(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:N,type:"gem.portraitBorders"}:{gem:N,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:N,type:"gem.walletDisplay",...Si(e,t?.only)})}declareControls(e){return this.state!=="connected"||!this.parentSupports("controls")?false:this.send({gem:N,type:"gem.controlsDeclare",uses:vr(e)})}setMenu(e,t){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:N,type:"gem.menu",...Rr(e,t)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:N,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:N,type:"gem.requestAvatarPicker"})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:N,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:N,type:"gem.frameStats",fps:lc(e.fps,1e3),frameTimeP95Ms:lc(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:N,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:N,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:N,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:N,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,o,i,a){return this.send({gem:N,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,t){return this.send({gem:N,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:N,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:N,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,o){return this.send({gem:N,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(Sn)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(Sn)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(Sn)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:N,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=Rn[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||dc(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=Rn[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=os(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let a=o(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.menuSelect":this.options.onMenuSelect?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return dc(t.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(yh(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:N,type:"gem.screenshot.denied",reason:e,retryable:t});}};function dc(n){for(let e of n)try{e?.close?.();}catch{}}var cc="https://api.gemarcade.com";function Ri(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 fh=new Set(["localhost","127.0.0.1","[::1]"]);function uc(n){let e=Ri(n);if(e!==null)return e;let t=new URL(n);return t.protocol==="http:"&&!fh.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 _h=Object.freeze(["https://gemarcade.com","https://meme-games.com","http://gemarcade.localhost","gemarcade://localhost"]),vh=cc,mc=8e3,xi=15e3,wh=9e4,kh=1/0,Sh=8e3,Rh=5e3,xh=5e3;async function Ah(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 a=()=>{let d=r.indexOf(s);d>=0&&r.splice(d,1);},s=d=>{n.clearTimeout(l),a(),i(d);},l=n.setTimeout(()=>{a(),i(e);},o);r.push(s);})}}}function IR(n={}){let e=n.clock??ge,t=n.log===void 0?c=>console.info(c):n.log,r=n.baseUrl??void 0;if(r!=null){let c=Ri(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=Gs(typeof window>"u"?void 0:window.location?.search),i=ni();i.mark("sdk created");let a=()=>Qn(ne.gameVersion,n.clientVersion?.gameVersion),s=new qt({client:()=>rt,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,environment:()=>{let c=a();return {sdk_version:Ui(),...c===null?{}:{game_version:c}}},...n.analytics===void 0?{}:{options:n.analytics},log:t}),l=Bl(()=>{i.mark("engaged"),s.release(),F.reportEngaged();},typeof window>"u"?{}:window),d=c=>{if(c===false)return null;let R=c?.attempts??kh,$=c?.budgetMs??wh;return !(R>0)||!($>0)?null:{attempts:R,budgetMs:$,maxDelayMs:c?.maxDelayMs??Sh}},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"||!Nr(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([..._h,...p])]),b=pn(e),k=pn(e),x=false,A=pn(e),_=Ns(t),S=pn(e),C=n.manageAudio===false?null:Xl();n.selectableText!==true&&Ql();let T=null,J=()=>{T!==null&&(k.current!==null&&k.current.muted===T||F.reportMuted(T));},U,H,P=-1/0,I=null,L=()=>{if(U===void 0||I!==null||U===H)return;let c=P+1e3-e.now();if(c>0){I=e.setTimeout(()=>{I=null,L();},c);return}F.showPortraitBorders(U)&&(H=U,P=e.now());},D=null,j=null,W=()=>{if(D===null)return false;let c=JSON.stringify(Si(D.visible,D.only));return c===j?F.parentSupports("walletDisplay"):F.setWalletVisible(D.visible,D)?(j=c,true):false},Y=null,de=null,X=null,Le=null,we=()=>{if(X===null)return false;let c=JSON.stringify(X);return c===Le?F.parentSupports("controls"):F.declareControls(X)?(Le=c,true):false},ke=()=>{if(Y===null)return false;let c=typeof Y.onSettings=="function",R=JSON.stringify(Rr(c,Y.items));return R===de?F.parentSupports("gameMenu"):F.setMenu(c,Y.items)?(de=R,true):false},Ge=Zl({report:c=>F.reportFrameStats(c)}),Z=false,K=ad(()=>Ni,()=>Z),ce=c=>{let R=Z&&!c,$=Z!==c;if(Z=c,R&&K.close(),!!$)try{n.onDevToolsPermissionChange?.(c);}catch(re){t?.(`[gem] onDevToolsPermissionChange threw: ${re instanceof Error?re.message:String(re)}`),queueMicrotask(()=>{throw re});}},qe=r??vh,xr=r!==void 0,et,h=c=>(t?.(`[gem] token refused: ${c}`),n.onError?.("internal",c),false),M=(c,R)=>{if(c===void 0)return R!==void 0?h("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 $=uc(c);return $!==null?h(`the embedder named an API root that cannot be used: ${$}. Its value is withheld here rather than written to logs.`):et!==void 0&&et!==c?h("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."):(et=c,xr||(qe=c),true)},q=window.location?.origin,ee=null,Se=-1/0,gn=2e3,tt=new Set,Rt=c=>ee!==false?Promise.resolve(true):new Promise(R=>{let $=e.setTimeout(()=>{tt.delete(re),R(false);},c),re=()=>{e.clearTimeout($),tt.delete(re),R(true);};tt.add(re);}),Ar=()=>{},Pr=null,F=new mn({allowedEmbedders:y,...typeof q=="string"&&q!==""?{selfOrigin:q}:{},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","controls","gameMenu","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...n.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:c=>{Pr=c,n.onRefused?.(c);},...n.onError===void 0?{}:{onError:n.onError},onStateChange:c=>{ne.onBridgeState(c),c!=="connected"&&Ge.setRequested(false),j=null,de=null,Le=null,H=void 0,c==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Pr===null?"":` (${Pr})`)+", 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."),Ar()),c==="connected"&&(i.mark("bridge connected"),pc(),J(),L(),W(),ke(),we(),F.unbiddenLaunch&&!l.engaged&&s.hold(),s.startSession(),l.engaged&&F.reportEngaged()),n.onStateChange?.(c);},onPlayer:c=>{b.set(c),n.onPlayer?.(c);},onPrefs:c=>{let R={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,lookSensitivity:c.recommended.lookSensitivity??100,gamepadLookSensitivity:c.recommended.gamepadLookSensitivity??100,invertLookY:c.recommended.invertLookY??false,touchMovement:c.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:Zd(c.recommended.graphicsQuality,c.recommended.batterySaver),graphicsQualityAuto:c.recommended.graphicsQualityAuto??true})};k.set(R),C?.setMuted(R.muted),Ge.setRequested(R.showFrameStats&&F.parentSupports("frameStats")),n.onPrefs?.(R);},onCohorts:c=>{let R=Object.freeze(c.cohorts.map($=>Object.freeze({experimentId:$.experimentId,variantKey:$.variantKey})));A.set(R),n.onCohorts?.(R);},onEarnAllowanceChanged:()=>_.emit(),onViewport:c=>{let R=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(re=>Object.freeze({x:re.x,y:re.y,width:re.width,height:re.height})))});S.set(R);let $=td();nd($,R.insets),od($,R.reserved,rd()),n.onViewport?.(R);},onPause:c=>{x=c.paused,s.setPaused(c.paused),Ge.setPaused(c.paused),n.onPause?.(c.paused);},onMenuSelect:c=>{if(Y===null)return;if(c.entry==="settings"){Y.onSettings?.();return}(Rr(false,Y.items).items??[]).some($=>$.id===c.id)&&Y.items?.find($=>$.id===c.id)?.onSelect?.();},onWillTerminate:c=>{s.endSession(c.reason),n.onWillTerminate?.({reason:c.reason,graceMs:c.graceMs});},onToken:c=>{let R=c.garden;if(ce(c.allowDevTools===true),!M(c.apiBaseUrl,R))return;let $=c;ne.onToken($);let re=ne.identity;re&&(Er.set(re),Pi||(Pi=true,ue.reconcileSeats().catch(()=>{}))),Ei.push({token:$.token,expiresAt:$.expiresAt});},onTokenDenied:c=>{ce(false),ne.onDenied(c);},onScreenshot:(c,R,$)=>{Jl(c,R,$,{...n.onScreenshot===void 0?{}:{handler:n.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{zl(F,n.onFeedbackContext);},onDevtools:c=>{c==="close"?K.close():c==="open"?K.openFrom("platform").catch(()=>{}):K.isOpen?K.close():K.openFrom("platform").catch(()=>{});},onRoomEvent:c=>ue.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=>ue.handleSeated(c.roomId),onAutoStartFailedEvent:c=>ue.handleAutoStartFailed(c.roomId,c.code),onSocketState:c=>{let R=ee;if(ee=c.connected,c.connected)for(let re of [...tt])re();if(!c.connected||R===true)return;let $=e.now();$-Se<gn||(Se=$,ue.reconcile().catch(()=>{}));},onSignalEvent:c=>{let R=typeof c.data=="object"&&c.data!==null&&!Array.isArray(c.data)?c.data:{};ot.handleSignalEvent(c.matchId,c.event,R),c.event==="matchEnded"&&ue.reconcile({matchId:c.matchId,...typeof R.reason=="string"?{reason:R.reason}:{}}).catch(()=>{});},onDedicatedEvent:c=>{c.event==="matchEnded"&&(xt.handleMatchEnded(c.matchId,c.reason),ue.reconcile({matchId:c.matchId,...c.reason===void 0?{}:{reason:c.reason}}).catch(()=>{})),Ai.handleEvent(c);},onClusterTarget:c=>fn.accept(c.clusterTargetId,c.clusterTargetIds),onLocalServer:c=>bn.accept(c),onLocalServerDenied:c=>bn.refuse(c),onPartyResult:c=>Ci.settle(c.requestId,c.partyId),onPurchaseResult:c=>Mi.settle(c),onDeviceSettings:c=>{hn.receive(c),n.onDeviceSettings?.(hn.api.current);},onDeviceSettingsResult:c=>hn.settle(c),onAdResult:c=>Li.settle(c),onSignInResult:c=>Gi.settle(c),onFriendChallengeResult:c=>Di.settle(c)}),Ai=new ln({bridge:F}),Er=pn(e);Ar=()=>{Er.release(),b.release(),A.release();},F.currentState==="refused"&&Ar();let Pi=false,Tr=new Set,yn,Ei={current:()=>yn,subscribe:c=>(Tr.add(c),yn!==void 0&&c(yn),()=>Tr.delete(c)),push:c=>{yn=c;for(let R of [...Tr])try{R(c);}catch($){t?.(`[gem] a server-token listener threw: ${$ instanceof Error?$.message:String($)}`);}}},ne=ld({bridge:F,clock:e,onStateChange:(c,R)=>{if(c==="ready"){if(i.mark("token ready")){let $=i.marks.find(re=>re.name==="token ready")?.at;s.trackPlatform("gem_boot_ready",$===void 0?{}:{boot_ms:Math.max(0,Math.round($))});}}else c==="lost"&&(i.mark("token lost"),s.trackPlatform("gem_auth_lost"));n.onAuthStateChange?.(c,R);}}),Ti=()=>{let c=ne.identity;return !c||ne.source.currentState==="lost"?null:`${c.playerId}\0${c.gameId}\0${c.channel}`},pc=()=>{i.mark("token requested"),ne.source.get().catch(()=>{});},Ci=bi({bridge:F,clock:e}),Ii={},Mi=Nd({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c),confirm:async c=>Ii.confirm?.(c)??"unknown"}),hn=ac({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c)}),Oi={},Li=oc({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c),readAvailability:(c,R)=>Oi.read?.(c,R)??Promise.reject(new Error("the gem-api client is not built yet")),log:n.log}),Gi=Bd({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c)}),Di=js({bridge:F,clock:e,onDropped:c=>n.onError?.("internal",c)}),fn=Ys({bridge:F,clock:e}),bn=id({bridge:F,clock:e}),Cr=c=>{let R=F.handleWindowMessage({data:c.data,origin:c.origin,source:c.source,ports:c.ports});return R&&window.removeEventListener("message",Cr),R};window.addEventListener("message",Cr);let nt=Vl(window,Cr),gc=nt?.capture,Ir=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Ir?.domInteractive!==void 0&&Ir.domInteractive>0&&i.mark("document parsed",Ir.domInteractive),gc?.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 Mr=n.handshakeWarningMs;Mr!==null&&t&&e.setTimeout(()=>{let c=nt===null?"no capture script ran":`capture: ${nt.delivered} offer(s) delivered, ${nt.stale} stale, ${nt.capture.dropped} evicted${nt.capture.late?", installed late":""}`;if(F.currentState==="connected"){t(`[gem] handshake connected. boot: ${i.timeline()} \xB7 ${c}`);return}t(`[gem] no completed handshake after ${Mr??mc}ms (bridge state: ${F.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);},Mr??mc);let yc=hr({get baseUrl(){return qe},tokenSource:ne.source,get defaultQuery(){let c=ne.identity;return c?{game_id:c.gameId,channel:c.channel}:{}}}),rt=new je({transport:yc,clock:e}),pe={client:rt,gameId:()=>ne.identity?.gameId??""};Ii.confirm=c=>Ud(pe,c),Oi.read=(c,R)=>Ja(pe,"players","me",c,{signal:R});let hc=()=>ne.identity?.channel??"release",$i=new Un(pe,hc),Fi=async c=>(await $i.load())?.currency(c)?.id??void 0,qi=Dn(pe,Qr,{identity:Ti,resolveCurrencyId:Fi}),Or=async c=>{let R=await Er.wait(c);if(R)return R;throw F.currentState==="refused"?new se("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 se("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},Lr=d(n.autoReconnect),ue=No({client:rt,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,awaitGameId:async()=>(await Or(xi)).gameId,resolveParty:Ci.resolve,resolveClusterTargets:fn.resolveList,refreshClusterTargets:fn.refresh,ensureLocalServer:bn.ensure,localHostAvailable:bn.available,...n.clientVersion===void 0?{}:{clientVersion:n.clientVersion},platformGameVersion:()=>ne.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},...Lr===null?{}:{autoReconnect:{...Lr,redial:(c,R)=>Gr.redialMatch(c,R),abandon:(c,R)=>Gr.abandonMatch(c,R)}}});m(ue),Nl({analytics:s,rooms:ue});let ot=jl({client:rt,clock:e,rooms:ue,bridge:F,gameId:()=>ne.identity?.gameId??"",baseUrl:()=>qe,resolveClusterTarget:fn.resolve,boot:i,...n.log===void 0?{}:{log:n.log}}),ji=ti(i,t),xt=xd({client:rt,clock:e,rooms:ue,signaling:()=>Ai.channel(),signalingReady:Rt,log:t??(()=>{})}),Gr=qd({rooms:ue,p2p:{connect:c=>ji(ot.connect(c)),session:c=>ot.session(c)},dedicated:{connect:(c=>pr(i,"welcome",xt.connect(c),t))},clock:e,identity:()=>ne.identity,apiBaseUrl:()=>qe,tokens:Ei,room:()=>ue.currentRoom,autoReconnect:Lr!==null,...n.log===void 0?{}:{log:n.log}}),fc=async()=>(await Or(xi)).playerId,Ni={client:rt,boot:i,get identity(){return ne.identity},awaitIdentity:(c=xi)=>Or(c),awaitBridge:c=>F.settled(c),get player(){return b.current},awaitPlayer:(c=Rh)=>b.wait(c),me:qi,characters:new Fn(pe,void 0,Ti,Fi),transfers:new jn(pe,Qr,qi.inventory),gameConfig:$i,purchases:Mi.api,deviceSettings:hn.api,ads:Li.api,account:Gi.api,share:Kd({frame:F,log:n.log}),vibration:Jd({frame:F,log:n.log}),get avatarPickerAvailable(){return F.currentState==="connected"&&F.parentSupports("avatarPicker")},openAvatarPicker:()=>F.requestAvatarPicker(),controls:Qd({declare:c=>(X=vr(c),we()),recommended:()=>k.current?.recommended??null}),analytics:s,leaderboards:new Ot(pe),challenges:new Ct(pe),showcase:new Lt(pe,fc),friends:new Gt(pe,{challenge:Di.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new $t(pe,_,t),profiles:new Ft(pe),functions:new He((c,R)=>La(pe,c,R)),get prefs(){return k.current},get paused(){return x},get cohorts(){return A.current},get viewport(){return S.current},awaitCohorts:(c=xh)=>A.wait(c),reportMuted:c=>{T=!!c,J();},showPortraitBorders:c=>{let R=Sr(c);R!==void 0&&(U=R,L());},cueReward:c=>F.cueReward(c),setWalletVisible:(c,R)=>{let $=Array.isArray(R?.only)?[...R.only]:void 0;return D=$===void 0?{visible:c===true}:{visible:c===true,only:$},W()},setMenu:c=>(Y={...typeof c?.onSettings=="function"?{onSettings:c.onSettings}:{},...Array.isArray(c?.items)?{items:c.items.map(R=>({...R}))}:{}},ke()),exit:c=>Ah(ue,F,c,s),frame:F,devtools:K,rooms:ue,dedicatedServer:{listClusterTargets:c=>xt.listClusterTargets(c),connect:(c=>pr(i,"welcome",xt.connect(c),t)),handleMatchEnded:(c,R)=>xt.handleMatchEnded(c,R)},p2p:{handleSignalEvent:(c,R,$)=>ot.handleSignalEvent(c,R,$),session:c=>ot.session(c),connect:c=>ji(ot.connect(c))},match:Gr};return Ni}
2
+ export{_h as ARCADE_EMBEDDERS,qt as AnalyticsApi,se as AuthError,Ct as ChallengesApi,ki as DEVICE_SETTINGS_MAX_BYTES,w as DedicatedServerError,Ve as FriendChallengeError,Gt as FriendsApi,He as FunctionsApi,O as GemApiError,je as GemClient,le as GemConfigError,mn as GemFrame,zn as GemFunctionError,ie as GemSaveError,un as GemUnframedError,Ot as LeaderboardsApi,Rs as MAX_PERIODS_BACK,rm as PLATFORM_EVENTS,$t as PlatformApi,Kn as PlatformCurrenciesApi,Jn as PlatformEarnAllowanceApi,ye as PlayerText,Ft as ProfilesApi,De as PurchaseRefusal,Lt as ShowcaseApi,oe as TransportRefusal,Vt as UNRELIABLE_CHANNEL_LABEL,Me as asPlayerText,ni as createBootTimeline,IR as createGem,Ah as leaveAndExit,be as mapIdentity,pr as markOnResolve,Tu as platformIconUrl,Ut as presentJoinCredential,yt as readTemplateTransports,Ht as readTransportAdvert,ti as reportOnResolve,dt as text,rr as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.game.js.map
3
3
  //# sourceMappingURL=gem-web-sdk.game.js.map