@indiegems/gem-web-sdk 16.0.1 → 16.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- var GemWebSdkGame=(function(exports){'use strict';var ym=Object.defineProperty;var fm=(t,e)=>{for(var n in e)ym(t,n,{get:e[n],enumerable:true});};var To="GemWebSdkHandshake";function hm(){return typeof document>"u"?void 0:document.readyState}var Va=()=>Date.now();function Ka(t={}){let e=t.win??window,n=e,r=n[To];if(r!==void 0)return r;let o=t.readyState??hm,i=t.now??Va,s=[],a=[],l=m=>{let c=m.data;!c||c.type!=="gem.handshake"||(s.length>=4&&(s.shift(),a.shift(),d.dropped+=1),s.push(m),a.push(i()));};e.addEventListener("message",l);let d={events:s,times:a,dropped:0,late:o()==="complete",uninstall(){e.removeEventListener("message",l);}};return n[To]=d,d}function Ja(t,e,n={}){let r=t[To];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??Va,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,m=false,c=i()-o;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(s[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:16.0.1]";function za(){let t=globalThis.__gemWebSdkVersion;if(typeof t!="string")return "";let e=t.lastIndexOf(":"),n=t.lastIndexOf("]");return e<0||n<=e+1?"":t.slice(e+1,n)}var bm={initialDelayMs:2e3,maxDelayMs:6e4};function vm(t,e){return e!==void 0?!e:t==="chain_exhausted"}var _t=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;retry=null;failures=0;notBefore=0;disposed=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new ne(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.pastChainCeiling())throw new ne("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new ne(this.failure??"unavailable","the embedder asked for no new token yet; one is asked for when that wait is over");return this.refresh(this.nextReason())}pastChainCeiling(){return this.grant===null||this.seconds()<this.grant.chainEndsAt?false:(this.enter("lost","chain_exhausted"),true)}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);}dispose(){this.disposed=true,this.cancelRetry();}scheduleRetry(e){if(this.cancelRetry(),this.failures+=1,this.notBefore=e===void 0?0:this.options.clock.now()+e,this.disposed)return;let{initialDelayMs:n,maxDelayMs:r}=bm,o=Math.min(r,n*2**(this.failures-1)),i=Math.max(o/2,e??0)+Math.random()*(o/2);this.retry={handle:this.options.clock.setTimeout(()=>this.retryNow(),i)};}retryNow(){this.retry=null,this.notBefore=0,!(this.state==="lost"||this.pastChainCeiling())&&this.refresh(this.nextReason()).catch(()=>{});}cancelRetry(){this.retry!==null&&(this.options.clock.clearTimeout(this.retry.handle),this.retry=null);}refresh(e){if(this.inFlight)return this.inFlight;this.cancelRetry();let n=this.generation;this.enter("pending");let r=this.options.request(e).then(o=>{if(n!==this.generation)throw new ne("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=_m(o),{retryable:s,retryAfterMs:a}=o??{};throw n===this.generation&&(vm(i,typeof s=="boolean"?s:void 0)?this.enter("lost",i):(this.scheduleRetry(typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0),this.enter("degraded",i))),o instanceof ne?o:new ne(i,String(o))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){(e==="ready"||e==="lost")&&this.cancelRetry(),e==="ready"&&(this.failures=0,this.notBefore=0),this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},ne=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function _m(t){if(t instanceof ne)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var ae=class t extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof t)return true;let n=e;return n?.name==="TransportRefusal"&&n.retryable===false}},Jn=["if-match","if-none-match"],Ya=4096;function wm(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!Jn.includes(o)||r===void 0)continue;let i=typeof r=="string"?Sm(r):r;if(typeof i!="string"||i.length>Ya||!Rm(i))throw new ae(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Ya} 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 Sm(t){let e=o=>o===32||o===9||o===10||o===13,n=0,r=t.length;for(;n<r&&e(t.charCodeAt(n));)n++;for(;r>n&&e(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function Rm(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n!==9&&(n<32||n===127||n>255))return false}return true}function km(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new ae("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new ae("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 Xa(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=wm(o.headers),s=km(o),a=Object.freeze({...o,headers:i,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await t(a,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),c=await t(a,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new ne("unavailable","the server refused a freshly minted token");return c}}}function zn(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Am(e))}function Yn(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Eo(t){return new TextDecoder().decode(Yn(t))}function Am(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var O=class extends Error{constructor(n,r,o,i,s){super(`${n} (${r}): ${o}`);this.reason=n;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Za=new WeakMap;function es(t){return Za.get(t)??{}}var xm=new Set([408,429,500,502,503,504]),Pm=6e4;function Tm(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new ae(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(t)}. This is a configuration fault, not a server failure.`);return t}var We=class{constructor(e){this.options=e;}options;async get(e,n){return this.send({method:"GET",path:e,signal:n},true)}async getWithEtag(e,n={}){let r=await this.sendRaw({method:"GET",path:e,...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{headers:{"if-none-match":n.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,n,r,o={}){return this.send({method:"PUT",path:e,body:n,signal:r,...Wt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...Wt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async postBytes(e,n,r,o={}){let i=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...Wt(o)},o.replaySafe===true,o.retryRateLimited!==false);return {bytes:Em(i.body),...i.invocationId===void 0?{}:{invocationId:i.invocationId}}}async patch(e,n,r,o={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...Wt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Wt(r)},r.replaySafe===true,r.retryRateLimited!==false)}async send(e,n,r=true){return (await this.sendRaw(e,n,r)).body}async sendRaw(e,n,r=true){let o=n?Tm(this.options.maxRetries)+1:1,i=null;if(e.signal?.aborted)throw Qa(e.signal);for(let s=0;s<o;s++){if(s>0&&await this.backoff(s,i,e.signal),e.signal?.aborted)throw Qa(e.signal);let a;try{a=await this.options.transport.request(e);}catch(d){if(ne.isAuthError(d)||ae.isRefusal(d)||e.signal?.aborted||Im(d))throw d;i=new O("unavailable",0,String(d));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let l=Cm(a);if(!xm.has(a.status)||a.status===429&&!r)throw l;i=l;}throw i??new O("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let o=n?.retryAfterSeconds,i=o!==void 0?o*1e3:2**(e-1)*250,s=2**(e-1)*250,a=Math.min(Math.max(i,s),Pm);return new Promise(l=>{let d=this.options.clock,m=false,c=false,p,g=()=>{m||(m=true,c&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,a),c=true,m&&d.clearTimeout(p);})}};function Em(t){if(t instanceof Uint8Array)return t;if(t==null)return new Uint8Array(0);let e=typeof t=="string"?t:JSON.stringify(t);return new TextEncoder().encode(e)}function Wt(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function Qa(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Im(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Cm(t){let e=Om(t),n=Lm(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Za.set(e,r),e}var Mm=new Map([["insufficient_funds","insufficient_funds"]]);function Om(t){let{status:e,body:n}=t,r=Gm(n),o=t.retryAfterSeconds??Fm(n),i=Dm(n),s=i===void 0?void 0:Mm.get(i);if(s!==void 0)return new O(s,e,r,void 0,i);switch(e){case 304:return new O("not_modified",e,r);case 400:case 422:return new O("invalid",e,r,void 0,i);case 403:return new O("forbidden",e,r,void 0,i);case 404:return new O("not_found",e,r,void 0,i);case 402:return new O("insufficient_funds",e,r,void 0,i);case 409:return new O("conflict",e,r,void 0,i);case 412:return new O("precondition_failed",e,r,void 0,i);case 413:return new O("too_large",e,r,void 0,i);case 429:return new O("rate_limited",e,r,o,i);default:return new O("unavailable",e,r,o,i)}}function Gm(t){if(typeof t=="string")return t;let e=t?.message;if(typeof e=="string")return e;let n=t?.error;if(typeof n=="string")return n;let r=n?.message;return typeof r=="string"?r:"no detail"}function Lm(t){let n=t?.error?.details;return n===null?void 0:n}function Dm(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Fm(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _(t){let e=String(t);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 ts(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function ns(t,e,n,r,o,i){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/add`;return t.client.post(s,o,i?.signal)}async function rs(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function os(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}`;return t.client.delete(r,n?.signal)}async function is(t,e,n,r,o,i){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/claim`;return t.client.post(s,o,i?.signal)}async function as(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function ss(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ls(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ds(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function cs(t,e,n,r,o){let i=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(i,o?.signal)}async function us(t,e,n,r,o){let i=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(i,o?.signal)}async function ms(t,e,n,r){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.delete(o,r?.signal)}async function ps(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function gs(t,e,n,r,o,i){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/finalize`;return t.client.post(s,o,i?.signal)}async function ys(t,e,n){let r=`/v1/games/${_(t.gameId())}/avatars-3d/${_(e)}/owned`;return t.client.get(r,n?.signal)}async function fs(t,e,n){let r=`/v1/games/${_(t.gameId())}/config/channels/${_(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function hs(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.get(r,n?.signal)}async function bs(t,e,n){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function vs(t,e,n,r,o){let i=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function _s(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),s=`/v1/inventory/${_(e)}/${_(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function ws(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/items/${_(r)}`;return t.client.get(i,o?.signal)}async function Ss(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let s=i.toString(),a=`/v1/leaderboards/${_(e)}/${_(n)}/${_(r)}`+(s?`?${s}`:"");return t.client.get(a,o?.signal)}async function Rs(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/orders/${_(r)}`;return t.client.get(i,o?.signal)}async function ks(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}`;return t.client.get(i,o?.signal)}async function As(t,e,n,r,o,i){let s=`/v1/inventory/${_(e)}/${_(n)}/catalogs/${_(r)}/recipes/${_(o)}/availability`;return t.client.get(s,i?.signal)}async function xs(t,e,n,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),s=`/v1/inventory/${_(e)}/${_(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Io(t,e,n,r,o){let i=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Ps(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${_(e)}/friends`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Ts(t,e,n){let r=`/v1/showcase/friends/${_(e)}`;return t.client.get(r,n?.signal)}async function Es(t,e){let n=`/v1/games/${_(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function Is(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}`;return t.client.get(r,n?.signal)}async function Cs(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${_(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Ms(t,e){let n=`/v1/games/${_(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function Xn(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Os(t,e,n){let r=`/v1/profiles/players/${_(e)}`;return t.client.get(r,n?.signal)}async function Gs(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Ls(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return t.client.get(r,n?.signal)}async function Ds(t,e,n,r){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.get(o,r?.signal)}async function Fs(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function $s(t,e,n){let r=`/v1/inventory/transfers/${_(e)}`;return t.client.get(r,n?.signal)}async function qs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function Ns(t,e,n){let r=`/v1/games/${_(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true,retryRateLimited:false})}async function js(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Us(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/platform-funded-game-inventory-purchases`;return t.client.post(i,r,o?.signal)}async function Bs(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Ws(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),o="/v1/challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Hs(t,e){return t.client.get("/v1/characters",e?.signal)}async function Vs(t,e,n,r){let o=`/v1/settings/${_(e)}/${_(n)}`;return t.client.get(o,r?.signal)}async function Ks(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),s=`/v1/inventory/${_(e)}/${_(n)}/orders`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Js(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),s=`/v1/saves/${_(e)}/${_(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function zs(t,e){let n=new URLSearchParams;e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Ys(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o="/v1/friends"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Xs(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Qs(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function Zs(t,e,n,r){let o=`/v1/games/${_(t.gameId())}/matches/${_(e)}/end`;return t.client.post(o,n,r?.signal)}async function el(t,e,n,r,o,i){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/max`;return t.client.post(s,o,i?.signal)}async function tl(t,e,n,r,o,i){let s=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.put(s,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function nl(t,e,n,r,o){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.put(i,r,o?.signal)}async function rl(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/rewarded-placements/${_(r)}/availability`;return t.client.get(i,o?.signal)}async function ol(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function il(t,e,n,r){let o=`/v1/characters/${_(e)}`;return t.client.patch(o,n,r?.signal)}async function al(t,e,n,r,o,i){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/upload-url`;return t.client.post(s,o,i?.signal,{replaySafe:true})}async function sl(t,e,n,r,o,i){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/reset`;return t.client.post(s,o,i?.signal)}async function ll(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.delete(r,n?.signal)}var j="gem-web-bridge",Zn={min:1,max:1},$m=65536,dl=8,Qn=5e3,cl=1024;var Ht=Object.create(null),er="__malformed";var Oo=Object.create(null),qm=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"]]);function tr(t){let e=Oo[t];if(e!==void 0)return e;for(let[n,r]of qm)if(t.startsWith(n))return r}function wt(t){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(t);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function Nm(t){let e;try{e=new URL(t);}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 jm(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Um(t){return /^[a-z_]+$/.test(t)}function Bm(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(t)&&!t.includes("--")}function Co(t,e,n){if(e>dl)return `nesting deeper than ${dl}`;if(++n.nodes>Qn)return `more than ${Qn} values`;if(n.bytes>n.cap)return `over the ${n.cap} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let o=t;if(n.seen.has(o))return "a repeated or cyclic object reference";if(n.seen.add(o),Array.isArray(t)){if(t.length>cl)return `an array of ${t.length} entries, over the ${cl} limit`;n.bytes+=2;for(let a of t){let l=Co(a,e+1,n);if(l)return l}return null}let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)return "a value that is not a plain object";n.bytes+=2;let s=t;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++n.nodes>Qn)return `more than ${Qn} values`;if(n.bytes+=a.length*3+4,n.bytes>n.cap)return `over the ${n.cap} byte limit`;let l=Co(s[a],e+1,n);if(l)return l}return null}function Wm(t,e=$m){let n={nodes:0,bytes:0,seen:new Set,cap:e},r=Co(t,0,n);return r?`message contains ${r}`:n.bytes>e?`message is over the ${e} byte limit`:null}var Hm={origin:[wt,"not a well-formed origin"],url:[Nm,"not a safe absolute http(s) URL"],bcp47:[jm,"not a well-formed BCP 47 tag"],code:[Um,"not a code of lower-case letters and underscores"],gameRef:[Bm,"not a game id or web address"]};function ul(t,e,n){for(let r of e){let o=n===""?r[0]:`${n}.${r[0]}`,i=t[r[0]];if(i==null){if(r[1]<"a")continue;return `${o}: required`}let s=Mo(i,r,o);if(s)return s}return null}function Mo(t,e,n){let r=e[1].toLowerCase();switch(r){case "u":return typeof t=="boolean"?null:Mo(t,typeof t=="string"?[e[0],"s",e[2]]:[e[0],"n",e[3],e[4]],n);case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e[2])return `${n}: exceeds ${e[2]} characters`;if(e[3]){let[o,i]=Hm[e[3]];if(!o(t))return `${n}: ${i}`}return null}case "n":case "i":return typeof t!="number"||!(r=="i"?Number.isInteger:Number.isFinite)(t)?`${n}: expected ${r=="i"?"integer":"number"}`:t<e[2]||t>e[3]?`${n}: out of range ${e[2]}..${e[3]}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let o=e[2];return o.includes(t)?null:`${n}: not one of ${o.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:ul(t,e[2],n);case "j":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "a":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e[2])return `${n}: exceeds ${e[2]} items`;let o=e[3],i=`${n}[]`;for(let s of t){if(s==null){if(o[1]<"a")continue;return `${i}: required`}let a=Mo(s,o,i);if(a)return a}return null}default:return `${n}: unknown kind ${String(r)}`}}var ml=Object.create(null);function k(t,e,n,r,o){return Ht[t]=n,r&&(Oo[t]=r),ml[t]=i=>{let s=Wm(i,o);if(s)return s;if(typeof i!="object"||i===null||Array.isArray(i))return "message: expected object";let a=i;return a.gem!==j?"gem: wrong protocol marker":a.type!==t?`type: expected ${t}`:ul(a,e,"")}}var H=["requestId","s",64],et=["outcome","e",["ok","declined","unavailable"]],tt=["reason","S",64,"code"];k("gem.handshake",[["versions","o",[["min","i",1,1e3],["max","i",1,1e3]]],["capabilities","A",64,["","s",64]],["embedder","s",2048,"origin"],["unbidden","B"]],30);k("gem.handshake.accept",[["v","i",1,1e3],["capabilities","A",64,["","s",64]]],5);k("gem.token",[["token","s",4096],["requestId","S",64],["generation","i",0,2147483647],["apiBaseUrl","S",512,"url"],["playerId","s",64],["gameId","s",64],["channel","e",["dev","test","release"]],["gameVersion","S",64],["expiresAt","i",0,4102444800],["chainEndsAt","i",0,4102444800],["allowDevTools","B"]],30);k("gem.token.denied",[H,["retryable","b"],["retryAfterMs","I",0,36e5],["reason","e",["chain_exhausted","unavailable"]],["correlationId","s",64]],30);k("gem.player",[["untrusted","o",[["displayName","s",64],["displayTag","S",80],["displayHandle","s",80]]],["playerId","S",64],["discriminator","S",8],["avatarIconUrl","S",2048,"url"],["avatarIconId","S",64],["avatar3dId","S",64],["avatar3dModelUrl","S",2048,"url"],["avatar3dIconUrl","S",2048,"url"],["avatars3d","A",8,["","o",[["family","s",32],["id","s",64],["modelUrl","s",256,"url"],["iconUrl","s",256,"url"]]]],["badges","A",2,["","o",[["itemId","s",64],["iconUrl","s",2048,"url"]]]],["displayTag","s",8],["avatarUrl","S",2048,"url"],["boost","O",[["multipliers","a",8,["","o",[["currencyId","s",64],["currencySlug","s",32],["multiplierBp","i",1e4,1e6]]]],["expiresInDays","I",1,7]]]],12);k("gem.pause",[["paused","b"]],120);k("gem.prefs",[["reducedMotion","b"],["muted","b"],["showFrameStats","B"],["music","B"],["sounds","B"],["locale","s",35,"bcp47"],["recommended","O",[["volume","i",0,100],["batterySaver","b"],["keyboardLayout","e",["wasd","arrows"]],["gamepadConfirm","e",["south","east"]],["vibration","b"],["lookSensitivity","I",20,400],["gamepadLookSensitivity","I",20,400],["invertLookY","B"],["touchMovement","S",16,"code"],["graphicsQuality","S",16,"code"],["graphicsQualityAuto","B"],["colorHelp","B"]]]],60);k("gem.cohorts",[["cohorts","a",8,["","o",[["experimentId","s",36],["variantKey","s",32]]]]],12,"cohorts");k("gem.earnAllowanceChanged",[],30,"earnAllowance");k("gem.viewport",[["insets","o",[["top","i",0,4096],["right","i",0,4096],["bottom","i",0,4096],["left","i",0,4096]]],["reserved","A",4,["","o",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384],["control","O",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384]]]]]]],60,"viewport");k("gem.deviceSettings",[["settings","J"]],12,"deviceSettings");k("gem.willTerminate",[["reason","e",["grant_expiring","session_ended","navigating","kill_switch"]],["graceMs","i",0,6e4]],10);k("gem.roomEvent",[["event","e",["updated","match_started","match_ready","match_failed","version_stale"]],["roomId","s",64],["matchId","S",64],["version","I",0,2147483647],["reason","S",64],["platform","E",["universal","mobile"]]],120,"rooms");k("gem.socketState",[["connected","b"],["reason","E",["connecting","dropped","watchdog","terminal"]]],12,"socketState");k("gem.seatedEvent",[["roomId","s",64]],60,"partySeating");k("gem.autoStartFailedEvent",[["roomId","s",64],["code","s",64]],30,"autoStartFailure");k("gem.ticketEvent",[["event","e",["queued","matched","expired","cancelled","failed"]],["ticketId","s",64],["partySize","I",1,64],["queuedAt","I",0,4102444800],["expiresAt","I",0,4102444800],["reason","S",64],["roomId","S",64]],60,"ticketEvents");k("gem.signalEvent",[["event","e",["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]],["matchId","s",64],["data","j"]],1800,"p2p");k("gem.dedicatedEvent",[["event","e",["answer","error","matchEnded"]],["matchId","s",64],["sdp","S",10240],["sessionId","S",64],["code","S",64],["message","S",256],["reason","S",64]],120,"dedicated");k("gem.partyResult",[H,["partyId","S",64]],30,"parties");k("gem.clusterTarget",[["clusterTargetId","s",64],["clusterTargetIds","A",3,["","s",64]]],12,"clusterTarget");k("gem.devtools",[["action","e",["open","close","toggle"]]],30,"devtools");k("gem.screenshot",[["maxWidth","i",1,7680],["maxHeight","i",1,4320]],6,"screenshot");k("gem.screenshot.denied",[["reason","e",["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]],["retryable","b"]],12,"screenshot");k("gem.requestContext",[],12,"feedbackContext");k("gem.gameContext",[["context","j"]],12,"feedbackContext");k("gem.signal",[["signal","e",["join","offer","answer","ice","migrationAck","hostUnreachable"]],["matchId","s",64],["data","j"]],1200,"p2p");k("gem.dedicatedOffer",[["matchId","s",64],["sdp","s",10240],["intent","e",["initial","ice_restart","full_reconnect"]]],60,"dedicated");k("gem.partyRequest",[H],12,"parties");k("gem.ready",[],5);k("gem.engaged",[],5,"engagement");k("gem.progress",[["loaded","i",0,1099511627776],["total","i",0,1099511627776]],600);k("gem.requestToken",[H,["reason","e",["initial","expiring","rejected"]]],12);k("gem.requestLocalServer",[H,["gameRoomId","s",64]],6,"localHost");k("gem.localServer",[H,["serverId","S",128]],30,"localHost");k("gem.localServer.denied",[H,["retryable","b"],["reason","e",["refused","unavailable"]]],30,"localHost");k("gem.exit",[["reason","S",64]],5);k("gem.openExternal",[["url","s",2048,"url"]],6);k("gem.requestFullscreen",[["enabled","b"]],30);k("gem.audioState",[["muted","b"]],120,"audioState");k("gem.rewardCue",[["currencySlug","s",32],["expected","I",1,1e9],["origin","O",[["x","i",0,16384],["y","i",0,16384]]]],60,"rewardCue");k("gem.walletDisplay",[["visible","b"],["currencies","A",8,["","s",64]],["score","B"]],60,"walletDisplay");k("gem.controlsDeclare",[["uses","o",[["lookSensitivity","S",16,"code"],["gamepadLookSensitivity","S",16,"code"],["invertLookY","S",16,"code"],["touchMovement","S",16,"code"]]]],60,"controls");k("gem.menu",[["settings","b"],["items","A",4,["","o",[["id","s",32],["label","s",40]]]]],60,"gameMenu");k("gem.menuSelect",[["entry","e",["settings","item"]],["id","S",32]],60,"gameMenu");k("gem.gemCorner",[["corner","e",["top-left","top-right","bottom-left","bottom-right"]]],12,"gemCorner");k("gem.settingsDeclare",[["settings","a",8,["","o",[["id","s",40],["label","s",40],["kind","e",["toggle","slider","choice"]],["value","u",40,-1e6,1e6],["quick","B"],["icon","S",16,"code"],["min","N",-1e6,1e6],["max","N",-1e6,1e6],["step","N",0,1e6],["options","A",4,["","o",[["id","s",40],["label","s",40]]]]]]]],120,"gameSettings");k("gem.settingChange",[["id","s",40],["value","u",40,-1e6,1e6]],120,"gameSettings");k("gem.requestShare",[["params","a",16,["","o",[["key","s",64],["value","s",512]]]]],6,"share");k("gem.requestAvatarPicker",[["tab","E",["2d","3d"]]],6,"avatarPicker");k("gem.vibrate",[["pattern","a",99,["","i",0,1e4]]],600,"vibration");k("gem.frameStats",[["fps","i",0,1e3],["frameTimeP95Ms","i",0,1e5],["counts","E",["pageFrames","gameDraws"]]],120,"frameStats");k("gem.portraitBorders",[["name","S",40]],60,"portraitBorders");k("gem.error",[["code","e",["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]],["message","S",256]],60);k("gem.requestPurchase",[H,["purchaseKind","e",["item","recipe"]],["targetId","s",64],["currencySlug","s",32],["quantity","I",1,10],["catalogId","S",64]],12,"purchases");k("gem.requestAvatar3dPurchase",[H,["itemId","s",64],["currencySlug","s",32]],12,"avatar3dPurchases");k("gem.purchaseResult",[H,et,tt,["purchaseId","S",64]],30,"purchases");k("gem.deviceSettings.put",[H,["settings","j"]],30,"deviceSettings");k("gem.deviceSettings.result",[H,["outcome","e",["stored","too_large","unavailable"]]],30,"deviceSettings");k("gem.requestAd",[H,["placement","s",32],["format","e",["interstitial","rewarded"]]],6,"ads");k("gem.adResult",[H,["outcome","e",["shown","no_ad","unavailable"]]],12,"ads");k("gem.signalMoment",[H,["kind","e",["level_end","run_end","match_end","menu_return","other_break"]],["placement","S",32]],6,"moments");k("gem.momentResult",[H,["shown","b"]],12,"moments");k("gem.requestSignIn",[H],6,"signIn");k("gem.signInResult",[H,["outcome","e",["signed_in","declined","unavailable"]]],12,"signIn");k("gem.requestFriendChallenge",[H,["playerId","s",64],["template","s",64],["params","J"]],12,"friendChallenges");k("gem.friendChallengeResult",[H,["outcome","e",["accepted","cancelled","refused","unavailable","rate_limited","invalid"]],["code","S",64],["param","S",64],["channel","S",16],["configVersion","I",0,9007199254740991],["retryAfterMs","I",0,864e5],["detail","S",300]],30,"friendChallenges");k("gem.requestAppLinks",[H],12,"appLinks");k("gem.appLinksResult",[H,et,tt,["arcade","O",[["store","e",["app_store","google_play"]]]],["game","O",[["store","e",["app_store","google_play"]]]]],30,"appLinks");k("gem.requestOpenApp",[H,["target","e",["arcade","game"]]],6,"appLinks");k("gem.openAppResult",[H,et,tt],30,"appLinks");var pl=k("gem.requestOpenGame",[H,["ref","s",40,"gameRef"]],6,"openGame");k("gem.openGameResult",[H,et,tt],30,"openGame");k("gem.requestSimilarGames",[H,["limit","I",1,24]],12,"openGame");k("gem.similarGamesResult",[H,et,tt,["games","a",24,["","o",[["gameId","s",36,"gameRef"],["slug","S",40,"gameRef"],["iconUrl","s",1024,"url"],["capsuleLandscapeUrl","s",1024,"url"],["capsulePortraitUrl","s",1024,"url"],["previewVideoUrl","S",1024,"url"],["previewPosterUrl","S",1024,"url"],["untrusted","o",[["name","s",64],["tagline","s",64],["shortDescription","s",320],["tags","a",10,["","s",32]]]]]]]],30,"openGame",524288);k("gem.requestStoreOffers",[H],12,"store");k("gem.storeOffersResult",[H,et,tt,["offers","a",32,["","o",[["skuId","s",64],["kind","e",["gem_pack","boost","pass","bundle"]],["name","s",80],["description","s",400],["imageUrl","S",1024,"url"],["priceDisplay","s",32],["grant","O",[["currency","s",32],["amount","i",1,1e9]]]]]]],30,"store",262144);k("gem.requestStorePurchase",[H,["skuId","s",64]],12,"store");k("gem.storePurchaseResult",[H,et,tt],30,"store");k("gem.storePurchaseSettled",[["skuId","s",64]],30,"store");var nr=Object.freeze(ml);Ht.__malformed=60;Object.freeze(Ht);Object.freeze(Oo);var ue={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Vt=class{constructor(e=ue){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Ht[e];if(n===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??n,s=Math.max(0,r-o),a=Math.min(n,i+s*n/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function St(t,e){return t.toLowerCase()===e.toLowerCase()}function He(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function rr(t,e){if(typeof e!="string"||e==="")return false;let n,r;try{n=new URL(t),r=new URL(e);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||n.username!==""||n.password!==""||n.pathname!=="/"||n.search!==""||n.hash!==""||n.port===""?false:He(n.hostname)&&He(r.hostname)}function gl(t,e){if(e.min>e.max)return null;let n=Math.min(t.max,e.max),r=Math.max(t.min,e.min);return n>=r?n:null}var or=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}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,n={}){let o=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,i=o.find(a=>a.currencyId===e),s;return !i&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(i=o.find(a=>a.currencyId===s))),{currencyId:i?i.currencyId:s??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function Lo(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let o=r??{};typeof o.id!="string"||o.id===""||typeof o.threshold!="number"||!Number.isFinite(o.threshold)||n.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 {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var yl="inventory",Rt=t=>typeof t=="number"?t:0,Kt=t=>typeof t=="string"?t:"";function Go(t,e){let n=t??{},r=typeof n.next_cursor=="string"?n.next_cursor:void 0;return {data:Array.isArray(n.data)?n.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function fl(t){let e=t??{};return {itemDefinitionId:Kt(e.item_definition_id),instanceId:Kt(e.instance_id),quantity:Rt(e.quantity),acquiredAt:Rt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function Vm(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Go(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(s=>{let a=s??{};return {bucket:Kt(a.bucket),balance:Rt(a.balance)}}):void 0;return {currencyId:Kt(o.currency_id),total:Rt(o.total),...i===void 0?{}:{buckets:i}}}),items:Go(e.items,fl),progressions:Go(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:Kt(o.progression_definition_id),currentValue:Rt(o.current_value),completionCount:Rt(o.completion_count),isCompleted:o.is_completed===true,...Lo(o)}}),...n===void 0?{}:{etag:n}}}var ir=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${yl}#buckets`:yl;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let i=r.items.data.filter(s=>s.itemDefinitionId===e);if(i.length>0)return i}let o=await ws(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(fl):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let n=await _s(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 Vm(n)}};var Km={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,already_owned:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},Jm=new Set(Object.keys(Km));function hl(t){return typeof t=="string"&&Jm.has(t)?t:"error"}var Ve=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var re=t=>typeof t=="string"?t:"",zm=t=>typeof t=="string"?t:re(t&&typeof t=="object"?t.type:void 0),Ie=t=>typeof t=="number"?t:0;function Ym(t){let e=t??{};return {prerequisiteType:re(e.prerequisite_type),referenceId:re(e.reference_id),required:Ie(e.required),current:Ie(e.current)}}function Jt(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:re(e.order_id),status:re(e.status),...n===void 0?{}:{etag:n}}}function ar(){return crypto.randomUUID()}var Xm="recipe-usage",bl=100;function sr(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:re(e.currency_id),bucket:re(e.bucket),delta:Ie(e.delta),balanceAfter:Ie(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:re(e.item_definition_id),instanceId:re(e.instance_id),delta:Ie(e.delta),quantityAfter:Ie(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:re(e.progression_definition_id),delta:Ie(e.delta),valueAfter:Ie(e.value_after),completed:e.completed===true};default:return {kind:"other",type:re(e.type)}}}function Qm(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:re(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Ie(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(sr):[]}}function Zm(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(Qm):void 0;return {orderId:re(e.order_id),status:re(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(sr):[],consumed:Array.isArray(e.consumed)?e.consumed.map(sr):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(sr):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function ep(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:re(e.target_order_id)||re(e.source_order_id),status:re(e.status),purchaseId:re(e.purchase_id),sourceOrderId:re(e.source_order_id),price:{currencyId:re(n.platform_currency_id),amount:Ie(n.price)}}}function tp(t){let e=t??{},n=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:re(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...n===void 0?{}:{lastUsedAt:n},...r===void 0?{}:{cooldownExpiresAt:r}}}function vl(t){switch(t.type){case "currency_grant":case "currency_consume":return {type:t.type,currency_id:t.currencyId,amount:t.amount};default:return {type:t.type,item_definition_id:t.itemDefinitionId,quantity:t.quantity}}}var lr=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;async create(e,n={}){let r=await this.write(()=>ls(this.api,this.entity.type,this.entity.id,{operations:e.map(vl),source:n.source??"play",nonce:ar()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Jt(r)}async createMany(e,n={}){return this.write(()=>ss(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(vl),nonce:ar()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let i=await As(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},s=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,a=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(Ym):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>zm(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(Xm,[],async()=>{let n=await xs(this.api,this.entity.type,this.entity.id,{limit:bl})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(tp),truncated:r.length>=bl}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>ps(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:ar()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...Zm(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([Gs(this.api,n.signal===void 0?{}:{signal:n.signal}),Xn(this.api,n.signal===void 0?{}:{signal:n.signal})]),i=e.payment.currencySlug.toLowerCase(),s=o.currencies.find(c=>c.currency_id.toLowerCase()===i||c.slug.toLowerCase()===i);if(s===void 0){let c=o.currencies.map(p=>p.slug);throw new Ve("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let a=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(a===void 0)throw new Ve("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=a.platform_prices.find(c=>c.platform_currency_id===s.currency_id);if(l===void 0){let c=g=>o.currencies.find(y=>y.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${c(g.platform_currency_id)} ${g.price}`);throw new Ve("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Ve("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>Us(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:s.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:ar(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return ep(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let o=await this.write(()=>ns(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Jt(o)}async maxProgression(e,n,r){let o=await this.write(()=>el(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Jt(o)}async claimProgression(e,n){let r=await this.write(()=>is(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Jt(r)}async resetProgression(e,n){let r=await this.write(()=>sl(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Jt(r)}async write(e){return this.cache.invalidate(),e()}};var Do=t=>typeof t=="string"?t:"",np=t=>typeof t=="number"?t:0;function _l(t){let e=t??{};return {orderId:Do(e.order_id),status:Do(e.status),source:Do(e.source),createdAt:np(e.created_at)}}var dr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await Ks(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(_l):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Rs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return _l(r)}};var wl=t=>typeof t=="number"?t:0,rp=t=>typeof t=="string"?t:"";function op(t){let e=t??{};return {progressionDefinitionId:rp(e.progression_definition_id),currentValue:wl(e.current_value),completionCount:wl(e.completion_count),isCompleted:e.is_completed===true,...Lo(e)}}var cr=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let o=(await this.inventory.snapshot()).progressions.data.find(i=>i.progressionDefinitionId===e);if(o&&o.achievementsUnavailable!==true)return o;try{let i=await ks(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return op(i)}catch{return o??null}}};var ur=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,o){this.rebind();let i=n.length===0,s=i?e:e+"\0"+n.join("\0"),a=this.slots.get(s);if(a){let c=a.filledAt;if(c!==void 0&&(o===void 0||this.clock.now()-c<=o))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,m=r().then(c=>(i&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function Fo(t){let e=o=>new RegExp(`<${o}>([^<]{0,300})</${o}>`).exec(t)?.[1]?.trim()||void 0,n=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(n.length>0)return n.join(" \u2014 ");let r=t.trim();return r?r.slice(0,300):""}async function $o(t){try{let e=Fo(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var le=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},ip=3e4,Sl="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",ap=/^[A-Za-z0-9_]{1,64}$/;function Ce(t){let e=t.length===0?"a save key cannot be empty":t.length>64?`it is ${t.length} characters; a save key is at most 64`:t.startsWith("_")||t.startsWith("$")?`it begins with ${JSON.stringify(t[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(!ap.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Rl(t,e){let n=new AbortController,r=AbortSignal.timeout(e),o=()=>n.abort(r.reason),i=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",i,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",o),t?.removeEventListener("abort",i);}}}function qo(t,e){return t.aborted&&e?.aborted!==true}var sp=new Set(["x-ms-blob-type"]),lp=/^[ -~]+$/;function dp(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new le("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,o]of Object.entries(t)){let i=r.toLowerCase();if(!sp.has(i))throw new le("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"||!lp.test(o))throw new le("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 n)throw new le("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function No(t){let e=typeof t.metadata=="object"&&t.metadata!==null&&!Array.isArray(t.metadata)?t.metadata:void 0;return {key:t.key,sizeBytes:t.size_bytes,etag:t.etag,...e===void 0?{}:{metadata:e},createdAt:t.created_at,updatedAt:t.updated_at}}function jo(t){return t?.reason==="not_found"}var mr=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let o;try{o=JSON.stringify(n);}catch(i){throw new le("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 le("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,n,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),s=Rl(r.signal,i);try{let a=await al(this.api,this.entity.type,this.entity.id,Ce(e),{size_bytes:n.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:s.signal});if(typeof a.upload_url!="string"||typeof a.session_id!="string")throw new le("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=dp(a.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(a.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:n,credentials:"omit",signal:s.signal});}catch(c){throw qo(s.signal,r.signal)?this.timeout("upload",i):new le("upload_failed",`${Sl} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await $o(d);throw new le("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+c:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+c)}return No(await gs(this.api,this.entity.type,this.entity.id,Ce(e),{session_id:a.session_id},{signal:s.signal}))}catch(a){throw this.rethrow(a,r.signal,s.signal,"save",i)}finally{s.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new le("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,n={}){let r=this.budget(n.timeoutMs),o=Rl(n.signal,r);try{let i;try{let l=await Io(this.api,this.entity.type,this.entity.id,Ce(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(jo(l))return null;throw l}if(typeof i.download_url!="string")throw new le("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let s=this.options.fetch??globalThis.fetch.bind(globalThis),a;try{a=await s(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw qo(o.signal,n.signal)?this.timeout("download",r):new le("download_failed",`${Sl} for GET. Underlying error: ${l}`)}if(!a.ok){let l=await $o(a);throw new le("download_failed",`the save download answered ${a.status}. `+(a.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await a.arrayBuffer())}catch(i){throw this.rethrow(i,n.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,n={}){try{let r=await Io(this.api,this.entity.type,this.entity.id,Ce(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?No(r.body):null}catch(r){if(jo(r))return null;throw r}}async list(e={}){let n=await Js(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=n.next_cursor;return {saves:(n.data??[]).map(No),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await us(this.api,this.entity.type,this.entity.id,Ce(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!jo(r))throw r}}budget(e){return e??this.options.timeoutMs??ip}timeout(e,n){return new le("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof le?e:qo(r,n)?this.timeout(o,i):e}};function cp(t){try{return Eo(t)}catch{return t}}function Uo(t,e){let n=t??{},r=typeof n.etag=="string"?n.etag:e;return {key:typeof n.key=="string"?n.key:"",value:typeof n.value=="string"?cp(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var pr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await Vs(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>Uo(o)):[]}async get(e,n={}){try{let r=await vs(this.api,this.entity.type,this.entity.id,e,{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Uo(r.body,r.etag):null}catch(r){if(kl(r))return null;throw r}}async put(e,n,r={}){let o=await tl(this.api,this.entity.type,this.entity.id,e,{value:zn(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Uo(o)}async delete(e,n){try{await cs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!kl(r))throw r}}};function kl(t){return t?.reason==="not_found"}function gr(t,e,n={}){let r=new ur(ue,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new ir(t,e,r);return {settings:new pr(t,e),inventory:o,saves:new mr(t,e,n.saves??{}),currencies:new or(o,n.resolveCurrencyId),mutations:new lr(t,e,r),orders:new dr(t,e),progressions:new cr(t,e,o)}}var Bo={type:"players",id:"me"};var nt=t=>typeof t=="string"?t:"",kt=t=>typeof t=="number"?t:0;function yr(t,e){let n=e??{},r=nt(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:nt(n.player_id),gameId:nt(n.game_id),channel:nt(n.channel)||"release",name:nt(n.name),slotIndex:kt(n.slot_index),isActive:n.is_active!==false,createdAt:nt(n.created_at),updatedAt:nt(n.updated_at)}}var fr=class{constructor(e,n,r,o){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=o;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=gr(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};async list(e){let r=(await Hs(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>yr(this.scope,o)):[]}async get(e,n){let r=await hs(this.api,e,n===void 0?{}:{signal:n});return yr(this.scope,r)}async create(e){let n=await as(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return yr(this.scope,n)}async update(e,n,r){let o=await il(this.api,e,{name:n},r===void 0?{}:{signal:r});return yr(this.scope,o)}async delete(e,n){await ll(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await Fs(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:kt(r?.total_slots),availableSlots:kt(r?.available_slots),activeCharacterCount:kt(r?.active_character_count),defaultMaxSlots:kt(r?.default_max_slots),purchasedExtraSlots:kt(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var Pl="[gem: use gem.text.toPlain()]",Al=new Set,xl;function up(t){try{if(Al.has(t))return;let e=globalThis.location;if(xl??=!!e?.port&&He(e.hostname??""),!xl)return;Al.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${Pl}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
2
- ${new Error().stack}`);}catch{}}var ve=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return up(this.#n),Pl}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function he(t,e){return new ve(t,e)}var rt={toPlain(t){return ve.unwrap(t)},compare(t,e,n){let r=t instanceof ve?ve.unwrap(t):t,o=e instanceof ve?ve.unwrap(e):e;if(typeof Intl>"u"||typeof Intl.Collator!="function")return r<o?-1:r>o?1:0;let i;try{i=new Intl.Collator(n);}catch{i=new Intl.Collator;}return i.compare(r,o)},equals(t,e){let n=t instanceof ve?ve.unwrap(t):t,r=e instanceof ve?ve.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var At=t=>typeof t=="string"?t:"";function hr(t){let e=t??{},n=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:At(e.transfer_id),status:At(e.status),sourceEntityId:At(e.source_entity_id),targetEntityId:At(e.target_entity_id),...n===void 0?{}:{message:he(n,"transfer.message")},createdAt:At(e.created_at),expiresAt:At(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function mp(){return crypto.randomUUID()}var br=class{constructor(e,n,r){this.api=e;this.self=n;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let n=await js(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:mp()},e.signal===void 0?{}:{signal:e.signal});return hr(n)}async list(e={}){let r=await Xs(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(hr):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await $s(this.api,e,n===void 0?{}:{signal:n});return hr(r)}async accept(e,n){return this.resolve(()=>ts(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>ol(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>rs(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),hr(await e())}};var pp=t=>typeof t=="string"?t:"",gp=t=>typeof t=="string"&&t?t:void 0,yp=t=>typeof t=="number"?t:void 0;function Tl(t){let e=new Map(t.map(r=>[r.id,r])),n=new Map(t.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??n.get(r)??null}function fp(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new pe("config_malformed",`the config document is ${t===null?"null":typeof t}, expected a JSON object`);let e=t,n=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new pe("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=yp(e.version);if(r===void 0)throw new pe("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let c=pp(l.id);if(!c)throw new pe("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},i=n("items");i.forEach((l,d)=>o(l??{},"items",d));let s=n("currencies");s.forEach((l,d)=>o(l??{},"currencies",d));let a=t;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:i,currencies:s,catalogs:n("catalogs"),loot_tables:n("loot_tables"),affix_pools:n("affix_pools"),progressions:n("progressions"),game_room_templates:n("game_room_templates"),kv:typeof a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:Tl(i),currency:Tl(s)}}var pe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},El=10*1024*1024,Il=15e3,Cl=new Set(["dev","test","release"]);function hp(t){if(!Cl.has(t))throw new pe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Cl].join(", ")}. gem-api would reject the assignment read.`);return t}var vr=t=>typeof t=="number"?t:0,Wo=t=>typeof t=="string"?t:"";function bp(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let o=r??{},i=typeof o.rarity_tier=="string"?o.rarity_tier:void 0;return {entryId:Wo(o.entry_id),weight:vr(o.weight),dropRate:vr(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:Wo(e.loot_table_id),name:Wo(e.name),rollCount:vr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:vr(e.total_weight),entries:n}}var _r=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=void 0;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded!==void 0)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,n=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===n&&(this.inFlight=null);});return this.inFlight=n,n}refresh(){this.loaded=void 0,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new pe("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let o=this.dropRatesByConfig.get(r);o===void 0&&(o=new Map,this.dropRatesByConfig.set(r,o));let i=o.get(e);if(i!==void 0)return i;let s=(async()=>{let a=await bs(this.api,e,n===void 0?{}:{signal:n});return bp(a)})().catch(a=>{throw o?.get(e)===s&&o.delete(e),a});return o.set(e,s),s}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??Il),n;try{let l=await fs(this.api,hp(this.channel()),{signal:e});if(!l.modified)throw new pe("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof pe)throw l;if(l?.reason==="not_found")return null;throw l}let r=gp(n.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 pe("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??Il}ms`):new pe("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=>Fo(d)).catch(()=>"");throw new pe("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await i.text();if(s.length>El)throw new pe("config_too_large",`the config document is ${s.length} bytes, over the ${El} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new pe("config_malformed",`config document is not JSON: ${String(l)}`)}return fp(a)}};var Ml=400,Me=t=>typeof t=="string"?t:"",vp=/(?:Z|[+-]\d{2}:?\d{2})$/i;function ot(t){let e=Me(t);if(!vp.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var _p=/^[0-9a-f]{1,64}$/,wp=/^[0-9a-f]{16}$/,Sp=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Rp=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Ho(t){let e=Me(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,o,i]=[Number(n[1]),Number(n[2]),Number(n[3])],s=new Date(Date.UTC(r,o-1,i));return s.getUTCFullYear()===r&&s.getUTCMonth()===o-1&&s.getUTCDate()===i?e:void 0}var kp=4096,Ap=new TextEncoder;function xp(t){let e=Me(t.challenge_data),n=Me(t.challenge_data_hash);return e===""||!wp.test(n)?{}:Ap.encode(e).length>kp?{}:{data:e,dataHash:n}}function Pp(t){let e=t??{},n=ot(e.period_start_at),r=ot(e.period_ends_at);if(n===0||r===0)return;let o=Me(e.slug),i=Me(e.seed),s=Ho(e.period_local_date),a=Me(e.boundary),l=Me(e.reset_time);return {id:Me(e.progression_definition_id),...o===""?{}:{slug:o},window:Me(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:Sp.test(a)?a:"",resetTime:Rp.test(l)?l:"",seed:_p.test(i)?i:"",...xp(e)}}function xt(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function wr(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Pp).filter(n=>n!==void 0):[]}var zt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;xt(n);let r=await Ws(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return wr(r)}};function Oe(t){return typeof t=="string"&&t!==""?t:void 0}var Ol=new Set(["localhost","127.0.0.1","[::1]"]);function it(t){return Sr(t)}function Sr(t){let e=Oe(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&Ol.has(n.hostname)))return e}var Tp=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Ep=/^[a-z][a-z0-9_]{0,31}$/;function Ip(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let o=r??{},i=Oe(o.family),s=Oe(o.avatar_3d_id),a=it(o.model_url),l=it(o.icon_url);i===void 0||!Ep.test(i)||n.has(i)||s===void 0||!Tp.test(s)||a===void 0||l===void 0||(n.add(i),e.push({family:i,id:s,modelUrl:a,iconUrl:l}));}return e}function Cp(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=Oe(r.item_id),i=it(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function Pe(t){let e=t??{},n=Oe(e.player_id),r=Oe(e.display_name),o=Oe(e.discriminator),i=Oe(e.display_tag),s=Oe(e.avatar_icon_id),a=it(e.avatar_icon_url),l=Oe(e.avatar_3d_id),d=it(e.avatar_3d_model_url),m=it(e.avatar_3d_icon_url),c=Ip(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:he(r,"displayName")},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:he(i,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...m===void 0?{}:{avatar3dIconUrl:m},...c===void 0?{}:{avatars3d:c},badges:Cp(e.badges)}}var Mp=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Op(t){if(t===void 0)return;let e=it(t);if(e===void 0)return;let n=new URL(e);return Ol.has(n.hostname)||Mp.has(n.origin)?e:void 0}var Gl=100,Fl=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Vo(t){let{periodsBack:e,period:n,playerId:r}=t;if(xt(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!Fl.test(n)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(n)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...n===void 0?{}:{period:n},...r===void 0?{}:{player_id:r}}}function $l(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!Fl.test(e))return;let n=Ho(t.period_local_date),r=ot(t.period_start_at),o=ot(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:ot(t.opens_at),closesAt:ot(t.closes_at),final:t.final===true}}var Yt=t=>typeof t=="string"?t:"",Pt=t=>typeof t=="number"?t:0,Xt=t=>typeof t=="string"?t:void 0,Gp=t=>typeof t=="number"?t:void 0,ql={player:"players",character:"characters"};function Lp(t,e){let n=t??{},r=Xt(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(ql,n.entity_type)?n.entity_type:void 0,i=Nl(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...Pe(n),rank:Pt(n.rank),occurredAt:Pt(n.occurred_at),...a===void 0?{}:{isViewer:a},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...s===void 0?{}:{properties:s}}}function Ll(t,e){let n=t??{},r=Xt(n.bucket_1),o=Xt(n.bucket_2),i=Gp(n.update_frequency_seconds),s=$l(n);return {leaderboardType:Yt(n.leaderboard_type),runType:Yt(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(a=>Lp(a,e)):[],generatedAt:Pt(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...s===void 0?{}:{period:s}}}function Dl(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=Nl(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:Pt(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function Nl(t){if(t===null||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t))typeof r=="number"&&(e[n]=r);return e}function Dp(t,e,n){let r=t??{},o=Xt(r.bucket_1),i=Xt(r.bucket_2),s=$l(r);return {leaderboardType:Yt(r.leaderboard_type),runType:Yt(r.run_type),entityType:e,entityId:n,...o===void 0?{}:{bucket1:o},...i===void 0?{}:{bucket2:i},entries:Array.isArray(r.entries)?r.entries.map(Dl).filter(a=>a!==void 0):[],personalBest:Dl(r.personal_best)??null,totalRuns:Pt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:Pt(r.generated_at),...s===void 0?{}:{period:s}}}var Qt=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Vo(n),o=await Cs(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Ll(o,false)}async friends(e,n={}){let r=Vo(n),o=await Ps(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Ll(o,true)}async mine(e,n={}){return this.#n(e,"player","me",n)}async character(e,n,r={}){return this.#n(e,"character",n,r)}async#n(e,n,r,o){if(o.limit!==void 0){let{limit:l}=o;if(!Number.isInteger(l)||l<1||l>Gl)throw new TypeError(`limit must be an integer between 1 and ${Gl}, got ${String(l)}`)}let i=Vo(o),s=await Ss(this.#e,e,ql[n],r,{...i,...o.bucket1===void 0?{}:{bucket_1:o.bucket1},...o.bucket2===void 0?{}:{bucket_2:o.bucket2},...o.limit===void 0?{}:{limit:o.limit},...o.signal===void 0?{}:{signal:o.signal}}),a=n==="player"&&r==="me"&&Yt((s??{}).entity_id)||r;return Dp(s,n,a)}};var Rr=t=>typeof t=="string"?t:"",Ko=t=>typeof t=="number"?t:0;function jl(t){let e=t??{};return {playerId:Rr(e.player_id),key:Rr(e.key),value:e.value,updatedAt:Ko(e.updated_at)}}function Fp(t){let e=t??{};return {...Pe(e),playerId:Rr(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Ko(e.updated_at)}}function $p(t){return t?.reason==="not_found"}var Zt=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await Ts(this.api,Ce(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:Rr(o.key),entries:Array.isArray(o.entries)?o.entries.map(Fp):[],generatedAt:Ko(o.generated_at)}}async of(e,n,r={}){try{return jl(await Ds(this.api,e,Ce(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if($p(o))return null;throw o}}async set(e,n,r={}){if(Ce(e),n===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(n);}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 jl(await nl(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await ms(this.api,r,Ce(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var qp="gemChallenge",Ul=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Bl(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(qp)??void 0}catch{return}}var at=class extends O{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,o]of Object.entries(n))o!==void 0&&Object.assign(this,{[r]:o});}},kr=t=>typeof t=="string"?t:void 0;function Wl(t){let e=t??{};return {...Pe(e),playerId:kr(e.player_id)??""}}function Hl(t){let e=t.has_more===true?kr(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function Np(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(Wl):[],...Hl(e)}}var Jo=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function jp(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function Vl(t){let e=t??{},n=Jo(e.opened_at),r=Jo(e.answered_at);return {id:kr(e.item_id)??"",from:Wl(e.sender),template:kr(e.template)??"",params:jp(e.params),createdAt:Jo(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function Up(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(Vl):[],...Hl(e)}}function Bp(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var en=class{#e;#n;#i;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#i=n.launchedChallengeId;}async list(e={}){let n=await Ys(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Np(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await zs(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Up(n)}async launchedChallenge(e={}){let n=this.#i;if(n===void 0||!Ul.test(n))return null;try{return Vl(await Is(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(Bp(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!Ul.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 Qs(this.#e,e);}};var Wp=0;function _e(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++Wp)}-${String(Date.now())}-${t}`}}var Hp=12e4,Kl=8,Vp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Kp=/^[a-z0-9][a-z0-9_-]{0,63}$/;function tn(t,e,n={}){return new at(new O("invalid",400,e,void 0,t),n)}function Jp(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function zp(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!Vp.test(e))return {error:tn("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!Kp.test(n))return {error:tn("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:n,params:void 0};if(!Jp(r))return {error:tn("param_invalid","params must be a plain object of strings and integers")};let o={},i=Object.keys(r);for(let s of i){let a=r[s];if(typeof a=="string"||typeof a=="number"&&Number.isSafeInteger(a)){Object.defineProperty(o,s,{value:a,enumerable:true,writable:true,configurable:true});continue}return {error:tn("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return i.length>Kl?{error:tn("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(Kl)}`)}:{playerId:e,template:n,params:o}}function Yp(t){switch(t.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:t.outcome}};case "rate_limited":{let e=t.retryAfterMs,n=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new at(new O("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new at(new O("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function Xp(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function Jl(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=zp(n);if("error"in r)return Promise.reject(r.error);let o=`challenge-${_e()}`;return new Promise((i,s)=>{let a={},l=m=>{e.delete(o)&&(t.clock.clearTimeout(a.timer),"error"in m?s(m.error):i(m.outcome));};e.set(o,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??Hp);let d=false;try{d=t.bridge.requestFriendChallenge(o,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(n){let r=e.get(n.requestId);if(r===void 0){t.onDropped?.(`gem.friendChallengeResult (${Xp(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(Yp(n));}}}var Ar=t=>typeof t=="string"?t:void 0;function Qp(t){let e=t??{},n=Ar(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Ar(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var xr=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await Xn(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=Qp(i);s!==void 0&&o.push(s);}return o}},zo=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function Zp(t){let e=t??{},n=Ar(e.currency_id);if(n===void 0||n==="")return;let r=zo(e.limit),o=Math.min(zo(e.earned),r),i=Math.min(zo(e.remaining),r-o),s=e.period_days,a=typeof s=="number"&&Number.isInteger(s)&&s>=1?s:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Ar(e.currency_slug)??"",currencyId:n,limit:r,earned:o,remaining:i,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function zl(t){let e=new Set,n=r=>{t?.(`[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,n);}catch(o){n(o);}}}}var Pr=class{#e;#n;#i;constructor(e,n,r){this.#e=e,this.#n=n,this.#i=r;}async get(e={}){let r=(await Ms(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=Zp(i);s!==void 0&&o.push(s);}return o}on(e,n){return e!=="changed"?(this.#i?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},nn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new xr(e),this.earnAllowance=new Pr(e,n,r);}};var Yo=t=>typeof t=="string"?t:"",Yl=t=>typeof t=="number"?t:0;function eg(t){let e=t??{};return {key:Yo(e.key),visibility:Yo(e.visibility),value:e.value,updatedAt:Yl(e.updated_at)}}function tg(t){let e=t??{};return {...Pe(e),playerId:Yo(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(eg):[],generatedAt:Yl(e.generated_at)}}function ng(t){return t?.reason==="not_found"}var rn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return tg(await Os(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(ng(r))return null;throw r}}};var rg=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]]),on=class extends O{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:rg.get(this.code))??super.retryable}},Ke=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=og(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof O?ag(i):i}return ig(o)}};function og(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let e;try{e=JSON.stringify(t);}catch(n){throw new ae(`the function input could not be serialised to JSON: ${String(n)}. 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 ae(`the function input is ${typeof t}, 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 ig(t){let{bytes:e}=t,n=()=>new TextDecoder("utf-8",{fatal:true}).decode(e);return {bytes:e,...t.invocationId===void 0?{}:{invocationId:t.invocationId},text:n,json:()=>JSON.parse(n())}}function ag(t){let{details:e,invocationId:n}=es(t),o=e?.untrusted?.message,i=e?.reason;return new on(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof o=="string"?{functionMessage:o}:{},...t.code==="function_failed"&&typeof i=="string"?{failure:i}:{}})}function Tr(t,e){let n=e?.retryAfterSeconds,r=typeof n=="number"&&Number.isFinite(n)&&n>0?n*1e3:0,o=1e4*2**Math.min(Math.max(0,t-1),16);return Math.min(Math.max(r,o),3e5)}var sg=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Xo="gem_";function Xl(t){return t.startsWith(Xo)}function lg(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function dg(t){let e=t;return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^=e>>>16,e>>>0}function Er(t,e,n){if(Qo(t,n),typeof e!="string"||e==="")throw new TypeError("[gem] experiment: playerId must be a non-empty string");let r=typeof n=="number"?n:n.length,o=dg(lg(`${t}:${e}`))%r;return typeof n=="number"?o:n[o]}function Qo(t,e){if(typeof t!="string"||t==="")throw new TypeError("[gem] experiment: key must be a non-empty string");if(typeof e=="number"){if(!Number.isInteger(e)||e<1||e>2048)throw new RangeError(`[gem] experiment '${t}': the count must be an integer from 1 to 2048; got ${String(e)}`);return}if(!Array.isArray(e))throw new TypeError(`[gem] experiment '${t}': pass a count or a list of strings; got ${typeof e}`);let n=e;if(n.length<1||n.length>2048)throw new RangeError(`[gem] experiment '${t}': the list must hold 1 to 2048 strings; got ${n.length}`);if(!n.every(r=>typeof r=="string"))throw new TypeError(`[gem] experiment '${t}': every option must be a string`)}var Ql=1e4,Zl=50,cg=500,ug=65536-4*1024,mg=24*1024;function ed(t){let e={},n={};for(let[r,o]of Object.entries(t))typeof o=="string"?e[r]=o:typeof o=="number"&&Number.isFinite(o)&&(n[r]=o);return {dimensions:e,measures:n}}var td=t=>typeof t=="number"?t:0,pg=t=>typeof t=="string"?t:"";function Ir(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function gg(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:td(i.index),code:pg(i.code)}}):[];return {accepted:td(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Zo(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function yg(t){return t?.retryable===true}var an=class{#e;#n;#i;#f;#t=[];#h={};#a=0;#s=null;#b=false;#v=false;#m=0;#_=0;#w=0;#r=false;#S=null;#l=null;#c=false;#o=false;#p=false;#R=false;#k=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#i=Math.max(Ql,e.options?.flushIntervalMs??Ql),this.#f=Math.max(1,Math.floor(e.options?.maxQueue??cg));}track(e,n={}){if(!(!this.#n||this.#r)){if(Xl(e)){this.#k||(this.#k=true,this.#y(`[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.#A(e,ed({...this.#h,...n}));}}setContext(e){this.#h={...this.#h,...e};}async experiment(e,n){Qo(e,n);let r=this.#e.awaitPlayerId===void 0?this.#e.playerId():await this.#e.awaitPlayerId();if(r===null)throw new Error(`[gem] experiment '${e}': no player to select for \u2014 this call was not made by a player.`);return typeof n=="number"?Er(e,r,n):Er(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return Ir();let n=this.#C();if(n===null||n==="")return this.#t.length>0&&!this.#R&&(this.#R=true,this.#y("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),Ir();if(this.#P(),this.#t.length===0)return Ir();let r=e.keepalive===true;if(this.#m>0&&!r)return Ir();this.#u();let o=this.#t.splice(0,this.#E(r)),i=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:Zo(),sent_at_ms:s,events:o.map(d=>nd(d,s))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await Ns(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=gg(d,i);return this.#_=0,this.#w=0,this.#I(m),m}catch(d){throw yg(d)?(this.#T(o,i),this.#_+=1,this.#w=this.#e.clock.now()+Tr(this.#_,d)):this.#y(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#m-=1,this.#t.length>0&&this.#d();}}trackPlatform(e,n={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#A(e,ed(n));}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(),n=this.#t.map(r=>({...r,atMs:e}));this.#t=n,this.#p&&(this.#p=false,this.#l=e,this.#c=false,this.#t.unshift({uid:Zo(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Zl?this.#g():this.#t.length>0&&this.#d();}get held(){return this.#o}startSession(){if(!(this.#r||this.#l!==null)){if(this.#o){this.#p=true;return}this.#l=this.#e.clock.now(),this.#c=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#c)return;if(this.#c=true,this.#o){this.#p=false,this.#t=[],this.#a=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#g({keepalive:true});}setPaused(e){this.#r||e===this.#b||(this.#b=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#v||(this.#v=e,e?this.#u():this.#t.length>0&&this.#d());}dispose(){this.#r=true,this.#u(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#A(e,n){let{dimensions:r,measures:o}=n;for(this.#P();this.#t.length>=this.#f;)this.#t.shift(),this.#a+=1;this.#t.push({uid:Zo(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=Zl?this.#g():this.#d();}#g(e={}){if(e.keepalive!==true&&this.#x()>0){this.#d();return}this.flush(e).catch(()=>{});}#x(){return Math.max(0,this.#w-this.#e.clock.now())}#T(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#f;)this.#t.shift(),this.#a+=1;}#E(e){let n=e?mg:ug,r=Math.min(this.#t.length,100),o=128;for(let i=0;i<r;i+=1){let s=this.#t[i];if(s===void 0)break;if(o+=JSON.stringify(nd(s,0)).length+1,o>n)return Math.max(1,i)}return r}#d(){this.#s!==null||this.#b||this.#v||this.#o||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#g();},Math.max(this.#i,this.#x())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#P(){let e=this.#M();e===null||e===""||(this.#S!==null&&this.#S!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#S=e);}#I(e){for(let n of e.rejected)this.#y(`[gem] analytics: an event was refused (${n.code}). `+fg(n.code));}#y(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#C(){try{return this.#e.gameId()}catch{return null}}#M(){try{return this.#e.playerId()}catch{return null}}};function nd(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function fg(t){switch(t){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 be(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function sn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=be(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var hg=2e3,bg=5e3;function od(t){let e=[],n=false,r=null,o=new Map,i=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,m=null;s=c=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(c));},m=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??hg);});return r={promise:a,settle:s},a};return {resolveList:i,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(s=>s[0])},refresh(s){return !rd(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=m=>{o.delete(d)&&(t.clock.clearTimeout(l),a(m));};o.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??bg);})},accept(s,a){let l=sn(a),d=be(s),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...o])rd(m,p)||c(m);}}}}function rd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var vg=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(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="DedicatedServerError",this.retryable=vg.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var id=["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"],_g=new Set(id);function Je(t){return typeof t=="string"&&_g.has(t)?t:"unknown"}var Cr="webrtc_dedicated",ri=["universal","mobile","web"];var wg="p2p_unavailable",Sg="capacity_unavailable",Rg=2,ad=3e4,sd=1e3,ld=2e4;async function oi(t){let e=be(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??ue,i=t.retry??{},s=i.budgetMs??ad,a=i.maxDelayMs??ld,l=i.initialDelayMs??sd,d=o.now(),m=d+s,c=0;for(;;){c++;try{let p=await li(t.signal,"while allocating",()=>t.client.post(`${ud(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!kg(p)||s<=0)throw p;if(p.status===503&&p.code===wg)throw new w("p2p_unavailable",`room ${t.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===Sg?r+1:0,n!==void 0&&r>=Rg){let x=n;n=void 0;let P=be(await x());P!==void 0&&(e=P,r=0);}let g=Math.min(a,l*2**(c-1)),y=Math.min(a,(p.retryAfterSeconds??0)*1e3),R=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+R>m)throw Ag(t,p,c,o.now()-d,s);if(i.onWaiting?.({attempt:c,elapsedMs:o.now()-d,budgetMs:s,nextAttemptInMs:R,status:p.status,message:p.message}),await Mr(o,R,t.signal),t.signal?.aborted)throw ni("while waiting to allocate")}}}function kg(t){return t instanceof O?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Ag(t,e,n,r,o){let i=`${n} attempt${n===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 ${t.roomId} after ${i}: ${e.message}`,{cause:e}):new w("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${i}: ${e.message}`,{cause:e})}var xg=12e4,Pg=1e3;async function ii(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Pg,o=t.timeoutMs??xg,i=e.now()+o,s=dd(t),a={seen:t.knownToExist===true};for(;;){let l=await cd(t,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>i)throw new w("timeout",`match ${n} was still ${l.status} after ${o}ms`);await Mr(e,r,t.signal);}}async function ai(t){return (await cd(t,dd(t),{seen:t.knownToExist===true})).outcome}function dd(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${ud(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function cd(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await li(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof O&&s.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(n.seen=true,i.status==="ready")return {status:"ready",outcome:Tg(r,i,o)};if(i.status==="failed"){let s=i.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Je(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function si(t){let e=await li(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let o=r?.cluster_target_id;typeof o!="string"||o.length===0||n.push({id:o,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function li(t,e,n){if(t?.aborted)throw ni(e);try{return await n()}catch(r){throw t?.aborted?ni(e,r):r}}function ni(t,e){return new w("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function Tg(t,e,n){let r=e.join_credential,o=e.expires_in_seconds,i=typeof r=="string"&&typeof o=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...i?{joinCredential:r,credentialExpiresAt:n+o*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function ud(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Mr(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let o=()=>{t.clearTimeout(i),n?.removeEventListener("abort",o),r();},i=t.setTimeout(o,e);n?.addEventListener("abort",o);})}function md(t){return typeof t=="string"&&t.trim()!==""}function Or(t,e){return md(t)?t.trim():md(e)?e:null}var Gr="0.1.0-beta",pd="0-beta",Tt="web",Eg=/^(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 Ig(t){let e=Eg.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function gd(t,e){let n=Cg(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:Gr};let o=Ig(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 '${Gr}' for it.`);if(o!==pd)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${pd}' 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 '${Gr}' for it.`);return {...t,platform:n,engineVersion:r}}function Cg(t,e){if(t===void 0||t===Tt)return Tt;if(!ri.includes(t))throw new w("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${ri.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${Tt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${Tt}' 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.`),Tt}function ln(t){let e=t??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let n=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:yd(e.queued_at),expiresAt:yd(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function yd(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var Mg=3,fd=1e3,Lr=class{constructor(e){this.options=e;this.snapshot=e.first;let n=new Promise((i,s)=>{this.resolve=i,this.reject=s;});n.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:n,cancel:()=>(this.requestCancel(),n)};}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 n=e?fd:Math.max(fd,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},n);}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,n=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){n=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(n);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<Mg){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof O&&e.code==="matchmaking_unavailable";this.settle({status:n?"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 n=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:n});}catch(n){this.busy=false,this.fail(n);}}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 Og="gemPlayWith",Gg=/^[A-Za-z0-9_-]{16,128}$/;function hd(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(Og);}catch{return}return e!==null&&Gg.test(e)?e:void 0}function bd(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var Lg="join",Dg="welcome",Fg="rejected",vd=25e3,$g=1e3,di=1;function ci(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var qg={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 ui(t){let e=typeof t=="string"?t:"unknown";return new w(qg[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function dn(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??vd),a=n.setTimeout(()=>v(new w("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,$g)),l=R=>{let x=R.data;if(typeof x!="string"){c(x);return}let P;try{P=JSON.parse(x);}catch{c(x);return}if(i){c(x);return}if(P.t===Dg){let h=ci(P.heartbeat_interval);y({...typeof P.player_id=="string"?{playerId:P.player_id}:{},...typeof P.match_id=="string"?{matchId:P.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(P.t===Fg){v(ui(P.reason));return}c(x);},d=()=>{v(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{v(new w("aborted","the caller aborted during the join exchange"));},c=R=>{i&&t.onMessage?.(R);},p=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=R=>{i=true,p(),t.onMessage===void 0&&g(),r({welcome:R,detach:g});},v=R=>{i||(i=true,p(),g(),o(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Lg,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:di}:{}}));}catch(R){v(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var st=1,cn=2,mi=4,yi=8,Ng=2,jg=1e3,fi="heartbeat timeout",un="gem-uu",Dr=2,wd="gem_transports";function Et(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Ug(r)||e.includes(r)||e.push(r);}return e}function Ug(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function mn(t,e){if(typeof t!="object"||t===null)return null;let n=t[wd];if(typeof n!="object"||n===null)return null;let r=n;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 Fr(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Sd=new TextEncoder,Rd=new TextDecoder;function hi(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function bi(t){let e=0;return t?.reliable===false&&(e|=st),t?.ordered===false&&(e|=cn),e}function vi(t){return {reliable:(t&st)===0,ordered:(t&cn)===0}}var _i={reliable:true,ordered:true};function kd(t){return JSON.stringify({t:"join",credential:t,wire:Dr,heartbeat:di})}function Ad(t){let e;try{e=JSON.parse(t);}catch{throw new w("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=ci(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...n===void 0?{}:{heartbeatIntervalMs:n}}}throw e.t==="rejected"?ui(e.reason):new w("join_refused","the server answered the join out of protocol")}function $r(){return typeof globalThis.WebTransport=="function"&&wi===null}function qr(){return wi}var wi=null;var _d="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Bg(t){let e=Yn(t);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 pi=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let i=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(i===0||i>1<<20)throw new w("connection_failed",`a control-stream record claims ${i} bytes`);if(this.buffered.byteLength<4+i)break;let s=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function gi(t,e){let n=new Uint8Array(5+e.byteLength);return new DataView(n.buffer).setUint32(0,e.byteLength+1,true),n[4]=t,n.set(e,5),n}async function pn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new w("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new a(t.url):new a(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Bg(t.certHashBase64)}]});}let r=n,o=a=>{try{r.close();}catch{}throw a},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(wi=_d,o(new w("connection_failed",`${_d}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new w("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return o(new w("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(gi(mi,Sd.encode(kd(t.credential))));let c=new pi,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),s]);if(y.done||y.value===void 0)return o(new w("connection_failed","the control stream closed before the join was answered"));for(let v of c.push(y.value)){g=Ad(Rd.decode(v.payload));break}}return {link:Wg(r,m,p,c,t.log??(y=>console.warn(y)),Pd(g,t.clock)),welcome:g}}catch(a){return o(a)}}function Wg(t,e,n,r,o,i){let s,a,l=false,d=y=>{if(!l){l=true,m.stop();try{t.close();}catch{}a?.(y);}},m=Ri(i,()=>d(fi)),c=(y,v)=>{m.heard(),(y&yi)===0&&s!==void 0&&((y&mi)!==0?s(Rd.decode(v),_i):s(v,vi(y)));};(async()=>{try{for(;;){let y=await n.read();if(y.done||y.value===void 0)break;for(let v of r.push(y.value))c(v.flags,v.payload);}}catch{}d("stream closed");})();let p,g;try{let y=t.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let v=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let R=await v.read();if(R.done||R.value===void 0)break;let x=R.value;x.byteLength!==0&&c((x[0]??0)|st|cn,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 (${Fr(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(xd(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,v){if(l)return;if(typeof y=="string"){e.write(gi(mi,Sd.encode(y))).catch(()=>d("write failed"));return}let R=bi(v);if((R&st)!==0&&g!==void 0){let x=hi(R,y),P=p?.maxDatagramSize;if(P===void 0||x.byteLength<=P){g.write(x).catch(()=>{});return}}e.write(gi(R,y)).catch(()=>d("write failed"));},onMessage(y){s=y;},onClose(y){a=y;},close(){d("closed");}}}function Si(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let o=globalThis.WebSocket;if(o===void 0)return Promise.reject(new w("connection_failed","this environment has no WebSocket"));n=new o(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((o,i)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),i(new w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),i(g));},d=()=>{r.send(kd(t.credential));},m=g=>{if(s)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let y;try{y=Ad(g.data);}catch(v){l(v);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),o({link:Hg(r,Pd(y,t.clock)),welcome:y});},c=()=>{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",c),r.addEventListener("error",p),r.readyState===1&&d();})}function xd(t){return typeof t=="string"&&t.length>0?t:void 0}function Pd(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function Ri(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,jg)*Ng,o=n.now(),i=null,s=()=>{i=null;let a=n.now()-o;if(a>=r){e();return}i=n.setTimeout(s,r-a);};return i=n.setTimeout(s,r),{heard:()=>{o=n.now();},stop:()=>{i!==null&&(n.clearTimeout(i),i=null);}}}function Hg(t,e){let n,r,o=false,i=a=>{if(!o){o=true,s.stop();try{t.close();}catch{}r?.(a);}},s=Ri(e,()=>i(fi));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,_i);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&yi)===0&&n?.(l.slice(1),vi(d));})),t.addEventListener("close",(a=>i(xd(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!o){if(typeof a=="string"){t.send(a);return}t.send(hi(bi(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){i("closed");}}}function ki(t,e,n,r){let o,i,s=false,a=n,l=c=>{if(!s){s=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}i?.(c);}},d=Ri(r,()=>l(fi)),m=(c,p)=>{if(d.heard(),typeof c=="string"){o?.(c,_i);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&yi)===0&&o?.(g.slice(1),vi(y|p));};if(t.addEventListener("message",(c=>m(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),a!==void 0){let c=a;c.addEventListener("message",(p=>m(p.data,st|cn))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,p){if(s)return;if(typeof c=="string"){t.send(c);return}let g=bi(p),y=hi(g,c);if((g&st)!==0&&a!==void 0&&a.readyState==="open"){a.send(y);return}t.send(y);},onMessage(c){o=c;},onClose(c){i=c;},close(){l("closed");}}}function Td(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=Ai(r);o!==void 0&&(e[n]=o);}return e}function Ed(t){if(Array.isArray(t))return t.map(Vg).filter(e=>!!e)}function Ai(t){if(xi(t)||Array.isArray(t)&&t.every(xi))return t}function xi(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function Vg(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Ai(e.fixed),r=Ai(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,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...It("description",Kg(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(xi)?{allowed:e.allowed}:{},...It("min",gn(e.min)),...It("max",gn(e.max)),...It("minItems",gn(e.min_items)),...It("maxItems",gn(e.max_items)),...It("maxLength",gn(e.max_length))}}function Kg(t){return typeof t=="string"&&t.length>0?t:void 0}function gn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function It(t,e){return e===void 0?{}:{[t]:e}}function $e(t){let e=t??{},n=Q(e.id)??Q(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(Jg):[];return {id:n,gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:Ge(e.max_players)??0,memberCount:Ge(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...ke("joinCode",Q(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...ke("roomArgs",Td(e.room_args)),...ke("roomArgsTemplate",Ed(e.room_args_template)),gameChannel:Q(e.game_channel)??"release",...ke("region",Q(e.region)),...ke("clusterTargetId",Q(e.cluster_target_id)),selfHosted:e.self_hosted===true,...ke("matchId",Q(e.match_id)),version:Ge(e.version)??0,...ke("templateId",Q(e.template_id)),...ke("templateSlug",Q(e.template_slug)),roomType:Q(e.game_room_type)??"Standard",...ke("transports",Et(e.transports)??void 0),createdAt:Ge(e.created_at)??0,updatedAt:Ge(e.updated_at)??0,...ke("startedAt",Ge(e.started_at))}}function Jg(t){let e=t??{};return {...Pe(e),playerId:Q(e.player_id)??"",isReady:e.is_ready===true,role:Q(e.role)??"member",joinedAt:Ge(e.joined_at)??0,...ke("groupId",Q(e.group_id)),...ke("platform",Q(e.platform))}}function Pi(t){let e=t??{};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:Ge(e.max_players)??0,memberCount:Ge(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Q(e.game_channel)??"release",roomType:Q(e.game_room_type)??"Standard",createdAt:Ge(e.created_at)??0}}function Q(t){return typeof t=="string"&&t.length>0?t:void 0}function Ge(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ke(t,e){return e===void 0?{}:{[t]:e}}var Nr=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(o=>({rooms:(o.game_rooms??[]).map(Pi),...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(n=>({rooms:(n.game_rooms??[]).map(Pi)}))}create(e,n,r){return Yg(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},...yn(n)},e.signal).then($e)}get(e,n){return this.options.client.get(this.roomV2(e),n).then($e)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...yn(r)},n.signal).then($e)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...yn(r)},n.signal).then($e)}quickJoin(e,n,r=[]){return Ti(this.options,e,n,r).then(o=>o.room)}createTicket(e,n,r=[]){return ds(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},...yn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(ln)}heartbeatTicket(e){return qs(this.generated(),e).then(ln)}cancelTicket(e,n=false){return n?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(ln):os(this.generated(),e).then(ln)}leave(e,n,r,o=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:o}).then(()=>{})}asksSelfHosted(e){return Cd(this.options,e)}close(e,n){return this.options.client.delete(this.roomV1(e),n).then(()=>{})}update(e,n){return this.options.client.patch(this.roomV2(e),{...n.name===void 0?{}:{name:n.name},...n.maxPlayers===void 0?{}:{max_players:n.maxPlayers},...n.isPublic===void 0?{}:{is_public:n.isPublic},...n.settings===void 0?{}:{settings:n.settings},...n.roomArgs===void 0?{}:{room_args:n.roomArgs}},n.signal).then($e)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then($e)}kick(e,n,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(n)}`,{},r).then(()=>this.get(e,r))}transferHost(e,n,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(n)}`,{},r).then($e)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return Id(this.options)}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 Id(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function Cd(t,e){return e===void 0&&t.selfHosted?.()===true}function Ti(t,e,n,r=[],o){let i=Cd(t,e.partyId);return t.client.post(`${Id(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...zg(e.templateSlugs,i),...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...i?{self_hosted:true}:{},...o===void 0?{}:{play_with_ticket:o},...yn(n)},e.signal).then(s=>({room:$e(s),playWith:o===void 0?null:bd(s)}))}function zg(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function yn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function Yg(t){t!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${t}) 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 jr=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let o=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===o&&n(o);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...o)=>{r(),n(...o);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let o of [...r])o(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};var Ur=class{constructor(e){this.options=e;let n=e.first,r=new Promise(a=>{this.resolve=a;}),o=()=>this.status;this.ticket={id:n.ticketId,get status(){return o()},partySize:n.partySize??0,queuedAt:n.queuedAt??0,expiresAt:n.expiresAt??0,outcome:r};let i=n.queuedAt!==void 0&&n.expiresAt!==void 0?(n.expiresAt-n.queuedAt)*1e3:9e5,s=Math.min(Math.max(i,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},s);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function Xg(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var Qg=1e3,Zg=3e3,ey=6e4,ty=2,Md=new Set(["game_room_closed","game_room_gone"]),ny=12e4,ry=5e3,oy=new Set(["invalid_cluster_target","capacity_unavailable"]),iy=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Dd(t,e){return new Ei(e,t)}var Ei=class{constructor(e,n={}){this.options=e;this.internals=n;this.autoFollow=e.followMatch!==false,this.apiOptions={client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true},this.api=new Nr(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new jr;api;apiOptions;playWithAnswer=null;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let n=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("create",async()=>{let i=await n;return this.api.create(r,this.version("create"),i[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,i);if(a[0]===void 0||a[0]===i[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(o,"created"),this.askForLocalServer(o),o}async join(e,n={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(n),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,n={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(n),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"),ly(e);let n=this.clusterTargets(),r=await this.attachParty(e),o=a=>this.postQuickJoin(r,a).catch(l=>this.retryPastStaleMembership(l,r,a)),i=await this.run("quickJoin",async()=>{let a=await n;return o(a).catch(async l=>{let d=await this.afterRefusedClusters(l,a);if(d.length===0||Ld(d,a))throw l;return o(d)})}),{room:s}=i;return this.playWithAnswer=i.playWith,this.enter(s,"joined"),this.askForLocalServer(s),s}async queueForMatch(e){this.assertNotQueued("queueForMatch"),sy(e?.templateSlugs),this.queueing=true;try{let n=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("queueForMatch",async()=>{let s=await n;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Ld(l,s))throw a;return this.api.createTicket(r,this.version("queueForMatch"),l)})});this.heldQueued?.ticketId===o.id&&(this.heldQueued=null),this.partyWatch?.end({status:"lost"});let i=new Lr({clock:this.options.clock,first:o,heartbeat:s=>this.track(this.api.heartbeatTicket(s)),cancel:(s,a)=>this.track(this.api.cancelTicket(s,a)),seat:s=>this.enterMatchedRoom(s),onSettled:()=>{this.ticketWatch===i&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=i,this.retuneSeatWatch(),i.start(),i.ticket}finally{this.queueing=false;let n=this.heldQueued;this.heldQueued=null,n!==null&&this.showPartyTicket(n);}}async enterMatchedRoom(e){let n=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?n:(this.room!==null&&this.room.id!==n.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(n,"joined"),this.room?.id===n.id?this.room:n)}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,o=()=>this.run("leave",()=>this.api.leave(n.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 n=await this.myRooms(e),r=[];for(let o of n)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 n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(o){if(o instanceof O&&o.reason==="not_found"){let i=this.heldMatchId;if(i!==null){let s=await this.askWhyEnded(i,e);this.endMatch(i,s??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",o),o}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let o=await this.askWhyEnded(r,e);o!==null&&this.endMatch(r,o,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let o=this.takeHint(e),i;try{i=await this.track(this.onceGameIdKnown(()=>ai({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),...n===void 0?{}:{signal:n}})));}catch(s){return s instanceof O&&s.reason==="not_found"?o??null:(this.reportError("reconcile",s),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=Je(n.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 n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),o=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(o),o}async kick(e,n){let r=this.requireRoom("kick"),o=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(o),o}async transferHost(e,n){let r=this.requireRoom("transferHost"),o=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(o),o}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){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,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let o=be(n.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(m,c)=>oi({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...o===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(i,[s]).catch(async m=>{if(o!==void 0||!Gd(m))throw m;let c=await this.nextCluster([s],true);if(c===void 0)throw m;return a(c,[s,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new 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 n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),o=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(o)}chase(e,n,r){return ii({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...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,!Md.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,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let o={matchId:e,cause:n,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,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}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,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!lt()){this.park(e,()=>this.reconnectStep(e));return}let n=this.options.autoReconnect;if(n===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=n.attempts||r<Qg){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:n.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(Xg(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!lt()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let o=null;try{o=await this.track(this.onceGameIdKnown(()=>ai({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,!Md.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 n.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),i="failed";}if(e.done||this.reconnect!==e)return;if(i==="closed"){this.finishReconnect();return}if(i==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let n=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})):n&&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 n=this.session.matchId;this.session={phase:"suspended",matchId:n,reason:e},this.emitter.emit("matchSuspended",{matchId:n,cause:e}),this.armReconnect(n,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 n=this.heldMatchId;if(n===null)throw new w("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:n},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let n=this.heldMatchId;if(n!==null)try{await this.api.leaveMatch(n,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}get playWith(){return this.playWithAnswer}on(e,n){let r=this.emitter.on(e,n);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}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 n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,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||!oy.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let n=new Ur({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===n&&(this.partyWatch=null);}});this.partyWatch=n,this.emitter.emit("partyQueued",n.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.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])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(o=>o.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&lt())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let n=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(n,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!lt())){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 Br)e.addEventListener(r,this.visibilityListener);let n=globalThis.document;typeof n?.addEventListener=="function"&&n.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 n=this.inFlight;this.inFlight=[],await Promise.allSettled(n);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of Br)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??ry}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 n=this.options.clientVersion,r=Or(this.options.platformGameVersion?.(),n?.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 gd({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return sn(await this.options.resolveClusterTargets());let e=be(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Gd(e)||n.length===0?[]:sn(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=s=>s.find(a=>!e.includes(a)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!n?i:r(sn(await this.options.refreshClusterTargets?.(o)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof O)||e.reason!=="conflict"||!iy.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(n.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.postQuickJoin(n,r)}postQuickJoin(e,n){return Ti(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}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,n){try{return await this.track(this.onceGameIdKnown(n))}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,n){let r=n instanceof O?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof w?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){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(n,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 n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(a=>[a.playerId,a])),o=new Map(e.members.map(a=>[a.playerId,a])),i=this.playerId();for(let a of o.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!o.has(a)){if(a===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,l]of o){let d=r.get(a);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",a,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=ay(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"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,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{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 n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??ny;return new Promise((o,i)=>{let s=c=>{a(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>o(c))),l=this.emitter.on("matchFailed",(c,p)=>s(()=>i(new w("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>s(()=>i(new w("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>s(()=>i(new w("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Zg}pushedInterval(){return this.options.pushedPollIntervalMs??ey}pushed(){return this.options.clock.now()-this.lastPushAt<ty*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=n=>{if(this.ticketWatch?.abandon(true),n?.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 lt(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Br=["visibilitychange","focus","pageshow","online"];function ay(t,e){return t.version!==e.version||t.status!==e.status||t.matchId!==e.matchId||t.hostPlayerId!==e.hostPlayerId||t.name!==e.name||t.maxPlayers!==e.maxPlayers||t.isPublic!==e.isPublic||Od(t)!==Od(e)}function Od(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Gd(t){return t instanceof O&&t.code==="invalid_cluster_target"}var Wr=8;function sy(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=Wr&&t.every(n=>typeof n=="string"&&n.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Wr} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function ly(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Wr&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Wr} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(t?.templateSlug!==void 0||t?.templateId!==void 0)throw new w("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function Ld(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var dy=["p2p","dedicated","unknown"],Ii=["connection_setup_duration_seconds","reconnect_latency_seconds","datachannel_rtt_seconds","p2p_join_to_play_latency_seconds","ice_restart_outcome_total","connection_failures_total","transport_permanent_failures_total","transport_quality_score","host_migration_outcome_total","turn_relay_usage_ratio"];var Ct=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=cy(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},n);}report(e){this.post(e).catch(()=>{});}};function cy(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>Ii.includes(o.type)).slice(0,100).map(o=>{let i=uy(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function uy(t){if(t!==void 0)return dy.includes(t)?t:"unknown"}var fn=class{constructor(e){this.options=e;this.reporter=new Ct({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let o=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:Hr(o.credential)??"",hostFingerprint:Hr(o.host_fingerprint)??"",hostEpoch:Vr(o.host_epoch)??0,expiresAt:(Vr(o.expires_at)??0)*1e3}}async turnLease(e,n,r){let o=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),i=[];for(let l of Array.isArray(o.ice_servers)?o.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&i.push({urls:m,username:Hr(d.username)??"",credential:Hr(d.credential)??""});}let s=Vr(o.expires_at),a=Vr(o.ttl_seconds);return {iceServers:i,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,n,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:n},r);}async leave(e,n=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:n});}async telemetry(e,n){await this.reporter.post(e,n);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function Hr(t){return typeof t=="string"&&t.length>0?t:void 0}function Vr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var my=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),D=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=my.has(n);}reason;retryable};var Fd=10240,$d=2048,py=new TextEncoder;function qd(t){return py.encode(t).length}function ze(t,e){let n=o=>{throw new w("invalid_sdp",`the ${e} ${o}`)},r=qd(t);r>=Fd&&n(`is ${r} bytes, over the ${Fd} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let o of t.split(/\r\n|\n/)){let i=qd(o);i>$d&&n(`has a ${i}-byte line, over the ${$d} limit`);}}function Kr(t){for(let e of t.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[n,r="0"]=e.slice(2).trim().split(/\s+/);if(!(n!=="audio"&&n!=="video")&&r.split("/")[0]!=="0")return true}return false}var Jr=class{listeners=new Map;on(e,n){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(n),()=>this.off(e,n)}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...o)=>{r(),n(...o);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let o of [...r])o(...n);}clear(){this.listeners.clear();}};var gy=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function Mt(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=zr(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function zr(t){let[e,...n]=t.trim().split(/\s+/);if(e===void 0||n.length===0)return null;let r=`${e.toLowerCase()} ${n.join("").toUpperCase()}`;return gy.test(r)?r:null}function hn(t,e){if(t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}var Ci=5e3,yy=12e4+Ci,fy=1024,hy=6e4,by=1e4,Nd=64*1024,jd=5;function Mi(t){let e=new Map,n=-1/0,r=null,o=(()=>{let a;try{a=new URL(`${t.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),i=()=>{let a=t.subtle??globalThis.crypto?.subtle;if(!a)throw new D("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!o.ok)throw new D("keys_unavailable",o.reason);let a=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(by)});}catch{throw new D("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 D("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>Nd)throw new D("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${Nd} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof D?p:new D("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>jd)throw new D("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${jd} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=i();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!o.ok)throw new D("keys_unavailable",o.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new D("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<n&&(n=-1/0),d-n<hy?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var bn=class{seen=new Map;admit(e,n){for(let[r,o]of this.seen)o<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=fy){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+yy),true}};function Bd(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function Ud(t){try{let e=new TextDecoder().decode(Bd(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Oi(t,e,n,r,o){let i=N=>{throw new D("peer_unauthenticated",`the peer's join credential is not usable: ${N}`)},s=t.split(".");s.length!==3&&i("it is not a three-part JWT");let[a,l,d]=s,m=Ud(a);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&i("it names no key");let p=await n.key(c);p===null&&i("it was signed by a key this build cannot resolve");let g=o.subtle??globalThis.crypto?.subtle;g||i("this environment has no WebCrypto");let y=new TextEncoder().encode(`${a}.${l}`),v;try{v=Bd(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,v,y)||i("its signature does not verify");let x=Ud(l);x===null&&i("its payload does not decode");let P=x,h=N=>typeof P[N]=="string"?P[N]:"",S=N=>typeof P[N]=="number"&&Number.isFinite(P[N])?P[N]:NaN;h("iss")!==o.issuer&&i("it was issued by someone else"),h("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),h("match_id")!==e.matchId&&i("it is for another match"),h("game_id")!==e.gameId&&i("it is for another game");let I=S("exp")*1e3,T=S("nbf")*1e3;(!Number.isFinite(I)||e.now>I+Ci)&&i("it has expired"),Number.isFinite(T)&&e.now<T-Ci&&i("it is not valid yet");let W=h("role");W!=="host"&&W!=="client"&&i("it names no usable role");let q=S("host_epoch");q!==e.hostEpoch&&i("it names a different host epoch");let U=zr(h("fingerprint"));U===null&&i("its fingerprint claim is malformed"),hn(U,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let E=zr(h("host_fingerprint"));E===null&&i("its host fingerprint claim is malformed"),hn(E,e.hostFingerprint)||i("it was issued against a different host certificate");let M=h("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 F=h("sub");return F.length===0&&i("it names no player"),{playerId:F.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:q,role:W,fingerprint:U,hostFingerprint:E,jti:M,expiresAt:I}}function Gi(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function Li(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function Di(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Fi(t){if(t.byteLength<1)return null;let e=new DataView(t);switch(e.getUint8(0)){case 1:{if(t.byteLength<3)return null;let n=e.getUint16(1,true);return n>8192||t.byteLength<3+n+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(t,3,n)),protocolVersion:e.getUint32(3+n,true),assignedPeerId:e.getUint32(7+n,true)}}case 2:return t.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return t.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function Wd(t){switch(t){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 (${t})`}}function Hd(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var vn=class{constructor(e,n,r){this.localPlayerId=e;this.hostPlayerId=n,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,n){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=n,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var $i={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}},qe=["reliable","ordered","unreliable"];function qi(t){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:t.iceServers,...t.certificates===void 0?{}:{certificates:t.certificates}})}async function _n(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Kd=1,Ry=3e4,Jd=2e3,ky=5e3,zd=6e4,Ay=8,ji=class{constructor(e=Ay){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 n=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[n++]=r);this.sent.length=n;}},xy=new ji,Py=8,Ty=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Sn=class{constructor(e){this.options=e;this.keys=e.keys??Mi({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Jr;links=new Map;replays=new bn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Kd+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 n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??Ry;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),o=be(this.options.clusterTargetId);if(o!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,o,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Ni(a)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let i=this.options.clock.setTimeout(()=>{this.fail(new D("timeout",`no usable P2P connection after ${n}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},n),s=()=>this.fail(new D("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",s),this.ready=null;}}async kick(e){if(!this.isHost)throw new D("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,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);default:return}}async onHello(e){let n=de(e.playerId),r=de(e.hostPlayerId),o=Yr(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new vn(n,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 n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,Kd),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new D("invalid_sdp","the browser produced an offer with no SDP");ze(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,o=r===void 0?null:Mt(r);if(o===null)throw new D("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??xy,s=()=>this.closed||e!==this.credentialGeneration,a=ky;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let m=d.status,c;if(m===409)c=Jd;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=a,a=Math.min(a*2,zd)),c=Math.min(Math.max(c,Jd),zd);}else throw d;if(!await this.waitForCredential(c,s))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=Py){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let o=de(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;ze(r,"offer"),this.refuseMedia(r,"offer");let i=Mt(r);if(i===null)throw new D("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),o!==null&&this.answeredSessions.set(n,o);let s=this.links.get(n);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(n,this.nextPeerId++);a.remoteFingerprint=i,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let l=await a.connection.createAnswer();await a.connection.setLocalDescription(l);let d=a.connection.localDescription?.sdp??l.sdp;if(!d)throw new D("invalid_sdp","the browser produced an answer with no SDP");ze(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;ze(r,"answer"),this.refuseMedia(r,"answer");let i=Mt(r);if(i===null)throw new D("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 n=this.credential;return n===null||e.remoteFingerprint===null?false:hn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new D("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 n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e);}async onIce(e){let n=de(e.fromPlayerId),r=de(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=de(e.sdpMid),s=Yr(e.sdpMLineIndex)??Yr(e.sdpMLineIndexAlt),a={candidate:r,...i===null?{}:{sdpMid:i},...s===null?{}:{sdpMLineIndex:s}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(a);return}await o.connection.addIceCandidate(a);}onPeerLeft(e){let n=de(e.playerId);if(n===null)return;let r=de(e.reason)??"left";if(n===this.localPlayerId){this.fail(new D("kicked",`this player was removed from the match (${r})`)),this.close();return}let o=this.links.get(n);o&&this.dropLink(o,r,true);}async onMigration(e){let n=de(e.hostPlayerId),r=Yr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...de(e.reason)===null?{}:{reason:de(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",n,r);return}if(o.kind==="refused"){this.report_(new D("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",n,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 D("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 n=de(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new D("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=de(e.code)??"unknown",r=de(e.message)??"the platform refused a signaling message";this.report_(new D("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??qi)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of qe){let g=o.createDataChannel(p,$i[p]);g.binaryType="arraybuffer",i[p]=g;}let s={playerId:e,assignedPeerId:n,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),m=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",a),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",c),i.reliable.addEventListener("message",m),s.detachHandshake=()=>{i.reliable.removeEventListener("open",c),i.reliable.removeEventListener("message",m);},s.detachAll=()=>{s.detachHandshake(),o.removeEventListener("icecandidate",a),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}flushCandidates(e){let n=e.pendingCandidates;e.pendingCandidates=[];for(let r of n)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let n=this.credential;if(n===null)throw new D("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=n.expiresAt)throw new D("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(Gi({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Fi(n);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 D(Hd(r.reason),Wd(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,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=Mt(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 Oi(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:o,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof D&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",Ni(s)),a&&this.fail(s);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Li({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,o){this.warn(`refused to admit ${e.playerId}: ${o}`);try{e.channels.reliable.send(Di(n));}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 n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let o of qe)Yd(e.channels[o]);Yd(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,n);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let n=this.ready;this.ready=null,n.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof D?e:new D("connection_failed",Ni(e),{cause:e}));}count(e){this.counted||!Ty.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(Kr(e))throw new D("media_refused",`the ${n} 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(n=>this.options.clock.setTimeout(n,e))}warn(e){let n=this.options.log;n!==null&&(n??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function de(t){return typeof t=="string"&&t.length>0?t:null}function Yr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Ni(t){return t instanceof Error?t.message:String(t)}function Yd(t){try{t.close();}catch{}}var Ey=100,Iy=50,Rn=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,n){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:n});}answer(e,n,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:n,assignedPeerId:r});}candidate(e,n,r,o){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Ey)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...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,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,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 D("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new D("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:n,candidate:r,sdpMid:o,sdpMLineIndex:i}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...o===void 0?{}:{sdpMid:o},...i===void 0?{}:{sdpMLineIndex:i}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??Iy));}};function V(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Ye(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function Ot(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function Xd(t){return typeof t=="boolean"?t:void 0}var Se=V(64),kn=Ye(0,2147483647);function Ui(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=Se(n);typeof r=="string"&&e.push(r);}return e}function X(t,e,n){return {to:t,from:e,read:n,required:true}}function K(t,e,n){return {to:t,from:e,read:n,required:false}}var Oy=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=Ot("disconnected","failed","closed")(e.iceState),r=Ye(0,4102444800)(e.lastSeenAt);if(!(n===void 0&&r===void 0))return {...n===void 0?{}:{ice_state:n},...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:[X("sdp","sdp",V(10240)),X("signaling_intent","intent",Ot("initial","ice_restart","full_reconnect")),K("sdp_hash","sdpHash",V(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[X("peer_id","peerId",Se),X("sdp","sdp",V(10240)),X("assigned_peer_id","assignedPeerId",Ye(0,4294967295)),K("sdp_hash","sdpHash",V(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[X("peer_id","peerId",Se),X("candidate","candidate",V(512)),K("sdp_mid","sdpMid",V(64)),K("sdp_mline_index","sdpMLineIndex",Ye(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[X("host_epoch","hostEpoch",kn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[X("host_epoch","hostEpoch",kn),K("evidence","evidence",Oy)]}}));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:[X("playerId","player_id",Se),X("hostPlayerId","host_player_id",Se),X("hostEpoch","host_epoch",kn),K("members","members",Ui)],offer:[X("fromPlayerId","from_player_id",Se),X("sdp","sdp",V(10240)),K("sessionId","signaling_session_id",V(128)),K("sdpHash","sdp_hash",V(128)),K("iceUfrag","ice_ufrag",V(64)),K("intent","signaling_intent",Ot("initial","ice_restart","full_reconnect"))],answer:[X("fromPlayerId","from_player_id",Se),X("sdp","sdp",V(10240)),K("sessionId","signaling_session_id",V(128)),K("sdpHash","sdp_hash",V(128)),K("iceUfrag","ice_ufrag",V(64)),K("assignedPeerId","assigned_peer_id",Ye(0,4294967295))],ice:[X("fromPlayerId","from_player_id",Se),X("candidate","candidate",V(512)),K("sdpMid","sdp_mid",V(64)),K("sdpMLineIndex","sdp_m_line_index",Ye(0,255)),K("sdpMLineIndexAlt","sdp_mline_index",Ye(0,255))],peerJoined:[X("playerId","player_id",Se)],peerLeft:[X("playerId","player_id",Se),K("reason","reason",V(64))],migration:[X("hostPlayerId","new_host_player_id",Se),X("hostEpoch","host_epoch",kn),K("reason","reason",V(64)),K("kickedPlayerIds","kicked_player_ids",Ui),K("migrationComplete","migration_complete",Xd)],matchEnded:[K("reason","reason",V(64))],error:[K("code","code",V(64)),K("message","message",V(256))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var ct="webrtc_p2p";function Zd(t){let e=new fn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,o,i){n.get(r)?.handleSignal(o,i);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new D("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=be(r.clusterTargetId),i=o??be(await t.resolveClusterTarget?.());t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...o===void 0?{}:{clusterTargetId:o},...r.signal===void 0?{}:{signal:r.signal}});let s=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==ct)throw new D("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${ct}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new Rn({bridge:t.bridge,matchId:s.matchId,clock:t.clock}),l=new Sn({api:e,clock:t.clock,matchId:s.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:a,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await _n(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(s.matchId,l),l.on("matchEnded",()=>n.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(s.matchId),l.close(),d}return l}}}function ec(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,o=t.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let a=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",a),i.push(()=>r.removeEventListener?.("pagehide",a));let l=()=>e.setHidden(!lt());for(let d of Br)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(!lt());}let s=new Map;return i.push(n.on("matchReady",a=>{let l=a.protocol===ct?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(n.on("matchEnded",a=>{let l=s.get(a.matchId);l!==void 0&&(s.delete(a.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let a of i.splice(0))try{a();}catch{}s.clear();}}var tc=["pointerdown","keydown"];function nc(t,e=globalThis){let n=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},s=()=>{if(!r){r=true,i();for(let g of tc)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(g){g?.isTrusted===true&&a();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(v=>v.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},c=()=>{if(o=null,!(n||r)){if(d()){a();return}m()&&(o=e.requestAnimationFrame?.(c)??null);}};function p(){o===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let g of tc)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(o=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:s}}async function Xr(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function Bi(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function Wi(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(o,i){return r.has(o)?false:(r.add(o),n.push({name:o,at:i??e()}),true)},timeline(){let o=[...n].sort((i,s)=>i.at-s.at);return o.map((i,s)=>{let a=o[s-1],l=a===void 0?"":` (+${Math.round(i.at-a.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var Hi=new WeakMap,rc=new WeakSet,Vi=new Set,Qr=new Set,Zr=[],Lt=null,Ki=false,Gy=1920;function Ji(t){return Hi.get(t)}function zi(t){return !Ki||rc.has(t)}function Yi(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function oc(t=globalThis.window){if(Ki||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;Ki=true;for(let i of Array.from(t.document?.querySelectorAll("canvas")??[]))rc.add(i);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(i,...s){let a=n.call(this,i,...s);if(a&&!Hi.has(this)){let l={kind:i,context:a};Hi.set(this,l),Yi(l)&&Vi.add(this);}return a};let r=t.requestAnimationFrame,o=t.cancelAnimationFrame;t.requestAnimationFrame=i=>{let s=r.call(t,a=>{Qr.delete(s);try{i(a);}finally{Ly();}});return Qr.add(s),sc(),s},t.cancelAnimationFrame=i=>{Qr.delete(i),o.call(t,i);};}function ic(t,e){return new Promise(n=>{let r={canvas:t,done:i=>{clearTimeout(o),Zr=Zr.filter(s=>s!==r),n(i);}},o=setTimeout(()=>r.done(null),e);Zr.push(r);})}function ac(t){return Lt?.canvas===t?Lt.bitmap:null}function Ly(){for(let t of Zr){let e;try{e=Xi(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}Qr.size===0&&Dy();}function Dy(){let t=null;for(let r of Vi)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):Vi.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,Gy/Math.max(t.width,t.height)),n=e<1?{resizeWidth:Math.max(1,Math.floor(t.width*e)),resizeHeight:Math.max(1,Math.floor(t.height*e)),resizeQuality:"medium"}:{};sc(),Lt={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function sc(){Lt&&(Lt.bitmap.then(t=>t?.close()),Lt=null);}function Xi(t){let e=Fy();if(!e)return true;e.clearRect(0,0,8,8),e.drawImage(t,0,0,8,8);let n=e.getImageData(0,0,8,8).data;for(let r=0;r<n.length;r+=4){if(n[r]|n[r+1]|n[r+2])return true;let o=n[r+3];if(o!==0&&o!==255)return true}return false}var An;function Fy(){if(An!==void 0)return An;if(typeof OffscreenCanvas=="function")An=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),An=t?.getContext("2d",{willReadFrequently:true})??null;}return An??null}var Qi=false;async function uc(t,e,n,r){if(Qi){e.close(),n("busy",true);return}Qi=true;let o=null;try{let i=await Ny(t,r);if(typeof i=="string"){e.close(),n(i,$y(i));return}o=i;let a=await(r.encodeRef??(l=>Hy(l,r)))(o);if(o.close(),o=null,a===null){e.close(),n("failed",!0);return}if(a.size>Wy){e.close(),n("too_large",!1);return}e.postMessage(a);}catch(i){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",i);}finally{Qi=false,o?.close();}}function $y(t){switch(t){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}}var qy=600;async function Ny(t,e){if(e.handler){let o=await e.handler(t);return o===null?"declined":lc(o,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=By(n);if(!r)return "no_source";try{let o=await jy(r);return typeof o=="string"?o:lc(o,t)}catch(o){if(o instanceof DOMException&&o.name==="SecurityError")return "tainted";throw o}}async function jy(t){let e=Uy(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!Yi(e))return createImageBitmap(t);let n=await ic(t,qy);if(n)return n;let r=await ac(t);return r&&Xi(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function Uy(t){let e=Ji(t);if(e)return e;if(!zi(t))return "no_source";try{for(let n of ["webgl2","webgl","2d","webgpu"]){let r=t.getContext(n);if(r)return {kind:n,context:r}}}catch{return "unreadable"}return "unreadable"}function By(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let o=r.width*r.height;o<=0||r.clientWidth<=0||r.clientHeight<=0||!Ji(r)&&!zi(r)||o>n&&(e=r,n=o);}return e}async function lc(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let o=Math.min(n/t.width,r/t.height),i=Math.max(1,Math.floor(t.width*o)),s=Math.max(1,Math.floor(t.height*o));try{let a=await createImageBitmap(t,{resizeWidth:i,resizeHeight:s,resizeQuality:"high"});return t.close(),a}catch{return t.close(),"too_large"}}var Wy=8*1024*1024,dc="image/webp",cc=.92;async function Hy(t,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(t.width,t.height),s=i.getContext("2d");if(s){s.drawImage(t,0,0);let a=await i.convertToBlob({type:dc,quality:cc});if(a&&a.size>0)return a}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");return !o||(o.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(i=>{r.toBlob(s=>i(s),dc,cc);})}async function mc(t,e){if(!e)return;let n;try{n=await Vy(e);}catch(r){console.error("[gem] onFeedbackContext threw; sending the report without context",r);return}if(n!=null){if(typeof n!="object"||Array.isArray(n)){console.error("[gem] onFeedbackContext must return a plain object or null; got",n);return}t.sendGameContext(n);}}function Vy(t){return new Promise((e,n)=>{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()=>t())().then(i=>{r||(r=true,clearTimeout(o),e(i??null));},i=>{r||(r=true,clearTimeout(o),n(i instanceof Error?i:new Error(String(i))));});})}var pc=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function gc(t=globalThis){let n=t[pc];if(n!==void 0)return n;let r=false,o=()=>r,i=[],s=Ky(t,o);s!==null&&i.push(s);let a=Jy(t,o);a!==null&&i.push(a);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of i)c();}}};return Object.defineProperty(t,pc,{value:l,configurable:true}),l}function Ky(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let o=t.OfflineAudioContext,i=n.connect,s=n.disconnect,a=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(o!==void 0&&c instanceof o)return null;let p=a.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,i.call(p,m),a.set(c,p)),p};return n.connect=function(...c){let[p,...g]=c;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return i.call(this,y,...g),p}return i.apply(this,c)},n.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let y=a.get(p.context);if(y!==void 0&&y!==this)try{return s.call(this,y,...g)}catch{}}return s.apply(this,c)},()=>{for(let[m,c]of a){if(m.state==="closed"){a.delete(m);continue}try{l(c);}catch{}}}}function Jy(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,s=o?.set;if(i===void 0||s===void 0)return null;let a=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),s.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return a.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{s.call(g,(l.get(g)??!1)||e());}catch{}}}}var zy=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Yy=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Xy=`${zy}${Yy}`,Zi=new WeakSet;function yc(t=globalThis.document){if(t==null||Zi.has(t))return null;try{let e=t.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(t.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(Xy),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],Zi.add(t),"sheet"}let n=t.documentElement?.style;return n===void 0||typeof n.setProperty!="function"?null:(n.setProperty("-webkit-user-select","none"),n.setProperty("user-select","none"),n.setProperty("-webkit-tap-highlight-color","transparent"),Zi.add(t),"inline")}catch{return null}}function fc(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=t.now??(()=>globalThis.performance?.now()??Date.now()),o=false,i=false,s=false,a=null,l=null,d=null,m=[],c=false,p=0,g=null,y=[],v=()=>o&&!i&&!s,R=()=>{l=null,d=null,m=[],p=0,g=null,y=[];},x=S=>{if(a=null,!v()){R();return}if(d!==null&&m.push(S-d),d=S,l===null)l=S;else {let I=S-l;if(I>=e&&m.length>0){if(c){let T=g===null?I:r()-g;t.report(Zy(p,y,I,T));}else t.report(Qy(m,I));l=S,m=[],p=0,y=[];}}P();},P=()=>{let S=n.requestAnimationFrame;typeof S=="function"&&(a=S.call(n,x));},h=()=>{if(v()){a===null&&(R(),P());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),R();};return {setRequested(S){o=S,h();},setPaused(S){i=S,h();},draw(){if(!c){c=true,a!==null&&R();return}if(a===null||l===null)return;let S=r();g!==null&&y.length<1e3&&y.push(S-g),g=S,p+=1;},get running(){return a!==null},dispose(){s=true,h();}}}function Qy(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:hc(t),counts:"pageFrames"}}function Zy(t,e,n,r){let o=r;return e.length>0&&(o=hc(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:o,counts:"gameDraws"}}function hc(t){let e=[...t].sort((r,o)=>r-o),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var eo=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function bc(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function vc(t,e){t!==null&&(t.style.setProperty(eo.top,`${e.top}px`),t.style.setProperty(eo.right,`${e.right}px`),t.style.setProperty(eo.bottom,`${e.bottom}px`),t.style.setProperty(eo.left,`${e.left}px`));}var to=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height",centerY:"--gem-reserved-tl-center-y",controlHeight:"--gem-reserved-tl-control-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height",centerY:"--gem-reserved-tr-center-y",controlHeight:"--gem-reserved-tr-control-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height",centerY:"--gem-reserved-bl-center-y",controlHeight:"--gem-reserved-bl-control-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height",centerY:"--gem-reserved-br-center-y",controlHeight:"--gem-reserved-br-control-height"}});function _c(){let t=globalThis,e=t.innerWidth,n=t.innerHeight;return typeof e=="number"&&e>0&&typeof n=="number"&&n>0?{width:e,height:n}:null}function ef(t,e){let n={tl:{width:0,height:0,control:null},tr:{width:0,height:0,control:null},bl:{width:0,height:0,control:null},br:{width:0,height:0,control:null}};for(let r of t){let o=e?r.x+r.width/2<=e.width/2:r.x===0,i=e?r.y+r.height/2<=e.height/2:r.y===0,s=o?r.x+r.width:e?e.width-r.x:r.width,a=i?r.y+r.height:e?e.height-r.y:r.height,l=n[`${i?"t":"b"}${o?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));let d=r.control;if(d){let m=l.control;l.control=m?{top:Math.min(m.top,d.y),bottom:Math.max(m.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function wc(t,e,n){if(t===null)return;let r=ef(e,n);for(let o of ["tl","tr","bl","br"]){t.style.setProperty(to[o].width,`${r[o].width}px`),t.style.setProperty(to[o].height,`${r[o].height}px`);let i=r[o].control;t.style.setProperty(to[o].centerY,i?`${(i.top+i.bottom)/2}px`:""),t.style.setProperty(to[o].controlHeight,i?`${i.bottom-i.top}px`:"");}}var tf=3e4,no=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Sc(t){let e=t.clock??ue,n=t.timeoutMs??tf,r=new Map,o=new Map,i=0,s=a=>{let l=r.get(a);return l?(r.delete(a),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(a){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(a);if(l)return l;let d=new Promise((m,c)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(a),c(new no("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(p,{room:a,resolve:m,reject:c,timer:g}),t.bridge.requestLocalServer(p,a)||(s(p),m());});return o.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new no(a.reason,a.retryable,a.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var xn={url:"https://downloads.indiegems.games/sdk/v16.0.1/gem-web-sdk.devtools.min.js",integrity:"sha384-7K6H+jP3KWTKNRZ8QakllImPKmZzpi0SlfGWtJyrwD74j2UDAI2ATUmFb1x/Y3/5"};var Dt=null;function nf(){return Dt!==null||(Dt=new Promise((t,e)=>{let n=document.createElement("script");n.src=xn.url,n.integrity=xn.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Dt=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${xn.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Dt=null,e(new Error(`gem devtools: could not load ${xn.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(n);})),Dt}function Rc(t,e){let n=null,r=0;async function o(i){if(n!==null)return true;let s=++r;if(!e())return false;let a=await nf();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:i,text:rt,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>o("game"),openFrom:o}}var rf=1e4,kc={reason:"unavailable",retryable:false};function Ac(t){let e=new Map,n=null,r=null,o=0,i=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??rf);},s=(d,m)=>{let c=a(d);c&&m(c);},a=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new _t({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,c)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){c(kc);return}let g=`t${++o}`,y={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,y),i(g,y),y.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){s(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),i(m,c),t.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])s(m,c=>c.reject(kc));},get identity(){return n},get gameVersion(){return r}}}function of(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var af=new Set(Jn);function sf(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))af.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function ro(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return Xa(async(n,r)=>{let o;try{o=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new ae("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(/\/+$/,"")+n.path);}catch{throw new ae(`${JSON.stringify(typeof n.path=="string"?of(n.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 ae(`${JSON.stringify(i.pathname)} resolves to ${i.protocol}//${i.host}, not ${o.protocol}//${o.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(i.username!==""||i.password!==""){let g=o.username!==""||o.password!=="",y=i.username!==o.username||i.password!==o.password,v=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new ae(`the ${v} puts credentials in the URL, which cannot be fetched (${n.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(t.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,y);let s=n.bytes,a=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(s=JSON.stringify(n.body),a="application/json");}catch(g){throw new ae(`the body of ${n.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:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...sf(n.headers)},body:s,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),c=lf(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},t)}function lf(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}var df=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),ta="embedder_relay_unavailable",cf="embedder_no_relay",uf=new Set([ta]),na=new Set([cf]),Pn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new ea(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.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){n.refuse(new w("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(mf(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new w("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,n);}release(e,n){this.pending.get(e)===n&&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 mf(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new w(pf(t),r,{platformCode:t})}function pf(t){return t===void 0||uf.has(t)?"signaling_failed":na.has(t)?"offer_refused":df.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var ea=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){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 n?.aborted?Promise.reject(new w("aborted","the caller aborted before the offer was sent")):new Promise((o,i)=>{let s=()=>{a(),i(new w("aborted","the caller aborted the signaling exchange"));},a=()=>{n?.removeEventListener("abort",s),this.hub.release(e.matchId,l),this.teardown===a&&(this.teardown=null);},l={settle:d=>{a(),o(d);},refuse:d=>{a(),i(d);}};this.teardown=a,n?.addEventListener("abort",s),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof w?d:new w("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var xc="match_ended:",Pc="server_shutdown:",Tc="kicked:",gf=123;function yf(t){if(typeof t!="string"||t.length===0||t.length>gf)return {kind:"other"};if(t.startsWith(xc)){let e=Je(t.slice(xc.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Pc)?{kind:"server_shutdown",cause:t.slice(Pc.length)}:t.startsWith(Tc)?{kind:"kicked",detail:t.slice(Tc.length)}:{kind:"other"}}function ra(t,e,n){let r=yf(n),o=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(o).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function oa(){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 ff=3e3,hf=1e4,bf=15e3;async function oo(t){let e=t.peerConnection;try{Ic(t,"before the handshake started"),ia(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let s of t.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});t.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await wf(e,t),ia(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new w("invalid_sdp","the offer carried no SDP");ze(o,"offer"),Ec(o,"offer");let i=await _f(t,o);if(ia(t),typeof i?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return ze(i.sdp,"answer"),Ec(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await Sf(n,t),Ic(t,"before the channel opened"),n}catch(n){throw e.close(),vf(n)}}function vf(t){return t instanceof w?t:Oc(t)?ut():new w("connection_failed",Gc(t),{cause:t})}function Ec(t,e){if(Kr(t))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 _f(t,e){let n=t.exchangeTimeoutMs??hf,r=Mc(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof w?i:Oc(i)?ut():new w("signaling_failed",Gc(i),{cause:i})});return Rf(o,t,r,()=>r.exhausted?aa("while the offer was in flight"):new w("timeout",`no answer arrived within ${n}ms`))}function wf(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let o=()=>{n.clearTimeout(s),t.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{t.iceGatheringState==="complete"&&o();},s=n.setTimeout(o,e.gatherTimeoutMs??ff);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function Sf(t,e){if(e.signal?.aborted)return Promise.reject(ut());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new w("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??bf,o=Mc(e,r);return new Promise((i,s)=>{let a=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{a(),i();},d=g=>{a(),s(new w("connection_failed","the data channel failed before it opened",Cc(g)===void 0?void 0:{cause:Cc(g)}));},m=()=>{a(),s(ut());},c=()=>{a(),s(o.exhausted?aa("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(c,o.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Mc(t,e){if(t.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let n=t.credentialExpiresAt-t.clock.now();return n<=e?{ms:Math.max(0,n),exhausted:true}:{ms:e,exhausted:false}}function Rf(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(ut()):new Promise((s,a)=>{let l=c=>{o.clearTimeout(m),i?.removeEventListener("abort",d),c();},d=()=>l(()=>a(ut())),m=o.setTimeout(()=>l(()=>a(r())),n.ms);i?.addEventListener("abort",d),t.then(c=>l(()=>s(c)),c=>l(()=>a(c)));})}function Ic(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw aa(`already ${e}`)}function aa(t){return new w("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function ia(t){if(t.signal?.aborted)throw ut()}function ut(){return new w("aborted","the caller aborted the connection attempt")}function Oc(t){return t?.name==="AbortError"}function Cc(t){return t?.error}function Gc(t){return t instanceof Error?t.message:String(t)}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:[X("sdp","sdp",V(10240)),K("sessionId","session_id",V(64))],error:[K("code","code",V(64)),K("message","message",V(256))],matchEnded:[K("reason","reason",V(64))]}));function Uc(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??oa,i=t.log??(h=>console.warn(h)),s=new Ct({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,S)=>{let I=a.get(h)??new Set;I.add(S),a.set(h,I);},d=(h,S)=>{let I=a.get(h);I!==void 0&&(I.delete(S),I.size===0&&a.delete(h));},m=async h=>{if(r.isHost&&!la(r)&&r.currentRoom?.matchId===void 0){let S=be(h.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},...h.retry===void 0?{}:{retry:h.retry},...h.signal===void 0?{}:{signal:h.signal}});}return Nc(r.matchConnectionState==="suspended"?await r.reconnectToMatch(sa(h)):await r.awaitMatch(sa(h)))},c=async h=>Nc(await r.pollMatchStatus(sa(h))),p=async(h,S)=>{let I=false;try{let T=await m(h),W=r.currentRoom?.transports;if(W!==void 0&&!W.includes("webrtc"))throw new w("misconfigured",`the room template offers (${W.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 q=h.peerConnection??jc();I=!0;let U=await oo({peerConnection:q,signaling:S,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...io(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),E=null;if(h.presentCredential!==!1)try{E=await dn({channel:U,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...io(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(M){throw Te(U),Te(q),M}return Mf(r,T,U,q,S,h.reportDisconnect!==!1,h.reportConnected!==!1,E,{remember:l,forget:d},h.onMatchEnded)}catch(T){throw I&&qc(s,T),Te(S),T}},g=async(h,S,I,T,W,q)=>{if(h==="webtransport"){let B=T?.webtransport;if(B===void 0)throw new w("misconfigured","webtransport is not advertised");let J={credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n};if(typeof B.named_url=="string"&&B.named_url!==""){let oe=Math.max(Math.floor(q/2),1e3);try{return await pn({url:B.named_url,timeoutMs:oe,log:i,...J})}catch(ge){if(qr()!==null)throw ge;return i(`[gem] webtransport named dial failed (${Fr(ge)}); retrying the pinned dial`),pn({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:oe,log:i,...J})}}return pn({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:q,...J})}if(h==="websocket"){let B=T?.websocket;if(B===void 0)throw new w("misconfigured","websocket is not advertised");return Si({url:B.url,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n,timeoutMs:q})}let U=S.peerConnection??jc(),E,M=await oo({peerConnection:U,signaling:W,clock:n,matchId:I.matchId,credentialExpiresAt:I.credentialExpiresAt,extraChannels:[{label:un,ordered:false,maxRetransmits:0}],onExtraChannel:(B,J)=>{B===un&&(E=J);},...io(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:xf}:{}}),F;try{F=await dn({channel:M,clock:n,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,wire:Dr,heartbeat:!0,...io(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(B){throw Te(M),Te(U),B}let N=F.welcome.heartbeatIntervalMs;return {link:ki(M,U,E,N===void 0?void 0:{clock:n,intervalMs:N}),welcome:F.welcome,channel:M,peerConnection:U}},y=(h,S,I,T,W)=>{let q=false,U;T.link.onClose(N=>{!q&&h.reportDisconnect!==false&&ra(r,S.matchId,N),U?.(N);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let E={transport:T.link.transport,send:(N,B)=>T.link.send(N,B),onMessage:N=>T.link.onMessage(N),onClose:N=>{U=N;},close:()=>T.link.close()},M=()=>{q||(q=true,Te(T.link),Te(W));},F=N=>{if(!q){try{h.onMatchEnded?.(N);}catch{}M();}};return l(S.matchId,F),{matchId:S.matchId,transport:I,link:E,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,F),M();}}},v=async(h,S)=>{let I=r.currentRoom?.id,T=r.gameId,W=()=>({advert:mn(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(I===void 0||T===null)return W();try{let q=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(I)}`,S);return {advert:mn(q.settings,h),template:Et(q.transports)??r.currentRoom?.transports??null}}catch{return W()}},R=(h,S)=>{let I=h??Lc;return S.length===0?I:I.filter(T=>S.includes(T))},x=async(h,S,I)=>{try{let T=await m(h),{advert:W,template:q}=await v(T.matchId,h.signal),U=R(q,S),E=U.filter(Y=>Ef(Y,W)),M=qr();if(M!==null&&U.includes("webtransport")&&W?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${M} (learned on an earlier dial in this page)`),E.length===0){let Y=q===null?`the default order (${Lc.join(", ")})`:`the room template's transports (${q.join(", ")||"none"})`;throw new w("misconfigured",`none of ${Y}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let F=h.transportAttemptTimeoutMs??Af,N=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-n.now(),B=Y=>t.signalingReady===void 0||Y<=0?Promise.resolve(!0):t.signalingReady(Y),J=[],oe=[];for(let Y of E){if(N()<Fc){i(`[gem] ${Y} rung not tried: the reconnect budget is spent`);break}oe.length>0&&T.credentialExpiresAt-n.now()<$c&&(T=await c(h)),oe.push(Y);let Ne=!1,Re=!1,ye={attempts:0,waitedMs:0};for(;;){if(Y==="webrtc"&&h.redial===!0){let te=Math.min(Dc,N());await B(te)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let je=Math.max(Math.min(F,N()),Fc);try{return y(h,T,Y,await g(Y,h,T,W,I,je),I)}catch(te){let z=te instanceof w?te:new w("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(Y==="webrtc"&&qc(s,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Ne){Ne=!0,T=await c(h);continue}if(Y==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===ta&&!Re){Re=!0;let se=Math.min(Dc,N());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 B(se))continue}if(z.reason==="join_rate_limited"){let se=Tf(ye,Math.random,N());if(se!==null){if(ye.attempts+=1,ye.waitedMs+=se,i(`[gem] ${Y} rung: the server is rate-limiting this player's joins; waiting ${Math.round(se)}ms before presenting again (retry ${ye.attempts} of ${Wc.maxAttempts})`),await Mr(n,se,h.signal),h.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<$c&&(T=await c(h));continue}}if(Pf.has(z.reason)||z.reason==="credential_expired"||Y==="webrtc"&&Bc(z)){i(`[gem] ${Y} rung failed (${z.reason}): ${Fr(z.cause??z)} \u2014 `+(oe.length<E.length?`falling through to ${E[oe.length]}`:"no rungs left")),J.push(z);break}throw i(`[gem] ${Y} rung refused the session (${z.reason}): ${z.message}`),z}}}let ge=J[J.length-1];throw ge===void 0?new w("timeout",`the reconnect budget ran out before any transport (${E.join(", ")}) could be tried`):new w(ge.reason,`every transport tried (${oe.join(", ")}) failed; the last said: ${ge.message}`,{cause:J,platformCode:ge.platformCode})}catch(T){throw Te(I),T}};return {listClusterTargets:async(h={})=>si({client:e,...h}),handleMatchEnded(h,S){let I=a.get(h);if(I!==void 0){a.delete(h);for(let T of I)T(S);}},connect:(async(h={})=>{let S=h.signaling??o();return h.transports===void 0?p(h,S):x(h,h.transports,S)})}}var Lc=["webtransport","webrtc","websocket"],Af=1e4,xf=5e3,Dc=3e3,Fc=1e3,$c=1e4,Pf=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Bc(t){return t.platformCode!==void 0&&na.has(t.platformCode)}var Wc={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Tf(t,e=Math.random,n=1/0){let r=Wc;if(t.attempts>=r.maxAttempts)return null;let o=Math.min(r.budgetMs-t.waitedMs,n);if(o<r.initialDelayMs)return null;let i=r.initialDelayMs*r.factor**t.attempts;return Math.min(i+e()*r.jitterMs,o)}function Ef(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&$r():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||If(e.websocket.url)}function If(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return He(e)}function sa(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var Cf=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function qc(t,e){e instanceof w&&(!Cf.has(e.reason)&&!Bc(e)||t.report([{type:"connection_failures_total",value:1}]));}function Mf(t,e,n,r,o,i,s,a,l,d){let m=false,c=()=>{m||ra(t,e.matchId,void 0);};i&&(n.addEventListener("close",c),s&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",c),a?.detach(),Te(n),Te(r),Te(o));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function la(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Nc(t){if(t.status==="failed")throw new w("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new w("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Cr)throw new w("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Cr}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:n}=t;if(e===void 0||n===void 0)throw new w("connection_failed",`match ${t.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...t,joinCredential:e,credentialExpiresAt:n}}function jc(){let t=globalThis.RTCPeerConnection;if(!t)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 t({iceServers:[]})}function Te(t){try{t.close();}catch{}}function io(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var Of=1e4;function Hc(t,e){return da(t,e)}function da(t,e){if(typeof t.serverToken!="function"||typeof t.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 n=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new _t({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((s,a)=>{let l=e.clock.setTimeout(()=>{r=null,a({reason:"unavailable",retryable:true});},e.timeoutMs??Of);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),i=t.onServerToken(s=>{let a=n(s),l=r;if(l){r=null,l.resolve(a);return}o.accept(a);});return {source:o,dispose(){i(),o.dispose(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var ua={};fm(ua,{acceptTransfer:()=>Gf,addEntityProgression:()=>Lf,adminAction:()=>Df,cancelInventoryTransfer:()=>Ff,claimEntityProgressionRewards:()=>$f,closeGameRoom:()=>qf,createEntityBatchOrder:()=>Nf,createEntityOrder:()=>jf,createSession:()=>Uf,deleteEntityGameSetting:()=>Bf,deleteEntitySave:()=>Wf,deleteSession:()=>Hf,deleteShowcaseValue:()=>Vf,executeEntityRecipe:()=>Kf,finalizeSaveUpload:()=>Jf,getChannelAssignment:()=>zf,getDropRates:()=>Yf,getEntityCurrency:()=>Xf,getEntityGameSetting:()=>Qf,getEntityInventory:()=>Zf,getEntityInventoryItem:()=>eh,getEntityLeaderboard:()=>th,getEntityOrder:()=>nh,getEntityProgression:()=>rh,getEntityRecipeAvailability:()=>oh,getEntityRecipeUsage:()=>ih,getEntitySave:()=>ah,getEvent:()=>sh,getGameRoomV2:()=>lh,getLeaderboard:()=>dh,getPlayerGameProfile:()=>ch,getPurchaseCatalog:()=>uh,getResolvedTemplate:()=>mh,getRoomArgs:()=>ph,getShowcaseValue:()=>gh,getTransferDetails:()=>yh,ingestAnalyticsEvents:()=>ca,initiateInventoryTransfer:()=>fh,invokeFunction:()=>hh,kickPlayer:()=>bh,listChallenges:()=>vh,listEntityGameSettings:()=>_h,listEntityOrders:()=>wh,listEntityProgressions:()=>Sh,listEntitySaves:()=>Rh,listEvents:()=>kh,listGameRooms:()=>Ah,listResolvedTemplates:()=>xh,listTransfers:()=>Ph,maxEntityProgression:()=>Th,putEntityGameSetting:()=>Eh,putRoomArgs:()=>Ih,putShowcaseValue:()=>Ch,rejectTransfer:()=>Mh,reportMatchPlayers:()=>Oh,requestSaveUploadUrl:()=>Gh,resetEntityProgression:()=>Lh,setMatchBackfill:()=>Dh,simulateEntityOrder:()=>Fh,transferHostV2:()=>$h,updateGameRoomV2:()=>qh});function b(t){let e=String(t);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 Gf(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Lf(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/add`;return t.client.post(s,o,i?.signal)}async function Df(t,e,n,r){let o=`/v1/voice/sessions/${b(e)}/admin`;return t.client.post(o,n,r?.signal)}async function Ff(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function $f(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/claim`;return t.client.post(s,o,i?.signal)}async function qf(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.delete(r,n?.signal)}async function Nf(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function jf(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Uf(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Bf(t,e,n,r,o){let i=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(i,o?.signal)}async function Wf(t,e,n,r,o){let i=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(i,o?.signal)}async function Hf(t,e,n){let r=`/v1/voice/sessions/${b(e)}`;return t.client.delete(r,n?.signal)}async function Vf(t,e,n,r){let o=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.delete(o,r?.signal)}async function Kf(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Jf(t,e,n,r,o,i){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/finalize`;return t.client.post(s,o,i?.signal)}async function zf(t,e,n){let r=`/v1/games/${b(t.gameId())}/config/channels/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Yf(t,e,n){let r=`/v1/inventory/loot-tables/${b(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Xf(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/currencies/${b(r)}`;return t.client.get(i,o?.signal)}async function Qf(t,e,n,r,o){let i=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Zf(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),s=`/v1/inventory/${b(e)}/${b(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function eh(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/items/${b(r)}`;return t.client.get(i,o?.signal)}async function th(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let s=i.toString(),a=`/v1/leaderboards/${b(e)}/${b(n)}/${b(r)}`+(s?`?${s}`:"");return t.client.get(a,o?.signal)}async function nh(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders/${b(r)}`;return t.client.get(i,o?.signal)}async function rh(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}`;return t.client.get(i,o?.signal)}async function oh(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/catalogs/${b(r)}/recipes/${b(o)}/availability`;return t.client.get(s,i?.signal)}async function ih(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),s=`/v1/inventory/${b(e)}/${b(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function ah(t,e,n,r,o){let i=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function sh(t,e,n){let r=`/v1/events/${b(e)}`;return t.client.get(r,n?.signal)}async function lh(t,e,n){let r=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function dh(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${b(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function ch(t,e,n){let r=`/v1/profiles/players/${b(e)}`;return t.client.get(r,n?.signal)}async function uh(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function mh(t,e,n){let r=`/v1/game-room-templates/${b(e)}`;return t.client.get(r,n?.signal)}async function ph(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.get(r,n?.signal)}async function gh(t,e,n,r){let o=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.get(o,r?.signal)}async function yh(t,e,n){let r=`/v1/inventory/transfers/${b(e)}`;return t.client.get(r,n?.signal)}async function ca(t,e,n){let r=`/v1/games/${b(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function fh(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function hh(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function bh(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/kick/${b(n)}`;return t.client.post(o,void 0,r?.signal)}async function vh(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),o="/v1/challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function _h(t,e,n,r){let o=`/v1/settings/${b(e)}/${b(n)}`;return t.client.get(o,r?.signal)}async function wh(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),s=`/v1/inventory/${b(e)}/${b(n)}/orders`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Sh(t,e,n,r){let o=`/v1/inventory/${b(e)}/${b(n)}/progressions`;return t.client.get(o,r?.signal)}async function Rh(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),s=`/v1/saves/${b(e)}/${b(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function kh(t,e){let n=new URLSearchParams;e?.include_inactive!==void 0&&n.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.offset!==void 0&&n.set("offset",String(e?.offset));let r=n.toString(),o="/v1/events"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Ah(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o=`/v1/games/${b(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function xh(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function Ph(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Th(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/max`;return t.client.post(s,o,i?.signal)}async function Eh(t,e,n,r,o,i){let s=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.put(s,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ih(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.put(o,n,r?.signal)}async function Ch(t,e,n,r,o){let i=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.put(i,r,o?.signal)}async function Mh(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Oh(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/matches/${b(e)}/players/report`;return t.client.post(o,n,r?.signal)}async function Gh(t,e,n,r,o,i){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/upload-url`;return t.client.post(s,o,i?.signal,{replaySafe:true})}async function Lh(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/reset`;return t.client.post(s,o,i?.signal)}async function Dh(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/matches/${b(e)}/backfill`;return t.client.put(o,n,r?.signal)}async function Fh(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders/simulate`;return t.client.post(i,r,o?.signal)}async function $h(t,e,n,r){let o=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}/transfer/${b(n)}`;return t.client.post(o,void 0,r?.signal)}async function qh(t,e,n,r){let o=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.patch(o,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Nh=1e4,jh=50,Uh=1e3,Bh=65536-4*1024,Vc=t=>typeof t=="number"?t:0,Wh=t=>typeof t=="string"?t:"";function Kc(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function Hh(t){return t?.retryable===true}function Vh(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:Vc(i.index),code:Wh(i.code)}}):[];return {accepted:Vc(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Jc(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,player_id:t.playerId,dimensions:t.dimensions,measures:t.measures}}function zc(t){let e=Math.max(1,Math.floor(t.maxQueue??Uh)),n={client:t.client,gameId:()=>t.gameId},r=[],o=0,i=null,s=false,a=null,l=0,d=0,m=false,c=false,p=h=>{t.log?.(h);},g=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},y=()=>Math.max(0,d-t.clock.now()),v=()=>{i!==null||s||a!==null||(i=t.clock.setTimeout(()=>{i=null,x().catch(()=>{});},Math.max(Nh,y())));},R=()=>{let h=Math.min(r.length,100),S=128;for(let I=0;I<h;I+=1){let T=r[I];if(T===void 0)break;if(S+=JSON.stringify(Jc(T,0)).length+1,S>Bh)return Math.max(1,I)}return h};async function x(h){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let S=P(h);a=S;try{return await S}finally{a===S&&(a=null),r.length>0&&v();}}async function P(h){g();let S=r.splice(0,R()),I=o;o=0;let T=Math.round(t.clock.now()),W={batch_id:Kc(),sent_at_ms:T,events:S.map(q=>Jc(q,T))};try{let q=await ca(n,W,h===void 0?void 0:{signal:h}),U=Vh(q,I);l=0,d=0;for(let E of U.rejected)p(`[gem] analytics: an event was refused (${E.code}). See the analytics_events section of your game config.`);return U}catch(q){if(Hh(q)){for(r=[...S,...r],o+=I;r.length>e;)r.shift(),o+=1;l+=1,d=t.clock.now()+Tr(l,q);}else p(`[gem] analytics: ${S.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(q)}`);throw q}}return {track(h,S,I={}){if(s)return;if(typeof h!="string"||h===""){c||(c=true,p(`[gem] analytics: '${S}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(S.startsWith(Xo)){m||(m=true,p(`[gem] analytics: '${S}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let T={},W={};for(let[q,U]of Object.entries(I))typeof U=="string"?T[q]=U:typeof U=="number"&&Number.isFinite(U)&&(W[q]=U);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:Kc(),playerId:h,name:S,atMs:t.clock.now(),dimensions:T,measures:W}),r.length>=jh&&a===null&&y()===0?x().catch(()=>{}):v();},flush:h=>x(h),get pending(){return r.length},dispose(){s=true,g(),r=[],o=0;}}}function Yc(t){return {async list(e){let{playerId:n,periodsBack:r,signal:o}=e??{};if(typeof n!="string"||n==="")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().");xt(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return wr(i)}}}function Kh(t){let e={};for(let[n,r]of Object.entries(ua))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function Ft(t,e={}){let n=e.clock??ue,r=e.baseUrl??t.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=da(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=ro({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new We({transport:i,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=Kh({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,m=t.endMatch,c=t.log,p=zc({client:s,clock:n,gameId:a.gameId,...typeof c=="function"?{log:y=>c.call(t,y)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);},setBackfill:async(y,v)=>{let R=await l.setMatchBackfill(a.matchId,{open:y.open,...y.seats===void 0?{}:{seats:y.seats}},v===void 0?{}:{signal:v});return {open:R.open,seats:R.seats??null}},reportPlayers:async(y,v)=>(await l.reportMatchPlayers(a.matchId,{players:y.map(x=>({player_id:x.playerId,state:x.state}))},v===void 0?{}:{signal:v})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new Ke(l.invokeFunction),challenges:Yc(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let v=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),R=v.modified?v.body:void 0;if(R?.room_args==null||R.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:R.room_args,room_args_template:R.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function mt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function $t(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function Tn(t){return typeof t=="string"?t:t.slice().buffer}function ao(t){if(typeof t=="string")return {data:t,isText:true};if(t instanceof ArrayBuffer)return {data:new Uint8Array(t),isText:false};if(ArrayBuffer.isView(t)){let e=t;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var Jh=5e3,Xc=3e4,Qc=2e3,zh=1e4,Yh=3,Zc=1;async function eu(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let o=e.log===void 0?f=>console.info(f):e.log,i=f=>o?.(`[gem host] ${f}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,m=(f,C)=>{l&&(a=a.then(async()=>{if(!d)try{await C();}catch(L){i(`the bundle's ${f} handler threw: ${pt(L)}. Serving continues.`);}}));},c=true,p,g,y,v=f=>{if(!c)return;c=false,m("leave",()=>s.leave?.(r,{cause:f??"left"}));let C=g;C&&queueMicrotask(()=>C(f));},R={send(f,C){if(!c)return;let L=$t(mt(C));m("message",()=>s.message?.(r,f,typeof f=="string",{reliable:L.reliable,ordered:L.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){v("closed");}},x=(f,C)=>{if(!c)return;let L=$t(mt(C));queueMicrotask(()=>{c&&p?.(f,L);});},P=new Map,h=f=>{let C=[];for(let L of qe){let Z=f.channels[L];try{Z.binaryType="arraybuffer";}catch{}let we=$t(L),Fn=ht=>{let jt=ao(ht?.data);jt!==null&&m("message",()=>s.message?.(f.playerId,jt.data,jt.isText,{reliable:we.reliable,ordered:we.ordered}));};Z.addEventListener("message",Fn),C.push(()=>Z.removeEventListener("message",Fn));}P.get(f.playerId)?.forEach(L=>L()),P.set(f.playerId,C);},S=f=>{P.get(f)?.forEach(C=>C()),P.delete(f);},I=new Set,T=new Map,W=(f,C,L)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...C?{rejoin:true}:{},...L?{superseded:true}:{}}),q=f=>{let C=P.has(f.playerId),L=I.has(f.playerId);I.add(f.playerId),h(f),C&&m("leave",()=>s.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>s.join?.(f.playerId,W(f,L,C)));},U=new Set,E=(f,C,L)=>{if(f===r){x(C,L);return}let Z=n.peer(f);if(Z===null){let we=T.get(f);if(we!==void 0&&e.clock.now()-we<Qc)return;U.has(f)||(U.add(f),i(`send to '${f}' dropped: no such connected player`));return}Z.send(Tn(C),mt(L));},M={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=c?[r]:[];for(let C of n.peers)f.push(C.playerId);return f},profile(f){let C=e.room()?.members.find(L=>L.playerId===f);if(!(!C||C.displayName===void 0))return {displayName:rt.toPlain(C.displayName),...C.displayTag===void 0?{}:{displayTag:rt.toPlain(C.displayTag)},...C.discriminator===void 0?{}:{discriminator:C.discriminator}}},playerNumber(f){return f===r?Zc:n.peer(f)?.assignedPeerId},send(f,C,L){E(f,C,L);},broadcast(f,C){let L=C?.except;c&&r!==L&&x(f,C);for(let Z of n.peers)Z.playerId!==L&&Z.send(Tn(f),mt(C));},async endMatch(){let f=await je();return f.answer!=="ok"&&i(f.cause),f.answer},kick(f,C){if(f===r){v(C??"kicked");return}n.kick(f).catch(L=>{i(`kick of '${f}' failed: ${pt(L)}`);});},log(f){i(f);},warn(f){i(`\u26A0 ${f}`);}},F=()=>{},N=new Promise(f=>{F=f;}),B=[],J=null,oe=async(f,C)=>{l=false;let L=a.then(async()=>{try{await s.shutdown(f);}catch(Z){i(`the bundle's shutdown threw: ${pt(Z)}`);}});a=L,await L,Fe();for(let Z of B.splice(0))Z();for(let Z of [...P.keys()])S(Z);v(C);},ge=(f,C)=>J||(J=(async()=>{await oe(C,f),n.close(),F();})(),J),Y=()=>J||(J=(async()=>{await oe({reason:"signal"},"left"),await n.leave().catch(f=>i(`leaving the match failed: ${pt(f)}`)),F();})(),J),Ne=()=>J||(J=(async()=>{l=false;let f=await je();f.answer==="ok"?(await oe({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${f.cause}; leaving instead`),await oe({reason:"signal"},"left"),await n.leave().catch(C=>i(`leaving the match failed: ${pt(C)}`))),F();})(),J),Re=null,ye=()=>(Re??=Ft(M,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Re),je=async()=>{try{return await Zs({client:ye().client,gameId:()=>M.gameId},M.matchId,{},{signal:AbortSignal.timeout(Jh)}),{answer:"ok"}}catch(f){return f instanceof O&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${pt(f)}`}}},te=null,z=false,se=0,xe,Ue=null,Fe=()=>{z=true,te!==null&&(e.clock.clearTimeout(te),te=null),Ue?.(),Ue=null;},yt=f=>{i(`heartbeats paused: ${f}; they resume when a fresh play token arrives`),Ee();let C=xe,L=false,Z=e.tokens.subscribe(we=>{L||z||we.token===C||Nt(we)||(L=true,Ue?.(),Ue=null,se=0,xe=void 0,Ee(),i("a fresh play token arrived; heartbeats resume"),te=e.clock.setTimeout(()=>{Be();},0));});L?Z():Ue=Z;},Ee=()=>{let f=Re;Re=null,f?.dispose();},Nt=f=>f.expiresAt*1e3<=e.clock.now(),Be=async()=>{if(te=null,!z){try{await ye().client.post(`/v1/games/${encodeURIComponent(M.gameId)}/matches/${encodeURIComponent(M.matchId)}/heartbeat`,void 0,AbortSignal.timeout(zh)),se=0,xe=void 0;}catch(f){if(f instanceof O&&(f.reason==="forbidden"||f.reason==="not_found")){i(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),Fe();return}if(Xh(f)){if(z)return;se+=1;let C=e.tokens.current(),L=C===void 0?"this host holds no play token":Nt(C)?"this host's play token has expired":C.token===xe?"the platform refused this host's play token again":se>=Yh?`the platform refused this host's play token ${se} times in a row`:null;if(xe=C?.token,L!==null){yt(L);return}}else se=0,xe=void 0;i(`heartbeat failed: ${pt(f)}`);}z||(te=e.clock.setTimeout(()=>{Be();},Xc));}},yo=()=>{z||te!==null||(te=e.clock.setTimeout(()=>{Be();},Xc));};{let f=F;F=()=>{Fe(),Re?.dispose(),Re=null,f();};}let ft=Promise.resolve().then(()=>s.init(M));a=ft.then(()=>{},()=>{}),m("join",()=>s.join?.(r,{playerNumber:Zc,transport:"loopback"})),B.push(n.on("peerJoined",q)),B.push(n.on("peerLeft",(f,C)=>{S(f);let L=e.clock.now();for(let[Z,we]of T)L-we>=Qc&&T.delete(Z);T.set(f,L),U.delete(f),m("leave",()=>s.leave?.(f,{cause:C}));})),B.push(n.on("error",f=>{i(`\u26A0 session error: ${f.message}`);})),B.push(n.on("matchEnded",f=>{J||ma(y,f),ge("match ended",{reason:"match_ended",platform_reason:f});})),B.push(n.on("hostChanged",f=>{f!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)q(f);try{await ft,yo();}catch(f){l=false,Fe(),d=true;for(let C of B.splice(0))C();for(let C of [...P.keys()])S(C);throw n.leave().catch(()=>{}),F(),f}return {matchId:n.matchId,localLink:R,onMatchEnded(f){y=f;},end:Ne,leave:Y,stop:f=>ge(f,{reason:"stopped"}),done:N}}function ma(t,e){try{t?.(e);}catch{}}function Xh(t){return t instanceof O&&t.status===401||ne.isAuthError(t)}function pt(t){return t instanceof Error?t.message:String(t)}function pa(t,e){let n=async()=>{throw new w("misconfigured",`this seat is \`${t}\`, not the match's authority: `+(t==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:t,matchId:e,end:n,leave:n,stop:async()=>{}}}function tu(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async a=>{r.isHost&&!la(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...a.signal===void 0?{}:{signal:a.signal}});let l={...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},s=a=>({...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0?{}:{clusterTargetId:a.clusterTargetId}});return {async serve(a,l={}){let d=await i(l);if(d.protocol!==ct)return pa("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return pa("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(s(l)),g=await eu(a,{session:p,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return o.set(d.matchId,g),g.done.then(()=>{o.get(d.matchId)===g&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(a={}){let l=await i(a),d=a.onMatchEnded;if(l.protocol===ct){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),tb(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 _n(),v=async()=>t.p2p.connect({...s(a),certificate:y}),R=await v(),x=rb(R,v,d,P=>{r.notifyMatchDisconnected(P).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(R.matchId,{redial:x.redial,abandon:x.abandon}),x.onClosed(()=>{e.get(R.matchId)?.abandon===x.abandon&&e.delete(R.matchId);})),x}let m=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),c=await m(),p=nb(c,m,r,n);return n&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var nu="link_closed",Qh="host_unreachable",Zh=new Set(["failed","closed"]);function eb(t){return Zh.has(t)?nu:Qh}function tb(t,e,n){let r=e.localLink;e.onMatchEnded(n);let o="connected";r.onClose(()=>{o="closed";});let i;return {matchId:t,protocol:"loopback",get state(){return o},send:(s,a)=>r.send(s,a),onMessage:s=>r.onMessage(s),onClose:s=>{i=s,r.onClose(a=>{o="closed",i?.(a);});},close:()=>r.close()}}function nb(t,e,n,r){let o=t.matchId,i=t,s="connected",a,l,d=[],m=false,c=false,p=y=>{if(s!=="closed"){s="closed";for(let v of d.splice(0))v();l?.(y);}},g=y=>{y.link.onMessage((v,R)=>a?.(v,R)),y.link.onClose(v=>{if(y!==i||s==="closed")return;if(m||!r){p(v);return}let R=n.matchSession;if(R.phase==="suspended"&&R.matchId===o){s="suspended";return}p(v);});};return g(t),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return s},send(y,v){s==="connected"&&i.link.send(y,v);},onMessage(y){a=y;},onClose(y){l=y;},close(){if(s!=="closed"){if(m=true,s==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(s==="closed"||m)return "closed";if(c)return "connected";c=true;let v;try{v=await e(y===void 0?{}:{deadlineAt:y});}finally{c=false;}return m||s==="closed"?(v.close(),"closed"):(i=v,g(v),s="connected",n.notifyMatchConnected(o),"connected")},abandon(y){s!=="closed"&&(s==="connected"&&i.close(),p(y));},onClosed(y){s==="closed"?y():d.push(y);}}}function rb(t,e,n,r,o,i=false){let s=t.matchId,a=t,l,d,m=[],c=[],p=[],g=false,y=false,v=false,R=false,x="connected",P=E=>{if(g)return;g=true,x="closed";for(let F of m.splice(0))F();for(let F of c.splice(0))F();for(let F of p.splice(0))F();let M=d;M&&queueMicrotask(()=>M(E));},h=E=>{for(let M of m.splice(0))M();for(let M of qe){let F=E.channels[M];try{F.binaryType="arraybuffer";}catch{}let N=$t(M),B=J=>{let oe=ao(J?.data);oe!==null&&l?.(oe.data,N);};F.addEventListener("message",B),m.push(()=>F.removeEventListener("message",B));}},S=()=>a.peer(a.hostPlayerId),I=E=>{if(!(g||a.isHost)&&x!=="suspended"){if(r?.(E),i){x="suspended";return}P(E);}},T=E=>{for(let M of qe){let F=E.channels[M];if(typeof F.addEventListener!="function")continue;let N=()=>{S()===E&&I(nu);};F.addEventListener("close",N),m.push(()=>F.removeEventListener?.("close",N));}},W=E=>{h(E),T(E),!g&&(x="connected",o?.());},q=E=>{for(let M of c.splice(0))M();c.push(E.on("migrating",()=>{R=true;})),c.push(E.on("hostChanged",M=>{if(R=false,M===E.playerId){P("host_migrated_here");return}let F=S();F!==null&&W(F);})),c.push(E.on("peerJoined",M=>{M.playerId===E.hostPlayerId&&W(M);})),c.push(E.on("matchEnded",M=>{g||ma(n,M),P(M);})),c.push(E.on("peerLeft",(M,F)=>{M===E.hostPlayerId&&I(eb(F));}));};q(a);let U=S();return U!==null&&W(U),{matchId:s,protocol:"p2p",get state(){return x},send(E,M){x==="connected"&&S()?.send(Tn(E),mt(M));},onMessage(E){l=E;},onClose(E){d=E;},close(){y=true,P("closed"),a.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||v)return "connected";if(R)throw new D("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");v=true;let E;try{for(let F of m.splice(0))F();for(let F of c.splice(0))F();a.close(),E=await e();}finally{v=false;}if(g)return y?E.leave().catch(()=>{}):E.close(),"closed";a=E,q(a);let M=S();if(M===null)throw a.close(),new D("connection_failed","this peer rejoined the match but the host never answered with a link");return W(M),"connected"},abandon(E){P(E);},onClosed(E){g?E():p.push(E);}}}function ru(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(o=>{let i={},s=l=>{n.delete(r)&&(t.clock.clearTimeout(i.timer),o(l));};n.set(r,s),i.timer=t.clock.setTimeout(()=>s(void 0),t.timeoutMs??2e3);let a=false;try{a=t.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,o){n.get(r)?.(o);}}}var ob=12e4;function gt(t,e){return {outcome:t,reason:e}}function ou(t){let e=false,n=new Map,r=(o,i,s,a)=>{if(!t.bridge.parentSupports(o))return Promise.resolve(gt("unavailable","error"));if(e)return Promise.resolve(gt("declined","busy"));let l=`purchase-${_e()}`;return new Promise(d=>{let m={},c=g=>{n.delete(l)&&(e=false,t.clock.clearTimeout(m.timer),d(g));};e=true,n.set(l,{finish:c,check:s,label:a}),m.timer=t.clock.setTimeout(()=>c(gt("unavailable","error")),t.timeoutMs??ob);let p=false;try{p=i(l);}catch{}p||c(gt("unavailable","error"));})};return {api:{request(o){return r("purchases",i=>t.bridge.requestPurchase(i,o.kind,o.targetId,o.currencySlug,o.quantity,o.catalogId),i=>i===void 0?null:t.confirm(i),i=>`purchase ${JSON.stringify(i)}`)}},requestAvatar3d(o){return r("avatar3dPurchases",i=>t.bridge.requestAvatar3dPurchase(i,o.itemId,o.currencySlug),()=>t.confirmAvatar3d(o.itemId),()=>`3D avatar ${JSON.stringify(o.itemId)}`)},settle(o){let i=o.outcome==="ok"||o.outcome==="declined"?o.outcome:"unavailable",s=n.get(o.requestId);if(s===void 0){t.onDropped?.(`gem.purchaseResult (${i}) for an unknown requestId: `+JSON.stringify(o.requestId));return}let{finish:a}=s;if(i!=="ok"){a(gt(i,hl(o.reason)));return}let l=o.purchaseId,d;try{d=s.check(l);}catch{d=Promise.resolve("unknown");}if(d===null){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),a(gt("unavailable","error"));return}(async()=>{let m;try{m=await d;}catch{m="unknown";}if(m==="granted"){a(l===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:l});return}m==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(gt("unavailable","error"));})();}}}async function iu(t,e){try{return (await Ls(t,e)).granted?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}var ib="small_human",au=/^[a-z][a-z0-9_]{0,31}$/,su=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,ab=8;function ga(t){if(t===null)return [];if(t.avatars3d!==void 0)return t.avatars3d;let{avatar3dId:e,avatar3dModelUrl:n,avatar3dIconUrl:r}=t;return e===void 0||n===void 0||r===void 0?[]:[{family:ib,id:e,modelUrl:n,iconUrl:r}]}function sb(t,e){return t.length===e.length&&t.every((n,r)=>{let o=e[r];return n.family===o.family&&n.id===o.id&&n.modelUrl===o.modelUrl})}function lb(t){let e=t??{},n=typeof e.item_id=="string"&&su.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&au.test(e.family)?e.family:void 0,o=typeof e.slug=="string"&&e.slug!==""?e.slug:void 0,i=typeof e.display_name=="string"&&e.display_name!==""?e.display_name:void 0,s=typeof e.description=="string"&&e.description!==""?e.description:void 0,a=Sr(e.icon_url),l=Sr(e.model_url),d=[];for(let m of Array.isArray(e.prices)?e.prices:[]){let c=m??{};typeof c.currency_slug=="string"&&c.currency_slug!==""&&typeof c.price=="number"&&Number.isSafeInteger(c.price)&&c.price>0&&d.push({currencySlug:c.currency_slug,price:c.price});}if(!(n===void 0||r===void 0||o===void 0||i===void 0||a===void 0||l===void 0||d.length===0))return {itemId:n,slug:o,family:r,displayName:i,...s===void 0?{}:{description:s},iconUrl:a,modelUrl:l,prices:d}}function db(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&au.test(n)&&!e.includes(n)&&e.push(n),e.length===ab)break;return e}function lu(t){let e=new Set,n=ga(t.player()),r=o=>{t.log?.(`[gem] an avatars3d onChange listener threw: ${o instanceof Error?o.message:String(o)}`);};return t.subscribe(o=>{let i=ga(o);if(!sb(n,i)){n=i;for(let s of [...e])try{s(i);}catch(a){r(a);}}}),{async families(){return db(await t.configFamilies())},worn(o){let i=ga(t.player());if(o!==void 0)return i.find(l=>l.family===o);let a=t.player()?.avatar3dId;return (a===void 0?void 0:i.find(l=>l.id===a))??i[0]},async offers(){let o=await t.readOffers(),i=[];for(let s of Array.isArray(o?.offers)?o.offers:[]){let a=lb(s);a!==void 0&&i.push(a);}return i},purchase(o){let i=o?.itemId,s=o?.currencySlug;return typeof i!="string"||!su.test(i)?Promise.resolve({outcome:"declined",reason:"not_purchasable"}):typeof s!="string"||s===""?Promise.resolve({outcome:"declined",reason:"unknown_currency"}):t.purchase({itemId:i,currencySlug:s})},onChange(o){return e.add(o),()=>{e.delete(o);}}}}async function du(t,e){try{return (await ys(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}function cu(t){return Es(t)}var cb=6e5;function uu(t){let e=null,n=new Map;return {api:{requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${_e()}`;return e=new Promise(o=>{let i={},s=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(i.timer),o(l));};n.set(r,s),i.timer=t.clock.setTimeout(()=>{s({outcome:"unavailable"});},t.timeoutMs??cb);let a=false;try{a=t.bridge.requestSignIn(r);}catch{}a||s({outcome:"unavailable"});}),e}},settle(r){let o=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.signInResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var ub=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),mb=["utm_"];function mu(t){return ub.has(t)||mb.some(e=>t.startsWith(e))}var pu=16,gu=512,pb=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,gb=/[\p{Cc}\p{Cf}]/u,yb=/\p{Cs}/u,Le="[gem] gem.share.request:";function yu(t){let{frame:e,log:n}=t,r=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,i=s=>{n!==null&&(n===void 0?console.warn(s):n(s));};return {get available(){return o()!==null},request(s){let a=o();if(a===null)throw new Error(`${Le} the arcade does not handle share here \u2014 check gem.share.available first`);if(s!==void 0&&(typeof s!="object"||s===null))throw new TypeError(`${Le} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!fb(l))throw new TypeError(`${Le} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>pu)throw new TypeError(`${Le} at most ${pu} params; got ${d.length}`);let m=[];for(let[c,p]of d){let g=JSON.stringify(c);if(!pb.test(c))throw new TypeError(`${Le} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(mu(c))throw new TypeError(`${Le} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Le} param ${g}: values must be strings`);if(p.length>gu)throw new TypeError(`${Le} param ${g}: a value is at most ${gu} characters`);if(gb.test(p))throw new TypeError(`${Le} param ${g}: control and format characters are not allowed`);if(yb.test(p))throw new TypeError(`${Le} param ${g}: a value must be well-formed text`);m.push({key:c,value:p});}!a.requestShare(m)&&!r&&(r=true,i("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function fb(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var En=3e4,ya=12e4;function In(t,e,n){return t.held?Promise.resolve(n):(t.held=true,e().then(r=>(t.held=false,r)))}function ce(t,e,n){return {outcome:t,reason:e,...n}}function Xe(t){let e=t.outcome==="ok"||t.outcome==="declined"?t.outcome:"unavailable";return typeof t.reason=="string"?{outcome:e,reason:t.reason}:{outcome:e}}function fu(t){let e=new Map;return {ask(n,r,o,i){let s=`arcade-${_e()}`;return new Promise(a=>{let l={},d=c=>{e.delete(s)&&("timer"in l&&t.clearTimeout(l.timer),a(o(c)));};e.set(s,{expect:n,finish:d}),i!==void 0&&(l.timer=t.setTimeout(()=>d(null),i));let m=false;try{m=r(s);}catch{}m||d(null);})},settle(n){let r=e.get(n.requestId);return r===void 0||r.expect!==n.type?false:(r.finish(n),true)},abandon(){for(let n of [...e.values()])n.finish(null);}}}var hb=12,bb=24,fa=Object.freeze({games:Object.freeze([])});function vb(t){let e=(n,r)=>he(n,`GameCard.${r}`);return Object.freeze({gameId:t.gameId,...t.slug===void 0?{}:{slug:t.slug},name:e(t.untrusted.name,"name"),tagline:e(t.untrusted.tagline,"tagline"),shortDescription:e(t.untrusted.shortDescription,"shortDescription"),tags:Object.freeze(t.untrusted.tags.map(n=>e(n,"tags"))),iconUrl:t.iconUrl,capsuleLandscapeUrl:t.capsuleLandscapeUrl,capsulePortraitUrl:t.capsulePortraitUrl,...t.previewVideoUrl===void 0?{}:{previewVideoUrl:t.previewVideoUrl},...t.previewPosterUrl===void 0?{}:{previewPosterUrl:t.previewPosterUrl}})}function so(t){return ce("unavailable","error",t)}function hu(t){let{bridge:e,asker:n,acting:r}=t,o=a=>e.currentState==="connected"&&e.parentSupports(a),i=new Map,s=(a,l)=>{let d=i.get(a);if(d!==void 0)return d;let m=l().then(c=>(i.delete(a),c));return i.set(a,m),m};return {get available(){return {appLinks:o("appLinks"),openGame:o("openGame")}},appLinks(){return e.parentSupports("appLinks")?s("appLinks",()=>n.ask("gem.appLinksResult",a=>e.requestArcade({type:"gem.requestAppLinks",requestId:a}),a=>{if(a===null)return so({});let l=a;return {...Xe(a),...l.arcade===void 0?{}:{arcade:{store:l.arcade.store}},...l.game===void 0?{}:{game:{store:l.game.store}}}},En)):Promise.resolve(ce("unavailable","unsupported",{}))},openApp(a){return e.parentSupports("appLinks")?a!=="arcade"&&a!=="game"?Promise.resolve(ce("unavailable","invalid_argument",{})):In(r,()=>n.ask("gem.openAppResult",l=>e.requestArcade({type:"gem.requestOpenApp",requestId:l,target:a}),l=>l===null?so({}):Xe(l),ya),ce("declined","busy",{})):Promise.resolve(ce("unavailable","unsupported",{}))},openGame(a){if(!e.parentSupports("openGame"))return Promise.resolve(ce("unavailable","unsupported",{}));let l=typeof a=="string"?a.toLowerCase():"";return pl({gem:j,type:"gem.requestOpenGame",requestId:"-",ref:l})!==null?Promise.resolve(ce("unavailable","invalid_argument",{})):In(r,()=>n.ask("gem.openGameResult",m=>e.requestArcade({type:"gem.requestOpenGame",requestId:m,ref:l}),m=>m===null?so({}):Xe(m),ya),ce("declined","busy",{}))},similarGames(a){if(!e.parentSupports("openGame"))return Promise.resolve(ce("unavailable","unsupported",fa));let l=a?.limit;return l!==void 0&&(typeof l!="number"||!Number.isInteger(l)||l<1||l>bb)?Promise.resolve(ce("unavailable","invalid_argument",fa)):s(`similar:${l??hb}`,()=>n.ask("gem.similarGamesResult",d=>e.requestArcade({type:"gem.requestSimilarGames",requestId:d,...l===void 0?{}:{limit:l}}),d=>{if(d===null)return so(fa);let m=Xe(d),c=d,p=m.outcome==="ok"?Object.freeze(c.games.map(vb)):[];return {...m,games:p}},En))}}}var _b=64,bu=Object.freeze({offers:Object.freeze([])});function wb(t){return Object.freeze({skuId:t.skuId,kind:t.kind,name:t.name,description:t.description,...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl},priceDisplay:t.priceDisplay,...t.grant===void 0?{}:{grant:Object.freeze({currency:t.grant.currency,amount:t.grant.amount})}})}function vu(t){let{bridge:e,asker:n,acting:r}=t,o=new Set,i=null;return {api:{get available(){return e.currentState==="connected"&&e.parentSupports("store")},offers(){return e.parentSupports("store")?(i!==null||(i=n.ask("gem.storeOffersResult",s=>e.requestArcade({type:"gem.requestStoreOffers",requestId:s}),s=>{if(s===null)return ce("unavailable","error",bu);let a=Xe(s),l=s,d=a.outcome==="ok"?Object.freeze(l.offers.map(wb)):[];return {...a,offers:d}},En).then(s=>(i=null,s))),i):Promise.resolve(ce("unavailable","unsupported",bu))},purchase(s){return e.parentSupports("store")?typeof s!="string"||s.length===0||s.length>_b?Promise.resolve(ce("unavailable","invalid_argument",{})):In(r,()=>n.ask("gem.storePurchaseResult",a=>e.requestArcade({type:"gem.requestStorePurchase",requestId:a,skuId:s}),a=>a===null?ce("unavailable","error",{}):Xe(a)),ce("declined","busy",{})):Promise.resolve(ce("unavailable","unsupported",{}))},onSettled(s){return o.add(s),()=>{o.delete(s);}}},settled(s){let a=Object.freeze({skuId:s.skuId});for(let l of [...o])try{l(a);}catch(d){t.onListenerError?.(d);}}}}var Ab="(any-pointer: coarse)";function xb(t){let e=Array.isArray(t)?t:[t],n=[],r=1e4;for(let o of e){if(typeof o!="number"||!Number.isFinite(o)||o<0)return null;if(n.length===99||r===0)continue;let i=Math.min(Math.trunc(o),1e4,r);n.push(i),r-=i;}return n.length%2===0&&n.pop(),n.every(o=>o===0)?[]:n}function _u(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},o=r.navigator,i,s=new Set,a=()=>typeof o?.vibrate!="function"||r.matchMedia===void 0?false:(i??=r.matchMedia(Ab),i.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,c)=>{s.has(m)||(s.add(m),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return a()||l()},vibrate(m){let c=a();if(!c&&!l())return false;let p=xb(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(c)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 qt=Math.PI/180,De=Object.freeze({touch:Object.freeze({yaw:1*qt,pitch:.66*qt}),mouse:Object.freeze({yaw:.5*qt,pitch:.5*.77*qt}),stick:Object.freeze({yaw:240*qt,pitch:240*.77*qt}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),ha="[gem.controls]",ba=Object.freeze({yaw:0,pitch:0}),lo=t=>Number.isFinite(t)?t:0,wu=(t,e)=>({yaw:t+0,pitch:e+0});function Su(t){let e=lo(t),n=(Math.abs(e)-De.stickDeadzone)/(1-De.stickDeadzone),r=De.stickCurve,o=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,o))+0}function Pb(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-De.touchPitchMin)+De.touchPitchMin}function Ru(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${ha} ${e} takes an options object`);let n=t;for(let r of ["sensitivity","gamepadSensitivity"]){let o=n[r];if(o!==void 0&&!(typeof o=="number"&&Number.isFinite(o)&&o>0))throw new TypeError(`${ha} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(o)}`)}if(n.invertY!==void 0&&typeof n.invertY!="boolean")throw new TypeError(`${ha} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function Tb(t,e){let n=Ru(e,"look()"),r=n.sensitivity,o=n.gamepadSensitivity,i=n.invertY,s=a=>i??a?.invertLookY??false;return {fromPointer(a,l,d,m){let c=lo(a),p=lo(l);if(c===0&&p===0)return ba;let g=t(),y=r??(g===null?void 0:g.lookSensitivity/100)??1,v=d==="touch"||d==="pen",R=v?De.touch:De.mouse,x=c*R.yaw*y,P=-p*R.pitch*y;return s(g)&&(P=-P),v&&m!==void 0&&Number.isFinite(m)&&P*m>0&&(P*=Pb(m)),wu(x,P)},fromStick(a,l,d){let m=lo(d);if(m<=0)return ba;let c=Su(a),p=Su(l);if(c===0&&p===0)return ba;let g=t(),y=o??(g===null?void 0:g.gamepadLookSensitivity/100)??1,v=c*De.stick.yaw*m*y,R=-p*De.stick.pitch*m*y;return s(g)&&(R=-R),wu(v,R)},set(a){let l=Ru(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(o=l.gamepadSensitivity),"invertY"in l&&(i=l.invertY);}}}function ku(t){return {look:e=>Tb(t.recommended,e),LOOK_BASE:De}}var Au=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),xu=/^[A-Za-z0-9_-]{1,40}$/;function va(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function Pu(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function Tu(t,e,n,r){let o=a=>Number.parseFloat(a.toPrecision(12)),i=Math.min(n,Math.max(e,t)),s=o(e+Math.round((i-e)/r)*r);return s>n&&(s=o(s-r)),Math.min(n,Math.max(e,s))}function Eu(t,e){switch(t.kind){case "toggle":return typeof e=="boolean"?e:void 0;case "slider":{if(typeof e!="number"||!Number.isFinite(e))return;let n=t.min??0,r=t.max??100;return Tu(e,n,r,t.step??1)}case "choice":return typeof e=="string"&&(t.options??[]).some(n=>n.id===e)?e:void 0;default:return}}function Iu(t,e=()=>{}){if(!Array.isArray(t))return null;let n=[],r=0;for(let o=0;o<t.length;o+=1){let i=t[o],s=`settings[${o}]`;if(n.length===8){e(`${s} and later were left out: at most 8 settings are shown.`);break}if(typeof i!="object"||i===null){e(`${s} was dropped: a setting is an object.`);continue}let a=i,l=a.id;if(typeof l!="string"||!xu.test(l)){e(`${s} was dropped: its id must be 1 to 40 of A-Z a-z 0-9 _ -.`);continue}let d=`${s} (${JSON.stringify(l)})`;if(n.some(p=>p.id===l)){e(`${d} was dropped: an earlier setting has the same id.`);continue}let m=Pu(a.label);if(m===void 0){e(`${d} was dropped: its label is empty.`);continue}let c;switch(a.kind){case "toggle":{if(typeof a.value!="boolean"){e(`${d} was dropped: a toggle's value is true or false.`);continue}c={id:l,label:m,kind:"toggle",value:a.value},a.quick===true&&(r<2?(c.quick=true,r+=1):e(`${d} is not in the quick row: at most 2 toggles are, the first that ask.`));break}case "slider":{let p=a.min??0,g=a.max??100,y=a.step??1;if(!va(p)||!va(g)||!va(y)||p>=g||y<=0){e(`${d} was dropped: a slider needs finite numbers within \xB11000000 with min below max and a step above 0.`);continue}if(typeof a.value!="number"||!Number.isFinite(a.value)){e(`${d} was dropped: a slider's value is a number.`);continue}c={id:l,label:m,kind:"slider",value:Tu(a.value,p,g,y),min:p,max:g,step:y};break}case "choice":{let p=[];for(let g of Array.isArray(a.options)?a.options:[]){if(p.length===4)break;if(typeof g!="object"||g===null)continue;let y=g,v=Pu(y.label);typeof y.id!="string"||!xu.test(y.id)||v===void 0||p.some(R=>R.id===y.id)||p.push({id:y.id,label:v});}if(p.length<2){e(`${d} was dropped: a choice needs 2 to 4 options, each with an id of 1 to 40 of A-Z a-z 0-9 _ - and a label.`);continue}if(typeof a.value!="string"||!p.some(g=>g.id===a.value)){e(`${d} was dropped: a choice's value is the id of one of its options.`);continue}c={id:l,label:m,kind:"choice",value:a.value,options:p};break}default:e(`${d} was dropped: its kind must be 'toggle', 'slider' or 'choice'.`);continue}a.icon!==void 0&&(Au.includes(a.icon)?c.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${Au.join(", ")}.`)),n.push(c);}return n}var Eb=500;function Cu(t){let{clock:e}=t,n=null,r=null,o=-1/0,i=null,s=new Set,a=new Set,l=c=>{a.has(c)||(a.add(c),t.log!==null&&(t.log===void 0?console.warn(c):t.log(c)));},d=()=>{let c=t.frame();return c.currentState==="connected"&&c.parentSupports("gameSettings")},m=()=>{if(n===null||i!==null)return;let c=JSON.stringify(n);if(c===r)return;let p=o+Eb-e.now();if(p>0){i=e.setTimeout(()=>{i=null,m();},p);return}t.frame().declareSettings(n)&&(r=c,o=e.now());};return {api:{declare(c){let p=Iu(c,g=>l(`[gem] gem.settings.declare: ${g}`));return p===null?(l("[gem] gem.settings.declare did nothing: pass an array of settings, or [] for none."),false):(n=p,m(),d())},onChange(c){if(typeof c!="function")return ()=>{};let p=g=>c(g);return s.add(p),()=>{s.delete(p);}}},forgetSent(){r=null,o=-1/0;},flush:m,onSettingChange(c){let p=n?.findIndex(x=>x.id===c.id)??-1,g=n?.[p];if(n===null||g===void 0)return;let y=Eu(g,c.value);if(y===void 0)return;let v=JSON.stringify(n);n=n.map((x,P)=>P===p?{...x,value:y}:x),r===v&&(r=JSON.stringify(n));let R={id:g.id,value:y};for(let x of [...s])try{x(R);}catch(P){console.error("[gem] a gem.settings.onChange handler threw:",P);}}}}function Mu(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var Ib=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Ou(t){if(typeof t!="string"||!Ib.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function Cn(){return {declared:false,grantable:false,heldLimitReached:false}}function Gu(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Ou(n.resets_at),o=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...Cn(),...o};let i=n.remaining_today,s=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):void 0,a=n.next_eligible_at,l=Ou(a),d=n.held_limit_reached===true,m=a!=null,c=i!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!c&&!m&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...o}}var Cb=18e4,_a=32,Mb=/^[a-z0-9_-]+$/,Ob="rewarded_requires_user_gesture";function Gb(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var Lb=1e3;function Db(){let t=globalThis,e=t.navigator?.getGamepads,n=t.performance?.now;if(typeof e!="function"||typeof n!="function")return;let r=n.call(t.performance),o=e.call(t.navigator);for(let i=0;i<o.length;i+=1){let s=o[i]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=Lb)return true}return false}var Lu=1e4;function Fb(t){return t==="interstitial"||t==="rewarded"}function Du(t){return typeof t=="string"&&t!==""&&t.length<=_a&&Mb.test(t)}function $b(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function co(t){return typeof t=="string"?JSON.stringify(t):typeof t}function Fu(t){let e=false,n=new Map,r=new Map,o=new Set,i=d=>{try{t.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let m=t.log;if(m!==null)try{m===void 0?console.warn(`[gem] ${d}`):m(`[gem] ${d}`);}catch{}},l=d=>{let m=t.readAvailability;if(m===void 0)return Promise.resolve(Cn());let c=r.get(d);if(c!==void 0)return c;let p=new Promise(g=>{let y={},v=h=>y.done===true?false:(y.done=true,t.clock.clearTimeout(y.timer),g(h),true),R=(h,S)=>{!v(Cn())||o.has(h)||(o.add(h),i(`gem.ads.rewardedStatus("${d}") answered not grantable: ${S}. Said once.`));},x=h=>{R($b(h),`the read failed (${h instanceof Error?h.message:co(h)})`);},P;try{P=Promise.resolve(m(d,AbortSignal.timeout(Lu)));}catch(h){P=Promise.reject(h);}y.timer=t.clock.setTimeout(()=>{R("timeout","no answer within 10 s");},Lu),P.then(h=>{try{v(Gu(h,t.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 Du(d)?l(d):(i(`gem.ads.rewardedStatus(${co(d)}) answered not grantable: a placement is 1..${String(_a)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(Cn()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let m=d?.placement,c=d?.format;if(!Du(m)||!Fb(c))return i(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${co(m)}, format ${co(c)}. A placement is 1..${String(_a)} 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(c==="rewarded"){let g;try{g=(t.userActivation??Gb)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??Db)()===!0&&(g=!0);}catch{}if(g===false){let y=`${Ob}: gem.ads.requestAd("${m}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return i(y),a(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${_e()}`;return new Promise(g=>{let y={},v=x=>{n.delete(p)&&(e=false,t.clock.clearTimeout(y.timer),g(x));};e=true,n.set(p,v),y.timer=t.clock.setTimeout(()=>{v({outcome:"unavailable"});},t.timeoutMs??Cb);let R=false;try{R=t.bridge.requestAd(p,m,c);}catch{}R||v({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:m});}}}var $u=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),qu=18e4,qb=1e4,Nb=/^[a-z0-9_-]{1,32}$/;function Nu(t){return typeof t=="string"?JSON.stringify(t):typeof t}var Mn=Object.freeze({shown:false});function ju(t){let e=new Map,n,r=false,o=i=>{try{t.onDropped?.(i);}catch{}return Mn};return {api:{signal(i){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(Mn):(r=!0,Promise.resolve(o("moments_unsupported: gem.moments.signal answered shown: false without asking: this arcade does not do platform moments. Keep the call; it costs nothing. Said once.")));let s=i?.kind,a=i?.placement;if(!$u.includes(s)||a!==void 0&&(typeof a!="string"||!Nb.test(a)))return Promise.resolve(o(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${Nu(s)}, placement ${Nu(a)}. A kind is one of ${$u.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'. Answering shown: false.`));if(!t.bridge.readyCalled())return Promise.resolve(o(`moments_before_ready: gem.moments.signal({ kind: '${s}' }) before gem.frame.ready(): a moment is a break in play, and play has not started. Signal from the press that leaves a break, never on boot. Answering shown: false.`));if(e.size>0)return Promise.resolve(o(`moments_in_flight: gem.moments.signal({ kind: '${s}' }) while another moment is still waiting for its answer. Signal once per break, and await the answer before play resumes. Answering shown: false.`));let l=t.clock.now();if(n!==void 0&&l-n<qb)return Promise.resolve(o(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(l-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let d=`moment-${_e()}`;return new Promise(m=>{let c={},p=(y,v)=>{e.delete(d)&&(t.clock.clearTimeout(c.timer),v&&(n=t.clock.now()),m(y));};e.set(d,y=>p(y,!0)),c.timer=t.clock.setTimeout(()=>{e.has(d)&&(p(Mn,!0),o(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??qu)/1e3)} s. Answering shown: false.`));},t.timeoutMs??qu);let g=!1;try{g=t.bridge.signalMoment(d,s,a);}catch{}g||p(Mn,!1);})}catch{return Promise.resolve(Mn)}}},settle(i){let s=e.get(i.requestId);if(s===void 0){o(`gem.momentResult (shown: ${String(i.shown)}) for an unknown requestId: `+JSON.stringify(i.requestId));return}s({shown:i.shown===true});}}}var wa=16384;function Uu(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e;try{e=JSON.stringify(t);}catch{return null}return typeof e!="string"?null:jb(e)}function jb(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let o=t.charCodeAt(n+1);o>=56320&&o<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var Ub=1e4,Bb=5e3;function Bu(t){let e=null,n=false,r=[],o=new Map,i=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=Bb){return n?Promise.resolve(e):new Promise(a=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{t.clock.clearTimeout(m),l(),a(e);},m=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=Uu(s);if(a===null)return t.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(a>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(s)),d=`device-settings-${_e()}`;return new Promise(m=>{let c={},p=y=>{o.delete(d)&&(t.clock.clearTimeout(c.timer),y==="stored"&&(e=l,n=true,i()),m(y));};o.set(d,p),c.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??Ub);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,n=true,i();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=o.get(s.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var On=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 Wb=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Hb(t){return typeof t=="string"&&Wb.test(t)}function uo(t){if(t===null||Hb(t))return t;let e=typeof t=="string"?JSON.stringify(t.length>48?`${t.slice(0,48)}\u2026`:t):`a value of type ${typeof t}`;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 Wu(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Ra(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let o of Array.isArray(e)?e:[])o==="score"?r=true:typeof o=="string"&&o.length>0&&o.length<=64&&!n.includes(o)&&n.push(o);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function mo(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(e.length===4)break;if(typeof n!="object"||n===null)continue;let{id:r,label:o}=n;typeof r!="string"||r.length===0||r.length>32||typeof o!="string"||o.trim().length===0||e.some(i=>i.id===r)||e.push({id:r,label:o.trim().slice(0,40)});}return e.length===0?{settings:false}:{settings:false,items:e}}function Hu(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Vb(t){let e=t.untrusted,n=he(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,o=r?he(r,"gem.player.displayTag"):void 0,i=t.discriminator||t.displayTag,s=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,a=t.avatarIconUrl||t.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=t.avatarIconId,m=t.avatar3dId,c={displayName:n,displayHandle:o??n,badges:(t.badges??[]).map(v=>({itemId:v.itemId,iconUrl:v.iconUrl}))};t.playerId&&(c.playerId=t.playerId),s&&(c.discriminator=s),o&&(c.displayTag=o),a&&(c.avatarIconUrl=c.avatarUrl=a),d&&l.test(d)&&(c.avatarIconId=d),m&&l.test(m)&&(c.avatar3dId=m),t.avatar3dModelUrl&&(c.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(c.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(c.avatars3d=t.avatars3d.filter(v=>l.test(v.id)&&/^[a-z][a-z0-9_]*$/.test(v.family)).filter((v,R,x)=>x.findIndex(P=>P.family==v.family)==R).map(({family:v,id:R,modelUrl:x,iconUrl:P})=>({family:v,id:R,modelUrl:x,iconUrl:P})));let p=t.boost,g=(p?.multipliers??[]).map(v=>({currencyId:v.currencyId,currencySlug:v.currencySlug,multiplier:v.multiplierBp/1e4})),y=g.some(v=>v.multiplier>1);return c.boost=y&&p?.expiresInDays?{active:y,multipliers:g,expiresInDays:p.expiresInDays}:{active:y,multipliers:g},c}var Kb=1e4,Jb=["appLinks","openGame","store"],Sa=new WeakMap;function Ku(t,e){if(Sa.has(t))throw new Error("admitBuildEmbedders: already admitted");Sa.set(t,Object.freeze([...e]));}var Gn=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??ue,this.inbound=new Vt(this.clock),this.outbound=new Vt(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(a=>St(a,e.origin))||rr(e.origin,this.options.selfOrigin)||(Sa.get(this)??[]).some(a=>St(a,e.origin))))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=nr["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!St(o.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${o.embedder}' but arrived from '${e.origin}'`),false;let i=e.ports?.[0];if(!i)return this.refuse(e,"handshake transferred no MessagePort"),false;let s=gl(Zn,o.versions);return s===null?(i.onmessage=null,i.postMessage({gem:j,type:"gem.error",code:"version_mismatch",message:`frame supports v${Zn.min}..v${Zn.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=s,i.onmessage=a=>this.receive(a.data,a.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:j,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:j,type:"gem.ready"});}settled(e=Kb){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=i=>{this.clock.clearTimeout(o),n(i);},o=this.clock.setTimeout(()=>{let i=this.settleWaiters.indexOf(r);i>=0&&this.settleWaiters.splice(i,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:j,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:j,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:j,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:j,type:"gem.exit"}:{gem:j,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:j,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:j,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:j,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:j,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:j,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:Wu(e.origin.x),y:Wu(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=uo(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:j,type:"gem.portraitBorders"}:{gem:j,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:j,type:"gem.walletDisplay",...Ra(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:j,type:"gem.menu",...mo(e)}):false}declareSettings(e){return this.gated("gameSettings")?this.send({gem:j,type:"gem.settingsDeclare",settings:e}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:j,type:"gem.gemCorner",corner:e}):false}requestShare(e){return this.gated("share")?this.send({gem:j,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:j,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:j,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:j,type:"gem.frameStats",fps:Hu(e.fps,1e3),frameTimeP95Ms:Hu(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:j,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:j,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:j,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:j,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,o,i,s){return this.send({gem:j,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...s===void 0?{}:{catalogId:s}})}requestAvatar3dPurchase(e,n,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:j,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:j,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:j,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r){return this.send({gem:j,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:j,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,o){return this.send({gem:j,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...o===void 0?{}:{params:o}})}requestArcade(e){return this.gated(tr(e.type))&&this.send({gem:j,...e})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(er)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(er)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(er)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:j,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}gated(e){return this.state==="connected"&&this.parentSupports(e)}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let n=e.type;if(!this.outbound.allow(n))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${n}`),false;let r=nr[n]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${n}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,n=[]){let r=false;try{r=this.dispatchInbound(e,n);}finally{r||Vu(n);}}dispatchInbound(e,n){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=nr[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=tr(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let s=o(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.settingChange":this.options.onSettingChange?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=n[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return Vu(n.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(Vb(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.ticketEvent":this.options.onTicketEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.momentResult":this.options.onMomentResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:if(Jb.includes(tr(r))){this.options.onArcadeAnswer?.(a);break}this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:j,type:"gem.screenshot.denied",reason:e,retryable:n});}};function Vu(t){for(let e of t)try{e?.close?.();}catch{}}var Ju="https://api.gemarcade.com";function ka(t){let e;try{e=new URL(t);}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 zb=new Set(["localhost","127.0.0.1","[::1]"]);function zu(t){let e=ka(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!zb.has(n.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 Qu="/gem-embedders.json",po=4096,Yu=16,Xu=5e3,Ln=Object.freeze({origins:Object.freeze([])});function Qe(t){return {origins:[],refused:`[gem] ${Qu} was ignored: ${t}`}}function Yb(t){if(t.trim()==="")return Ln;let e;try{e=JSON.parse(t);}catch{return Qe("it is not JSON.")}if(e===null||typeof e!="object"||Array.isArray(e))return Qe('it must be an object, { "embedders": [...] }.');let n=e.embedders;if(n===void 0)return Ln;if(!Array.isArray(n))return Qe('"embedders" must be an array of origins.');if(n.length>Yu)return Qe(`"embedders" has more than ${Yu} entries.`);let r=n.filter(o=>typeof o!="string"||!wt(o)||!o.toLowerCase().startsWith("https://")||He(new URL(o).hostname));if(r.length>0){let o=r.slice(0,3).map(i=>typeof i=="string"?JSON.stringify(i.slice(0,100)):String(i)).join(", ");return Qe(`${r.length===1?"an entry is":"entries are"} not an https origin off this machine (${o}${r.length>3?", \u2026":""}).`)}return {origins:Object.freeze([...new Set(n)])}}async function Zu(t){let e=typeof AbortController=="function"?new AbortController:null,n,r=new Promise(i=>{n=t.clock.setTimeout(()=>{e?.abort(),i(Qe(`it took more than ${Xu} ms to read.`));},Xu);}),o=(async()=>{let i=await t.fetch(t.selfOrigin+Qu,{credentials:"omit",redirect:"error",...e?{signal:e.signal}:{}});if(!i.ok||(i.headers.get("content-type")??"").toLowerCase().includes("text/html"))return Ln;if(Number(i.headers.get("content-length"))>po)return Qe(`it is larger than ${po} bytes.`);let a=await i.text();return a.length>po?Qe(`it is larger than ${po} bytes.`):Yb(a)})().catch(()=>Ln);try{return await Promise.race([o,r])}finally{t.clock.clearTimeout(n);}}function em(t){if(typeof t!="string"||!wt(t))return null;let e=t.slice(0,t.indexOf(":")).toLowerCase();return e==="https"||e==="http"?t:null}function tm(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function Xb(){let t=[["root",null],["hips","root"],["spine","hips"],["chest","spine"],["upper_chest","chest"],["neck","upper_chest"],["head","neck"],["head_socket","head"]];for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("shoulder"),"upper_chest"],[n("upper_arm"),n("shoulder")],[n("lower_arm"),n("upper_arm")],[n("hand"),n("lower_arm")],[n("hand_socket"),n("hand")]);for(let r of ["thumb","index","middle","ring","little"])for(let o=1;o<=3;o++)t.push([n(`${r}_${o}`),n(o===1?"hand":`${r}_${o-1}`)]);}for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("upper_leg"),"hips"],[n("lower_leg"),n("upper_leg")],[n("foot"),n("lower_leg")],[n("toes"),n("foot")]);}return t}var Qb=Object.freeze({small_human:tm([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:tm(Xb())});var ev=Object.freeze(["https://gemarcade.com","https://developer.gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),tv=Ju,nv=["top-left","top-right","bottom-left","bottom-right"],nm=8e3,go=15e3,rv=9e4,ov=1/0,iv=8e3,av=5e3,sv=5e3;async function lv(t,e,n,r){if(t.isInRoom)try{await t.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(n);}function Dn(t){let e=null,n=false,r=[];return {get current(){return e},set(o){e=o;for(let i of r.splice(0))i(o);},release(){n=true;for(let o of r.splice(0))o(e);},wait(o){return e!==null||n?Promise.resolve(e):new Promise(i=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{t.clearTimeout(l),s(),i(d);},l=t.setTimeout(()=>{s(),i(e);},o);r.push(a);})}}}function mT(t={}){let e=t.clock??ue,n=t.log===void 0?u=>console.info(u):t.log,r=t.baseUrl??void 0;if(r!=null){let u=ka(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=typeof window>"u"?void 0:window.location?.search,i=Bl(o),s=hd(o),a=Wi();a.mark("sdk created");let l=()=>Or(ie.gameVersion,t.clientVersion?.gameVersion),d=new an({client:()=>bt,clock:e,gameId:()=>ie.identity?.gameId??null,playerId:()=>ie.identity?.playerId??null,awaitPlayerId:async()=>(await Kn(go)).playerId,environment:()=>{let u=l();return {sdk_version:za(),...u===null?{}:{game_version:u}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),m=nc(()=>{a.mark("engaged"),d.release(),$.reportEngaged();},typeof window>"u"?{}:window),c=u=>{if(u===false)return null;let A=u?.attempts??ov,G=u?.budgetMs??rv;return !(A>0)||!(G>0)?null:{attempts:A,budgetMs:G,maxDelayMs:u?.maxDelayMs??iv}},p=u=>{u.on("created",()=>{a.mark("room created");}),u.on("joined",()=>{a.mark("room joined");}),u.on("matchAllocationStarted",()=>{a.mark("allocation started");}),u.on("matchReady",()=>{a.mark("match ready");}),u.on("matchFailed",()=>{a.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 On;let g=t.allowedEmbedders;if(g!=null&&!Array.isArray(g))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 y=Array.from(g??[]),v=y.filter(u=>typeof u!="string"||!wt(u));if(v.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${v.length===1?"an entry":"entries"} that ${v.length===1?"is":"are"} not an origin: ${v.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let R=Object.freeze([...new Set([...ev,...y])]),x=Dn(e),P=new Set,h=Dn(e),S=false,I=Dn(e),T=zl(n),W=Dn(e),q=t.manageAudio===false?null:gc();t.selectableText!==true&&yc(),t.onScreenshot===void 0&&oc(window);let U=null,E=null,M=null,F=()=>{U===null||U===E||$.reportMuted(U)&&(E=U);},N,B,J=-1/0,oe=null,ge=()=>{if(N===void 0||oe!==null||N===B)return;let u=J+1e3-e.now();if(u>0){oe=e.setTimeout(()=>{oe=null,ge();},u);return}$.showPortraitBorders(N)&&(B=N,J=e.now());},Y=null,Ne=null,Re=()=>{if(Y===null)return false;let u=JSON.stringify(Ra(Y.visible,Y.only));return u===Ne?$.parentSupports("walletDisplay"):$.setWalletVisible(Y.visible,Y)?(Ne=u,true):false},ye=null,je=null,te=()=>{if(ye===null)return false;let u=JSON.stringify(mo(ye.items));return u===je?$.parentSupports("gameMenu"):$.setMenu(ye.items)?(je=u,true):false},z=null,se=null,xe=Cu({frame:()=>$,clock:e,log:t.log}),Ue=()=>z===null?false:z===se?$.parentSupports("gemCorner"):$.setGemCorner(z)?(se=z,true):false,Fe=fc({report:u=>$.reportFrameStats(u)}),yt=false,Ee=Rc(()=>Ua,()=>yt),Nt=u=>{let A=yt&&!u,G=yt!==u;if(yt=u,A&&Ee.close(),!!G)try{t.onDevToolsPermissionChange?.(u);}catch(ee){n?.(`[gem] onDevToolsPermissionChange threw: ${ee instanceof Error?ee.message:String(ee)}`),queueMicrotask(()=>{throw ee});}},Be=r??tv,yo=r!==void 0,ft,f=u=>(n?.(`[gem] token refused: ${u}`),t.onError?.("internal",u),false),C=(u,A)=>{if(u===void 0)return A!==void 0?f("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 G=zu(u);return G!==null?f(`the embedder named an API root that cannot be used: ${G}. Its value is withheld here rather than written to logs.`):ft!==void 0&&ft!==u?f("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."):(ft=u,yo||(Be=u),true)},L=window.location?.origin,Z=null,we=-1/0,Fn=2e3,ht=new Set,jt=u=>Z!==false?Promise.resolve(true):new Promise(A=>{let G=e.setTimeout(()=>{ht.delete(ee),A(false);},u),ee=()=>{e.clearTimeout(G),ht.delete(ee),A(true);};ht.add(ee);}),fo=()=>{},ho=null,$n=fu(e),$=new Gn({allowedEmbedders:R,...typeof L=="string"&&L!==""?{selfOrigin:L}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","ticketEvents","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","gemCorner","gameSettings","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges","appLinks","openGame","store",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[]],onRefused:u=>{ho=u,t.onRefused?.(u);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:u=>{ie.onBridgeState(u),u!=="connected"&&$n.abandon(),u!=="connected"&&Fe.setRequested(false),E=null,Ne=null,je=null,se=null,xe.forgetSent(),B=void 0,u==="refused"&&(console.error("[gem] this game refused the page that framed it"+(ho===null?"":` (${ho})`)+", 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."),fo()),u==="connected"&&(a.mark("bridge connected"),am(),F(),ge(),Re(),te(),Ue(),xe.flush(),$.unbiddenLaunch&&!m.engaged&&d.hold(),d.startSession(),m.engaged&&$.reportEngaged()),t.onStateChange?.(u);},onPlayer:u=>{x.set(u);for(let A of [...P])A(u);t.onPlayer?.(u);},onPrefs:u=>{let A={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true,music:u.music!==false,sounds:u.sounds!==false,recommended:u.recommended===void 0?null:Object.freeze({volume:u.recommended.volume,batterySaver:u.recommended.batterySaver,keyboardLayout:u.recommended.keyboardLayout,gamepadConfirm:u.recommended.gamepadConfirm,vibration:u.recommended.vibration,lookSensitivity:u.recommended.lookSensitivity??100,gamepadLookSensitivity:u.recommended.gamepadLookSensitivity??100,invertLookY:u.recommended.invertLookY??false,touchMovement:u.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:Mu(u.recommended.graphicsQuality,u.recommended.batterySaver),graphicsQualityAuto:u.recommended.graphicsQualityAuto??true,colorHelp:typeof u.recommended.colorHelp=="boolean"?u.recommended.colorHelp:null})};h.set(A),E=A.muted,q?.setMuted(A.muted),Fe.setRequested(A.showFrameStats&&$.parentSupports("frameStats")),t.onPrefs?.(A),t.onAudioChannels!==void 0&&(M===null||M.music!==A.music||M.sounds!==A.sounds)&&(M=Object.freeze({music:A.music,sounds:A.sounds}),t.onAudioChannels(M));},onCohorts:u=>{let A=Object.freeze(u.cohorts.map(G=>Object.freeze({experimentId:G.experimentId,variantKey:G.variantKey})));I.set(A),t.onCohorts?.(A);},onEarnAllowanceChanged:()=>T.emit(),onViewport:u=>{let A=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left}),reserved:Object.freeze((u.reserved??[]).map(({x:ee,y:Ba,width:Wa,height:Ha,control:Bt})=>Object.freeze(Bt?{x:ee,y:Ba,width:Wa,height:Ha,control:Object.freeze({x:Bt.x,y:Bt.y,width:Bt.width,height:Bt.height})}:{x:ee,y:Ba,width:Wa,height:Ha})))});W.set(A);let G=bc();vc(G,A.insets),wc(G,A.reserved,_c()),t.onViewport?.(A);},onPause:u=>{S=u.paused,d.setPaused(u.paused),Fe.setPaused(u.paused),t.onPause?.(u.paused);},onSettingChange:u=>xe.onSettingChange(u),onMenuSelect:u=>{ye===null||u.entry!=="item"||!(mo(ye.items).items??[]).some(G=>G.id===u.id)||ye.items?.find(G=>G.id===u.id)?.onSelect?.();},onWillTerminate:u=>{d.endSession(u.reason),t.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let A=u.garden;if(Nt(u.allowDevTools===true),!C(u.apiBaseUrl,A))return;let G=u;ie.onToken(G);let ee=ie.identity;ee&&(bo.set(ee),Pa||(Pa=true,me.reconcileSeats().catch(()=>{}))),Ta.push({token:G.token,expiresAt:G.expiresAt});},onTokenDenied:u=>{Nt(false),ie.onDenied(u);},onScreenshot:(u,A,G)=>{uc(u,A,G,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{mc($,t.onFeedbackContext);},onDevtools:u=>{u==="close"?Ee.close():u==="open"?Ee.openFrom("platform").catch(()=>{}):Ee.isOpen?Ee.close():Ee.openFrom("platform").catch(()=>{});},onRoomEvent:u=>me.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>me.handleSeated(u.roomId),onAutoStartFailedEvent:u=>me.handleAutoStartFailed(u.roomId,u.code),onTicketEvent:u=>me.handleTicketEvent({event:u.event,ticketId:u.ticketId,...u.partySize===void 0?{}:{partySize:u.partySize},...u.queuedAt===void 0?{}:{queuedAt:u.queuedAt},...u.expiresAt===void 0?{}:{expiresAt:u.expiresAt},...u.reason===void 0?{}:{reason:u.reason},...u.roomId===void 0?{}:{roomId:u.roomId}}),onSocketState:u=>{let A=Z;if(Z=u.connected,u.connected)for(let ee of [...ht])ee();if(!u.connected||A===true)return;let G=e.now();G-we<Fn||(we=G,me.reconcile().catch(()=>{}));},onSignalEvent:u=>{let A=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};vt.handleSignalEvent(u.matchId,u.event,A),u.event==="matchEnded"&&me.reconcile({matchId:u.matchId,...typeof A.reason=="string"?{reason:A.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(Ut.handleMatchEnded(u.matchId,u.reason),me.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),xa.handleEvent(u);},onClusterTarget:u=>Un.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>Bn.accept(u),onLocalServerDenied:u=>Bn.refuse(u),onPartyResult:u=>Ia.settle(u.requestId,u.partyId),onPurchaseResult:u=>_o.settle(u),onDeviceSettings:u=>{jn.receive(u),t.onDeviceSettings?.(jn.api.current);},onDeviceSettingsResult:u=>jn.settle(u),onAdResult:u=>Ma.settle(u),onMomentResult:u=>Oa.settle(u),onSignInResult:u=>Ga.settle(u),onFriendChallengeResult:u=>Fa.settle(u),onArcadeAnswer:u=>{u.type==="gem.storePurchaseSettled"?Da.settled(u):lm(u);}}),xa=new Pn({bridge:$}),bo=Dn(e);fo=()=>{bo.release(),x.release(),I.release();},$.currentState==="refused"&&fo();let Pa=false,vo=new Set,qn,Ta={current:()=>qn,subscribe:u=>(vo.add(u),qn!==void 0&&u(qn),()=>vo.delete(u)),push:u=>{qn=u;for(let A of [...vo])try{A(u);}catch(G){n?.(`[gem] a server-token listener threw: ${G instanceof Error?G.message:String(G)}`);}}},ie=Ac({bridge:$,clock:e,onStateChange:(u,A)=>{if(u==="ready"){if(a.mark("token ready")){let G=a.marks.find(ee=>ee.name==="token ready")?.at;d.trackPlatform("gem_boot_ready",G===void 0?{}:{boot_ms:Math.max(0,Math.round(G))});}}else u==="lost"&&(a.mark("token lost"),d.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(u,A);}}),Ea=()=>{let u=ie.identity;return !u||ie.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},am=()=>{a.mark("token requested"),ie.source.get().catch(()=>{});},Ia=ru({bridge:$,clock:e}),Nn={},_o=ou({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u),confirm:async u=>Nn.confirm?.(u)??"unknown",confirmAvatar3d:async u=>Nn.confirmAvatar3d?.(u)??"unknown"}),jn=Bu({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u)}),Ca={},Ma=Fu({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u),readAvailability:(u,A)=>Ca.read?.(u,A)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),Oa=ju({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u)}),Ga=uu({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u)}),La={held:false},sm=hu({bridge:$,asker:$n,acting:La}),Da=vu({bridge:$,asker:$n,acting:La,onListenerError:u=>t.onError?.("internal",`gem.store.onSettled listener threw: ${String(u)}`)}),lm=u=>{$n.settle(u)||t.onError?.("internal",`${u.type} (${u.outcome}) for an unknown requestId: `+JSON.stringify(u.requestId));},Fa=Jl({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u)}),Un=od({bridge:$,clock:e}),Bn=Sc({bridge:$,clock:e}),wo=em(L),$a=window.fetch,Wn=wo!==null&&typeof $a=="function"?"unread":"read",Hn=null,So=false,dm=u=>{if(Wn==="read"||u.source!==window.parent)return false;let A=u.origin;return typeof A!="string"||R.some(G=>St(G,A))||rr(A,typeof L=="string"?L:void 0)?false:((Hn===null||!So)&&(Hn=u),Wn==="unread"&&wo!==null&&(Wn="reading",Zu({fetch:(G,ee)=>$a.call(window,G,ee),selfOrigin:wo,clock:e}).then(G=>{"refused"in G&&n?.(G.refused),G.origins.length>0&&Ku($,G.origins),Wn="read";let ee=Hn;Hn=null,ee!==null&&$.currentState==="waiting"&&Vn(ee);})),true)},Vn=u=>{if(dm(u))return false;let A=$.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return A&&window.removeEventListener("message",Vn),A};window.addEventListener("message",Vn),So=true;let Ze;try{Ze=Ja(window,Vn);}finally{So=false;}let cm=Ze?.capture,Ro=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Ro?.domInteractive!==void 0&&Ro.domInteractive>0&&a.mark("document parsed",Ro.domInteractive),cm?.late&&n?.("[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 ko=t.handshakeWarningMs;ko!==null&&n&&e.setTimeout(()=>{let u=Ze===null?"no capture script ran":`capture: ${Ze.delivered} offer(s) delivered, ${Ze.stale} stale, ${Ze.capture.dropped} evicted${Ze.capture.late?", installed late":""}`;if($.currentState==="connected"){n(`[gem] handshake connected. boot: ${a.timeline()} \xB7 ${u}`);return}n(`[gem] no completed handshake after ${ko??nm}ms (bridge state: ${$.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${a.timeline()} \xB7 `+u);},ko??nm);let um=ro({get baseUrl(){return Be},tokenSource:ie.source,get defaultQuery(){let u=ie.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),bt=new We({transport:um,clock:e}),fe={client:bt,gameId:()=>ie.identity?.gameId??""};Nn.confirm=u=>iu(fe,u),Nn.confirmAvatar3d=u=>du(fe,u),Ca.read=(u,A)=>rl(fe,"players","me",u,{signal:A});let mm=()=>ie.identity?.channel??"release",Ao=new _r(fe,mm),pm=lu({player:()=>x.current,subscribe:u=>(P.add(u),()=>{P.delete(u);}),configFamilies:async()=>(await Ao.load())?.avatar_3d_families,readOffers:()=>cu(fe),purchase:u=>_o.requestAvatar3d(u),log:t.log}),qa=async u=>(await Ao.load())?.currency(u)?.id??void 0,Na=gr(fe,Bo,{identity:Ea,resolveCurrencyId:qa}),Kn=async u=>{let A=await bo.wait(u);if(A)return A;throw $.currentState==="refused"?new ne("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 ne("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).")},xo=c(t.autoReconnect),me=Dd(s===void 0?{}:{playWithTicket:s},{client:bt,clock:e,gameId:()=>ie.identity?.gameId??null,playerId:()=>ie.identity?.playerId??null,awaitGameId:async()=>(await Kn(go)).gameId,resolveParty:Ia.resolve,resolveClusterTargets:Un.resolveList,refreshClusterTargets:Un.refresh,ensureLocalServer:Bn.ensure,localHostAvailable:Bn.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>ie.gameVersion,...t.pollRooms===void 0?{}:{poll:t.pollRooms},...t.recoverStaleMembership===void 0?{}:{recoverStaleMembership:t.recoverStaleMembership},...t.retryAutoStart===void 0?{}:{retryAutoStart:t.retryAutoStart},...t.watchSeats===void 0?{}:{watchSeats:t.watchSeats},...t.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:t.seatPollIntervalMs},...xo===null?{}:{autoReconnect:{...xo,redial:(u,A)=>Po.redialMatch(u,A),abandon:(u,A)=>Po.abandonMatch(u,A)}}});p(me),ec({analytics:d,rooms:me});let vt=Zd({client:bt,clock:e,rooms:me,bridge:$,gameId:()=>ie.identity?.gameId??"",baseUrl:()=>Be,resolveClusterTarget:Un.resolve,boot:a,...t.log===void 0?{}:{log:t.log}}),ja=Bi(a,n),Ut=Uc({client:bt,clock:e,rooms:me,signaling:()=>xa.channel(),signalingReady:jt,log:n??(()=>{})}),Po=tu({rooms:me,p2p:{connect:u=>ja(vt.connect(u)),session:u=>vt.session(u)},dedicated:{connect:(u=>Xr(a,"welcome",Ut.connect(u),n))},clock:e,identity:()=>ie.identity,apiBaseUrl:()=>Be,tokens:Ta,room:()=>me.currentRoom,autoReconnect:xo!==null,...t.log===void 0?{}:{log:t.log}}),gm=async()=>(await Kn(go)).playerId,Ua={client:bt,boot:a,get identity(){return ie.identity},awaitIdentity:(u=go)=>Kn(u),awaitBridge:u=>$.settled(u),get player(){return x.current},awaitPlayer:(u=av)=>x.wait(u),me:Na,characters:new fr(fe,void 0,Ea,qa),transfers:new br(fe,Bo,Na.inventory),gameConfig:Ao,purchases:_o.api,deviceSettings:jn.api,moments:Oa.api,ads:Ma.api,account:Ga.api,share:yu({frame:$,log:t.log}),arcade:sm,store:Da.api,vibration:_u({frame:$,log:t.log}),get avatarPickerAvailable(){return $.currentState==="connected"&&$.parentSupports("avatarPicker")},openAvatarPicker:u=>$.requestAvatarPicker(u?.tab),avatars3d:pm,settings:xe.api,controls:ku({recommended:()=>h.current?.recommended??null}),analytics:d,leaderboards:new Qt(fe),challenges:new zt(fe),showcase:new Zt(fe,gm),friends:new en(fe,{challenge:Fa.challenge,...i===void 0?{}:{launchedChallengeId:i}}),platform:new nn(fe,T,n),profiles:new rn(fe),functions:new Ke((u,A)=>Bs(fe,u,A)),get prefs(){return h.current},get paused(){return S},get cohorts(){return I.current},get viewport(){return W.current},awaitCohorts:(u=sv)=>I.wait(u),reportMuted:u=>{U=!!u,F();},showPortraitBorders:u=>{let A=uo(u);A!==void 0&&(N=A,ge());},cueReward:u=>$.cueReward(u),setWalletVisible:(u,A)=>{let G=Array.isArray(A?.only)?[...A.only]:void 0;return Y=G===void 0?{visible:u===true}:{visible:u===true,only:G},Re()},setMenu:u=>(ye=Array.isArray(u?.items)?{items:u.items.map(A=>({...A}))}:{},te()),setGemCorner:u=>{if(!nv.includes(u)){let A=typeof u=="string"?JSON.stringify(u.slice(0,48)):`a value of type ${typeof u}`;return console.warn(`[gem] setGemCorner: ${A} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return z=u,Ue()},reportFrame:()=>Fe.draw(),exit:u=>lv(me,$,u,d),frame:$,devtools:Ee,rooms:me,dedicatedServer:{listClusterTargets:u=>Ut.listClusterTargets(u),connect:(u=>Xr(a,"welcome",Ut.connect(u),n)),handleMatchEnded:(u,A)=>Ut.handleMatchEnded(u,A)},p2p:{handleSignalEvent:(u,A,G)=>vt.handleSignalEvent(u,A,G),session:u=>vt.session(u),connect:u=>ja(vt.connect(u))},match:Po};return Ua}var rm="the match has not started yet: the runtime hands over the host at `init`, and this was read before that. Read it from `init` or later \u2014 a bundle that needs a value at module scope is reading it one call too early.";function Aa(t,e={}){let n=e.clock??ue,r=()=>{let a=t();if(a===null)throw new Error(rm);return a},o=null,i=()=>{if(o===null)throw new Error(rm);return o};return {server:{get identity(){return i().identity},get client(){return i().client},get api(){return i().api},get match(){return i().match},get analytics(){return i().analytics},get functions(){return i().functions},get challenges(){return i().challenges},get room(){return i().room},dispose(){o?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(a){let d=r().profile?.(a);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:he(m,"profile.displayName"),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:he(d.displayTag,"profile.displayTag")}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(a){return r().playerNumber?.(a)},send(a,l,d){d===void 0?r().send(a,l):r().send(a,l,d);},broadcast(a,l){l===void 0?r().broadcast(a):r().broadcast(a,l);},kick(a,l){l===void 0?r().kick(a):r().kick(a,l);},log(a){r().log(a);},warn(a){r().warn(a);}},attach:()=>{o=Ft(r(),{...e,clock:n});}}}function om(t,e={}){let{server:n,attach:r}=Aa(()=>t,e);return r(),n}function dv(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:Je(e)}}}var cv=1e4;function uv(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout(cv));}catch{return}r.catch(o=>{o instanceof O&&o.status>=400&&o.status<500&&(e=o.status!==429);});}}function im(t,e={}){return ()=>{let n=null,{server:r,attach:o}=Aa(()=>n,e),i=t(r),s={async init(l){n=l,o(),await i.init?.();},async shutdown(l){let d=dv(l);try{await i.shutdown?.(d);}finally{r.dispose();}}},a=uv(r);return s.join=(l,d)=>(a(l),i.join?.(l,d)),i.leave&&(s.leave=(l,d)=>i.leave?.(l,d)),i.message&&(s.message=(l,d,m,c)=>i.message?.(l,d,m,c)),s}}Ka();
3
- exports.ARCADE_EMBEDDERS=ev;exports.AVATAR_RIGS=Qb;exports.AnalyticsApi=an;exports.AuthError=ne;exports.CONDITIONAL_HEADERS=Jn;exports.ChallengesApi=zt;exports.DEVICE_SETTINGS_MAX_BYTES=wa;exports.DedicatedServerError=w;exports.FriendChallengeError=at;exports.FriendsApi=en;exports.FunctionsApi=Ke;exports.GemApiError=O;exports.GemClient=We;exports.GemConfigError=pe;exports.GemFrame=Gn;exports.GemFunctionError=on;exports.GemSaveError=le;exports.GemUnframedError=On;exports.LeaderboardsApi=Qt;exports.MAX_PERIODS_BACK=Ml;exports.PLATFORM_EVENTS=sg;exports.PlatformApi=nn;exports.PlatformCurrenciesApi=xr;exports.PlatformEarnAllowanceApi=Pr;exports.PlayerText=ve;exports.ProfilesApi=rn;exports.PurchaseRefusal=Ve;exports.ShowcaseApi=Zt;exports.TransportRefusal=ae;exports.UNRELIABLE_CHANNEL_LABEL=un;exports.asPlayerText=he;exports.createBootTimeline=Wi;exports.createGem=mT;exports.createGemServer=Ft;exports.createHostTokenSource=Hc;exports.createMatchServer=om;exports.defineServer=im;exports.experimentSelection=Er;exports.leaveAndExit=lv;exports.mapIdentity=Pe;exports.markOnResolve=Xr;exports.platformIconUrl=Op;exports.presentJoinCredential=dn;exports.readTemplateTransports=Et;exports.readTransportAdvert=mn;exports.reportOnResolve=Bi;exports.systemClock=ue;exports.text=rt;exports.toBase64=zn;exports.webTransportAvailable=$r;return exports;})({});
1
+ var GemWebSdkGame=(function(exports){'use strict';var Am=Object.defineProperty;var xm=(t,e)=>{for(var n in e)Am(t,n,{get:e[n],enumerable:true});};var Ei="GemWebSdkHandshake";function Pm(){return typeof document>"u"?void 0:document.readyState}var za=()=>Date.now();function Xa(t={}){let e=t.win??window,n=e,r=n[Ei];if(r!==void 0)return r;let i=t.readyState??Pm,o=t.now??za,s=[],a=[],l=m=>{let c=m.data;!c||c.type!=="gem.handshake"||(s.length>=4&&(s.shift(),a.shift(),d.dropped+=1),s.push(m),a.push(o()));};e.addEventListener("message",l);let d={events:s,times:a,dropped:0,late:i()==="complete",uninstall(){e.removeEventListener("message",l);}};return n[Ei]=d,d}function Ya(t,e,n={}){let r=t[Ei];if(r===void 0)return null;let i=n.ttlMs??9500,o=n.now??za,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,m=false,c=o()-i;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(s[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:16.2.0]";function Qa(){let t=globalThis.__gemWebSdkVersion;if(typeof t!="string")return "";let e=t.lastIndexOf(":"),n=t.lastIndexOf("]");return e<0||n<=e+1?"":t.slice(e+1,n)}var Tm={initialDelayMs:2e3,maxDelayMs:6e4};function Em(t,e){return e!==void 0?!e:t==="chain_exhausted"}var _t=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;retry=null;failures=0;notBefore=0;disposed=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new ne(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.pastChainCeiling())throw new ne("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new ne(this.failure??"unavailable","the embedder asked for no new token yet; one is asked for when that wait is over");return this.refresh(this.nextReason())}pastChainCeiling(){return this.grant===null||this.seconds()<this.grant.chainEndsAt?false:(this.enter("lost","chain_exhausted"),true)}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);}dispose(){this.disposed=true,this.cancelRetry();}scheduleRetry(e){if(this.cancelRetry(),this.failures+=1,this.notBefore=e===void 0?0:this.options.clock.now()+e,this.disposed)return;let{initialDelayMs:n,maxDelayMs:r}=Tm,i=Math.min(r,n*2**(this.failures-1)),o=Math.max(i/2,e??0)+Math.random()*(i/2);this.retry={handle:this.options.clock.setTimeout(()=>this.retryNow(),o)};}retryNow(){this.retry=null,this.notBefore=0,!(this.state==="lost"||this.pastChainCeiling())&&this.refresh(this.nextReason()).catch(()=>{});}cancelRetry(){this.retry!==null&&(this.options.clock.clearTimeout(this.retry.handle),this.retry=null);}refresh(e){if(this.inFlight)return this.inFlight;this.cancelRetry();let n=this.generation;this.enter("pending");let r=this.options.request(e).then(i=>{if(n!==this.generation)throw new ne("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=Im(i),{retryable:s,retryAfterMs:a}=i??{};throw n===this.generation&&(Em(o,typeof s=="boolean"?s:void 0)?this.enter("lost",o):(this.scheduleRetry(typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0),this.enter("degraded",o))),i instanceof ne?i:new ne(o,String(i))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){(e==="ready"||e==="lost")&&this.cancelRetry(),e==="ready"&&(this.failures=0,this.notBefore=0),this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},ne=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Im(t){if(t instanceof ne)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var se=class t extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof t)return true;let n=e;return n?.name==="TransportRefusal"&&n.retryable===false}},Jn=["if-match","if-none-match"],Za=4096;function Cm(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let i=n.toLowerCase();if(!Jn.includes(i)||r===void 0)continue;let o=typeof r=="string"?Mm(r):r;if(typeof o!="string"||o.length>Za||!Om(o))throw new se(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${Za} characters, or contains a character outside the range an HTTP header value may carry. This is a malformed request, not a server failure; the value is withheld here rather than written to logs.`);o!==""&&(e[i]=o);}return Object.freeze(e)}function Mm(t){let e=i=>i===32||i===9||i===10||i===13,n=0,r=t.length;for(;n<r&&e(t.charCodeAt(n));)n++;for(;r>n&&e(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function Om(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n!==9&&(n<32||n===127||n>255))return false}return true}function Gm(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new se("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new se("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 es(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=Cm(i.headers),s=Gm(i),a=Object.freeze({...i,headers:o,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await t(a,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),c=await t(a,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new ne("unavailable","the server refused a freshly minted token");return c}}}function zn(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Lm(e))}function Xn(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Ii(t){return new TextDecoder().decode(Xn(t))}function Lm(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var M=class extends Error{constructor(n,r,i,o,s){super(`${n} (${r}): ${i}`);this.reason=n;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},rs=new WeakMap;function is(t){return rs.get(t)??{}}var Dm=new Set([408,429,500,502,503,504]),Fm=6e4,os=new WeakMap;function as(t,e){os.set(t,e);}function ts(t){return t!==null&&(t.reason==="rate_limited"||t.retryAfterSeconds!==void 0)}function $m(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new se(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(t)}. This is a configuration fault, not a server failure.`);return t}var We=class{constructor(e){this.options=e;}options;async get(e,n){return this.send({method:"GET",path:e,signal:n},true)}async getWithEtag(e,n={}){let r=await this.sendRaw({method:"GET",path:e,...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{headers:{"if-none-match":n.ifNoneMatch}}},true),i=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...i}:{modified:true,body:r.body,...i}}async put(e,n,r,i={}){return this.send({method:"PUT",path:e,body:n,signal:r,...Wt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async post(e,n,r,i={}){return this.send({method:"POST",path:e,body:n,signal:r,...Wt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async postBytes(e,n,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...Wt(i)},i.replaySafe===true,i.retryRateLimited!==false);return {bytes:qm(o.body),...o.invocationId===void 0?{}:{invocationId:o.invocationId}}}async patch(e,n,r,i={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...Wt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Wt(r)},r.replaySafe===true,r.retryRateLimited!==false)}async send(e,n,r=true){return (await this.sendRaw(e,n,r)).body}async sendRaw(e,n,r=true){let i=n?$m(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw ns(e.signal);let s=e.signal===void 0?void 0:os.get(e.signal);for(let a=0;a<i;a++){if(a>0){let m=this.backoffMs(a,o);if(ts(o)&&s!==void 0&&m>=s())throw o;await this.backoff(m,e.signal);}if(e.signal?.aborted)throw ts(o)&&s!==void 0&&s()<=0?o:ns(e.signal);let l;try{l=await this.options.transport.request(e);}catch(m){if(ne.isAuthError(m)||se.isRefusal(m)||e.signal?.aborted||Nm(m))throw m;o=new M("unavailable",0,String(m));continue}if(l.status>=200&&l.status<300||l.status===304)return l;let d=jm(l);if(!Dm.has(l.status)||l.status===429&&!r)throw d;o=d;}throw o??new M("unavailable",0,"no attempt was made")}backoffMs(e,n){let r=n?.retryAfterSeconds,i=r!==void 0?r*1e3:2**(e-1)*250,o=2**(e-1)*250;return Math.min(Math.max(i,o),Fm)}backoff(e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=this.options.clock,o=false,s=false,a,l=()=>{o||(o=true,s&&i.clearTimeout(a),n?.removeEventListener("abort",l),r());};n?.addEventListener("abort",l,{once:true}),a=i.setTimeout(l,e),s=true,o&&i.clearTimeout(a);})}};function qm(t){if(t instanceof Uint8Array)return t;if(t==null)return new Uint8Array(0);let e=typeof t=="string"?t:JSON.stringify(t);return new TextEncoder().encode(e)}function Wt(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function ns(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Nm(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function jm(t){let e=Bm(t),n=Hm(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&rs.set(e,r),e}var Um=new Map([["insufficient_funds","insufficient_funds"]]);function Bm(t){let{status:e,body:n}=t,r=Wm(n),i=t.retryAfterSeconds??Km(n),o=Vm(n),s=o===void 0?void 0:Um.get(o);if(s!==void 0)return new M(s,e,r,void 0,o);switch(e){case 304:return new M("not_modified",e,r);case 400:case 422:return new M("invalid",e,r,void 0,o);case 403:return new M("forbidden",e,r,void 0,o);case 404:return new M("not_found",e,r,void 0,o);case 402:return new M("insufficient_funds",e,r,void 0,o);case 409:return new M("conflict",e,r,void 0,o);case 412:return new M("precondition_failed",e,r,void 0,o);case 413:return new M("too_large",e,r,void 0,o);case 429:return new M("rate_limited",e,r,i,o);default:return new M("unavailable",e,r,i,o)}}function Wm(t){if(typeof t=="string")return t;let e=t?.message;if(typeof e=="string")return e;let n=t?.error;if(typeof n=="string")return n;let r=n?.message;return typeof r=="string"?r:"no detail"}function Hm(t){let n=t?.error?.details;return n===null?void 0:n}function Vm(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Km(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _(t){let e=String(t);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 ss(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function ls(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/add`;return t.client.post(s,i,o?.signal)}async function ds(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function cs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}`;return t.client.delete(r,n?.signal)}async function us(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/claim`;return t.client.post(s,i,o?.signal)}async function ms(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function ps(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function gs(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function fs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function ys(t,e,n,r,i){let o=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(o,i?.signal)}async function hs(t,e,n,r,i){let o=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(o,i?.signal)}async function bs(t,e,n,r){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.delete(i,r?.signal)}async function vs(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function _s(t,e,n,r,i,o){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function ws(t,e,n){let r=`/v1/games/${_(t.gameId())}/avatars-3d/${_(e)}/owned`;return t.client.get(r,n?.signal)}async function Ss(t,e,n){let r=`/v1/games/${_(t.gameId())}/config/channels/${_(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function ks(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.get(r,n?.signal)}async function Rs(t,e,n){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function As(t,e,n,r,i){let o=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function xs(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Ps(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/items/${_(r)}`;return t.client.get(o,i?.signal)}async function Ts(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${_(e)}/${_(n)}/${_(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function Es(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders/${_(r)}`;return t.client.get(o,i?.signal)}async function Is(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}`;return t.client.get(o,i?.signal)}async function Cs(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/catalogs/${_(r)}/recipes/${_(i)}/availability`;return t.client.get(s,o?.signal)}async function Ms(t,e,n,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Ci(t,e,n,r,i){let o=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Os(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}/friends`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function Gs(t,e,n){let r=`/v1/showcase/friends/${_(e)}`;return t.client.get(r,n?.signal)}async function Ls(t,e){let n=`/v1/games/${_(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function Ds(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}`;return t.client.get(r,n?.signal)}async function Fs(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function $s(t,e){let n=`/v1/games/${_(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function Yn(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function qs(t,e,n){let r=`/v1/profiles/players/${_(e)}`;return t.client.get(r,n?.signal)}async function Ns(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function js(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return t.client.get(r,n?.signal)}async function Us(t,e,n,r){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.get(i,r?.signal)}async function Bs(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function Ws(t,e,n){let r=`/v1/inventory/transfers/${_(e)}`;return t.client.get(r,n?.signal)}async function Hs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function Vs(t,e,n){let r=`/v1/games/${_(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true,retryRateLimited:false})}async function Ks(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Js(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/platform-funded-game-inventory-purchases`;return t.client.post(o,r,i?.signal)}async function zs(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Xs(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ys(t,e){return t.client.get("/v1/characters",e?.signal)}async function Qs(t,e,n,r){let i=`/v1/settings/${_(e)}/${_(n)}`;return t.client.get(i,r?.signal)}async function Zs(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function el(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${_(e)}/${_(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function tl(t,e){let n=new URLSearchParams;e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function nl(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i="/v1/friends"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function rl(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function il(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function ol(t,e,n,r){let i=`/v1/games/${_(t.gameId())}/matches/${_(e)}/end`;return t.client.post(i,n,r?.signal)}async function al(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/max`;return t.client.post(s,i,o?.signal)}async function sl(t,e,n,r,i,o){let s=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ll(t,e,n,r,i){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.put(o,r,i?.signal)}async function dl(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/rewarded-placements/${_(r)}/availability`;return t.client.get(o,i?.signal)}async function cl(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function ul(t,e,n,r){let i=`/v1/characters/${_(e)}`;return t.client.patch(i,n,r?.signal)}async function ml(t,e,n,r,i,o){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function pl(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/reset`;return t.client.post(s,i,o?.signal)}async function gl(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.delete(r,n?.signal)}var j="gem-web-bridge",Zn={min:1,max:1},Jm=65536,fl=8,Qn=5e3,yl=1024;var Ht=Object.create(null),er="__malformed";var Gi=Object.create(null),zm=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"]]);function tr(t){let e=Gi[t];if(e!==void 0)return e;for(let[n,r]of zm)if(t.startsWith(n))return r}function wt(t){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(t);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function Xm(t){let e;try{e=new URL(t);}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 Ym(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Qm(t){return /^[a-z_]+$/.test(t)}function Zm(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(t)&&!t.includes("--")}function Mi(t,e,n){if(e>fl)return `nesting deeper than ${fl}`;if(++n.nodes>Qn)return `more than ${Qn} values`;if(n.bytes>n.cap)return `over the ${n.cap} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=t;if(n.seen.has(i))return "a repeated or cyclic object reference";if(n.seen.add(i),Array.isArray(t)){if(t.length>yl)return `an array of ${t.length} entries, over the ${yl} limit`;n.bytes+=2;for(let a of t){let l=Mi(a,e+1,n);if(l)return l}return null}let o=Object.getPrototypeOf(t);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";n.bytes+=2;let s=t;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++n.nodes>Qn)return `more than ${Qn} values`;if(n.bytes+=a.length*3+4,n.bytes>n.cap)return `over the ${n.cap} byte limit`;let l=Mi(s[a],e+1,n);if(l)return l}return null}function ep(t,e=Jm){let n={nodes:0,bytes:0,seen:new Set,cap:e},r=Mi(t,0,n);return r?`message contains ${r}`:n.bytes>e?`message is over the ${e} byte limit`:null}var tp={origin:[wt,"not a well-formed origin"],url:[Xm,"not a safe absolute http(s) URL"],bcp47:[Ym,"not a well-formed BCP 47 tag"],code:[Qm,"not a code of lower-case letters and underscores"],gameRef:[Zm,"not a game id or web address"]};function hl(t,e,n){for(let r of e){let i=n===""?r[0]:`${n}.${r[0]}`,o=t[r[0]];if(o==null){if(r[1]<"a")continue;return `${i}: required`}let s=Oi(o,r,i);if(s)return s}return null}function Oi(t,e,n){let r=e[1].toLowerCase();switch(r){case "u":return typeof t=="boolean"?null:Oi(t,typeof t=="string"?[e[0],"s",e[2]]:[e[0],"n",e[3],e[4]],n);case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e[2])return `${n}: exceeds ${e[2]} characters`;if(e[3]){let[i,o]=tp[e[3]];if(!i(t))return `${n}: ${o}`}return null}case "n":case "i":return typeof t!="number"||!(r=="i"?Number.isInteger:Number.isFinite)(t)?`${n}: expected ${r=="i"?"integer":"number"}`:t<e[2]||t>e[3]?`${n}: out of range ${e[2]}..${e[3]}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let i=e[2];return i.includes(t)?null:`${n}: not one of ${i.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:hl(t,e[2],n);case "j":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "a":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e[2])return `${n}: exceeds ${e[2]} items`;let i=e[3],o=`${n}[]`;for(let s of t){if(s==null){if(i[1]<"a")continue;return `${o}: required`}let a=Oi(s,i,o);if(a)return a}return null}default:return `${n}: unknown kind ${String(r)}`}}var bl=Object.create(null);function R(t,e,n,r,i){return Ht[t]=n,r&&(Gi[t]=r),bl[t]=o=>{let s=ep(o,i);if(s)return s;if(typeof o!="object"||o===null||Array.isArray(o))return "message: expected object";let a=o;return a.gem!==j?"gem: wrong protocol marker":a.type!==t?`type: expected ${t}`:hl(a,e,"")}}var H=["requestId","s",64],et=["outcome","e",["ok","declined","unavailable"]],tt=["reason","S",64,"code"];R("gem.handshake",[["versions","o",[["min","i",1,1e3],["max","i",1,1e3]]],["capabilities","A",64,["","s",64]],["embedder","s",2048,"origin"],["unbidden","B"]],30);R("gem.handshake.accept",[["v","i",1,1e3],["capabilities","A",64,["","s",64]]],5);R("gem.token",[["token","s",4096],["requestId","S",64],["generation","i",0,2147483647],["apiBaseUrl","S",512,"url"],["playerId","s",64],["gameId","s",64],["channel","e",["dev","test","release"]],["gameVersion","S",64],["expiresAt","i",0,4102444800],["chainEndsAt","i",0,4102444800],["allowDevTools","B"]],30);R("gem.token.denied",[H,["retryable","b"],["retryAfterMs","I",0,36e5],["reason","e",["chain_exhausted","unavailable"]],["correlationId","s",64]],30);R("gem.player",[["untrusted","o",[["displayName","s",64],["displayTag","S",80],["displayHandle","s",80]]],["playerId","S",64],["discriminator","S",8],["avatarIconUrl","S",2048,"url"],["avatarIconId","S",64],["avatar3dId","S",64],["avatar3dModelUrl","S",2048,"url"],["avatar3dIconUrl","S",2048,"url"],["avatars3d","A",8,["","o",[["family","s",32],["id","s",64],["modelUrl","s",256,"url"],["iconUrl","s",256,"url"]]]],["badges","A",2,["","o",[["itemId","s",64],["iconUrl","s",2048,"url"]]]],["displayTag","s",8],["avatarUrl","S",2048,"url"],["boost","O",[["multipliers","a",8,["","o",[["currencyId","s",64],["currencySlug","s",32],["multiplierBp","i",1e4,1e6]]]],["expiresInDays","I",1,7]]]],12);R("gem.pause",[["paused","b"]],120);R("gem.prefs",[["reducedMotion","b"],["muted","b"],["showFrameStats","B"],["music","B"],["sounds","B"],["locale","s",35,"bcp47"],["recommended","O",[["volume","i",0,100],["batterySaver","b"],["keyboardLayout","e",["wasd","arrows"]],["gamepadConfirm","e",["south","east"]],["vibration","b"],["lookSensitivity","I",20,400],["gamepadLookSensitivity","I",20,400],["invertLookY","B"],["touchMovement","S",16,"code"],["graphicsQuality","S",16,"code"],["graphicsQualityAuto","B"],["colorHelp","B"]]]],60);R("gem.cohorts",[["cohorts","a",8,["","o",[["experimentId","s",36],["variantKey","s",32]]]]],12,"cohorts");R("gem.earnAllowanceChanged",[],30,"earnAllowance");R("gem.viewport",[["insets","o",[["top","i",0,4096],["right","i",0,4096],["bottom","i",0,4096],["left","i",0,4096]]],["reserved","A",4,["","o",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384],["control","O",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384]]]]]]],60,"viewport");R("gem.deviceSettings",[["settings","J"]],12,"deviceSettings");R("gem.willTerminate",[["reason","e",["grant_expiring","session_ended","navigating","kill_switch"]],["graceMs","i",0,6e4]],10);R("gem.roomEvent",[["event","e",["updated","match_started","match_ready","match_failed","version_stale"]],["roomId","s",64],["matchId","S",64],["version","I",0,2147483647],["reason","S",64],["platform","E",["universal","mobile"]]],120,"rooms");R("gem.socketState",[["connected","b"],["reason","E",["connecting","dropped","watchdog","terminal"]]],12,"socketState");R("gem.seatedEvent",[["roomId","s",64]],60,"partySeating");R("gem.autoStartFailedEvent",[["roomId","s",64],["code","s",64]],30,"autoStartFailure");R("gem.ticketEvent",[["event","e",["queued","matched","expired","cancelled","failed"]],["ticketId","s",64],["partySize","I",1,64],["queuedAt","I",0,4102444800],["expiresAt","I",0,4102444800],["reason","S",64],["roomId","S",64]],60,"ticketEvents");R("gem.signalEvent",[["event","e",["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]],["matchId","s",64],["data","j"]],1800,"p2p");R("gem.dedicatedEvent",[["event","e",["answer","error","matchEnded"]],["matchId","s",64],["sdp","S",10240],["sessionId","S",64],["code","S",64],["message","S",256],["reason","S",64]],120,"dedicated");R("gem.partyResult",[H,["partyId","S",64]],30,"parties");R("gem.clusterTarget",[["clusterTargetId","s",64],["clusterTargetIds","A",3,["","s",64]]],12,"clusterTarget");R("gem.devtools",[["action","e",["open","close","toggle"]]],30,"devtools");R("gem.screenshot",[["maxWidth","i",1,7680],["maxHeight","i",1,4320]],6,"screenshot");R("gem.screenshot.denied",[["reason","e",["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]],["retryable","b"]],12,"screenshot");R("gem.requestContext",[],12,"feedbackContext");R("gem.gameContext",[["context","j"]],12,"feedbackContext");R("gem.signal",[["signal","e",["join","offer","answer","ice","migrationAck","hostUnreachable"]],["matchId","s",64],["data","j"]],1200,"p2p");R("gem.dedicatedOffer",[["matchId","s",64],["sdp","s",10240],["intent","e",["initial","ice_restart","full_reconnect"]]],60,"dedicated");R("gem.partyRequest",[H],12,"parties");R("gem.ready",[],5);R("gem.engaged",[],5,"engagement");R("gem.progress",[["loaded","i",0,1099511627776],["total","i",0,1099511627776]],600);R("gem.requestToken",[H,["reason","e",["initial","expiring","rejected"]]],12);R("gem.requestLocalServer",[H,["gameRoomId","s",64]],6,"localHost");R("gem.localServer",[H,["serverId","S",128]],30,"localHost");R("gem.localServer.denied",[H,["retryable","b"],["reason","e",["refused","unavailable"]]],30,"localHost");R("gem.exit",[["reason","S",64]],5);R("gem.openExternal",[["url","s",2048,"url"]],6);R("gem.requestFullscreen",[["enabled","b"]],30);R("gem.audioState",[["muted","b"]],120,"audioState");R("gem.rewardCue",[["currencySlug","s",32],["expected","I",1,1e9],["origin","O",[["x","i",0,16384],["y","i",0,16384]]]],60,"rewardCue");R("gem.walletDisplay",[["visible","b"],["currencies","A",8,["","s",64]],["score","B"]],60,"walletDisplay");R("gem.controlsDeclare",[["uses","o",[["lookSensitivity","S",16,"code"],["gamepadLookSensitivity","S",16,"code"],["invertLookY","S",16,"code"],["touchMovement","S",16,"code"]]]],60,"controls");R("gem.menu",[["settings","b"],["items","A",4,["","o",[["id","s",32],["label","s",40]]]]],60,"gameMenu");R("gem.menuSelect",[["entry","e",["settings","item"]],["id","S",32]],60,"gameMenu");R("gem.gemCorner",[["corner","e",["top-left","top-right","bottom-left","bottom-right"]]],12,"gemCorner");R("gem.settingsDeclare",[["settings","a",8,["","o",[["id","s",40],["label","s",40],["kind","e",["toggle","slider","choice"]],["value","u",40,-1e6,1e6],["quick","B"],["icon","S",16,"code"],["min","N",-1e6,1e6],["max","N",-1e6,1e6],["step","N",0,1e6],["options","A",4,["","o",[["id","s",40],["label","s",40]]]]]]]],120,"gameSettings");R("gem.settingChange",[["id","s",40],["value","u",40,-1e6,1e6]],120,"gameSettings");R("gem.requestShare",[["params","a",16,["","o",[["key","s",64],["value","s",512]]]]],6,"share");R("gem.requestAvatarPicker",[["tab","E",["2d","3d"]]],6,"avatarPicker");R("gem.vibrate",[["pattern","a",99,["","i",0,1e4]]],600,"vibration");R("gem.frameStats",[["fps","i",0,1e3],["frameTimeP95Ms","i",0,1e5],["counts","E",["pageFrames","gameDraws"]]],120,"frameStats");R("gem.portraitBorders",[["name","S",40]],60,"portraitBorders");R("gem.error",[["code","e",["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]],["message","S",256]],60);R("gem.requestPurchase",[H,["purchaseKind","e",["item","recipe"]],["targetId","s",64],["currencySlug","s",32],["quantity","I",1,10],["catalogId","S",64]],12,"purchases");R("gem.requestAvatar3dPurchase",[H,["itemId","s",64],["currencySlug","s",32]],12,"avatar3dPurchases");R("gem.purchaseResult",[H,et,tt,["purchaseId","S",64]],30,"purchases");R("gem.deviceSettings.put",[H,["settings","j"]],30,"deviceSettings");R("gem.deviceSettings.result",[H,["outcome","e",["stored","too_large","unavailable"]]],30,"deviceSettings");R("gem.requestAd",[H,["placement","s",32],["format","e",["interstitial","rewarded"]]],6,"ads");R("gem.adResult",[H,["outcome","e",["shown","no_ad","unavailable"]]],12,"ads");R("gem.signalMoment",[H,["kind","e",["level_end","run_end","match_end","menu_return","other_break"]],["placement","S",32],["wall","B"]],6,"moments");R("gem.momentResult",[H,["shown","b"]],12,"moments");R("gem.requestSignIn",[H],6,"signIn");R("gem.signInResult",[H,["outcome","e",["signed_in","declined","unavailable"]]],12,"signIn");R("gem.requestFriendChallenge",[H,["playerId","s",64],["template","s",64],["params","J"]],12,"friendChallenges");R("gem.friendChallengeResult",[H,["outcome","e",["accepted","cancelled","refused","unavailable","rate_limited","invalid"]],["code","S",64],["param","S",64],["channel","S",16],["configVersion","I",0,9007199254740991],["retryAfterMs","I",0,864e5],["detail","S",300]],30,"friendChallenges");R("gem.requestAppLinks",[H],12,"appLinks");R("gem.appLinksResult",[H,et,tt,["arcade","O",[["store","e",["app_store","google_play"]]]],["game","O",[["store","e",["app_store","google_play"]]]]],30,"appLinks");R("gem.requestOpenApp",[H,["target","e",["arcade","game"]]],6,"appLinks");R("gem.openAppResult",[H,et,tt],30,"appLinks");var vl=R("gem.requestOpenGame",[H,["ref","s",40,"gameRef"]],6,"openGame");R("gem.openGameResult",[H,et,tt],30,"openGame");R("gem.requestSimilarGames",[H,["limit","I",1,24]],12,"openGame");R("gem.similarGamesResult",[H,et,tt,["games","a",24,["","o",[["gameId","s",36,"gameRef"],["slug","S",40,"gameRef"],["iconUrl","s",1024,"url"],["capsuleLandscapeUrl","s",1024,"url"],["capsulePortraitUrl","s",1024,"url"],["previewVideoUrl","S",1024,"url"],["previewPosterUrl","S",1024,"url"],["untrusted","o",[["name","s",64],["tagline","s",64],["shortDescription","s",320],["tags","a",10,["","s",32]]]]]]]],30,"openGame",524288);R("gem.requestStoreOffers",[H],12,"store");R("gem.storeOffersResult",[H,et,tt,["offers","a",32,["","o",[["skuId","s",64],["kind","e",["gem_pack","boost","pass","bundle"]],["name","s",80],["description","s",400],["imageUrl","S",1024,"url"],["priceDisplay","s",32],["grant","O",[["currency","s",32],["amount","i",1,1e9]]]]]]],30,"store",262144);R("gem.requestStorePurchase",[H,["skuId","s",64]],12,"store");R("gem.storePurchaseResult",[H,et,tt],30,"store");R("gem.storePurchaseSettled",[["skuId","s",64]],30,"store");var nr=Object.freeze(bl);Ht.__malformed=60;Object.freeze(Ht);Object.freeze(Gi);var ue={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Vt=class{constructor(e=ue){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Ht[e];if(n===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??n,s=Math.max(0,r-i),a=Math.min(n,o+s*n/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function St(t,e){return t.toLowerCase()===e.toLowerCase()}function He(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function rr(t,e){if(typeof e!="string"||e==="")return false;let n,r;try{n=new URL(t),r=new URL(e);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||n.username!==""||n.password!==""||n.pathname!=="/"||n.search!==""||n.hash!==""||n.port===""?false:He(n.hostname)&&He(r.hostname)}function _l(t,e){if(e.min>e.max)return null;let n=Math.min(t.max,e.max),r=Math.max(t.min,e.min);return n>=r?n:null}var ir=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}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,n={}){let i=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,o=i.find(a=>a.currencyId===e),s;return !o&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(o=i.find(a=>a.currencyId===s))),{currencyId:o?o.currencyId:s??e,total:o?o.total:null,...o?.buckets===void 0?{}:{buckets:o.buckets}}}};function Di(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let i=r??{};typeof i.id!="string"||i.id===""||typeof i.threshold!="number"||!Number.isFinite(i.threshold)||n.push({id:i.id,threshold:i.threshold,points:typeof i.points=="number"?i.points:0,hidden:i.hidden===true,...typeof i.unlocked_at=="number"&&Number.isFinite(i.unlocked_at)?{unlockedAt:i.unlocked_at}:{},...i.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var wl="inventory",kt=t=>typeof t=="number"?t:0,Kt=t=>typeof t=="string"?t:"";function Li(t,e){let n=t??{},r=typeof n.next_cursor=="string"?n.next_cursor:void 0;return {data:Array.isArray(n.data)?n.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function Sl(t){let e=t??{};return {itemDefinitionId:Kt(e.item_definition_id),instanceId:Kt(e.instance_id),quantity:kt(e.quantity),acquiredAt:kt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function np(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Li(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:Kt(a.bucket),balance:kt(a.balance)}}):void 0;return {currencyId:Kt(i.currency_id),total:kt(i.total),...o===void 0?{}:{buckets:o}}}),items:Li(e.items,Sl),progressions:Li(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:Kt(i.progression_definition_id),currentValue:kt(i.current_value),completionCount:kt(i.completion_count),isCompleted:i.is_completed===true,...Di(i)}}),...n===void 0?{}:{etag:n}}}var or=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${wl}#buckets`:wl;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let o=r.items.data.filter(s=>s.itemDefinitionId===e);if(o.length>0)return o}let i=await Ps(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(i)?i.map(Sl):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let n=await xs(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 np(n)}};var rp={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,already_owned:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},ip=new Set(Object.keys(rp));function kl(t){return typeof t=="string"&&ip.has(t)?t:"error"}var Ve=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var re=t=>typeof t=="string"?t:"",op=t=>typeof t=="string"?t:re(t&&typeof t=="object"?t.type:void 0),Ie=t=>typeof t=="number"?t:0;function ap(t){let e=t??{};return {prerequisiteType:re(e.prerequisite_type),referenceId:re(e.reference_id),required:Ie(e.required),current:Ie(e.current)}}function Jt(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:re(e.order_id),status:re(e.status),...n===void 0?{}:{etag:n}}}function ar(){return crypto.randomUUID()}var sp="recipe-usage",Rl=100;function sr(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:re(e.currency_id),bucket:re(e.bucket),delta:Ie(e.delta),balanceAfter:Ie(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:re(e.item_definition_id),instanceId:re(e.instance_id),delta:Ie(e.delta),quantityAfter:Ie(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:re(e.progression_definition_id),delta:Ie(e.delta),valueAfter:Ie(e.value_after),completed:e.completed===true};default:return {kind:"other",type:re(e.type)}}}function lp(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:re(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Ie(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(sr):[]}}function dp(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(lp):void 0;return {orderId:re(e.order_id),status:re(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(sr):[],consumed:Array.isArray(e.consumed)?e.consumed.map(sr):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(sr):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function cp(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:re(e.target_order_id)||re(e.source_order_id),status:re(e.status),purchaseId:re(e.purchase_id),sourceOrderId:re(e.source_order_id),price:{currencyId:re(n.platform_currency_id),amount:Ie(n.price)}}}function up(t){let e=t??{},n=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:re(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...n===void 0?{}:{lastUsedAt:n},...r===void 0?{}:{cooldownExpiresAt:r}}}function Al(t){switch(t.type){case "currency_grant":case "currency_consume":return {type:t.type,currency_id:t.currencyId,amount:t.amount};default:return {type:t.type,item_definition_id:t.itemDefinitionId,quantity:t.quantity}}}var lr=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;async create(e,n={}){let r=await this.write(()=>gs(this.api,this.entity.type,this.entity.id,{operations:e.map(Al),source:n.source??"play",nonce:ar()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Jt(r)}async createMany(e,n={}){return this.write(()=>ps(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Al),nonce:ar()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let o=await Cs(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},s=typeof o.uses_remaining=="number"?o.uses_remaining:void 0,a=typeof o.cooldown_expires_at=="string"?o.cooldown_expires_at:void 0,l=Array.isArray(o.lock_reasons)?o.lock_reasons.map(ap):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>op(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(sp,[],async()=>{let n=await Ms(this.api,this.entity.type,this.entity.id,{limit:Rl})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(up),truncated:r.length>=Rl}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>vs(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:ar()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...dp(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,i]=await Promise.all([Ns(this.api,n.signal===void 0?{}:{signal:n.signal}),Yn(this.api,n.signal===void 0?{}:{signal:n.signal})]),o=e.payment.currencySlug.toLowerCase(),s=i.currencies.find(c=>c.currency_id.toLowerCase()===o||c.slug.toLowerCase()===o);if(s===void 0){let c=i.currencies.map(p=>p.slug);throw new Ve("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let a=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(a===void 0)throw new Ve("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=a.platform_prices.find(c=>c.platform_currency_id===s.currency_id);if(l===void 0){let c=g=>i.currencies.find(f=>f.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${c(g.platform_currency_id)} ${g.price}`);throw new Ve("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Ve("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>Js(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:s.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:ar(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return cp(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let i=await this.write(()=>ls(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Jt(i)}async maxProgression(e,n,r){let i=await this.write(()=>al(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Jt(i)}async claimProgression(e,n){let r=await this.write(()=>us(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Jt(r)}async resetProgression(e,n){let r=await this.write(()=>pl(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Jt(r)}async write(e){return this.cache.invalidate(),e()}};var Fi=t=>typeof t=="string"?t:"",mp=t=>typeof t=="number"?t:0;function xl(t){let e=t??{};return {orderId:Fi(e.order_id),status:Fi(e.status),source:Fi(e.source),createdAt:mp(e.created_at)}}var dr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await Zs(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(xl):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await Es(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return xl(r)}};var Pl=t=>typeof t=="number"?t:0,pp=t=>typeof t=="string"?t:"";function gp(t){let e=t??{};return {progressionDefinitionId:pp(e.progression_definition_id),currentValue:Pl(e.current_value),completionCount:Pl(e.completion_count),isCompleted:e.is_completed===true,...Di(e)}}var cr=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let i=(await this.inventory.snapshot()).progressions.data.find(o=>o.progressionDefinitionId===e);if(i&&i.achievementsUnavailable!==true)return i;try{let o=await Is(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return gp(o)}catch{return i??null}}};var ur=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,i){this.rebind();let o=n.length===0,s=o?e:e+"\0"+n.join("\0"),a=this.slots.get(s);if(a){let c=a.filledAt;if(c!==void 0&&(i===void 0||this.clock.now()-c<=i))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,m=r().then(c=>(o&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function fp(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var yp=new Set(Jn);function hp(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))yp.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function mr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return es(async(n,r)=>{let i;try{i=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new se("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let o;try{o=new URL(i.href.replace(/\/+$/,"")+n.path);}catch{throw new se(`${JSON.stringify(typeof n.path=="string"?fp(n.path):"(a non-string path)")} does not form a valid URL against ${i.protocol}//${i.host}. This is a malformed request, not a server failure.`)}if(o.protocol!==i.protocol||o.host!==i.host)throw new se(`${JSON.stringify(o.pathname)} resolves to ${o.protocol}//${o.host}, not ${i.protocol}//${i.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(o.username!==""||o.password!==""){let g=i.username!==""||i.password!=="",f=o.username!==i.username||o.password!==i.password,v=g?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new se(`the ${v} puts credentials in the URL, which cannot be fetched (${n.method} ${o.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,f]of Object.entries(t.defaultQuery??{}))o.searchParams.has(g)||o.searchParams.set(g,f);let s=n.bytes,a=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(s=JSON.stringify(n.body),a="application/json");}catch(g){throw new se(`the body of ${n.method} ${JSON.stringify(o.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(o.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...hp(n.headers)},body:s,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),c=$i(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},t)}function $i(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}function qi(t){let e=i=>new RegExp(`<${i}>([^<]{0,300})</${i}>`).exec(t)?.[1]?.trim()||void 0,n=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(n.length>0)return n.join(" \u2014 ");let r=t.trim();return r?r.slice(0,300):""}async function pr(t){try{let e=qi(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ie=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},bp=3e4,vp=5e3,Tl=6e4,_p=2**31-1,El="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",wp=/^[A-Za-z0-9_]{1,64}$/;function Fe(t){let e=t.length===0?"a save key cannot be empty":t.length>64?`it is ${t.length} characters; a save key is at most 64`:t.startsWith("_")||t.startsWith("$")?`it begins with ${JSON.stringify(t[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(!wp.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Il(t,e){let n=new AbortController,r=Date.now()+e;as(n.signal,()=>r-Date.now());let i=AbortSignal.timeout(e),o=()=>n.abort(i.reason),s=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(i.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",s,{once:true})),{signal:n.signal,release:()=>{i.removeEventListener("abort",o),t?.removeEventListener("abort",s);}}}function Ni(t,e){return t.aborted&&e?.aborted!==true}var Sp=new Set(["x-ms-blob-type"]),kp=/^[ -~]+$/;function Rp(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,i]of Object.entries(t)){let o=r.toLowerCase();if(!Sp.has(o))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 i!="string"||!kp.test(i))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(o in n)throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);n[o]=i;}return n}function ji(t){let e=typeof t.metadata=="object"&&t.metadata!==null&&!Array.isArray(t.metadata)?t.metadata:void 0;return {key:t.key,sizeBytes:t.size_bytes,etag:t.etag,...e===void 0?{}:{metadata:e},createdAt:t.created_at,updatedAt:t.updated_at}}function Ui(t){return t?.reason==="not_found"}function Ap(t){return t?.code==="save_conflict"}function Cl(t){return t instanceof M&&t.reason==="rate_limited"}async function Ml(t,e){let n=await pr(e);return new M("rate_limited",429,`the save ${t} answered 429: too many save calls. ${n}`.trim(),$i(e.headers.get("retry-after")))}function gr(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function xp(t,e,n,r,i){let o=false,s=()=>o?false:(o=true,a.detach?.(),true),a={signal:n.signal,budget:r,deadlineAt:Date.now()+r,teardown:n.teardown===true,overwrite:n.overwrite===true,identity:i,resolve:l=>{s()&&t(l);},reject:l=>{s()&&e(l);},detach:void 0};return a}function Ol(t,e){return t!==null&&e!==null&&e!==t}function Gl(t){return new ie("save_conflict",`save ${JSON.stringify(t)} was not written: the signed-in player changed while it waited for the write before it, and it holds the last player's progress.`)}var fr=class{constructor(e,n,r={},i){this.api=e;this.entity=n;this.options=r;this.identity=i;}api;entity;options;identity;versions=new Map;seq=0;versionsOf=null;writes=new Map;holdUntil=0;async put(e,n,r={}){let i;try{i=JSON.stringify(n);}catch(o){throw new ie("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}. Retrying stores the same unserialisable value.`)}if(i===void 0)throw new 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(i),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){if(Fe(e),r.signal?.aborted)throw gr(r.signal);let i=this.budget(r.timeoutMs),o=this.slotWrites(e);return new Promise((s,a)=>{let l=o.queued;l?.release();let d=l?.waiters[l.waiters.length-1];d!==void 0&&this.holdOwn(o,d);let m=this.identity?.()??null;for(let c of l?.waiters.slice()??[])Ol(c.identity,m)&&this.drop(o,c,Gl(e));o.queued=this.queue(o,n,r,xp(s,a,r,i,m),l?.waiters??[]),o.wake?.(),this.pump(e,o);})}holdOwn(e,n){let{signal:r}=n,i=n.deadlineAt-Date.now();if(r?.aborted)return this.drop(e,n,gr(r));if(i<=0)return this.drop(e,n,this.timeout("save",n.budget));let o=AbortSignal.timeout(i),s=()=>this.drop(e,n,this.timeout("save",n.budget)),a=()=>{r&&this.drop(e,n,gr(r));};o.addEventListener("abort",s,{once:true}),r?.addEventListener("abort",a,{once:true}),n.detach=()=>{o.removeEventListener("abort",s),r?.removeEventListener("abort",a);};}drop(e,n,r){let i=e.queued?.waiters,o=i?.indexOf(n)??-1;o>=0&&i?.splice(o,1),n.reject(r),e.wake?.();}queue(e,n,r,i,o){let{budget:s}=i,a=[...o,i],l=AbortSignal.timeout(s),d=g=>{if(e.queued===p){this.take(e,p);for(let f of a)f.reject(g);e.wake?.();}},m=()=>d(this.timeout("save",s)),c=()=>{r.signal&&d(gr(r.signal));};l.addEventListener("abort",m,{once:true}),r.signal?.addEventListener("abort",c,{once:true});let p={bytes:n,options:r,budget:s,deadlineAt:i.deadlineAt,identity:i.identity,waiters:a,release:()=>{l.removeEventListener("abort",m),r.signal?.removeEventListener("abort",c);}};return p}async pump(e,n){if(!n.running){n.running=true;try{for(let r=n.queued;r!==void 0;r=n.queued){let i=Date.now(),o=this.holdUntil-i;if(o>0){if(o>=r.deadlineAt-i){this.take(n,r);for(let l of r.waiters)l.reject(this.held(e,o));continue}for(let l of r.waiters.slice(0,-1))o>=l.deadlineAt-i&&this.drop(n,l,this.held(e,o));}let s=Math.max(o,this.spacing(n,r,i));if(s>0){await this.pause(n,s);continue}this.take(n,r);let a;try{a=this.precondition(e,r);}catch(l){for(let d of r.waiters)d.reject(l);continue}n.lastSentAt=i;try{let l=await this.send(e,r,a);for(let d of r.waiters)d.resolve(l);}catch(l){for(let d of r.waiters)d.reject(l);}}}finally{n.running=false;}}}spacing(e,n,r){if(e.lastSentAt===void 0||n.waiters.some(s=>s.teardown))return 0;let i=this.options.minWriteIntervalMs??vp,o=Math.min(...n.waiters.map(s=>s.deadlineAt-s.budget/2));return Math.min(e.lastSentAt+i,o)-r}pause(e,n){return new Promise(r=>{let i=()=>{clearTimeout(o),e.wake===i&&(e.wake=void 0),r();},o=setTimeout(i,Math.min(n,_p));e.wake=i;})}take(e,n){e.queued===n&&(e.queued=void 0),n.release();}slotWrites(e){let n=this.writes.get(e);return n===void 0&&(n={running:false,queued:void 0,lastSentAt:void 0,wake:void 0},this.writes.set(e,n)),n}noteRateLimit(e){if(!Cl(e))return;let n=e.retryAfterSeconds,r=n===void 0?Tl:Math.min(n*1e3,Tl);this.holdUntil=Math.max(this.holdUntil,Date.now()+r);}held(e,n){let r=Math.ceil(n/1e3);return new M("rate_limited",429,`save ${JSON.stringify(e)} was not sent: the platform refused a save call for the rate, and the wait it asked for ends in ${r}s, after this call's timeoutMs. Keep the state and write once the wait is over.`,r)}async send(e,n,r){let{bytes:i,options:o,budget:s}=n,a=o.contentType??"application/octet-stream",l=Il(o.signal,Math.max(0,n.deadlineAt-Date.now()));try{let d=await ml(this.api,this.entity.type,this.entity.id,e,{size_bytes:i.byteLength,content_type:a,...r,...o.metadata===void 0?{}:{metadata:o.metadata}},{signal:l.signal});if(typeof d.upload_url!="string"||typeof d.session_id!="string")throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let m=Rp(d.upload_headers,e),c,p=this.options.fetch??globalThis.fetch.bind(globalThis);try{c=await p(d.upload_url,{method:"PUT",headers:{"content-type":a,...m},body:i,credentials:"omit",signal:l.signal});}catch(f){throw Ni(l.signal,o.signal)?this.timeout("upload",s):new ie("upload_failed",`${El} for PUT. Underlying error: ${f}`)}if(c.status===429)throw await Ml("upload",c);if(!c.ok){let f=await pr(c);throw new ie("upload_failed",c.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. "+f:`the save upload answered ${c.status}. `+(c.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. ":"")+f)}let g=ji(await _s(this.api,this.entity.type,this.entity.id,e,{session_id:d.session_id},{signal:l.signal}));return this.remember(e,g.etag?{kind:"etag",etag:g.etag}:void 0),g}catch(d){throw Ap(d)?new ie("save_conflict",`save ${JSON.stringify(e)} was not written: the stored save changed since this game last loaded or wrote it, so another device or tab saved in between. Load it again and decide what to write from what is stored, rather than resending this write.`):(this.noteRateLimit(d),this.rethrow(d,o.signal,l.signal,"save",s))}finally{l.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(i){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: ${i}`)}}async getBytes(e,n={}){Fe(e);let r=this.budget(n.timeoutMs),i=Il(n.signal,r),o=this.seq;try{let s;try{let m=await Ci(this.api,this.entity.type,this.entity.id,e,{signal:i.signal});if(!m.modified)return this.remember(e,{kind:"empty"},o),null;s=m.body;}catch(m){if(Ui(m))return this.remember(e,{kind:"empty"},o),null;throw m}if(typeof s.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),l;try{l=await a(s.download_url,{credentials:"omit",signal:i.signal});}catch(m){throw Ni(i.signal,n.signal)?this.timeout("download",r):new ie("download_failed",`${El} for GET. Underlying error: ${m}`)}if(l.status===429)throw await Ml("download",l);if(!l.ok){let m=await pr(l);throw new ie("download_failed",`the save download answered ${l.status}. `+(l.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+m)}let d=new Uint8Array(await l.arrayBuffer());return this.remember(e,s.etag?{kind:"etag",etag:s.etag}:void 0,o),d}catch(s){throw this.slots().get(e)===void 0&&this.remember(e,{kind:"failed"}),this.noteRateLimit(s),this.rethrow(s,n.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,n={}){try{let r=await Ci(this.api,this.entity.type,this.entity.id,Fe(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?ji(r.body):null}catch(r){if(Ui(r))return null;throw r}}async list(e={}){let n=await el(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=n.next_cursor;return {saves:(n.data??[]).map(ji),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await hs(this.api,this.entity.type,this.entity.id,Fe(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Ui(r))throw r}this.remember(e,{kind:"empty"});}precondition(e,n){if(Ol(n.identity,this.identity?.()??null))throw Gl(e);if(n.waiters.some(i=>i.overwrite))return {};let r=this.slots().get(e);if(r===void 0)return {};if(r.kind==="etag")return {if_match:r.etag};if(r.kind==="empty")return {if_none_match:"*"};throw new ie("load_failed",`save ${JSON.stringify(e)} was not written: the last load of this slot failed, so what this write would replace is unknown, and it could be the player's real progress. Load it again before saving, or pass overwrite: true if replacing whatever is stored is what you mean.`)}remember(e,n,r){let i=this.slots(),o=i.get(e);r!==void 0&&o!==void 0&&o.kind!=="failed"&&o.seq>r||(this.seq+=1,n===void 0?i.delete(e):i.set(e,{...n,seq:this.seq}));}slots(){let e=this.identity?.()??null;return e!==null&&e!==this.versionsOf&&(this.versionsOf!==null&&this.versions.clear(),this.versionsOf=e),this.versions}budget(e){return e??this.options.timeoutMs??bp}timeout(e,n){return new ie("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,i,o){return e instanceof ie||Cl(e)?e:Ni(r,n)?this.timeout(i,o):e}};function Pp(t){try{return Ii(t)}catch{return t}}function Bi(t,e){let n=t??{},r=typeof n.etag=="string"?n.etag:e;return {key:typeof n.key=="string"?n.key:"",value:typeof n.value=="string"?Pp(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var yr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await Qs(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>Bi(i)):[]}async get(e,n={}){try{let r=await As(this.api,this.entity.type,this.entity.id,e,{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Bi(r.body,r.etag):null}catch(r){if(Ll(r))return null;throw r}}async put(e,n,r={}){let i=await sl(this.api,this.entity.type,this.entity.id,e,{value:zn(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Bi(i)}async delete(e,n){try{await ys(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!Ll(r))throw r}}};function Ll(t){return t?.reason==="not_found"}function hr(t,e,n={}){let r=new ur(ue,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let i=new or(t,e,r);return {settings:new yr(t,e),inventory:i,saves:new fr(t,e,n.saves??{},n.identity),currencies:new ir(i,n.resolveCurrencyId),mutations:new lr(t,e,r),orders:new dr(t,e),progressions:new cr(t,e,i)}}var Wi={type:"players",id:"me"};var nt=t=>typeof t=="string"?t:"",Rt=t=>typeof t=="number"?t:0;function br(t,e){let n=e??{},r=nt(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:nt(n.player_id),gameId:nt(n.game_id),channel:nt(n.channel)||"release",name:nt(n.name),slotIndex:Rt(n.slot_index),isActive:n.is_active!==false,createdAt:nt(n.created_at),updatedAt:nt(n.updated_at)}}var vr=class{constructor(e,n,r,i){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=i;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=hr(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};async list(e){let r=(await Ys(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>br(this.scope,i)):[]}async get(e,n){let r=await ks(this.api,e,n===void 0?{}:{signal:n});return br(this.scope,r)}async create(e){let n=await ms(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return br(this.scope,n)}async update(e,n,r){let i=await ul(this.api,e,{name:n},r===void 0?{}:{signal:r});return br(this.scope,i)}async delete(e,n){await gl(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await Bs(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:Rt(r?.total_slots),availableSlots:Rt(r?.available_slots),activeCharacterCount:Rt(r?.active_character_count),defaultMaxSlots:Rt(r?.default_max_slots),purchasedExtraSlots:Rt(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var $l="[gem: use gem.text.toPlain()]",Dl=new Set,Fl;function Tp(t){try{if(Dl.has(t))return;let e=globalThis.location;if(Fl??=!!e?.port&&He(e.hostname??""),!Fl)return;Dl.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${$l}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
2
+ ${new Error().stack}`);}catch{}}var ve=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return Tp(this.#n),$l}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function he(t,e){return new ve(t,e)}var rt={toPlain(t){return ve.unwrap(t)},compare(t,e,n){let r=t instanceof ve?ve.unwrap(t):t,i=e instanceof ve?ve.unwrap(e):e;if(typeof Intl>"u"||typeof Intl.Collator!="function")return r<i?-1:r>i?1:0;let o;try{o=new Intl.Collator(n);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(t,e){let n=t instanceof ve?ve.unwrap(t):t,r=e instanceof ve?ve.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var At=t=>typeof t=="string"?t:"";function _r(t){let e=t??{},n=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:At(e.transfer_id),status:At(e.status),sourceEntityId:At(e.source_entity_id),targetEntityId:At(e.target_entity_id),...n===void 0?{}:{message:he(n,"transfer.message")},createdAt:At(e.created_at),expiresAt:At(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Ep(){return crypto.randomUUID()}var wr=class{constructor(e,n,r){this.api=e;this.self=n;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let n=await Ks(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:Ep()},e.signal===void 0?{}:{signal:e.signal});return _r(n)}async list(e={}){let r=await rl(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(_r):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await Ws(this.api,e,n===void 0?{}:{signal:n});return _r(r)}async accept(e,n){return this.resolve(()=>ss(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>cl(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>ds(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),_r(await e())}};var Ip=t=>typeof t=="string"?t:"",Cp=t=>typeof t=="string"&&t?t:void 0,Mp=t=>typeof t=="number"?t:void 0;function ql(t){let e=new Map(t.map(r=>[r.id,r])),n=new Map(t.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??n.get(r)??null}function Op(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new pe("config_malformed",`the config document is ${t===null?"null":typeof t}, expected a JSON object`);let e=t,n=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new pe("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Mp(e.version);if(r===void 0)throw new pe("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,m)=>{let c=Ip(l.id);if(!c)throw new pe("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},o=n("items");o.forEach((l,d)=>i(l??{},"items",d));let s=n("currencies");s.forEach((l,d)=>i(l??{},"currencies",d));let a=t;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:o,currencies:s,catalogs:n("catalogs"),loot_tables:n("loot_tables"),affix_pools:n("affix_pools"),progressions:n("progressions"),game_room_templates:n("game_room_templates"),kv:typeof a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:ql(o),currency:ql(s)}}var pe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Nl=10*1024*1024,jl=15e3,Ul=new Set(["dev","test","release"]);function Gp(t){if(!Ul.has(t))throw new pe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Ul].join(", ")}. gem-api would reject the assignment read.`);return t}var Sr=t=>typeof t=="number"?t:0,Hi=t=>typeof t=="string"?t:"";function Lp(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let i=r??{},o=typeof i.rarity_tier=="string"?i.rarity_tier:void 0;return {entryId:Hi(i.entry_id),weight:Sr(i.weight),dropRate:Sr(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:Hi(e.loot_table_id),name:Hi(e.name),rollCount:Sr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Sr(e.total_weight),entries:n}}var kr=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=void 0;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded!==void 0)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,n=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===n&&(this.inFlight=null);});return this.inFlight=n,n}refresh(){this.loaded=void 0,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new pe("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let i=this.dropRatesByConfig.get(r);i===void 0&&(i=new Map,this.dropRatesByConfig.set(r,i));let o=i.get(e);if(o!==void 0)return o;let s=(async()=>{let a=await Rs(this.api,e,n===void 0?{}:{signal:n});return Lp(a)})().catch(a=>{throw i?.get(e)===s&&i.delete(e),a});return i.set(e,s),s}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??jl),n;try{let l=await Ss(this.api,Gp(this.channel()),{signal:e});if(!l.modified)throw new pe("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof pe)throw l;if(l?.reason==="not_found")return null;throw l}let r=Cp(n.config_url);if(r===void 0)return null;let i=this.options.fetch??globalThis.fetch.bind(globalThis),o;try{o=await i(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new pe("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??jl}ms`):new pe("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!o.ok){let l=await o.text().then(d=>qi(d)).catch(()=>"");throw new pe("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await o.text();if(s.length>Nl)throw new pe("config_too_large",`the config document is ${s.length} bytes, over the ${Nl} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new pe("config_malformed",`config document is not JSON: ${String(l)}`)}return Op(a)}};var Bl=400,Ce=t=>typeof t=="string"?t:"",Dp=/(?:Z|[+-]\d{2}:?\d{2})$/i;function it(t){let e=Ce(t);if(!Dp.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Fp=/^[0-9a-f]{1,64}$/,$p=/^[0-9a-f]{16}$/,qp=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Np=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Vi(t){let e=Ce(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,i,o]=[Number(n[1]),Number(n[2]),Number(n[3])],s=new Date(Date.UTC(r,i-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===i-1&&s.getUTCDate()===o?e:void 0}var jp=4096,Up=new TextEncoder;function Bp(t){let e=Ce(t.challenge_data),n=Ce(t.challenge_data_hash);return e===""||!$p.test(n)?{}:Up.encode(e).length>jp?{}:{data:e,dataHash:n}}function Wp(t){let e=t??{},n=it(e.period_start_at),r=it(e.period_ends_at);if(n===0||r===0)return;let i=Ce(e.slug),o=Ce(e.seed),s=Vi(e.period_local_date),a=Ce(e.boundary),l=Ce(e.reset_time);return {id:Ce(e.progression_definition_id),...i===""?{}:{slug:i},window:Ce(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:qp.test(a)?a:"",resetTime:Np.test(l)?l:"",seed:Fp.test(o)?o:"",...Bp(e)}}function xt(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function Rr(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Wp).filter(n=>n!==void 0):[]}var zt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;xt(n);let r=await Xs(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return Rr(r)}};function Me(t){return typeof t=="string"&&t!==""?t:void 0}var Wl=new Set(["localhost","127.0.0.1","[::1]"]);function ot(t){return Ar(t)}function Ar(t){let e=Me(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&Wl.has(n.hostname)))return e}var Hp=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Vp=/^[a-z][a-z0-9_]{0,31}$/;function Kp(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let i=r??{},o=Me(i.family),s=Me(i.avatar_3d_id),a=ot(i.model_url),l=ot(i.icon_url);o===void 0||!Vp.test(o)||n.has(o)||s===void 0||!Hp.test(s)||a===void 0||l===void 0||(n.add(o),e.push({family:o,id:s,modelUrl:a,iconUrl:l}));}return e}function Jp(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},i=Me(r.item_id),o=ot(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Pe(t){let e=t??{},n=Me(e.player_id),r=Me(e.display_name),i=Me(e.discriminator),o=Me(e.display_tag),s=Me(e.avatar_icon_id),a=ot(e.avatar_icon_url),l=Me(e.avatar_3d_id),d=ot(e.avatar_3d_model_url),m=ot(e.avatar_3d_icon_url),c=Kp(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:he(r,"displayName")},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:he(o,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...m===void 0?{}:{avatar3dIconUrl:m},...c===void 0?{}:{avatars3d:c},badges:Jp(e.badges)}}var zp=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Xp(t){if(t===void 0)return;let e=ot(t);if(e===void 0)return;let n=new URL(e);return Wl.has(n.hostname)||zp.has(n.origin)?e:void 0}var Hl=100,Jl=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Ki(t){let{periodsBack:e,period:n,playerId:r}=t;if(xt(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!Jl.test(n)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(n)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...n===void 0?{}:{period:n},...r===void 0?{}:{player_id:r}}}function zl(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!Jl.test(e))return;let n=Vi(t.period_local_date),r=it(t.period_start_at),i=it(t.period_ends_at),o=r>0&&i>0;return {id:e,...n===void 0?{}:{localDate:n},...o?{startAt:r,endsAt:i}:{},opensAt:it(t.opens_at),closesAt:it(t.closes_at),final:t.final===true}}var Xt=t=>typeof t=="string"?t:"",Pt=t=>typeof t=="number"?t:0,Yt=t=>typeof t=="string"?t:void 0,Yp=t=>typeof t=="number"?t:void 0,Xl={player:"players",character:"characters"};function Qp(t,e){let n=t??{},r=Yt(n.entity_id),i=typeof n.entity_type=="string"&&Object.hasOwn(Xl,n.entity_type)?n.entity_type:void 0,o=Yl(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...Pe(n),rank:Pt(n.rank),occurredAt:Pt(n.occurred_at),...a===void 0?{}:{isViewer:a},...r===void 0?{}:{entityId:r},...i===void 0?{}:{entityType:i},...o===void 0?{}:{stats:o},...s===void 0?{}:{properties:s}}}function Vl(t,e){let n=t??{},r=Yt(n.bucket_1),i=Yt(n.bucket_2),o=Yp(n.update_frequency_seconds),s=zl(n);return {leaderboardType:Xt(n.leaderboard_type),runType:Xt(n.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(n.entries)?n.entries.map(a=>Qp(a,e)):[],generatedAt:Pt(n.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function Kl(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=Yl(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:Pt(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function Yl(t){if(t===null||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t))typeof r=="number"&&(e[n]=r);return e}function Zp(t,e,n){let r=t??{},i=Yt(r.bucket_1),o=Yt(r.bucket_2),s=zl(r);return {leaderboardType:Xt(r.leaderboard_type),runType:Xt(r.run_type),entityType:e,entityId:n,...i===void 0?{}:{bucket1:i},...o===void 0?{}:{bucket2:o},entries:Array.isArray(r.entries)?r.entries.map(Kl).filter(a=>a!==void 0):[],personalBest:Kl(r.personal_best)??null,totalRuns:Pt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:Pt(r.generated_at),...s===void 0?{}:{period:s}}}var Qt=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Ki(n),i=await Fs(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Vl(i,false)}async friends(e,n={}){let r=Ki(n),i=await Os(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Vl(i,true)}async mine(e,n={}){return this.#n(e,"player","me",n)}async character(e,n,r={}){return this.#n(e,"character",n,r)}async#n(e,n,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>Hl)throw new TypeError(`limit must be an integer between 1 and ${Hl}, got ${String(l)}`)}let o=Ki(i),s=await Ts(this.#e,e,Xl[n],r,{...o,...i.bucket1===void 0?{}:{bucket_1:i.bucket1},...i.bucket2===void 0?{}:{bucket_2:i.bucket2},...i.limit===void 0?{}:{limit:i.limit},...i.signal===void 0?{}:{signal:i.signal}}),a=n==="player"&&r==="me"&&Xt((s??{}).entity_id)||r;return Zp(s,n,a)}};var xr=t=>typeof t=="string"?t:"",Ji=t=>typeof t=="number"?t:0;function Ql(t){let e=t??{};return {playerId:xr(e.player_id),key:xr(e.key),value:e.value,updatedAt:Ji(e.updated_at)}}function eg(t){let e=t??{};return {...Pe(e),playerId:xr(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Ji(e.updated_at)}}function tg(t){return t?.reason==="not_found"}var Zt=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let i=await Gs(this.api,Fe(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:xr(i.key),entries:Array.isArray(i.entries)?i.entries.map(eg):[],generatedAt:Ji(i.generated_at)}}async of(e,n,r={}){try{return Ql(await Us(this.api,e,Fe(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(tg(i))return null;throw i}}async set(e,n,r={}){if(Fe(e),n===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(n);}catch(o){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}.`,{cause:o})}let i=await this.selfPlayerId();return Ql(await ll(this.api,i,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await bs(this.api,r,Fe(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var ng="gemChallenge",Zl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ed(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(ng)??void 0}catch{return}}var at=class extends M{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(n))i!==void 0&&Object.assign(this,{[r]:i});}},Pr=t=>typeof t=="string"?t:void 0;function td(t){let e=t??{};return {...Pe(e),playerId:Pr(e.player_id)??""}}function nd(t){let e=t.has_more===true?Pr(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function rg(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(td):[],...nd(e)}}var zi=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function ig(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function rd(t){let e=t??{},n=zi(e.opened_at),r=zi(e.answered_at);return {id:Pr(e.item_id)??"",from:td(e.sender),template:Pr(e.template)??"",params:ig(e.params),createdAt:zi(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function og(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(rd):[],...nd(e)}}function ag(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var en=class{#e;#n;#o;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#o=n.launchedChallengeId;}async list(e={}){let n=await nl(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return rg(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await tl(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return og(n)}async launchedChallenge(e={}){let n=this.#o;if(n===void 0||!Zl.test(n))return null;try{return rd(await Ds(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(ag(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!Zl.test(e))throw new M("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await il(this.#e,e);}};var sg=0;function _e(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++sg)}-${String(Date.now())}-${t}`}}var lg=12e4,id=8,dg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,cg=/^[a-z0-9][a-z0-9_-]{0,63}$/;function tn(t,e,n={}){return new at(new M("invalid",400,e,void 0,t),n)}function ug(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function mg(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!dg.test(e))return {error:tn("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!cg.test(n))return {error:tn("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:n,params:void 0};if(!ug(r))return {error:tn("param_invalid","params must be a plain object of strings and integers")};let i={},o=Object.keys(r);for(let s of o){let a=r[s];if(typeof a=="string"||typeof a=="number"&&Number.isSafeInteger(a)){Object.defineProperty(i,s,{value:a,enumerable:true,writable:true,configurable:true});continue}return {error:tn("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>id?{error:tn("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(id)}`)}:{playerId:e,template:n,params:i}}function pg(t){switch(t.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:t.outcome}};case "rate_limited":{let e=t.retryAfterMs,n=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new at(new M("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new at(new M("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function gg(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function od(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=mg(n);if("error"in r)return Promise.reject(r.error);let i=`challenge-${_e()}`;return new Promise((o,s)=>{let a={},l=m=>{e.delete(i)&&(t.clock.clearTimeout(a.timer),"error"in m?s(m.error):o(m.outcome));};e.set(i,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??lg);let d=false;try{d=t.bridge.requestFriendChallenge(i,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(n){let r=e.get(n.requestId);if(r===void 0){t.onDropped?.(`gem.friendChallengeResult (${gg(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(pg(n));}}}var Tr=t=>typeof t=="string"?t:void 0;function fg(t){let e=t??{},n=Tr(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Tr(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Er=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await Yn(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=fg(o);s!==void 0&&i.push(s);}return i}},Xi=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function yg(t){let e=t??{},n=Tr(e.currency_id);if(n===void 0||n==="")return;let r=Xi(e.limit),i=Math.min(Xi(e.earned),r),o=Math.min(Xi(e.remaining),r-i),s=e.period_days,a=typeof s=="number"&&Number.isInteger(s)&&s>=1?s:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Tr(e.currency_slug)??"",currencyId:n,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function ad(t){let e=new Set,n=r=>{t?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let i=r();typeof i?.then=="function"&&i.then(void 0,n);}catch(i){n(i);}}}}var Ir=class{#e;#n;#o;constructor(e,n,r){this.#e=e,this.#n=n,this.#o=r;}async get(e={}){let r=(await $s(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=yg(o);s!==void 0&&i.push(s);}return i}on(e,n){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},nn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Er(e),this.earnAllowance=new Ir(e,n,r);}};var Yi=t=>typeof t=="string"?t:"",sd=t=>typeof t=="number"?t:0;function hg(t){let e=t??{};return {key:Yi(e.key),visibility:Yi(e.visibility),value:e.value,updatedAt:sd(e.updated_at)}}function bg(t){let e=t??{};return {...Pe(e),playerId:Yi(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(hg):[],generatedAt:sd(e.generated_at)}}function vg(t){return t?.reason==="not_found"}var rn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return bg(await qs(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(vg(r))return null;throw r}}};var _g=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]]),on=class extends M{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:_g.get(this.code))??super.retryable}},Ke=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=wg(e),i;try{i=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(o){throw o instanceof M?kg(o):o}return Sg(i)}};function wg(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let e;try{e=JSON.stringify(t);}catch(n){throw new se(`the function input could not be serialised to JSON: ${String(n)}. 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 se(`the function input is ${typeof t}, 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 Sg(t){let{bytes:e}=t,n=()=>new TextDecoder("utf-8",{fatal:true}).decode(e);return {bytes:e,...t.invocationId===void 0?{}:{invocationId:t.invocationId},text:n,json:()=>JSON.parse(n())}}function kg(t){let{details:e,invocationId:n}=is(t),i=e?.untrusted?.message,o=e?.reason;return new on(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...t.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}function Cr(t,e){let n=e?.retryAfterSeconds,r=typeof n=="number"&&Number.isFinite(n)&&n>0?n*1e3:0,i=1e4*2**Math.min(Math.max(0,t-1),16);return Math.min(Math.max(r,i),3e5)}var Rg=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Qi="gem_";function ld(t){return t.startsWith(Qi)}function Ag(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function xg(t){let e=t;return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^=e>>>16,e>>>0}function Mr(t,e,n){if(Zi(t,n),typeof e!="string"||e==="")throw new TypeError("[gem] experiment: playerId must be a non-empty string");let r=typeof n=="number"?n:n.length,i=xg(Ag(`${t}:${e}`))%r;return typeof n=="number"?i:n[i]}function Zi(t,e){if(typeof t!="string"||t==="")throw new TypeError("[gem] experiment: key must be a non-empty string");if(typeof e=="number"){if(!Number.isInteger(e)||e<1||e>2048)throw new RangeError(`[gem] experiment '${t}': the count must be an integer from 1 to 2048; got ${String(e)}`);return}if(!Array.isArray(e))throw new TypeError(`[gem] experiment '${t}': pass a count or a list of strings; got ${typeof e}`);let n=e;if(n.length<1||n.length>2048)throw new RangeError(`[gem] experiment '${t}': the list must hold 1 to 2048 strings; got ${n.length}`);if(!n.every(r=>typeof r=="string"))throw new TypeError(`[gem] experiment '${t}': every option must be a string`)}var dd=1e4,cd=50,Pg=500,Tg=65536-4*1024,Eg=24*1024;function ud(t){let e={},n={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=i:typeof i=="number"&&Number.isFinite(i)&&(n[r]=i);return {dimensions:e,measures:n}}var md=t=>typeof t=="number"?t:0,Ig=t=>typeof t=="string"?t:"";function Or(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function Cg(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:md(o.index),code:Ig(o.code)}}):[];return {accepted:md(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function eo(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function Mg(t){return t?.retryable===true}var an=class{#e;#n;#o;#y;#t=[];#h={};#a=0;#s=null;#b=false;#v=false;#m=0;#_=0;#w=0;#r=false;#S=null;#l=null;#c=false;#i=false;#p=false;#k=false;#R=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#o=Math.max(dd,e.options?.flushIntervalMs??dd),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??Pg));}track(e,n={}){if(!(!this.#n||this.#r)){if(ld(e)){this.#R||(this.#R=true,this.#f(`[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.#A(e,ud({...this.#h,...n}));}}setContext(e){this.#h={...this.#h,...e};}async experiment(e,n){Zi(e,n);let r=this.#e.awaitPlayerId===void 0?this.#e.playerId():await this.#e.awaitPlayerId();if(r===null)throw new Error(`[gem] experiment '${e}': no player to select for \u2014 this call was not made by a player.`);return typeof n=="number"?Mr(e,r,n):Mr(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return Or();let n=this.#C();if(n===null||n==="")return this.#t.length>0&&!this.#k&&(this.#k=true,this.#f("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),Or();if(this.#P(),this.#t.length===0)return Or();let r=e.keepalive===true;if(this.#m>0&&!r)return Or();this.#u();let i=this.#t.splice(0,this.#E(r)),o=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:eo(),sent_at_ms:s,events:i.map(d=>pd(d,s))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await Vs(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=Cg(d,o);return this.#_=0,this.#w=0,this.#I(m),m}catch(d){throw Mg(d)?(this.#T(i,o),this.#_+=1,this.#w=this.#e.clock.now()+Cr(this.#_,d)):this.#f(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#m-=1,this.#t.length>0&&this.#d();}}trackPlatform(e,n={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#A(e,ud(n));}hold(){this.#r||this.#l!==null||(this.#i=true,this.#u());}release(){if(!this.#i||this.#r)return;this.#i=false;let e=this.#e.clock.now(),n=this.#t.map(r=>({...r,atMs:e}));this.#t=n,this.#p&&(this.#p=false,this.#l=e,this.#c=false,this.#t.unshift({uid:eo(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=cd?this.#g():this.#t.length>0&&this.#d();}get held(){return this.#i}startSession(){if(!(this.#r||this.#l!==null)){if(this.#i){this.#p=true;return}this.#l=this.#e.clock.now(),this.#c=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#c)return;if(this.#c=true,this.#i){this.#p=false,this.#t=[],this.#a=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#g({keepalive:true});}setPaused(e){this.#r||e===this.#b||(this.#b=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#v||(this.#v=e,e?this.#u():this.#t.length>0&&this.#d());}dispose(){this.#r=true,this.#u(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#A(e,n){let{dimensions:r,measures:i}=n;for(this.#P();this.#t.length>=this.#y;)this.#t.shift(),this.#a+=1;this.#t.push({uid:eo(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=cd?this.#g():this.#d();}#g(e={}){if(e.keepalive!==true&&this.#x()>0){this.#d();return}this.flush(e).catch(()=>{});}#x(){return Math.max(0,this.#w-this.#e.clock.now())}#T(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#y;)this.#t.shift(),this.#a+=1;}#E(e){let n=e?Eg:Tg,r=Math.min(this.#t.length,100),i=128;for(let o=0;o<r;o+=1){let s=this.#t[o];if(s===void 0)break;if(i+=JSON.stringify(pd(s,0)).length+1,i>n)return Math.max(1,o)}return r}#d(){this.#s!==null||this.#b||this.#v||this.#i||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#g();},Math.max(this.#o,this.#x())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#P(){let e=this.#M();e===null||e===""||(this.#S!==null&&this.#S!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#S=e);}#I(e){for(let n of e.rejected)this.#f(`[gem] analytics: an event was refused (${n.code}). `+Og(n.code));}#f(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#C(){try{return this.#e.gameId()}catch{return null}}#M(){try{return this.#e.playerId()}catch{return null}}};function pd(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function Og(t){switch(t){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 be(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function sn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=be(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Gg=2e3,Lg=5e3;function fd(t){let e=[],n=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,m=null;s=c=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(c));},m=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??Gg);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !gd(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=m=>{i.delete(d)&&(t.clock.clearTimeout(l),a(m));};i.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??Lg);})},accept(s,a){let l=sn(a),d=be(s),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...i])gd(m,p)||c(m);}}}}function gd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Dg=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(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="DedicatedServerError",this.retryable=Dg.has(n),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var yd=["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"],Fg=new Set(yd);function Je(t){return typeof t=="string"&&Fg.has(t)?t:"unknown"}var Gr="webrtc_dedicated",io=["universal","mobile","web"];var $g="p2p_unavailable",qg="capacity_unavailable",Ng=2,hd=3e4,bd=1e3,vd=2e4;async function oo(t){let e=be(t.clusterTargetId),n=t.nextClusterTarget,r=0,i=t.clock??ue,o=t.retry??{},s=o.budgetMs??hd,a=o.maxDelayMs??vd,l=o.initialDelayMs??bd,d=i.now(),m=d+s,c=0;for(;;){c++;try{let p=await co(t.signal,"while allocating",()=>t.client.post(`${Sd(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!jg(p)||s<=0)throw p;if(p.status===503&&p.code===$g)throw new w("p2p_unavailable",`room ${t.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===qg?r+1:0,n!==void 0&&r>=Ng){let x=n;n=void 0;let P=be(await x());P!==void 0&&(e=P,r=0);}let g=Math.min(a,l*2**(c-1)),f=Math.min(a,(p.retryAfterSeconds??0)*1e3),k=Math.max(g/2,f)+Math.random()*(g/2);if(i.now()+k>m)throw Ug(t,p,c,i.now()-d,s);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:k,status:p.status,message:p.message}),await Lr(i,k,t.signal),t.signal?.aborted)throw ro("while waiting to allocate")}}}function jg(t){return t instanceof M?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Ug(t,e,n,r,i){let o=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new w("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${o}: ${e.message}`,{cause:e}):new w("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${o}: ${e.message}`,{cause:e})}var Bg=12e4,Wg=1e3;async function ao(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Wg,i=t.timeoutMs??Bg,o=e.now()+i,s=_d(t),a={seen:t.knownToExist===true};for(;;){let l=await wd(t,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new w("timeout",`match ${n} was still ${l.status} after ${i}ms`);await Lr(e,r,t.signal);}}async function so(t){return (await wd(t,_d(t),{seen:t.knownToExist===true})).outcome}function _d(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Sd(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function wd(t,e,n){let{matchId:r}=t,i=t.clock.now(),o;try{o=await co(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof M&&s.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(n.seen=true,o.status==="ready")return {status:"ready",outcome:Hg(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Je(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function lo(t){let e=await co(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||n.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function co(t,e,n){if(t?.aborted)throw ro(e);try{return await n()}catch(r){throw t?.aborted?ro(e,r):r}}function ro(t,e){return new w("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function Hg(t,e,n){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:n+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function Sd(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Lr(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{t.clearTimeout(o),n?.removeEventListener("abort",i),r();},o=t.setTimeout(i,e);n?.addEventListener("abort",i);})}function kd(t){return typeof t=="string"&&t.trim()!==""}function Dr(t,e){return kd(t)?t.trim():kd(e)?e:null}var Fr="0.1.0-beta",Rd="0-beta",Tt="web",Vg=/^(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 Kg(t){let e=Vg.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Ad(t,e){let n=Jg(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:Fr};let i=Kg(r);if(i===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 '${Fr}' for it.`);if(i!==Rd)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Rd}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${Fr}' for it.`);return {...t,platform:n,engineVersion:r}}function Jg(t,e){if(t===void 0||t===Tt)return Tt;if(!io.includes(t))throw new w("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${io.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${Tt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${Tt}' 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.`),Tt}function ln(t){let e=t??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let n=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:xd(e.queued_at),expiresAt:xd(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function xd(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var zg=3,Pd=1e3,$r=class{constructor(e){this.options=e;this.snapshot=e.first;let n=new Promise((o,s)=>{this.resolve=o,this.reject=s;});n.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:n,cancel:()=>(this.requestCancel(),n)};}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 n=e?Pd:Math.max(Pd,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},n);}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,n=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){n=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(n);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof M&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<zg){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof M&&e.code==="matchmaking_unavailable";this.settle({status:n?"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 n=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:n});}catch(n){this.busy=false,this.fail(n);}}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 Xg="gemPlayWith",Yg=/^[A-Za-z0-9_-]{16,128}$/;function Td(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(Xg);}catch{return}return e!==null&&Yg.test(e)?e:void 0}function Ed(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var Qg="join",Zg="welcome",ef="rejected",Id=25e3,tf=1e3,uo=1;function mo(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var nf={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 po(t){let e=typeof t=="string"?t:"unknown";return new w(nf[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function dn(t){let{channel:e,clock:n}=t;return new Promise((r,i)=>{let o=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Id),a=n.setTimeout(()=>v(new w("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,tf)),l=k=>{let x=k.data;if(typeof x!="string"){c(x);return}let P;try{P=JSON.parse(x);}catch{c(x);return}if(o){c(x);return}if(P.t===Zg){let h=mo(P.heartbeat_interval);f({...typeof P.player_id=="string"?{playerId:P.player_id}:{},...typeof P.match_id=="string"?{matchId:P.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(P.t===ef){v(po(P.reason));return}c(x);},d=()=>{v(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{v(new w("aborted","the caller aborted during the join exchange"));},c=k=>{o&&t.onMessage?.(k);},p=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},f=k=>{o=true,p(),t.onMessage===void 0&&g(),r({welcome:k,detach:g});},v=k=>{o||(o=true,p(),g(),i(k));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Qg,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:uo}:{}}));}catch(k){v(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(k)}`,{cause:k}));}})}var st=1,cn=2,go=4,ho=8,rf=2,of=1e3,bo="heartbeat timeout",un="gem-uu",qr=2,Md="gem_transports";function Et(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!af(r)||e.includes(r)||e.push(r);}return e}function af(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function mn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Md];if(typeof n!="object"||n===null)return null;let r=n;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(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Od=new TextEncoder,Gd=new TextDecoder;function vo(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function _o(t){let e=0;return t?.reliable===false&&(e|=st),t?.ordered===false&&(e|=cn),e}function wo(t){return {reliable:(t&st)===0,ordered:(t&cn)===0}}var So={reliable:true,ordered:true};function Ld(t){return JSON.stringify({t:"join",credential:t,wire:qr,heartbeat:uo})}function Dd(t){let e;try{e=JSON.parse(t);}catch{throw new w("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=mo(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...n===void 0?{}:{heartbeatIntervalMs:n}}}throw e.t==="rejected"?po(e.reason):new w("join_refused","the server answered the join out of protocol")}function jr(){return typeof globalThis.WebTransport=="function"&&ko===null}function Ur(){return ko}var ko=null;var Cd="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function sf(t){let e=Xn(t);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 fo=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new w("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function yo(t,e){let n=new Uint8Array(5+e.byteLength);return new DataView(n.buffer).setUint32(0,e.byteLength+1,true),n[4]=t,n.set(e,5),n}async function pn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new w("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new a(t.url):new a(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:sf(t.certHashBase64)}]});}let r=n,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(ko=Cd,i(new w("connection_failed",`${Cd}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new w("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return i(new w("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(yo(go,Od.encode(Ld(t.credential))));let c=new fo,p=d.readable.getReader(),g;for(;g===void 0;){let f=await Promise.race([p.read(),s]);if(f.done||f.value===void 0)return i(new w("connection_failed","the control stream closed before the join was answered"));for(let v of c.push(f.value)){g=Dd(Gd.decode(v.payload));break}}return {link:lf(r,m,p,c,t.log??(f=>console.warn(f)),$d(g,t.clock)),welcome:g}}catch(a){return i(a)}}function lf(t,e,n,r,i,o){let s,a,l=false,d=f=>{if(!l){l=true,m.stop();try{t.close();}catch{}a?.(f);}},m=Ao(o,()=>d(bo)),c=(f,v)=>{m.heard(),(f&ho)===0&&s!==void 0&&((f&go)!==0?s(Gd.decode(v),So):s(v,wo(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let v of r.push(f.value))c(v.flags,v.payload);}}catch{}d("stream closed");})();let p,g;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let v=f.readable.getReader();g=f.writable.getWriter(),p=f,(async()=>{try{for(;;){let k=await v.read();if(k.done||k.value===void 0)break;let x=k.value;x.byteLength!==0&&c((x[0]??0)|st|cn,x.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){p=void 0,g=void 0,i(`[gem] webtransport datagram lane unusable (${Nr(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(Fd(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,v){if(l)return;if(typeof f=="string"){e.write(yo(go,Od.encode(f))).catch(()=>d("write failed"));return}let k=_o(v);if((k&st)!==0&&g!==void 0){let x=vo(k,f),P=p?.maxDatagramSize;if(P===void 0||x.byteLength<=P){g.write(x).catch(()=>{});return}}e.write(yo(k,f)).catch(()=>d("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){d("closed");}}}function Ro(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new w("connection_failed","this environment has no WebSocket"));n=new i(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),o(g));},d=()=>{r.send(Ld(t.credential));},m=g=>{if(s)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let f;try{f=Dd(g.data);}catch(v){l(v);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),i({link:df(r,$d(f,t.clock)),welcome:f});},c=()=>{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",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Fd(t){return typeof t=="string"&&t.length>0?t:void 0}function $d(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function Ao(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,of)*rf,i=n.now(),o=null,s=()=>{o=null;let a=n.now()-i;if(a>=r){e();return}o=n.setTimeout(s,r-a);};return o=n.setTimeout(s,r),{heard:()=>{i=n.now();},stop:()=>{o!==null&&(n.clearTimeout(o),o=null);}}}function df(t,e){let n,r,i=false,o=a=>{if(!i){i=true,s.stop();try{t.close();}catch{}r?.(a);}},s=Ao(e,()=>o(bo));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,So);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&ho)===0&&n?.(l.slice(1),wo(d));})),t.addEventListener("close",(a=>o(Fd(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){t.send(a);return}t.send(vo(_o(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){o("closed");}}}function xo(t,e,n,r){let i,o,s=false,a=n,l=c=>{if(!s){s=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}o?.(c);}},d=Ao(r,()=>l(bo)),m=(c,p)=>{if(d.heard(),typeof c=="string"){i?.(c,So);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let f=g[0]??0;(f&ho)===0&&i?.(g.slice(1),wo(f|p));};if(t.addEventListener("message",(c=>m(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),a!==void 0){let c=a;c.addEventListener("message",(p=>m(p.data,st|cn))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,p){if(s)return;if(typeof c=="string"){t.send(c);return}let g=_o(p),f=vo(g,c);if((g&st)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}t.send(f);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}function qd(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let i=Po(r);i!==void 0&&(e[n]=i);}return e}function Nd(t){if(Array.isArray(t))return t.map(cf).filter(e=>!!e)}function Po(t){if(To(t)||Array.isArray(t)&&t.every(To))return t}function To(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function cf(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Po(e.fixed),r=Po(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,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...It("description",uf(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(To)?{allowed:e.allowed}:{},...It("min",gn(e.min)),...It("max",gn(e.max)),...It("minItems",gn(e.min_items)),...It("maxItems",gn(e.max_items)),...It("maxLength",gn(e.max_length))}}function uf(t){return typeof t=="string"&&t.length>0?t:void 0}function gn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function It(t,e){return e===void 0?{}:{[t]:e}}function $e(t){let e=t??{},n=Q(e.id)??Q(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(mf):[];return {id:n,gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:Oe(e.max_players)??0,memberCount:Oe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...Re("joinCode",Q(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...Re("roomArgs",qd(e.room_args)),...Re("roomArgsTemplate",Nd(e.room_args_template)),gameChannel:Q(e.game_channel)??"release",...Re("region",Q(e.region)),...Re("clusterTargetId",Q(e.cluster_target_id)),selfHosted:e.self_hosted===true,...Re("matchId",Q(e.match_id)),version:Oe(e.version)??0,...Re("templateId",Q(e.template_id)),...Re("templateSlug",Q(e.template_slug)),roomType:Q(e.game_room_type)??"Standard",...Re("transports",Et(e.transports)??void 0),createdAt:Oe(e.created_at)??0,updatedAt:Oe(e.updated_at)??0,...Re("startedAt",Oe(e.started_at))}}function mf(t){let e=t??{};return {...Pe(e),playerId:Q(e.player_id)??"",isReady:e.is_ready===true,role:Q(e.role)??"member",joinedAt:Oe(e.joined_at)??0,...Re("groupId",Q(e.group_id)),...Re("platform",Q(e.platform))}}function Eo(t){let e=t??{};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:Oe(e.max_players)??0,memberCount:Oe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Q(e.game_channel)??"release",roomType:Q(e.game_room_type)??"Standard",createdAt:Oe(e.created_at)??0}}function Q(t){return typeof t=="string"&&t.length>0?t:void 0}function Oe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Re(t,e){return e===void 0?{}:{[t]:e}}var Br=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(Eo),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(n=>({rooms:(n.game_rooms??[]).map(Eo)}))}create(e,n,r){return gf(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},...fn(n)},e.signal).then($e)}get(e,n){return this.options.client.get(this.roomV2(e),n).then($e)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...fn(r)},n.signal).then($e)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...fn(r)},n.signal).then($e)}quickJoin(e,n,r=[]){return Io(this.options,e,n,r).then(i=>i.room)}createTicket(e,n,r=[]){return fs(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...fn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(ln)}heartbeatTicket(e){return Hs(this.generated(),e).then(ln)}cancelTicket(e,n=false){return n?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(ln):cs(this.generated(),e).then(ln)}leave(e,n,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return Ud(this.options,e)}close(e,n){return this.options.client.delete(this.roomV1(e),n).then(()=>{})}update(e,n){return this.options.client.patch(this.roomV2(e),{...n.name===void 0?{}:{name:n.name},...n.maxPlayers===void 0?{}:{max_players:n.maxPlayers},...n.isPublic===void 0?{}:{is_public:n.isPublic},...n.settings===void 0?{}:{settings:n.settings},...n.roomArgs===void 0?{}:{room_args:n.roomArgs}},n.signal).then($e)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then($e)}kick(e,n,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(n)}`,{},r).then(()=>this.get(e,r))}transferHost(e,n,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(n)}`,{},r).then($e)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return jd(this.options)}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 jd(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function Ud(t,e){return e===void 0&&t.selfHosted?.()===true}function Io(t,e,n,r=[],i){let o=Ud(t,e.partyId);return t.client.post(`${jd(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...pf(e.templateSlugs,o),...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},...o?{self_hosted:true}:{},...i===void 0?{}:{play_with_ticket:i},...fn(n)},e.signal).then(s=>({room:$e(s),playWith:i===void 0?null:Ed(s)}))}function pf(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function fn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function gf(t){t!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${t}) 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 Wr=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===i&&n(i);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};var Hr=class{constructor(e){this.options=e;let n=e.first,r=new Promise(a=>{this.resolve=a;}),i=()=>this.status;this.ticket={id:n.ticketId,get status(){return i()},partySize:n.partySize??0,queuedAt:n.queuedAt??0,expiresAt:n.expiresAt??0,outcome:r};let o=n.queuedAt!==void 0&&n.expiresAt!==void 0?(n.expiresAt-n.queuedAt)*1e3:9e5,s=Math.min(Math.max(o,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},s);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function ff(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var yf=1e3,hf=3e3,bf=6e4,vf=2,Bd=new Set(["game_room_closed","game_room_gone"]),_f=12e4,wf=5e3,Sf=new Set(["invalid_cluster_target","capacity_unavailable"]),kf=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Kd(t,e){return new Co(e,t)}var Co=class{constructor(e,n={}){this.options=e;this.internals=n;this.autoFollow=e.followMatch!==false,this.apiOptions={client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true},this.api=new Br(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new Wr;api;apiOptions;playWithAnswer=null;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await n;return this.api.create(r,this.version("create"),o[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,n={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(n),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(n),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),xf(e);let n=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.postQuickJoin(r,a).catch(l=>this.retryPastStaleMembership(l,r,a)),o=await this.run("quickJoin",async()=>{let a=await n;return i(a).catch(async l=>{let d=await this.afterRefusedClusters(l,a);if(d.length===0||Vd(d,a))throw l;return i(d)})}),{room:s}=o;return this.playWithAnswer=o.playWith,this.enter(s,"joined"),this.askForLocalServer(s),s}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Af(e?.templateSlugs),this.queueing=true;try{let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let s=await n;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Vd(l,s))throw a;return this.api.createTicket(r,this.version("queueForMatch"),l)})});this.heldQueued?.ticketId===i.id&&(this.heldQueued=null),this.partyWatch?.end({status:"lost"});let o=new $r({clock:this.options.clock,first:i,heartbeat:s=>this.track(this.api.heartbeatTicket(s)),cancel:(s,a)=>this.track(this.api.cancelTicket(s,a)),seat:s=>this.enterMatchedRoom(s),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;let n=this.heldQueued;this.heldQueued=null,n!==null&&this.showPartyTicket(n);}}async enterMatchedRoom(e){let n=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?n:(this.room!==null&&this.room.id!==n.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(n,"joined"),this.room?.id===n.id?this.room:n)}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let i of n)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(i){if(i instanceof M&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>so({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),...n===void 0?{}:{signal:n}})));}catch(s){return s instanceof M&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=Je(n.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 n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(i),i}async kick(e,n){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(i),i}async transferHost(e,n){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(i),i}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){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,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let i=be(n.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(m,c)=>oo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(o,[s]).catch(async m=>{if(i!==void 0||!Hd(m))throw m;let c=await this.nextCluster([s],true);if(c===void 0)throw m;return a(c,[s,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new 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 n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(i)}chase(e,n,r){return ao({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...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,!Bd.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,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let i={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}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,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!lt()){this.park(e,()=>this.reconnectStep(e));return}let n=this.options.autoReconnect;if(n===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=n.attempts||r<yf){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:n.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(ff(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!lt()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>so({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(o){this.reportError("reconcile",o);}if(this.reconnecting(e)){if(i?.status==="ended"){this.endMatch(i.matchId,i.reason,!Bd.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await n.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let n=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})):n&&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 n=this.session.matchId;this.session={phase:"suspended",matchId:n,reason:e},this.emitter.emit("matchSuspended",{matchId:n,cause:e}),this.armReconnect(n,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 n=this.heldMatchId;if(n===null)throw new w("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:n},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let n=this.heldMatchId;if(n!==null)try{await this.api.leaveMatch(n,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}get playWith(){return this.playWithAnswer}on(e,n){let r=this.emitter.on(e,n);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}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 n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Sf.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let n=new Hr({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===n&&(this.partyWatch=null);}});this.partyWatch=n,this.emitter.emit("partyQueued",n.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.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])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(i=>i.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&lt())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let n=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(n,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!lt())){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 Vr)e.addEventListener(r,this.visibilityListener);let n=globalThis.document;typeof n?.addEventListener=="function"&&n.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 n=this.inFlight;this.inFlight=[],await Promise.allSettled(n);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of Vr)e.removeEventListener?.(r,this.visibilityListener);globalThis.document?.removeEventListener?.("resume",this.visibilityListener),this.visibilityListener=null;}}get watchingSeats(){return this.options.watchSeats!==false&&this.emitter.hasListeners("seated")}get seatPollMs(){return this.options.seatPollIntervalMs??wf}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 n=this.options.clientVersion,r=Dr(this.options.platformGameVersion?.(),n?.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 Ad({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return sn(await this.options.resolveClusterTargets());let e=be(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Hd(e)||n.length===0?[]:sn(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!n?o:r(sn(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof M)||e.reason!=="conflict"||!kf.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(n.signal);}catch{throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new M(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.postQuickJoin(n,r)}postQuickJoin(e,n){return Io(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}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,n){try{return await this.track(this.onceGameIdKnown(n))}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,n){let r=n instanceof M?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof w?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){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(n,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 n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,l]of i){let d=r.get(a);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",a,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=Rf(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"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,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??_f;return new Promise((i,o)=>{let s=c=>{a(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>i(c))),l=this.emitter.on("matchFailed",(c,p)=>s(()=>o(new w("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>s(()=>o(new w("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>s(()=>o(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??hf}pushedInterval(){return this.options.pushedPollIntervalMs??bf}pushed(){return this.options.clock.now()-this.lastPushAt<vf*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=n=>{if(this.ticketWatch?.abandon(true),n?.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 lt(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Vr=["visibilitychange","focus","pageshow","online"];function Rf(t,e){return t.version!==e.version||t.status!==e.status||t.matchId!==e.matchId||t.hostPlayerId!==e.hostPlayerId||t.name!==e.name||t.maxPlayers!==e.maxPlayers||t.isPublic!==e.isPublic||Wd(t)!==Wd(e)}function Wd(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Hd(t){return t instanceof M&&t.code==="invalid_cluster_target"}var Kr=8;function Af(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=Kr&&t.every(n=>typeof n=="string"&&n.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Kr} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function xf(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Kr&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Kr} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(t?.templateSlug!==void 0||t?.templateId!==void 0)throw new w("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function Vd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Pf=["p2p","dedicated","unknown"],Mo=["connection_setup_duration_seconds","reconnect_latency_seconds","datachannel_rtt_seconds","p2p_join_to_play_latency_seconds","ice_restart_outcome_total","connection_failures_total","transport_permanent_failures_total","transport_quality_score","host_migration_outcome_total","turn_relay_usage_ratio"];var Ct=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let i=Tf(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},n);}report(e){this.post(e).catch(()=>{});}};function Tf(t,e,n){let r=Math.floor(n/1e3);return t.filter(i=>Mo.includes(i.type)).slice(0,100).map(i=>{let o=Ef(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Ef(t){if(t!==void 0)return Pf.includes(t)?t:"unknown"}var yn=class{constructor(e){this.options=e;this.reporter=new Ct({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:Jr(i.credential)??"",hostFingerprint:Jr(i.host_fingerprint)??"",hostEpoch:zr(i.host_epoch)??0,expiresAt:(zr(i.expires_at)??0)*1e3}}async turnLease(e,n,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&o.push({urls:m,username:Jr(d.username)??"",credential:Jr(d.credential)??""});}let s=zr(i.expires_at),a=zr(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,n,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:n},r);}async leave(e,n=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:n});}async telemetry(e,n){await this.reporter.post(e,n);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function Jr(t){return typeof t=="string"&&t.length>0?t:void 0}function zr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var If=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),D=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="P2pError",this.retryable=If.has(n);}reason;retryable};var Jd=10240,zd=2048,Cf=new TextEncoder;function Xd(t){return Cf.encode(t).length}function ze(t,e){let n=i=>{throw new w("invalid_sdp",`the ${e} ${i}`)},r=Xd(t);r>=Jd&&n(`is ${r} bytes, over the ${Jd} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let i of t.split(/\r\n|\n/)){let o=Xd(i);o>zd&&n(`has a ${o}-byte line, over the ${zd} limit`);}}function Xr(t){for(let e of t.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[n,r="0"]=e.slice(2).trim().split(/\s+/);if(!(n!=="audio"&&n!=="video")&&r.split("/")[0]!=="0")return true}return false}var Yr=class{listeners=new Map;on(e,n){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(n),()=>this.off(e,n)}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}clear(){this.listeners.clear();}};var Mf=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function Mt(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=Qr(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Qr(t){let[e,...n]=t.trim().split(/\s+/);if(e===void 0||n.length===0)return null;let r=`${e.toLowerCase()} ${n.join("").toUpperCase()}`;return Mf.test(r)?r:null}function hn(t,e){if(t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}var Oo=5e3,Of=12e4+Oo,Gf=1024,Lf=6e4,Df=1e4,Yd=64*1024,Qd=5;function Go(t){let e=new Map,n=-1/0,r=null,i=(()=>{let a;try{a=new URL(`${t.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=t.subtle??globalThis.crypto?.subtle;if(!a)throw new D("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!i.ok)throw new D("keys_unavailable",i.reason);let a=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(Df)});}catch{throw new D("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new D("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>Yd)throw new D("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Yd} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof D?p:new D("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Qd)throw new D("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Qd} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let f=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,f);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!i.ok)throw new D("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new D("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<n&&(n=-1/0),d-n<Lf?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var bn=class{seen=new Map;admit(e,n){for(let[r,i]of this.seen)i<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=Gf){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+Of),true}};function ec(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}function Zd(t){try{let e=new TextDecoder().decode(ec(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Lo(t,e,n,r,i){let o=N=>{throw new D("peer_unauthenticated",`the peer's join credential is not usable: ${N}`)},s=t.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,m=Zd(a);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let p=await n.key(c);p===null&&o("it was signed by a key this build cannot resolve");let g=i.subtle??globalThis.crypto?.subtle;g||o("this environment has no WebCrypto");let f=new TextEncoder().encode(`${a}.${l}`),v;try{v=ec(d);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,v,f)||o("its signature does not verify");let x=Zd(l);x===null&&o("its payload does not decode");let P=x,h=N=>typeof P[N]=="string"?P[N]:"",S=N=>typeof P[N]=="number"&&Number.isFinite(P[N])?P[N]:NaN;h("iss")!==i.issuer&&o("it was issued by someone else"),h("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),h("match_id")!==e.matchId&&o("it is for another match"),h("game_id")!==e.gameId&&o("it is for another game");let I=S("exp")*1e3,T=S("nbf")*1e3;(!Number.isFinite(I)||e.now>I+Oo)&&o("it has expired"),Number.isFinite(T)&&e.now<T-Oo&&o("it is not valid yet");let W=h("role");W!=="host"&&W!=="client"&&o("it names no usable role");let q=S("host_epoch");q!==e.hostEpoch&&o("it names a different host epoch");let U=Qr(h("fingerprint"));U===null&&o("its fingerprint claim is malformed"),hn(U,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let E=Qr(h("host_fingerprint"));E===null&&o("its host fingerprint claim is malformed"),hn(E,e.hostFingerprint)||o("it was issued against a different host certificate");let O=h("jti");O.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(O,e.now)||o("it has already been used");let F=h("sub");return F.length===0&&o("it names no player"),{playerId:F.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:q,role:W,fingerprint:U,hostFingerprint:E,jti:O,expiresAt:I}}function Do(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function Fo(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function $o(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function qo(t){if(t.byteLength<1)return null;let e=new DataView(t);switch(e.getUint8(0)){case 1:{if(t.byteLength<3)return null;let n=e.getUint16(1,true);return n>8192||t.byteLength<3+n+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(t,3,n)),protocolVersion:e.getUint32(3+n,true),assignedPeerId:e.getUint32(7+n,true)}}case 2:return t.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return t.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function tc(t){switch(t){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 (${t})`}}function nc(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var vn=class{constructor(e,n,r){this.localPlayerId=e;this.hostPlayerId=n,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,n){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=n,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var No={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}},qe=["reliable","ordered","unreliable"];function jo(t){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:t.iceServers,...t.certificates===void 0?{}:{certificates:t.certificates}})}async function _n(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var ic=1,jf=3e4,oc=2e3,Uf=5e3,ac=6e4,Bf=8,Bo=class{constructor(e=Bf){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 n=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[n++]=r);this.sent.length=n;}},Wf=new Bo,Hf=8,Vf=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Sn=class{constructor(e){this.options=e;this.keys=e.keys??Go({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Yr;links=new Map;replays=new bn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=ic+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 n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??jf;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),i=be(this.options.clusterTargetId);if(i!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Uo(a)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new D("timeout",`no usable P2P connection after ${n}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},n),s=()=>this.fail(new D("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",s),this.ready=null;}}async kick(e){if(!this.isHost)throw new D("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,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);default:return}}async onHello(e){let n=de(e.playerId),r=de(e.hostPlayerId),i=Zr(e.hostEpoch);if(!(n===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new vn(n,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,ic),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new D("invalid_sdp","the browser produced an offer with no SDP");ze(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:Mt(r);if(i===null)throw new D("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??Wf,s=()=>this.closed||e!==this.credentialGeneration,a=Uf;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let m=d.status,c;if(m===409)c=oc;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=a,a=Math.min(a*2,ac)),c=Math.min(Math.max(c,oc),ac);}else throw d;if(!await this.waitForCredential(c,s))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=Hf){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let i=de(e.sessionId);if(i!==null&&this.answeredSessions.get(n)===i)return;ze(r,"offer"),this.refuseMedia(r,"offer");let o=Mt(r);if(o===null)throw new D("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(n,i);let s=this.links.get(n);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(n,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let l=await a.connection.createAnswer();await a.connection.setLocalDescription(l);let d=a.connection.localDescription?.sdp??l.sdp;if(!d)throw new D("invalid_sdp","the browser produced an answer with no SDP");ze(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||n!==this.hostPlayerId)return;ze(r,"answer"),this.refuseMedia(r,"answer");let o=Mt(r);if(o===null)throw new D("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:hn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new D("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 n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e);}async onIce(e){let n=de(e.fromPlayerId),r=de(e.candidate);if(n===null||r===null)return;let i=this.links.get(n);if(!i)return;let o=de(e.sdpMid),s=Zr(e.sdpMLineIndex)??Zr(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let n=de(e.playerId);if(n===null)return;let r=de(e.reason)??"left";if(n===this.localPlayerId){this.fail(new D("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(n);i&&this.dropLink(i,r,true);}async onMigration(e){let n=de(e.hostPlayerId),r=Zr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:n,hostEpoch:r,...de(e.reason)===null?{}:{reason:de(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(i.kind==="refused"){this.report_(new D("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new D("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 n=de(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new D("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=de(e.code)??"unknown",r=de(e.message)??"the platform refused a signaling message";this.report_(new D("signaling_failed",`${n}: ${r}`));}openLink(e,n){let i=(this.options.peerConnectionFactory??jo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of qe){let g=i.createDataChannel(p,No[p]);g.binaryType="arraybuffer",o[p]=g;}let s={playerId:e,assignedPeerId:n,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),m=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",m),s.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",m);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}flushCandidates(e){let n=e.pendingCandidates;e.pendingCandidates=[];for(let r of n)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let n=this.credential;if(n===null)throw new D("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=n.expiresAt)throw new D("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(Do({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=qo(n);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 D(nc(r.reason),tc(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=Mt(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await Lo(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof D&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",Uo(s)),a&&this.fail(s);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Fo({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send($o(n));}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 n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let i of qe)sc(e.channels[i]);sc(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,n);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let n=this.ready;this.ready=null,n.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof D?e:new D("connection_failed",Uo(e),{cause:e}));}count(e){this.counted||!Vf.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(Xr(e))throw new D("media_refused",`the ${n} 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(n=>this.options.clock.setTimeout(n,e))}warn(e){let n=this.options.log;n!==null&&(n??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function de(t){return typeof t=="string"&&t.length>0?t:null}function Zr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Uo(t){return t instanceof Error?t.message:String(t)}function sc(t){try{t.close();}catch{}}var Kf=100,Jf=50,kn=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,n){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:n});}answer(e,n,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:n,assignedPeerId:r});}candidate(e,n,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Kf)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,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 D("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new D("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:n,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??Jf));}};function V(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Xe(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function Ot(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function lc(t){return typeof t=="boolean"?t:void 0}var Se=V(64),Rn=Xe(0,2147483647);function Wo(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=Se(n);typeof r=="string"&&e.push(r);}return e}function Y(t,e,n){return {to:t,from:e,read:n,required:true}}function K(t,e,n){return {to:t,from:e,read:n,required:false}}var Yf=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=Ot("disconnected","failed","closed")(e.iceState),r=Xe(0,4102444800)(e.lastSeenAt);if(!(n===void 0&&r===void 0))return {...n===void 0?{}:{ice_state:n},...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:[Y("sdp","sdp",V(10240)),Y("signaling_intent","intent",Ot("initial","ice_restart","full_reconnect")),K("sdp_hash","sdpHash",V(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[Y("peer_id","peerId",Se),Y("sdp","sdp",V(10240)),Y("assigned_peer_id","assignedPeerId",Xe(0,4294967295)),K("sdp_hash","sdpHash",V(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[Y("peer_id","peerId",Se),Y("candidate","candidate",V(512)),K("sdp_mid","sdpMid",V(64)),K("sdp_mline_index","sdpMLineIndex",Xe(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[Y("host_epoch","hostEpoch",Rn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[Y("host_epoch","hostEpoch",Rn),K("evidence","evidence",Yf)]}}));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:[Y("playerId","player_id",Se),Y("hostPlayerId","host_player_id",Se),Y("hostEpoch","host_epoch",Rn),K("members","members",Wo)],offer:[Y("fromPlayerId","from_player_id",Se),Y("sdp","sdp",V(10240)),K("sessionId","signaling_session_id",V(128)),K("sdpHash","sdp_hash",V(128)),K("iceUfrag","ice_ufrag",V(64)),K("intent","signaling_intent",Ot("initial","ice_restart","full_reconnect"))],answer:[Y("fromPlayerId","from_player_id",Se),Y("sdp","sdp",V(10240)),K("sessionId","signaling_session_id",V(128)),K("sdpHash","sdp_hash",V(128)),K("iceUfrag","ice_ufrag",V(64)),K("assignedPeerId","assigned_peer_id",Xe(0,4294967295))],ice:[Y("fromPlayerId","from_player_id",Se),Y("candidate","candidate",V(512)),K("sdpMid","sdp_mid",V(64)),K("sdpMLineIndex","sdp_m_line_index",Xe(0,255)),K("sdpMLineIndexAlt","sdp_mline_index",Xe(0,255))],peerJoined:[Y("playerId","player_id",Se)],peerLeft:[Y("playerId","player_id",Se),K("reason","reason",V(64))],migration:[Y("hostPlayerId","new_host_player_id",Se),Y("hostEpoch","host_epoch",Rn),K("reason","reason",V(64)),K("kickedPlayerIds","kicked_player_ids",Wo),K("migrationComplete","migration_complete",lc)],matchEnded:[K("reason","reason",V(64))],error:[K("code","code",V(64)),K("message","message",V(256))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var ct="webrtc_p2p";function cc(t){let e=new yn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,i,o){n.get(r)?.handleSignal(i,o);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new D("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=be(r.clusterTargetId),o=i??be(await t.resolveClusterTarget?.());t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let s=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==ct)throw new D("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${ct}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new kn({bridge:t.bridge,matchId:s.matchId,clock:t.clock}),l=new Sn({api:e,clock:t.clock,matchId:s.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:a,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await _n(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(s.matchId,l),l.on("matchEnded",()=>n.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(s.matchId),l.close(),d}return l}}}function uc(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,i=t.document??globalThis.document,o=[];if(typeof r.addEventListener=="function"){let a=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",a),o.push(()=>r.removeEventListener?.("pagehide",a));let l=()=>e.setHidden(!lt());for(let d of Vr)r.addEventListener(d,l),o.push(()=>r.removeEventListener?.(d,l));typeof i?.addEventListener=="function"&&(i.addEventListener("resume",l),o.push(()=>i.removeEventListener?.("resume",l))),e.setHidden(!lt());}let s=new Map;return o.push(n.on("matchReady",a=>{let l=a.protocol===ct?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(n.on("matchEnded",a=>{let l=s.get(a.matchId);l!==void 0&&(s.delete(a.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let a of o.splice(0))try{a();}catch{}s.clear();}}var mc=["pointerdown","keydown"];function pc(t,e=globalThis){let n=false,r=false,i=null,o=()=>{if(i!==null){try{e.cancelAnimationFrame?.(i);}catch{}i=null;}},s=()=>{if(!r){r=true,o();for(let g of mc)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(g){g?.isTrusted===true&&a();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(f=>f?.buttons.some(v=>v.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},c=()=>{if(i=null,!(n||r)){if(d()){a();return}m()&&(i=e.requestAnimationFrame?.(c)??null);}};function p(){i===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let g of mc)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(i=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:s}}async function ei(t,e,n,r){let i=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),i}function Ho(t,e){let n=false;return async r=>{let i=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),i}}function Vo(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(i,o){return r.has(i)?false:(r.add(i),n.push({name:i,at:o??e()}),true)},timeline(){let i=[...n].sort((o,s)=>o.at-s.at);return i.map((o,s)=>{let a=i[s-1],l=a===void 0?"":` (+${Math.round(o.at-a.at)}ms)`;return `${o.name}@${Math.round(o.at)}ms${l}`}).join(" \u2192 ")}}}var Ko=new WeakMap,gc=new WeakSet,Jo=new Set,ti=new Set,ni=[],Lt=null,zo=false,Qf=1920;function Xo(t){return Ko.get(t)}function Yo(t){return !zo||gc.has(t)}function Qo(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function fc(t=globalThis.window){if(zo||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;zo=true;for(let o of Array.from(t.document?.querySelectorAll("canvas")??[]))gc.add(o);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(o,...s){let a=n.call(this,o,...s);if(a&&!Ko.has(this)){let l={kind:o,context:a};Ko.set(this,l),Qo(l)&&Jo.add(this);}return a};let r=t.requestAnimationFrame,i=t.cancelAnimationFrame;t.requestAnimationFrame=o=>{let s=r.call(t,a=>{ti.delete(s);try{o(a);}finally{Zf();}});return ti.add(s),bc(),s},t.cancelAnimationFrame=o=>{ti.delete(o),i.call(t,o);};}function yc(t,e){return new Promise(n=>{let r={canvas:t,done:o=>{clearTimeout(i),ni=ni.filter(s=>s!==r),n(o);}},i=setTimeout(()=>r.done(null),e);ni.push(r);})}function hc(t){return Lt?.canvas===t?Lt.bitmap:null}function Zf(){for(let t of ni){let e;try{e=Zo(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}ti.size===0&&ey();}function ey(){let t=null;for(let r of Jo)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):Jo.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,Qf/Math.max(t.width,t.height)),n=e<1?{resizeWidth:Math.max(1,Math.floor(t.width*e)),resizeHeight:Math.max(1,Math.floor(t.height*e)),resizeQuality:"medium"}:{};bc(),Lt={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function bc(){Lt&&(Lt.bitmap.then(t=>t?.close()),Lt=null);}function Zo(t){let e=ty();if(!e)return true;e.clearRect(0,0,8,8),e.drawImage(t,0,0,8,8);let n=e.getImageData(0,0,8,8).data;for(let r=0;r<n.length;r+=4){if(n[r]|n[r+1]|n[r+2])return true;let i=n[r+3];if(i!==0&&i!==255)return true}return false}var An;function ty(){if(An!==void 0)return An;if(typeof OffscreenCanvas=="function")An=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),An=t?.getContext("2d",{willReadFrequently:true})??null;}return An??null}var ea=false;async function Sc(t,e,n,r){if(ea){e.close(),n("busy",true);return}ea=true;let i=null;try{let o=await iy(t,r);if(typeof o=="string"){e.close(),n(o,ny(o));return}i=o;let a=await(r.encodeRef??(l=>dy(l,r)))(i);if(i.close(),i=null,a===null){e.close(),n("failed",!0);return}if(a.size>ly){e.close(),n("too_large",!1);return}e.postMessage(a);}catch(o){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",o);}finally{ea=false,i?.close();}}function ny(t){switch(t){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}}var ry=600;async function iy(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":vc(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=sy(n);if(!r)return "no_source";try{let i=await oy(r);return typeof i=="string"?i:vc(i,t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}async function oy(t){let e=ay(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!Qo(e))return createImageBitmap(t);let n=await yc(t,ry);if(n)return n;let r=await hc(t);return r&&Zo(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function ay(t){let e=Xo(t);if(e)return e;if(!Yo(t))return "no_source";try{for(let n of ["webgl2","webgl","2d","webgpu"]){let r=t.getContext(n);if(r)return {kind:n,context:r}}}catch{return "unreadable"}return "unreadable"}function sy(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let i=r.width*r.height;i<=0||r.clientWidth<=0||r.clientHeight<=0||!Xo(r)&&!Yo(r)||i>n&&(e=r,n=i);}return e}async function vc(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let i=Math.min(n/t.width,r/t.height),o=Math.max(1,Math.floor(t.width*i)),s=Math.max(1,Math.floor(t.height*i));try{let a=await createImageBitmap(t,{resizeWidth:o,resizeHeight:s,resizeQuality:"high"});return t.close(),a}catch{return t.close(),"too_large"}}var ly=8*1024*1024,_c="image/webp",wc=.92;async function dy(t,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(t.width,t.height),s=o.getContext("2d");if(s){s.drawImage(t,0,0);let a=await o.convertToBlob({type:_c,quality:wc});if(a&&a.size>0)return a}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let i=r.getContext("2d");return !i||(i.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(s=>o(s),_c,wc);})}async function kc(t,e){if(!e)return;let n;try{n=await cy(e);}catch(r){console.error("[gem] onFeedbackContext threw; sending the report without context",r);return}if(n!=null){if(typeof n!="object"||Array.isArray(n)){console.error("[gem] onFeedbackContext must return a plain object or null; got",n);return}t.sendGameContext(n);}}function cy(t){return new Promise((e,n)=>{let r=false,i=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>t())().then(o=>{r||(r=true,clearTimeout(i),e(o??null));},o=>{r||(r=true,clearTimeout(i),n(o instanceof Error?o:new Error(String(o))));});})}var Rc=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Ac(t=globalThis){let n=t[Rc];if(n!==void 0)return n;let r=false,i=()=>r,o=[],s=uy(t,i);s!==null&&o.push(s);let a=my(t,i);a!==null&&o.push(a);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of o)c();}}};return Object.defineProperty(t,Rc,{value:l,configurable:true}),l}function uy(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let i=t.OfflineAudioContext,o=n.connect,s=n.disconnect,a=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(i!==void 0&&c instanceof i)return null;let p=a.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,o.call(p,m),a.set(c,p)),p};return n.connect=function(...c){let[p,...g]=c;if(p instanceof r){let f;try{f=d(p);}catch{f=null;}if(f!==null)return o.call(this,f,...g),p}return o.apply(this,c)},n.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let f=a.get(p.context);if(f!==void 0&&f!==this)try{return s.call(this,f,...g)}catch{}}return s.apply(this,c)},()=>{for(let[m,c]of a){if(m.state==="closed"){a.delete(m);continue}try{l(c);}catch{}}}}function my(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,i=Object.getOwnPropertyDescriptor(r,"muted"),o=i?.get,s=i?.set;if(o===void 0||s===void 0)return null;let a=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!o.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),s.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!o.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return a.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{s.call(g,(l.get(g)??!1)||e());}catch{}}}}var py=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",gy=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',fy=`${py}${gy}`,ta=new WeakSet;function xc(t=globalThis.document){if(t==null||ta.has(t))return null;try{let e=t.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(t.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(fy),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],ta.add(t),"sheet"}let n=t.documentElement?.style;return n===void 0||typeof n.setProperty!="function"?null:(n.setProperty("-webkit-user-select","none"),n.setProperty("user-select","none"),n.setProperty("-webkit-tap-highlight-color","transparent"),ta.add(t),"inline")}catch{return null}}function Pc(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=t.now??(()=>globalThis.performance?.now()??Date.now()),i=false,o=false,s=false,a=null,l=null,d=null,m=[],c=false,p=0,g=null,f=[],v=()=>i&&!o&&!s,k=()=>{l=null,d=null,m=[],p=0,g=null,f=[];},x=S=>{if(a=null,!v()){k();return}if(d!==null&&m.push(S-d),d=S,l===null)l=S;else {let I=S-l;if(I>=e&&m.length>0){if(c){let T=g===null?I:r()-g;t.report(hy(p,f,I,T));}else t.report(yy(m,I));l=S,m=[],p=0,f=[];}}P();},P=()=>{let S=n.requestAnimationFrame;typeof S=="function"&&(a=S.call(n,x));},h=()=>{if(v()){a===null&&(k(),P());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),k();};return {setRequested(S){i=S,h();},setPaused(S){o=S,h();},draw(){if(!c){c=true,a!==null&&k();return}if(a===null||l===null)return;let S=r();g!==null&&f.length<1e3&&f.push(S-g),g=S,p+=1;},get running(){return a!==null},dispose(){s=true,h();}}}function yy(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:Tc(t),counts:"pageFrames"}}function hy(t,e,n,r){let i=r;return e.length>0&&(i=Tc(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:i,counts:"gameDraws"}}function Tc(t){let e=[...t].sort((r,i)=>r-i),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var ri=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Ec(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Ic(t,e){t!==null&&(t.style.setProperty(ri.top,`${e.top}px`),t.style.setProperty(ri.right,`${e.right}px`),t.style.setProperty(ri.bottom,`${e.bottom}px`),t.style.setProperty(ri.left,`${e.left}px`));}var ii=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height",centerY:"--gem-reserved-tl-center-y",controlHeight:"--gem-reserved-tl-control-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height",centerY:"--gem-reserved-tr-center-y",controlHeight:"--gem-reserved-tr-control-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height",centerY:"--gem-reserved-bl-center-y",controlHeight:"--gem-reserved-bl-control-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height",centerY:"--gem-reserved-br-center-y",controlHeight:"--gem-reserved-br-control-height"}});function Cc(){let t=globalThis,e=t.innerWidth,n=t.innerHeight;return typeof e=="number"&&e>0&&typeof n=="number"&&n>0?{width:e,height:n}:null}function by(t,e){let n={tl:{width:0,height:0,control:null},tr:{width:0,height:0,control:null},bl:{width:0,height:0,control:null},br:{width:0,height:0,control:null}};for(let r of t){let i=e?r.x+r.width/2<=e.width/2:r.x===0,o=e?r.y+r.height/2<=e.height/2:r.y===0,s=i?r.x+r.width:e?e.width-r.x:r.width,a=o?r.y+r.height:e?e.height-r.y:r.height,l=n[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));let d=r.control;if(d){let m=l.control;l.control=m?{top:Math.min(m.top,d.y),bottom:Math.max(m.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Mc(t,e,n){if(t===null)return;let r=by(e,n);for(let i of ["tl","tr","bl","br"]){t.style.setProperty(ii[i].width,`${r[i].width}px`),t.style.setProperty(ii[i].height,`${r[i].height}px`);let o=r[i].control;t.style.setProperty(ii[i].centerY,o?`${(o.top+o.bottom)/2}px`:""),t.style.setProperty(ii[i].controlHeight,o?`${o.bottom-o.top}px`:"");}}var vy=3e4,oi=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Oc(t){let e=t.clock??ue,n=t.timeoutMs??vy,r=new Map,i=new Map,o=0,s=a=>{let l=r.get(a);return l?(r.delete(a),i.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(a){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(a);if(l)return l;let d=new Promise((m,c)=>{let p=`ls${++o}`,g=e.setTimeout(()=>{r.delete(p),i.delete(a),c(new oi("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(p,{room:a,resolve:m,reject:c,timer:g}),t.bridge.requestLocalServer(p,a)||(s(p),m());});return i.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new oi(a.reason,a.retryable,a.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var xn={url:"https://downloads.indiegems.games/sdk/v16.2.0/gem-web-sdk.devtools.min.js",integrity:"sha384-sJtWLi28fYBmXlgnYHjmE6ftrg4nhBc8Jntgqv8tH0FdsrVDYbU/WZVumSGiB8UX"};var Dt=null;function _y(){return Dt!==null||(Dt=new Promise((t,e)=>{let n=document.createElement("script");n.src=xn.url,n.integrity=xn.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Dt=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${xn.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Dt=null,e(new Error(`gem devtools: could not load ${xn.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(n);})),Dt}function Gc(t,e){let n=null,r=0;async function i(o){if(n!==null)return true;let s=++r;if(!e())return false;let a=await _y();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:o,text:rt,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>i("game"),openFrom:i}}var wy=1e4,Lc={reason:"unavailable",retryable:false};function Dc(t){let e=new Map,n=null,r=null,i=0,o=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??wy);},s=(d,m)=>{let c=a(d);c&&m(c);},a=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new _t({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,c)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){c(Lc);return}let g=`t${++i}`,f={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,f),o(g,f),f.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){s(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),o(m,c),t.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])s(m,c=>c.reject(Lc));},get identity(){return n},get gameVersion(){return r}}}var Sy=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),ra="embedder_relay_unavailable",ky="embedder_no_relay",Ry=new Set([ra]),ia=new Set([ky]),Pn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new na(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.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){n.refuse(new w("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(Ay(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new w("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,n);}release(e,n){this.pending.get(e)===n&&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 Ay(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new w(xy(t),r,{platformCode:t})}function xy(t){return t===void 0||Ry.has(t)?"signaling_failed":ia.has(t)?"offer_refused":Sy.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var na=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new w("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return n?.aborted?Promise.reject(new w("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new w("aborted","the caller aborted the signaling exchange"));},a=()=>{n?.removeEventListener("abort",s),this.hub.release(e.matchId,l),this.teardown===a&&(this.teardown=null);},l={settle:d=>{a(),i(d);},refuse:d=>{a(),o(d);}};this.teardown=a,n?.addEventListener("abort",s),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof w?d:new w("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var Fc="match_ended:",$c="server_shutdown:",qc="kicked:",Py=123;function Ty(t){if(typeof t!="string"||t.length===0||t.length>Py)return {kind:"other"};if(t.startsWith(Fc)){let e=Je(t.slice(Fc.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith($c)?{kind:"server_shutdown",cause:t.slice($c.length)}:t.startsWith(qc)?{kind:"kicked",detail:t.slice(qc.length)}:{kind:"other"}}function oa(t,e,n){let r=Ty(n),i=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function aa(){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 Ey=3e3,Iy=1e4,Cy=15e3;async function ai(t){let e=t.peerConnection;try{jc(t,"before the handshake started"),sa(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let s of t.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});t.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await Gy(e,t),sa(t);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new w("invalid_sdp","the offer carried no SDP");ze(i,"offer"),Nc(i,"offer");let o=await Oy(t,i);if(sa(t),typeof o?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return ze(o.sdp,"answer"),Nc(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Ly(n,t),jc(t,"before the channel opened"),n}catch(n){throw e.close(),My(n)}}function My(t){return t instanceof w?t:Wc(t)?ut():new w("connection_failed",Hc(t),{cause:t})}function Nc(t,e){if(Xr(t))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 Oy(t,e){let n=t.exchangeTimeoutMs??Iy,r=Bc(t,n),i=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(o=>{throw o instanceof w?o:Wc(o)?ut():new w("signaling_failed",Hc(o),{cause:o})});return Dy(i,t,r,()=>r.exhausted?la("while the offer was in flight"):new w("timeout",`no answer arrived within ${n}ms`))}function Gy(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let i=()=>{n.clearTimeout(s),t.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{t.iceGatheringState==="complete"&&i();},s=n.setTimeout(i,e.gatherTimeoutMs??Ey);t.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Ly(t,e){if(e.signal?.aborted)return Promise.reject(ut());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new w("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??Cy,i=Bc(e,r);return new Promise((o,s)=>{let a=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{a(),o();},d=g=>{a(),s(new w("connection_failed","the data channel failed before it opened",Uc(g)===void 0?void 0:{cause:Uc(g)}));},m=()=>{a(),s(ut());},c=()=>{a(),s(i.exhausted?la("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(c,i.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Bc(t,e){if(t.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let n=t.credentialExpiresAt-t.clock.now();return n<=e?{ms:Math.max(0,n),exhausted:true}:{ms:e,exhausted:false}}function Dy(t,e,n,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(ut()):new Promise((s,a)=>{let l=c=>{i.clearTimeout(m),o?.removeEventListener("abort",d),c();},d=()=>l(()=>a(ut())),m=i.setTimeout(()=>l(()=>a(r())),n.ms);o?.addEventListener("abort",d),t.then(c=>l(()=>s(c)),c=>l(()=>a(c)));})}function jc(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw la(`already ${e}`)}function la(t){return new w("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function sa(t){if(t.signal?.aborted)throw ut()}function ut(){return new w("aborted","the caller aborted the connection attempt")}function Wc(t){return t?.name==="AbortError"}function Uc(t){return t?.error}function Hc(t){return t instanceof Error?t.message:String(t)}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:[Y("sdp","sdp",V(10240)),K("sessionId","session_id",V(64))],error:[K("code","code",V(64)),K("message","message",V(256))],matchEnded:[K("reason","reason",V(64))]}));function Zc(t){let{client:e,clock:n,rooms:r}=t,i=t.signaling??aa,o=t.log??(h=>console.warn(h)),s=new Ct({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,S)=>{let I=a.get(h)??new Set;I.add(S),a.set(h,I);},d=(h,S)=>{let I=a.get(h);I!==void 0&&(I.delete(S),I.size===0&&a.delete(h));},m=async h=>{if(r.isHost&&!ca(r)&&r.currentRoom?.matchId===void 0){let S=be(h.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},...h.retry===void 0?{}:{retry:h.retry},...h.signal===void 0?{}:{signal:h.signal}});}return Yc(r.matchConnectionState==="suspended"?await r.reconnectToMatch(da(h)):await r.awaitMatch(da(h)))},c=async h=>Yc(await r.pollMatchStatus(da(h))),p=async(h,S)=>{let I=false;try{let T=await m(h),W=r.currentRoom?.transports;if(W!==void 0&&!W.includes("webrtc"))throw new w("misconfigured",`the room template offers (${W.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 q=h.peerConnection??Qc();I=!0;let U=await ai({peerConnection:q,signaling:S,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...si(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),E=null;if(h.presentCredential!==!1)try{E=await dn({channel:U,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...si(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(O){throw Te(U),Te(q),O}return Hy(r,T,U,q,S,h.reportDisconnect!==!1,h.reportConnected!==!1,E,{remember:l,forget:d},h.onMatchEnded)}catch(T){throw I&&Xc(s,T),Te(S),T}},g=async(h,S,I,T,W,q)=>{if(h==="webtransport"){let B=T?.webtransport;if(B===void 0)throw new w("misconfigured","webtransport is not advertised");let J={credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n};if(typeof B.named_url=="string"&&B.named_url!==""){let oe=Math.max(Math.floor(q/2),1e3);try{return await pn({url:B.named_url,timeoutMs:oe,log:o,...J})}catch(ge){if(Ur()!==null)throw ge;return o(`[gem] webtransport named dial failed (${Nr(ge)}); retrying the pinned dial`),pn({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:oe,log:o,...J})}}return pn({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:q,...J})}if(h==="websocket"){let B=T?.websocket;if(B===void 0)throw new w("misconfigured","websocket is not advertised");return Ro({url:B.url,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n,timeoutMs:q})}let U=S.peerConnection??Qc(),E,O=await ai({peerConnection:U,signaling:W,clock:n,matchId:I.matchId,credentialExpiresAt:I.credentialExpiresAt,extraChannels:[{label:un,ordered:false,maxRetransmits:0}],onExtraChannel:(B,J)=>{B===un&&(E=J);},...si(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:qy}:{}}),F;try{F=await dn({channel:O,clock:n,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,wire:qr,heartbeat:!0,...si(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(B){throw Te(O),Te(U),B}let N=F.welcome.heartbeatIntervalMs;return {link:xo(O,U,E,N===void 0?void 0:{clock:n,intervalMs:N}),welcome:F.welcome,channel:O,peerConnection:U}},f=(h,S,I,T,W)=>{let q=false,U;T.link.onClose(N=>{!q&&h.reportDisconnect!==false&&oa(r,S.matchId,N),U?.(N);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let E={transport:T.link.transport,send:(N,B)=>T.link.send(N,B),onMessage:N=>T.link.onMessage(N),onClose:N=>{U=N;},close:()=>T.link.close()},O=()=>{q||(q=true,Te(T.link),Te(W));},F=N=>{if(!q){try{h.onMatchEnded?.(N);}catch{}O();}};return l(S.matchId,F),{matchId:S.matchId,transport:I,link:E,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,F),O();}}},v=async(h,S)=>{let I=r.currentRoom?.id,T=r.gameId,W=()=>({advert:mn(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(I===void 0||T===null)return W();try{let q=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(I)}`,S);return {advert:mn(q.settings,h),template:Et(q.transports)??r.currentRoom?.transports??null}}catch{return W()}},k=(h,S)=>{let I=h??Vc;return S.length===0?I:I.filter(T=>S.includes(T))},x=async(h,S,I)=>{try{let T=await m(h),{advert:W,template:q}=await v(T.matchId,h.signal),U=k(q,S),E=U.filter(X=>Uy(X,W)),O=Ur();if(O!==null&&U.includes("webtransport")&&W?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${O} (learned on an earlier dial in this page)`),E.length===0){let X=q===null?`the default order (${Vc.join(", ")})`:`the room template's transports (${q.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 F=h.transportAttemptTimeoutMs??$y,N=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-n.now(),B=X=>t.signalingReady===void 0||X<=0?Promise.resolve(!0):t.signalingReady(X),J=[],oe=[];for(let X of E){if(N()<Jc){o(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}oe.length>0&&T.credentialExpiresAt-n.now()<zc&&(T=await c(h)),oe.push(X);let Ne=!1,ke=!1,fe={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&h.redial===!0){let te=Math.min(Kc,N());await B(te)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let je=Math.max(Math.min(F,N()),Jc);try{return f(h,T,X,await g(X,h,T,W,I,je),I)}catch(te){let z=te instanceof w?te:new w("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(X==="webrtc"&&Xc(s,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Ne){Ne=!0,T=await c(h);continue}if(X==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===ra&&!ke){ke=!0;let le=Math.min(Kc,N());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(le)}ms for the socket before offering again`),await B(le))continue}if(z.reason==="join_rate_limited"){let le=jy(fe,Math.random,N());if(le!==null){if(fe.attempts+=1,fe.waitedMs+=le,o(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(le)}ms before presenting again (retry ${fe.attempts} of ${tu.maxAttempts})`),await Lr(n,le,h.signal),h.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<zc&&(T=await c(h));continue}}if(Ny.has(z.reason)||z.reason==="credential_expired"||X==="webrtc"&&eu(z)){o(`[gem] ${X} rung failed (${z.reason}): ${Nr(z.cause??z)} \u2014 `+(oe.length<E.length?`falling through to ${E[oe.length]}`:"no rungs left")),J.push(z);break}throw o(`[gem] ${X} rung refused the session (${z.reason}): ${z.message}`),z}}}let ge=J[J.length-1];throw ge===void 0?new w("timeout",`the reconnect budget ran out before any transport (${E.join(", ")}) could be tried`):new w(ge.reason,`every transport tried (${oe.join(", ")}) failed; the last said: ${ge.message}`,{cause:J,platformCode:ge.platformCode})}catch(T){throw Te(I),T}};return {listClusterTargets:async(h={})=>lo({client:e,...h}),handleMatchEnded(h,S){let I=a.get(h);if(I!==void 0){a.delete(h);for(let T of I)T(S);}},connect:(async(h={})=>{let S=h.signaling??i();return h.transports===void 0?p(h,S):x(h,h.transports,S)})}}var Vc=["webtransport","webrtc","websocket"],$y=1e4,qy=5e3,Kc=3e3,Jc=1e3,zc=1e4,Ny=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function eu(t){return t.platformCode!==void 0&&ia.has(t.platformCode)}var tu={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function jy(t,e=Math.random,n=1/0){let r=tu;if(t.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-t.waitedMs,n);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**t.attempts;return Math.min(o+e()*r.jitterMs,i)}function Uy(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&jr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||By(e.websocket.url)}function By(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return He(e)}function da(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var Wy=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Xc(t,e){e instanceof w&&(!Wy.has(e.reason)&&!eu(e)||t.report([{type:"connection_failures_total",value:1}]));}function Hy(t,e,n,r,i,o,s,a,l,d){let m=false,c=()=>{m||oa(t,e.matchId,void 0);};o&&(n.addEventListener("close",c),s&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",c),a?.detach(),Te(n),Te(r),Te(i));},g=f=>{if(!m){try{d?.(f);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function ca(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Yc(t){if(t.status==="failed")throw new w("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new w("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Gr)throw new w("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Gr}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:n}=t;if(e===void 0||n===void 0)throw new w("connection_failed",`match ${t.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...t,joinCredential:e,credentialExpiresAt:n}}function Qc(){let t=globalThis.RTCPeerConnection;if(!t)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 t({iceServers:[]})}function Te(t){try{t.close();}catch{}}function si(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var Vy=1e4;function nu(t,e){return ua(t,e)}function ua(t,e){if(typeof t.serverToken!="function"||typeof t.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 n=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new _t({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((s,a)=>{let l=e.clock.setTimeout(()=>{r=null,a({reason:"unavailable",retryable:true});},e.timeoutMs??Vy);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),o=t.onServerToken(s=>{let a=n(s),l=r;if(l){r=null,l.resolve(a);return}i.accept(a);});return {source:i,dispose(){o(),i.dispose(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var pa={};xm(pa,{acceptTransfer:()=>Ky,addEntityProgression:()=>Jy,adminAction:()=>zy,cancelInventoryTransfer:()=>Xy,claimEntityProgressionRewards:()=>Yy,closeGameRoom:()=>Qy,createEntityBatchOrder:()=>Zy,createEntityOrder:()=>eh,createSession:()=>th,deleteEntityGameSetting:()=>nh,deleteEntitySave:()=>rh,deleteSession:()=>ih,deleteShowcaseValue:()=>oh,executeEntityRecipe:()=>ah,finalizeSaveUpload:()=>sh,getChannelAssignment:()=>lh,getDropRates:()=>dh,getEntityCurrency:()=>ch,getEntityGameSetting:()=>uh,getEntityInventory:()=>mh,getEntityInventoryItem:()=>ph,getEntityLeaderboard:()=>gh,getEntityOrder:()=>fh,getEntityProgression:()=>yh,getEntityRecipeAvailability:()=>hh,getEntityRecipeUsage:()=>bh,getEntitySave:()=>vh,getEvent:()=>_h,getGameRoomV2:()=>wh,getLeaderboard:()=>Sh,getPlayerGameProfile:()=>kh,getPurchaseCatalog:()=>Rh,getResolvedTemplate:()=>Ah,getRoomArgs:()=>xh,getShowcaseValue:()=>Ph,getTransferDetails:()=>Th,ingestAnalyticsEvents:()=>ma,initiateInventoryTransfer:()=>Eh,invokeFunction:()=>Ih,kickPlayer:()=>Ch,listChallenges:()=>Mh,listEntityGameSettings:()=>Oh,listEntityOrders:()=>Gh,listEntityProgressions:()=>Lh,listEntitySaves:()=>Dh,listEvents:()=>Fh,listGameRooms:()=>$h,listResolvedTemplates:()=>qh,listTransfers:()=>Nh,maxEntityProgression:()=>jh,putEntityGameSetting:()=>Uh,putRoomArgs:()=>Bh,putShowcaseValue:()=>Wh,rejectTransfer:()=>Hh,reportMatchPlayers:()=>Vh,requestSaveUploadUrl:()=>Kh,resetEntityProgression:()=>Jh,setMatchBackfill:()=>zh,simulateEntityOrder:()=>Xh,transferHostV2:()=>Yh,updateGameRoomV2:()=>Qh});function b(t){let e=String(t);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 Ky(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Jy(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/add`;return t.client.post(s,i,o?.signal)}async function zy(t,e,n,r){let i=`/v1/voice/sessions/${b(e)}/admin`;return t.client.post(i,n,r?.signal)}async function Xy(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Yy(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/claim`;return t.client.post(s,i,o?.signal)}async function Qy(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.delete(r,n?.signal)}async function Zy(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function eh(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function th(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function nh(t,e,n,r,i){let o=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(o,i?.signal)}async function rh(t,e,n,r,i){let o=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(o,i?.signal)}async function ih(t,e,n){let r=`/v1/voice/sessions/${b(e)}`;return t.client.delete(r,n?.signal)}async function oh(t,e,n,r){let i=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.delete(i,r?.signal)}async function ah(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function sh(t,e,n,r,i,o){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function lh(t,e,n){let r=`/v1/games/${b(t.gameId())}/config/channels/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function dh(t,e,n){let r=`/v1/inventory/loot-tables/${b(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function ch(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/currencies/${b(r)}`;return t.client.get(o,i?.signal)}async function uh(t,e,n,r,i){let o=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function mh(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${b(e)}/${b(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function ph(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/items/${b(r)}`;return t.client.get(o,i?.signal)}async function gh(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${b(e)}/${b(n)}/${b(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function fh(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders/${b(r)}`;return t.client.get(o,i?.signal)}async function yh(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}`;return t.client.get(o,i?.signal)}async function hh(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/catalogs/${b(r)}/recipes/${b(i)}/availability`;return t.client.get(s,o?.signal)}async function bh(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${b(e)}/${b(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function vh(t,e,n,r,i){let o=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function _h(t,e,n){let r=`/v1/events/${b(e)}`;return t.client.get(r,n?.signal)}async function wh(t,e,n){let r=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Sh(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${b(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function kh(t,e,n){let r=`/v1/profiles/players/${b(e)}`;return t.client.get(r,n?.signal)}async function Rh(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ah(t,e,n){let r=`/v1/game-room-templates/${b(e)}`;return t.client.get(r,n?.signal)}async function xh(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.get(r,n?.signal)}async function Ph(t,e,n,r){let i=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.get(i,r?.signal)}async function Th(t,e,n){let r=`/v1/inventory/transfers/${b(e)}`;return t.client.get(r,n?.signal)}async function ma(t,e,n){let r=`/v1/games/${b(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function Eh(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Ih(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Ch(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/kick/${b(n)}`;return t.client.post(i,void 0,r?.signal)}async function Mh(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Oh(t,e,n,r){let i=`/v1/settings/${b(e)}/${b(n)}`;return t.client.get(i,r?.signal)}async function Gh(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${b(e)}/${b(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Lh(t,e,n,r){let i=`/v1/inventory/${b(e)}/${b(n)}/progressions`;return t.client.get(i,r?.signal)}async function Dh(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${b(e)}/${b(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Fh(t,e){let n=new URLSearchParams;e?.include_inactive!==void 0&&n.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.offset!==void 0&&n.set("offset",String(e?.offset));let r=n.toString(),i="/v1/events"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function $h(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i=`/v1/games/${b(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function qh(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function Nh(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function jh(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/max`;return t.client.post(s,i,o?.signal)}async function Uh(t,e,n,r,i,o){let s=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Bh(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.put(i,n,r?.signal)}async function Wh(t,e,n,r,i){let o=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.put(o,r,i?.signal)}async function Hh(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Vh(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/matches/${b(e)}/players/report`;return t.client.post(i,n,r?.signal)}async function Kh(t,e,n,r,i,o){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function Jh(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/reset`;return t.client.post(s,i,o?.signal)}async function zh(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/matches/${b(e)}/backfill`;return t.client.put(i,n,r?.signal)}async function Xh(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders/simulate`;return t.client.post(o,r,i?.signal)}async function Yh(t,e,n,r){let i=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}/transfer/${b(n)}`;return t.client.post(i,void 0,r?.signal)}async function Qh(t,e,n,r){let i=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.patch(i,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Zh=1e4,eb=50,tb=1e3,nb=65536-4*1024,ru=t=>typeof t=="number"?t:0,rb=t=>typeof t=="string"?t:"";function iu(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function ib(t){return t?.retryable===true}function ob(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:ru(o.index),code:rb(o.code)}}):[];return {accepted:ru(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function ou(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,player_id:t.playerId,dimensions:t.dimensions,measures:t.measures}}function au(t){let e=Math.max(1,Math.floor(t.maxQueue??tb)),n={client:t.client,gameId:()=>t.gameId},r=[],i=0,o=null,s=false,a=null,l=0,d=0,m=false,c=false,p=h=>{t.log?.(h);},g=()=>{o!==null&&(t.clock.clearTimeout(o),o=null);},f=()=>Math.max(0,d-t.clock.now()),v=()=>{o!==null||s||a!==null||(o=t.clock.setTimeout(()=>{o=null,x().catch(()=>{});},Math.max(Zh,f())));},k=()=>{let h=Math.min(r.length,100),S=128;for(let I=0;I<h;I+=1){let T=r[I];if(T===void 0)break;if(S+=JSON.stringify(ou(T,0)).length+1,S>nb)return Math.max(1,I)}return h};async function x(h){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let S=P(h);a=S;try{return await S}finally{a===S&&(a=null),r.length>0&&v();}}async function P(h){g();let S=r.splice(0,k()),I=i;i=0;let T=Math.round(t.clock.now()),W={batch_id:iu(),sent_at_ms:T,events:S.map(q=>ou(q,T))};try{let q=await ma(n,W,h===void 0?void 0:{signal:h}),U=ob(q,I);l=0,d=0;for(let E of U.rejected)p(`[gem] analytics: an event was refused (${E.code}). See the analytics_events section of your game config.`);return U}catch(q){if(ib(q)){for(r=[...S,...r],i+=I;r.length>e;)r.shift(),i+=1;l+=1,d=t.clock.now()+Cr(l,q);}else p(`[gem] analytics: ${S.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(q)}`);throw q}}return {track(h,S,I={}){if(s)return;if(typeof h!="string"||h===""){c||(c=true,p(`[gem] analytics: '${S}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(S.startsWith(Qi)){m||(m=true,p(`[gem] analytics: '${S}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let T={},W={};for(let[q,U]of Object.entries(I))typeof U=="string"?T[q]=U:typeof U=="number"&&Number.isFinite(U)&&(W[q]=U);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:iu(),playerId:h,name:S,atMs:t.clock.now(),dimensions:T,measures:W}),r.length>=eb&&a===null&&f()===0?x().catch(()=>{}):v();},flush:h=>x(h),get pending(){return r.length},dispose(){s=true,g(),r=[],i=0;}}}function su(t){return {async list(e){let{playerId:n,periodsBack:r,signal:i}=e??{};if(typeof n!="string"||n==="")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().");xt(r);let o=await t({player_id:n,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return Rr(o)}}}function ab(t){let e={};for(let[n,r]of Object.entries(pa))if(typeof r=="function"){let i=r;e[n]=(...o)=>i(t,...o);}return e}function Ft(t,e={}){let n=e.clock??ue,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let i=ua(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=mr({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new We({transport:o,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=ab({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,m=t.endMatch,c=t.log,p=au({client:s,clock:n,gameId:a.gameId,...typeof c=="function"?{log:f=>c.call(t,f)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);},setBackfill:async(f,v)=>{let k=await l.setMatchBackfill(a.matchId,{open:f.open,...f.seats===void 0?{}:{seats:f.seats}},v===void 0?{}:{signal:v});return {open:k.open,seats:k.seats??null}},reportPlayers:async(f,v)=>(await l.reportMatchPlayers(a.matchId,{players:f.map(x=>({player_id:x.playerId,state:x.state}))},v===void 0?{}:{signal:v})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new Ke(l.invokeFunction),challenges:su(l.listChallenges),...d===void 0?{}:{room:{get:f=>l.getGameRoomV2(d,f),args:async f=>{let v=await l.getGameRoomV2(d,f?.signal===void 0?{}:{signal:f.signal}),k=v.modified?v.body:void 0;if(k?.room_args==null||k.room_args_template==null)throw new M("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(),i.dispose();}}}function mt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function $t(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function Tn(t){return typeof t=="string"?t:t.slice().buffer}function li(t){if(typeof t=="string")return {data:t,isText:true};if(t instanceof ArrayBuffer)return {data:new Uint8Array(t),isText:false};if(ArrayBuffer.isView(t)){let e=t;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var sb=5e3,lu=3e4,du=2e3,lb=1e4,db=3,cu=1;async function uu(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let i=e.log===void 0?y=>console.info(y):e.log,o=y=>i?.(`[gem host] ${y}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,m=(y,C)=>{l&&(a=a.then(async()=>{if(!d)try{await C();}catch(L){o(`the bundle's ${y} handler threw: ${pt(L)}. Serving continues.`);}}));},c=true,p,g,f,v=y=>{if(!c)return;c=false,m("leave",()=>s.leave?.(r,{cause:y??"left"}));let C=g;C&&queueMicrotask(()=>C(y));},k={send(y,C){if(!c)return;let L=$t(mt(C));m("message",()=>s.message?.(r,y,typeof y=="string",{reliable:L.reliable,ordered:L.ordered}));},onMessage(y){p=y;},onClose(y){g=y;},close(){v("closed");}},x=(y,C)=>{if(!c)return;let L=$t(mt(C));queueMicrotask(()=>{c&&p?.(y,L);});},P=new Map,h=y=>{let C=[];for(let L of qe){let Z=y.channels[L];try{Z.binaryType="arraybuffer";}catch{}let we=$t(L),Fn=ht=>{let jt=li(ht?.data);jt!==null&&m("message",()=>s.message?.(y.playerId,jt.data,jt.isText,{reliable:we.reliable,ordered:we.ordered}));};Z.addEventListener("message",Fn),C.push(()=>Z.removeEventListener("message",Fn));}P.get(y.playerId)?.forEach(L=>L()),P.set(y.playerId,C);},S=y=>{P.get(y)?.forEach(C=>C()),P.delete(y);},I=new Set,T=new Map,W=(y,C,L)=>({playerNumber:y.assignedPeerId,transport:"webrtc_p2p",...C?{rejoin:true}:{},...L?{superseded:true}:{}}),q=y=>{let C=P.has(y.playerId),L=I.has(y.playerId);I.add(y.playerId),h(y),C&&m("leave",()=>s.leave?.(y.playerId,{cause:"superseded"})),m("join",()=>s.join?.(y.playerId,W(y,L,C)));},U=new Set,E=(y,C,L)=>{if(y===r){x(C,L);return}let Z=n.peer(y);if(Z===null){let we=T.get(y);if(we!==void 0&&e.clock.now()-we<du)return;U.has(y)||(U.add(y),o(`send to '${y}' dropped: no such connected player`));return}Z.send(Tn(C),mt(L));},O={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:y=>e.tokens.subscribe(y),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(y=>y.playerId)??[],players(){let y=c?[r]:[];for(let C of n.peers)y.push(C.playerId);return y},profile(y){let C=e.room()?.members.find(L=>L.playerId===y);if(!(!C||C.displayName===void 0))return {displayName:rt.toPlain(C.displayName),...C.displayTag===void 0?{}:{displayTag:rt.toPlain(C.displayTag)},...C.discriminator===void 0?{}:{discriminator:C.discriminator}}},playerNumber(y){return y===r?cu:n.peer(y)?.assignedPeerId},send(y,C,L){E(y,C,L);},broadcast(y,C){let L=C?.except;c&&r!==L&&x(y,C);for(let Z of n.peers)Z.playerId!==L&&Z.send(Tn(y),mt(C));},async endMatch(){let y=await je();return y.answer!=="ok"&&o(y.cause),y.answer},kick(y,C){if(y===r){v(C??"kicked");return}n.kick(y).catch(L=>{o(`kick of '${y}' failed: ${pt(L)}`);});},log(y){o(y);},warn(y){o(`\u26A0 ${y}`);}},F=()=>{},N=new Promise(y=>{F=y;}),B=[],J=null,oe=async(y,C)=>{l=false;let L=a.then(async()=>{try{await s.shutdown(y);}catch(Z){o(`the bundle's shutdown threw: ${pt(Z)}`);}});a=L,await L,De();for(let Z of B.splice(0))Z();for(let Z of [...P.keys()])S(Z);v(C);},ge=(y,C)=>J||(J=(async()=>{await oe(C,y),n.close(),F();})(),J),X=()=>J||(J=(async()=>{await oe({reason:"signal"},"left"),await n.leave().catch(y=>o(`leaving the match failed: ${pt(y)}`)),F();})(),J),Ne=()=>J||(J=(async()=>{l=false;let y=await je();y.answer==="ok"?(await oe({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(o(`${y.cause}; leaving instead`),await oe({reason:"signal"},"left"),await n.leave().catch(C=>o(`leaving the match failed: ${pt(C)}`))),F();})(),J),ke=null,fe=()=>(ke??=Ft(O,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),ke),je=async()=>{try{return await ol({client:fe().client,gameId:()=>O.gameId},O.matchId,{},{signal:AbortSignal.timeout(sb)}),{answer:"ok"}}catch(y){return y instanceof M&&(y.reason==="forbidden"||y.reason==="not_found")?{answer:y.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${y.reason})`}:{answer:"failed",cause:`ending the match failed: ${pt(y)}`}}},te=null,z=false,le=0,xe,Ue=null,De=()=>{z=true,te!==null&&(e.clock.clearTimeout(te),te=null),Ue?.(),Ue=null;},ft=y=>{o(`heartbeats paused: ${y}; they resume when a fresh play token arrives`),Ee();let C=xe,L=false,Z=e.tokens.subscribe(we=>{L||z||we.token===C||Nt(we)||(L=true,Ue?.(),Ue=null,le=0,xe=void 0,Ee(),o("a fresh play token arrived; heartbeats resume"),te=e.clock.setTimeout(()=>{Be();},0));});L?Z():Ue=Z;},Ee=()=>{let y=ke;ke=null,y?.dispose();},Nt=y=>y.expiresAt*1e3<=e.clock.now(),Be=async()=>{if(te=null,!z){try{await fe().client.post(`/v1/games/${encodeURIComponent(O.gameId)}/matches/${encodeURIComponent(O.matchId)}/heartbeat`,void 0,AbortSignal.timeout(lb)),le=0,xe=void 0;}catch(y){if(y instanceof M&&(y.reason==="forbidden"||y.reason==="not_found")){o(`the platform no longer holds this match under this host (${y.reason}); heartbeats stop`),De();return}if(cb(y)){if(z)return;le+=1;let C=e.tokens.current(),L=C===void 0?"this host holds no play token":Nt(C)?"this host's play token has expired":C.token===xe?"the platform refused this host's play token again":le>=db?`the platform refused this host's play token ${le} times in a row`:null;if(xe=C?.token,L!==null){ft(L);return}}else le=0,xe=void 0;o(`heartbeat failed: ${pt(y)}`);}z||(te=e.clock.setTimeout(()=>{Be();},lu));}},yi=()=>{z||te!==null||(te=e.clock.setTimeout(()=>{Be();},lu));};{let y=F;F=()=>{De(),ke?.dispose(),ke=null,y();};}let yt=Promise.resolve().then(()=>s.init(O));a=yt.then(()=>{},()=>{}),m("join",()=>s.join?.(r,{playerNumber:cu,transport:"loopback"})),B.push(n.on("peerJoined",q)),B.push(n.on("peerLeft",(y,C)=>{S(y);let L=e.clock.now();for(let[Z,we]of T)L-we>=du&&T.delete(Z);T.set(y,L),U.delete(y),m("leave",()=>s.leave?.(y,{cause:C}));})),B.push(n.on("error",y=>{o(`\u26A0 session error: ${y.message}`);})),B.push(n.on("matchEnded",y=>{J||ga(f,y),ge("match ended",{reason:"match_ended",platform_reason:y});})),B.push(n.on("hostChanged",y=>{y!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let y of n.peers)q(y);try{await yt,yi();}catch(y){l=false,De(),d=true;for(let C of B.splice(0))C();for(let C of [...P.keys()])S(C);throw n.leave().catch(()=>{}),F(),y}return {matchId:n.matchId,localLink:k,onMatchEnded(y){f=y;},end:Ne,leave:X,stop:y=>ge(y,{reason:"stopped"}),done:N}}function ga(t,e){try{t?.(e);}catch{}}function cb(t){return t instanceof M&&t.status===401||ne.isAuthError(t)}function pt(t){return t instanceof Error?t.message:String(t)}function fa(t,e){let n=async()=>{throw new w("misconfigured",`this seat is \`${t}\`, not the match's authority: `+(t==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:t,matchId:e,end:n,leave:n,stop:async()=>{}}}function mu(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,i=new Map,o=async a=>{r.isHost&&!ca(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...a.signal===void 0?{}:{signal:a.signal}});let l={...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},s=a=>({...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0?{}:{clusterTargetId:a.clusterTargetId}});return {async serve(a,l={}){let d=await o(l);if(d.protocol!==ct)return fa("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return fa("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(s(l)),g=await uu(a,{session:p,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return i.set(d.matchId,g),g.done.then(()=>{i.get(d.matchId)===g&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(a={}){let l=await o(a),d=a.onMatchEnded;if(l.protocol===ct){let g=i.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),gb(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 f=await _n(),v=async()=>t.p2p.connect({...s(a),certificate:f}),k=await v(),x=yb(k,v,d,P=>{r.notifyMatchDisconnected(P).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(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 t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),c=await m(),p=fb(c,m,r,n);return n&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var pu="link_closed",ub="host_unreachable",mb=new Set(["failed","closed"]);function pb(t){return mb.has(t)?pu:ub}function gb(t,e,n){let r=e.localLink;e.onMatchEnded(n);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:t,protocol:"loopback",get state(){return i},send:(s,a)=>r.send(s,a),onMessage:s=>r.onMessage(s),onClose:s=>{o=s,r.onClose(a=>{i="closed",o?.(a);});},close:()=>r.close()}}function fb(t,e,n,r){let i=t.matchId,o=t,s="connected",a,l,d=[],m=false,c=false,p=f=>{if(s!=="closed"){s="closed";for(let v of d.splice(0))v();l?.(f);}},g=f=>{f.link.onMessage((v,k)=>a?.(v,k)),f.link.onClose(v=>{if(f!==o||s==="closed")return;if(m||!r){p(v);return}let k=n.matchSession;if(k.phase==="suspended"&&k.matchId===i){s="suspended";return}p(v);});};return g(t),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return s},send(f,v){s==="connected"&&o.link.send(f,v);},onMessage(f){a=f;},onClose(f){l=f;},close(){if(s!=="closed"){if(m=true,s==="suspended"){p("closed");return}o.close(),p("closed");}},async redial(f){if(s==="closed"||m)return "closed";if(c)return "connected";c=true;let v;try{v=await e(f===void 0?{}:{deadlineAt:f});}finally{c=false;}return m||s==="closed"?(v.close(),"closed"):(o=v,g(v),s="connected",n.notifyMatchConnected(i),"connected")},abandon(f){s!=="closed"&&(s==="connected"&&o.close(),p(f));},onClosed(f){s==="closed"?f():d.push(f);}}}function yb(t,e,n,r,i,o=false){let s=t.matchId,a=t,l,d,m=[],c=[],p=[],g=false,f=false,v=false,k=false,x="connected",P=E=>{if(g)return;g=true,x="closed";for(let F of m.splice(0))F();for(let F of c.splice(0))F();for(let F of p.splice(0))F();let O=d;O&&queueMicrotask(()=>O(E));},h=E=>{for(let O of m.splice(0))O();for(let O of qe){let F=E.channels[O];try{F.binaryType="arraybuffer";}catch{}let N=$t(O),B=J=>{let oe=li(J?.data);oe!==null&&l?.(oe.data,N);};F.addEventListener("message",B),m.push(()=>F.removeEventListener("message",B));}},S=()=>a.peer(a.hostPlayerId),I=E=>{if(!(g||a.isHost)&&x!=="suspended"){if(r?.(E),o){x="suspended";return}P(E);}},T=E=>{for(let O of qe){let F=E.channels[O];if(typeof F.addEventListener!="function")continue;let N=()=>{S()===E&&I(pu);};F.addEventListener("close",N),m.push(()=>F.removeEventListener?.("close",N));}},W=E=>{h(E),T(E),!g&&(x="connected",i?.());},q=E=>{for(let O of c.splice(0))O();c.push(E.on("migrating",()=>{k=true;})),c.push(E.on("hostChanged",O=>{if(k=false,O===E.playerId){P("host_migrated_here");return}let F=S();F!==null&&W(F);})),c.push(E.on("peerJoined",O=>{O.playerId===E.hostPlayerId&&W(O);})),c.push(E.on("matchEnded",O=>{g||ga(n,O),P(O);})),c.push(E.on("peerLeft",(O,F)=>{O===E.hostPlayerId&&I(pb(F));}));};q(a);let U=S();return U!==null&&W(U),{matchId:s,protocol:"p2p",get state(){return x},send(E,O){x==="connected"&&S()?.send(Tn(E),mt(O));},onMessage(E){l=E;},onClose(E){d=E;},close(){f=true,P("closed"),a.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||v)return "connected";if(k)throw new D("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");v=true;let E;try{for(let F of m.splice(0))F();for(let F of c.splice(0))F();a.close(),E=await e();}finally{v=false;}if(g)return f?E.leave().catch(()=>{}):E.close(),"closed";a=E,q(a);let O=S();if(O===null)throw a.close(),new D("connection_failed","this peer rejoined the match but the host never answered with a link");return W(O),"connected"},abandon(E){P(E);},onClosed(E){g?E():p.push(E);}}}function gu(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},s=l=>{n.delete(r)&&(t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>s(void 0),t.timeoutMs??2e3);let a=false;try{a=t.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){n.get(r)?.(i);}}}var hb=12e4;function gt(t,e){return {outcome:t,reason:e}}function fu(t){let e=false,n=new Map,r=(i,o,s,a)=>{if(!t.bridge.parentSupports(i))return Promise.resolve(gt("unavailable","error"));if(e)return Promise.resolve(gt("declined","busy"));let l=`purchase-${_e()}`;return new Promise(d=>{let m={},c=g=>{n.delete(l)&&(e=false,t.clock.clearTimeout(m.timer),d(g));};e=true,n.set(l,{finish:c,check:s,label:a}),m.timer=t.clock.setTimeout(()=>c(gt("unavailable","error")),t.timeoutMs??hb);let p=false;try{p=o(l);}catch{}p||c(gt("unavailable","error"));})};return {api:{request(i){return r("purchases",o=>t.bridge.requestPurchase(o,i.kind,i.targetId,i.currencySlug,i.quantity,i.catalogId),o=>o===void 0?null:t.confirm(o),o=>`purchase ${JSON.stringify(o)}`)}},requestAvatar3d(i){return r("avatar3dPurchases",o=>t.bridge.requestAvatar3dPurchase(o,i.itemId,i.currencySlug),()=>t.confirmAvatar3d(i.itemId),()=>`3D avatar ${JSON.stringify(i.itemId)}`)},settle(i){let o=i.outcome==="ok"||i.outcome==="declined"?i.outcome:"unavailable",s=n.get(i.requestId);if(s===void 0){t.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(i.requestId));return}let{finish:a}=s;if(o!=="ok"){a(gt(o,kl(i.reason)));return}let l=i.purchaseId,d;try{d=s.check(l);}catch{d=Promise.resolve("unknown");}if(d===null){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),a(gt("unavailable","error"));return}(async()=>{let m;try{m=await d;}catch{m="unknown";}if(m==="granted"){a(l===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:l});return}m==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(gt("unavailable","error"));})();}}}async function yu(t,e){try{return (await js(t,e)).granted?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}var bb="small_human",hu=/^[a-z][a-z0-9_]{0,31}$/,bu=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,vb=8;function ya(t){if(t===null)return [];if(t.avatars3d!==void 0)return t.avatars3d;let{avatar3dId:e,avatar3dModelUrl:n,avatar3dIconUrl:r}=t;return e===void 0||n===void 0||r===void 0?[]:[{family:bb,id:e,modelUrl:n,iconUrl:r}]}function _b(t,e){return t.length===e.length&&t.every((n,r)=>{let i=e[r];return n.family===i.family&&n.id===i.id&&n.modelUrl===i.modelUrl})}function wb(t){let e=t??{},n=typeof e.item_id=="string"&&bu.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&hu.test(e.family)?e.family:void 0,i=typeof e.slug=="string"&&e.slug!==""?e.slug:void 0,o=typeof e.display_name=="string"&&e.display_name!==""?e.display_name:void 0,s=typeof e.description=="string"&&e.description!==""?e.description:void 0,a=Ar(e.icon_url),l=Ar(e.model_url),d=[];for(let m of Array.isArray(e.prices)?e.prices:[]){let c=m??{};typeof c.currency_slug=="string"&&c.currency_slug!==""&&typeof c.price=="number"&&Number.isSafeInteger(c.price)&&c.price>0&&d.push({currencySlug:c.currency_slug,price:c.price});}if(!(n===void 0||r===void 0||i===void 0||o===void 0||a===void 0||l===void 0||d.length===0))return {itemId:n,slug:i,family:r,displayName:o,...s===void 0?{}:{description:s},iconUrl:a,modelUrl:l,prices:d}}function Sb(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&hu.test(n)&&!e.includes(n)&&e.push(n),e.length===vb)break;return e}function vu(t){let e=new Set,n=ya(t.player()),r=i=>{t.log?.(`[gem] an avatars3d onChange listener threw: ${i instanceof Error?i.message:String(i)}`);};return t.subscribe(i=>{let o=ya(i);if(!_b(n,o)){n=o;for(let s of [...e])try{s(o);}catch(a){r(a);}}}),{async families(){return Sb(await t.configFamilies())},worn(i){let o=ya(t.player());if(i!==void 0)return o.find(l=>l.family===i);let a=t.player()?.avatar3dId;return (a===void 0?void 0:o.find(l=>l.id===a))??o[0]},async offers(){let i=await t.readOffers(),o=[];for(let s of Array.isArray(i?.offers)?i.offers:[]){let a=wb(s);a!==void 0&&o.push(a);}return o},purchase(i){let o=i?.itemId,s=i?.currencySlug;return typeof o!="string"||!bu.test(o)?Promise.resolve({outcome:"declined",reason:"not_purchasable"}):typeof s!="string"||s===""?Promise.resolve({outcome:"declined",reason:"unknown_currency"}):t.purchase({itemId:o,currencySlug:s})},onChange(i){return e.add(i),()=>{e.delete(i);}}}}async function _u(t,e){try{return (await ws(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}function wu(t){return Ls(t)}var kb=6e5;function Su(t){let e=null,n=new Map;return {api:{requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${_e()}`;return e=new Promise(i=>{let o={},s=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>{s({outcome:"unavailable"});},t.timeoutMs??kb);let a=false;try{a=t.bridge.requestSignIn(r);}catch{}a||s({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var Rb=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),Ab=["utm_"];function ku(t){return Rb.has(t)||Ab.some(e=>t.startsWith(e))}var Ru=16,Au=512,xb=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Pb=/[\p{Cc}\p{Cf}]/u,Tb=/\p{Cs}/u,Ge="[gem] gem.share.request:";function xu(t){let{frame:e,log:n}=t,r=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,o=s=>{n!==null&&(n===void 0?console.warn(s):n(s));};return {get available(){return i()!==null},request(s){let a=i();if(a===null)throw new Error(`${Ge} the arcade does not handle share here \u2014 check gem.share.available first`);if(s!==void 0&&(typeof s!="object"||s===null))throw new TypeError(`${Ge} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!Eb(l))throw new TypeError(`${Ge} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>Ru)throw new TypeError(`${Ge} at most ${Ru} params; got ${d.length}`);let m=[];for(let[c,p]of d){let g=JSON.stringify(c);if(!xb.test(c))throw new TypeError(`${Ge} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(ku(c))throw new TypeError(`${Ge} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Ge} param ${g}: values must be strings`);if(p.length>Au)throw new TypeError(`${Ge} param ${g}: a value is at most ${Au} characters`);if(Pb.test(p))throw new TypeError(`${Ge} param ${g}: control and format characters are not allowed`);if(Tb.test(p))throw new TypeError(`${Ge} param ${g}: a value must be well-formed text`);m.push({key:c,value:p});}!a.requestShare(m)&&!r&&(r=true,o("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function Eb(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var En=3e4,ha=12e4;function In(t,e,n){return t.held?Promise.resolve(n):(t.held=true,e().then(r=>(t.held=false,r)))}function ce(t,e,n){return {outcome:t,reason:e,...n}}function Ye(t){let e=t.outcome==="ok"||t.outcome==="declined"?t.outcome:"unavailable";return typeof t.reason=="string"?{outcome:e,reason:t.reason}:{outcome:e}}function Pu(t){let e=new Map;return {ask(n,r,i,o){let s=`arcade-${_e()}`;return new Promise(a=>{let l={},d=c=>{e.delete(s)&&("timer"in l&&t.clearTimeout(l.timer),a(i(c)));};e.set(s,{expect:n,finish:d}),o!==void 0&&(l.timer=t.setTimeout(()=>d(null),o));let m=false;try{m=r(s);}catch{}m||d(null);})},settle(n){let r=e.get(n.requestId);return r===void 0||r.expect!==n.type?false:(r.finish(n),true)},abandon(){for(let n of [...e.values()])n.finish(null);}}}var Ib=12,Cb=24,ba=Object.freeze({games:Object.freeze([])});function Mb(t){let e=(n,r)=>he(n,`GameCard.${r}`);return Object.freeze({gameId:t.gameId,...t.slug===void 0?{}:{slug:t.slug},name:e(t.untrusted.name,"name"),tagline:e(t.untrusted.tagline,"tagline"),shortDescription:e(t.untrusted.shortDescription,"shortDescription"),tags:Object.freeze(t.untrusted.tags.map(n=>e(n,"tags"))),iconUrl:t.iconUrl,capsuleLandscapeUrl:t.capsuleLandscapeUrl,capsulePortraitUrl:t.capsulePortraitUrl,...t.previewVideoUrl===void 0?{}:{previewVideoUrl:t.previewVideoUrl},...t.previewPosterUrl===void 0?{}:{previewPosterUrl:t.previewPosterUrl}})}function di(t){return ce("unavailable","error",t)}function Tu(t){let{bridge:e,asker:n,acting:r}=t,i=a=>e.currentState==="connected"&&e.parentSupports(a),o=new Map,s=(a,l)=>{let d=o.get(a);if(d!==void 0)return d;let m=l().then(c=>(o.delete(a),c));return o.set(a,m),m};return {get available(){return {appLinks:i("appLinks"),openGame:i("openGame")}},appLinks(){return e.parentSupports("appLinks")?s("appLinks",()=>n.ask("gem.appLinksResult",a=>e.requestArcade({type:"gem.requestAppLinks",requestId:a}),a=>{if(a===null)return di({});let l=a;return {...Ye(a),...l.arcade===void 0?{}:{arcade:{store:l.arcade.store}},...l.game===void 0?{}:{game:{store:l.game.store}}}},En)):Promise.resolve(ce("unavailable","unsupported",{}))},openApp(a){return e.parentSupports("appLinks")?a!=="arcade"&&a!=="game"?Promise.resolve(ce("unavailable","invalid_argument",{})):In(r,()=>n.ask("gem.openAppResult",l=>e.requestArcade({type:"gem.requestOpenApp",requestId:l,target:a}),l=>l===null?di({}):Ye(l),ha),ce("declined","busy",{})):Promise.resolve(ce("unavailable","unsupported",{}))},openGame(a){if(!e.parentSupports("openGame"))return Promise.resolve(ce("unavailable","unsupported",{}));let l=typeof a=="string"?a.toLowerCase():"";return vl({gem:j,type:"gem.requestOpenGame",requestId:"-",ref:l})!==null?Promise.resolve(ce("unavailable","invalid_argument",{})):In(r,()=>n.ask("gem.openGameResult",m=>e.requestArcade({type:"gem.requestOpenGame",requestId:m,ref:l}),m=>m===null?di({}):Ye(m),ha),ce("declined","busy",{}))},similarGames(a){if(!e.parentSupports("openGame"))return Promise.resolve(ce("unavailable","unsupported",ba));let l=a?.limit;return l!==void 0&&(typeof l!="number"||!Number.isInteger(l)||l<1||l>Cb)?Promise.resolve(ce("unavailable","invalid_argument",ba)):s(`similar:${l??Ib}`,()=>n.ask("gem.similarGamesResult",d=>e.requestArcade({type:"gem.requestSimilarGames",requestId:d,...l===void 0?{}:{limit:l}}),d=>{if(d===null)return di(ba);let m=Ye(d),c=d,p=m.outcome==="ok"?Object.freeze(c.games.map(Mb)):[];return {...m,games:p}},En))}}}var Ob=64,Eu=Object.freeze({offers:Object.freeze([])});function Gb(t){return Object.freeze({skuId:t.skuId,kind:t.kind,name:t.name,description:t.description,...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl},priceDisplay:t.priceDisplay,...t.grant===void 0?{}:{grant:Object.freeze({currency:t.grant.currency,amount:t.grant.amount})}})}function Iu(t){let{bridge:e,asker:n,acting:r}=t,i=new Set,o=null;return {api:{get available(){return e.currentState==="connected"&&e.parentSupports("store")},offers(){return e.parentSupports("store")?(o!==null||(o=n.ask("gem.storeOffersResult",s=>e.requestArcade({type:"gem.requestStoreOffers",requestId:s}),s=>{if(s===null)return ce("unavailable","error",Eu);let a=Ye(s),l=s,d=a.outcome==="ok"?Object.freeze(l.offers.map(Gb)):[];return {...a,offers:d}},En).then(s=>(o=null,s))),o):Promise.resolve(ce("unavailable","unsupported",Eu))},purchase(s){return e.parentSupports("store")?typeof s!="string"||s.length===0||s.length>Ob?Promise.resolve(ce("unavailable","invalid_argument",{})):In(r,()=>n.ask("gem.storePurchaseResult",a=>e.requestArcade({type:"gem.requestStorePurchase",requestId:a,skuId:s}),a=>a===null?ce("unavailable","error",{}):Ye(a)),ce("declined","busy",{})):Promise.resolve(ce("unavailable","unsupported",{}))},onSettled(s){return i.add(s),()=>{i.delete(s);}}},settled(s){let a=Object.freeze({skuId:s.skuId});for(let l of [...i])try{l(a);}catch(d){t.onListenerError?.(d);}}}}var $b="(any-pointer: coarse)";function qb(t){let e=Array.isArray(t)?t:[t],n=[],r=1e4;for(let i of e){if(typeof i!="number"||!Number.isFinite(i)||i<0)return null;if(n.length===99||r===0)continue;let o=Math.min(Math.trunc(i),1e4,r);n.push(o),r-=o;}return n.length%2===0&&n.pop(),n.every(i=>i===0)?[]:n}function Cu(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},i=r.navigator,o,s=new Set,a=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia($b),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,c)=>{s.has(m)||(s.add(m),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return a()||l()},vibrate(m){let c=a();if(!c&&!l())return false;let p=qb(m);if(p===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(i?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(c)try{return i.vibrate(p)===!0}catch{return false}let g=e.requestVibrate(p);return g||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),g}}}var qt=Math.PI/180,Le=Object.freeze({touch:Object.freeze({yaw:1*qt,pitch:.66*qt}),mouse:Object.freeze({yaw:.5*qt,pitch:.5*.77*qt}),stick:Object.freeze({yaw:240*qt,pitch:240*.77*qt}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),va="[gem.controls]",_a=Object.freeze({yaw:0,pitch:0}),ci=t=>Number.isFinite(t)?t:0,Mu=(t,e)=>({yaw:t+0,pitch:e+0});function Ou(t){let e=ci(t),n=(Math.abs(e)-Le.stickDeadzone)/(1-Le.stickDeadzone),r=Le.stickCurve,i=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,i))+0}function Nb(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Le.touchPitchMin)+Le.touchPitchMin}function Gu(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${va} ${e} takes an options object`);let n=t;for(let r of ["sensitivity","gamepadSensitivity"]){let i=n[r];if(i!==void 0&&!(typeof i=="number"&&Number.isFinite(i)&&i>0))throw new TypeError(`${va} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(i)}`)}if(n.invertY!==void 0&&typeof n.invertY!="boolean")throw new TypeError(`${va} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function jb(t,e){let n=Gu(e,"look()"),r=n.sensitivity,i=n.gamepadSensitivity,o=n.invertY,s=a=>o??a?.invertLookY??false;return {fromPointer(a,l,d,m){let c=ci(a),p=ci(l);if(c===0&&p===0)return _a;let g=t(),f=r??(g===null?void 0:g.lookSensitivity/100)??1,v=d==="touch"||d==="pen",k=v?Le.touch:Le.mouse,x=c*k.yaw*f,P=-p*k.pitch*f;return s(g)&&(P=-P),v&&m!==void 0&&Number.isFinite(m)&&P*m>0&&(P*=Nb(m)),Mu(x,P)},fromStick(a,l,d){let m=ci(d);if(m<=0)return _a;let c=Ou(a),p=Ou(l);if(c===0&&p===0)return _a;let g=t(),f=i??(g===null?void 0:g.gamepadLookSensitivity/100)??1,v=c*Le.stick.yaw*m*f,k=-p*Le.stick.pitch*m*f;return s(g)&&(k=-k),Mu(v,k)},set(a){let l=Gu(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(i=l.gamepadSensitivity),"invertY"in l&&(o=l.invertY);}}}function Lu(t){return {look:e=>jb(t.recommended,e),LOOK_BASE:Le}}var Du=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),Fu=/^[A-Za-z0-9_-]{1,40}$/;function wa(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function $u(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function qu(t,e,n,r){let i=a=>Number.parseFloat(a.toPrecision(12)),o=Math.min(n,Math.max(e,t)),s=i(e+Math.round((o-e)/r)*r);return s>n&&(s=i(s-r)),Math.min(n,Math.max(e,s))}function Nu(t,e){switch(t.kind){case "toggle":return typeof e=="boolean"?e:void 0;case "slider":{if(typeof e!="number"||!Number.isFinite(e))return;let n=t.min??0,r=t.max??100;return qu(e,n,r,t.step??1)}case "choice":return typeof e=="string"&&(t.options??[]).some(n=>n.id===e)?e:void 0;default:return}}function ju(t,e=()=>{}){if(!Array.isArray(t))return null;let n=[],r=0;for(let i=0;i<t.length;i+=1){let o=t[i],s=`settings[${i}]`;if(n.length===8){e(`${s} and later were left out: at most 8 settings are shown.`);break}if(typeof o!="object"||o===null){e(`${s} was dropped: a setting is an object.`);continue}let a=o,l=a.id;if(typeof l!="string"||!Fu.test(l)){e(`${s} was dropped: its id must be 1 to 40 of A-Z a-z 0-9 _ -.`);continue}let d=`${s} (${JSON.stringify(l)})`;if(n.some(p=>p.id===l)){e(`${d} was dropped: an earlier setting has the same id.`);continue}let m=$u(a.label);if(m===void 0){e(`${d} was dropped: its label is empty.`);continue}let c;switch(a.kind){case "toggle":{if(typeof a.value!="boolean"){e(`${d} was dropped: a toggle's value is true or false.`);continue}c={id:l,label:m,kind:"toggle",value:a.value},a.quick===true&&(r<2?(c.quick=true,r+=1):e(`${d} is not in the quick row: at most 2 toggles are, the first that ask.`));break}case "slider":{let p=a.min??0,g=a.max??100,f=a.step??1;if(!wa(p)||!wa(g)||!wa(f)||p>=g||f<=0){e(`${d} was dropped: a slider needs finite numbers within \xB11000000 with min below max and a step above 0.`);continue}if(typeof a.value!="number"||!Number.isFinite(a.value)){e(`${d} was dropped: a slider's value is a number.`);continue}c={id:l,label:m,kind:"slider",value:qu(a.value,p,g,f),min:p,max:g,step:f};break}case "choice":{let p=[];for(let g of Array.isArray(a.options)?a.options:[]){if(p.length===4)break;if(typeof g!="object"||g===null)continue;let f=g,v=$u(f.label);typeof f.id!="string"||!Fu.test(f.id)||v===void 0||p.some(k=>k.id===f.id)||p.push({id:f.id,label:v});}if(p.length<2){e(`${d} was dropped: a choice needs 2 to 4 options, each with an id of 1 to 40 of A-Z a-z 0-9 _ - and a label.`);continue}if(typeof a.value!="string"||!p.some(g=>g.id===a.value)){e(`${d} was dropped: a choice's value is the id of one of its options.`);continue}c={id:l,label:m,kind:"choice",value:a.value,options:p};break}default:e(`${d} was dropped: its kind must be 'toggle', 'slider' or 'choice'.`);continue}a.icon!==void 0&&(Du.includes(a.icon)?c.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${Du.join(", ")}.`)),n.push(c);}return n}var Ub=500;function Uu(t){let{clock:e}=t,n=null,r=null,i=-1/0,o=null,s=new Set,a=new Set,l=c=>{a.has(c)||(a.add(c),t.log!==null&&(t.log===void 0?console.warn(c):t.log(c)));},d=()=>{let c=t.frame();return c.currentState==="connected"&&c.parentSupports("gameSettings")},m=()=>{if(n===null||o!==null)return;let c=JSON.stringify(n);if(c===r)return;let p=i+Ub-e.now();if(p>0){o=e.setTimeout(()=>{o=null,m();},p);return}t.frame().declareSettings(n)&&(r=c,i=e.now());};return {api:{declare(c){let p=ju(c,g=>l(`[gem] gem.settings.declare: ${g}`));return p===null?(l("[gem] gem.settings.declare did nothing: pass an array of settings, or [] for none."),false):(n=p,m(),d())},onChange(c){if(typeof c!="function")return ()=>{};let p=g=>c(g);return s.add(p),()=>{s.delete(p);}}},forgetSent(){r=null,i=-1/0;},flush:m,onSettingChange(c){let p=n?.findIndex(x=>x.id===c.id)??-1,g=n?.[p];if(n===null||g===void 0)return;let f=Nu(g,c.value);if(f===void 0)return;let v=JSON.stringify(n);n=n.map((x,P)=>P===p?{...x,value:f}:x),r===v&&(r=JSON.stringify(n));let k={id:g.id,value:f};for(let x of [...s])try{x(k);}catch(P){console.error("[gem] a gem.settings.onChange handler threw:",P);}}}}function Bu(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var Bb=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Wu(t){if(typeof t!="string"||!Bb.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function Cn(){return {declared:false,grantable:false,heldLimitReached:false}}function Hu(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Wu(n.resets_at),i=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...Cn(),...i};let o=n.remaining_today,s=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,a=n.next_eligible_at,l=Wu(a),d=n.held_limit_reached===true,m=a!=null,c=o!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!c&&!m&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var Wb=18e4,Sa=32,Hb=/^[a-z0-9_-]+$/,Vb="rewarded_requires_user_gesture";function Kb(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var Jb=1e3;function zb(){let t=globalThis,e=t.navigator?.getGamepads,n=t.performance?.now;if(typeof e!="function"||typeof n!="function")return;let r=n.call(t.performance),i=e.call(t.navigator);for(let o=0;o<i.length;o+=1){let s=i[o]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=Jb)return true}return false}var Vu=1e4;function Xb(t){return t==="interstitial"||t==="rewarded"}function Ku(t){return typeof t=="string"&&t!==""&&t.length<=Sa&&Hb.test(t)}function Yb(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function ui(t){return typeof t=="string"?JSON.stringify(t):typeof t}function Ju(t){let e=false,n=new Map,r=new Map,i=new Set,o=d=>{try{t.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let m=t.log;if(m!==null)try{m===void 0?console.warn(`[gem] ${d}`):m(`[gem] ${d}`);}catch{}},l=d=>{let m=t.readAvailability;if(m===void 0)return Promise.resolve(Cn());let c=r.get(d);if(c!==void 0)return c;let p=new Promise(g=>{let f={},v=h=>f.done===true?false:(f.done=true,t.clock.clearTimeout(f.timer),g(h),true),k=(h,S)=>{!v(Cn())||i.has(h)||(i.add(h),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${S}. Said once.`));},x=h=>{k(Yb(h),`the read failed (${h instanceof Error?h.message:ui(h)})`);},P;try{P=Promise.resolve(m(d,AbortSignal.timeout(Vu)));}catch(h){P=Promise.reject(h);}f.timer=t.clock.setTimeout(()=>{k("timeout","no answer within 10 s");},Vu),P.then(h=>{try{v(Hu(h,t.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 Ku(d)?l(d):(o(`gem.ads.rewardedStatus(${ui(d)}) answered not grantable: a placement is 1..${String(Sa)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(Cn()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let m=d?.placement,c=d?.format;if(!Ku(m)||!Xb(c))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${ui(m)}, format ${ui(c)}. A placement is 1..${String(Sa)} 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(c==="rewarded"){let g;try{g=(t.userActivation??Kb)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??zb)()===!0&&(g=!0);}catch{}if(g===false){let f=`${Vb}: gem.ads.requestAd("${m}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return o(f),a(f),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${_e()}`;return new Promise(g=>{let f={},v=x=>{n.delete(p)&&(e=false,t.clock.clearTimeout(f.timer),g(x));};e=true,n.set(p,v),f.timer=t.clock.setTimeout(()=>{v({outcome:"unavailable"});},t.timeoutMs??Wb);let k=false;try{k=t.bridge.requestAd(p,m,c);}catch{}k||v({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:m});}}}var zu=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),Xu=18e4,Qb=1e4,Zb=/^[a-z0-9_-]{1,32}$/;function ka(t){return typeof t=="string"?JSON.stringify(t):typeof t}var Mn=Object.freeze({shown:false});function Yu(t){let e=new Map,n,r=false,i=o=>{try{t.onDropped?.(o);}catch{}return Mn};return {api:{signal(o){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(Mn):(r=!0,Promise.resolve(i("moments_unsupported: gem.moments.signal answered shown: false without asking: this arcade does not do platform moments. Keep the call; it costs nothing. Said once.")));let s=o?.kind,a=o?.placement,l=o?.wall;if(!zu.includes(s)||a!==void 0&&(typeof a!="string"||!Zb.test(a))||l!==void 0&&typeof l!="boolean")return Promise.resolve(i(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${ka(s)}, placement ${ka(a)}, wall ${ka(l)}. A kind is one of ${zu.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'; a wall, when given, is true or false. Answering shown: false.`));if(!t.bridge.readyCalled())return Promise.resolve(i(`moments_before_ready: gem.moments.signal({ kind: '${s}' }) before gem.frame.ready(): a moment is a break in play, and play has not started. Signal from the press that leaves a break, never on boot. Answering shown: false.`));if(e.size>0)return Promise.resolve(i(`moments_in_flight: gem.moments.signal({ kind: '${s}' }) while another moment is still waiting for its answer. Signal once per break, and await the answer before play resumes. Answering shown: false.`));let d=t.clock.now();if(n!==void 0&&d-n<Qb)return Promise.resolve(i(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(d-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let m=`moment-${_e()}`;return new Promise(c=>{let p={},g=(v,k)=>{e.delete(m)&&(t.clock.clearTimeout(p.timer),k&&(n=t.clock.now()),c(v));};e.set(m,v=>g(v,!0)),p.timer=t.clock.setTimeout(()=>{e.has(m)&&(g(Mn,!0),i(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??Xu)/1e3)} s. Answering shown: false.`));},t.timeoutMs??Xu);let f=!1;try{f=t.bridge.signalMoment(m,s,a,l===!0?!0:void 0);}catch{}f||g(Mn,!1);})}catch{return Promise.resolve(Mn)}}},settle(o){let s=e.get(o.requestId);if(s===void 0){i(`gem.momentResult (shown: ${String(o.shown)}) for an unknown requestId: `+JSON.stringify(o.requestId));return}s({shown:o.shown===true});}}}var Ra=16384;function Qu(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e;try{e=JSON.stringify(t);}catch{return null}return typeof e!="string"?null:ev(e)}function ev(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var tv=1e4,nv=5e3;function Zu(t){let e=null,n=false,r=[],i=new Map,o=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=nv){return n?Promise.resolve(e):new Promise(a=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{t.clock.clearTimeout(m),l(),a(e);},m=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=Qu(s);if(a===null)return t.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(a>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(s)),d=`device-settings-${_e()}`;return new Promise(m=>{let c={},p=f=>{i.delete(d)&&(t.clock.clearTimeout(c.timer),f==="stored"&&(e=l,n=true,o()),m(f));};i.set(d,p),c.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??tv);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,n=true,o();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=i.get(s.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var On=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 rv=/^[a-z0-9][a-z0-9_-]{0,39}$/;function iv(t){return typeof t=="string"&&rv.test(t)}function mi(t){if(t===null||iv(t))return t;let e=typeof t=="string"?JSON.stringify(t.length>48?`${t.slice(0,48)}\u2026`:t):`a value of type ${typeof t}`;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 em(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function xa(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!n.includes(i)&&n.push(i);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function pi(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(e.length===4)break;if(typeof n!="object"||n===null)continue;let{id:r,label:i}=n;typeof r!="string"||r.length===0||r.length>32||typeof i!="string"||i.trim().length===0||e.some(o=>o.id===r)||e.push({id:r,label:i.trim().slice(0,40)});}return e.length===0?{settings:false}:{settings:false,items:e}}function tm(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function ov(t){let e=t.untrusted,n=he(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,i=r?he(r,"gem.player.displayTag"):void 0,o=t.discriminator||t.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=t.avatarIconUrl||t.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=t.avatarIconId,m=t.avatar3dId,c={displayName:n,displayHandle:i??n,badges:(t.badges??[]).map(v=>({itemId:v.itemId,iconUrl:v.iconUrl}))};t.playerId&&(c.playerId=t.playerId),s&&(c.discriminator=s),i&&(c.displayTag=i),a&&(c.avatarIconUrl=c.avatarUrl=a),d&&l.test(d)&&(c.avatarIconId=d),m&&l.test(m)&&(c.avatar3dId=m),t.avatar3dModelUrl&&(c.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(c.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(c.avatars3d=t.avatars3d.filter(v=>l.test(v.id)&&/^[a-z][a-z0-9_]*$/.test(v.family)).filter((v,k,x)=>x.findIndex(P=>P.family==v.family)==k).map(({family:v,id:k,modelUrl:x,iconUrl:P})=>({family:v,id:k,modelUrl:x,iconUrl:P})));let p=t.boost,g=(p?.multipliers??[]).map(v=>({currencyId:v.currencyId,currencySlug:v.currencySlug,multiplier:v.multiplierBp/1e4})),f=g.some(v=>v.multiplier>1);return c.boost=f&&p?.expiresInDays?{active:f,multipliers:g,expiresInDays:p.expiresInDays}:{active:f,multipliers:g},c}var av=1e4,sv=["appLinks","openGame","store"],Aa=new WeakMap;function rm(t,e){if(Aa.has(t))throw new Error("admitBuildEmbedders: already admitted");Aa.set(t,Object.freeze([...e]));}var Gn=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??ue,this.inbound=new Vt(this.clock),this.outbound=new Vt(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(a=>St(a,e.origin))||rr(e.origin,this.options.selfOrigin)||(Aa.get(this)??[]).some(a=>St(a,e.origin))))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=nr["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!St(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let s=_l(Zn,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:j,type:"gem.error",code:"version_mismatch",message:`frame supports v${Zn.min}..v${Zn.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=s,o.onmessage=a=>this.receive(a.data,a.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:j,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:j,type:"gem.ready"});}settled(e=av){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=o=>{this.clock.clearTimeout(i),n(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:j,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:j,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:j,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:j,type:"gem.exit"}:{gem:j,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:j,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:j,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:j,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:j,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:j,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:em(e.origin.x),y:em(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=mi(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:j,type:"gem.portraitBorders"}:{gem:j,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:j,type:"gem.walletDisplay",...xa(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:j,type:"gem.menu",...pi(e)}):false}declareSettings(e){return this.gated("gameSettings")?this.send({gem:j,type:"gem.settingsDeclare",settings:e}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:j,type:"gem.gemCorner",corner:e}):false}requestShare(e){return this.gated("share")?this.send({gem:j,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:j,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:j,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:j,type:"gem.frameStats",fps:tm(e.fps,1e3),frameTimeP95Ms:tm(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:j,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:j,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:j,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:j,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,i,o,s){return this.send({gem:j,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}requestAvatar3dPurchase(e,n,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:j,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:j,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:j,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r,i){return this.send({gem:j,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r},...i===true?{wall:true}:{}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:j,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,i){return this.send({gem:j,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...i===void 0?{}:{params:i}})}requestArcade(e){return this.gated(tr(e.type))&&this.send({gem:j,...e})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(er)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(er)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(er)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:j,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}gated(e){return this.state==="connected"&&this.parentSupports(e)}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let n=e.type;if(!this.outbound.allow(n))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${n}`),false;let r=nr[n]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${n}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,n=[]){let r=false;try{r=this.dispatchInbound(e,n);}finally{r||nm(n);}}dispatchInbound(e,n){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=nr[r];if(!i)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let o=tr(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.settingChange":this.options.onSettingChange?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=n[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return nm(n.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(ov(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.ticketEvent":this.options.onTicketEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.momentResult":this.options.onMomentResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:if(sv.includes(tr(r))){this.options.onArcadeAnswer?.(a);break}this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:j,type:"gem.screenshot.denied",reason:e,retryable:n});}};function nm(t){for(let e of t)try{e?.close?.();}catch{}}var im="https://api.gemarcade.com";function Pa(t){let e;try{e=new URL(t);}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 lv=new Set(["localhost","127.0.0.1","[::1]"]);function om(t){let e=Pa(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!lv.has(n.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 lm="/gem-embedders.json",gi=4096,am=16,sm=5e3,Ln=Object.freeze({origins:Object.freeze([])});function Qe(t){return {origins:[],refused:`[gem] ${lm} was ignored: ${t}`}}function dv(t){if(t.trim()==="")return Ln;let e;try{e=JSON.parse(t);}catch{return Qe("it is not JSON.")}if(e===null||typeof e!="object"||Array.isArray(e))return Qe('it must be an object, { "embedders": [...] }.');let n=e.embedders;if(n===void 0)return Ln;if(!Array.isArray(n))return Qe('"embedders" must be an array of origins.');if(n.length>am)return Qe(`"embedders" has more than ${am} entries.`);let r=n.filter(i=>typeof i!="string"||!wt(i)||!i.toLowerCase().startsWith("https://")||He(new URL(i).hostname));if(r.length>0){let i=r.slice(0,3).map(o=>typeof o=="string"?JSON.stringify(o.slice(0,100)):String(o)).join(", ");return Qe(`${r.length===1?"an entry is":"entries are"} not an https origin off this machine (${i}${r.length>3?", \u2026":""}).`)}return {origins:Object.freeze([...new Set(n)])}}async function dm(t){let e=typeof AbortController=="function"?new AbortController:null,n,r=new Promise(o=>{n=t.clock.setTimeout(()=>{e?.abort(),o(Qe(`it took more than ${sm} ms to read.`));},sm);}),i=(async()=>{let o=await t.fetch(t.selfOrigin+lm,{credentials:"omit",redirect:"error",...e?{signal:e.signal}:{}});if(!o.ok||(o.headers.get("content-type")??"").toLowerCase().includes("text/html"))return Ln;if(Number(o.headers.get("content-length"))>gi)return Qe(`it is larger than ${gi} bytes.`);let a=await o.text();return a.length>gi?Qe(`it is larger than ${gi} bytes.`):dv(a)})().catch(()=>Ln);try{return await Promise.race([i,r])}finally{t.clock.clearTimeout(n);}}function cm(t){if(typeof t!="string"||!wt(t))return null;let e=t.slice(0,t.indexOf(":")).toLowerCase();return e==="https"||e==="http"?t:null}function um(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function cv(){let t=[["root",null],["hips","root"],["spine","hips"],["chest","spine"],["upper_chest","chest"],["neck","upper_chest"],["head","neck"],["head_socket","head"]];for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("shoulder"),"upper_chest"],[n("upper_arm"),n("shoulder")],[n("lower_arm"),n("upper_arm")],[n("hand"),n("lower_arm")],[n("hand_socket"),n("hand")]);for(let r of ["thumb","index","middle","ring","little"])for(let i=1;i<=3;i++)t.push([n(`${r}_${i}`),n(i===1?"hand":`${r}_${i-1}`)]);}for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("upper_leg"),"hips"],[n("lower_leg"),n("upper_leg")],[n("foot"),n("lower_leg")],[n("toes"),n("foot")]);}return t}var uv=Object.freeze({small_human:um([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:um(cv())});var pv=Object.freeze(["https://gemarcade.com","https://developer.gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),gv=im,fv=["top-left","top-right","bottom-left","bottom-right"],mm=8e3,fi=15e3,yv=9e4,hv=1/0,bv=8e3,vv=5e3,_v=5e3;async function wv(t,e,n,r){if(t.isInRoom)try{await t.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(n);}function Dn(t){let e=null,n=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){n=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||n?Promise.resolve(e):new Promise(o=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{t.clearTimeout(l),s(),o(d);},l=t.setTimeout(()=>{s(),o(e);},i);r.push(a);})}}}function PT(t={}){let e=t.clock??ue,n=t.log===void 0?u=>console.info(u):t.log,r=t.baseUrl??void 0;if(r!=null){let u=Pa(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=typeof window>"u"?void 0:window.location?.search,o=ed(i),s=Td(i),a=Vo();a.mark("sdk created");let l=()=>Dr(ae.gameVersion,t.clientVersion?.gameVersion),d=new an({client:()=>bt,clock:e,gameId:()=>ae.identity?.gameId??null,playerId:()=>ae.identity?.playerId??null,awaitPlayerId:async()=>(await Kn(fi)).playerId,environment:()=>{let u=l();return {sdk_version:Qa(),...u===null?{}:{game_version:u}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),m=pc(()=>{a.mark("engaged"),d.release(),$.reportEngaged();},typeof window>"u"?{}:window),c=u=>{if(u===false)return null;let A=u?.attempts??hv,G=u?.budgetMs??yv;return !(A>0)||!(G>0)?null:{attempts:A,budgetMs:G,maxDelayMs:u?.maxDelayMs??bv}},p=u=>{u.on("created",()=>{a.mark("room created");}),u.on("joined",()=>{a.mark("room joined");}),u.on("matchAllocationStarted",()=>{a.mark("allocation started");}),u.on("matchReady",()=>{a.mark("match ready");}),u.on("matchFailed",()=>{a.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 On;let g=t.allowedEmbedders;if(g!=null&&!Array.isArray(g))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 f=Array.from(g??[]),v=f.filter(u=>typeof u!="string"||!wt(u));if(v.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${v.length===1?"an entry":"entries"} that ${v.length===1?"is":"are"} not an origin: ${v.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let k=Object.freeze([...new Set([...pv,...f])]),x=Dn(e),P=new Set,h=Dn(e),S=false,I=Dn(e),T=ad(n),W=Dn(e),q=t.manageAudio===false?null:Ac();t.selectableText!==true&&xc(),t.onScreenshot===void 0&&fc(window);let U=null,E=null,O=null,F=()=>{U===null||U===E||$.reportMuted(U)&&(E=U);},N,B,J=-1/0,oe=null,ge=()=>{if(N===void 0||oe!==null||N===B)return;let u=J+1e3-e.now();if(u>0){oe=e.setTimeout(()=>{oe=null,ge();},u);return}$.showPortraitBorders(N)&&(B=N,J=e.now());},X=null,Ne=null,ke=()=>{if(X===null)return false;let u=JSON.stringify(xa(X.visible,X.only));return u===Ne?$.parentSupports("walletDisplay"):$.setWalletVisible(X.visible,X)?(Ne=u,true):false},fe=null,je=null,te=()=>{if(fe===null)return false;let u=JSON.stringify(pi(fe.items));return u===je?$.parentSupports("gameMenu"):$.setMenu(fe.items)?(je=u,true):false},z=null,le=null,xe=Uu({frame:()=>$,clock:e,log:t.log}),Ue=()=>z===null?false:z===le?$.parentSupports("gemCorner"):$.setGemCorner(z)?(le=z,true):false,De=Pc({report:u=>$.reportFrameStats(u)}),ft=false,Ee=Gc(()=>Ha,()=>ft),Nt=u=>{let A=ft&&!u,G=ft!==u;if(ft=u,A&&Ee.close(),!!G)try{t.onDevToolsPermissionChange?.(u);}catch(ee){n?.(`[gem] onDevToolsPermissionChange threw: ${ee instanceof Error?ee.message:String(ee)}`),queueMicrotask(()=>{throw ee});}},Be=r??gv,yi=r!==void 0,yt,y=u=>(n?.(`[gem] token refused: ${u}`),t.onError?.("internal",u),false),C=(u,A)=>{if(u===void 0)return A!==void 0?y("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 G=om(u);return G!==null?y(`the embedder named an API root that cannot be used: ${G}. Its value is withheld here rather than written to logs.`):yt!==void 0&&yt!==u?y("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."):(yt=u,yi||(Be=u),true)},L=window.location?.origin,Z=null,we=-1/0,Fn=2e3,ht=new Set,jt=u=>Z!==false?Promise.resolve(true):new Promise(A=>{let G=e.setTimeout(()=>{ht.delete(ee),A(false);},u),ee=()=>{e.clearTimeout(G),ht.delete(ee),A(true);};ht.add(ee);}),hi=()=>{},bi=null,$n=Pu(e),$=new Gn({allowedEmbedders:k,...typeof L=="string"&&L!==""?{selfOrigin:L}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","ticketEvents","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","gemCorner","gameSettings","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges","appLinks","openGame","store",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[]],onRefused:u=>{bi=u,t.onRefused?.(u);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:u=>{ae.onBridgeState(u),u!=="connected"&&$n.abandon(),u!=="connected"&&De.setRequested(false),E=null,Ne=null,je=null,le=null,xe.forgetSent(),B=void 0,u==="refused"&&(console.error("[gem] this game refused the page that framed it"+(bi===null?"":` (${bi})`)+", 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."),hi()),u==="connected"&&(a.mark("bridge connected"),ym(),F(),ge(),ke(),te(),Ue(),xe.flush(),$.unbiddenLaunch&&!m.engaged&&d.hold(),d.startSession(),m.engaged&&$.reportEngaged()),t.onStateChange?.(u);},onPlayer:u=>{x.set(u);for(let A of [...P])A(u);t.onPlayer?.(u);},onPrefs:u=>{let A={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true,music:u.music!==false,sounds:u.sounds!==false,recommended:u.recommended===void 0?null:Object.freeze({volume:u.recommended.volume,batterySaver:u.recommended.batterySaver,keyboardLayout:u.recommended.keyboardLayout,gamepadConfirm:u.recommended.gamepadConfirm,vibration:u.recommended.vibration,lookSensitivity:u.recommended.lookSensitivity??100,gamepadLookSensitivity:u.recommended.gamepadLookSensitivity??100,invertLookY:u.recommended.invertLookY??false,touchMovement:u.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:Bu(u.recommended.graphicsQuality,u.recommended.batterySaver),graphicsQualityAuto:u.recommended.graphicsQualityAuto??true,colorHelp:typeof u.recommended.colorHelp=="boolean"?u.recommended.colorHelp:null})};h.set(A),E=A.muted,q?.setMuted(A.muted),De.setRequested(A.showFrameStats&&$.parentSupports("frameStats")),t.onPrefs?.(A),t.onAudioChannels!==void 0&&(O===null||O.music!==A.music||O.sounds!==A.sounds)&&(O=Object.freeze({music:A.music,sounds:A.sounds}),t.onAudioChannels(O));},onCohorts:u=>{let A=Object.freeze(u.cohorts.map(G=>Object.freeze({experimentId:G.experimentId,variantKey:G.variantKey})));I.set(A),t.onCohorts?.(A);},onEarnAllowanceChanged:()=>T.emit(),onViewport:u=>{let A=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left}),reserved:Object.freeze((u.reserved??[]).map(({x:ee,y:Va,width:Ka,height:Ja,control:Bt})=>Object.freeze(Bt?{x:ee,y:Va,width:Ka,height:Ja,control:Object.freeze({x:Bt.x,y:Bt.y,width:Bt.width,height:Bt.height})}:{x:ee,y:Va,width:Ka,height:Ja})))});W.set(A);let G=Ec();Ic(G,A.insets),Mc(G,A.reserved,Cc()),t.onViewport?.(A);},onPause:u=>{S=u.paused,d.setPaused(u.paused),De.setPaused(u.paused),t.onPause?.(u.paused);},onSettingChange:u=>xe.onSettingChange(u),onMenuSelect:u=>{fe===null||u.entry!=="item"||!(pi(fe.items).items??[]).some(G=>G.id===u.id)||fe.items?.find(G=>G.id===u.id)?.onSelect?.();},onWillTerminate:u=>{d.endSession(u.reason),t.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let A=u.garden;if(Nt(u.allowDevTools===true),!C(u.apiBaseUrl,A))return;let G=u;ae.onToken(G);let ee=ae.identity;ee&&(vi.set(ee),Ia||(Ia=true,me.reconcileSeats().catch(()=>{}))),Ca.push({token:G.token,expiresAt:G.expiresAt});},onTokenDenied:u=>{Nt(false),ae.onDenied(u);},onScreenshot:(u,A,G)=>{Sc(u,A,G,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{kc($,t.onFeedbackContext);},onDevtools:u=>{u==="close"?Ee.close():u==="open"?Ee.openFrom("platform").catch(()=>{}):Ee.isOpen?Ee.close():Ee.openFrom("platform").catch(()=>{});},onRoomEvent:u=>me.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>me.handleSeated(u.roomId),onAutoStartFailedEvent:u=>me.handleAutoStartFailed(u.roomId,u.code),onTicketEvent:u=>me.handleTicketEvent({event:u.event,ticketId:u.ticketId,...u.partySize===void 0?{}:{partySize:u.partySize},...u.queuedAt===void 0?{}:{queuedAt:u.queuedAt},...u.expiresAt===void 0?{}:{expiresAt:u.expiresAt},...u.reason===void 0?{}:{reason:u.reason},...u.roomId===void 0?{}:{roomId:u.roomId}}),onSocketState:u=>{let A=Z;if(Z=u.connected,u.connected)for(let ee of [...ht])ee();if(!u.connected||A===true)return;let G=e.now();G-we<Fn||(we=G,me.reconcile().catch(()=>{}));},onSignalEvent:u=>{let A=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};vt.handleSignalEvent(u.matchId,u.event,A),u.event==="matchEnded"&&me.reconcile({matchId:u.matchId,...typeof A.reason=="string"?{reason:A.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(Ut.handleMatchEnded(u.matchId,u.reason),me.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),Ea.handleEvent(u);},onClusterTarget:u=>Un.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>Bn.accept(u),onLocalServerDenied:u=>Bn.refuse(u),onPartyResult:u=>Oa.settle(u.requestId,u.partyId),onPurchaseResult:u=>wi.settle(u),onDeviceSettings:u=>{jn.receive(u),t.onDeviceSettings?.(jn.api.current);},onDeviceSettingsResult:u=>jn.settle(u),onAdResult:u=>La.settle(u),onMomentResult:u=>Da.settle(u),onSignInResult:u=>Fa.settle(u),onFriendChallengeResult:u=>Na.settle(u),onArcadeAnswer:u=>{u.type==="gem.storePurchaseSettled"?qa.settled(u):bm(u);}}),Ea=new Pn({bridge:$}),vi=Dn(e);hi=()=>{vi.release(),x.release(),I.release();},$.currentState==="refused"&&hi();let Ia=false,_i=new Set,qn,Ca={current:()=>qn,subscribe:u=>(_i.add(u),qn!==void 0&&u(qn),()=>_i.delete(u)),push:u=>{qn=u;for(let A of [..._i])try{A(u);}catch(G){n?.(`[gem] a server-token listener threw: ${G instanceof Error?G.message:String(G)}`);}}},ae=Dc({bridge:$,clock:e,onStateChange:(u,A)=>{if(u==="ready"){if(a.mark("token ready")){let G=a.marks.find(ee=>ee.name==="token ready")?.at;d.trackPlatform("gem_boot_ready",G===void 0?{}:{boot_ms:Math.max(0,Math.round(G))});}}else u==="lost"&&(a.mark("token lost"),d.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(u,A);}}),Ma=()=>{let u=ae.identity;return !u||ae.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},ym=()=>{a.mark("token requested"),ae.source.get().catch(()=>{});},Oa=gu({bridge:$,clock:e}),Nn={},wi=fu({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u),confirm:async u=>Nn.confirm?.(u)??"unknown",confirmAvatar3d:async u=>Nn.confirmAvatar3d?.(u)??"unknown"}),jn=Zu({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u)}),Ga={},La=Ju({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u),readAvailability:(u,A)=>Ga.read?.(u,A)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),Da=Yu({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u)}),Fa=Su({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u)}),$a={held:false},hm=Tu({bridge:$,asker:$n,acting:$a}),qa=Iu({bridge:$,asker:$n,acting:$a,onListenerError:u=>t.onError?.("internal",`gem.store.onSettled listener threw: ${String(u)}`)}),bm=u=>{$n.settle(u)||t.onError?.("internal",`${u.type} (${u.outcome}) for an unknown requestId: `+JSON.stringify(u.requestId));},Na=od({bridge:$,clock:e,onDropped:u=>t.onError?.("internal",u)}),Un=fd({bridge:$,clock:e}),Bn=Oc({bridge:$,clock:e}),Si=cm(L),ja=window.fetch,Wn=Si!==null&&typeof ja=="function"?"unread":"read",Hn=null,ki=false,vm=u=>{if(Wn==="read"||u.source!==window.parent)return false;let A=u.origin;return typeof A!="string"||k.some(G=>St(G,A))||rr(A,typeof L=="string"?L:void 0)?false:((Hn===null||!ki)&&(Hn=u),Wn==="unread"&&Si!==null&&(Wn="reading",dm({fetch:(G,ee)=>ja.call(window,G,ee),selfOrigin:Si,clock:e}).then(G=>{"refused"in G&&n?.(G.refused),G.origins.length>0&&rm($,G.origins),Wn="read";let ee=Hn;Hn=null,ee!==null&&$.currentState==="waiting"&&Vn(ee);})),true)},Vn=u=>{if(vm(u))return false;let A=$.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return A&&window.removeEventListener("message",Vn),A};window.addEventListener("message",Vn),ki=true;let Ze;try{Ze=Ya(window,Vn);}finally{ki=false;}let _m=Ze?.capture,Ri=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Ri?.domInteractive!==void 0&&Ri.domInteractive>0&&a.mark("document parsed",Ri.domInteractive),_m?.late&&n?.("[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 Ai=t.handshakeWarningMs;Ai!==null&&n&&e.setTimeout(()=>{let u=Ze===null?"no capture script ran":`capture: ${Ze.delivered} offer(s) delivered, ${Ze.stale} stale, ${Ze.capture.dropped} evicted${Ze.capture.late?", installed late":""}`;if($.currentState==="connected"){n(`[gem] handshake connected. boot: ${a.timeline()} \xB7 ${u}`);return}n(`[gem] no completed handshake after ${Ai??mm}ms (bridge state: ${$.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${a.timeline()} \xB7 `+u);},Ai??mm);let wm=mr({get baseUrl(){return Be},tokenSource:ae.source,get defaultQuery(){let u=ae.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),bt=new We({transport:wm,clock:e}),ye={client:bt,gameId:()=>ae.identity?.gameId??""};Nn.confirm=u=>yu(ye,u),Nn.confirmAvatar3d=u=>_u(ye,u),Ga.read=(u,A)=>dl(ye,"players","me",u,{signal:A});let Sm=()=>ae.identity?.channel??"release",xi=new kr(ye,Sm),km=vu({player:()=>x.current,subscribe:u=>(P.add(u),()=>{P.delete(u);}),configFamilies:async()=>(await xi.load())?.avatar_3d_families,readOffers:()=>wu(ye),purchase:u=>wi.requestAvatar3d(u),log:t.log}),Ua=async u=>(await xi.load())?.currency(u)?.id??void 0,Ba=hr(ye,Wi,{identity:Ma,resolveCurrencyId:Ua}),Kn=async u=>{let A=await vi.wait(u);if(A)return A;throw $.currentState==="refused"?new ne("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 ne("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).")},Pi=c(t.autoReconnect),me=Kd(s===void 0?{}:{playWithTicket:s},{client:bt,clock:e,gameId:()=>ae.identity?.gameId??null,playerId:()=>ae.identity?.playerId??null,awaitGameId:async()=>(await Kn(fi)).gameId,resolveParty:Oa.resolve,resolveClusterTargets:Un.resolveList,refreshClusterTargets:Un.refresh,ensureLocalServer:Bn.ensure,localHostAvailable:Bn.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>ae.gameVersion,...t.pollRooms===void 0?{}:{poll:t.pollRooms},...t.recoverStaleMembership===void 0?{}:{recoverStaleMembership:t.recoverStaleMembership},...t.retryAutoStart===void 0?{}:{retryAutoStart:t.retryAutoStart},...t.watchSeats===void 0?{}:{watchSeats:t.watchSeats},...t.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:t.seatPollIntervalMs},...Pi===null?{}:{autoReconnect:{...Pi,redial:(u,A)=>Ti.redialMatch(u,A),abandon:(u,A)=>Ti.abandonMatch(u,A)}}});p(me),uc({analytics:d,rooms:me});let vt=cc({client:bt,clock:e,rooms:me,bridge:$,gameId:()=>ae.identity?.gameId??"",baseUrl:()=>Be,resolveClusterTarget:Un.resolve,boot:a,...t.log===void 0?{}:{log:t.log}}),Wa=Ho(a,n),Ut=Zc({client:bt,clock:e,rooms:me,signaling:()=>Ea.channel(),signalingReady:jt,log:n??(()=>{})}),Ti=mu({rooms:me,p2p:{connect:u=>Wa(vt.connect(u)),session:u=>vt.session(u)},dedicated:{connect:(u=>ei(a,"welcome",Ut.connect(u),n))},clock:e,identity:()=>ae.identity,apiBaseUrl:()=>Be,tokens:Ca,room:()=>me.currentRoom,autoReconnect:Pi!==null,...t.log===void 0?{}:{log:t.log}}),Rm=async()=>(await Kn(fi)).playerId,Ha={client:bt,boot:a,get identity(){return ae.identity},awaitIdentity:(u=fi)=>Kn(u),awaitBridge:u=>$.settled(u),get player(){return x.current},awaitPlayer:(u=vv)=>x.wait(u),me:Ba,characters:new vr(ye,void 0,Ma,Ua),transfers:new wr(ye,Wi,Ba.inventory),gameConfig:xi,purchases:wi.api,deviceSettings:jn.api,moments:Da.api,ads:La.api,account:Fa.api,share:xu({frame:$,log:t.log}),arcade:hm,store:qa.api,vibration:Cu({frame:$,log:t.log}),get avatarPickerAvailable(){return $.currentState==="connected"&&$.parentSupports("avatarPicker")},openAvatarPicker:u=>$.requestAvatarPicker(u?.tab),avatars3d:km,settings:xe.api,controls:Lu({recommended:()=>h.current?.recommended??null}),analytics:d,leaderboards:new Qt(ye),challenges:new zt(ye),showcase:new Zt(ye,Rm),friends:new en(ye,{challenge:Na.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new nn(ye,T,n),profiles:new rn(ye),functions:new Ke((u,A)=>zs(ye,u,A)),get prefs(){return h.current},get paused(){return S},get cohorts(){return I.current},get viewport(){return W.current},awaitCohorts:(u=_v)=>I.wait(u),reportMuted:u=>{U=!!u,F();},showPortraitBorders:u=>{let A=mi(u);A!==void 0&&(N=A,ge());},cueReward:u=>$.cueReward(u),setWalletVisible:(u,A)=>{let G=Array.isArray(A?.only)?[...A.only]:void 0;return X=G===void 0?{visible:u===true}:{visible:u===true,only:G},ke()},setMenu:u=>(fe=Array.isArray(u?.items)?{items:u.items.map(A=>({...A}))}:{},te()),setGemCorner:u=>{if(!fv.includes(u)){let A=typeof u=="string"?JSON.stringify(u.slice(0,48)):`a value of type ${typeof u}`;return console.warn(`[gem] setGemCorner: ${A} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return z=u,Ue()},reportFrame:()=>De.draw(),exit:u=>wv(me,$,u,d),frame:$,devtools:Ee,rooms:me,dedicatedServer:{listClusterTargets:u=>Ut.listClusterTargets(u),connect:(u=>ei(a,"welcome",Ut.connect(u),n)),handleMatchEnded:(u,A)=>Ut.handleMatchEnded(u,A)},p2p:{handleSignalEvent:(u,A,G)=>vt.handleSignalEvent(u,A,G),session:u=>vt.session(u),connect:u=>Wa(vt.connect(u))},match:Ti};return Ha}var pm="the match has not started yet: the runtime hands over the host at `init`, and this was read before that. Read it from `init` or later \u2014 a bundle that needs a value at module scope is reading it one call too early.";function Ta(t,e={}){let n=e.clock??ue,r=()=>{let a=t();if(a===null)throw new Error(pm);return a},i=null,o=()=>{if(i===null)throw new Error(pm);return i};return {server:{get identity(){return o().identity},get client(){return o().client},get api(){return o().api},get match(){return o().match},get analytics(){return o().analytics},get functions(){return o().functions},get challenges(){return o().challenges},get room(){return o().room},dispose(){i?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(a){let d=r().profile?.(a);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:he(m,"profile.displayName"),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:he(d.displayTag,"profile.displayTag")}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(a){return r().playerNumber?.(a)},send(a,l,d){d===void 0?r().send(a,l):r().send(a,l,d);},broadcast(a,l){l===void 0?r().broadcast(a):r().broadcast(a,l);},kick(a,l){l===void 0?r().kick(a):r().kick(a,l);},log(a){r().log(a);},warn(a){r().warn(a);}},attach:()=>{i=Ft(r(),{...e,clock:n});}}}function gm(t,e={}){let{server:n,attach:r}=Ta(()=>t,e);return r(),n}function Sv(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:Je(e)}}}var kv=1e4;function Rv(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout(kv));}catch{return}r.catch(i=>{i instanceof M&&i.status>=400&&i.status<500&&(e=i.status!==429);});}}function fm(t,e={}){return ()=>{let n=null,{server:r,attach:i}=Ta(()=>n,e),o=t(r),s={async init(l){n=l,i(),await o.init?.();},async shutdown(l){let d=Sv(l);try{await o.shutdown?.(d);}finally{r.dispose();}}},a=Rv(r);return s.join=(l,d)=>(a(l),o.join?.(l,d)),o.leave&&(s.leave=(l,d)=>o.leave?.(l,d)),o.message&&(s.message=(l,d,m,c)=>o.message?.(l,d,m,c)),s}}Xa();
3
+ exports.ARCADE_EMBEDDERS=pv;exports.AVATAR_RIGS=uv;exports.AnalyticsApi=an;exports.AuthError=ne;exports.CONDITIONAL_HEADERS=Jn;exports.ChallengesApi=zt;exports.DEVICE_SETTINGS_MAX_BYTES=Ra;exports.DedicatedServerError=w;exports.FriendChallengeError=at;exports.FriendsApi=en;exports.FunctionsApi=Ke;exports.GemApiError=M;exports.GemClient=We;exports.GemConfigError=pe;exports.GemFrame=Gn;exports.GemFunctionError=on;exports.GemSaveError=ie;exports.GemUnframedError=On;exports.LeaderboardsApi=Qt;exports.MAX_PERIODS_BACK=Bl;exports.PLATFORM_EVENTS=Rg;exports.PlatformApi=nn;exports.PlatformCurrenciesApi=Er;exports.PlatformEarnAllowanceApi=Ir;exports.PlayerText=ve;exports.ProfilesApi=rn;exports.PurchaseRefusal=Ve;exports.ShowcaseApi=Zt;exports.TransportRefusal=se;exports.UNRELIABLE_CHANNEL_LABEL=un;exports.asPlayerText=he;exports.createBootTimeline=Vo;exports.createGem=PT;exports.createGemServer=Ft;exports.createHostTokenSource=nu;exports.createMatchServer=gm;exports.defineServer=fm;exports.experimentSelection=Mr;exports.leaveAndExit=wv;exports.mapIdentity=Pe;exports.markOnResolve=ei;exports.platformIconUrl=Xp;exports.presentJoinCredential=dn;exports.readTemplateTransports=Et;exports.readTransportAdvert=mn;exports.reportOnResolve=Ho;exports.systemClock=ue;exports.text=rt;exports.toBase64=zn;exports.webTransportAvailable=jr;return exports;})({});