@indiegems/gem-web-sdk 19.0.1 → 19.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- var GemWebSdkGame=(function(exports){'use strict';var Jm=Object.defineProperty;var zm=(t,e)=>{for(var n in e)Jm(t,n,{get:e[n],enumerable:true});};var Go="GemWebSdkHandshake";function Xm(){return typeof document>"u"?void 0:document.readyState}var os=()=>Date.now();function is(t={}){let e=t.win??window,n=e,r=n[Go];if(r!==void 0)return r;let o=t.readyState??Xm,i=t.now??os,s=[],a=[],l=u=>{let c=u.data;!c||c.type!=="gem.handshake"||(s.length>=4&&(s.shift(),a.shift(),d.dropped+=1),s.push(u),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[Go]=d,d}function as(t,e,n={}){let r=t[Go];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??os,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,u=false,c=i()-o;for(let g=s.length-1;g>=0;g--){let p=a?.[g];if(p!==void 0&&p<c){d+=1;continue}if(l+=1,e(s[g])===true){u=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:u}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:19.0.1]";function ss(){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 Ym={initialDelayMs:2e3,maxDelayMs:6e4};function Qm(t,e){return e!==void 0?!e:t==="chain_exhausted"}var wt=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}=Ym,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=Zm(o),{retryable:s,retryAfterMs:a}=o??{};throw n===this.generation&&(Qm(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 Zm(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}},tr=["if-match","if-none-match"],ls=4096;function ep(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!tr.includes(o)||r===void 0)continue;let i=typeof r=="string"?tp(r):r;if(typeof i!="string"||i.length>ls||!np(i))throw new se(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${ls} 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 tp(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 np(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 rp(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 ds(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=ep(o.headers),s=rp(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 u=await e.tokenSource.get(),c=await t(a,u);if(c.status===401)throw e.tokenSource.close("unavailable"),new ne("unavailable","the server refused a freshly minted token");return c}}}function nr(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(op(e))}function rr(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 Lo(t){return new TextDecoder().decode(rr(t))}function op(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var G=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"}},ms=new WeakMap;function ps(t){return ms.get(t)??{}}var ip=new Set([408,429,500,502,503,504]),ap=6e4,gs=new WeakMap;function fs(t,e){gs.set(t,e);}function cs(t){return t!==null&&(t.reason==="rate_limited"||t.retryAfterSeconds!==void 0)}function sp(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 He=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,...Kt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...Kt(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,...Kt(o)},o.replaySafe===true,o.retryRateLimited!==false);return {bytes:lp(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,...Kt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Kt(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?sp(this.options.maxRetries)+1:1,i=null;if(e.signal?.aborted)throw us(e.signal);let s=e.signal===void 0?void 0:gs.get(e.signal);for(let a=0;a<o;a++){if(a>0){let u=this.backoffMs(a,i);if(cs(i)&&s!==void 0&&u>=s())throw i;await this.backoff(u,e.signal);}if(e.signal?.aborted)throw cs(i)&&s!==void 0&&s()<=0?i:us(e.signal);let l;try{l=await this.options.transport.request(e);}catch(u){if(ne.isAuthError(u)||se.isRefusal(u)||e.signal?.aborted||dp(u))throw u;i=new G("unavailable",0,String(u));continue}if(l.status>=200&&l.status<300||l.status===304)return l;let d=cp(l);if(!ip.has(l.status)||l.status===429&&!r)throw d;i=d;}throw i??new G("unavailable",0,"no attempt was made")}backoffMs(e,n){let r=n?.retryAfterSeconds,o=r!==void 0?r*1e3:2**(e-1)*250,i=2**(e-1)*250;return Math.min(Math.max(o,i),ap)}backoff(e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let o=this.options.clock,i=false,s=false,a,l=()=>{i||(i=true,s&&o.clearTimeout(a),n?.removeEventListener("abort",l),r());};n?.addEventListener("abort",l,{once:true}),a=o.setTimeout(l,e),s=true,i&&o.clearTimeout(a);})}};function lp(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 Kt(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function us(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function dp(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function cp(t){let e=mp(t),n=gp(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&ms.set(e,r),e}var up=new Map([["insufficient_funds","insufficient_funds"]]);function mp(t){let{status:e,body:n}=t,r=pp(n),o=t.retryAfterSeconds??yp(n),i=fp(n),s=i===void 0?void 0:up.get(i);if(s!==void 0)return new G(s,e,r,void 0,i);switch(e){case 304:return new G("not_modified",e,r);case 400:case 422:return new G("invalid",e,r,void 0,i);case 403:return new G("forbidden",e,r,void 0,i);case 404:return new G("not_found",e,r,void 0,i);case 402:return new G("insufficient_funds",e,r,void 0,i);case 409:return new G("conflict",e,r,void 0,i);case 412:return new G("precondition_failed",e,r,void 0,i);case 413:return new G("too_large",e,r,void 0,i);case 429:return new G("rate_limited",e,r,o,i);default:return new G("unavailable",e,r,o,i)}}function pp(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 gp(t){let n=t?.error?.details;return n===null?void 0:n}function fp(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function yp(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 ys(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function hs(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 bs(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function vs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}`;return t.client.delete(r,n?.signal)}async function _s(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 ws(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 ks(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 Rs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function As(t,e,n,r,o){let i=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(i,o?.signal)}async function xs(t,e,n,r,o){let i=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(i,o?.signal)}async function Ps(t,e,n,r){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.delete(o,r?.signal)}async function Ts(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 Es(t,e,n,r,o,i){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/finalize`;return t.client.post(s,o,i?.signal)}async function Is(t,e,n){let r=`/v1/games/${_(t.gameId())}/avatars-3d/${_(e)}/owned`;return t.client.get(r,n?.signal)}async function Cs(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 Ms(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.get(r,n?.signal)}async function Os(t,e,n){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Gs(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 Ls(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 Ds(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/items/${_(r)}`;return t.client.get(i,o?.signal)}async function $s(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 Fs(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/orders/${_(r)}`;return t.client.get(i,o?.signal)}async function qs(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}`;return t.client.get(i,o?.signal)}async function Ns(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 js(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 Do(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 Bs(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 Us(t,e,n){let r=`/v1/showcase/friends/${_(e)}`;return t.client.get(r,n?.signal)}async function Ws(t,e){let n=`/v1/games/${_(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function Hs(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}`;return t.client.get(r,n?.signal)}async function Vs(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 Ks(t,e){let n=`/v1/games/${_(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function Js(t,e){let n=`/v1/games/${_(t.gameId())}/players/me/passes`;return t.client.get(n,e?.signal)}async function or(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function zs(t,e,n){let r=`/v1/profiles/players/${_(e)}`;return t.client.get(r,n?.signal)}async function Xs(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 Ys(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return t.client.get(r,n?.signal)}async function Qs(t,e,n,r){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.get(o,r?.signal)}async function Zs(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function el(t,e,n){let r=`/v1/inventory/transfers/${_(e)}`;return t.client.get(r,n?.signal)}async function tl(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function nl(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 rl(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ol(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 il(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function al(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 sl(t,e){return t.client.get("/v1/characters",e?.signal)}async function ll(t,e,n,r){let o=`/v1/settings/${_(e)}/${_(n)}`;return t.client.get(o,r?.signal)}async function dl(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 cl(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 ul(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 ml(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 pl(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 gl(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function fl(t,e,n,r){let o=`/v1/games/${_(t.gameId())}/matches/${_(e)}/end`;return t.client.post(o,n,r?.signal)}async function yl(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 hl(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 bl(t,e,n,r,o){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.put(i,r,o?.signal)}async function vl(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/rewarded-placements/${_(r)}/availability`;return t.client.get(i,o?.signal)}async function _l(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function wl(t,e,n,r){let o=`/v1/characters/${_(e)}`;return t.client.patch(o,n,r?.signal)}async function Sl(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 kl(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 Rl(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.delete(r,n?.signal)}var j="gem-web-bridge",ar={min:1,max:1},hp=65536,Al=8,ir=5e3,xl=1024;var Jt=Object.create(null),sr="__malformed";var qo=Object.create(null),bp=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"]]);function lr(t){let e=qo[t];if(e!==void 0)return e;for(let[n,r]of bp)if(t.startsWith(n))return r}function St(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 vp(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 _p(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function wp(t){return /^[a-z_]+$/.test(t)}function Sp(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 $o(t,e,n){if(e>Al)return `nesting deeper than ${Al}`;if(++n.nodes>ir)return `more than ${ir} 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>xl)return `an array of ${t.length} entries, over the ${xl} limit`;n.bytes+=2;for(let a of t){let l=$o(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>ir)return `more than ${ir} values`;if(n.bytes+=a.length*3+4,n.bytes>n.cap)return `over the ${n.cap} byte limit`;let l=$o(s[a],e+1,n);if(l)return l}return null}function kp(t,e=hp){let n={nodes:0,bytes:0,seen:new Set,cap:e},r=$o(t,0,n);return r?`message contains ${r}`:n.bytes>e?`message is over the ${e} byte limit`:null}var Rp={origin:[St,"not a well-formed origin"],url:[vp,"not a safe absolute http(s) URL"],bcp47:[_p,"not a well-formed BCP 47 tag"],code:[wp,"not a code of lower-case letters and underscores"],gameRef:[Sp,"not a game id or web address"]};function Pl(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=Fo(i,r,o);if(s)return s}return null}function Fo(t,e,n){let r=e[1].toLowerCase();switch(r){case "u":return typeof t=="boolean"?null:Fo(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]=Rp[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`:Pl(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=Fo(s,o,i);if(a)return a}return null}default:return `${n}: unknown kind ${String(r)}`}}var Tl=Object.create(null);function E(t,e,n,r,o){return Jt[t]=n,r&&(qo[t]=r),Tl[t]=i=>{let s=kp(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}`:Pl(a,e,"")}}var H=["requestId","s",64],Ve=["outcome","e",["ok","declined","unavailable"]],Ke=["reason","S",64,"code"];E("gem.handshake",[["versions","o",[["min","i",1,1e3],["max","i",1,1e3]]],["capabilities","A",64,["","s",64]],["embedder","s",2048,"origin"],["unbidden","B"]],30);E("gem.handshake.accept",[["v","i",1,1e3],["capabilities","A",64,["","s",64]]],5);E("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);E("gem.token.denied",[H,["retryable","b"],["retryAfterMs","I",0,36e5],["reason","e",["chain_exhausted","unavailable"]],["correlationId","s",64]],30);E("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);E("gem.pause",[["paused","b"]],120);E("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);E("gem.cohorts",[["cohorts","a",8,["","o",[["experimentId","s",36],["variantKey","s",32]]]]],12,"cohorts");E("gem.earnAllowanceChanged",[],30,"earnAllowance");E("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");E("gem.deviceSettings",[["settings","J"]],12,"deviceSettings");E("gem.willTerminate",[["reason","e",["grant_expiring","session_ended","navigating","kill_switch"]],["graceMs","i",0,6e4]],10);E("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");E("gem.socketState",[["connected","b"],["reason","E",["connecting","dropped","watchdog","terminal"]]],12,"socketState");E("gem.seatedEvent",[["roomId","s",64]],60,"partySeating");E("gem.autoStartFailedEvent",[["roomId","s",64],["code","s",64]],30,"autoStartFailure");E("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");E("gem.signalEvent",[["event","e",["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]],["matchId","s",64],["data","j"]],1800,"p2p");E("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");E("gem.partyResult",[H,["partyId","S",64]],30,"parties");E("gem.clusterTarget",[["clusterTargetId","s",64],["clusterTargetIds","A",3,["","s",64]]],12,"clusterTarget");E("gem.devtools",[["action","e",["open","close","toggle"]]],30,"devtools");E("gem.screenshot",[["maxWidth","i",1,7680],["maxHeight","i",1,4320]],6,"screenshot");E("gem.screenshot.denied",[["reason","e",["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]],["retryable","b"]],12,"screenshot");E("gem.requestContext",[],12,"feedbackContext");E("gem.gameContext",[["context","j"]],12,"feedbackContext");E("gem.signal",[["signal","e",["join","offer","answer","ice","migrationAck","hostUnreachable"]],["matchId","s",64],["data","j"]],1200,"p2p");E("gem.dedicatedOffer",[["matchId","s",64],["sdp","s",10240],["intent","e",["initial","ice_restart","full_reconnect"]]],60,"dedicated");E("gem.partyRequest",[H],12,"parties");E("gem.ready",[],5);E("gem.engaged",[],5,"engagement");E("gem.progress",[["loaded","i",0,1099511627776],["total","i",0,1099511627776]],600);E("gem.requestToken",[H,["reason","e",["initial","expiring","rejected"]]],12);E("gem.requestLocalServer",[H,["gameRoomId","s",64]],6,"localHost");E("gem.localServer",[H,["serverId","S",128]],30,"localHost");E("gem.localServer.denied",[H,["retryable","b"],["reason","e",["refused","unavailable"]]],30,"localHost");E("gem.exit",[["reason","S",64]],5);E("gem.openExternal",[["url","s",2048,"url"]],6);E("gem.requestFullscreen",[["enabled","b"]],30);E("gem.audioState",[["muted","b"]],120,"audioState");E("gem.rewardCue",[["currencySlug","s",32],["expected","I",1,1e9],["origin","O",[["x","i",0,16384],["y","i",0,16384]]]],60,"rewardCue");E("gem.walletDisplay",[["visible","b"],["currencies","A",8,["","s",64]],["score","B"]],60,"walletDisplay");E("gem.controlsDeclare",[["uses","o",[["lookSensitivity","S",16,"code"],["gamepadLookSensitivity","S",16,"code"],["invertLookY","S",16,"code"],["touchMovement","S",16,"code"]]]],60,"controls");E("gem.menu",[["settings","b"],["items","A",4,["","o",[["id","s",32],["label","s",40]]]]],60,"gameMenu");E("gem.menuSelect",[["entry","e",["settings","item"]],["id","S",32]],60,"gameMenu");E("gem.gemCorner",[["corner","e",["top-left","top-right","bottom-left","bottom-right"]]],12,"gemCorner");E("gem.menuStyle",[["ground","S",7],["accent","S",7]],12,"menuStyle");E("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");E("gem.settingChange",[["id","s",40],["value","u",40,-1e6,1e6]],120,"gameSettings");E("gem.requestShare",[["params","a",16,["","o",[["key","s",64],["value","s",512]]]]],6,"share");E("gem.requestAvatarPicker",[["tab","E",["2d","3d"]]],6,"avatarPicker");E("gem.vibrate",[["pattern","a",99,["","i",0,1e4]]],600,"vibration");E("gem.frameStats",[["fps","i",0,1e3],["frameTimeP95Ms","i",0,1e5],["counts","E",["pageFrames","gameDraws"]]],120,"frameStats");E("gem.portraitBorders",[["name","S",40]],60,"portraitBorders");E("gem.error",[["code","e",["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]],["message","S",256]],60);E("gem.requestPurchase",[H,["purchaseKind","e",["item","recipe"]],["targetId","s",64],["currencySlug","s",32],["quantity","I",1,10],["catalogId","S",64]],12,"purchases");E("gem.requestAvatar3dPurchase",[H,["itemId","s",64],["currencySlug","s",32]],12,"avatar3dPurchases");E("gem.purchaseResult",[H,Ve,Ke,["purchaseId","S",64]],30,"purchases");E("gem.deviceSettings.put",[H,["settings","j"]],30,"deviceSettings");E("gem.deviceSettings.result",[H,["outcome","e",["stored","too_large","unavailable"]]],30,"deviceSettings");E("gem.requestAd",[H,["placement","s",32],["format","e",["interstitial","rewarded"]]],6,"ads");E("gem.adResult",[H,["outcome","e",["shown","no_ad","unavailable"]]],12,"ads");E("gem.signalMoment",[H,["kind","e",["level_end","run_end","match_end","menu_return","other_break"]],["placement","S",32],["wall","B"]],6,"moments");E("gem.momentResult",[H,["shown","b"]],12,"moments");E("gem.requestSignIn",[H],6,"signIn");E("gem.signInResult",[H,["outcome","e",["signed_in","declined","unavailable"]]],12,"signIn");E("gem.requestFriendChallenge",[H,["playerId","s",64],["template","s",64],["params","J"]],12,"friendChallenges");E("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");E("gem.requestAppLinks",[H],12,"appLinks");E("gem.appLinksResult",[H,Ve,Ke,["arcade","O",[["store","e",["app_store","google_play"]]]],["game","O",[["store","e",["app_store","google_play"]]]]],30,"appLinks");E("gem.requestOpenApp",[H,["target","e",["arcade","game"]]],6,"appLinks");E("gem.openAppResult",[H,Ve,Ke],30,"appLinks");var El=E("gem.requestOpenGame",[H,["ref","s",40,"gameRef"]],6,"openGame");E("gem.openGameResult",[H,Ve,Ke],30,"openGame");E("gem.requestSimilarGames",[H,["limit","I",1,24]],12,"openGame");E("gem.similarGamesResult",[H,Ve,Ke,["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);E("gem.requestStoreOffers",[H],12,"store");E("gem.storeOffersResult",[H,Ve,Ke,["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);E("gem.requestStorePurchase",[H,["skuId","s",64]],12,"store");E("gem.storePurchaseResult",[H,Ve,Ke],30,"store");E("gem.storePurchaseSettled",[["skuId","s",64]],30,"store");E("gem.requestStoreOfferSheet",[H,["skuId","s",64]],12,"storeOfferSheet");E("gem.storeOfferSheetResult",[H,Ve,Ke],30,"storeOfferSheet");var dr=Object.freeze(Tl);Jt.__malformed=60;Object.freeze(Jt);Object.freeze(qo);var de={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},zt=class{constructor(e=de){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Jt[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 kt(t,e){return t.toLowerCase()===e.toLowerCase()}function Je(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function cr(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:Je(n.hostname)&&Je(r.hostname)}function Il(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 ur=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 jo(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 Cl="inventory",Rt=t=>typeof t=="number"?t:0,Xt=t=>typeof t=="string"?t:"";function No(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 Ml(t){let e=t??{};return {itemDefinitionId:Xt(e.item_definition_id),instanceId:Xt(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 Ap(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:No(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(s=>{let a=s??{};return {bucket:Xt(a.bucket),balance:Rt(a.balance)}}):void 0;return {currencyId:Xt(o.currency_id),total:Rt(o.total),...i===void 0?{}:{buckets:i}}}),items:No(e.items,Ml),progressions:No(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:Xt(o.progression_definition_id),currentValue:Rt(o.current_value),completionCount:Rt(o.completion_count),isCompleted:o.is_completed===true,...jo(o)}}),...n===void 0?{}:{etag:n}}}var mr=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Cl}#buckets`:Cl;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 Ds(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(Ml):[]}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 Ls(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 Ap(n)}};var xp={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},Pp=new Set(Object.keys(xp));function Ol(t){return typeof t=="string"&&Pp.has(t)?t:"error"}var ze=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var re=t=>typeof t=="string"?t:"",Tp=t=>typeof t=="string"?t:re(t&&typeof t=="object"?t.type:void 0),Ee=t=>typeof t=="number"?t:0;function Ep(t){let e=t??{};return {prerequisiteType:re(e.prerequisite_type),referenceId:re(e.reference_id),required:Ee(e.required),current:Ee(e.current)}}function Yt(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 pr(){return crypto.randomUUID()}var Ip="recipe-usage",Gl=100;function gr(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:re(e.currency_id),bucket:re(e.bucket),delta:Ee(e.delta),balanceAfter:Ee(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:re(e.item_definition_id),instanceId:re(e.instance_id),delta:Ee(e.delta),quantityAfter:Ee(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:re(e.progression_definition_id),delta:Ee(e.delta),valueAfter:Ee(e.value_after),completed:e.completed===true};default:return {kind:"other",type:re(e.type)}}}function Cp(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:Ee(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(gr):[]}}function Mp(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(Cp):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(gr):[],consumed:Array.isArray(e.consumed)?e.consumed.map(gr):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(gr):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Op(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:Ee(n.price)}}}function Gp(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 Ll(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 fr=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(()=>ks(this.api,this.entity.type,this.entity.id,{operations:e.map(Ll),source:n.source??"play",nonce:pr()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Yt(r)}async createMany(e,n={}){return this.write(()=>Ss(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Ll),nonce:pr()})),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 Ns(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(Ep):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>Tp(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(Ip,[],async()=>{let n=await js(this.api,this.entity.type,this.entity.id,{limit:Gl})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(Gp),truncated:r.length>=Gl}})}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,g=await this.write(()=>Ts(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:pr()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...Mp(g)}}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([Xs(this.api,n.signal===void 0?{}:{signal:n.signal}),or(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(g=>g.slug);throw new ze("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 ze("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=p=>o.currencies.find(f=>f.currency_id===p)?.slug??p,g=a.platform_prices.map(p=>`${c(p.platform_currency_id)} ${p.price}`);throw new ze("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${g.length===0?"nothing":g.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new ze("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let u=await this.write(()=>ol(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:pr(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return Op(u)}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(()=>hs(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Yt(o)}async maxProgression(e,n,r){let o=await this.write(()=>yl(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Yt(o)}async claimProgression(e,n){let r=await this.write(()=>_s(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Yt(r)}async resetProgression(e,n){let r=await this.write(()=>kl(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Yt(r)}async write(e){return this.cache.invalidate(),e()}};var Bo=t=>typeof t=="string"?t:"",Lp=t=>typeof t=="number"?t:0;function Dl(t){let e=t??{};return {orderId:Bo(e.order_id),status:Bo(e.status),source:Bo(e.source),createdAt:Lp(e.created_at)}}var yr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await dl(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(Dl):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Fs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Dl(r)}};var Dp=["live"],Uo=6e4,$l=864e5;function $p(t){let e=t?.passes;if(!Array.isArray(e))return Object.freeze([]);let n=e.flatMap(r=>{let o=r??{};if(typeof o.pass!="string"||o.pass==="")return [];let i=o.held===true,s=i&&typeof o.ends_at=="string"?o.ends_at:null;return [Object.freeze({pass:o.pass,held:i,endsAt:s})]});return Object.freeze(n)}function Fp(t){let n=t.flatMap(r=>r.endsAt===null?[]:[Date.parse(r.endsAt)]).filter(r=>Number.isFinite(r));return n.length===0?null:Math.min(...n)}function Fl(t,e,n={}){let{watch:r}=n,o=new Set,i=null,s=0,a=null,l=Uo,d=()=>{a!==null&&r?.clock.clearTimeout(a.handle),a=null;},u=k=>{d(),!(r===void 0||o.size===0)&&(a={handle:r.clock.setTimeout(R,k)});},c=k=>{let P=Fp(k);if(P===null||r===void 0){d();return}let h=P-r.clock.now();u(h>0?Math.min(h,$l):Uo);},g=k=>{r?.log?.(`[gem] a passes 'changed' listener threw: ${k instanceof Error?k.message:String(k)}`);},p=k=>{let P=i!==null&&JSON.stringify(i)!==JSON.stringify(k);if(i=k,l=Uo,c(k),!!P)for(let h of [...o])try{let S=h(k);typeof S?.then=="function"&&S.then(void 0,g);}catch(S){g(S);}},f=()=>{let k=s;return e.read("passes",Dp,()=>Js(t)).then(P=>{if(k!==s)return f();let h=$p(P);return p(h),h})},y=()=>{f().catch(()=>{u(l),l=Math.min(l*2,$l);});};function R(){s+=1,e.invalidate(),d(),r!==void 0&&o.size>0&&y();}return {api:{list:f,async get(k){return (await f()).find(h=>h.pass===k)??Object.freeze({pass:k,held:false,endsAt:null})},on(k,P){let h=o.size===0;return o.add(P),h&&r!==void 0&&(i===null?y():c(i)),()=>{o.delete(P),o.size===0&&d();}}},recheck:R}}var ql=t=>typeof t=="number"?t:0,qp=t=>typeof t=="string"?t:"";function Np(t){let e=t??{};return {progressionDefinitionId:qp(e.progression_definition_id),currentValue:ql(e.current_value),completionCount:ql(e.completion_count),isCompleted:e.is_completed===true,...jo(e)}}var hr=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 qs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Np(i)}catch{return o??null}}};var Qt=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,u=r().then(c=>(i&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===u&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=u,u}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 jp(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Bp=new Set(tr);function Up(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Bp.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function br(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return ds(async(n,r)=>{let o;try{o=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 i;try{i=new URL(o.href.replace(/\/+$/,"")+n.path);}catch{throw new se(`${JSON.stringify(typeof n.path=="string"?jp(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 se(`${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 p=o.username!==""||o.password!=="",f=i.username!==o.username||i.password!==o.password,y=p?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new se(`the ${y} 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[p,f]of Object.entries(t.defaultQuery??{}))i.searchParams.has(p)||i.searchParams.set(p,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(p){throw new se(`the body of ${n.method} ${JSON.stringify(i.pathname)} could not be serialised to JSON: ${String(p)}. 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},...Up(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 p=await l.text();if(p.length>0)try{d=JSON.parse(p);}catch{d=p;}}let u=l.headers.get("etag"),c=Wo(l.headers.get("retry-after")),g=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...u===null?{}:{etag:u},...c===void 0?{}:{retryAfterSeconds:c},...g===null||g===""?{}:{invocationId:g}}},t)}function Wo(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 Ho(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 vr(t){try{let e=Ho(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var oe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},Wp=3e4,Hp=5e3,Nl=6e4,Vp=2**31-1,jl="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",Kp=/^[A-Za-z0-9_]{1,64}$/;function qe(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(!Kp.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Bl(t,e){let n=new AbortController,r=Date.now()+e;fs(n.signal,()=>r-Date.now());let o=AbortSignal.timeout(e),i=()=>n.abort(o.reason),s=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(o.addEventListener("abort",i,{once:true}),t?.addEventListener("abort",s,{once:true})),{signal:n.signal,release:()=>{o.removeEventListener("abort",i),t?.removeEventListener("abort",s);}}}function Vo(t,e){return t.aborted&&e?.aborted!==true}var Jp=new Set(["x-ms-blob-type"]),zp=/^[ -~]+$/;function Xp(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new oe("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(!Jp.has(i))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof o!="string"||!zp.test(o))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(i in n)throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function Ko(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"}function Yp(t){return t?.code==="save_conflict"}function Ul(t){return t instanceof G&&t.reason==="rate_limited"}async function Wl(t,e){let n=await vr(e);return new G("rate_limited",429,`the save ${t} answered 429: too many save calls. ${n}`.trim(),Wo(e.headers.get("retry-after")))}function _r(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Qp(t,e,n,r,o){let i=false,s=()=>i?false:(i=true,a.detach?.(),true),a={signal:n.signal,budget:r,deadlineAt:Date.now()+r,teardown:n.teardown===true,overwrite:n.overwrite===true,identity:o,resolve:l=>{s()&&t(l);},reject:l=>{s()&&e(l);},detach:void 0};return a}function Hl(t,e){return t!==null&&e!==null&&e!==t}function Vl(t){return new oe("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 wr=class{constructor(e,n,r={},o){this.api=e;this.entity=n;this.options=r;this.identity=o;}api;entity;options;identity;versions=new Map;seq=0;versionsOf=null;writes=new Map;holdUntil=0;async put(e,n,r={}){let o;try{o=JSON.stringify(n);}catch(i){throw new oe("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}. Retrying stores the same unserialisable value.`)}if(o===void 0)throw new oe("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){if(qe(e),r.signal?.aborted)throw _r(r.signal);let o=this.budget(r.timeoutMs),i=this.slotWrites(e);return new Promise((s,a)=>{let l=i.queued;l?.release();let d=l?.waiters[l.waiters.length-1];d!==void 0&&this.holdOwn(i,d);let u=this.identity?.()??null;for(let c of l?.waiters.slice()??[])Hl(c.identity,u)&&this.drop(i,c,Vl(e));i.queued=this.queue(i,n,r,Qp(s,a,r,o,u),l?.waiters??[]),i.wake?.(),this.pump(e,i);})}holdOwn(e,n){let{signal:r}=n,o=n.deadlineAt-Date.now();if(r?.aborted)return this.drop(e,n,_r(r));if(o<=0)return this.drop(e,n,this.timeout("save",n.budget));let i=AbortSignal.timeout(o),s=()=>this.drop(e,n,this.timeout("save",n.budget)),a=()=>{r&&this.drop(e,n,_r(r));};i.addEventListener("abort",s,{once:true}),r?.addEventListener("abort",a,{once:true}),n.detach=()=>{i.removeEventListener("abort",s),r?.removeEventListener("abort",a);};}drop(e,n,r){let o=e.queued?.waiters,i=o?.indexOf(n)??-1;i>=0&&o?.splice(i,1),n.reject(r),e.wake?.();}queue(e,n,r,o,i){let{budget:s}=o,a=[...i,o],l=AbortSignal.timeout(s),d=p=>{if(e.queued===g){this.take(e,g);for(let f of a)f.reject(p);e.wake?.();}},u=()=>d(this.timeout("save",s)),c=()=>{r.signal&&d(_r(r.signal));};l.addEventListener("abort",u,{once:true}),r.signal?.addEventListener("abort",c,{once:true});let g={bytes:n,options:r,budget:s,deadlineAt:o.deadlineAt,identity:o.identity,waiters:a,release:()=>{l.removeEventListener("abort",u),r.signal?.removeEventListener("abort",c);}};return g}async pump(e,n){if(!n.running){n.running=true;try{for(let r=n.queued;r!==void 0;r=n.queued){let o=Date.now(),i=this.holdUntil-o;if(i>0){if(i>=r.deadlineAt-o){this.take(n,r);for(let l of r.waiters)l.reject(this.held(e,i));continue}for(let l of r.waiters.slice(0,-1))i>=l.deadlineAt-o&&this.drop(n,l,this.held(e,i));}let s=Math.max(i,this.spacing(n,r,o));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=o;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 o=this.options.minWriteIntervalMs??Hp,i=Math.min(...n.waiters.map(s=>s.deadlineAt-s.budget/2));return Math.min(e.lastSentAt+o,i)-r}pause(e,n){return new Promise(r=>{let o=()=>{clearTimeout(i),e.wake===o&&(e.wake=void 0),r();},i=setTimeout(o,Math.min(n,Vp));e.wake=o;})}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(!Ul(e))return;let n=e.retryAfterSeconds,r=n===void 0?Nl:Math.min(n*1e3,Nl);this.holdUntil=Math.max(this.holdUntil,Date.now()+r);}held(e,n){let r=Math.ceil(n/1e3);return new G("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:o,options:i,budget:s}=n,a=i.contentType??"application/octet-stream",l=Bl(i.signal,Math.max(0,n.deadlineAt-Date.now()));try{let d=await Sl(this.api,this.entity.type,this.entity.id,e,{size_bytes:o.byteLength,content_type:a,...r,...i.metadata===void 0?{}:{metadata:i.metadata}},{signal:l.signal});if(typeof d.upload_url!="string"||typeof d.session_id!="string")throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let u=Xp(d.upload_headers,e),c,g=this.options.fetch??globalThis.fetch.bind(globalThis);try{c=await g(d.upload_url,{method:"PUT",headers:{"content-type":a,...u},body:o,credentials:"omit",signal:l.signal});}catch(f){throw Vo(l.signal,i.signal)?this.timeout("upload",s):new oe("upload_failed",`${jl} for PUT. Underlying error: ${f}`)}if(c.status===429)throw await Wl("upload",c);if(!c.ok){let f=await vr(c);throw new oe("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 p=Ko(await Es(this.api,this.entity.type,this.entity.id,e,{session_id:d.session_id},{signal:l.signal}));return this.remember(e,p.etag?{kind:"etag",etag:p.etag}:void 0),p}catch(d){throw Yp(d)?new oe("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,i.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(o){throw new oe("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${o}`)}}async getBytes(e,n={}){qe(e);let r=this.budget(n.timeoutMs),o=Bl(n.signal,r),i=this.seq;try{let s;try{let u=await Do(this.api,this.entity.type,this.entity.id,e,{signal:o.signal});if(!u.modified)return this.remember(e,{kind:"empty"},i),null;s=u.body;}catch(u){if(Jo(u))return this.remember(e,{kind:"empty"},i),null;throw u}if(typeof s.download_url!="string")throw new oe("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),l;try{l=await a(s.download_url,{credentials:"omit",signal:o.signal});}catch(u){throw Vo(o.signal,n.signal)?this.timeout("download",r):new oe("download_failed",`${jl} for GET. Underlying error: ${u}`)}if(l.status===429)throw await Wl("download",l);if(!l.ok){let u=await vr(l);throw new oe("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. ":"")+u)}let d=new Uint8Array(await l.arrayBuffer());return this.remember(e,s.etag?{kind:"etag",etag:s.etag}:void 0,i),d}catch(s){throw this.slots().get(e)===void 0&&this.remember(e,{kind:"failed"}),this.noteRateLimit(s),this.rethrow(s,n.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,n={}){try{let r=await Do(this.api,this.entity.type,this.entity.id,qe(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Ko(r.body):null}catch(r){if(Jo(r))return null;throw r}}async list(e={}){let n=await cl(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(Ko),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await xs(this.api,this.entity.type,this.entity.id,qe(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Jo(r))throw r}this.remember(e,{kind:"empty"});}precondition(e,n){if(Hl(n.identity,this.identity?.()??null))throw Vl(e);if(n.waiters.some(o=>o.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 oe("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 o=this.slots(),i=o.get(e);r!==void 0&&i!==void 0&&i.kind!=="failed"&&i.seq>r||(this.seq+=1,n===void 0?o.delete(e):o.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??Wp}timeout(e,n){return new oe("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof oe||Ul(e)?e:Vo(r,n)?this.timeout(o,i):e}};function Zp(t){try{return Lo(t)}catch{return t}}function zo(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"?Zp(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Sr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await ll(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>zo(o)):[]}async get(e,n={}){try{let r=await Gs(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?zo(r.body,r.etag):null}catch(r){if(Kl(r))return null;throw r}}async put(e,n,r={}){let o=await hl(this.api,this.entity.type,this.entity.id,e,{value:nr(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return zo(o)}async delete(e,n){try{await As(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 Xo(t,e,n={}){let r=new Qt(de,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new mr(t,e,r);return {settings:new Sr(t,e),inventory:o,saves:new wr(t,e,n.saves??{},n.identity),currencies:new ur(o,n.resolveCurrencyId),mutations:new fr(t,e,r),orders:new yr(t,e),progressions:new hr(t,e,o)}}function Jl(t,e,n={}){let r=new Qt(de,n.identity),o=Fl(t,r,n);return {scope:{...Xo(t,e,n),passes:o.api},recheckPasses:o.recheck}}var Yo={type:"players",id:"me"};var ot=t=>typeof t=="string"?t:"",At=t=>typeof t=="number"?t:0;function kr(t,e){let n=e??{},r=ot(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:ot(n.player_id),gameId:ot(n.game_id),channel:ot(n.channel)||"release",name:ot(n.name),slotIndex:At(n.slot_index),isActive:n.is_active!==false,createdAt:ot(n.created_at),updatedAt:ot(n.updated_at)}}var Rr=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=Xo(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 sl(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>kr(this.scope,o)):[]}async get(e,n){let r=await Ms(this.api,e,n===void 0?{}:{signal:n});return kr(this.scope,r)}async create(e){let n=await ws(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return kr(this.scope,n)}async update(e,n,r){let o=await wl(this.api,e,{name:n},r===void 0?{}:{signal:r});return kr(this.scope,o)}async delete(e,n){await Rl(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await Zs(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:At(r?.total_slots),availableSlots:At(r?.available_slots),activeCharacterCount:At(r?.active_character_count),defaultMaxSlots:At(r?.default_max_slots),purchasedExtraSlots:At(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var Yl="[gem: use gem.text.toPlain()]",zl=new Set,Xl;function eg(t){try{if(zl.has(t))return;let e=globalThis.location;if(Xl??=!!e?.port&&Je(e.hostname??""),!Xl)return;zl.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${Yl}. 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 eg(this.#n),Yl}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 it={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 xt=t=>typeof t=="string"?t:"";function Ar(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:xt(e.transfer_id),status:xt(e.status),sourceEntityId:xt(e.source_entity_id),targetEntityId:xt(e.target_entity_id),...n===void 0?{}:{message:he(n,"transfer.message")},createdAt:xt(e.created_at),expiresAt:xt(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function tg(){return crypto.randomUUID()}var xr=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 rl(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:tg()},e.signal===void 0?{}:{signal:e.signal});return Ar(n)}async list(e={}){let r=await pl(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(Ar):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await el(this.api,e,n===void 0?{}:{signal:n});return Ar(r)}async accept(e,n){return this.resolve(()=>ys(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>_l(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>bs(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Ar(await e())}};var ng=t=>typeof t=="string"?t:"",rg=t=>typeof t=="string"&&t?t:void 0,og=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 ig(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=og(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,u)=>{let c=ng(l.id);if(!c)throw new pe("config_malformed",`${d}[${u}] 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:Ql(i),currency:Ql(s)}}var pe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Zl=10*1024*1024,ed=15e3,td=new Set(["dev","test","release"]);function ag(t){if(!td.has(t))throw new pe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...td].join(", ")}. gem-api would reject the assignment read.`);return t}var Pr=t=>typeof t=="number"?t:0,Qo=t=>typeof t=="string"?t:"";function sg(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:Qo(o.entry_id),weight:Pr(o.weight),dropRate:Pr(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:Qo(e.loot_table_id),name:Qo(e.name),rollCount:Pr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Pr(e.total_weight),entries:n}}var Tr=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 Os(this.api,e,n===void 0?{}:{signal:n});return sg(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??ed),n;try{let l=await Cs(this.api,ag(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=rg(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??ed}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=>Ho(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>Zl)throw new pe("config_too_large",`the config document is ${s.length} bytes, over the ${Zl} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new pe("config_malformed",`config document is not JSON: ${String(l)}`)}return ig(a)}};var nd=400,Ie=t=>typeof t=="string"?t:"",lg=/(?:Z|[+-]\d{2}:?\d{2})$/i;function at(t){let e=Ie(t);if(!lg.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var dg=/^[0-9a-f]{1,64}$/,cg=/^[0-9a-f]{16}$/,ug=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,mg=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Zo(t){let e=Ie(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 pg=4096,gg=new TextEncoder;function fg(t){let e=Ie(t.challenge_data),n=Ie(t.challenge_data_hash);return e===""||!cg.test(n)?{}:gg.encode(e).length>pg?{}:{data:e,dataHash:n}}function yg(t){let e=t??{},n=at(e.period_start_at),r=at(e.period_ends_at);if(n===0||r===0)return;let o=Ie(e.slug),i=Ie(e.seed),s=Zo(e.period_local_date),a=Ie(e.boundary),l=Ie(e.reset_time);return {id:Ie(e.progression_definition_id),...o===""?{}:{slug:o},window:Ie(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:ug.test(a)?a:"",resetTime:mg.test(l)?l:"",seed:dg.test(i)?i:"",...fg(e)}}function Pt(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 Er(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(yg).filter(n=>n!==void 0):[]}var Zt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;Pt(n);let r=await al(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return Er(r)}};function Ce(t){return typeof t=="string"&&t!==""?t:void 0}var rd=new Set(["localhost","127.0.0.1","[::1]"]);function st(t){return Tt(t)}function Tt(t){let e=Ce(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:"&&rd.has(n.hostname)))return e}var hg=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,bg=/^[a-z][a-z0-9_]{0,31}$/;function vg(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let o=r??{},i=Ce(o.family),s=Ce(o.avatar_3d_id),a=st(o.model_url),l=st(o.icon_url);i===void 0||!bg.test(i)||n.has(i)||s===void 0||!hg.test(s)||a===void 0||l===void 0||(n.add(i),e.push({family:i,id:s,modelUrl:a,iconUrl:l}));}return e}function _g(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=Ce(r.item_id),i=st(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function Pe(t){let e=t??{},n=Ce(e.player_id),r=Ce(e.display_name),o=Ce(e.discriminator),i=Ce(e.display_tag),s=Ce(e.avatar_icon_id),a=st(e.avatar_icon_url),l=Ce(e.avatar_3d_id),d=st(e.avatar_3d_model_url),u=st(e.avatar_3d_icon_url),c=vg(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},...u===void 0?{}:{avatar3dIconUrl:u},...c===void 0?{}:{avatars3d:c},badges:_g(e.badges)}}var wg=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function ei(t){if(t===void 0)return;let e=st(t);if(e===void 0)return;let n=new URL(e);return rd.has(n.hostname)||wg.has(n.origin)?e:void 0}var od=100,sd=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function ti(t){let{periodsBack:e,period:n,playerId:r}=t;if(Pt(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!sd.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 ld(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!sd.test(e))return;let n=Zo(t.period_local_date),r=at(t.period_start_at),o=at(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:at(t.opens_at),closesAt:at(t.closes_at),final:t.final===true}}var en=t=>typeof t=="string"?t:"",Et=t=>typeof t=="number"?t:0,tn=t=>typeof t=="string"?t:void 0,Sg=t=>typeof t=="number"?t:void 0,dd={player:"players",character:"characters"};function kg(t,e){let n=t??{},r=tn(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(dd,n.entity_type)?n.entity_type:void 0,i=cd(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:Et(n.rank),occurredAt:Et(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 id(t,e){let n=t??{},r=tn(n.bucket_1),o=tn(n.bucket_2),i=Sg(n.update_frequency_seconds),s=ld(n);return {leaderboardType:en(n.leaderboard_type),runType:en(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(a=>kg(a,e)):[],generatedAt:Et(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...s===void 0?{}:{period:s}}}function ad(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=cd(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:Et(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function cd(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 Rg(t,e,n){let r=t??{},o=tn(r.bucket_1),i=tn(r.bucket_2),s=ld(r);return {leaderboardType:en(r.leaderboard_type),runType:en(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(ad).filter(a=>a!==void 0):[],personalBest:ad(r.personal_best)??null,totalRuns:Et(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:Et(r.generated_at),...s===void 0?{}:{period:s}}}var nn=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=ti(n),o=await Vs(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 id(o,false)}async friends(e,n={}){let r=ti(n),o=await Bs(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 id(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>od)throw new TypeError(`limit must be an integer between 1 and ${od}, got ${String(l)}`)}let i=ti(o),s=await $s(this.#e,e,dd[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"&&en((s??{}).entity_id)||r;return Rg(s,n,a)}};var Ir=t=>typeof t=="string"?t:"",ni=t=>typeof t=="number"?t:0;function ud(t){let e=t??{};return {playerId:Ir(e.player_id),key:Ir(e.key),value:e.value,updatedAt:ni(e.updated_at)}}function Ag(t){let e=t??{};return {...Pe(e),playerId:Ir(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:ni(e.updated_at)}}function xg(t){return t?.reason==="not_found"}var rn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await Us(this.api,qe(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:Ir(o.key),entries:Array.isArray(o.entries)?o.entries.map(Ag):[],generatedAt:ni(o.generated_at)}}async of(e,n,r={}){try{return ud(await Qs(this.api,e,qe(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(xg(o))return null;throw o}}async set(e,n,r={}){if(qe(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 ud(await bl(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Ps(this.api,r,qe(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var Pg="gemChallenge",md=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pd(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(Pg)??void 0}catch{return}}var lt=class extends G{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});}},Cr=t=>typeof t=="string"?t:void 0;function gd(t){let e=t??{};return {...Pe(e),playerId:Cr(e.player_id)??""}}function fd(t){let e=t.has_more===true?Cr(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function Tg(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(gd):[],...fd(e)}}var ri=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Eg(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 yd(t){let e=t??{},n=ri(e.opened_at),r=ri(e.answered_at);return {id:Cr(e.item_id)??"",from:gd(e.sender),template:Cr(e.template)??"",params:Eg(e.params),createdAt:ri(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function Ig(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(yd):[],...fd(e)}}function Cg(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var on=class{#e;#n;#i;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#i=n.launchedChallengeId;}async list(e={}){let n=await ml(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Tg(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await ul(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Ig(n)}async launchedChallenge(e={}){let n=this.#i;if(n===void 0||!md.test(n))return null;try{return yd(await Hs(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(Cg(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!md.test(e))throw new G("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await gl(this.#e,e);}};var Mg=0;function _e(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++Mg)}-${String(Date.now())}-${t}`}}var Og=12e4,hd=8,Gg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Lg=/^[a-z0-9][a-z0-9_-]{0,63}$/;function an(t,e,n={}){return new lt(new G("invalid",400,e,void 0,t),n)}function Dg(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function $g(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!Gg.test(e))return {error:an("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!Lg.test(n))return {error:an("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(!Dg(r))return {error:an("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:an("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return i.length>hd?{error:an("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(hd)}`)}:{playerId:e,template:n,params:o}}function Fg(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 lt(new G("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 lt(new G("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 qg(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function bd(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=$g(n);if("error"in r)return Promise.reject(r.error);let o=`challenge-${_e()}`;return new Promise((i,s)=>{let a={},l=u=>{e.delete(o)&&(t.clock.clearTimeout(a.timer),"error"in u?s(u.error):i(u.outcome));};e.set(o,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??Og);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 (${qg(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(Fg(n));}}}var Mr=t=>typeof t=="string"?t:void 0;function Ng(t){let e=t??{},n=Mr(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Mr(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Or=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await or(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=Ng(i);s!==void 0&&o.push(s);}return o}},oi=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function jg(t){let e=t??{},n=Mr(e.currency_id);if(n===void 0||n==="")return;let r=oi(e.limit),o=Math.min(oi(e.earned),r),i=Math.min(oi(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:Mr(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 vd(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 Gr=class{#e;#n;#i;constructor(e,n,r){this.#e=e,this.#n=n,this.#i=r;}async get(e={}){let r=(await Ks(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=jg(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)??(()=>{})}},sn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Or(e),this.earnAllowance=new Gr(e,n,r);}};var ii=t=>typeof t=="string"?t:"",_d=t=>typeof t=="number"?t:0;function Bg(t){let e=t??{};return {key:ii(e.key),visibility:ii(e.visibility),value:e.value,updatedAt:_d(e.updated_at)}}function Ug(t){let e=t??{};return {...Pe(e),playerId:ii(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Bg):[],generatedAt:_d(e.generated_at)}}function Wg(t){return t?.reason==="not_found"}var ln=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return Ug(await zs(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Wg(r))return null;throw r}}};var Hg=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]]),dn=class extends G{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:Hg.get(this.code))??super.retryable}},Xe=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Vg(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof G?Jg(i):i}return Kg(o)}};function Vg(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 Kg(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 Jg(t){let{details:e,invocationId:n}=ps(t),o=e?.untrusted?.message,i=e?.reason;return new dn(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 Lr(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 zg=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],ai="gem_";function si(t){return t.startsWith(ai)}function Xg(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function Yg(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 Dr(t,e,n){if(li(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=Yg(Xg(`${t}:${e}`))%r;return typeof n=="number"?o:n[o]}function li(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 wd=1e4,Sd=50,Qg=500,Zg=65536-4*1024,ef=24*1024;function kd(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 tf=6e4;function nf(t){let e=new Map;for(let n of t??[]){let r=new Set;for(let[o,i]of Object.entries(n.dimensions??{})){let s=i?.range;typeof s=="object"&&s!==null&&r.add(o);}r.size>0&&e.set(n.id,r);}return e}function rf(t,e){if(e===void 0)return t;let n=null,r={};for(let[o,i]of Object.entries(t.measures))e.has(o)?(n??={...t.dimensions})[o]=String(i):r[o]=i;return n===null?t:{dimensions:n,measures:r}}var Rd=t=>typeof t=="number"?t:0,of=t=>typeof t=="string"?t:"";function $r(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function af(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:Rd(i.index),code:of(i.code)}}):[];return {accepted:Rd(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function di(){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 sf(t){return t?.retryable===true}var cn=class{#e;#n;#i;#h;#t=[];#b={};#a=0;#s=null;#v=false;#_=false;#m=0;#w=0;#S=0;#r=false;#k=null;#l=null;#c=false;#o=false;#p=false;#R=false;#A=false;#g=void 0;#x=false;#P=0;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#i=Math.max(wd,e.options?.flushIntervalMs??wd),this.#h=Math.max(1,Math.floor(e.options?.maxQueue??Qg));}track(e,n={}){if(!this.#n||this.#r)return;if(si(e)){this.#A||(this.#A=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.#T(e,kd({...this.#b,...n}));let r=this.#C();this.#g===void 0&&!this.#x&&r!==null&&r!==""&&(this.#x=true,this.#M());}setContext(e){this.#b={...this.#b,...e};}async experiment(e,n){li(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"?Dr(e,r,n):Dr(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return $r();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.")),$r();let r=e.keepalive===true;if(!r&&this.#e.declarations!==void 0&&this.#t.some(d=>!si(d.name))&&await this.#M(),this.#I(),this.#t.length===0||this.#m>0&&!r)return $r();this.#u();let o=this.#t.splice(0,this.#G(r)),i=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:di(),sent_at_ms:s,events:o.map(d=>Ad(d,s,this.#g?.get(d.name)))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await nl(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),u=af(d,i);return this.#w=0,this.#S=0,this.#L(u),u}catch(d){throw sf(d)?(this.#O(o,i),this.#w+=1,this.#S=this.#e.clock.now()+Lr(this.#w,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.#T(e,kd(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:di(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Sd?this.#f():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.#f({keepalive:true});}setPaused(e){this.#r||e===this.#v||(this.#v=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#_||(this.#_=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}#T(e,n){let{dimensions:r,measures:o}=n;for(this.#I();this.#t.length>=this.#h;)this.#t.shift(),this.#a+=1;this.#t.push({uid:di(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=Sd?this.#f():this.#d();}#f(e={}){if(e.keepalive!==true&&this.#E()>0){this.#d();return}this.flush(e).catch(()=>{});}#E(){return Math.max(0,this.#S-this.#e.clock.now())}#O(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#h;)this.#t.shift(),this.#a+=1;}#G(e){let n=e?ef:Zg,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(Ad(s,0,this.#g?.get(s.name))).length+1,o>n)return Math.max(1,i)}return r}#d(){this.#s!==null||this.#v||this.#_||this.#o||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#f();},Math.max(this.#i,this.#E())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#I(){let e=this.#D();e===null||e===""||(this.#k!==null&&this.#k!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#k=e);}#L(e){for(let n of e.rejected)this.#y(`[gem] analytics: an event was refused (${n.code}). `+lf(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}}#D(){try{return this.#e.playerId()}catch{return null}}async#M(){let e=this.#e.declarations;if(e!==void 0&&!(this.#e.clock.now()<this.#P))try{this.#g=nf(await e());}catch{this.#P=this.#e.clock.now()+tf;}}};function Ad(t,e,n){let{dimensions:r,measures:o}=rf(t,n);return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:r,measures:o}}function lf(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 un(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 df=2e3,cf=5e3;function Pd(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,u=null;s=c=>{d||(d=true,r=null,t.clock.clearTimeout(u),l(c));},u=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??df);});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 !xd(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=u=>{o.delete(d)&&(t.clock.clearTimeout(l),a(u));};o.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??cf);})},accept(s,a){let l=un(a),d=be(s),u=l.length>0?l:d===void 0?[]:[d];if(u.length!==0){e=u,r?.settle(u);for(let[c,g]of [...o])xd(u,g)||c(u);}}}}function xd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var uf=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=uf.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var Td=["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"],mf=new Set(Td);function Ye(t){return typeof t=="string"&&mf.has(t)?t:"unknown"}var Fr="webrtc_dedicated",pi=["universal","mobile","web"];var pf="p2p_unavailable",gf="capacity_unavailable",ff=2,Ed=3e4,Id=1e3,Cd=2e4;async function gi(t){let e=be(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??de,i=t.retry??{},s=i.budgetMs??Ed,a=i.maxDelayMs??Cd,l=i.initialDelayMs??Id,d=o.now(),u=d+s,c=0;for(;;){c++;try{let g=await bi(t.signal,"while allocating",()=>t.client.post(`${Gd(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:g.match_id,status:g.status}}catch(g){if(!yf(g)||s<=0)throw g;if(g.status===503&&g.code===pf)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: ${g.message}`,{cause:g});if(r=g.code===gf?r+1:0,n!==void 0&&r>=ff){let k=n;n=void 0;let P=be(await k());P!==void 0&&(e=P,r=0);}let p=Math.min(a,l*2**(c-1)),f=Math.min(a,(g.retryAfterSeconds??0)*1e3),R=Math.max(p/2,f)+Math.random()*(p/2);if(o.now()+R>u)throw hf(t,g,c,o.now()-d,s);if(i.onWaiting?.({attempt:c,elapsedMs:o.now()-d,budgetMs:s,nextAttemptInMs:R,status:g.status,message:g.message}),await qr(o,R,t.signal),t.signal?.aborted)throw mi("while waiting to allocate")}}}function yf(t){return t instanceof G?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function hf(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 bf=12e4,vf=1e3;async function fi(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??vf,o=t.timeoutMs??bf,i=e.now()+o,s=Md(t),a={seen:t.knownToExist===true};for(;;){let l=await Od(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 qr(e,r,t.signal);}}async function yi(t){return (await Od(t,Md(t),{seen:t.knownToExist===true})).outcome}function Md(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Gd(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Od(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await bi(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof G&&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:_f(r,i,o)};if(i.status==="failed"){let s=i.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Ye(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function hi(t){let e=await bi(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 bi(t,e,n){if(t?.aborted)throw mi(e);try{return await n()}catch(r){throw t?.aborted?mi(e,r):r}}function mi(t,e){return new w("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function _f(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 Gd(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function qr(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 Ld(t){return typeof t=="string"&&t.trim()!==""}function Nr(t,e){return Ld(t)?t.trim():Ld(e)?e:null}var jr="0.1.0-beta",Dd="0-beta",It="web",wf=/^(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 Sf(t){let e=wf.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function $d(t,e){let n=kf(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:jr};let o=Sf(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 '${jr}' for it.`);if(o!==Dd)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${Dd}' 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 '${jr}' for it.`);return {...t,platform:n,engineVersion:r}}function kf(t,e){if(t===void 0||t===It)return It;if(!pi.includes(t))throw new w("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${pi.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${It}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${It}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),It}function mn(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:Fd(e.queued_at),expiresAt:Fd(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function Fd(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var Rf=3,qd=1e3,Br=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?qd:Math.max(qd,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 G&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<Rf){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof G&&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 Af="gemPlayWith",xf=/^[A-Za-z0-9_-]{16,128}$/;function Nd(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(Af);}catch{return}return e!==null&&xf.test(e)?e:void 0}function jd(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var Pf="join",Tf="welcome",Ef="rejected",Bd=25e3,If=1e3,vi=1;function _i(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Cf={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 wi(t){let e=typeof t=="string"?t:"unknown";return new w(Cf[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function pn(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Bd),a=n.setTimeout(()=>y(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,If)),l=R=>{let k=R.data;if(typeof k!="string"){c(k);return}let P;try{P=JSON.parse(k);}catch{c(k);return}if(i){c(k);return}if(P.t===Tf){let h=_i(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){y(wi(P.reason));return}c(k);},d=()=>{y(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},u=()=>{y(new w("aborted","the caller aborted during the join exchange"));},c=R=>{i&&t.onMessage?.(R);},g=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",u);},p=()=>{e.removeEventListener("message",l);},f=R=>{i=true,g(),t.onMessage===void 0&&p(),r({welcome:R,detach:p});},y=R=>{i||(i=true,g(),p(),o(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){u();return}t.signal?.addEventListener("abort",u);try{e.send(JSON.stringify({t:Pf,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:vi}:{}}));}catch(R){y(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var dt=1,gn=2,Si=4,Ai=8,Mf=2,Of=1e3,xi="heartbeat timeout",fn="gem-uu",Ur=2,Wd="gem_transports";function Ct(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Gf(r)||e.includes(r)||e.push(r);}return e}function Gf(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function yn(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 Wr(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Hd=new TextEncoder,Vd=new TextDecoder;function Pi(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function Ti(t){let e=0;return t?.reliable===false&&(e|=dt),t?.ordered===false&&(e|=gn),e}function Ei(t){return {reliable:(t&dt)===0,ordered:(t&gn)===0}}var Ii={reliable:true,ordered:true};function Kd(t){return JSON.stringify({t:"join",credential:t,wire:Ur,heartbeat:vi})}function Jd(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=_i(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"?wi(e.reason):new w("join_refused","the server answered the join out of protocol")}function Hr(){return typeof globalThis.WebTransport=="function"&&Ci===null}function Vr(){return Ci}var Ci=null;var Ud="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Lf(t){let e=rr(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 ki=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 Ri(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 hn(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:Lf(t.certHashBase64)}]});}let r=n,o=a=>{try{r.close();}catch{}throw a},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(Ci=Ud,o(new w("connection_failed",`${Ud}; 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,u=d.writable.getWriter();await u.write(Ri(Si,Hd.encode(Kd(t.credential))));let c=new ki,g=d.readable.getReader(),p;for(;p===void 0;){let f=await Promise.race([g.read(),s]);if(f.done||f.value===void 0)return o(new w("connection_failed","the control stream closed before the join was answered"));for(let y of c.push(f.value)){p=Jd(Vd.decode(y.payload));break}}return {link:Df(r,u,g,c,t.log??(f=>console.warn(f)),Xd(p,t.clock)),welcome:p}}catch(a){return o(a)}}function Df(t,e,n,r,o,i){let s,a,l=false,d=f=>{if(!l){l=true,u.stop();try{t.close();}catch{}a?.(f);}},u=Oi(i,()=>d(xi)),c=(f,y)=>{u.heard(),(f&Ai)===0&&s!==void 0&&((f&Si)!==0?s(Vd.decode(y),Ii):s(y,Ei(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let y of r.push(f.value))c(y.flags,y.payload);}}catch{}d("stream closed");})();let g,p;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let y=f.readable.getReader();p=f.writable.getWriter(),g=f,(async()=>{try{for(;;){let R=await y.read();if(R.done||R.value===void 0)break;let k=R.value;k.byteLength!==0&&c((k[0]??0)|dt|gn,k.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){g=void 0,p=void 0,o(`[gem] webtransport datagram lane unusable (${Wr(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(zd(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,y){if(l)return;if(typeof f=="string"){e.write(Ri(Si,Hd.encode(f))).catch(()=>d("write failed"));return}let R=Ti(y);if((R&dt)!==0&&p!==void 0){let k=Pi(R,f),P=g?.maxDatagramSize;if(P===void 0||k.byteLength<=P){p.write(k).catch(()=>{});return}}e.write(Ri(R,f)).catch(()=>d("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){d("closed");}}}function Mi(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=p=>{s||(s=true,clearTimeout(a),r.close(),i(p));},d=()=>{r.send(Kd(t.credential));},u=p=>{if(s)return;if(typeof p.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let f;try{f=Jd(p.data);}catch(y){l(y);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",u),r.removeEventListener("close",c),r.removeEventListener("error",g),o({link:$f(r,Xd(f,t.clock)),welcome:f});},c=()=>{l(new w("connection_failed","the websocket closed before the join was answered"));},g=()=>{l(new w("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",u),r.addEventListener("close",c),r.addEventListener("error",g),r.readyState===1&&d();})}function zd(t){return typeof t=="string"&&t.length>0?t:void 0}function Xd(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function Oi(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Of)*Mf,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 $f(t,e){let n,r,o=false,i=a=>{if(!o){o=true,s.stop();try{t.close();}catch{}r?.(a);}},s=Oi(e,()=>i(xi));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,Ii);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Ai)===0&&n?.(l.slice(1),Ei(d));})),t.addEventListener("close",(a=>i(zd(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!o){if(typeof a=="string"){t.send(a);return}t.send(Pi(Ti(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){i("closed");}}}function Gi(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=Oi(r,()=>l(xi)),u=(c,g)=>{if(d.heard(),typeof c=="string"){o?.(c,Ii);return}let p=new Uint8Array(c);if(p.byteLength===0)return;let f=p[0]??0;(f&Ai)===0&&o?.(p.slice(1),Ei(f|g));};if(t.addEventListener("message",(c=>u(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",(g=>u(g.data,dt|gn))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,g){if(s)return;if(typeof c=="string"){t.send(c);return}let p=Ti(g),f=Pi(p,c);if((p&dt)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}t.send(f);},onMessage(c){o=c;},onClose(c){i=c;},close(){l("closed");}}}function Yd(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=Li(r);o!==void 0&&(e[n]=o);}return e}function Qd(t){if(Array.isArray(t))return t.map(Ff).filter(e=>!!e)}function Li(t){if(Di(t)||Array.isArray(t)&&t.every(Di))return t}function Di(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function Ff(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Li(e.fixed),r=Li(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},...Mt("description",qf(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Di)?{allowed:e.allowed}:{},...Mt("min",bn(e.min)),...Mt("max",bn(e.max)),...Mt("minItems",bn(e.min_items)),...Mt("maxItems",bn(e.max_items)),...Mt("maxLength",bn(e.max_length))}}function qf(t){return typeof t=="string"&&t.length>0?t:void 0}function bn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Mt(t,e){return e===void 0?{}:{[t]:e}}function Ne(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(Nf):[];return {id:n,gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:Me(e.max_players)??0,memberCount:Me(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",Yd(e.room_args)),...Re("roomArgsTemplate",Qd(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:Me(e.version)??0,...Re("templateId",Q(e.template_id)),...Re("templateSlug",Q(e.template_slug)),roomType:Q(e.game_room_type)??"Standard",...Re("transports",Ct(e.transports)??void 0),createdAt:Me(e.created_at)??0,updatedAt:Me(e.updated_at)??0,...Re("startedAt",Me(e.started_at))}}function Nf(t){let e=t??{};return {...Pe(e),playerId:Q(e.player_id)??"",isReady:e.is_ready===true,role:Q(e.role)??"member",joinedAt:Me(e.joined_at)??0,...Re("groupId",Q(e.group_id)),...Re("platform",Q(e.platform))}}function $i(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:Me(e.max_players)??0,memberCount:Me(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Q(e.game_channel)??"release",roomType:Q(e.game_room_type)??"Standard",createdAt:Me(e.created_at)??0}}function Q(t){return typeof t=="string"&&t.length>0?t:void 0}function Me(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Re(t,e){return e===void 0?{}:{[t]:e}}var Kr=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($i),...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($i)}))}create(e,n,r){return Bf(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},...vn(n)},e.signal).then(Ne)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Ne)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...vn(r)},n.signal).then(Ne)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...vn(r)},n.signal).then(Ne)}quickJoin(e,n,r=[]){return Fi(this.options,e,n,r).then(o=>o.room)}createTicket(e,n,r=[]){return Rs(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},...vn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(mn)}heartbeatTicket(e){return tl(this.generated(),e).then(mn)}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(mn):vs(this.generated(),e).then(mn)}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 ec(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(Ne)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Ne)}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(Ne)}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 Zd(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 Zd(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function ec(t,e){return e===void 0&&t.selfHosted?.()===true}function Fi(t,e,n,r=[],o){let i=ec(t,e.partyId);return t.client.post(`${Zd(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...jf(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},...vn(n)},e.signal).then(s=>({room:Ne(s),playWith:o===void 0?null:jd(s)}))}function jf(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function vn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function Bf(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 zr=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 Uf(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var Wf=1e3,Hf=3e3,Vf=6e4,Kf=2,tc=new Set(["game_room_closed","game_room_gone"]),Jf=12e4,zf=5e3,Xf=new Set(["invalid_cluster_target","capacity_unavailable"]),Yf=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function ic(t,e){return new qi(e,t)}var qi=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 Kr(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"),ey(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||oc(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"),Zf(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||oc(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 Br({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 G&&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(()=>yi({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 G&&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=Ye(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=(u,c)=>gi({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...u===void 0?{}:{clusterTargetId:u},...o===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:g=>{this.emitter.emit("matchStartWaiting",g),n.retry?.onWaiting?.(g);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(i,[s]).catch(async u=>{if(o!==void 0||!rc(u))throw u;let c=await this.nextCluster([s],true);if(c===void 0)throw u;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 fi({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,!tc.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(!ct()){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<Wf){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(Uf(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!ct()){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(()=>yi({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,!tc.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||!Xf.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 zr({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&&ct())){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(),!!ct())){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 Xr)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 Xr)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??zf}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=Nr(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 $d({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return un(await this.options.resolveClusterTargets());let e=be(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !rc(e)||n.length===0?[]:un(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(un(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 G)||e.reason!=="conflict"||!Yf.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new G(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 G(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 G(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 Fi(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 G?{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=Qf(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??Jf;return new Promise((o,i)=>{let s=c=>{a(),l(),this.options.clock.clearTimeout(u),e.signal?.removeEventListener("abort",d),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>o(c))),l=this.emitter.on("matchFailed",(c,g)=>s(()=>i(new w("allocation_failed",`match ${c} did not come up: ${g}`)))),d=()=>s(()=>i(new w("aborted","the caller aborted while awaiting a match"))),u=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??Hf}pushedInterval(){return this.options.pushedPollIntervalMs??Vf}pushed(){return this.options.clock.now()-this.lastPushAt<Kf*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 ct(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Xr=["visibilitychange","focus","pageshow","online"];function Qf(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||nc(t)!==nc(e)}function nc(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function rc(t){return t instanceof G&&t.code==="invalid_cluster_target"}var Yr=8;function Zf(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=Yr&&t.every(n=>typeof n=="string"&&n.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Yr} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function ey(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Yr&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Yr} 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 oc(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var ty=["p2p","dedicated","unknown"],Ni=["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 Ot=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=ny(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 ny(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>Ni.includes(o.type)).slice(0,100).map(o=>{let i=ry(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function ry(t){if(t!==void 0)return ty.includes(t)?t:"unknown"}var _n=class{constructor(e){this.options=e;this.reporter=new Ot({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:Qr(o.credential)??"",hostFingerprint:Qr(o.host_fingerprint)??"",hostEpoch:Zr(o.host_epoch)??0,expiresAt:(Zr(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,u=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);u.length!==0&&i.push({urls:u,username:Qr(d.username)??"",credential:Qr(d.credential)??""});}let s=Zr(o.expires_at),a=Zr(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 Qr(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 oy=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),$=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=oy.has(n);}reason;retryable};var ac=10240,sc=2048,iy=new TextEncoder;function lc(t){return iy.encode(t).length}function Qe(t,e){let n=o=>{throw new w("invalid_sdp",`the ${e} ${o}`)},r=lc(t);r>=ac&&n(`is ${r} bytes, over the ${ac} 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=lc(o);i>sc&&n(`has a ${i}-byte line, over the ${sc} limit`);}}function eo(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 to=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 ay=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function Gt(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=no(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function no(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 ay.test(r)?r:null}function wn(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 ji=5e3,sy=12e4+ji,ly=1024,dy=6e4,cy=1e4,dc=64*1024,cc=5;function Bi(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 $("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 $("keys_unavailable",o.reason);let a=t.fetch??((g,p)=>globalThis.fetch(g,p)),l;try{l=await a(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(cy)});}catch{throw new $("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 $("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let g=await l.text();if(g.length>dc)throw new $("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${dc} characters, which is not a key set this platform publishes.`);d=JSON.parse(g);}catch(g){throw g instanceof $?g:new $("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let u=Array.isArray(d.keys)?d.keys:[];if(u.length>cc)throw new $("keys_unavailable",`the JWKS endpoint published ${u.length} keys, over the ${cc} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=i();for(let g of u){let p=g;if(p.kty==="RSA"&&!(p.alg!==void 0&&p.alg!=="RS256")&&!(p.use!==void 0&&p.use!=="sig")&&!(typeof p.kid!="string"||p.kid.length===0))try{let f=await c.importKey("jwk",{...g,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(p.kid,f);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!o.ok)throw new $("keys_unavailable",o.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new $("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<dy?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var Sn=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>=ly){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+sy),true}};function mc(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 uc(t){try{let e=new TextDecoder().decode(mc(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Ui(t,e,n,r,o){let i=B=>{throw new $("peer_unauthenticated",`the peer's join credential is not usable: ${B}`)},s=t.split(".");s.length!==3&&i("it is not a three-part JWT");let[a,l,d]=s,u=uc(a);u===null&&i("its header does not decode"),u.alg!=="RS256"&&i(`its alg is ${JSON.stringify(u.alg)}, not RS256`),u.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(u.typ)}, not p2p+jwt`);let c=u.kid;(typeof c!="string"||c.length===0)&&i("it names no key");let g=await n.key(c);g===null&&i("it was signed by a key this build cannot resolve");let p=o.subtle??globalThis.crypto?.subtle;p||i("this environment has no WebCrypto");let f=new TextEncoder().encode(`${a}.${l}`),y;try{y=mc(d);}catch{i("its signature does not decode");}await p.verify({name:"RSASSA-PKCS1-v1_5"},g,y,f)||i("its signature does not verify");let k=uc(l);k===null&&i("its payload does not decode");let P=k,h=B=>typeof P[B]=="string"?P[B]:"",S=B=>typeof P[B]=="number"&&Number.isFinite(P[B])?P[B]: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 C=S("exp")*1e3,I=S("nbf")*1e3;(!Number.isFinite(C)||e.now>C+ji)&&i("it has expired"),Number.isFinite(I)&&e.now<I-ji&&i("it is not valid yet");let U=h("role");U!=="host"&&U!=="client"&&i("it names no usable role");let q=S("host_epoch");q!==e.hostEpoch&&i("it names a different host epoch");let x=no(h("fingerprint"));x===null&&i("its fingerprint claim is malformed"),wn(x,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let A=no(h("host_fingerprint"));A===null&&i("its host fingerprint claim is malformed"),wn(A,e.hostFingerprint)||i("it was issued against a different host certificate");let O=h("jti");O.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(O,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:U,fingerprint:x,hostFingerprint:A,jti:O,expiresAt:C}}function Wi(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 Hi(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 Vi(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Ki(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 pc(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 gc(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var kn=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 Ji={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}},je=["reliable","ordered","unreliable"];function zi(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 Rn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var yc=1,fy=3e4,hc=2e3,yy=5e3,bc=6e4,hy=8,Yi=class{constructor(e=hy){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;}},by=new Yi,vy=8,_y=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),xn=class{constructor(e){this.options=e;this.keys=e.keys??Bi({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new to;links=new Map;replays=new Sn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=yc+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??fy;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: ${Xi(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 $("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 $("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 $("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=ce(e.playerId),r=ce(e.hostPlayerId),o=ro(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new kn(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,yc),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new $("invalid_sdp","the browser produced an offer with no SDP");Qe(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,o=r===void 0?null:Gt(r);if(o===null)throw new $("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??by,s=()=>this.closed||e!==this.credentialGeneration,a=yy;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 u=d.status,c;if(u===409)c=hc;else if(u===429){let g=d.retryAfterSeconds;typeof g=="number"&&Number.isFinite(g)&&g>=0?c=g*1e3:(c=a,a=Math.min(a*2,bc)),c=Math.min(Math.max(c,hc),bc);}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=ce(e.fromPlayerId),r=ce(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=vy){let u=this.pendingOffers.keys().next().value;u!==void 0&&this.pendingOffers.delete(u);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let o=ce(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;Qe(r,"offer"),this.refuseMedia(r,"offer");let i=Gt(r);if(i===null)throw new $("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 $("invalid_sdp","the browser produced an answer with no SDP");Qe(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=ce(e.fromPlayerId),r=ce(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;Qe(r,"answer"),this.refuseMedia(r,"answer");let i=Gt(r);if(i===null)throw new $("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:wn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new $("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=ce(e.fromPlayerId),r=ce(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=ce(e.sdpMid),s=ro(e.sdpMLineIndex)??ro(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=ce(e.playerId);if(n===null)return;let r=ce(e.reason)??"left";if(n===this.localPlayerId){this.fail(new $("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=ce(e.hostPlayerId),r=ro(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...ce(e.reason)===null?{}:{reason:ce(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 $("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 $("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=ce(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new $("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=ce(e.code)??"unknown",r=ce(e.message)??"the platform refused a signaling message";this.report_(new $("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??zi)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let g of je){let p=o.createDataChannel(g,Ji[g]);p.binaryType="arraybuffer",i[g]=p;}let s={playerId:e,assignedPeerId:n,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=g=>{let p=g.candidate;p?.candidate&&this.options.signaling.candidate(e,p.candidate,p.sdpMid??void 0,p.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),u=g=>{this.onHandshakeMessage(s,g.data).catch(p=>this.report_(p));},c=()=>{this.onReliableOpen(s).catch(g=>this.report_(g));};return o.addEventListener("icecandidate",a),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",c),i.reliable.addEventListener("message",u),s.detachHandshake=()=>{i.reliable.removeEventListener("open",c),i.reliable.removeEventListener("message",u);},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 $("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 $("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(Wi({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Ki(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 $(gc(r.reason),pc(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=Gt(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 Ui(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 $&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",Xi(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(Hi({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(Vi(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 je)vc(e.channels[o]);vc(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 $?e:new $("connection_failed",Xi(e),{cause:e}));}count(e){this.counted||!_y.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(eo(e))throw new $("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 ce(t){return typeof t=="string"&&t.length>0?t:null}function ro(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Xi(t){return t instanceof Error?t.message:String(t)}function vc(t){try{t.close();}catch{}}var wy=100,Sy=50,Pn=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??wy)){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 $("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new $("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??Sy));}};function V(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Ze(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function Lt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function _c(t){return typeof t=="boolean"?t:void 0}var we=V(64),Tn=Ze(0,2147483647);function Qi(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=we(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 Ay=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=Lt("disconnected","failed","closed")(e.iceState),r=Ze(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",Lt("initial","ice_restart","full_reconnect")),K("sdp_hash","sdpHash",V(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[Y("peer_id","peerId",we),Y("sdp","sdp",V(10240)),Y("assigned_peer_id","assignedPeerId",Ze(0,4294967295)),K("sdp_hash","sdpHash",V(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[Y("peer_id","peerId",we),Y("candidate","candidate",V(512)),K("sdp_mid","sdpMid",V(64)),K("sdp_mline_index","sdpMLineIndex",Ze(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[Y("host_epoch","hostEpoch",Tn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[Y("host_epoch","hostEpoch",Tn),K("evidence","evidence",Ay)]}}));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",we),Y("hostPlayerId","host_player_id",we),Y("hostEpoch","host_epoch",Tn),K("members","members",Qi)],offer:[Y("fromPlayerId","from_player_id",we),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",Lt("initial","ice_restart","full_reconnect"))],answer:[Y("fromPlayerId","from_player_id",we),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",Ze(0,4294967295))],ice:[Y("fromPlayerId","from_player_id",we),Y("candidate","candidate",V(512)),K("sdpMid","sdp_mid",V(64)),K("sdpMLineIndex","sdp_m_line_index",Ze(0,255)),K("sdpMLineIndexAlt","sdp_mline_index",Ze(0,255))],peerJoined:[Y("playerId","player_id",we)],peerLeft:[Y("playerId","player_id",we),K("reason","reason",V(64))],migration:[Y("hostPlayerId","new_host_player_id",we),Y("hostEpoch","host_epoch",Tn),K("reason","reason",V(64)),K("kickedPlayerIds","kicked_player_ids",Qi),K("migrationComplete","migration_complete",_c)],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 mt="webrtc_p2p";function Sc(t){let e=new _n({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 $("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!==mt)throw new $("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${mt}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new Pn({bridge:t.bridge,matchId:s.matchId,clock:t.clock}),l=new xn({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 Rn(),...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 kc(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(!ct());for(let d of Xr)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(!ct());}let s=new Map;return i.push(n.on("matchReady",a=>{let l=a.protocol===mt?"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 Rc=["pointerdown","keydown"];function Ac(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 p of Rc)e.removeEventListener?.(p,l,{capture:true});e.removeEventListener?.("gamepadconnected",g,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(p){p?.isTrusted===true&&a();}let d=()=>{let p;try{p=e.navigator?.getGamepads?.()??[];}catch{return false}return p.some(f=>f?.buttons.some(y=>y.pressed)===true)},u=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(p=>p!==null)}catch{return false}},c=()=>{if(o=null,!(n||r)){if(d()){a();return}u()&&(o=e.requestAnimationFrame?.(c)??null);}};function g(){o===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let p of Rc)e.addEventListener(p,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",g,{capture:true,passive:true}),u()&&(o=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:s}}async function oo(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function Zi(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function ea(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 ta=new WeakMap,xc=new WeakSet,na=new Set,io=new Set,ao=[],$t=null,ra=false,xy=1920;function oa(t){return ta.get(t)}function ia(t){return !ra||xc.has(t)}function aa(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function Pc(t=globalThis.window){if(ra||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;ra=true;for(let i of Array.from(t.document?.querySelectorAll("canvas")??[]))xc.add(i);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(i,...s){let a=n.call(this,i,...s);if(a&&!ta.has(this)){let l={kind:i,context:a};ta.set(this,l),aa(l)&&na.add(this);}return a};let r=t.requestAnimationFrame,o=t.cancelAnimationFrame;t.requestAnimationFrame=i=>{let s=r.call(t,a=>{io.delete(s);try{i(a);}finally{Py();}});return io.add(s),Ic(),s},t.cancelAnimationFrame=i=>{io.delete(i),o.call(t,i);};}function Tc(t,e){return new Promise(n=>{let r={canvas:t,done:i=>{clearTimeout(o),ao=ao.filter(s=>s!==r),n(i);}},o=setTimeout(()=>r.done(null),e);ao.push(r);})}function Ec(t){return $t?.canvas===t?$t.bitmap:null}function Py(){for(let t of ao){let e;try{e=sa(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}io.size===0&&Ty();}function Ty(){let t=null;for(let r of na)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):na.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,xy/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"}:{};Ic(),$t={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function Ic(){$t&&($t.bitmap.then(t=>t?.close()),$t=null);}function sa(t){let e=Ey();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 En;function Ey(){if(En!==void 0)return En;if(typeof OffscreenCanvas=="function")En=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),En=t?.getContext("2d",{willReadFrequently:true})??null;}return En??null}var la=false;async function Gc(t,e,n,r){if(la){e.close(),n("busy",true);return}la=true;let o=null;try{let i=await My(t,r);if(typeof i=="string"){e.close(),n(i,Iy(i));return}o=i;let a=await(r.encodeRef??(l=>$y(l,r)))(o);if(o.close(),o=null,a===null){e.close(),n("failed",!0);return}if(a.size>Dy){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{la=false,o?.close();}}function Iy(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 Cy=600;async function My(t,e){if(e.handler){let o=await e.handler(t);return o===null?"declined":Cc(o,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Ly(n);if(!r)return "no_source";try{let o=await Oy(r);return typeof o=="string"?o:Cc(o,t)}catch(o){if(o instanceof DOMException&&o.name==="SecurityError")return "tainted";throw o}}async function Oy(t){let e=Gy(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!aa(e))return createImageBitmap(t);let n=await Tc(t,Cy);if(n)return n;let r=await Ec(t);return r&&sa(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function Gy(t){let e=oa(t);if(e)return e;if(!ia(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 Ly(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||!oa(r)&&!ia(r)||o>n&&(e=r,n=o);}return e}async function Cc(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 Dy=8*1024*1024,Mc="image/webp",Oc=.92;async function $y(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:Mc,quality:Oc});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),Mc,Oc);})}async function Lc(t,e){if(!e)return;let n;try{n=await Fy(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 Fy(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 Dc=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Fc(t=globalThis){let n=t[Dc];if(n!==void 0)return n;let r=false,o=()=>r,i=jy(t),s=[],a=qy(t,o,i.watch);a!==null&&s.push(a);let l=Ny(t,o,i.watch);l!==null&&s.push(l);let d={get muted(){return r},setMuted(u){let c=!!u;if(c!==r){r=c;for(let g of s)g();}},setPaused(u){i.setPaused(!!u);}};return Object.defineProperty(t,Dc,{value:d,configurable:true}),d}function qy(t,e,n){let r=t.AudioNode?.prototype,o=t.AudioDestinationNode;if(r===void 0||o===void 0)return null;let i=t.OfflineAudioContext,s=r.connect,a=r.disconnect,l=new Map,d=c=>{let g=c.gain,p=c.context.currentTime;g.cancelScheduledValues(p),e()?g.setValueAtTime(0,p):g.setTargetAtTime(1,p,.01);},u=c=>{let g=c.context;if(i!==void 0&&g instanceof i)return null;let p=l.get(g);return p===void 0&&(p=g.createGain(),p.gain.value=e()?0:1,s.call(p,c),l.set(g,p),n.context(g)),p};return r.connect=function(...g){let[p,...f]=g;if(p instanceof o){let y;try{y=u(p);}catch{y=null;}if(y!==null)return s.call(this,y,...f),p}return s.apply(this,g)},r.disconnect=function(...g){let[p,...f]=g;if(p instanceof o){let y=l.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...f)}catch{}}return a.apply(this,g)},()=>{for(let[c,g]of l){if(c.state==="closed"){l.delete(c);continue}try{d(g);}catch{}}}}function Ny(t,e,n){let r=t.HTMLMediaElement;if(r===void 0)return null;let o=r.prototype,i=Object.getOwnPropertyDescriptor(o,"muted"),s=i?.get,a=i?.set;if(s===void 0||a===void 0)return null;let l=o.play,d=new WeakMap,u=new WeakSet,c=new Set,g=p=>{d.has(p)||d.set(p,!!s.call(p)),u.has(p)||(u.add(p),c.add(new WeakRef(p)),n.element(p)),a.call(p,(d.get(p)??false)||e());};return Object.defineProperty(o,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let p=d.get(this);return p===void 0?!!s.call(this):p},set(p){d.set(this,!!p),g(this);}}),o.play=function(){try{g(this);}catch{}return l.call(this)},t.document?.addEventListener("play",p=>{let f=p.target;if(f instanceof r)try{g(f);}catch{}},true),()=>{for(let p of c){let f=p.deref();if(f===void 0){c.delete(p);continue}try{a.call(f,(d.get(f)??!1)||e());}catch{}}}}var $c=["pointerup","touchend","click","keydown"];function jy(t){let e=t.document,n=new Set,r=new WeakSet,o=new WeakSet,i=new Set,s=new Set,a=false,l=false,d=t.AudioContext?.prototype,u=d?.suspend,c=d?.resume,g=d!==void 0&&typeof u=="function"&&typeof c=="function";g&&(d.suspend=function(...A){try{o.add(this);}catch{}return u.apply(this,A)},d.resume=function(...A){try{o.delete(this);}catch{}return c.apply(this,A)});let p=t.HTMLMediaElement?.prototype,f=p?.pause;p!==void 0&&typeof f=="function"&&(p.pause=function(){s.delete(this),f.call(this);});let y=x=>x.state!=="running"&&x.state!=="closed"&&r.has(x)&&!o.has(x),R=x=>x.paused&&!x.ended,k=()=>{for(let x of n)if(x.state==="closed")n.delete(x);else if(y(x))return true;for(let x of s){if(R(x))return true;s.delete(x);}return false},P=()=>{for(let x of i){let A=x.deref();if(A===void 0){i.delete(x);continue}try{!A.paused&&!A.ended&&s.add(A);}catch{}}},h=()=>{if(l){l=false,s.clear();for(let x of $c)e?.removeEventListener?.(x,C,true);}},S=()=>{try{l&&!k()&&h();}catch{}};function C(){if(!l||a)return;let x=[];try{for(let A of n){if(A.state==="closed"){n.delete(A);continue}if(y(A))try{x.push(Promise.resolve(c?.call(A)));}catch{}}for(let A of s){if(!R(A)){s.delete(A);continue}try{x.push(Promise.resolve(A.play()).then(()=>s.delete(A),O=>{O?.name!=="NotAllowedError"&&s.delete(A);}));}catch{s.delete(A);}}}catch{}if(x.length===0){S();return}Promise.allSettled(x).then(S);}let I=()=>{if(!(l||e===void 0)){l=true;for(let x of $c)e.addEventListener(x,C,true);}},U=()=>{P(),e?.visibilityState!=="hidden"&&I();};try{e?.addEventListener("visibilitychange",()=>{try{e.visibilityState==="hidden"?P():I();}catch{}},!0),t.addEventListener?.("pagehide",()=>{try{P();}catch{}}),t.addEventListener?.("pageshow",x=>{try{x.persisted&&I();}catch{}});}catch{}return {watch:{context(x){if(g)try{n.add(x),x.state==="running"&&r.add(x),x.addEventListener("statechange",()=>{try{let A=x.state;A==="running"?(r.add(x),S()):A!=="closed"&&r.has(x)&&!o.has(x)&&U();}catch{}});}catch{}},element(x){try{i.add(new WeakRef(x));}catch{}}},setPaused(x){a=x;}}}var By=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Uy=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Wy=`${By}${Uy}`,da=new WeakSet;function qc(t=globalThis.document){if(t==null||da.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(Wy),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],da.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"),da.add(t),"inline")}catch{return null}}function Nc(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,u=[],c=false,g=0,p=null,f=[],y=()=>o&&!i&&!s,R=()=>{l=null,d=null,u=[],g=0,p=null,f=[];},k=S=>{if(a=null,!y()){R();return}if(d!==null&&u.push(S-d),d=S,l===null)l=S;else {let C=S-l;if(C>=e&&u.length>0){if(c){let I=p===null?C:r()-p;t.report(Vy(g,f,C,I));}else t.report(Hy(u,C));l=S,u=[],g=0,f=[];}}P();},P=()=>{let S=n.requestAnimationFrame;typeof S=="function"&&(a=S.call(n,k));},h=()=>{if(y()){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();p!==null&&f.length<1e3&&f.push(S-p),p=S,g+=1;},get running(){return a!==null},dispose(){s=true,h();}}}function Hy(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:jc(t),counts:"pageFrames"}}function Vy(t,e,n,r){let o=r;return e.length>0&&(o=jc(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:o,counts:"gameDraws"}}function jc(t){let e=[...t].sort((r,o)=>r-o),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var so=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 Uc(t,e){t!==null&&(t.style.setProperty(so.top,`${e.top}px`),t.style.setProperty(so.right,`${e.right}px`),t.style.setProperty(so.bottom,`${e.bottom}px`),t.style.setProperty(so.left,`${e.left}px`));}var lo=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 Wc(){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 Ky(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 u=l.control;l.control=u?{top:Math.min(u.top,d.y),bottom:Math.max(u.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Hc(t,e,n){if(t===null)return;let r=Ky(e,n);for(let o of ["tl","tr","bl","br"]){t.style.setProperty(lo[o].width,`${r[o].width}px`),t.style.setProperty(lo[o].height,`${r[o].height}px`);let i=r[o].control;t.style.setProperty(lo[o].centerY,i?`${(i.top+i.bottom)/2}px`:""),t.style.setProperty(lo[o].controlHeight,i?`${i.bottom-i.top}px`:"");}}var Jy=3e4,co=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Vc(t){let e=t.clock??de,n=t.timeoutMs??Jy,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((u,c)=>{let g=`ls${++i}`,p=e.setTimeout(()=>{r.delete(g),o.delete(a),c(new co("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(g,{room:a,resolve:u,reject:c,timer:p}),t.bridge.requestLocalServer(g,a)||(s(g),u());});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 co(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 In={url:"https://downloads.indiegems.games/sdk/v19.0.1/gem-web-sdk.devtools.min.js",integrity:"sha384-qrdTTpfVyW5pT2DKYimvzOFQgpzs98Z4UDxjJ6VdvWEj3GJindT4I2QDt+StWnEq"};var Ft=null;function zy(){return Ft!==null||(Ft=new Promise((t,e)=>{let n=document.createElement("script");n.src=In.url,n.integrity=In.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Ft=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${In.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Ft=null,e(new Error(`gem devtools: could not load ${In.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);})),Ft}function Kc(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 zy();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:i,text:it,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 Xy=1e4,Jc={reason:"unavailable",retryable:false};function zc(t){let e=new Map,n=null,r=null,o=0,i=(d,u)=>{u.timer=t.clock.setTimeout(()=>{e.delete(d),u.reject({reason:"timeout",retryable:true});},t.timeoutMs??Xy);},s=(d,u)=>{let c=a(d);c&&u(c);},a=d=>{let u=e.get(d);return u?(e.delete(d),t.clock.clearTimeout(u.timer),u):null},l=new wt({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((u,c)=>{let g=t.bridge.currentState;if(g==="refused"||g==="closed"){c(Jc);return}let p=`t${++o}`,f={resolve:u,reject:c,reason:d,timer:null,held:g!=="connected"};e.set(p,f),i(p,f),f.held||t.bridge.requestToken(p,d);})});return {source:l,onToken(d){let u={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(u));return}l.accept(u);},onDenied(d){s(d.requestId,u=>u.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[u,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),i(u,c),t.bridge.requestToken(u,c.reason));else if(d==="refused"||d==="closed")for(let u of [...e.keys()])s(u,c=>c.reject(Jc));},get identity(){return n},get gameVersion(){return r}}}var Yy=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),ua="embedder_relay_unavailable",Qy="embedder_no_relay",Zy=new Set([ua]),ma=new Set([Qy]),Cn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new ca(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(eh(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 eh(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new w(th(t),r,{platformCode:t})}function th(t){return t===void 0||Zy.has(t)?"signaling_failed":ma.has(t)?"offer_refused":Yy.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var ca=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:",Yc="server_shutdown:",Qc="kicked:",nh=123;function rh(t){if(typeof t!="string"||t.length===0||t.length>nh)return {kind:"other"};if(t.startsWith(Xc)){let e=Ye(t.slice(Xc.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Yc)?{kind:"server_shutdown",cause:t.slice(Yc.length)}:t.startsWith(Qc)?{kind:"kicked",detail:t.slice(Qc.length)}:{kind:"other"}}function pa(t,e,n){let r=rh(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 ga(){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 oh=3e3,ih=1e4,ah=15e3;async function uo(t){let e=t.peerConnection;try{eu(t,"before the handshake started"),fa(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 dh(e,t),fa(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new w("invalid_sdp","the offer carried no SDP");Qe(o,"offer"),Zc(o,"offer");let i=await lh(t,o);if(fa(t),typeof i?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return Qe(i.sdp,"answer"),Zc(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await ch(n,t),eu(t,"before the channel opened"),n}catch(n){throw e.close(),sh(n)}}function sh(t){return t instanceof w?t:ru(t)?pt():new w("connection_failed",ou(t),{cause:t})}function Zc(t,e){if(eo(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 lh(t,e){let n=t.exchangeTimeoutMs??ih,r=nu(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof w?i:ru(i)?pt():new w("signaling_failed",ou(i),{cause:i})});return uh(o,t,r,()=>r.exhausted?ya("while the offer was in flight"):new w("timeout",`no answer arrived within ${n}ms`))}function dh(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??oh);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function ch(t,e){if(e.signal?.aborted)return Promise.reject(pt());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??ah,o=nu(e,r);return new Promise((i,s)=>{let a=()=>{n.clearTimeout(g),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",u);},l=()=>{a(),i();},d=p=>{a(),s(new w("connection_failed","the data channel failed before it opened",tu(p)===void 0?void 0:{cause:tu(p)}));},u=()=>{a(),s(pt());},c=()=>{a(),s(o.exhausted?ya("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},g=n.setTimeout(c,o.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",u);})}function nu(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 uh(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(pt()):new Promise((s,a)=>{let l=c=>{o.clearTimeout(u),i?.removeEventListener("abort",d),c();},d=()=>l(()=>a(pt())),u=o.setTimeout(()=>l(()=>a(r())),n.ms);i?.addEventListener("abort",d),t.then(c=>l(()=>s(c)),c=>l(()=>a(c)));})}function eu(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw ya(`already ${e}`)}function ya(t){return new w("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function fa(t){if(t.signal?.aborted)throw pt()}function pt(){return new w("aborted","the caller aborted the connection attempt")}function ru(t){return t?.name==="AbortError"}function tu(t){return t?.error}function ou(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 mu(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??ga,i=t.log??(h=>console.warn(h)),s=new Ot({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,S)=>{let C=a.get(h)??new Set;C.add(S),a.set(h,C);},d=(h,S)=>{let C=a.get(h);C!==void 0&&(C.delete(S),C.size===0&&a.delete(h));},u=async h=>{if(r.isHost&&!ba(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 cu(r.matchConnectionState==="suspended"?await r.reconnectToMatch(ha(h)):await r.awaitMatch(ha(h)))},c=async h=>cu(await r.pollMatchStatus(ha(h))),g=async(h,S)=>{let C=false;try{let I=await u(h),U=r.currentRoom?.transports;if(U!==void 0&&!U.includes("webrtc"))throw new w("misconfigured",`the room template offers (${U.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??uu();C=!0;let x=await uo({peerConnection:q,signaling:S,clock:n,matchId:I.matchId,credentialExpiresAt:I.credentialExpiresAt,...mo(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),A=null;if(h.presentCredential!==!1)try{A=await pn({channel:x,clock:n,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,...mo(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(O){throw Te(x),Te(q),O}return _h(r,I,x,q,S,h.reportDisconnect!==!1,h.reportConnected!==!1,A,{remember:l,forget:d},h.onMatchEnded)}catch(I){throw C&&du(s,I),Te(S),I}},p=async(h,S,C,I,U,q)=>{if(h==="webtransport"){let W=I?.webtransport;if(W===void 0)throw new w("misconfigured","webtransport is not advertised");let J={credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:n};if(typeof W.named_url=="string"&&W.named_url!==""){let ie=Math.max(Math.floor(q/2),1e3);try{return await hn({url:W.named_url,timeoutMs:ie,log:i,...J})}catch(ge){if(Vr()!==null)throw ge;return i(`[gem] webtransport named dial failed (${Wr(ge)}); retrying the pinned dial`),hn({url:W.url,certHashBase64:W.cert_sha256_b64,timeoutMs:ie,log:i,...J})}}return hn({url:W.url,certHashBase64:W.cert_sha256_b64,timeoutMs:q,...J})}if(h==="websocket"){let W=I?.websocket;if(W===void 0)throw new w("misconfigured","websocket is not advertised");return Mi({url:W.url,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:n,timeoutMs:q})}let x=S.peerConnection??uu(),A,O=await uo({peerConnection:x,signaling:U,clock:n,matchId:C.matchId,credentialExpiresAt:C.credentialExpiresAt,extraChannels:[{label:fn,ordered:false,maxRetransmits:0}],onExtraChannel:(W,J)=>{W===fn&&(A=J);},...mo(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:gh}:{}}),F;try{F=await pn({channel:O,clock:n,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,wire:Ur,heartbeat:!0,...mo(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(W){throw Te(O),Te(x),W}let B=F.welcome.heartbeatIntervalMs;return {link:Gi(O,x,A,B===void 0?void 0:{clock:n,intervalMs:B}),welcome:F.welcome,channel:O,peerConnection:x}},f=(h,S,C,I,U)=>{let q=false,x;I.link.onClose(B=>{!q&&h.reportDisconnect!==false&&pa(r,S.matchId,B),x?.(B);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let A={transport:I.link.transport,send:(B,W)=>I.link.send(B,W),onMessage:B=>I.link.onMessage(B),onClose:B=>{x=B;},close:()=>I.link.close()},O=()=>{q||(q=true,Te(I.link),Te(U));},F=B=>{if(!q){try{h.onMatchEnded?.(B);}catch{}O();}};return l(S.matchId,F),{matchId:S.matchId,transport:C,link:A,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:I.welcome,...I.channel===void 0?{}:{channel:I.channel},...I.peerConnection===void 0?{}:{peerConnection:I.peerConnection},close(){d(S.matchId,F),O();}}},y=async(h,S)=>{let C=r.currentRoom?.id,I=r.gameId,U=()=>({advert:yn(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(C===void 0||I===null)return U();try{let q=await e.get(`/v2/games/${encodeURIComponent(I)}/game-rooms/${encodeURIComponent(C)}`,S);return {advert:yn(q.settings,h),template:Ct(q.transports)??r.currentRoom?.transports??null}}catch{return U()}},R=(h,S)=>{let C=h??iu;return S.length===0?C:C.filter(I=>S.includes(I))},k=async(h,S,C)=>{try{let I=await u(h),{advert:U,template:q}=await y(I.matchId,h.signal),x=R(q,S),A=x.filter(X=>hh(X,U)),O=Vr();if(O!==null&&x.includes("webtransport")&&U?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${O} (learned on an earlier dial in this page)`),A.length===0){let X=q===null?`the default order (${iu.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??ph,B=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-n.now(),W=X=>t.signalingReady===void 0||X<=0?Promise.resolve(!0):t.signalingReady(X),J=[],ie=[];for(let X of A){if(B()<su){i(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}ie.length>0&&I.credentialExpiresAt-n.now()<lu&&(I=await c(h)),ie.push(X);let Be=!1,Se=!1,fe={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&h.redial===!0){let te=Math.min(au,B());await W(te)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let Ue=Math.max(Math.min(F,B()),su);try{return f(h,I,X,await p(X,h,I,U,C,Ue),C)}catch(te){let z=te instanceof w?te:new w("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(X==="webrtc"&&du(s,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Be){Be=!0,I=await c(h);continue}if(X==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===ua&&!Se){Se=!0;let le=Math.min(au,B());if(i(`[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 W(le))continue}if(z.reason==="join_rate_limited"){let le=yh(fe,Math.random,B());if(le!==null){if(fe.attempts+=1,fe.waitedMs+=le,i(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(le)}ms before presenting again (retry ${fe.attempts} of ${gu.maxAttempts})`),await qr(n,le,h.signal),h.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");I.credentialExpiresAt-n.now()<lu&&(I=await c(h));continue}}if(fh.has(z.reason)||z.reason==="credential_expired"||X==="webrtc"&&pu(z)){i(`[gem] ${X} rung failed (${z.reason}): ${Wr(z.cause??z)} \u2014 `+(ie.length<A.length?`falling through to ${A[ie.length]}`:"no rungs left")),J.push(z);break}throw i(`[gem] ${X} rung refused the session (${z.reason}): ${z.message}`),z}}}let ge=J[J.length-1];throw ge===void 0?new w("timeout",`the reconnect budget ran out before any transport (${A.join(", ")}) could be tried`):new w(ge.reason,`every transport tried (${ie.join(", ")}) failed; the last said: ${ge.message}`,{cause:J,platformCode:ge.platformCode})}catch(I){throw Te(C),I}};return {listClusterTargets:async(h={})=>hi({client:e,...h}),handleMatchEnded(h,S){let C=a.get(h);if(C!==void 0){a.delete(h);for(let I of C)I(S);}},connect:(async(h={})=>{let S=h.signaling??o();return h.transports===void 0?g(h,S):k(h,h.transports,S)})}}var iu=["webtransport","webrtc","websocket"],ph=1e4,gh=5e3,au=3e3,su=1e3,lu=1e4,fh=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function pu(t){return t.platformCode!==void 0&&ma.has(t.platformCode)}var gu={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function yh(t,e=Math.random,n=1/0){let r=gu;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 hh(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Hr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||bh(e.websocket.url)}function bh(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return Je(e)}function ha(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var vh=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function du(t,e){e instanceof w&&(!vh.has(e.reason)&&!pu(e)||t.report([{type:"connection_failures_total",value:1}]));}function _h(t,e,n,r,o,i,s,a,l,d){let u=false,c=()=>{u||pa(t,e.matchId,void 0);};i&&(n.addEventListener("close",c),s&&t.notifyMatchConnected(e.matchId));let g=()=>{u||(u=true,n.removeEventListener("close",c),a?.detach(),Te(n),Te(r),Te(o));},p=f=>{if(!u){try{d?.(f);}catch{}g();}};return l.remember(e.matchId,p),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,p),g();}}}function ba(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function cu(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!==Fr)throw new w("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Fr}' 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 uu(){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 mo(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var wh=1e4;function fu(t,e){return va(t,e)}function va(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 wt({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??wh);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 wa={};zm(wa,{acceptTransfer:()=>Sh,addEntityProgression:()=>kh,adminAction:()=>Rh,cancelInventoryTransfer:()=>Ah,claimEntityProgressionRewards:()=>xh,closeGameRoom:()=>Ph,createEntityBatchOrder:()=>Th,createEntityOrder:()=>Eh,createSession:()=>Ih,deleteEntityGameSetting:()=>Ch,deleteEntitySave:()=>Mh,deleteSession:()=>Oh,deleteShowcaseValue:()=>Gh,executeEntityRecipe:()=>Lh,finalizeSaveUpload:()=>Dh,getChannelAssignment:()=>$h,getDropRates:()=>Fh,getEntityCurrency:()=>qh,getEntityGameSetting:()=>Nh,getEntityInventory:()=>jh,getEntityInventoryItem:()=>Bh,getEntityLeaderboard:()=>Uh,getEntityOrder:()=>Wh,getEntityProgression:()=>Hh,getEntityRecipeAvailability:()=>Vh,getEntityRecipeUsage:()=>Kh,getEntitySave:()=>Jh,getEvent:()=>zh,getGameRoomV2:()=>Xh,getLeaderboard:()=>Yh,getPlayerGameProfile:()=>Qh,getPurchaseCatalog:()=>Zh,getResolvedTemplate:()=>eb,getRoomArgs:()=>tb,getShowcaseValue:()=>nb,getTransferDetails:()=>rb,ingestAnalyticsEvents:()=>_a,initiateInventoryTransfer:()=>ob,invokeFunction:()=>ib,kickPlayer:()=>ab,listChallenges:()=>sb,listEntityGameSettings:()=>lb,listEntityOrders:()=>db,listEntityProgressions:()=>cb,listEntitySaves:()=>ub,listEvents:()=>mb,listGameRooms:()=>pb,listResolvedTemplates:()=>gb,listTransfers:()=>fb,maxEntityProgression:()=>yb,putEntityGameSetting:()=>hb,putRoomArgs:()=>bb,putShowcaseValue:()=>vb,rejectTransfer:()=>_b,reportMatchPlayers:()=>wb,requestSaveUploadUrl:()=>Sb,resetEntityProgression:()=>kb,setMatchBackfill:()=>Rb,simulateEntityOrder:()=>Ab,transferHostV2:()=>xb,updateGameRoomV2:()=>Pb});function v(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 Sh(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function kh(t,e,n,r,o,i){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/add`;return t.client.post(s,o,i?.signal)}async function Rh(t,e,n,r){let o=`/v1/voice/sessions/${v(e)}/admin`;return t.client.post(o,n,r?.signal)}async function Ah(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function xh(t,e,n,r,o,i){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/claim`;return t.client.post(s,o,i?.signal)}async function Ph(t,e,n){let r=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.delete(r,n?.signal)}async function Th(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Eh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ih(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Ch(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Mh(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Oh(t,e,n){let r=`/v1/voice/sessions/${v(e)}`;return t.client.delete(r,n?.signal)}async function Gh(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(o,r?.signal)}async function Lh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Dh(t,e,n,r,o,i){let s=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/finalize`;return t.client.post(s,o,i?.signal)}async function $h(t,e,n){let r=`/v1/games/${v(t.gameId())}/config/channels/${v(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Fh(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function qh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/currencies/${v(r)}`;return t.client.get(i,o?.signal)}async function Nh(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function jh(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/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Bh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/items/${v(r)}`;return t.client.get(i,o?.signal)}async function Uh(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/${v(e)}/${v(n)}/${v(r)}`+(s?`?${s}`:"");return t.client.get(a,o?.signal)}async function Wh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/${v(r)}`;return t.client.get(i,o?.signal)}async function Hh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}`;return t.client.get(i,o?.signal)}async function Vh(t,e,n,r,o,i){let s=`/v1/inventory/${v(e)}/${v(n)}/catalogs/${v(r)}/recipes/${v(o)}/availability`;return t.client.get(s,i?.signal)}async function Kh(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/${v(e)}/${v(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Jh(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function zh(t,e,n){let r=`/v1/events/${v(e)}`;return t.client.get(r,n?.signal)}async function Xh(t,e,n){let r=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Yh(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/${v(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Qh(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function Zh(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 eb(t,e,n){let r=`/v1/game-room-templates/${v(e)}`;return t.client.get(r,n?.signal)}async function tb(t,e,n){let r=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/room-args`;return t.client.get(r,n?.signal)}async function nb(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function rb(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function _a(t,e,n){let r=`/v1/games/${v(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function ob(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ib(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function ab(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/kick/${v(n)}`;return t.client.post(o,void 0,r?.signal)}async function sb(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 lb(t,e,n,r){let o=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function db(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/${v(e)}/${v(n)}/orders`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function cb(t,e,n,r){let o=`/v1/inventory/${v(e)}/${v(n)}/progressions`;return t.client.get(o,r?.signal)}async function ub(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/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function mb(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 pb(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/${v(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function gb(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function fb(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 yb(t,e,n,r,o,i){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/max`;return t.client.post(s,o,i?.signal)}async function hb(t,e,n,r,o,i){let s=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.put(s,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function bb(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/room-args`;return t.client.put(o,n,r?.signal)}async function vb(t,e,n,r,o){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(i,r,o?.signal)}async function _b(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function wb(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/matches/${v(e)}/players/report`;return t.client.post(o,n,r?.signal)}async function Sb(t,e,n,r,o,i){let s=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/upload-url`;return t.client.post(s,o,i?.signal,{replaySafe:true})}async function kb(t,e,n,r,o,i){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/reset`;return t.client.post(s,o,i?.signal)}async function Rb(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/matches/${v(e)}/backfill`;return t.client.put(o,n,r?.signal)}async function Ab(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/simulate`;return t.client.post(i,r,o?.signal)}async function xb(t,e,n,r){let o=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}/transfer/${v(n)}`;return t.client.post(o,void 0,r?.signal)}async function Pb(t,e,n,r){let o=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.patch(o,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Tb=1e4,Eb=50,Ib=1e3,Cb=65536-4*1024,yu=t=>typeof t=="number"?t:0,Mb=t=>typeof t=="string"?t:"";function hu(){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 Ob(t){return t?.retryable===true}function Gb(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:yu(i.index),code:Mb(i.code)}}):[];return {accepted:yu(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function bu(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 vu(t){let e=Math.max(1,Math.floor(t.maxQueue??Ib)),n={client:t.client,gameId:()=>t.gameId},r=[],o=0,i=null,s=false,a=null,l=0,d=0,u=false,c=false,g=h=>{t.log?.(h);},p=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},f=()=>Math.max(0,d-t.clock.now()),y=()=>{i!==null||s||a!==null||(i=t.clock.setTimeout(()=>{i=null,k().catch(()=>{});},Math.max(Tb,f())));},R=()=>{let h=Math.min(r.length,100),S=128;for(let C=0;C<h;C+=1){let I=r[C];if(I===void 0)break;if(S+=JSON.stringify(bu(I,0)).length+1,S>Cb)return Math.max(1,C)}return h};async function k(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&&y();}}async function P(h){p();let S=r.splice(0,R()),C=o;o=0;let I=Math.round(t.clock.now()),U={batch_id:hu(),sent_at_ms:I,events:S.map(q=>bu(q,I))};try{let q=await _a(n,U,h===void 0?void 0:{signal:h}),x=Gb(q,C);l=0,d=0;for(let A of x.rejected)g(`[gem] analytics: an event was refused (${A.code}). See the analytics_events section of your game config.`);return x}catch(q){if(Ob(q)){for(r=[...S,...r],o+=C;r.length>e;)r.shift(),o+=1;l+=1,d=t.clock.now()+Lr(l,q);}else g(`[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,C={}){if(s)return;if(typeof h!="string"||h===""){c||(c=true,g(`[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(ai)){u||(u=true,g(`[gem] analytics: '${S}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let I={},U={};for(let[q,x]of Object.entries(C))typeof x=="string"?I[q]=x:typeof x=="number"&&Number.isFinite(x)&&(U[q]=x);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:hu(),playerId:h,name:S,atMs:t.clock.now(),dimensions:I,measures:U}),r.length>=Eb&&a===null&&f()===0?k().catch(()=>{}):y();},flush:h=>k(h),get pending(){return r.length},dispose(){s=true,p(),r=[],o=0;}}}function _u(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().");Pt(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return Er(i)}}}function Lb(t){let e={};for(let[n,r]of Object.entries(wa))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function qt(t,e={}){let n=e.clock??de,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=va(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=br({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new He({transport:i,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=Lb({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,u=t.endMatch,c=t.log,g=vu({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(u===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 u.call(t);},setBackfill:async(f,y)=>{let R=await l.setMatchBackfill(a.matchId,{open:f.open,...f.seats===void 0?{}:{seats:f.seats}},y===void 0?{}:{signal:y});return {open:R.open,seats:R.seats??null}},reportPlayers:async(f,y)=>(await l.reportMatchPlayers(a.matchId,{players:f.map(k=>({player_id:k.playerId,state:k.state}))},y===void 0?{}:{signal:y})).players.map(k=>({playerId:k.player_id,outcome:k.outcome}))},analytics:g,functions:new Xe(l.invokeFunction),challenges:_u(l.listChallenges),...d===void 0?{}:{room:{get:f=>l.getGameRoomV2(d,f),args:async f=>{let y=await l.getGameRoomV2(d,f?.signal===void 0?{}:{signal:f.signal}),R=y.modified?y.body:void 0;if(R?.room_args==null||R.room_args_template==null)throw new G("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:()=>{g.dispose(),o.dispose();}}}function gt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Nt(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function Mn(t){return typeof t=="string"?t:t.slice().buffer}function po(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 Db=5e3,wu=3e4,Su=2e3,$b=1e4,Fb=3,ku=1;async function Ru(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?b=>console.info(b):e.log,i=b=>o?.(`[gem host] ${b}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,u=(b,M)=>{l&&(a=a.then(async()=>{if(!d)try{await M();}catch(N){i(`the bundle's ${b} handler threw: ${ft(N)}. Serving continues.`);}}));},c=true,g,p,f,y=b=>{if(!c)return;c=false,u("leave",()=>s.leave?.(r,{cause:b??"left"}));let M=p;M&&queueMicrotask(()=>M(b));},R={send(b,M){if(!c)return;let N=Nt(gt(M));u("message",()=>s.message?.(r,b,typeof b=="string",{reliable:N.reliable,ordered:N.ordered}));},onMessage(b){g=b;},onClose(b){p=b;},close(){y("closed");}},k=(b,M)=>{if(!c)return;let N=Nt(gt(M));queueMicrotask(()=>{c&&g?.(b,N);});},P=new Map,h=b=>{let M=[];for(let N of je){let Z=b.channels[N];try{Z.binaryType="arraybuffer";}catch{}let ke=Nt(N),Fe=Wt=>{let bt=po(Wt?.data);bt!==null&&u("message",()=>s.message?.(b.playerId,bt.data,bt.isText,{reliable:ke.reliable,ordered:ke.ordered}));};Z.addEventListener("message",Fe),M.push(()=>Z.removeEventListener("message",Fe));}P.get(b.playerId)?.forEach(N=>N()),P.set(b.playerId,M);},S=b=>{P.get(b)?.forEach(M=>M()),P.delete(b);},C=new Set,I=new Map,U=(b,M,N)=>({playerNumber:b.assignedPeerId,transport:"webrtc_p2p",...M?{rejoin:true}:{},...N?{superseded:true}:{}}),q=b=>{let M=P.has(b.playerId),N=C.has(b.playerId);C.add(b.playerId),h(b),M&&u("leave",()=>s.leave?.(b.playerId,{cause:"superseded"})),u("join",()=>s.join?.(b.playerId,U(b,N,M)));},x=new Set,A=(b,M,N)=>{if(b===r){k(M,N);return}let Z=n.peer(b);if(Z===null){let ke=I.get(b);if(ke!==void 0&&e.clock.now()-ke<Su)return;x.has(b)||(x.add(b),i(`send to '${b}' dropped: no such connected player`));return}Z.send(Mn(M),gt(N));},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:b=>e.tokens.subscribe(b),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(b=>b.playerId)??[],players(){let b=c?[r]:[];for(let M of n.peers)b.push(M.playerId);return b},profile(b){let M=e.room()?.members.find(N=>N.playerId===b);if(!(!M||M.displayName===void 0))return {displayName:it.toPlain(M.displayName),...M.displayTag===void 0?{}:{displayTag:it.toPlain(M.displayTag)},...M.discriminator===void 0?{}:{discriminator:M.discriminator}}},playerNumber(b){return b===r?ku:n.peer(b)?.assignedPeerId},send(b,M,N){A(b,M,N);},broadcast(b,M){let N=M?.except;c&&r!==N&&k(b,M);for(let Z of n.peers)Z.playerId!==N&&Z.send(Mn(b),gt(M));},async endMatch(){let b=await Ue();return b.answer!=="ok"&&i(b.cause),b.answer},kick(b,M){if(b===r){y(M??"kicked");return}n.kick(b).catch(N=>{i(`kick of '${b}' failed: ${ft(N)}`);});},log(b){i(b);},warn(b){i(`\u26A0 ${b}`);}},F=()=>{},B=new Promise(b=>{F=b;}),W=[],J=null,ie=async(b,M)=>{l=false;let N=a.then(async()=>{try{await s.shutdown(b);}catch(Z){i(`the bundle's shutdown threw: ${ft(Z)}`);}});a=N,await N,De();for(let Z of W.splice(0))Z();for(let Z of [...P.keys()])S(Z);y(M);},ge=(b,M)=>J||(J=(async()=>{await ie(M,b),n.close(),F();})(),J),X=()=>J||(J=(async()=>{await ie({reason:"signal"},"left"),await n.leave().catch(b=>i(`leaving the match failed: ${ft(b)}`)),F();})(),J),Be=()=>J||(J=(async()=>{l=false;let b=await Ue();b.answer==="ok"?(await ie({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${b.cause}; leaving instead`),await ie({reason:"signal"},"left"),await n.leave().catch(M=>i(`leaving the match failed: ${ft(M)}`))),F();})(),J),Se=null,fe=()=>(Se??=qt(O,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Se),Ue=async()=>{try{return await fl({client:fe().client,gameId:()=>O.gameId},O.matchId,{},{signal:AbortSignal.timeout(Db)}),{answer:"ok"}}catch(b){return b instanceof G&&(b.reason==="forbidden"||b.reason==="not_found")?{answer:b.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${b.reason})`}:{answer:"failed",cause:`ending the match failed: ${ft(b)}`}}},te=null,z=false,le=0,xe,Le=null,De=()=>{z=true,te!==null&&(e.clock.clearTimeout(te),te=null),Le?.(),Le=null;},jn=b=>{i(`heartbeats paused: ${b}; they resume when a fresh play token arrives`),Bt();let M=xe,N=false,Z=e.tokens.subscribe(ke=>{N||z||ke.token===M||nt(ke)||(N=true,Le?.(),Le=null,le=0,xe=void 0,Bt(),i("a fresh play token arrived; heartbeats resume"),te=e.clock.setTimeout(()=>{We();},0));});N?Z():Le=Z;},Bt=()=>{let b=Se;Se=null,b?.dispose();},nt=b=>b.expiresAt*1e3<=e.clock.now(),We=async()=>{if(te=null,!z){try{await fe().client.post(`/v1/games/${encodeURIComponent(O.gameId)}/matches/${encodeURIComponent(O.matchId)}/heartbeat`,void 0,AbortSignal.timeout($b)),le=0,xe=void 0;}catch(b){if(b instanceof G&&(b.reason==="forbidden"||b.reason==="not_found")){i(`the platform no longer holds this match under this host (${b.reason}); heartbeats stop`),De();return}if(qb(b)){if(z)return;le+=1;let M=e.tokens.current(),N=M===void 0?"this host holds no play token":nt(M)?"this host's play token has expired":M.token===xe?"the platform refused this host's play token again":le>=Fb?`the platform refused this host's play token ${le} times in a row`:null;if(xe=M?.token,N!==null){jn(N);return}}else le=0,xe=void 0;i(`heartbeat failed: ${ft(b)}`);}z||(te=e.clock.setTimeout(()=>{We();},wu));}},$e=()=>{z||te!==null||(te=e.clock.setTimeout(()=>{We();},wu));};{let b=F;F=()=>{De(),Se?.dispose(),Se=null,b();};}let Ut=Promise.resolve().then(()=>s.init(O));a=Ut.then(()=>{},()=>{}),u("join",()=>s.join?.(r,{playerNumber:ku,transport:"loopback"})),W.push(n.on("peerJoined",q)),W.push(n.on("peerLeft",(b,M)=>{S(b);let N=e.clock.now();for(let[Z,ke]of I)N-ke>=Su&&I.delete(Z);I.set(b,N),x.delete(b),u("leave",()=>s.leave?.(b,{cause:M}));})),W.push(n.on("error",b=>{i(`\u26A0 session error: ${b.message}`);})),W.push(n.on("matchEnded",b=>{J||Sa(f,b),ge("match ended",{reason:"match_ended",platform_reason:b});})),W.push(n.on("hostChanged",b=>{b!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let b of n.peers)q(b);try{await Ut,$e();}catch(b){l=false,De(),d=true;for(let M of W.splice(0))M();for(let M of [...P.keys()])S(M);throw n.leave().catch(()=>{}),F(),b}return {matchId:n.matchId,localLink:R,onMatchEnded(b){f=b;},end:Be,leave:X,stop:b=>ge(b,{reason:"stopped"}),done:B}}function Sa(t,e){try{t?.(e);}catch{}}function qb(t){return t instanceof G&&t.status===401||ne.isAuthError(t)}function ft(t){return t instanceof Error?t.message:String(t)}function ka(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 Au(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async a=>{r.isHost&&!ba(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!==mt)return ka("dedicated",d.matchId);let u=t.p2p.session?.(d.matchId)??null;if(u===null&&!r.isHost||u!==null&&!u.isHost)return ka("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 g=u??await t.p2p.connect(s(l)),p=await Ru(a,{session:g,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:g.playerId!==""?g.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return o.set(d.matchId,p),p.done.then(()=>{o.get(d.matchId)===p&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>p.end(),leave:()=>p.leave(),stop:()=>p.stop()}},async connect(a={}){let l=await i(a),d=a.onMatchEnded;if(l.protocol===mt){let p=o.get(l.matchId);if(p!==void 0)return r.notifyMatchConnected(l.matchId),Ub(l.matchId,p,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 Rn(),y=async()=>t.p2p.connect({...s(a),certificate:f}),R=await y(),k=Hb(R,y,d,P=>{r.notifyMatchDisconnected(P).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(R.matchId,{redial:k.redial,abandon:k.abandon}),k.onClosed(()=>{e.get(R.matchId)?.abandon===k.abandon&&e.delete(R.matchId);})),k}let u=async(p=null)=>await t.dedicated.connect({...p===null?{}:{reportConnected:false,redial:true,...p.deadlineAt===void 0?{}:{deadlineAt:p.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 u(),g=Wb(c,u,r,n);return n&&(e.set(c.matchId,{redial:g.redial,abandon:g.abandon}),g.onClosed(()=>{e.get(c.matchId)?.abandon===g.abandon&&e.delete(c.matchId);})),g},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 xu="link_closed",Nb="host_unreachable",jb=new Set(["failed","closed"]);function Bb(t){return jb.has(t)?xu:Nb}function Ub(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 Wb(t,e,n,r){let o=t.matchId,i=t,s="connected",a,l,d=[],u=false,c=false,g=f=>{if(s!=="closed"){s="closed";for(let y of d.splice(0))y();l?.(f);}},p=f=>{f.link.onMessage((y,R)=>a?.(y,R)),f.link.onClose(y=>{if(f!==i||s==="closed")return;if(u||!r){g(y);return}let R=n.matchSession;if(R.phase==="suspended"&&R.matchId===o){s="suspended";return}g(y);});};return p(t),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return s},send(f,y){s==="connected"&&i.link.send(f,y);},onMessage(f){a=f;},onClose(f){l=f;},close(){if(s!=="closed"){if(u=true,s==="suspended"){g("closed");return}i.close(),g("closed");}},async redial(f){if(s==="closed"||u)return "closed";if(c)return "connected";c=true;let y;try{y=await e(f===void 0?{}:{deadlineAt:f});}finally{c=false;}return u||s==="closed"?(y.close(),"closed"):(i=y,p(y),s="connected",n.notifyMatchConnected(o),"connected")},abandon(f){s!=="closed"&&(s==="connected"&&i.close(),g(f));},onClosed(f){s==="closed"?f():d.push(f);}}}function Hb(t,e,n,r,o,i=false){let s=t.matchId,a=t,l,d,u=[],c=[],g=[],p=false,f=false,y=false,R=false,k="connected",P=A=>{if(p)return;p=true,k="closed";for(let F of u.splice(0))F();for(let F of c.splice(0))F();for(let F of g.splice(0))F();let O=d;O&&queueMicrotask(()=>O(A));},h=A=>{for(let O of u.splice(0))O();for(let O of je){let F=A.channels[O];try{F.binaryType="arraybuffer";}catch{}let B=Nt(O),W=J=>{let ie=po(J?.data);ie!==null&&l?.(ie.data,B);};F.addEventListener("message",W),u.push(()=>F.removeEventListener("message",W));}},S=()=>a.peer(a.hostPlayerId),C=A=>{if(!(p||a.isHost)&&k!=="suspended"){if(r?.(A),i){k="suspended";return}P(A);}},I=A=>{for(let O of je){let F=A.channels[O];if(typeof F.addEventListener!="function")continue;let B=()=>{S()===A&&C(xu);};F.addEventListener("close",B),u.push(()=>F.removeEventListener?.("close",B));}},U=A=>{h(A),I(A),!p&&(k="connected",o?.());},q=A=>{for(let O of c.splice(0))O();c.push(A.on("migrating",()=>{R=true;})),c.push(A.on("hostChanged",O=>{if(R=false,O===A.playerId){P("host_migrated_here");return}let F=S();F!==null&&U(F);})),c.push(A.on("peerJoined",O=>{O.playerId===A.hostPlayerId&&U(O);})),c.push(A.on("matchEnded",O=>{p||Sa(n,O),P(O);})),c.push(A.on("peerLeft",(O,F)=>{O===A.hostPlayerId&&C(Bb(F));}));};q(a);let x=S();return x!==null&&U(x),{matchId:s,protocol:"p2p",get state(){return k},send(A,O){k==="connected"&&S()?.send(Mn(A),gt(O));},onMessage(A){l=A;},onClose(A){d=A;},close(){f=true,P("closed"),a.leave().catch(()=>{});},async redial(){if(k==="closed")return "closed";if(k==="connected"||y)return "connected";if(R)throw new $("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");y=true;let A;try{for(let F of u.splice(0))F();for(let F of c.splice(0))F();a.close(),A=await e();}finally{y=false;}if(p)return f?A.leave().catch(()=>{}):A.close(),"closed";a=A,q(a);let O=S();if(O===null)throw a.close(),new $("connection_failed","this peer rejoined the match but the host never answered with a link");return U(O),"connected"},abandon(A){P(A);},onClosed(A){p?A():g.push(A);}}}function Pu(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 Vb=12e4;function yt(t,e){return {outcome:t,reason:e}}function Tu(t){let e=false,n=new Map,r=(o,i,s,a)=>{if(!t.bridge.parentSupports(o))return Promise.resolve(yt("unavailable","error"));if(e)return Promise.resolve(yt("declined","busy"));let l=`purchase-${_e()}`;return new Promise(d=>{let u={},c=p=>{n.delete(l)&&(e=false,t.clock.clearTimeout(u.timer),d(p));};e=true,n.set(l,{finish:c,check:s,label:a}),u.timer=t.clock.setTimeout(()=>c(yt("unavailable","error")),t.timeoutMs??Vb);let g=false;try{g=i(l);}catch{}g||c(yt("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(yt(i,Ol(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(yt("unavailable","error"));return}(async()=>{let u;try{u=await d;}catch{u="unknown";}if(u==="granted"){a(l===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:l});return}u==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(yt("unavailable","error"));})();}}}async function Eu(t,e){try{return (await Ys(t,e)).granted?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}var Kb="small_human",Iu=/^[a-z][a-z0-9_]{0,31}$/,Cu=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Jb=8;function Ra(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:Kb,id:e,modelUrl:n,iconUrl:r}]}function zb(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 Xb(t){let e=t??{},n=typeof e.item_id=="string"&&Cu.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&Iu.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=Tt(e.icon_url),l=Tt(e.model_url),d=[];for(let u of Array.isArray(e.prices)?e.prices:[]){let c=u??{};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 Yb(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&Iu.test(n)&&!e.includes(n)&&e.push(n),e.length===Jb)break;return e}function Mu(t){let e=new Set,n=Ra(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=Ra(o);if(!zb(n,i)){n=i;for(let s of [...e])try{s(i);}catch(a){r(a);}}}),{async families(){return Yb(await t.configFamilies())},worn(o){let i=Ra(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=Xb(s);a!==void 0&&i.push(a);}return i},purchase(o){let i=o?.itemId,s=o?.currencySlug;return typeof i!="string"||!Cu.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 Ou(t,e){try{return (await Is(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}function Gu(t){return Ws(t)}var Qb=6e5;function Lu(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??Qb);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 Zb=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),ev=["utm_"];function Du(t){return Zb.has(t)||ev.some(e=>t.startsWith(e))}var $u=16,Fu=512,tv=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,nv=/[\p{Cc}\p{Cf}]/u,rv=/\p{Cs}/u,Oe="[gem] gem.share.request:";function qu(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(`${Oe} 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(`${Oe} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!ov(l))throw new TypeError(`${Oe} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>$u)throw new TypeError(`${Oe} at most ${$u} params; got ${d.length}`);let u=[];for(let[c,g]of d){let p=JSON.stringify(c);if(!tv.test(c))throw new TypeError(`${Oe} param ${p}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Du(c))throw new TypeError(`${Oe} param ${p} is reserved: the arcade reads it itself and never forwards it`);if(typeof g!="string")throw new TypeError(`${Oe} param ${p}: values must be strings`);if(g.length>Fu)throw new TypeError(`${Oe} param ${p}: a value is at most ${Fu} characters`);if(nv.test(g))throw new TypeError(`${Oe} param ${p}: control and format characters are not allowed`);if(rv.test(g))throw new TypeError(`${Oe} param ${p}: a value must be well-formed text`);u.push({key:c,value:g});}!a.requestShare(u)&&!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 ov(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var On=3e4,Aa=12e4;function Gn(t,e,n){return t.held?Promise.resolve(n):(t.held=true,e().then(r=>(t.held=false,r)))}function ue(t,e,n){return {outcome:t,reason:e,...n}}function et(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 Nu(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 u=false;try{u=r(s);}catch{}u||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 iv=12,av=24,xa=Object.freeze({games:Object.freeze([])});function sv(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 go(t){return ue("unavailable","error",t)}function ju(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 u=l().then(c=>(i.delete(a),c));return i.set(a,u),u};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 go({});let l=a;return {...et(a),...l.arcade===void 0?{}:{arcade:{store:l.arcade.store}},...l.game===void 0?{}:{game:{store:l.game.store}}}},On)):Promise.resolve(ue("unavailable","unsupported",{}))},openApp(a){return e.parentSupports("appLinks")?a!=="arcade"&&a!=="game"?Promise.resolve(ue("unavailable","invalid_argument",{})):Gn(r,()=>n.ask("gem.openAppResult",l=>e.requestArcade({type:"gem.requestOpenApp",requestId:l,target:a}),l=>l===null?go({}):et(l),Aa),ue("declined","busy",{})):Promise.resolve(ue("unavailable","unsupported",{}))},openGame(a){if(!e.parentSupports("openGame"))return Promise.resolve(ue("unavailable","unsupported",{}));let l=typeof a=="string"?a.toLowerCase():"";return El({gem:j,type:"gem.requestOpenGame",requestId:"-",ref:l})!==null?Promise.resolve(ue("unavailable","invalid_argument",{})):Gn(r,()=>n.ask("gem.openGameResult",u=>e.requestArcade({type:"gem.requestOpenGame",requestId:u,ref:l}),u=>u===null?go({}):et(u),Aa),ue("declined","busy",{}))},similarGames(a){if(!e.parentSupports("openGame"))return Promise.resolve(ue("unavailable","unsupported",xa));let l=a?.limit;return l!==void 0&&(typeof l!="number"||!Number.isInteger(l)||l<1||l>av)?Promise.resolve(ue("unavailable","invalid_argument",xa)):s(`similar:${l??iv}`,()=>n.ask("gem.similarGamesResult",d=>e.requestArcade({type:"gem.requestSimilarGames",requestId:d,...l===void 0?{}:{limit:l}}),d=>{if(d===null)return go(xa);let u=et(d),c=d,g=u.outcome==="ok"?Object.freeze(c.games.map(sv)):[];return {...u,games:g}},On))}}}var lv=64,Bu=Object.freeze({offers:Object.freeze([])});function dv(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 Uu(t){let{bridge:e,asker:n,acting:r}=t,o=new Set,i=null;function s(a,l,d,u){return e.parentSupports(a)?typeof u!="string"||u.length===0||u.length>lv?Promise.resolve(ue("unavailable","invalid_argument",{})):Gn(r,()=>n.ask(d,c=>e.requestArcade({type:l,requestId:c,skuId:u}),c=>c===null?ue("unavailable","error",{}):et(c)).then(c=>((c.outcome==="ok"||c.reason==="error")&&t.onPurchaseEnded?.(),c)),ue("declined","busy",{})):Promise.resolve(ue("unavailable","unsupported",{}))}return {api:{get available(){return e.currentState==="connected"&&e.parentSupports("store")},get showOfferAvailable(){return e.currentState==="connected"&&e.parentSupports("storeOfferSheet")},offers(){return e.parentSupports("store")?(i!==null||(i=n.ask("gem.storeOffersResult",a=>e.requestArcade({type:"gem.requestStoreOffers",requestId:a}),a=>{if(a===null)return ue("unavailable","error",Bu);let l=et(a),d=a,u=l.outcome==="ok"?Object.freeze(d.offers.map(dv)):[];return {...l,offers:u}},On).then(a=>(i=null,a))),i):Promise.resolve(ue("unavailable","unsupported",Bu))},purchase(a){return s("store","gem.requestStorePurchase","gem.storePurchaseResult",a)},showOffer(a){return s("storeOfferSheet","gem.requestStoreOfferSheet","gem.storeOfferSheetResult",a)},onSettled(a){return o.add(a),()=>{o.delete(a);}}},settled(a){t.onPurchaseEnded?.();let l=Object.freeze({skuId:a.skuId});for(let d of [...o])try{d(l);}catch(u){t.onListenerError?.(u);}}}}var zu="https://gemarcade.com/branding/manifest.json",cv=1,Wu=256*1024,uv=256,mv=64,pv=256,Hu=8e3,gv=6e4,fv=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Vu={GEMS:"gems-mark",ARCADE_TICKETS:"ticket-mark"},Ku=Object.freeze({outcome:"unavailable"}),Ju=Object.freeze({outcome:"not_found"});function ht(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function yo(t){return typeof t=="string"&&t!==""&&t.length<=pv}function yv(t,e){if(!yo(t))return;let n;try{n=new URL(t,e);}catch{return}let r=Tt(n.href);if(r!==void 0)return n.origin===new URL(e).origin?r:ei(r)}function hv(t,e){let n=t??{},r=yv(n.url,e);if(!(r===void 0||!yo(n.type))&&!(typeof n.bytes!="number"||!(n.bytes>=0))&&!(n.theme!==void 0&&n.theme!=="light"&&n.theme!=="dark"))return Object.freeze({url:r,type:n.type,bytes:n.bytes,...ht(n.width)?{width:n.width}:{},...ht(n.height)?{height:n.height}:{},...ht(n.size)?{size:n.size}:{},...ht(n.density)?{density:n.density}:{},...n.vector===true?{vector:true}:{},...n.theme===void 0?{}:{theme:n.theme}})}function bv(t,e=zu){let n;try{n=JSON.parse(t);}catch{return null}let r=n??{};if(r.format!==cv||!Array.isArray(r.assets))return null;let o=[],i=new Set;for(let s of r.assets.slice(0,uv)){let a=s??{};if(!yo(a.id)||!fv.test(a.id)||i.has(a.id)||!yo(a.kind)||!Array.isArray(a.variants))continue;let l=[];for(let d of a.variants.slice(0,mv)){let u=hv(d,e);u!==void 0&&l.push(u);}l.length!==0&&(i.add(a.id),o.push(Object.freeze({id:a.id,kind:a.kind,variants:Object.freeze(l)})));}return Object.freeze(o)}function fo(t){let e;for(let n of t)(e===void 0||(n.width??0)>(e.width??0))&&(e=n);return e}function vv(t,e,n){let r=t.find(l=>l.vector===true),o=t.filter(l=>l.size===void 0);if(e===void 0)return r??fo(o)??fo(t);let i=t.filter(l=>l.size===e);if(i.length>0){let l=u=>u.density??1,d=i.filter(u=>l(u)>=n);return d.length>0?d.reduce((u,c)=>l(c)<l(u)?c:u):i.reduce((u,c)=>l(c)>l(u)?c:u)}if(r!==void 0)return r;let s=o.filter(l=>(l.width??0)>=e*n);return (s.length>0?s.reduce((l,d)=>(d.width??0)<(l.width??0)?d:l):void 0)??fo(o)??fo(t)}function _v(t,e){let n=e.theme===void 0?[]:t.variants.filter(a=>a.theme===e.theme),r=t.variants.filter(a=>a.theme===void 0),o=[n,r].filter(a=>a.length>0);if(t.kind!=="image")return o[0]?.[0];let s=(e.size===void 0?void 0:o.find(a=>a.some(l=>l.size===e.size)))??o[0];return s&&vv(s,e.size,e.density)}function wv(t,e){if(e!==void 0){if(e===null||typeof e!="object")throw new TypeError(`[gem] branding.${t}: options must be an object`);if(e.size!==void 0&&!ht(e.size))throw new RangeError(`[gem] branding.${t}: size must be a positive number of CSS px`);if(e.density!==void 0&&!ht(e.density))throw new RangeError(`[gem] branding.${t}: density must be a positive number`);if(e.theme!==void 0&&e.theme!=="light"&&e.theme!=="dark")throw new TypeError(`[gem] branding.${t}: theme must be 'light' or 'dark'`)}}function Xu(t){let e=t.manifestUrl??zu,n=null,r=null,o=-1/0,i=false,s=u=>(o=t.clock.now(),i||(i=true,t.log?.(`[gem] gem.branding could not read the platform's branding (${u}), so every lookup answers 'unavailable' and your bundled fallback shows. If your page sets a Content-Security-Policy, allow ${new URL(e).origin} in connect-src and img-src.`)),null),a=async()=>{if(t.fetch===null)return s("this page has no fetch");let u=t.fetch,c=typeof AbortController=="function"?new AbortController:null,g,p=new Promise(y=>{g=t.clock.setTimeout(()=>{c?.abort(),y(s(`no answer in ${Hu} ms`));},Hu);}),f=(async()=>{let y=await u(e,{credentials:"omit",redirect:"error",...c?{signal:c.signal}:{}});if(!y.ok)return s("the manifest answered an error");if(Number(y.headers.get("content-length"))>Wu)return s("the manifest is too large");let R=await y.text();return R.length>Wu?s("the manifest is too large"):bv(R,e)??s("the manifest is not format 1 JSON")})().catch(()=>s("the request failed"));try{return await Promise.race([f,p])}finally{t.clock.clearTimeout(g);}},l=()=>n!==null?Promise.resolve(n):r!==null?r:t.clock.now()-o<gv?Promise.resolve(null):(r=a().then(u=>(r=null,u!==null&&(n=u),u)),r),d=async(u,c,g,p)=>{wv(u,p);let f=await l();if(f===null)return Ku;let y=f.find(P=>P.id===c&&P.kind===g);if(y===void 0)return Ju;let R=t.devicePixelRatio(),k=_v(y,{...p?.size===void 0?{}:{size:p.size},density:p?.density??(ht(R)?R:1),...p?.theme===void 0?{}:{theme:p.theme}});return k===void 0?Ju:Object.freeze({outcome:"ok",url:k.url,variant:k,asset:y})};return Object.freeze({get:async(u,c)=>{if(typeof u!="string"||u==="")throw new TypeError("[gem] branding.get: id must be a non-empty string");if(c===null||typeof c!="object"||typeof c.kind!="string")throw new TypeError("[gem] branding.get: options.kind must be a string, such as 'image'");return d("get",u,c.kind,c)},logo:u=>d("logo","gem-logo","image",u),wordmark:u=>d("wordmark","gem-wordmark","image",u),currencyMark:async(u,c)=>{let g=Object.prototype.hasOwnProperty.call(Vu,u)?Vu[u]:void 0;if(g===void 0)throw new TypeError("[gem] branding.currencyMark: currency must be 'GEMS' or 'ARCADE_TICKETS', not "+JSON.stringify(String(u).slice(0,40)));return d("currencyMark",g,"image",c)},trophy:u=>d("trophy","trophy-mark","image",u),list:async()=>{let u=await l();return u===null?Ku:Object.freeze({outcome:"ok",assets:u})}})}var Av="(any-pointer: coarse)";function xv(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 Yu(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?u=>matchMedia(u):void 0},o=r.navigator,i,s=new Set,a=()=>typeof o?.vibrate!="function"||r.matchMedia===void 0?false:(i??=r.matchMedia(Av),i.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(u,c)=>{s.has(u)||(s.add(u),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return a()||l()},vibrate(u){let c=a();if(!c&&!l())return false;let g=xv(u);if(g===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(g)===!0}catch{return false}let p=e.requestVibrate(g);return p||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),p}}}var jt=Math.PI/180,Ge=Object.freeze({touch:Object.freeze({yaw:1*jt,pitch:.66*jt}),mouse:Object.freeze({yaw:.5*jt,pitch:.5*.77*jt}),stick:Object.freeze({yaw:240*jt,pitch:240*.77*jt}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Pa="[gem.controls]",Ta=Object.freeze({yaw:0,pitch:0}),ho=t=>Number.isFinite(t)?t:0,Qu=(t,e)=>({yaw:t+0,pitch:e+0});function Zu(t){let e=ho(t),n=(Math.abs(e)-Ge.stickDeadzone)/(1-Ge.stickDeadzone),r=Ge.stickCurve,o=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,o))+0}function Pv(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Ge.touchPitchMin)+Ge.touchPitchMin}function em(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${Pa} ${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(`${Pa} ${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(`${Pa} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function Tv(t,e){let n=em(e,"look()"),r=n.sensitivity,o=n.gamepadSensitivity,i=n.invertY,s=a=>i??a?.invertLookY??false;return {fromPointer(a,l,d,u){let c=ho(a),g=ho(l);if(c===0&&g===0)return Ta;let p=t(),f=r??(p===null?void 0:p.lookSensitivity/100)??1,y=d==="touch"||d==="pen",R=y?Ge.touch:Ge.mouse,k=c*R.yaw*f,P=-g*R.pitch*f;return s(p)&&(P=-P),y&&u!==void 0&&Number.isFinite(u)&&P*u>0&&(P*=Pv(u)),Qu(k,P)},fromStick(a,l,d){let u=ho(d);if(u<=0)return Ta;let c=Zu(a),g=Zu(l);if(c===0&&g===0)return Ta;let p=t(),f=o??(p===null?void 0:p.gamepadLookSensitivity/100)??1,y=c*Ge.stick.yaw*u*f,R=-g*Ge.stick.pitch*u*f;return s(p)&&(R=-R),Qu(y,R)},set(a){let l=em(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(o=l.gamepadSensitivity),"invertY"in l&&(i=l.invertY);}}}function tm(t){return {look:e=>Tv(t.recommended,e),LOOK_BASE:Ge}}var nm=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),rm=/^[A-Za-z0-9_-]{1,40}$/;function Ea(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function om(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function im(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 am(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 im(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 sm(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"||!rm.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(g=>g.id===l)){e(`${d} was dropped: an earlier setting has the same id.`);continue}let u=om(a.label);if(u===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:u,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 g=a.min??0,p=a.max??100,f=a.step??1;if(!Ea(g)||!Ea(p)||!Ea(f)||g>=p||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:u,kind:"slider",value:im(a.value,g,p,f),min:g,max:p,step:f};break}case "choice":{let g=[];for(let p of Array.isArray(a.options)?a.options:[]){if(g.length===4)break;if(typeof p!="object"||p===null)continue;let f=p,y=om(f.label);typeof f.id!="string"||!rm.test(f.id)||y===void 0||g.some(R=>R.id===f.id)||g.push({id:f.id,label:y});}if(g.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"||!g.some(p=>p.id===a.value)){e(`${d} was dropped: a choice's value is the id of one of its options.`);continue}c={id:l,label:u,kind:"choice",value:a.value,options:g};break}default:e(`${d} was dropped: its kind must be 'toggle', 'slider' or 'choice'.`);continue}a.icon!==void 0&&(nm.includes(a.icon)?c.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${nm.join(", ")}.`)),n.push(c);}return n}var Ev=500;function lm(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")},u=()=>{if(n===null||i!==null)return;let c=JSON.stringify(n);if(c===r)return;let g=o+Ev-e.now();if(g>0){i=e.setTimeout(()=>{i=null,u();},g);return}t.frame().declareSettings(n)&&(r=c,o=e.now());};return {api:{declare(c){let g=sm(c,p=>l(`[gem] gem.settings.declare: ${p}`));return g===null?(l("[gem] gem.settings.declare did nothing: pass an array of settings, or [] for none."),false):(n=g,u(),d())},onChange(c){if(typeof c!="function")return ()=>{};let g=p=>c(p);return s.add(g),()=>{s.delete(g);}}},forgetSent(){r=null,o=-1/0;},flush:u,onSettingChange(c){let g=n?.findIndex(k=>k.id===c.id)??-1,p=n?.[g];if(n===null||p===void 0)return;let f=am(p,c.value);if(f===void 0)return;let y=JSON.stringify(n);n=n.map((k,P)=>P===g?{...k,value:f}:k),r===y&&(r=JSON.stringify(n));let R={id:p.id,value:f};for(let k of [...s])try{k(R);}catch(P){console.error("[gem] a gem.settings.onChange handler threw:",P);}}}}function dm(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var Iv=/(?:Z|[+-]\d{2}:?\d{2})$/i;function cm(t){if(typeof t!="string"||!Iv.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function Ln(){return {declared:false,grantable:false,heldLimitReached:false}}function um(t,e){let n=typeof t=="object"&&t!==null?t:{},r=cm(n.resets_at),o=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...Ln(),...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=cm(a),d=n.held_limit_reached===true,u=a!=null,c=i!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!c&&!u&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...o}}var Cv=18e4,Ia=32,Mv=/^[a-z0-9_-]+$/,Ov="rewarded_requires_user_gesture";function Gv(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var Lv=1e3;function Dv(){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<=Lv)return true}return false}var mm=1e4;function $v(t){return t==="interstitial"||t==="rewarded"}function pm(t){return typeof t=="string"&&t!==""&&t.length<=Ia&&Mv.test(t)}function Fv(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function bo(t){return typeof t=="string"?JSON.stringify(t):typeof t}function gm(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 u=t.log;if(u!==null)try{u===void 0?console.warn(`[gem] ${d}`):u(`[gem] ${d}`);}catch{}},l=d=>{let u=t.readAvailability;if(u===void 0)return Promise.resolve(Ln());let c=r.get(d);if(c!==void 0)return c;let g=new Promise(p=>{let f={},y=h=>f.done===true?false:(f.done=true,t.clock.clearTimeout(f.timer),p(h),true),R=(h,S)=>{!y(Ln())||o.has(h)||(o.add(h),i(`gem.ads.rewardedStatus("${d}") answered not grantable: ${S}. Said once.`));},k=h=>{R(Fv(h),`the read failed (${h instanceof Error?h.message:bo(h)})`);},P;try{P=Promise.resolve(u(d,AbortSignal.timeout(mm)));}catch(h){P=Promise.reject(h);}f.timer=t.clock.setTimeout(()=>{R("timeout","no answer within 10 s");},mm),P.then(h=>{try{y(um(h,t.bridge.parentSupports("ads")));}catch(S){k(S);}},k);});return r.set(d,g),g.then(()=>{r.get(d)===g&&r.delete(d);}),g};return {api:{rewardedStatus(d){return pm(d)?l(d):(i(`gem.ads.rewardedStatus(${bo(d)}) answered not grantable: a placement is 1..${String(Ia)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(Ln()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let u=d?.placement,c=d?.format;if(!pm(u)||!$v(c))return i(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${bo(u)}, format ${bo(c)}. A placement is 1..${String(Ia)} 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 p;try{p=(t.userActivation??Gv)();}catch{p=void 0;}if(p===false)try{(t.recentGamepadInput??Dv)()===!0&&(p=!0);}catch{}if(p===false){let f=`${Ov}: gem.ads.requestAd("${u}", '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(f),a(f),Promise.resolve({outcome:"no_ad"})}}let g=`ad-${_e()}`;return new Promise(p=>{let f={},y=k=>{n.delete(g)&&(e=false,t.clock.clearTimeout(f.timer),p(k));};e=true,n.set(g,y),f.timer=t.clock.setTimeout(()=>{y({outcome:"unavailable"});},t.timeoutMs??Cv);let R=false;try{R=t.bridge.requestAd(g,u,c);}catch{}R||y({outcome:"no_ad"});})}},settle(d){let u=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${u}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:u});}}}var fm=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),ym=18e4,qv=1e4,Nv=/^[a-z0-9_-]{1,32}$/;function Ca(t){return typeof t=="string"?JSON.stringify(t):typeof t}var Dn=Object.freeze({shown:false});function hm(t){let e=new Map,n,r=false,o=i=>{try{t.onDropped?.(i);}catch{}return Dn};return {api:{signal(i){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(Dn):(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,l=i?.wall;if(!fm.includes(s)||a!==void 0&&(typeof a!="string"||!Nv.test(a))||l!==void 0&&typeof l!="boolean")return Promise.resolve(o(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${Ca(s)}, placement ${Ca(a)}, wall ${Ca(l)}. A kind is one of ${fm.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(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 d=t.clock.now();if(n!==void 0&&d-n<qv)return Promise.resolve(o(`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 u=`moment-${_e()}`;return new Promise(c=>{let g={},p=(y,R)=>{e.delete(u)&&(t.clock.clearTimeout(g.timer),R&&(n=t.clock.now()),c(y));};e.set(u,y=>p(y,!0)),g.timer=t.clock.setTimeout(()=>{e.has(u)&&(p(Dn,!0),o(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??ym)/1e3)} s. Answering shown: false.`));},t.timeoutMs??ym);let f=!1;try{f=t.bridge.signalMoment(u,s,a,l===!0?!0:void 0);}catch{}f||p(Dn,!1);})}catch{return Promise.resolve(Dn)}}},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 Ma=16384;function bm(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:jv(e)}function jv(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 Bv=1e4,Uv=5e3;function vm(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=Uv){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(u),l(),a(e);},u=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=bm(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(u=>{let c={},g=f=>{o.delete(d)&&(t.clock.clearTimeout(c.timer),f==="stored"&&(e=l,n=true,i()),u(f));};o.set(d,g),c.timer=t.clock.setTimeout(()=>g("unavailable"),t.timeoutMs??Bv);let p=false;try{p=t.bridge.putDeviceSettings(d,l);}catch{}p||g("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 $n=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 Wv=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Hv(t){return typeof t=="string"&&Wv.test(t)}function vo(t){if(t===null||Hv(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 _m(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Ga(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 _o(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 wm(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Vv(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,u=t.avatar3dId,c={displayName:n,displayHandle:o??n,badges:(t.badges??[]).map(y=>({itemId:y.itemId,iconUrl:y.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),u&&l.test(u)&&(c.avatar3dId=u),t.avatar3dModelUrl&&(c.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(c.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(c.avatars3d=t.avatars3d.filter(y=>l.test(y.id)&&/^[a-z][a-z0-9_]*$/.test(y.family)).filter((y,R,k)=>k.findIndex(P=>P.family==y.family)==R).map(({family:y,id:R,modelUrl:k,iconUrl:P})=>({family:y,id:R,modelUrl:k,iconUrl:P})));let g=t.boost,p=(g?.multipliers??[]).map(y=>({currencyId:y.currencyId,currencySlug:y.currencySlug,multiplier:y.multiplierBp/1e4})),f=p.some(y=>y.multiplier>1);return c.boost=f&&g?.expiresInDays?{active:f,multipliers:p,expiresInDays:g.expiresInDays}:{active:f,multipliers:p},c}var Kv=1e4,Jv=["appLinks","openGame","store","storeOfferSheet"],Oa=new WeakMap;function km(t,e){if(Oa.has(t))throw new Error("admitBuildEmbedders: already admitted");Oa.set(t,Object.freeze([...e]));}var Fn=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??de,this.inbound=new zt(this.clock),this.outbound=new zt(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=>kt(a,e.origin))||cr(e.origin,this.options.selfOrigin)||(Oa.get(this)??[]).some(a=>kt(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=dr["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!kt(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=Il(ar,o.versions);return s===null?(i.onmessage=null,i.postMessage({gem:j,type:"gem.error",code:"version_mismatch",message:`frame supports v${ar.min}..v${ar.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=Kv){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:_m(e.origin.x),y:_m(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=vo(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",...Ga(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:j,type:"gem.menu",..._o(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}setMenuStyle(e){return this.gated("menuStyle")?this.send(e===null?{gem:j,type:"gem.menuStyle"}:{gem:j,type:"gem.menuStyle",ground:e.ground,accent:e.accent}):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:wm(e.fps,1e3),frameTimeP95Ms:wm(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,o){return this.send({gem:j,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r},...o===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,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(lr(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(sr)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(sr)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(sr)&&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=dr[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||Sm(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=dr[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=lr(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 Sm(n.slice(1)),this.options.onScreenshot(d,l,(u,c)=>this.screenshotDenied(u,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?.(Vv(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(Jv.includes(lr(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 Sm(t){for(let e of t)try{e?.close?.();}catch{}}var Rm="https://api.gemarcade.com";function La(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 zv=new Set(["localhost","127.0.0.1","[::1]"]);function Am(t){let e=La(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!zv.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 Tm="/gem-embedders.json",wo=4096,xm=16,Pm=5e3,qn=Object.freeze({origins:Object.freeze([])});function tt(t){return {origins:[],refused:`[gem] ${Tm} was ignored: ${t}`}}function Xv(t){if(t.trim()==="")return qn;let e;try{e=JSON.parse(t);}catch{return tt("it is not JSON.")}if(e===null||typeof e!="object"||Array.isArray(e))return tt('it must be an object, { "embedders": [...] }.');let n=e.embedders;if(n===void 0)return qn;if(!Array.isArray(n))return tt('"embedders" must be an array of origins.');if(n.length>xm)return tt(`"embedders" has more than ${xm} entries.`);let r=n.filter(o=>typeof o!="string"||!St(o)||!o.toLowerCase().startsWith("https://")||Je(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 tt(`${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 Em(t){let e=typeof AbortController=="function"?new AbortController:null,n,r=new Promise(i=>{n=t.clock.setTimeout(()=>{e?.abort(),i(tt(`it took more than ${Pm} ms to read.`));},Pm);}),o=(async()=>{let i=await t.fetch(t.selfOrigin+Tm,{credentials:"omit",redirect:"error",...e?{signal:e.signal}:{}});if(!i.ok||(i.headers.get("content-type")??"").toLowerCase().includes("text/html"))return qn;if(Number(i.headers.get("content-length"))>wo)return tt(`it is larger than ${wo} bytes.`);let a=await i.text();return a.length>wo?tt(`it is larger than ${wo} bytes.`):Xv(a)})().catch(()=>qn);try{return await Promise.race([o,r])}finally{t.clock.clearTimeout(n);}}function Im(t){if(typeof t!="string"||!St(t))return null;let e=t.slice(0,t.indexOf(":")).toLowerCase();return e==="https"||e==="http"?t:null}function Cm(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function Yv(){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 Qv=Object.freeze({small_human:Cm([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:Cm(Yv())});var e_=Object.freeze(["https://gemarcade.com","https://developer.gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),t_=Rm,n_=["top-left","top-right","bottom-left","bottom-right"];function Mm(t){let e=[1,3,5].map(n=>{let r=parseInt(t.slice(n,n+2),16)/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function r_(t){if(t===null)return null;let{ground:e,accent:n}=Object(t);for(let[s,a]of [["ground",e],["accent",n]]){if(typeof a=="string"&&/^#[0-9a-fA-F]{6}$/.test(a))continue;let l=typeof a=="string"?JSON.stringify(a.slice(0,48)):`a value of type ${typeof a}`;console.warn(`[gem] setMenuStyle: ${s} is ${l}, which is not #rrggbb, so nothing was sent.`);return}let r={ground:e.toLowerCase(),accent:n.toLowerCase()},o=[Mm(r.ground),Mm(r.accent)],i=(Math.max(...o)+.05)/(Math.min(...o)+.05);if(i>=3)return r;console.warn(`[gem] setMenuStyle: accent ${r.accent} reaches ${Math.floor(i*100)/100}:1 against ground ${r.ground}, under the 3:1 it needs, so nothing was sent.`);}var Om=8e3,So=15e3,o_=9e4,i_=1/0,a_=8e3,s_=5e3,l_=5e3;async function d_(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 Nn(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 RE(t={}){let e=t.clock??de,n=t.log===void 0?m=>console.info(m):t.log,r=t.baseUrl??void 0;if(r!=null){let m=La(r);if(m!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${m}. 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=pd(o),s=Nd(o),a=ea();a.mark("sdk created");let l=()=>Nr(ae.gameVersion,t.clientVersion?.gameVersion),d=new cn({client:()=>vt,clock:e,gameId:()=>ae.identity?.gameId??null,playerId:()=>ae.identity?.playerId??null,awaitPlayerId:async()=>(await er(So)).playerId,declarations:async()=>(await Zn.load())?.analytics_events,environment:()=>{let m=l();return {sdk_version:ss(),...m===null?{}:{game_version:m}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),u=Ac(()=>{a.mark("engaged"),d.release(),D.reportEngaged();},typeof window>"u"?{}:window),c=m=>{if(m===false)return null;let T=m?.attempts??i_,L=m?.budgetMs??o_;return !(T>0)||!(L>0)?null:{attempts:T,budgetMs:L,maxDelayMs:m?.maxDelayMs??a_}},g=m=>{m.on("created",()=>{a.mark("room created");}),m.on("joined",()=>{a.mark("room joined");}),m.on("matchAllocationStarted",()=>{a.mark("allocation started");}),m.on("matchReady",()=>{a.mark("match ready");}),m.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 $n;let p=t.allowedEmbedders;if(p!=null&&!Array.isArray(p))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(p??[]),y=f.filter(m=>typeof m!="string"||!St(m));if(y.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${y.length===1?"an entry":"entries"} that ${y.length===1?"is":"are"} not an origin: ${y.map(m=>typeof m=="string"?JSON.stringify(m):String(m)).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([...e_,...f])]),k=Nn(e),P=new Set,h=Nn(e),S=false,C=Nn(e),I=vd(n),U=Nn(e),q=t.manageAudio===false?null:Fc();t.selectableText!==true&&qc(),t.onScreenshot===void 0&&Pc(window);let x=null,A=null,O=null,F=()=>{x===null||x===A||D.reportMuted(x)&&(A=x);},B,W,J=-1/0,ie=null,ge=()=>{if(B===void 0||ie!==null||B===W)return;let m=J+1e3-e.now();if(m>0){ie=e.setTimeout(()=>{ie=null,ge();},m);return}D.showPortraitBorders(B)&&(W=B,J=e.now());},X=null,Be=null,Se=()=>{if(X===null)return false;let m=JSON.stringify(Ga(X.visible,X.only));return m===Be?D.parentSupports("walletDisplay"):D.setWalletVisible(X.visible,X)?(Be=m,true):false},fe=null,Ue=null,te=()=>{if(fe===null)return false;let m=JSON.stringify(_o(fe.items));return m===Ue?D.parentSupports("gameMenu"):D.setMenu(fe.items)?(Ue=m,true):false},z=null,le=null,xe,Le=null,De=lm({frame:()=>D,clock:e,log:t.log}),jn=()=>z===null?false:z===le?D.parentSupports("gemCorner"):D.setGemCorner(z)?(le=z,true):false,Bt=()=>{if(xe===void 0)return false;let m=JSON.stringify(xe);return m===Le?D.parentSupports("menuStyle"):D.setMenuStyle(xe)?(Le=m,true):false},nt=Nc({report:m=>D.reportFrameStats(m)}),We=false,$e=Kc(()=>es,()=>We),Ut=m=>{let T=We&&!m,L=We!==m;if(We=m,T&&$e.close(),!!L)try{t.onDevToolsPermissionChange?.(m);}catch(ee){n?.(`[gem] onDevToolsPermissionChange threw: ${ee instanceof Error?ee.message:String(ee)}`),queueMicrotask(()=>{throw ee});}},b=r??t_,M=r!==void 0,N,Z=m=>(n?.(`[gem] token refused: ${m}`),t.onError?.("internal",m),false),ke=(m,T)=>{if(m===void 0)return T!==void 0?Z("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 L=Am(m);return L!==null?Z(`the embedder named an API root that cannot be used: ${L}. Its value is withheld here rather than written to logs.`):N!==void 0&&N!==m?Z("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."):(N=m,M||(b=m),true)},Fe=window.location?.origin,Wt=null,bt=-1/0,$m=2e3,Bn=new Set,Fm=m=>Wt!==false?Promise.resolve(true):new Promise(T=>{let L=e.setTimeout(()=>{Bn.delete(ee),T(false);},m),ee=()=>{e.clearTimeout(L),Bn.delete(ee),T(true);};Bn.add(ee);}),ko=()=>{},Ro=null,Un=()=>{},Wn=Nu(e),D=new Fn({allowedEmbedders:R,...typeof Fe=="string"&&Fe!==""?{selfOrigin:Fe}:{},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","menuStyle","gameSettings","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges","appLinks","openGame","store","storeOfferSheet",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[]],onRefused:m=>{Ro=m,t.onRefused?.(m);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:m=>{ae.onBridgeState(m),m!=="connected"&&Wn.abandon(),m!=="connected"&&nt.setRequested(false),A=null,Be=null,Ue=null,le=null,Le=null,De.forgetSent(),W=void 0,m==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Ro===null?"":` (${Ro})`)+", 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."),ko()),m==="connected"&&(a.mark("bridge connected"),qm(),F(),ge(),Se(),te(),jn(),Bt(),De.flush(),D.unbiddenLaunch&&!u.engaged&&d.hold(),d.startSession(),u.engaged&&D.reportEngaged()),t.onStateChange?.(m);},onPlayer:m=>{k.set(m);for(let T of [...P])T(m);t.onPlayer?.(m);},onPrefs:m=>{let T={reducedMotion:m.reducedMotion,muted:m.muted,locale:m.locale,showFrameStats:m.showFrameStats===true,music:m.music!==false,sounds:m.sounds!==false,recommended:m.recommended===void 0?null:Object.freeze({volume:m.recommended.volume,batterySaver:m.recommended.batterySaver,keyboardLayout:m.recommended.keyboardLayout,gamepadConfirm:m.recommended.gamepadConfirm,vibration:m.recommended.vibration,lookSensitivity:m.recommended.lookSensitivity??100,gamepadLookSensitivity:m.recommended.gamepadLookSensitivity??100,invertLookY:m.recommended.invertLookY??false,touchMovement:m.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:dm(m.recommended.graphicsQuality,m.recommended.batterySaver),graphicsQualityAuto:m.recommended.graphicsQualityAuto??true,colorHelp:typeof m.recommended.colorHelp=="boolean"?m.recommended.colorHelp:null})};h.set(T),A=T.muted,q?.setMuted(T.muted),nt.setRequested(T.showFrameStats&&D.parentSupports("frameStats")),t.onPrefs?.(T),t.onAudioChannels!==void 0&&(O===null||O.music!==T.music||O.sounds!==T.sounds)&&(O=Object.freeze({music:T.music,sounds:T.sounds}),t.onAudioChannels(O));},onCohorts:m=>{let T=Object.freeze(m.cohorts.map(L=>Object.freeze({experimentId:L.experimentId,variantKey:L.variantKey})));C.set(T),t.onCohorts?.(T);},onEarnAllowanceChanged:()=>I.emit(),onViewport:m=>{let T=Object.freeze({insets:Object.freeze({top:m.insets.top,right:m.insets.right,bottom:m.insets.bottom,left:m.insets.left}),reserved:Object.freeze((m.reserved??[]).map(({x:ee,y:ts,width:ns,height:rs,control:Vt})=>Object.freeze(Vt?{x:ee,y:ts,width:ns,height:rs,control:Object.freeze({x:Vt.x,y:Vt.y,width:Vt.width,height:Vt.height})}:{x:ee,y:ts,width:ns,height:rs})))});U.set(T);let L=Bc();Uc(L,T.insets),Hc(L,T.reserved,Wc()),t.onViewport?.(T);},onPause:m=>{m.paused||Un(),S=m.paused,q?.setPaused?.(m.paused),d.setPaused(m.paused),nt.setPaused(m.paused),t.onPause?.(m.paused);},onSettingChange:m=>De.onSettingChange(m),onMenuSelect:m=>{fe===null||m.entry!=="item"||!(_o(fe.items).items??[]).some(L=>L.id===m.id)||fe.items?.find(L=>L.id===m.id)?.onSelect?.();},onWillTerminate:m=>{d.endSession(m.reason),t.onWillTerminate?.({reason:m.reason,graceMs:m.graceMs});},onToken:m=>{let T=m.garden;if(Ut(m.allowDevTools===true),!ke(m.apiBaseUrl,T))return;let L=m;ae.onToken(L);let ee=ae.identity;ee&&(Ao.set(ee),Fa||(Fa=true,me.reconcileSeats().catch(()=>{}))),qa.push({token:L.token,expiresAt:L.expiresAt});},onTokenDenied:m=>{Ut(false),ae.onDenied(m);},onScreenshot:(m,T,L)=>{Gc(m,T,L,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Lc(D,t.onFeedbackContext);},onDevtools:m=>{m==="close"?$e.close():m==="open"?$e.openFrom("platform").catch(()=>{}):$e.isOpen?$e.close():$e.openFrom("platform").catch(()=>{});},onRoomEvent:m=>me.handleRoomEvent({event:m.event,roomId:m.roomId,...m.matchId===void 0?{}:{matchId:m.matchId},...m.version===void 0?{}:{version:m.version},...m.reason===void 0?{}:{reason:m.reason},...m.platform===void 0?{}:{platform:m.platform}}),onSeatedEvent:m=>me.handleSeated(m.roomId),onAutoStartFailedEvent:m=>me.handleAutoStartFailed(m.roomId,m.code),onTicketEvent:m=>me.handleTicketEvent({event:m.event,ticketId:m.ticketId,...m.partySize===void 0?{}:{partySize:m.partySize},...m.queuedAt===void 0?{}:{queuedAt:m.queuedAt},...m.expiresAt===void 0?{}:{expiresAt:m.expiresAt},...m.reason===void 0?{}:{reason:m.reason},...m.roomId===void 0?{}:{roomId:m.roomId}}),onSocketState:m=>{let T=Wt;if(Wt=m.connected,m.connected)for(let ee of [...Bn])ee();if(!m.connected||T===true)return;let L=e.now();L-bt<$m||(bt=L,me.reconcile().catch(()=>{}));},onSignalEvent:m=>{let T=typeof m.data=="object"&&m.data!==null&&!Array.isArray(m.data)?m.data:{};_t.handleSignalEvent(m.matchId,m.event,T),m.event==="matchEnded"&&me.reconcile({matchId:m.matchId,...typeof T.reason=="string"?{reason:T.reason}:{}}).catch(()=>{});},onDedicatedEvent:m=>{m.event==="matchEnded"&&(Ht.handleMatchEnded(m.matchId,m.reason),me.reconcile({matchId:m.matchId,...m.reason===void 0?{}:{reason:m.reason}}).catch(()=>{})),$a.handleEvent(m);},onClusterTarget:m=>Jn.accept(m.clusterTargetId,m.clusterTargetIds),onLocalServer:m=>zn.accept(m),onLocalServerDenied:m=>zn.refuse(m),onPartyResult:m=>ja.settle(m.requestId,m.partyId),onPurchaseResult:m=>Po.settle(m),onDeviceSettings:m=>{Kn.receive(m),t.onDeviceSettings?.(Kn.api.current);},onDeviceSettingsResult:m=>Kn.settle(m),onAdResult:m=>Ua.settle(m),onMomentResult:m=>Wa.settle(m),onSignInResult:m=>{m.outcome==="signed_in"&&Un(),Ha.settle(m);},onFriendChallengeResult:m=>Ja.settle(m),onArcadeAnswer:m=>{m.type==="gem.storePurchaseSettled"?Ka.settled(m):jm(m);}}),$a=new Cn({bridge:D}),Ao=Nn(e);ko=()=>{Ao.release(),k.release(),C.release();},D.currentState==="refused"&&ko();let Fa=false,xo=new Set,Hn,qa={current:()=>Hn,subscribe:m=>(xo.add(m),Hn!==void 0&&m(Hn),()=>xo.delete(m)),push:m=>{Hn=m;for(let T of [...xo])try{T(m);}catch(L){n?.(`[gem] a server-token listener threw: ${L instanceof Error?L.message:String(L)}`);}}},ae=zc({bridge:D,clock:e,onStateChange:(m,T)=>{if(m==="ready"){if(a.mark("token ready")){let L=a.marks.find(ee=>ee.name==="token ready")?.at;d.trackPlatform("gem_boot_ready",L===void 0?{}:{boot_ms:Math.max(0,Math.round(L))});}}else m==="lost"&&(a.mark("token lost"),d.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(m,T);}}),Na=()=>{let m=ae.identity;return !m||ae.source.currentState==="lost"?null:`${m.playerId}\0${m.gameId}\0${m.channel}`},qm=()=>{a.mark("token requested"),ae.source.get().catch(()=>{});},ja=Pu({bridge:D,clock:e}),Vn={},Po=Tu({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m),confirm:async m=>Vn.confirm?.(m)??"unknown",confirmAvatar3d:async m=>Vn.confirmAvatar3d?.(m)??"unknown"}),Kn=vm({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),Ba={},Ua=gm({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m),readAvailability:(m,T)=>Ba.read?.(m,T)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),Wa=hm({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),Ha=Lu({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),Va={held:false},Nm=ju({bridge:D,asker:Wn,acting:Va}),Ka=Uu({bridge:D,asker:Wn,acting:Va,onListenerError:m=>t.onError?.("internal",`gem.store.onSettled listener threw: ${String(m)}`),onPurchaseEnded:()=>Un()}),jm=m=>{Wn.settle(m)||t.onError?.("internal",`${m.type} (${m.outcome}) for an unknown requestId: `+JSON.stringify(m.requestId));},Ja=bd({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),Jn=Pd({bridge:D,clock:e}),zn=Vc({bridge:D,clock:e}),To=Im(Fe),za=window.fetch,Xn=To!==null&&typeof za=="function"?"unread":"read",Yn=null,Eo=false,Bm=m=>{if(Xn==="read"||m.source!==window.parent)return false;let T=m.origin;return typeof T!="string"||R.some(L=>kt(L,T))||cr(T,typeof Fe=="string"?Fe:void 0)?false:((Yn===null||!Eo)&&(Yn=m),Xn==="unread"&&To!==null&&(Xn="reading",Em({fetch:(L,ee)=>za.call(window,L,ee),selfOrigin:To,clock:e}).then(L=>{"refused"in L&&n?.(L.refused),L.origins.length>0&&km(D,L.origins),Xn="read";let ee=Yn;Yn=null,ee!==null&&D.currentState==="waiting"&&Qn(ee);})),true)},Qn=m=>{if(Bm(m))return false;let T=D.handleWindowMessage({data:m.data,origin:m.origin,source:m.source,ports:m.ports});return T&&window.removeEventListener("message",Qn),T};window.addEventListener("message",Qn),Eo=true;let rt;try{rt=as(window,Qn);}finally{Eo=false;}let Um=rt?.capture,Io=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Io?.domInteractive!==void 0&&Io.domInteractive>0&&a.mark("document parsed",Io.domInteractive),Um?.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 Co=t.handshakeWarningMs;Co!==null&&n&&e.setTimeout(()=>{let m=rt===null?"no capture script ran":`capture: ${rt.delivered} offer(s) delivered, ${rt.stale} stale, ${rt.capture.dropped} evicted${rt.capture.late?", installed late":""}`;if(D.currentState==="connected"){n(`[gem] handshake connected. boot: ${a.timeline()} \xB7 ${m}`);return}n(`[gem] no completed handshake after ${Co??Om}ms (bridge state: ${D.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 `+m);},Co??Om);let Wm=br({get baseUrl(){return b},tokenSource:ae.source,get defaultQuery(){let m=ae.identity;return m?{game_id:m.gameId,channel:m.channel}:{}}}),vt=new He({transport:Wm,clock:e}),ye={client:vt,gameId:()=>ae.identity?.gameId??""};Vn.confirm=m=>Eu(ye,m),Vn.confirmAvatar3d=m=>Ou(ye,m),Ba.read=(m,T)=>vl(ye,"players","me",m,{signal:T});let Hm=()=>ae.identity?.channel??"release",Zn=new Tr(ye,Hm),Vm=Mu({player:()=>k.current,subscribe:m=>(P.add(m),()=>{P.delete(m);}),configFamilies:async()=>(await Zn.load())?.avatar_3d_families,readOffers:()=>Gu(ye),purchase:m=>Po.requestAvatar3d(m),log:t.log}),Xa=async m=>(await Zn.load())?.currency(m)?.id??void 0,Ya=Jl(ye,Yo,{identity:Na,resolveCurrencyId:Xa,watch:{clock:e,log:t.log}}),Qa=Ya.scope;Un=Ya.recheckPasses;let er=async m=>{let T=await Ao.wait(m);if(T)return T;throw D.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).")},Mo=c(t.autoReconnect),me=ic(s===void 0?{}:{playWithTicket:s},{client:vt,clock:e,gameId:()=>ae.identity?.gameId??null,playerId:()=>ae.identity?.playerId??null,awaitGameId:async()=>(await er(So)).gameId,resolveParty:ja.resolve,resolveClusterTargets:Jn.resolveList,refreshClusterTargets:Jn.refresh,ensureLocalServer:zn.ensure,localHostAvailable:zn.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},...Mo===null?{}:{autoReconnect:{...Mo,redial:(m,T)=>Oo.redialMatch(m,T),abandon:(m,T)=>Oo.abandonMatch(m,T)}}});g(me),kc({analytics:d,rooms:me});let _t=Sc({client:vt,clock:e,rooms:me,bridge:D,gameId:()=>ae.identity?.gameId??"",baseUrl:()=>b,resolveClusterTarget:Jn.resolve,boot:a,...t.log===void 0?{}:{log:t.log}}),Za=Zi(a,n),Ht=mu({client:vt,clock:e,rooms:me,signaling:()=>$a.channel(),signalingReady:Fm,log:n??(()=>{})}),Oo=Au({rooms:me,p2p:{connect:m=>Za(_t.connect(m)),session:m=>_t.session(m)},dedicated:{connect:(m=>oo(a,"welcome",Ht.connect(m),n))},clock:e,identity:()=>ae.identity,apiBaseUrl:()=>b,tokens:qa,room:()=>me.currentRoom,autoReconnect:Mo!==null,...t.log===void 0?{}:{log:t.log}}),Km=async()=>(await er(So)).playerId,es={client:vt,boot:a,get identity(){return ae.identity},awaitIdentity:(m=So)=>er(m),awaitBridge:m=>D.settled(m),get player(){return k.current},awaitPlayer:(m=s_)=>k.wait(m),me:Qa,characters:new Rr(ye,void 0,Na,Xa),transfers:new xr(ye,Yo,Qa.inventory),gameConfig:Zn,purchases:Po.api,deviceSettings:Kn.api,moments:Wa.api,ads:Ua.api,account:Ha.api,share:qu({frame:D,log:t.log}),arcade:Nm,store:Ka.api,branding:Xu({fetch:typeof window.fetch=="function"?(m,T)=>window.fetch.call(window,m,T):null,clock:e,devicePixelRatio:()=>window.devicePixelRatio??1,log:n}),vibration:Yu({frame:D,log:t.log}),get avatarPickerAvailable(){return D.currentState==="connected"&&D.parentSupports("avatarPicker")},openAvatarPicker:m=>D.requestAvatarPicker(m?.tab),avatars3d:Vm,settings:De.api,controls:tm({recommended:()=>h.current?.recommended??null}),analytics:d,leaderboards:new nn(ye),challenges:new Zt(ye),showcase:new rn(ye,Km),friends:new on(ye,{challenge:Ja.challenge,...i===void 0?{}:{launchedChallengeId:i}}),platform:new sn(ye,I,n),profiles:new ln(ye),functions:new Xe((m,T)=>il(ye,m,T)),get prefs(){return h.current},get paused(){return S},get cohorts(){return C.current},get viewport(){return U.current},awaitCohorts:(m=l_)=>C.wait(m),reportMuted:m=>{x=!!m,F();},showPortraitBorders:m=>{let T=vo(m);T!==void 0&&(B=T,ge());},cueReward:m=>D.cueReward(m),setWalletVisible:(m,T)=>{let L=Array.isArray(T?.only)?[...T.only]:void 0;return X=L===void 0?{visible:m===true}:{visible:m===true,only:L},Se()},setMenu:m=>(fe=Array.isArray(m?.items)?{items:m.items.map(T=>({...T}))}:{},te()),setGemCorner:m=>{if(!n_.includes(m)){let T=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setGemCorner: ${T} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return z=m,jn()},setMenuStyle:m=>{let T=r_(m);return T===void 0?false:(xe=T,Bt())},reportFrame:()=>nt.draw(),exit:m=>d_(me,D,m,d),frame:D,devtools:$e,rooms:me,dedicatedServer:{listClusterTargets:m=>Ht.listClusterTargets(m),connect:(m=>oo(a,"welcome",Ht.connect(m),n)),handleMatchEnded:(m,T)=>Ht.handleMatchEnded(m,T)},p2p:{handleSignalEvent:(m,T,L)=>_t.handleSignalEvent(m,T,L),session:m=>_t.session(m),connect:m=>Za(_t.connect(m))},match:Oo};return es}var Gm="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 Da(t,e={}){let n=e.clock??de,r=()=>{let a=t();if(a===null)throw new Error(Gm);return a},o=null,i=()=>{if(o===null)throw new Error(Gm);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 u=d.displayName;return typeof u!="string"||u===""?null:{displayName:he(u,"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=qt(r(),{...e,clock:n});}}}function Lm(t,e={}){let{server:n,attach:r}=Da(()=>t,e);return r(),n}function c_(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:Ye(e)}}}var u_=1e4;function m_(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout(u_));}catch{return}r.catch(o=>{o instanceof G&&o.status>=400&&o.status<500&&(e=o.status!==429);});}}function Dm(t,e={}){return ()=>{let n=null,{server:r,attach:o}=Da(()=>n,e),i=t(r),s={async init(l){n=l,o(),await i.init?.();},async shutdown(l){let d=c_(l);try{await i.shutdown?.(d);}finally{r.dispose();}}},a=m_(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,u,c)=>i.message?.(l,d,u,c)),s}}is();
1
+ var GemWebSdkGame=(function(exports){'use strict';var Jm=Object.defineProperty;var zm=(t,e)=>{for(var n in e)Jm(t,n,{get:e[n],enumerable:true});};var Go="GemWebSdkHandshake";function Xm(){return typeof document>"u"?void 0:document.readyState}var os=()=>Date.now();function is(t={}){let e=t.win??window,n=e,r=n[Go];if(r!==void 0)return r;let o=t.readyState??Xm,i=t.now??os,s=[],a=[],l=u=>{let c=u.data;!c||c.type!=="gem.handshake"||(s.length>=4&&(s.shift(),a.shift(),d.dropped+=1),s.push(u),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[Go]=d,d}function as(t,e,n={}){let r=t[Go];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??os,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,u=false,c=i()-o;for(let g=s.length-1;g>=0;g--){let p=a?.[g];if(p!==void 0&&p<c){d+=1;continue}if(l+=1,e(s[g])===true){u=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:u}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:19.0.2]";function ss(){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 Ym={initialDelayMs:2e3,maxDelayMs:6e4};function Qm(t,e){return e!==void 0?!e:t==="chain_exhausted"}var wt=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}=Ym,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=Zm(o),{retryable:s,retryAfterMs:a}=o??{};throw n===this.generation&&(Qm(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 Zm(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}},tr=["if-match","if-none-match"],ls=4096;function ep(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!tr.includes(o)||r===void 0)continue;let i=typeof r=="string"?tp(r):r;if(typeof i!="string"||i.length>ls||!np(i))throw new se(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${ls} 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 tp(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 np(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 rp(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 ds(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=ep(o.headers),s=rp(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 u=await e.tokenSource.get(),c=await t(a,u);if(c.status===401)throw e.tokenSource.close("unavailable"),new ne("unavailable","the server refused a freshly minted token");return c}}}function nr(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(op(e))}function rr(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 Lo(t){return new TextDecoder().decode(rr(t))}function op(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var G=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"}},ms=new WeakMap;function ps(t){return ms.get(t)??{}}var ip=new Set([408,429,500,502,503,504]),ap=6e4,gs=new WeakMap;function fs(t,e){gs.set(t,e);}function cs(t){return t!==null&&(t.reason==="rate_limited"||t.retryAfterSeconds!==void 0)}function sp(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 He=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,...Kt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...Kt(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,...Kt(o)},o.replaySafe===true,o.retryRateLimited!==false);return {bytes:lp(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,...Kt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Kt(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?sp(this.options.maxRetries)+1:1,i=null;if(e.signal?.aborted)throw us(e.signal);let s=e.signal===void 0?void 0:gs.get(e.signal);for(let a=0;a<o;a++){if(a>0){let u=this.backoffMs(a,i);if(cs(i)&&s!==void 0&&u>=s())throw i;await this.backoff(u,e.signal);}if(e.signal?.aborted)throw cs(i)&&s!==void 0&&s()<=0?i:us(e.signal);let l;try{l=await this.options.transport.request(e);}catch(u){if(ne.isAuthError(u)||se.isRefusal(u)||e.signal?.aborted||dp(u))throw u;i=new G("unavailable",0,String(u));continue}if(l.status>=200&&l.status<300||l.status===304)return l;let d=cp(l);if(!ip.has(l.status)||l.status===429&&!r)throw d;i=d;}throw i??new G("unavailable",0,"no attempt was made")}backoffMs(e,n){let r=n?.retryAfterSeconds,o=r!==void 0?r*1e3:2**(e-1)*250,i=2**(e-1)*250;return Math.min(Math.max(o,i),ap)}backoff(e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let o=this.options.clock,i=false,s=false,a,l=()=>{i||(i=true,s&&o.clearTimeout(a),n?.removeEventListener("abort",l),r());};n?.addEventListener("abort",l,{once:true}),a=o.setTimeout(l,e),s=true,i&&o.clearTimeout(a);})}};function lp(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 Kt(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function us(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function dp(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function cp(t){let e=mp(t),n=gp(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&ms.set(e,r),e}var up=new Map([["insufficient_funds","insufficient_funds"]]);function mp(t){let{status:e,body:n}=t,r=pp(n),o=t.retryAfterSeconds??yp(n),i=fp(n),s=i===void 0?void 0:up.get(i);if(s!==void 0)return new G(s,e,r,void 0,i);switch(e){case 304:return new G("not_modified",e,r);case 400:case 422:return new G("invalid",e,r,void 0,i);case 403:return new G("forbidden",e,r,void 0,i);case 404:return new G("not_found",e,r,void 0,i);case 402:return new G("insufficient_funds",e,r,void 0,i);case 409:return new G("conflict",e,r,void 0,i);case 412:return new G("precondition_failed",e,r,void 0,i);case 413:return new G("too_large",e,r,void 0,i);case 429:return new G("rate_limited",e,r,o,i);default:return new G("unavailable",e,r,o,i)}}function pp(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 gp(t){let n=t?.error?.details;return n===null?void 0:n}function fp(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function yp(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 ys(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function hs(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 bs(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function vs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}`;return t.client.delete(r,n?.signal)}async function _s(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 ws(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 ks(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 Rs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function As(t,e,n,r,o){let i=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(i,o?.signal)}async function xs(t,e,n,r,o){let i=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(i,o?.signal)}async function Ps(t,e,n,r){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.delete(o,r?.signal)}async function Ts(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 Es(t,e,n,r,o,i){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/finalize`;return t.client.post(s,o,i?.signal)}async function Is(t,e,n){let r=`/v1/games/${_(t.gameId())}/avatars-3d/${_(e)}/owned`;return t.client.get(r,n?.signal)}async function Cs(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 Ms(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.get(r,n?.signal)}async function Os(t,e,n){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Gs(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 Ls(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 Ds(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/items/${_(r)}`;return t.client.get(i,o?.signal)}async function $s(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 Fs(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/orders/${_(r)}`;return t.client.get(i,o?.signal)}async function qs(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}`;return t.client.get(i,o?.signal)}async function Ns(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 js(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 Do(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 Bs(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 Us(t,e,n){let r=`/v1/showcase/friends/${_(e)}`;return t.client.get(r,n?.signal)}async function Ws(t,e){let n=`/v1/games/${_(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function Hs(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}`;return t.client.get(r,n?.signal)}async function Vs(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 Ks(t,e){let n=`/v1/games/${_(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function Js(t,e){let n=`/v1/games/${_(t.gameId())}/players/me/passes`;return t.client.get(n,e?.signal)}async function or(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function zs(t,e,n){let r=`/v1/profiles/players/${_(e)}`;return t.client.get(r,n?.signal)}async function Xs(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 Ys(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return t.client.get(r,n?.signal)}async function Qs(t,e,n,r){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.get(o,r?.signal)}async function Zs(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function el(t,e,n){let r=`/v1/inventory/transfers/${_(e)}`;return t.client.get(r,n?.signal)}async function tl(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function nl(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 rl(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ol(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 il(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function al(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 sl(t,e){return t.client.get("/v1/characters",e?.signal)}async function ll(t,e,n,r){let o=`/v1/settings/${_(e)}/${_(n)}`;return t.client.get(o,r?.signal)}async function dl(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 cl(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 ul(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 ml(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 pl(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 gl(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function fl(t,e,n,r){let o=`/v1/games/${_(t.gameId())}/matches/${_(e)}/end`;return t.client.post(o,n,r?.signal)}async function yl(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 hl(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 bl(t,e,n,r,o){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.put(i,r,o?.signal)}async function vl(t,e,n,r,o){let i=`/v1/inventory/${_(e)}/${_(n)}/rewarded-placements/${_(r)}/availability`;return t.client.get(i,o?.signal)}async function _l(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function wl(t,e,n,r){let o=`/v1/characters/${_(e)}`;return t.client.patch(o,n,r?.signal)}async function Sl(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 kl(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 Rl(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.delete(r,n?.signal)}var j="gem-web-bridge",ar={min:1,max:1},hp=65536,Al=8,ir=5e3,xl=1024;var Jt=Object.create(null),sr="__malformed";var qo=Object.create(null),bp=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"]]);function lr(t){let e=qo[t];if(e!==void 0)return e;for(let[n,r]of bp)if(t.startsWith(n))return r}function St(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 vp(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 _p(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function wp(t){return /^[a-z_]+$/.test(t)}function Sp(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 $o(t,e,n){if(e>Al)return `nesting deeper than ${Al}`;if(++n.nodes>ir)return `more than ${ir} 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>xl)return `an array of ${t.length} entries, over the ${xl} limit`;n.bytes+=2;for(let a of t){let l=$o(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>ir)return `more than ${ir} values`;if(n.bytes+=a.length*3+4,n.bytes>n.cap)return `over the ${n.cap} byte limit`;let l=$o(s[a],e+1,n);if(l)return l}return null}function kp(t,e=hp){let n={nodes:0,bytes:0,seen:new Set,cap:e},r=$o(t,0,n);return r?`message contains ${r}`:n.bytes>e?`message is over the ${e} byte limit`:null}var Rp={origin:[St,"not a well-formed origin"],url:[vp,"not a safe absolute http(s) URL"],bcp47:[_p,"not a well-formed BCP 47 tag"],code:[wp,"not a code of lower-case letters and underscores"],gameRef:[Sp,"not a game id or web address"]};function Pl(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=Fo(i,r,o);if(s)return s}return null}function Fo(t,e,n){let r=e[1].toLowerCase();switch(r){case "u":return typeof t=="boolean"?null:Fo(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]=Rp[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`:Pl(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=Fo(s,o,i);if(a)return a}return null}default:return `${n}: unknown kind ${String(r)}`}}var Tl=Object.create(null);function E(t,e,n,r,o){return Jt[t]=n,r&&(qo[t]=r),Tl[t]=i=>{let s=kp(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}`:Pl(a,e,"")}}var H=["requestId","s",64],Ve=["outcome","e",["ok","declined","unavailable"]],Ke=["reason","S",64,"code"];E("gem.handshake",[["versions","o",[["min","i",1,1e3],["max","i",1,1e3]]],["capabilities","A",64,["","s",64]],["embedder","s",2048,"origin"],["unbidden","B"]],30);E("gem.handshake.accept",[["v","i",1,1e3],["capabilities","A",64,["","s",64]]],5);E("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);E("gem.token.denied",[H,["retryable","b"],["retryAfterMs","I",0,36e5],["reason","e",["chain_exhausted","unavailable"]],["correlationId","s",64]],30);E("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);E("gem.pause",[["paused","b"]],120);E("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);E("gem.cohorts",[["cohorts","a",8,["","o",[["experimentId","s",36],["variantKey","s",32]]]]],12,"cohorts");E("gem.earnAllowanceChanged",[],30,"earnAllowance");E("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");E("gem.deviceSettings",[["settings","J"]],12,"deviceSettings");E("gem.willTerminate",[["reason","e",["grant_expiring","session_ended","navigating","kill_switch"]],["graceMs","i",0,6e4]],10);E("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");E("gem.socketState",[["connected","b"],["reason","E",["connecting","dropped","watchdog","terminal"]]],12,"socketState");E("gem.seatedEvent",[["roomId","s",64]],60,"partySeating");E("gem.autoStartFailedEvent",[["roomId","s",64],["code","s",64]],30,"autoStartFailure");E("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");E("gem.signalEvent",[["event","e",["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]],["matchId","s",64],["data","j"]],1800,"p2p");E("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");E("gem.partyResult",[H,["partyId","S",64]],30,"parties");E("gem.clusterTarget",[["clusterTargetId","s",64],["clusterTargetIds","A",3,["","s",64]]],12,"clusterTarget");E("gem.devtools",[["action","e",["open","close","toggle"]]],30,"devtools");E("gem.screenshot",[["maxWidth","i",1,7680],["maxHeight","i",1,4320]],6,"screenshot");E("gem.screenshot.denied",[["reason","e",["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]],["retryable","b"]],12,"screenshot");E("gem.requestContext",[],12,"feedbackContext");E("gem.gameContext",[["context","j"]],12,"feedbackContext");E("gem.signal",[["signal","e",["join","offer","answer","ice","migrationAck","hostUnreachable"]],["matchId","s",64],["data","j"]],1200,"p2p");E("gem.dedicatedOffer",[["matchId","s",64],["sdp","s",10240],["intent","e",["initial","ice_restart","full_reconnect"]]],60,"dedicated");E("gem.partyRequest",[H],12,"parties");E("gem.ready",[],5);E("gem.engaged",[],5,"engagement");E("gem.progress",[["loaded","i",0,1099511627776],["total","i",0,1099511627776]],600);E("gem.requestToken",[H,["reason","e",["initial","expiring","rejected"]]],12);E("gem.requestLocalServer",[H,["gameRoomId","s",64]],6,"localHost");E("gem.localServer",[H,["serverId","S",128]],30,"localHost");E("gem.localServer.denied",[H,["retryable","b"],["reason","e",["refused","unavailable"]]],30,"localHost");E("gem.exit",[["reason","S",64]],5);E("gem.openExternal",[["url","s",2048,"url"]],6);E("gem.requestFullscreen",[["enabled","b"]],30);E("gem.audioState",[["muted","b"]],120,"audioState");E("gem.rewardCue",[["currencySlug","s",32],["expected","I",1,1e9],["origin","O",[["x","i",0,16384],["y","i",0,16384]]]],60,"rewardCue");E("gem.walletDisplay",[["visible","b"],["currencies","A",8,["","s",64]],["score","B"]],60,"walletDisplay");E("gem.controlsDeclare",[["uses","o",[["lookSensitivity","S",16,"code"],["gamepadLookSensitivity","S",16,"code"],["invertLookY","S",16,"code"],["touchMovement","S",16,"code"]]]],60,"controls");E("gem.menu",[["settings","b"],["items","A",4,["","o",[["id","s",32],["label","s",40]]]]],60,"gameMenu");E("gem.menuSelect",[["entry","e",["settings","item"]],["id","S",32]],60,"gameMenu");E("gem.gemCorner",[["corner","e",["top-left","top-right","bottom-left","bottom-right"]]],12,"gemCorner");E("gem.menuStyle",[["ground","S",7],["accent","S",7]],12,"menuStyle");E("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");E("gem.settingChange",[["id","s",40],["value","u",40,-1e6,1e6]],120,"gameSettings");E("gem.requestShare",[["params","a",16,["","o",[["key","s",64],["value","s",512]]]]],6,"share");E("gem.requestAvatarPicker",[["tab","E",["2d","3d"]]],6,"avatarPicker");E("gem.vibrate",[["pattern","a",99,["","i",0,1e4]]],600,"vibration");E("gem.frameStats",[["fps","i",0,1e3],["frameTimeP95Ms","i",0,1e5],["counts","E",["pageFrames","gameDraws"]]],120,"frameStats");E("gem.portraitBorders",[["name","S",40]],60,"portraitBorders");E("gem.error",[["code","e",["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]],["message","S",256]],60);E("gem.requestPurchase",[H,["purchaseKind","e",["item","recipe"]],["targetId","s",64],["currencySlug","s",32],["quantity","I",1,10],["catalogId","S",64]],12,"purchases");E("gem.requestAvatar3dPurchase",[H,["itemId","s",64],["currencySlug","s",32]],12,"avatar3dPurchases");E("gem.purchaseResult",[H,Ve,Ke,["purchaseId","S",64]],30,"purchases");E("gem.deviceSettings.put",[H,["settings","j"]],30,"deviceSettings");E("gem.deviceSettings.result",[H,["outcome","e",["stored","too_large","unavailable"]]],30,"deviceSettings");E("gem.requestAd",[H,["placement","s",32],["format","e",["interstitial","rewarded"]]],6,"ads");E("gem.adResult",[H,["outcome","e",["shown","no_ad","unavailable"]]],12,"ads");E("gem.signalMoment",[H,["kind","e",["level_end","run_end","match_end","menu_return","other_break"]],["placement","S",32],["wall","B"]],6,"moments");E("gem.momentResult",[H,["shown","b"]],12,"moments");E("gem.requestSignIn",[H],6,"signIn");E("gem.signInResult",[H,["outcome","e",["signed_in","declined","unavailable"]]],12,"signIn");E("gem.requestFriendChallenge",[H,["playerId","s",64],["template","s",64],["params","J"]],12,"friendChallenges");E("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");E("gem.requestAppLinks",[H],12,"appLinks");E("gem.appLinksResult",[H,Ve,Ke,["arcade","O",[["store","e",["app_store","google_play"]]]],["game","O",[["store","e",["app_store","google_play"]]]]],30,"appLinks");E("gem.requestOpenApp",[H,["target","e",["arcade","game"]]],6,"appLinks");E("gem.openAppResult",[H,Ve,Ke],30,"appLinks");var El=E("gem.requestOpenGame",[H,["ref","s",40,"gameRef"]],6,"openGame");E("gem.openGameResult",[H,Ve,Ke],30,"openGame");E("gem.requestSimilarGames",[H,["limit","I",1,24]],12,"openGame");E("gem.similarGamesResult",[H,Ve,Ke,["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);E("gem.requestStoreOffers",[H],12,"store");E("gem.storeOffersResult",[H,Ve,Ke,["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);E("gem.requestStorePurchase",[H,["skuId","s",64]],12,"store");E("gem.storePurchaseResult",[H,Ve,Ke],30,"store");E("gem.storePurchaseSettled",[["skuId","s",64]],30,"store");E("gem.requestStoreOfferSheet",[H,["skuId","s",64]],12,"storeOfferSheet");E("gem.storeOfferSheetResult",[H,Ve,Ke],30,"storeOfferSheet");var dr=Object.freeze(Tl);Jt.__malformed=60;Object.freeze(Jt);Object.freeze(qo);var de={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},zt=class{constructor(e=de){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Jt[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 kt(t,e){return t.toLowerCase()===e.toLowerCase()}function Je(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function cr(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:Je(n.hostname)&&Je(r.hostname)}function Il(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 ur=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 jo(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 Cl="inventory",Rt=t=>typeof t=="number"?t:0,Xt=t=>typeof t=="string"?t:"";function No(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 Ml(t){let e=t??{};return {itemDefinitionId:Xt(e.item_definition_id),instanceId:Xt(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 Ap(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:No(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(s=>{let a=s??{};return {bucket:Xt(a.bucket),balance:Rt(a.balance)}}):void 0;return {currencyId:Xt(o.currency_id),total:Rt(o.total),...i===void 0?{}:{buckets:i}}}),items:No(e.items,Ml),progressions:No(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:Xt(o.progression_definition_id),currentValue:Rt(o.current_value),completionCount:Rt(o.completion_count),isCompleted:o.is_completed===true,...jo(o)}}),...n===void 0?{}:{etag:n}}}var mr=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Cl}#buckets`:Cl;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 Ds(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(Ml):[]}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 Ls(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 Ap(n)}};var xp={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},Pp=new Set(Object.keys(xp));function Ol(t){return typeof t=="string"&&Pp.has(t)?t:"error"}var ze=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var re=t=>typeof t=="string"?t:"",Tp=t=>typeof t=="string"?t:re(t&&typeof t=="object"?t.type:void 0),Ee=t=>typeof t=="number"?t:0;function Ep(t){let e=t??{};return {prerequisiteType:re(e.prerequisite_type),referenceId:re(e.reference_id),required:Ee(e.required),current:Ee(e.current)}}function Yt(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 pr(){return crypto.randomUUID()}var Ip="recipe-usage",Gl=100;function gr(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:re(e.currency_id),bucket:re(e.bucket),delta:Ee(e.delta),balanceAfter:Ee(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:re(e.item_definition_id),instanceId:re(e.instance_id),delta:Ee(e.delta),quantityAfter:Ee(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:re(e.progression_definition_id),delta:Ee(e.delta),valueAfter:Ee(e.value_after),completed:e.completed===true};default:return {kind:"other",type:re(e.type)}}}function Cp(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:Ee(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(gr):[]}}function Mp(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(Cp):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(gr):[],consumed:Array.isArray(e.consumed)?e.consumed.map(gr):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(gr):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Op(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:Ee(n.price)}}}function Gp(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 Ll(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 fr=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(()=>ks(this.api,this.entity.type,this.entity.id,{operations:e.map(Ll),source:n.source??"play",nonce:pr()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Yt(r)}async createMany(e,n={}){return this.write(()=>Ss(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Ll),nonce:pr()})),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 Ns(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(Ep):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>Tp(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(Ip,[],async()=>{let n=await js(this.api,this.entity.type,this.entity.id,{limit:Gl})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(Gp),truncated:r.length>=Gl}})}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,g=await this.write(()=>Ts(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:pr()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...Mp(g)}}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([Xs(this.api,n.signal===void 0?{}:{signal:n.signal}),or(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(g=>g.slug);throw new ze("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 ze("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=p=>o.currencies.find(f=>f.currency_id===p)?.slug??p,g=a.platform_prices.map(p=>`${c(p.platform_currency_id)} ${p.price}`);throw new ze("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${g.length===0?"nothing":g.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new ze("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let u=await this.write(()=>ol(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:pr(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return Op(u)}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(()=>hs(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Yt(o)}async maxProgression(e,n,r){let o=await this.write(()=>yl(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Yt(o)}async claimProgression(e,n){let r=await this.write(()=>_s(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Yt(r)}async resetProgression(e,n){let r=await this.write(()=>kl(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Yt(r)}async write(e){return this.cache.invalidate(),e()}};var Bo=t=>typeof t=="string"?t:"",Lp=t=>typeof t=="number"?t:0;function Dl(t){let e=t??{};return {orderId:Bo(e.order_id),status:Bo(e.status),source:Bo(e.source),createdAt:Lp(e.created_at)}}var yr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await dl(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(Dl):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Fs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Dl(r)}};var Dp=["live"],Uo=6e4,$l=864e5;function $p(t){let e=t?.passes;if(!Array.isArray(e))return Object.freeze([]);let n=e.flatMap(r=>{let o=r??{};if(typeof o.pass!="string"||o.pass==="")return [];let i=o.held===true,s=i&&typeof o.ends_at=="string"?o.ends_at:null;return [Object.freeze({pass:o.pass,held:i,endsAt:s})]});return Object.freeze(n)}function Fp(t){let n=t.flatMap(r=>r.endsAt===null?[]:[Date.parse(r.endsAt)]).filter(r=>Number.isFinite(r));return n.length===0?null:Math.min(...n)}function Fl(t,e,n={}){let{watch:r}=n,o=new Set,i=null,s=0,a=null,l=Uo,d=()=>{a!==null&&r?.clock.clearTimeout(a.handle),a=null;},u=k=>{d(),!(r===void 0||o.size===0)&&(a={handle:r.clock.setTimeout(R,k)});},c=k=>{let P=Fp(k);if(P===null||r===void 0){d();return}let h=P-r.clock.now();u(h>0?Math.min(h,$l):Uo);},g=k=>{r?.log?.(`[gem] a passes 'changed' listener threw: ${k instanceof Error?k.message:String(k)}`);},p=k=>{let P=i!==null&&JSON.stringify(i)!==JSON.stringify(k);if(i=k,l=Uo,c(k),!!P)for(let h of [...o])try{let S=h(k);typeof S?.then=="function"&&S.then(void 0,g);}catch(S){g(S);}},f=()=>{let k=s;return e.read("passes",Dp,()=>Js(t)).then(P=>{if(k!==s)return f();let h=$p(P);return p(h),h})},y=()=>{f().catch(()=>{u(l),l=Math.min(l*2,$l);});};function R(){s+=1,e.invalidate(),d(),r!==void 0&&o.size>0&&y();}return {api:{list:f,async get(k){return (await f()).find(h=>h.pass===k)??Object.freeze({pass:k,held:false,endsAt:null})},on(k,P){let h=o.size===0;return o.add(P),h&&r!==void 0&&(i===null?y():c(i)),()=>{o.delete(P),o.size===0&&d();}}},recheck:R}}var ql=t=>typeof t=="number"?t:0,qp=t=>typeof t=="string"?t:"";function Np(t){let e=t??{};return {progressionDefinitionId:qp(e.progression_definition_id),currentValue:ql(e.current_value),completionCount:ql(e.completion_count),isCompleted:e.is_completed===true,...jo(e)}}var hr=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 qs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Np(i)}catch{return o??null}}};var Qt=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,u=r().then(c=>(i&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===u&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=u,u}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 jp(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Bp=new Set(tr);function Up(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Bp.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function br(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return ds(async(n,r)=>{let o;try{o=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 i;try{i=new URL(o.href.replace(/\/+$/,"")+n.path);}catch{throw new se(`${JSON.stringify(typeof n.path=="string"?jp(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 se(`${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 p=o.username!==""||o.password!=="",f=i.username!==o.username||i.password!==o.password,y=p?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new se(`the ${y} 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[p,f]of Object.entries(t.defaultQuery??{}))i.searchParams.has(p)||i.searchParams.set(p,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(p){throw new se(`the body of ${n.method} ${JSON.stringify(i.pathname)} could not be serialised to JSON: ${String(p)}. 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},...Up(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 p=await l.text();if(p.length>0)try{d=JSON.parse(p);}catch{d=p;}}let u=l.headers.get("etag"),c=Wo(l.headers.get("retry-after")),g=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...u===null?{}:{etag:u},...c===void 0?{}:{retryAfterSeconds:c},...g===null||g===""?{}:{invocationId:g}}},t)}function Wo(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 Ho(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 vr(t){try{let e=Ho(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var oe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},Wp=3e4,Hp=5e3,Nl=6e4,Vp=2**31-1,jl="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",Kp=/^[A-Za-z0-9_]{1,64}$/;function qe(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(!Kp.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Bl(t,e){let n=new AbortController,r=Date.now()+e;fs(n.signal,()=>r-Date.now());let o=AbortSignal.timeout(e),i=()=>n.abort(o.reason),s=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(o.addEventListener("abort",i,{once:true}),t?.addEventListener("abort",s,{once:true})),{signal:n.signal,release:()=>{o.removeEventListener("abort",i),t?.removeEventListener("abort",s);}}}function Vo(t,e){return t.aborted&&e?.aborted!==true}var Jp=new Set(["x-ms-blob-type"]),zp=/^[ -~]+$/;function Xp(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new oe("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(!Jp.has(i))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof o!="string"||!zp.test(o))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(i in n)throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function Ko(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"}function Yp(t){return t?.code==="save_conflict"}function Ul(t){return t instanceof G&&t.reason==="rate_limited"}async function Wl(t,e){let n=await vr(e);return new G("rate_limited",429,`the save ${t} answered 429: too many save calls. ${n}`.trim(),Wo(e.headers.get("retry-after")))}function _r(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Qp(t,e,n,r,o){let i=false,s=()=>i?false:(i=true,a.detach?.(),true),a={signal:n.signal,budget:r,deadlineAt:Date.now()+r,teardown:n.teardown===true,overwrite:n.overwrite===true,identity:o,resolve:l=>{s()&&t(l);},reject:l=>{s()&&e(l);},detach:void 0};return a}function Hl(t,e){return t!==null&&e!==null&&e!==t}function Vl(t){return new oe("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 wr=class{constructor(e,n,r={},o){this.api=e;this.entity=n;this.options=r;this.identity=o;}api;entity;options;identity;versions=new Map;seq=0;versionsOf=null;writes=new Map;holdUntil=0;async put(e,n,r={}){let o;try{o=JSON.stringify(n);}catch(i){throw new oe("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}. Retrying stores the same unserialisable value.`)}if(o===void 0)throw new oe("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){if(qe(e),r.signal?.aborted)throw _r(r.signal);let o=this.budget(r.timeoutMs),i=this.slotWrites(e);return new Promise((s,a)=>{let l=i.queued;l?.release();let d=l?.waiters[l.waiters.length-1];d!==void 0&&this.holdOwn(i,d);let u=this.identity?.()??null;for(let c of l?.waiters.slice()??[])Hl(c.identity,u)&&this.drop(i,c,Vl(e));i.queued=this.queue(i,n,r,Qp(s,a,r,o,u),l?.waiters??[]),i.wake?.(),this.pump(e,i);})}holdOwn(e,n){let{signal:r}=n,o=n.deadlineAt-Date.now();if(r?.aborted)return this.drop(e,n,_r(r));if(o<=0)return this.drop(e,n,this.timeout("save",n.budget));let i=AbortSignal.timeout(o),s=()=>this.drop(e,n,this.timeout("save",n.budget)),a=()=>{r&&this.drop(e,n,_r(r));};i.addEventListener("abort",s,{once:true}),r?.addEventListener("abort",a,{once:true}),n.detach=()=>{i.removeEventListener("abort",s),r?.removeEventListener("abort",a);};}drop(e,n,r){let o=e.queued?.waiters,i=o?.indexOf(n)??-1;i>=0&&o?.splice(i,1),n.reject(r),e.wake?.();}queue(e,n,r,o,i){let{budget:s}=o,a=[...i,o],l=AbortSignal.timeout(s),d=p=>{if(e.queued===g){this.take(e,g);for(let f of a)f.reject(p);e.wake?.();}},u=()=>d(this.timeout("save",s)),c=()=>{r.signal&&d(_r(r.signal));};l.addEventListener("abort",u,{once:true}),r.signal?.addEventListener("abort",c,{once:true});let g={bytes:n,options:r,budget:s,deadlineAt:o.deadlineAt,identity:o.identity,waiters:a,release:()=>{l.removeEventListener("abort",u),r.signal?.removeEventListener("abort",c);}};return g}async pump(e,n){if(!n.running){n.running=true;try{for(let r=n.queued;r!==void 0;r=n.queued){let o=Date.now(),i=this.holdUntil-o;if(i>0){if(i>=r.deadlineAt-o){this.take(n,r);for(let l of r.waiters)l.reject(this.held(e,i));continue}for(let l of r.waiters.slice(0,-1))i>=l.deadlineAt-o&&this.drop(n,l,this.held(e,i));}let s=Math.max(i,this.spacing(n,r,o));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=o;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 o=this.options.minWriteIntervalMs??Hp,i=Math.min(...n.waiters.map(s=>s.deadlineAt-s.budget/2));return Math.min(e.lastSentAt+o,i)-r}pause(e,n){return new Promise(r=>{let o=()=>{clearTimeout(i),e.wake===o&&(e.wake=void 0),r();},i=setTimeout(o,Math.min(n,Vp));e.wake=o;})}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(!Ul(e))return;let n=e.retryAfterSeconds,r=n===void 0?Nl:Math.min(n*1e3,Nl);this.holdUntil=Math.max(this.holdUntil,Date.now()+r);}held(e,n){let r=Math.ceil(n/1e3);return new G("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:o,options:i,budget:s}=n,a=i.contentType??"application/octet-stream",l=Bl(i.signal,Math.max(0,n.deadlineAt-Date.now()));try{let d=await Sl(this.api,this.entity.type,this.entity.id,e,{size_bytes:o.byteLength,content_type:a,...r,...i.metadata===void 0?{}:{metadata:i.metadata}},{signal:l.signal});if(typeof d.upload_url!="string"||typeof d.session_id!="string")throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let u=Xp(d.upload_headers,e),c,g=this.options.fetch??globalThis.fetch.bind(globalThis);try{c=await g(d.upload_url,{method:"PUT",headers:{"content-type":a,...u},body:o,credentials:"omit",signal:l.signal});}catch(f){throw Vo(l.signal,i.signal)?this.timeout("upload",s):new oe("upload_failed",`${jl} for PUT. Underlying error: ${f}`)}if(c.status===429)throw await Wl("upload",c);if(!c.ok){let f=await vr(c);throw new oe("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 p=Ko(await Es(this.api,this.entity.type,this.entity.id,e,{session_id:d.session_id},{signal:l.signal}));return this.remember(e,p.etag?{kind:"etag",etag:p.etag}:void 0),p}catch(d){throw Yp(d)?new oe("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,i.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(o){throw new oe("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${o}`)}}async getBytes(e,n={}){qe(e);let r=this.budget(n.timeoutMs),o=Bl(n.signal,r),i=this.seq;try{let s;try{let u=await Do(this.api,this.entity.type,this.entity.id,e,{signal:o.signal});if(!u.modified)return this.remember(e,{kind:"empty"},i),null;s=u.body;}catch(u){if(Jo(u))return this.remember(e,{kind:"empty"},i),null;throw u}if(typeof s.download_url!="string")throw new oe("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),l;try{l=await a(s.download_url,{credentials:"omit",signal:o.signal});}catch(u){throw Vo(o.signal,n.signal)?this.timeout("download",r):new oe("download_failed",`${jl} for GET. Underlying error: ${u}`)}if(l.status===429)throw await Wl("download",l);if(!l.ok){let u=await vr(l);throw new oe("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. ":"")+u)}let d=new Uint8Array(await l.arrayBuffer());return this.remember(e,s.etag?{kind:"etag",etag:s.etag}:void 0,i),d}catch(s){throw this.slots().get(e)===void 0&&this.remember(e,{kind:"failed"}),this.noteRateLimit(s),this.rethrow(s,n.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,n={}){try{let r=await Do(this.api,this.entity.type,this.entity.id,qe(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Ko(r.body):null}catch(r){if(Jo(r))return null;throw r}}async list(e={}){let n=await cl(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(Ko),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await xs(this.api,this.entity.type,this.entity.id,qe(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Jo(r))throw r}this.remember(e,{kind:"empty"});}precondition(e,n){if(Hl(n.identity,this.identity?.()??null))throw Vl(e);if(n.waiters.some(o=>o.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 oe("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 o=this.slots(),i=o.get(e);r!==void 0&&i!==void 0&&i.kind!=="failed"&&i.seq>r||(this.seq+=1,n===void 0?o.delete(e):o.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??Wp}timeout(e,n){return new oe("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof oe||Ul(e)?e:Vo(r,n)?this.timeout(o,i):e}};function Zp(t){try{return Lo(t)}catch{return t}}function zo(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"?Zp(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Sr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await ll(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>zo(o)):[]}async get(e,n={}){try{let r=await Gs(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?zo(r.body,r.etag):null}catch(r){if(Kl(r))return null;throw r}}async put(e,n,r={}){let o=await hl(this.api,this.entity.type,this.entity.id,e,{value:nr(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return zo(o)}async delete(e,n){try{await As(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 Xo(t,e,n={}){let r=new Qt(de,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new mr(t,e,r);return {settings:new Sr(t,e),inventory:o,saves:new wr(t,e,n.saves??{},n.identity),currencies:new ur(o,n.resolveCurrencyId),mutations:new fr(t,e,r),orders:new yr(t,e),progressions:new hr(t,e,o)}}function Jl(t,e,n={}){let r=new Qt(de,n.identity),o=Fl(t,r,n);return {scope:{...Xo(t,e,n),passes:o.api},recheckPasses:o.recheck}}var Yo={type:"players",id:"me"};var ot=t=>typeof t=="string"?t:"",At=t=>typeof t=="number"?t:0;function kr(t,e){let n=e??{},r=ot(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:ot(n.player_id),gameId:ot(n.game_id),channel:ot(n.channel)||"release",name:ot(n.name),slotIndex:At(n.slot_index),isActive:n.is_active!==false,createdAt:ot(n.created_at),updatedAt:ot(n.updated_at)}}var Rr=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=Xo(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 sl(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>kr(this.scope,o)):[]}async get(e,n){let r=await Ms(this.api,e,n===void 0?{}:{signal:n});return kr(this.scope,r)}async create(e){let n=await ws(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return kr(this.scope,n)}async update(e,n,r){let o=await wl(this.api,e,{name:n},r===void 0?{}:{signal:r});return kr(this.scope,o)}async delete(e,n){await Rl(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await Zs(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:At(r?.total_slots),availableSlots:At(r?.available_slots),activeCharacterCount:At(r?.active_character_count),defaultMaxSlots:At(r?.default_max_slots),purchasedExtraSlots:At(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var Yl="[gem: use gem.text.toPlain()]",zl=new Set,Xl;function eg(t){try{if(zl.has(t))return;let e=globalThis.location;if(Xl??=!!e?.port&&Je(e.hostname??""),!Xl)return;zl.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${Yl}. 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 eg(this.#n),Yl}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 it={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 xt=t=>typeof t=="string"?t:"";function Ar(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:xt(e.transfer_id),status:xt(e.status),sourceEntityId:xt(e.source_entity_id),targetEntityId:xt(e.target_entity_id),...n===void 0?{}:{message:he(n,"transfer.message")},createdAt:xt(e.created_at),expiresAt:xt(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function tg(){return crypto.randomUUID()}var xr=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 rl(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:tg()},e.signal===void 0?{}:{signal:e.signal});return Ar(n)}async list(e={}){let r=await pl(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(Ar):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await el(this.api,e,n===void 0?{}:{signal:n});return Ar(r)}async accept(e,n){return this.resolve(()=>ys(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>_l(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>bs(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Ar(await e())}};var ng=t=>typeof t=="string"?t:"",rg=t=>typeof t=="string"&&t?t:void 0,og=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 ig(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=og(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,u)=>{let c=ng(l.id);if(!c)throw new pe("config_malformed",`${d}[${u}] 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:Ql(i),currency:Ql(s)}}var pe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Zl=10*1024*1024,ed=15e3,td=new Set(["dev","test","release"]);function ag(t){if(!td.has(t))throw new pe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...td].join(", ")}. gem-api would reject the assignment read.`);return t}var Pr=t=>typeof t=="number"?t:0,Qo=t=>typeof t=="string"?t:"";function sg(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:Qo(o.entry_id),weight:Pr(o.weight),dropRate:Pr(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:Qo(e.loot_table_id),name:Qo(e.name),rollCount:Pr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Pr(e.total_weight),entries:n}}var Tr=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 Os(this.api,e,n===void 0?{}:{signal:n});return sg(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??ed),n;try{let l=await Cs(this.api,ag(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=rg(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??ed}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=>Ho(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>Zl)throw new pe("config_too_large",`the config document is ${s.length} bytes, over the ${Zl} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new pe("config_malformed",`config document is not JSON: ${String(l)}`)}return ig(a)}};var nd=400,Ie=t=>typeof t=="string"?t:"",lg=/(?:Z|[+-]\d{2}:?\d{2})$/i;function at(t){let e=Ie(t);if(!lg.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var dg=/^[0-9a-f]{1,64}$/,cg=/^[0-9a-f]{16}$/,ug=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,mg=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Zo(t){let e=Ie(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 pg=4096,gg=new TextEncoder;function fg(t){let e=Ie(t.challenge_data),n=Ie(t.challenge_data_hash);return e===""||!cg.test(n)?{}:gg.encode(e).length>pg?{}:{data:e,dataHash:n}}function yg(t){let e=t??{},n=at(e.period_start_at),r=at(e.period_ends_at);if(n===0||r===0)return;let o=Ie(e.slug),i=Ie(e.seed),s=Zo(e.period_local_date),a=Ie(e.boundary),l=Ie(e.reset_time);return {id:Ie(e.progression_definition_id),...o===""?{}:{slug:o},window:Ie(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:ug.test(a)?a:"",resetTime:mg.test(l)?l:"",seed:dg.test(i)?i:"",...fg(e)}}function Pt(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 Er(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(yg).filter(n=>n!==void 0):[]}var Zt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;Pt(n);let r=await al(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return Er(r)}};function Ce(t){return typeof t=="string"&&t!==""?t:void 0}var rd=new Set(["localhost","127.0.0.1","[::1]"]);function st(t){return Tt(t)}function Tt(t){let e=Ce(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:"&&rd.has(n.hostname)))return e}var hg=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,bg=/^[a-z][a-z0-9_]{0,31}$/;function vg(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let o=r??{},i=Ce(o.family),s=Ce(o.avatar_3d_id),a=st(o.model_url),l=st(o.icon_url);i===void 0||!bg.test(i)||n.has(i)||s===void 0||!hg.test(s)||a===void 0||l===void 0||(n.add(i),e.push({family:i,id:s,modelUrl:a,iconUrl:l}));}return e}function _g(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=Ce(r.item_id),i=st(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function Pe(t){let e=t??{},n=Ce(e.player_id),r=Ce(e.display_name),o=Ce(e.discriminator),i=Ce(e.display_tag),s=Ce(e.avatar_icon_id),a=st(e.avatar_icon_url),l=Ce(e.avatar_3d_id),d=st(e.avatar_3d_model_url),u=st(e.avatar_3d_icon_url),c=vg(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},...u===void 0?{}:{avatar3dIconUrl:u},...c===void 0?{}:{avatars3d:c},badges:_g(e.badges)}}var wg=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function ei(t){if(t===void 0)return;let e=st(t);if(e===void 0)return;let n=new URL(e);return rd.has(n.hostname)||wg.has(n.origin)?e:void 0}var od=100,sd=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function ti(t){let{periodsBack:e,period:n,playerId:r}=t;if(Pt(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!sd.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 ld(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!sd.test(e))return;let n=Zo(t.period_local_date),r=at(t.period_start_at),o=at(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:at(t.opens_at),closesAt:at(t.closes_at),final:t.final===true}}var en=t=>typeof t=="string"?t:"",Et=t=>typeof t=="number"?t:0,tn=t=>typeof t=="string"?t:void 0,Sg=t=>typeof t=="number"?t:void 0,dd={player:"players",character:"characters"};function kg(t,e){let n=t??{},r=tn(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(dd,n.entity_type)?n.entity_type:void 0,i=cd(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:Et(n.rank),occurredAt:Et(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 id(t,e){let n=t??{},r=tn(n.bucket_1),o=tn(n.bucket_2),i=Sg(n.update_frequency_seconds),s=ld(n);return {leaderboardType:en(n.leaderboard_type),runType:en(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(a=>kg(a,e)):[],generatedAt:Et(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...s===void 0?{}:{period:s}}}function ad(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=cd(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:Et(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function cd(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 Rg(t,e,n){let r=t??{},o=tn(r.bucket_1),i=tn(r.bucket_2),s=ld(r);return {leaderboardType:en(r.leaderboard_type),runType:en(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(ad).filter(a=>a!==void 0):[],personalBest:ad(r.personal_best)??null,totalRuns:Et(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:Et(r.generated_at),...s===void 0?{}:{period:s}}}var nn=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=ti(n),o=await Vs(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 id(o,false)}async friends(e,n={}){let r=ti(n),o=await Bs(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 id(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>od)throw new TypeError(`limit must be an integer between 1 and ${od}, got ${String(l)}`)}let i=ti(o),s=await $s(this.#e,e,dd[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"&&en((s??{}).entity_id)||r;return Rg(s,n,a)}};var Ir=t=>typeof t=="string"?t:"",ni=t=>typeof t=="number"?t:0;function ud(t){let e=t??{};return {playerId:Ir(e.player_id),key:Ir(e.key),value:e.value,updatedAt:ni(e.updated_at)}}function Ag(t){let e=t??{};return {...Pe(e),playerId:Ir(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:ni(e.updated_at)}}function xg(t){return t?.reason==="not_found"}var rn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await Us(this.api,qe(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:Ir(o.key),entries:Array.isArray(o.entries)?o.entries.map(Ag):[],generatedAt:ni(o.generated_at)}}async of(e,n,r={}){try{return ud(await Qs(this.api,e,qe(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(xg(o))return null;throw o}}async set(e,n,r={}){if(qe(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 ud(await bl(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Ps(this.api,r,qe(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var Pg="gemChallenge",md=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pd(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(Pg)??void 0}catch{return}}var lt=class extends G{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});}},Cr=t=>typeof t=="string"?t:void 0;function gd(t){let e=t??{};return {...Pe(e),playerId:Cr(e.player_id)??""}}function fd(t){let e=t.has_more===true?Cr(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function Tg(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(gd):[],...fd(e)}}var ri=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Eg(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 yd(t){let e=t??{},n=ri(e.opened_at),r=ri(e.answered_at);return {id:Cr(e.item_id)??"",from:gd(e.sender),template:Cr(e.template)??"",params:Eg(e.params),createdAt:ri(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function Ig(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(yd):[],...fd(e)}}function Cg(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var on=class{#e;#n;#i;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#i=n.launchedChallengeId;}async list(e={}){let n=await ml(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Tg(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await ul(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Ig(n)}async launchedChallenge(e={}){let n=this.#i;if(n===void 0||!md.test(n))return null;try{return yd(await Hs(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(Cg(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!md.test(e))throw new G("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await gl(this.#e,e);}};var Mg=0;function _e(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++Mg)}-${String(Date.now())}-${t}`}}var Og=12e4,hd=8,Gg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Lg=/^[a-z0-9][a-z0-9_-]{0,63}$/;function an(t,e,n={}){return new lt(new G("invalid",400,e,void 0,t),n)}function Dg(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function $g(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!Gg.test(e))return {error:an("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!Lg.test(n))return {error:an("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(!Dg(r))return {error:an("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:an("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return i.length>hd?{error:an("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(hd)}`)}:{playerId:e,template:n,params:o}}function Fg(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 lt(new G("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 lt(new G("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 qg(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function bd(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=$g(n);if("error"in r)return Promise.reject(r.error);let o=`challenge-${_e()}`;return new Promise((i,s)=>{let a={},l=u=>{e.delete(o)&&(t.clock.clearTimeout(a.timer),"error"in u?s(u.error):i(u.outcome));};e.set(o,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??Og);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 (${qg(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(Fg(n));}}}var Mr=t=>typeof t=="string"?t:void 0;function Ng(t){let e=t??{},n=Mr(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Mr(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Or=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await or(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=Ng(i);s!==void 0&&o.push(s);}return o}},oi=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function jg(t){let e=t??{},n=Mr(e.currency_id);if(n===void 0||n==="")return;let r=oi(e.limit),o=Math.min(oi(e.earned),r),i=Math.min(oi(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:Mr(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 vd(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 Gr=class{#e;#n;#i;constructor(e,n,r){this.#e=e,this.#n=n,this.#i=r;}async get(e={}){let r=(await Ks(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=jg(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)??(()=>{})}},sn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Or(e),this.earnAllowance=new Gr(e,n,r);}};var ii=t=>typeof t=="string"?t:"",_d=t=>typeof t=="number"?t:0;function Bg(t){let e=t??{};return {key:ii(e.key),visibility:ii(e.visibility),value:e.value,updatedAt:_d(e.updated_at)}}function Ug(t){let e=t??{};return {...Pe(e),playerId:ii(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Bg):[],generatedAt:_d(e.generated_at)}}function Wg(t){return t?.reason==="not_found"}var ln=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return Ug(await zs(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Wg(r))return null;throw r}}};var Hg=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]]),dn=class extends G{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:Hg.get(this.code))??super.retryable}},Xe=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Vg(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof G?Jg(i):i}return Kg(o)}};function Vg(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 Kg(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 Jg(t){let{details:e,invocationId:n}=ps(t),o=e?.untrusted?.message,i=e?.reason;return new dn(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 Lr(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 zg=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],ai="gem_";function si(t){return t.startsWith(ai)}function Xg(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function Yg(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 Dr(t,e,n){if(li(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=Yg(Xg(`${t}:${e}`))%r;return typeof n=="number"?o:n[o]}function li(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 wd=1e4,Sd=50,Qg=500,Zg=65536-4*1024,ef=24*1024;function kd(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 tf=6e4;function nf(t){let e=new Map;for(let n of t??[]){let r=new Set;for(let[o,i]of Object.entries(n.dimensions??{})){let s=i?.range;typeof s=="object"&&s!==null&&r.add(o);}r.size>0&&e.set(n.id,r);}return e}function rf(t,e){if(e===void 0)return t;let n=null,r={};for(let[o,i]of Object.entries(t.measures))e.has(o)?(n??={...t.dimensions})[o]=String(i):r[o]=i;return n===null?t:{dimensions:n,measures:r}}var Rd=t=>typeof t=="number"?t:0,of=t=>typeof t=="string"?t:"";function $r(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function af(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:Rd(i.index),code:of(i.code)}}):[];return {accepted:Rd(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function di(){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 sf(t){return t?.retryable===true}var cn=class{#e;#n;#i;#h;#t=[];#b={};#a=0;#s=null;#v=false;#_=false;#m=0;#w=0;#S=0;#r=false;#k=null;#l=null;#c=false;#o=false;#p=false;#R=false;#A=false;#g=void 0;#x=false;#P=0;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#i=Math.max(wd,e.options?.flushIntervalMs??wd),this.#h=Math.max(1,Math.floor(e.options?.maxQueue??Qg));}track(e,n={}){if(!this.#n||this.#r)return;if(si(e)){this.#A||(this.#A=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.#T(e,kd({...this.#b,...n}));let r=this.#C();this.#g===void 0&&!this.#x&&r!==null&&r!==""&&(this.#x=true,this.#M());}setContext(e){this.#b={...this.#b,...e};}async experiment(e,n){li(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"?Dr(e,r,n):Dr(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return $r();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.")),$r();let r=e.keepalive===true;if(!r&&this.#e.declarations!==void 0&&this.#t.some(d=>!si(d.name))&&await this.#M(),this.#I(),this.#t.length===0||this.#m>0&&!r)return $r();this.#u();let o=this.#t.splice(0,this.#G(r)),i=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:di(),sent_at_ms:s,events:o.map(d=>Ad(d,s,this.#g?.get(d.name)))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await nl(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),u=af(d,i);return this.#w=0,this.#S=0,this.#L(u),u}catch(d){throw sf(d)?(this.#O(o,i),this.#w+=1,this.#S=this.#e.clock.now()+Lr(this.#w,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.#T(e,kd(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:di(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Sd?this.#f():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.#f({keepalive:true});}setPaused(e){this.#r||e===this.#v||(this.#v=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#_||(this.#_=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}#T(e,n){let{dimensions:r,measures:o}=n;for(this.#I();this.#t.length>=this.#h;)this.#t.shift(),this.#a+=1;this.#t.push({uid:di(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=Sd?this.#f():this.#d();}#f(e={}){if(e.keepalive!==true&&this.#E()>0){this.#d();return}this.flush(e).catch(()=>{});}#E(){return Math.max(0,this.#S-this.#e.clock.now())}#O(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#h;)this.#t.shift(),this.#a+=1;}#G(e){let n=e?ef:Zg,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(Ad(s,0,this.#g?.get(s.name))).length+1,o>n)return Math.max(1,i)}return r}#d(){this.#s!==null||this.#v||this.#_||this.#o||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#f();},Math.max(this.#i,this.#E())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#I(){let e=this.#D();e===null||e===""||(this.#k!==null&&this.#k!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#k=e);}#L(e){for(let n of e.rejected)this.#y(`[gem] analytics: an event was refused (${n.code}). `+lf(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}}#D(){try{return this.#e.playerId()}catch{return null}}async#M(){let e=this.#e.declarations;if(e!==void 0&&!(this.#e.clock.now()<this.#P))try{this.#g=nf(await e());}catch{this.#P=this.#e.clock.now()+tf;}}};function Ad(t,e,n){let{dimensions:r,measures:o}=rf(t,n);return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:r,measures:o}}function lf(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 un(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 df=2e3,cf=5e3;function Pd(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,u=null;s=c=>{d||(d=true,r=null,t.clock.clearTimeout(u),l(c));},u=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??df);});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 !xd(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=u=>{o.delete(d)&&(t.clock.clearTimeout(l),a(u));};o.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??cf);})},accept(s,a){let l=un(a),d=be(s),u=l.length>0?l:d===void 0?[]:[d];if(u.length!==0){e=u,r?.settle(u);for(let[c,g]of [...o])xd(u,g)||c(u);}}}}function xd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var uf=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=uf.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var Td=["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"],mf=new Set(Td);function Ye(t){return typeof t=="string"&&mf.has(t)?t:"unknown"}var Fr="webrtc_dedicated",pi=["universal","mobile","web"];var pf="p2p_unavailable",gf="capacity_unavailable",ff=2,Ed=3e4,Id=1e3,Cd=2e4;async function gi(t){let e=be(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??de,i=t.retry??{},s=i.budgetMs??Ed,a=i.maxDelayMs??Cd,l=i.initialDelayMs??Id,d=o.now(),u=d+s,c=0;for(;;){c++;try{let g=await bi(t.signal,"while allocating",()=>t.client.post(`${Gd(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:g.match_id,status:g.status}}catch(g){if(!yf(g)||s<=0)throw g;if(g.status===503&&g.code===pf)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: ${g.message}`,{cause:g});if(r=g.code===gf?r+1:0,n!==void 0&&r>=ff){let k=n;n=void 0;let P=be(await k());P!==void 0&&(e=P,r=0);}let p=Math.min(a,l*2**(c-1)),f=Math.min(a,(g.retryAfterSeconds??0)*1e3),R=Math.max(p/2,f)+Math.random()*(p/2);if(o.now()+R>u)throw hf(t,g,c,o.now()-d,s);if(i.onWaiting?.({attempt:c,elapsedMs:o.now()-d,budgetMs:s,nextAttemptInMs:R,status:g.status,message:g.message}),await qr(o,R,t.signal),t.signal?.aborted)throw mi("while waiting to allocate")}}}function yf(t){return t instanceof G?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function hf(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 bf=12e4,vf=1e3;async function fi(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??vf,o=t.timeoutMs??bf,i=e.now()+o,s=Md(t),a={seen:t.knownToExist===true};for(;;){let l=await Od(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 qr(e,r,t.signal);}}async function yi(t){return (await Od(t,Md(t),{seen:t.knownToExist===true})).outcome}function Md(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Gd(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Od(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await bi(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof G&&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:_f(r,i,o)};if(i.status==="failed"){let s=i.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Ye(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function hi(t){let e=await bi(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 bi(t,e,n){if(t?.aborted)throw mi(e);try{return await n()}catch(r){throw t?.aborted?mi(e,r):r}}function mi(t,e){return new w("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function _f(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 Gd(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function qr(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 Ld(t){return typeof t=="string"&&t.trim()!==""}function Nr(t,e){return Ld(t)?t.trim():Ld(e)?e:null}var jr="0.1.0-beta",Dd="0-beta",It="web",wf=/^(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 Sf(t){let e=wf.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function $d(t,e){let n=kf(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:jr};let o=Sf(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 '${jr}' for it.`);if(o!==Dd)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${Dd}' 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 '${jr}' for it.`);return {...t,platform:n,engineVersion:r}}function kf(t,e){if(t===void 0||t===It)return It;if(!pi.includes(t))throw new w("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${pi.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${It}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${It}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),It}function mn(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:Fd(e.queued_at),expiresAt:Fd(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function Fd(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var Rf=3,qd=1e3,Br=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?qd:Math.max(qd,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 G&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<Rf){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof G&&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 Af="gemPlayWith",xf=/^[A-Za-z0-9_-]{16,128}$/;function Nd(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(Af);}catch{return}return e!==null&&xf.test(e)?e:void 0}function jd(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var Pf="join",Tf="welcome",Ef="rejected",Bd=25e3,If=1e3,vi=1;function _i(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Cf={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 wi(t){let e=typeof t=="string"?t:"unknown";return new w(Cf[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function pn(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Bd),a=n.setTimeout(()=>y(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,If)),l=R=>{let k=R.data;if(typeof k!="string"){c(k);return}let P;try{P=JSON.parse(k);}catch{c(k);return}if(i){c(k);return}if(P.t===Tf){let h=_i(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){y(wi(P.reason));return}c(k);},d=()=>{y(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},u=()=>{y(new w("aborted","the caller aborted during the join exchange"));},c=R=>{i&&t.onMessage?.(R);},g=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",u);},p=()=>{e.removeEventListener("message",l);},f=R=>{i=true,g(),t.onMessage===void 0&&p(),r({welcome:R,detach:p});},y=R=>{i||(i=true,g(),p(),o(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){u();return}t.signal?.addEventListener("abort",u);try{e.send(JSON.stringify({t:Pf,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:vi}:{}}));}catch(R){y(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var dt=1,gn=2,Si=4,Ai=8,Mf=2,Of=1e3,xi="heartbeat timeout",fn="gem-uu",Ur=2,Wd="gem_transports";function Ct(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Gf(r)||e.includes(r)||e.push(r);}return e}function Gf(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function yn(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 Wr(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Hd=new TextEncoder,Vd=new TextDecoder;function Pi(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function Ti(t){let e=0;return t?.reliable===false&&(e|=dt),t?.ordered===false&&(e|=gn),e}function Ei(t){return {reliable:(t&dt)===0,ordered:(t&gn)===0}}var Ii={reliable:true,ordered:true};function Kd(t){return JSON.stringify({t:"join",credential:t,wire:Ur,heartbeat:vi})}function Jd(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=_i(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"?wi(e.reason):new w("join_refused","the server answered the join out of protocol")}function Hr(){return typeof globalThis.WebTransport=="function"&&Ci===null}function Vr(){return Ci}var Ci=null;var Ud="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Lf(t){let e=rr(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 ki=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 Ri(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 hn(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:Lf(t.certHashBase64)}]});}let r=n,o=a=>{try{r.close();}catch{}throw a},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(Ci=Ud,o(new w("connection_failed",`${Ud}; 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,u=d.writable.getWriter();await u.write(Ri(Si,Hd.encode(Kd(t.credential))));let c=new ki,g=d.readable.getReader(),p;for(;p===void 0;){let f=await Promise.race([g.read(),s]);if(f.done||f.value===void 0)return o(new w("connection_failed","the control stream closed before the join was answered"));for(let y of c.push(f.value)){p=Jd(Vd.decode(y.payload));break}}return {link:Df(r,u,g,c,t.log??(f=>console.warn(f)),Xd(p,t.clock)),welcome:p}}catch(a){return o(a)}}function Df(t,e,n,r,o,i){let s,a,l=false,d=f=>{if(!l){l=true,u.stop();try{t.close();}catch{}a?.(f);}},u=Oi(i,()=>d(xi)),c=(f,y)=>{u.heard(),(f&Ai)===0&&s!==void 0&&((f&Si)!==0?s(Vd.decode(y),Ii):s(y,Ei(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let y of r.push(f.value))c(y.flags,y.payload);}}catch{}d("stream closed");})();let g,p;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let y=f.readable.getReader();p=f.writable.getWriter(),g=f,(async()=>{try{for(;;){let R=await y.read();if(R.done||R.value===void 0)break;let k=R.value;k.byteLength!==0&&c((k[0]??0)|dt|gn,k.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){g=void 0,p=void 0,o(`[gem] webtransport datagram lane unusable (${Wr(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(zd(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,y){if(l)return;if(typeof f=="string"){e.write(Ri(Si,Hd.encode(f))).catch(()=>d("write failed"));return}let R=Ti(y);if((R&dt)!==0&&p!==void 0){let k=Pi(R,f),P=g?.maxDatagramSize;if(P===void 0||k.byteLength<=P){p.write(k).catch(()=>{});return}}e.write(Ri(R,f)).catch(()=>d("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){d("closed");}}}function Mi(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=p=>{s||(s=true,clearTimeout(a),r.close(),i(p));},d=()=>{r.send(Kd(t.credential));},u=p=>{if(s)return;if(typeof p.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let f;try{f=Jd(p.data);}catch(y){l(y);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",u),r.removeEventListener("close",c),r.removeEventListener("error",g),o({link:$f(r,Xd(f,t.clock)),welcome:f});},c=()=>{l(new w("connection_failed","the websocket closed before the join was answered"));},g=()=>{l(new w("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",u),r.addEventListener("close",c),r.addEventListener("error",g),r.readyState===1&&d();})}function zd(t){return typeof t=="string"&&t.length>0?t:void 0}function Xd(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function Oi(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Of)*Mf,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 $f(t,e){let n,r,o=false,i=a=>{if(!o){o=true,s.stop();try{t.close();}catch{}r?.(a);}},s=Oi(e,()=>i(xi));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,Ii);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Ai)===0&&n?.(l.slice(1),Ei(d));})),t.addEventListener("close",(a=>i(zd(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!o){if(typeof a=="string"){t.send(a);return}t.send(Pi(Ti(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){i("closed");}}}function Gi(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=Oi(r,()=>l(xi)),u=(c,g)=>{if(d.heard(),typeof c=="string"){o?.(c,Ii);return}let p=new Uint8Array(c);if(p.byteLength===0)return;let f=p[0]??0;(f&Ai)===0&&o?.(p.slice(1),Ei(f|g));};if(t.addEventListener("message",(c=>u(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",(g=>u(g.data,dt|gn))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,g){if(s)return;if(typeof c=="string"){t.send(c);return}let p=Ti(g),f=Pi(p,c);if((p&dt)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}t.send(f);},onMessage(c){o=c;},onClose(c){i=c;},close(){l("closed");}}}function Yd(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=Li(r);o!==void 0&&(e[n]=o);}return e}function Qd(t){if(Array.isArray(t))return t.map(Ff).filter(e=>!!e)}function Li(t){if(Di(t)||Array.isArray(t)&&t.every(Di))return t}function Di(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function Ff(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Li(e.fixed),r=Li(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},...Mt("description",qf(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Di)?{allowed:e.allowed}:{},...Mt("min",bn(e.min)),...Mt("max",bn(e.max)),...Mt("minItems",bn(e.min_items)),...Mt("maxItems",bn(e.max_items)),...Mt("maxLength",bn(e.max_length))}}function qf(t){return typeof t=="string"&&t.length>0?t:void 0}function bn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Mt(t,e){return e===void 0?{}:{[t]:e}}function Ne(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(Nf):[];return {id:n,gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:Me(e.max_players)??0,memberCount:Me(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",Yd(e.room_args)),...Re("roomArgsTemplate",Qd(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:Me(e.version)??0,...Re("templateId",Q(e.template_id)),...Re("templateSlug",Q(e.template_slug)),roomType:Q(e.game_room_type)??"Standard",...Re("transports",Ct(e.transports)??void 0),createdAt:Me(e.created_at)??0,updatedAt:Me(e.updated_at)??0,...Re("startedAt",Me(e.started_at))}}function Nf(t){let e=t??{};return {...Pe(e),playerId:Q(e.player_id)??"",isReady:e.is_ready===true,role:Q(e.role)??"member",joinedAt:Me(e.joined_at)??0,...Re("groupId",Q(e.group_id)),...Re("platform",Q(e.platform))}}function $i(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:Me(e.max_players)??0,memberCount:Me(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Q(e.game_channel)??"release",roomType:Q(e.game_room_type)??"Standard",createdAt:Me(e.created_at)??0}}function Q(t){return typeof t=="string"&&t.length>0?t:void 0}function Me(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Re(t,e){return e===void 0?{}:{[t]:e}}var Kr=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($i),...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($i)}))}create(e,n,r){return Bf(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},...vn(n)},e.signal).then(Ne)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Ne)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...vn(r)},n.signal).then(Ne)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...vn(r)},n.signal).then(Ne)}quickJoin(e,n,r=[]){return Fi(this.options,e,n,r).then(o=>o.room)}createTicket(e,n,r=[]){return Rs(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},...vn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(mn)}heartbeatTicket(e){return tl(this.generated(),e).then(mn)}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(mn):vs(this.generated(),e).then(mn)}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 ec(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(Ne)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Ne)}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(Ne)}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 Zd(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 Zd(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function ec(t,e){return e===void 0&&t.selfHosted?.()===true}function Fi(t,e,n,r=[],o){let i=ec(t,e.partyId);return t.client.post(`${Zd(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...jf(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},...vn(n)},e.signal).then(s=>({room:Ne(s),playWith:o===void 0?null:jd(s)}))}function jf(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function vn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function Bf(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 zr=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 Uf(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var Wf=1e3,Hf=3e3,Vf=6e4,Kf=2,tc=new Set(["game_room_closed","game_room_gone"]),Jf=12e4,zf=5e3,Xf=new Set(["invalid_cluster_target","capacity_unavailable"]),Yf=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function ic(t,e){return new qi(e,t)}var qi=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 Kr(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"),ey(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||oc(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"),Zf(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||oc(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 Br({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 G&&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(()=>yi({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 G&&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=Ye(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=(u,c)=>gi({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...u===void 0?{}:{clusterTargetId:u},...o===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:g=>{this.emitter.emit("matchStartWaiting",g),n.retry?.onWaiting?.(g);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(i,[s]).catch(async u=>{if(o!==void 0||!rc(u))throw u;let c=await this.nextCluster([s],true);if(c===void 0)throw u;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 fi({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,!tc.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(!ct()){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<Wf){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(Uf(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!ct()){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(()=>yi({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,!tc.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||!Xf.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 zr({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&&ct())){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(),!!ct())){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 Xr)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 Xr)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??zf}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=Nr(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 $d({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return un(await this.options.resolveClusterTargets());let e=be(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !rc(e)||n.length===0?[]:un(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(un(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 G)||e.reason!=="conflict"||!Yf.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new G(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 G(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 G(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 Fi(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 G?{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=Qf(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??Jf;return new Promise((o,i)=>{let s=c=>{a(),l(),this.options.clock.clearTimeout(u),e.signal?.removeEventListener("abort",d),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>o(c))),l=this.emitter.on("matchFailed",(c,g)=>s(()=>i(new w("allocation_failed",`match ${c} did not come up: ${g}`)))),d=()=>s(()=>i(new w("aborted","the caller aborted while awaiting a match"))),u=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??Hf}pushedInterval(){return this.options.pushedPollIntervalMs??Vf}pushed(){return this.options.clock.now()-this.lastPushAt<Kf*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 ct(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Xr=["visibilitychange","focus","pageshow","online"];function Qf(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||nc(t)!==nc(e)}function nc(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function rc(t){return t instanceof G&&t.code==="invalid_cluster_target"}var Yr=8;function Zf(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=Yr&&t.every(n=>typeof n=="string"&&n.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Yr} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function ey(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Yr&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Yr} 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 oc(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var ty=["p2p","dedicated","unknown"],Ni=["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 Ot=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=ny(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 ny(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>Ni.includes(o.type)).slice(0,100).map(o=>{let i=ry(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function ry(t){if(t!==void 0)return ty.includes(t)?t:"unknown"}var _n=class{constructor(e){this.options=e;this.reporter=new Ot({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:Qr(o.credential)??"",hostFingerprint:Qr(o.host_fingerprint)??"",hostEpoch:Zr(o.host_epoch)??0,expiresAt:(Zr(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,u=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);u.length!==0&&i.push({urls:u,username:Qr(d.username)??"",credential:Qr(d.credential)??""});}let s=Zr(o.expires_at),a=Zr(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 Qr(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 oy=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),$=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=oy.has(n);}reason;retryable};var ac=10240,sc=2048,iy=new TextEncoder;function lc(t){return iy.encode(t).length}function Qe(t,e){let n=o=>{throw new w("invalid_sdp",`the ${e} ${o}`)},r=lc(t);r>=ac&&n(`is ${r} bytes, over the ${ac} 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=lc(o);i>sc&&n(`has a ${i}-byte line, over the ${sc} limit`);}}function eo(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 to=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 ay=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function Gt(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=no(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function no(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 ay.test(r)?r:null}function wn(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 ji=5e3,sy=12e4+ji,ly=1024,dy=6e4,cy=1e4,dc=64*1024,cc=5;function Bi(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 $("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 $("keys_unavailable",o.reason);let a=t.fetch??((g,p)=>globalThis.fetch(g,p)),l;try{l=await a(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(cy)});}catch{throw new $("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 $("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let g=await l.text();if(g.length>dc)throw new $("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${dc} characters, which is not a key set this platform publishes.`);d=JSON.parse(g);}catch(g){throw g instanceof $?g:new $("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let u=Array.isArray(d.keys)?d.keys:[];if(u.length>cc)throw new $("keys_unavailable",`the JWKS endpoint published ${u.length} keys, over the ${cc} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=i();for(let g of u){let p=g;if(p.kty==="RSA"&&!(p.alg!==void 0&&p.alg!=="RS256")&&!(p.use!==void 0&&p.use!=="sig")&&!(typeof p.kid!="string"||p.kid.length===0))try{let f=await c.importKey("jwk",{...g,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(p.kid,f);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!o.ok)throw new $("keys_unavailable",o.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new $("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<dy?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var Sn=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>=ly){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+sy),true}};function mc(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 uc(t){try{let e=new TextDecoder().decode(mc(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Ui(t,e,n,r,o){let i=B=>{throw new $("peer_unauthenticated",`the peer's join credential is not usable: ${B}`)},s=t.split(".");s.length!==3&&i("it is not a three-part JWT");let[a,l,d]=s,u=uc(a);u===null&&i("its header does not decode"),u.alg!=="RS256"&&i(`its alg is ${JSON.stringify(u.alg)}, not RS256`),u.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(u.typ)}, not p2p+jwt`);let c=u.kid;(typeof c!="string"||c.length===0)&&i("it names no key");let g=await n.key(c);g===null&&i("it was signed by a key this build cannot resolve");let p=o.subtle??globalThis.crypto?.subtle;p||i("this environment has no WebCrypto");let f=new TextEncoder().encode(`${a}.${l}`),y;try{y=mc(d);}catch{i("its signature does not decode");}await p.verify({name:"RSASSA-PKCS1-v1_5"},g,y,f)||i("its signature does not verify");let k=uc(l);k===null&&i("its payload does not decode");let P=k,h=B=>typeof P[B]=="string"?P[B]:"",S=B=>typeof P[B]=="number"&&Number.isFinite(P[B])?P[B]: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 C=S("exp")*1e3,I=S("nbf")*1e3;(!Number.isFinite(C)||e.now>C+ji)&&i("it has expired"),Number.isFinite(I)&&e.now<I-ji&&i("it is not valid yet");let U=h("role");U!=="host"&&U!=="client"&&i("it names no usable role");let q=S("host_epoch");q!==e.hostEpoch&&i("it names a different host epoch");let x=no(h("fingerprint"));x===null&&i("its fingerprint claim is malformed"),wn(x,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let A=no(h("host_fingerprint"));A===null&&i("its host fingerprint claim is malformed"),wn(A,e.hostFingerprint)||i("it was issued against a different host certificate");let O=h("jti");O.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(O,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:U,fingerprint:x,hostFingerprint:A,jti:O,expiresAt:C}}function Wi(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 Hi(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 Vi(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Ki(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 pc(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 gc(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var kn=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 Ji={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}},je=["reliable","ordered","unreliable"];function zi(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 Rn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var yc=1,fy=3e4,hc=2e3,yy=5e3,bc=6e4,hy=8,Yi=class{constructor(e=hy){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;}},by=new Yi,vy=8,_y=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),xn=class{constructor(e){this.options=e;this.keys=e.keys??Bi({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new to;links=new Map;replays=new Sn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=yc+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??fy;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: ${Xi(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 $("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 $("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 $("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=ce(e.playerId),r=ce(e.hostPlayerId),o=ro(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new kn(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,yc),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new $("invalid_sdp","the browser produced an offer with no SDP");Qe(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,o=r===void 0?null:Gt(r);if(o===null)throw new $("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??by,s=()=>this.closed||e!==this.credentialGeneration,a=yy;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 u=d.status,c;if(u===409)c=hc;else if(u===429){let g=d.retryAfterSeconds;typeof g=="number"&&Number.isFinite(g)&&g>=0?c=g*1e3:(c=a,a=Math.min(a*2,bc)),c=Math.min(Math.max(c,hc),bc);}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=ce(e.fromPlayerId),r=ce(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=vy){let u=this.pendingOffers.keys().next().value;u!==void 0&&this.pendingOffers.delete(u);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let o=ce(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;Qe(r,"offer"),this.refuseMedia(r,"offer");let i=Gt(r);if(i===null)throw new $("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 $("invalid_sdp","the browser produced an answer with no SDP");Qe(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=ce(e.fromPlayerId),r=ce(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;Qe(r,"answer"),this.refuseMedia(r,"answer");let i=Gt(r);if(i===null)throw new $("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:wn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new $("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=ce(e.fromPlayerId),r=ce(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=ce(e.sdpMid),s=ro(e.sdpMLineIndex)??ro(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=ce(e.playerId);if(n===null)return;let r=ce(e.reason)??"left";if(n===this.localPlayerId){this.fail(new $("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=ce(e.hostPlayerId),r=ro(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...ce(e.reason)===null?{}:{reason:ce(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 $("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 $("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=ce(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new $("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=ce(e.code)??"unknown",r=ce(e.message)??"the platform refused a signaling message";this.report_(new $("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??zi)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let g of je){let p=o.createDataChannel(g,Ji[g]);p.binaryType="arraybuffer",i[g]=p;}let s={playerId:e,assignedPeerId:n,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=g=>{let p=g.candidate;p?.candidate&&this.options.signaling.candidate(e,p.candidate,p.sdpMid??void 0,p.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),u=g=>{this.onHandshakeMessage(s,g.data).catch(p=>this.report_(p));},c=()=>{this.onReliableOpen(s).catch(g=>this.report_(g));};return o.addEventListener("icecandidate",a),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",c),i.reliable.addEventListener("message",u),s.detachHandshake=()=>{i.reliable.removeEventListener("open",c),i.reliable.removeEventListener("message",u);},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 $("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 $("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(Wi({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Ki(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 $(gc(r.reason),pc(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=Gt(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 Ui(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 $&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",Xi(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(Hi({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(Vi(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 je)vc(e.channels[o]);vc(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 $?e:new $("connection_failed",Xi(e),{cause:e}));}count(e){this.counted||!_y.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(eo(e))throw new $("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 ce(t){return typeof t=="string"&&t.length>0?t:null}function ro(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Xi(t){return t instanceof Error?t.message:String(t)}function vc(t){try{t.close();}catch{}}var wy=100,Sy=50,Pn=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??wy)){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 $("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new $("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??Sy));}};function V(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Ze(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function Lt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function _c(t){return typeof t=="boolean"?t:void 0}var we=V(64),Tn=Ze(0,2147483647);function Qi(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=we(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 Ay=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=Lt("disconnected","failed","closed")(e.iceState),r=Ze(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",Lt("initial","ice_restart","full_reconnect")),K("sdp_hash","sdpHash",V(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[Y("peer_id","peerId",we),Y("sdp","sdp",V(10240)),Y("assigned_peer_id","assignedPeerId",Ze(0,4294967295)),K("sdp_hash","sdpHash",V(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[Y("peer_id","peerId",we),Y("candidate","candidate",V(512)),K("sdp_mid","sdpMid",V(64)),K("sdp_mline_index","sdpMLineIndex",Ze(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[Y("host_epoch","hostEpoch",Tn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[Y("host_epoch","hostEpoch",Tn),K("evidence","evidence",Ay)]}}));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",we),Y("hostPlayerId","host_player_id",we),Y("hostEpoch","host_epoch",Tn),K("members","members",Qi)],offer:[Y("fromPlayerId","from_player_id",we),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",Lt("initial","ice_restart","full_reconnect"))],answer:[Y("fromPlayerId","from_player_id",we),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",Ze(0,4294967295))],ice:[Y("fromPlayerId","from_player_id",we),Y("candidate","candidate",V(512)),K("sdpMid","sdp_mid",V(64)),K("sdpMLineIndex","sdp_m_line_index",Ze(0,255)),K("sdpMLineIndexAlt","sdp_mline_index",Ze(0,255))],peerJoined:[Y("playerId","player_id",we)],peerLeft:[Y("playerId","player_id",we),K("reason","reason",V(64))],migration:[Y("hostPlayerId","new_host_player_id",we),Y("hostEpoch","host_epoch",Tn),K("reason","reason",V(64)),K("kickedPlayerIds","kicked_player_ids",Qi),K("migrationComplete","migration_complete",_c)],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 mt="webrtc_p2p";function Sc(t){let e=new _n({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 $("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!==mt)throw new $("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${mt}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new Pn({bridge:t.bridge,matchId:s.matchId,clock:t.clock}),l=new xn({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 Rn(),...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 kc(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(!ct());for(let d of Xr)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(!ct());}let s=new Map;return i.push(n.on("matchReady",a=>{let l=a.protocol===mt?"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 Rc=["pointerdown","keydown"];function Ac(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 p of Rc)e.removeEventListener?.(p,l,{capture:true});e.removeEventListener?.("gamepadconnected",g,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(p){p?.isTrusted===true&&a();}let d=()=>{let p;try{p=e.navigator?.getGamepads?.()??[];}catch{return false}return p.some(f=>f?.buttons.some(y=>y.pressed)===true)},u=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(p=>p!==null)}catch{return false}},c=()=>{if(o=null,!(n||r)){if(d()){a();return}u()&&(o=e.requestAnimationFrame?.(c)??null);}};function g(){o===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let p of Rc)e.addEventListener(p,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",g,{capture:true,passive:true}),u()&&(o=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:s}}async function oo(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function Zi(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function ea(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 ta=new WeakMap,xc=new WeakSet,na=new Set,io=new Set,ao=[],$t=null,ra=false,xy=1920;function oa(t){return ta.get(t)}function ia(t){return !ra||xc.has(t)}function aa(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function Pc(t=globalThis.window){if(ra||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;ra=true;for(let i of Array.from(t.document?.querySelectorAll("canvas")??[]))xc.add(i);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(i,...s){let a=n.call(this,i,...s);if(a&&!ta.has(this)){let l={kind:i,context:a};ta.set(this,l),aa(l)&&na.add(this);}return a};let r=t.requestAnimationFrame,o=t.cancelAnimationFrame;t.requestAnimationFrame=i=>{let s=r.call(t,a=>{io.delete(s);try{i(a);}finally{Py();}});return io.add(s),Ic(),s},t.cancelAnimationFrame=i=>{io.delete(i),o.call(t,i);};}function Tc(t,e){return new Promise(n=>{let r={canvas:t,done:i=>{clearTimeout(o),ao=ao.filter(s=>s!==r),n(i);}},o=setTimeout(()=>r.done(null),e);ao.push(r);})}function Ec(t){return $t?.canvas===t?$t.bitmap:null}function Py(){for(let t of ao){let e;try{e=sa(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}io.size===0&&Ty();}function Ty(){let t=null;for(let r of na)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):na.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,xy/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"}:{};Ic(),$t={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function Ic(){$t&&($t.bitmap.then(t=>t?.close()),$t=null);}function sa(t){let e=Ey();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 En;function Ey(){if(En!==void 0)return En;if(typeof OffscreenCanvas=="function")En=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),En=t?.getContext("2d",{willReadFrequently:true})??null;}return En??null}var la=false;async function Gc(t,e,n,r){if(la){e.close(),n("busy",true);return}la=true;let o=null;try{let i=await My(t,r);if(typeof i=="string"){e.close(),n(i,Iy(i));return}o=i;let a=await(r.encodeRef??(l=>$y(l,r)))(o);if(o.close(),o=null,a===null){e.close(),n("failed",!0);return}if(a.size>Dy){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{la=false,o?.close();}}function Iy(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 Cy=600;async function My(t,e){if(e.handler){let o=await e.handler(t);return o===null?"declined":Cc(o,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Ly(n);if(!r)return "no_source";try{let o=await Oy(r);return typeof o=="string"?o:Cc(o,t)}catch(o){if(o instanceof DOMException&&o.name==="SecurityError")return "tainted";throw o}}async function Oy(t){let e=Gy(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!aa(e))return createImageBitmap(t);let n=await Tc(t,Cy);if(n)return n;let r=await Ec(t);return r&&sa(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function Gy(t){let e=oa(t);if(e)return e;if(!ia(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 Ly(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||!oa(r)&&!ia(r)||o>n&&(e=r,n=o);}return e}async function Cc(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 Dy=8*1024*1024,Mc="image/webp",Oc=.92;async function $y(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:Mc,quality:Oc});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),Mc,Oc);})}async function Lc(t,e){if(!e)return;let n;try{n=await Fy(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 Fy(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 Dc=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Fc(t=globalThis){let n=t[Dc];if(n!==void 0)return n;let r=false,o=()=>r,i=jy(t),s=[],a=qy(t,o,i.watch);a!==null&&s.push(a);let l=Ny(t,o,i.watch);l!==null&&s.push(l);let d={get muted(){return r},setMuted(u){let c=!!u;if(c!==r){r=c;for(let g of s)g();}},setPaused(u){i.setPaused(!!u);}};return Object.defineProperty(t,Dc,{value:d,configurable:true}),d}function qy(t,e,n){let r=t.AudioNode?.prototype,o=t.AudioDestinationNode;if(r===void 0||o===void 0)return null;let i=t.OfflineAudioContext,s=r.connect,a=r.disconnect,l=new Map,d=c=>{let g=c.gain,p=c.context.currentTime;g.cancelScheduledValues(p),e()?g.setValueAtTime(0,p):g.setTargetAtTime(1,p,.01);},u=c=>{let g=c.context;if(i!==void 0&&g instanceof i)return null;let p=l.get(g);return p===void 0&&(p=g.createGain(),p.gain.value=e()?0:1,s.call(p,c),l.set(g,p),n.context(g)),p};return r.connect=function(...g){let[p,...f]=g;if(p instanceof o){let y;try{y=u(p);}catch{y=null;}if(y!==null)return s.call(this,y,...f),p}return s.apply(this,g)},r.disconnect=function(...g){let[p,...f]=g;if(p instanceof o){let y=l.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...f)}catch{}}return a.apply(this,g)},()=>{for(let[c,g]of l){if(c.state==="closed"){l.delete(c);continue}try{d(g);}catch{}}}}function Ny(t,e,n){let r=t.HTMLMediaElement;if(r===void 0)return null;let o=r.prototype,i=Object.getOwnPropertyDescriptor(o,"muted"),s=i?.get,a=i?.set;if(s===void 0||a===void 0)return null;let l=o.play,d=new WeakMap,u=new WeakSet,c=new Set,g=p=>{d.has(p)||d.set(p,!!s.call(p)),u.has(p)||(u.add(p),c.add(new WeakRef(p)),n.element(p)),a.call(p,(d.get(p)??false)||e());};return Object.defineProperty(o,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let p=d.get(this);return p===void 0?!!s.call(this):p},set(p){d.set(this,!!p),g(this);}}),o.play=function(){try{g(this);}catch{}return l.call(this)},t.document?.addEventListener("play",p=>{let f=p.target;if(f instanceof r)try{g(f);}catch{}},true),()=>{for(let p of c){let f=p.deref();if(f===void 0){c.delete(p);continue}try{a.call(f,(d.get(f)??!1)||e());}catch{}}}}var $c=["pointerup","touchend","click","keydown"];function jy(t){let e=t.document,n=new Set,r=new WeakSet,o=new WeakSet,i=new Set,s=new Set,a=false,l=false,d=t.AudioContext?.prototype,u=d?.suspend,c=d?.resume,g=d!==void 0&&typeof u=="function"&&typeof c=="function";g&&(d.suspend=function(...A){try{o.add(this);}catch{}return u.apply(this,A)},d.resume=function(...A){try{o.delete(this);}catch{}return c.apply(this,A)});let p=t.HTMLMediaElement?.prototype,f=p?.pause;p!==void 0&&typeof f=="function"&&(p.pause=function(){s.delete(this),f.call(this);});let y=x=>x.state!=="running"&&x.state!=="closed"&&r.has(x)&&!o.has(x),R=x=>x.paused&&!x.ended,k=()=>{for(let x of n)if(x.state==="closed")n.delete(x);else if(y(x))return true;for(let x of s){if(R(x))return true;s.delete(x);}return false},P=()=>{for(let x of i){let A=x.deref();if(A===void 0){i.delete(x);continue}try{!A.paused&&!A.ended&&s.add(A);}catch{}}},h=()=>{if(l){l=false,s.clear();for(let x of $c)e?.removeEventListener?.(x,C,true);}},S=()=>{try{l&&!k()&&h();}catch{}};function C(){if(!l||a)return;let x=[];try{for(let A of n){if(A.state==="closed"){n.delete(A);continue}if(y(A))try{x.push(Promise.resolve(c?.call(A)));}catch{}}for(let A of s){if(!R(A)){s.delete(A);continue}try{x.push(Promise.resolve(A.play()).then(()=>s.delete(A),O=>{O?.name!=="NotAllowedError"&&s.delete(A);}));}catch{s.delete(A);}}}catch{}if(x.length===0){S();return}Promise.allSettled(x).then(S);}let I=()=>{if(!(l||e===void 0)){l=true;for(let x of $c)e.addEventListener(x,C,true);}},U=()=>{P(),e?.visibilityState!=="hidden"&&I();};try{e?.addEventListener("visibilitychange",()=>{try{e.visibilityState==="hidden"?P():I();}catch{}},!0),t.addEventListener?.("pagehide",()=>{try{P();}catch{}}),t.addEventListener?.("pageshow",x=>{try{x.persisted&&I();}catch{}});}catch{}return {watch:{context(x){if(g)try{n.add(x),x.state==="running"&&r.add(x),x.addEventListener("statechange",()=>{try{let A=x.state;A==="running"?(r.add(x),S()):A!=="closed"&&r.has(x)&&!o.has(x)&&U();}catch{}});}catch{}},element(x){try{i.add(new WeakRef(x));}catch{}}},setPaused(x){a=x;}}}var By=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Uy=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Wy=`${By}${Uy}`,da=new WeakSet;function qc(t=globalThis.document){if(t==null||da.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(Wy),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],da.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"),da.add(t),"inline")}catch{return null}}function Nc(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,u=[],c=false,g=0,p=null,f=[],y=()=>o&&!i&&!s,R=()=>{l=null,d=null,u=[],g=0,p=null,f=[];},k=S=>{if(a=null,!y()){R();return}if(d!==null&&u.push(S-d),d=S,l===null)l=S;else {let C=S-l;if(C>=e&&u.length>0){if(c){let I=p===null?C:r()-p;t.report(Vy(g,f,C,I));}else t.report(Hy(u,C));l=S,u=[],g=0,f=[];}}P();},P=()=>{let S=n.requestAnimationFrame;typeof S=="function"&&(a=S.call(n,k));},h=()=>{if(y()){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();p!==null&&f.length<1e3&&f.push(S-p),p=S,g+=1;},get running(){return a!==null},dispose(){s=true,h();}}}function Hy(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:jc(t),counts:"pageFrames"}}function Vy(t,e,n,r){let o=r;return e.length>0&&(o=jc(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:o,counts:"gameDraws"}}function jc(t){let e=[...t].sort((r,o)=>r-o),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var so=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 Uc(t,e){t!==null&&(t.style.setProperty(so.top,`${e.top}px`),t.style.setProperty(so.right,`${e.right}px`),t.style.setProperty(so.bottom,`${e.bottom}px`),t.style.setProperty(so.left,`${e.left}px`));}var lo=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 Wc(){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 Ky(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 u=l.control;l.control=u?{top:Math.min(u.top,d.y),bottom:Math.max(u.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Hc(t,e,n){if(t===null)return;let r=Ky(e,n);for(let o of ["tl","tr","bl","br"]){t.style.setProperty(lo[o].width,`${r[o].width}px`),t.style.setProperty(lo[o].height,`${r[o].height}px`);let i=r[o].control;t.style.setProperty(lo[o].centerY,i?`${(i.top+i.bottom)/2}px`:""),t.style.setProperty(lo[o].controlHeight,i?`${i.bottom-i.top}px`:"");}}var Jy=3e4,co=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Vc(t){let e=t.clock??de,n=t.timeoutMs??Jy,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((u,c)=>{let g=`ls${++i}`,p=e.setTimeout(()=>{r.delete(g),o.delete(a),c(new co("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(g,{room:a,resolve:u,reject:c,timer:p}),t.bridge.requestLocalServer(g,a)||(s(g),u());});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 co(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 In={url:"https://downloads.indiegems.games/sdk/v19.0.2/gem-web-sdk.devtools.min.js",integrity:"sha384-9Hg1Oh4BGuV2VvOsKGVzNW6V1jES5pXMNeUqNO4KR82+LaVRqkLr/4PJ2nqSb/kJ"};var Ft=null;function zy(){return Ft!==null||(Ft=new Promise((t,e)=>{let n=document.createElement("script");n.src=In.url,n.integrity=In.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Ft=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${In.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Ft=null,e(new Error(`gem devtools: could not load ${In.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);})),Ft}function Kc(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 zy();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:i,text:it,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 Xy=1e4,Jc={reason:"unavailable",retryable:false};function zc(t){let e=new Map,n=null,r=null,o=0,i=(d,u)=>{u.timer=t.clock.setTimeout(()=>{e.delete(d),u.reject({reason:"timeout",retryable:true});},t.timeoutMs??Xy);},s=(d,u)=>{let c=a(d);c&&u(c);},a=d=>{let u=e.get(d);return u?(e.delete(d),t.clock.clearTimeout(u.timer),u):null},l=new wt({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((u,c)=>{let g=t.bridge.currentState;if(g==="refused"||g==="closed"){c(Jc);return}let p=`t${++o}`,f={resolve:u,reject:c,reason:d,timer:null,held:g!=="connected"};e.set(p,f),i(p,f),f.held||t.bridge.requestToken(p,d);})});return {source:l,onToken(d){let u={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(u));return}l.accept(u);},onDenied(d){s(d.requestId,u=>u.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[u,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),i(u,c),t.bridge.requestToken(u,c.reason));else if(d==="refused"||d==="closed")for(let u of [...e.keys()])s(u,c=>c.reject(Jc));},get identity(){return n},get gameVersion(){return r}}}var Yy=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),ua="embedder_relay_unavailable",Qy="embedder_no_relay",Zy=new Set([ua]),ma=new Set([Qy]),Cn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new ca(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(eh(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 eh(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new w(th(t),r,{platformCode:t})}function th(t){return t===void 0||Zy.has(t)?"signaling_failed":ma.has(t)?"offer_refused":Yy.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var ca=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:",Yc="server_shutdown:",Qc="kicked:",nh=123;function rh(t){if(typeof t!="string"||t.length===0||t.length>nh)return {kind:"other"};if(t.startsWith(Xc)){let e=Ye(t.slice(Xc.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Yc)?{kind:"server_shutdown",cause:t.slice(Yc.length)}:t.startsWith(Qc)?{kind:"kicked",detail:t.slice(Qc.length)}:{kind:"other"}}function pa(t,e,n){let r=rh(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 ga(){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 oh=3e3,ih=1e4,ah=15e3;async function uo(t){let e=t.peerConnection;try{eu(t,"before the handshake started"),fa(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 dh(e,t),fa(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new w("invalid_sdp","the offer carried no SDP");Qe(o,"offer"),Zc(o,"offer");let i=await lh(t,o);if(fa(t),typeof i?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return Qe(i.sdp,"answer"),Zc(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await ch(n,t),eu(t,"before the channel opened"),n}catch(n){throw e.close(),sh(n)}}function sh(t){return t instanceof w?t:ru(t)?pt():new w("connection_failed",ou(t),{cause:t})}function Zc(t,e){if(eo(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 lh(t,e){let n=t.exchangeTimeoutMs??ih,r=nu(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof w?i:ru(i)?pt():new w("signaling_failed",ou(i),{cause:i})});return uh(o,t,r,()=>r.exhausted?ya("while the offer was in flight"):new w("timeout",`no answer arrived within ${n}ms`))}function dh(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??oh);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function ch(t,e){if(e.signal?.aborted)return Promise.reject(pt());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??ah,o=nu(e,r);return new Promise((i,s)=>{let a=()=>{n.clearTimeout(g),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",u);},l=()=>{a(),i();},d=p=>{a(),s(new w("connection_failed","the data channel failed before it opened",tu(p)===void 0?void 0:{cause:tu(p)}));},u=()=>{a(),s(pt());},c=()=>{a(),s(o.exhausted?ya("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},g=n.setTimeout(c,o.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",u);})}function nu(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 uh(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(pt()):new Promise((s,a)=>{let l=c=>{o.clearTimeout(u),i?.removeEventListener("abort",d),c();},d=()=>l(()=>a(pt())),u=o.setTimeout(()=>l(()=>a(r())),n.ms);i?.addEventListener("abort",d),t.then(c=>l(()=>s(c)),c=>l(()=>a(c)));})}function eu(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw ya(`already ${e}`)}function ya(t){return new w("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function fa(t){if(t.signal?.aborted)throw pt()}function pt(){return new w("aborted","the caller aborted the connection attempt")}function ru(t){return t?.name==="AbortError"}function tu(t){return t?.error}function ou(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 mu(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??ga,i=t.log??(h=>console.warn(h)),s=new Ot({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,S)=>{let C=a.get(h)??new Set;C.add(S),a.set(h,C);},d=(h,S)=>{let C=a.get(h);C!==void 0&&(C.delete(S),C.size===0&&a.delete(h));},u=async h=>{if(r.isHost&&!ba(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 cu(r.matchConnectionState==="suspended"?await r.reconnectToMatch(ha(h)):await r.awaitMatch(ha(h)))},c=async h=>cu(await r.pollMatchStatus(ha(h))),g=async(h,S)=>{let C=false;try{let I=await u(h),U=r.currentRoom?.transports;if(U!==void 0&&!U.includes("webrtc"))throw new w("misconfigured",`the room template offers (${U.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??uu();C=!0;let x=await uo({peerConnection:q,signaling:S,clock:n,matchId:I.matchId,credentialExpiresAt:I.credentialExpiresAt,...mo(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),A=null;if(h.presentCredential!==!1)try{A=await pn({channel:x,clock:n,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,...mo(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(O){throw Te(x),Te(q),O}return _h(r,I,x,q,S,h.reportDisconnect!==!1,h.reportConnected!==!1,A,{remember:l,forget:d},h.onMatchEnded)}catch(I){throw C&&du(s,I),Te(S),I}},p=async(h,S,C,I,U,q)=>{if(h==="webtransport"){let W=I?.webtransport;if(W===void 0)throw new w("misconfigured","webtransport is not advertised");let J={credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:n};if(typeof W.named_url=="string"&&W.named_url!==""){let ie=Math.max(Math.floor(q/2),1e3);try{return await hn({url:W.named_url,timeoutMs:ie,log:i,...J})}catch(ge){if(Vr()!==null)throw ge;return i(`[gem] webtransport named dial failed (${Wr(ge)}); retrying the pinned dial`),hn({url:W.url,certHashBase64:W.cert_sha256_b64,timeoutMs:ie,log:i,...J})}}return hn({url:W.url,certHashBase64:W.cert_sha256_b64,timeoutMs:q,...J})}if(h==="websocket"){let W=I?.websocket;if(W===void 0)throw new w("misconfigured","websocket is not advertised");return Mi({url:W.url,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:n,timeoutMs:q})}let x=S.peerConnection??uu(),A,O=await uo({peerConnection:x,signaling:U,clock:n,matchId:C.matchId,credentialExpiresAt:C.credentialExpiresAt,extraChannels:[{label:fn,ordered:false,maxRetransmits:0}],onExtraChannel:(W,J)=>{W===fn&&(A=J);},...mo(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:gh}:{}}),F;try{F=await pn({channel:O,clock:n,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,wire:Ur,heartbeat:!0,...mo(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(W){throw Te(O),Te(x),W}let B=F.welcome.heartbeatIntervalMs;return {link:Gi(O,x,A,B===void 0?void 0:{clock:n,intervalMs:B}),welcome:F.welcome,channel:O,peerConnection:x}},f=(h,S,C,I,U)=>{let q=false,x;I.link.onClose(B=>{!q&&h.reportDisconnect!==false&&pa(r,S.matchId,B),x?.(B);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let A={transport:I.link.transport,send:(B,W)=>I.link.send(B,W),onMessage:B=>I.link.onMessage(B),onClose:B=>{x=B;},close:()=>I.link.close()},O=()=>{q||(q=true,Te(I.link),Te(U));},F=B=>{if(!q){try{h.onMatchEnded?.(B);}catch{}O();}};return l(S.matchId,F),{matchId:S.matchId,transport:C,link:A,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:I.welcome,...I.channel===void 0?{}:{channel:I.channel},...I.peerConnection===void 0?{}:{peerConnection:I.peerConnection},close(){d(S.matchId,F),O();}}},y=async(h,S)=>{let C=r.currentRoom?.id,I=r.gameId,U=()=>({advert:yn(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(C===void 0||I===null)return U();try{let q=await e.get(`/v2/games/${encodeURIComponent(I)}/game-rooms/${encodeURIComponent(C)}`,S);return {advert:yn(q.settings,h),template:Ct(q.transports)??r.currentRoom?.transports??null}}catch{return U()}},R=(h,S)=>{let C=h??iu;return S.length===0?C:C.filter(I=>S.includes(I))},k=async(h,S,C)=>{try{let I=await u(h),{advert:U,template:q}=await y(I.matchId,h.signal),x=R(q,S),A=x.filter(X=>hh(X,U)),O=Vr();if(O!==null&&x.includes("webtransport")&&U?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${O} (learned on an earlier dial in this page)`),A.length===0){let X=q===null?`the default order (${iu.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??ph,B=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-n.now(),W=X=>t.signalingReady===void 0||X<=0?Promise.resolve(!0):t.signalingReady(X),J=[],ie=[];for(let X of A){if(B()<su){i(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}ie.length>0&&I.credentialExpiresAt-n.now()<lu&&(I=await c(h)),ie.push(X);let Be=!1,Se=!1,fe={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&h.redial===!0){let te=Math.min(au,B());await W(te)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let Ue=Math.max(Math.min(F,B()),su);try{return f(h,I,X,await p(X,h,I,U,C,Ue),C)}catch(te){let z=te instanceof w?te:new w("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(X==="webrtc"&&du(s,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Be){Be=!0,I=await c(h);continue}if(X==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===ua&&!Se){Se=!0;let le=Math.min(au,B());if(i(`[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 W(le))continue}if(z.reason==="join_rate_limited"){let le=yh(fe,Math.random,B());if(le!==null){if(fe.attempts+=1,fe.waitedMs+=le,i(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(le)}ms before presenting again (retry ${fe.attempts} of ${gu.maxAttempts})`),await qr(n,le,h.signal),h.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");I.credentialExpiresAt-n.now()<lu&&(I=await c(h));continue}}if(fh.has(z.reason)||z.reason==="credential_expired"||X==="webrtc"&&pu(z)){i(`[gem] ${X} rung failed (${z.reason}): ${Wr(z.cause??z)} \u2014 `+(ie.length<A.length?`falling through to ${A[ie.length]}`:"no rungs left")),J.push(z);break}throw i(`[gem] ${X} rung refused the session (${z.reason}): ${z.message}`),z}}}let ge=J[J.length-1];throw ge===void 0?new w("timeout",`the reconnect budget ran out before any transport (${A.join(", ")}) could be tried`):new w(ge.reason,`every transport tried (${ie.join(", ")}) failed; the last said: ${ge.message}`,{cause:J,platformCode:ge.platformCode})}catch(I){throw Te(C),I}};return {listClusterTargets:async(h={})=>hi({client:e,...h}),handleMatchEnded(h,S){let C=a.get(h);if(C!==void 0){a.delete(h);for(let I of C)I(S);}},connect:(async(h={})=>{let S=h.signaling??o();return h.transports===void 0?g(h,S):k(h,h.transports,S)})}}var iu=["webtransport","webrtc","websocket"],ph=1e4,gh=5e3,au=3e3,su=1e3,lu=1e4,fh=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function pu(t){return t.platformCode!==void 0&&ma.has(t.platformCode)}var gu={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function yh(t,e=Math.random,n=1/0){let r=gu;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 hh(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Hr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||bh(e.websocket.url)}function bh(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return Je(e)}function ha(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var vh=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function du(t,e){e instanceof w&&(!vh.has(e.reason)&&!pu(e)||t.report([{type:"connection_failures_total",value:1}]));}function _h(t,e,n,r,o,i,s,a,l,d){let u=false,c=()=>{u||pa(t,e.matchId,void 0);};i&&(n.addEventListener("close",c),s&&t.notifyMatchConnected(e.matchId));let g=()=>{u||(u=true,n.removeEventListener("close",c),a?.detach(),Te(n),Te(r),Te(o));},p=f=>{if(!u){try{d?.(f);}catch{}g();}};return l.remember(e.matchId,p),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,p),g();}}}function ba(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function cu(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!==Fr)throw new w("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Fr}' 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 uu(){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 mo(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var wh=1e4;function fu(t,e){return va(t,e)}function va(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 wt({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??wh);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 wa={};zm(wa,{acceptTransfer:()=>Sh,addEntityProgression:()=>kh,adminAction:()=>Rh,cancelInventoryTransfer:()=>Ah,claimEntityProgressionRewards:()=>xh,closeGameRoom:()=>Ph,createEntityBatchOrder:()=>Th,createEntityOrder:()=>Eh,createSession:()=>Ih,deleteEntityGameSetting:()=>Ch,deleteEntitySave:()=>Mh,deleteSession:()=>Oh,deleteShowcaseValue:()=>Gh,executeEntityRecipe:()=>Lh,finalizeSaveUpload:()=>Dh,getChannelAssignment:()=>$h,getDropRates:()=>Fh,getEntityCurrency:()=>qh,getEntityGameSetting:()=>Nh,getEntityInventory:()=>jh,getEntityInventoryItem:()=>Bh,getEntityLeaderboard:()=>Uh,getEntityOrder:()=>Wh,getEntityProgression:()=>Hh,getEntityRecipeAvailability:()=>Vh,getEntityRecipeUsage:()=>Kh,getEntitySave:()=>Jh,getEvent:()=>zh,getGameRoomV2:()=>Xh,getLeaderboard:()=>Yh,getPlayerGameProfile:()=>Qh,getPurchaseCatalog:()=>Zh,getResolvedTemplate:()=>eb,getRoomArgs:()=>tb,getShowcaseValue:()=>nb,getTransferDetails:()=>rb,ingestAnalyticsEvents:()=>_a,initiateInventoryTransfer:()=>ob,invokeFunction:()=>ib,kickPlayer:()=>ab,listChallenges:()=>sb,listEntityGameSettings:()=>lb,listEntityOrders:()=>db,listEntityProgressions:()=>cb,listEntitySaves:()=>ub,listEvents:()=>mb,listGameRooms:()=>pb,listResolvedTemplates:()=>gb,listTransfers:()=>fb,maxEntityProgression:()=>yb,putEntityGameSetting:()=>hb,putRoomArgs:()=>bb,putShowcaseValue:()=>vb,rejectTransfer:()=>_b,reportMatchPlayers:()=>wb,requestSaveUploadUrl:()=>Sb,resetEntityProgression:()=>kb,setMatchBackfill:()=>Rb,simulateEntityOrder:()=>Ab,transferHostV2:()=>xb,updateGameRoomV2:()=>Pb});function v(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 Sh(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function kh(t,e,n,r,o,i){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/add`;return t.client.post(s,o,i?.signal)}async function Rh(t,e,n,r){let o=`/v1/voice/sessions/${v(e)}/admin`;return t.client.post(o,n,r?.signal)}async function Ah(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function xh(t,e,n,r,o,i){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/claim`;return t.client.post(s,o,i?.signal)}async function Ph(t,e,n){let r=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.delete(r,n?.signal)}async function Th(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Eh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ih(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Ch(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Mh(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Oh(t,e,n){let r=`/v1/voice/sessions/${v(e)}`;return t.client.delete(r,n?.signal)}async function Gh(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(o,r?.signal)}async function Lh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Dh(t,e,n,r,o,i){let s=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/finalize`;return t.client.post(s,o,i?.signal)}async function $h(t,e,n){let r=`/v1/games/${v(t.gameId())}/config/channels/${v(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Fh(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function qh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/currencies/${v(r)}`;return t.client.get(i,o?.signal)}async function Nh(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function jh(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/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Bh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/items/${v(r)}`;return t.client.get(i,o?.signal)}async function Uh(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/${v(e)}/${v(n)}/${v(r)}`+(s?`?${s}`:"");return t.client.get(a,o?.signal)}async function Wh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/${v(r)}`;return t.client.get(i,o?.signal)}async function Hh(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}`;return t.client.get(i,o?.signal)}async function Vh(t,e,n,r,o,i){let s=`/v1/inventory/${v(e)}/${v(n)}/catalogs/${v(r)}/recipes/${v(o)}/availability`;return t.client.get(s,i?.signal)}async function Kh(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/${v(e)}/${v(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Jh(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function zh(t,e,n){let r=`/v1/events/${v(e)}`;return t.client.get(r,n?.signal)}async function Xh(t,e,n){let r=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Yh(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/${v(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Qh(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function Zh(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 eb(t,e,n){let r=`/v1/game-room-templates/${v(e)}`;return t.client.get(r,n?.signal)}async function tb(t,e,n){let r=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/room-args`;return t.client.get(r,n?.signal)}async function nb(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function rb(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function _a(t,e,n){let r=`/v1/games/${v(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function ob(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ib(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function ab(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/kick/${v(n)}`;return t.client.post(o,void 0,r?.signal)}async function sb(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 lb(t,e,n,r){let o=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function db(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/${v(e)}/${v(n)}/orders`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function cb(t,e,n,r){let o=`/v1/inventory/${v(e)}/${v(n)}/progressions`;return t.client.get(o,r?.signal)}async function ub(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/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function mb(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 pb(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/${v(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function gb(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function fb(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 yb(t,e,n,r,o,i){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/max`;return t.client.post(s,o,i?.signal)}async function hb(t,e,n,r,o,i){let s=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.put(s,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function bb(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/room-args`;return t.client.put(o,n,r?.signal)}async function vb(t,e,n,r,o){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(i,r,o?.signal)}async function _b(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function wb(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/matches/${v(e)}/players/report`;return t.client.post(o,n,r?.signal)}async function Sb(t,e,n,r,o,i){let s=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/upload-url`;return t.client.post(s,o,i?.signal,{replaySafe:true})}async function kb(t,e,n,r,o,i){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/reset`;return t.client.post(s,o,i?.signal)}async function Rb(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/matches/${v(e)}/backfill`;return t.client.put(o,n,r?.signal)}async function Ab(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/simulate`;return t.client.post(i,r,o?.signal)}async function xb(t,e,n,r){let o=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}/transfer/${v(n)}`;return t.client.post(o,void 0,r?.signal)}async function Pb(t,e,n,r){let o=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.patch(o,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Tb=1e4,Eb=50,Ib=1e3,Cb=65536-4*1024,yu=t=>typeof t=="number"?t:0,Mb=t=>typeof t=="string"?t:"";function hu(){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 Ob(t){return t?.retryable===true}function Gb(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:yu(i.index),code:Mb(i.code)}}):[];return {accepted:yu(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function bu(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 vu(t){let e=Math.max(1,Math.floor(t.maxQueue??Ib)),n={client:t.client,gameId:()=>t.gameId},r=[],o=0,i=null,s=false,a=null,l=0,d=0,u=false,c=false,g=h=>{t.log?.(h);},p=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},f=()=>Math.max(0,d-t.clock.now()),y=()=>{i!==null||s||a!==null||(i=t.clock.setTimeout(()=>{i=null,k().catch(()=>{});},Math.max(Tb,f())));},R=()=>{let h=Math.min(r.length,100),S=128;for(let C=0;C<h;C+=1){let I=r[C];if(I===void 0)break;if(S+=JSON.stringify(bu(I,0)).length+1,S>Cb)return Math.max(1,C)}return h};async function k(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&&y();}}async function P(h){p();let S=r.splice(0,R()),C=o;o=0;let I=Math.round(t.clock.now()),U={batch_id:hu(),sent_at_ms:I,events:S.map(q=>bu(q,I))};try{let q=await _a(n,U,h===void 0?void 0:{signal:h}),x=Gb(q,C);l=0,d=0;for(let A of x.rejected)g(`[gem] analytics: an event was refused (${A.code}). See the analytics_events section of your game config.`);return x}catch(q){if(Ob(q)){for(r=[...S,...r],o+=C;r.length>e;)r.shift(),o+=1;l+=1,d=t.clock.now()+Lr(l,q);}else g(`[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,C={}){if(s)return;if(typeof h!="string"||h===""){c||(c=true,g(`[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(ai)){u||(u=true,g(`[gem] analytics: '${S}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let I={},U={};for(let[q,x]of Object.entries(C))typeof x=="string"?I[q]=x:typeof x=="number"&&Number.isFinite(x)&&(U[q]=x);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:hu(),playerId:h,name:S,atMs:t.clock.now(),dimensions:I,measures:U}),r.length>=Eb&&a===null&&f()===0?k().catch(()=>{}):y();},flush:h=>k(h),get pending(){return r.length},dispose(){s=true,p(),r=[],o=0;}}}function _u(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().");Pt(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return Er(i)}}}function Lb(t){let e={};for(let[n,r]of Object.entries(wa))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function qt(t,e={}){let n=e.clock??de,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=va(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=br({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new He({transport:i,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=Lb({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,u=t.endMatch,c=t.log,g=vu({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(u===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 u.call(t);},setBackfill:async(f,y)=>{let R=await l.setMatchBackfill(a.matchId,{open:f.open,...f.seats===void 0?{}:{seats:f.seats}},y===void 0?{}:{signal:y});return {open:R.open,seats:R.seats??null}},reportPlayers:async(f,y)=>(await l.reportMatchPlayers(a.matchId,{players:f.map(k=>({player_id:k.playerId,state:k.state}))},y===void 0?{}:{signal:y})).players.map(k=>({playerId:k.player_id,outcome:k.outcome}))},analytics:g,functions:new Xe(l.invokeFunction),challenges:_u(l.listChallenges),...d===void 0?{}:{room:{get:f=>l.getGameRoomV2(d,f),args:async f=>{let y=await l.getGameRoomV2(d,f?.signal===void 0?{}:{signal:f.signal}),R=y.modified?y.body:void 0;if(R?.room_args==null||R.room_args_template==null)throw new G("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:()=>{g.dispose(),o.dispose();}}}function gt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Nt(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function Mn(t){return typeof t=="string"?t:t.slice().buffer}function po(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 Db=5e3,wu=3e4,Su=2e3,$b=1e4,Fb=3,ku=1;async function Ru(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?b=>console.info(b):e.log,i=b=>o?.(`[gem host] ${b}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,u=(b,M)=>{l&&(a=a.then(async()=>{if(!d)try{await M();}catch(N){i(`the bundle's ${b} handler threw: ${ft(N)}. Serving continues.`);}}));},c=true,g,p,f,y=b=>{if(!c)return;c=false,u("leave",()=>s.leave?.(r,{cause:b??"left"}));let M=p;M&&queueMicrotask(()=>M(b));},R={send(b,M){if(!c)return;let N=Nt(gt(M));u("message",()=>s.message?.(r,b,typeof b=="string",{reliable:N.reliable,ordered:N.ordered}));},onMessage(b){g=b;},onClose(b){p=b;},close(){y("closed");}},k=(b,M)=>{if(!c)return;let N=Nt(gt(M));queueMicrotask(()=>{c&&g?.(b,N);});},P=new Map,h=b=>{let M=[];for(let N of je){let Z=b.channels[N];try{Z.binaryType="arraybuffer";}catch{}let ke=Nt(N),Fe=Wt=>{let bt=po(Wt?.data);bt!==null&&u("message",()=>s.message?.(b.playerId,bt.data,bt.isText,{reliable:ke.reliable,ordered:ke.ordered}));};Z.addEventListener("message",Fe),M.push(()=>Z.removeEventListener("message",Fe));}P.get(b.playerId)?.forEach(N=>N()),P.set(b.playerId,M);},S=b=>{P.get(b)?.forEach(M=>M()),P.delete(b);},C=new Set,I=new Map,U=(b,M,N)=>({playerNumber:b.assignedPeerId,transport:"webrtc_p2p",...M?{rejoin:true}:{},...N?{superseded:true}:{}}),q=b=>{let M=P.has(b.playerId),N=C.has(b.playerId);C.add(b.playerId),h(b),M&&u("leave",()=>s.leave?.(b.playerId,{cause:"superseded"})),u("join",()=>s.join?.(b.playerId,U(b,N,M)));},x=new Set,A=(b,M,N)=>{if(b===r){k(M,N);return}let Z=n.peer(b);if(Z===null){let ke=I.get(b);if(ke!==void 0&&e.clock.now()-ke<Su)return;x.has(b)||(x.add(b),i(`send to '${b}' dropped: no such connected player`));return}Z.send(Mn(M),gt(N));},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:b=>e.tokens.subscribe(b),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(b=>b.playerId)??[],players(){let b=c?[r]:[];for(let M of n.peers)b.push(M.playerId);return b},profile(b){let M=e.room()?.members.find(N=>N.playerId===b);if(!(!M||M.displayName===void 0))return {displayName:it.toPlain(M.displayName),...M.displayTag===void 0?{}:{displayTag:it.toPlain(M.displayTag)},...M.discriminator===void 0?{}:{discriminator:M.discriminator}}},playerNumber(b){return b===r?ku:n.peer(b)?.assignedPeerId},send(b,M,N){A(b,M,N);},broadcast(b,M){let N=M?.except;c&&r!==N&&k(b,M);for(let Z of n.peers)Z.playerId!==N&&Z.send(Mn(b),gt(M));},async endMatch(){let b=await Ue();return b.answer!=="ok"&&i(b.cause),b.answer},kick(b,M){if(b===r){y(M??"kicked");return}n.kick(b).catch(N=>{i(`kick of '${b}' failed: ${ft(N)}`);});},log(b){i(b);},warn(b){i(`\u26A0 ${b}`);}},F=()=>{},B=new Promise(b=>{F=b;}),W=[],J=null,ie=async(b,M)=>{l=false;let N=a.then(async()=>{try{await s.shutdown(b);}catch(Z){i(`the bundle's shutdown threw: ${ft(Z)}`);}});a=N,await N,De();for(let Z of W.splice(0))Z();for(let Z of [...P.keys()])S(Z);y(M);},ge=(b,M)=>J||(J=(async()=>{await ie(M,b),n.close(),F();})(),J),X=()=>J||(J=(async()=>{await ie({reason:"signal"},"left"),await n.leave().catch(b=>i(`leaving the match failed: ${ft(b)}`)),F();})(),J),Be=()=>J||(J=(async()=>{l=false;let b=await Ue();b.answer==="ok"?(await ie({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${b.cause}; leaving instead`),await ie({reason:"signal"},"left"),await n.leave().catch(M=>i(`leaving the match failed: ${ft(M)}`))),F();})(),J),Se=null,fe=()=>(Se??=qt(O,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Se),Ue=async()=>{try{return await fl({client:fe().client,gameId:()=>O.gameId},O.matchId,{},{signal:AbortSignal.timeout(Db)}),{answer:"ok"}}catch(b){return b instanceof G&&(b.reason==="forbidden"||b.reason==="not_found")?{answer:b.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${b.reason})`}:{answer:"failed",cause:`ending the match failed: ${ft(b)}`}}},te=null,z=false,le=0,xe,Le=null,De=()=>{z=true,te!==null&&(e.clock.clearTimeout(te),te=null),Le?.(),Le=null;},jn=b=>{i(`heartbeats paused: ${b}; they resume when a fresh play token arrives`),Bt();let M=xe,N=false,Z=e.tokens.subscribe(ke=>{N||z||ke.token===M||nt(ke)||(N=true,Le?.(),Le=null,le=0,xe=void 0,Bt(),i("a fresh play token arrived; heartbeats resume"),te=e.clock.setTimeout(()=>{We();},0));});N?Z():Le=Z;},Bt=()=>{let b=Se;Se=null,b?.dispose();},nt=b=>b.expiresAt*1e3<=e.clock.now(),We=async()=>{if(te=null,!z){try{await fe().client.post(`/v1/games/${encodeURIComponent(O.gameId)}/matches/${encodeURIComponent(O.matchId)}/heartbeat`,void 0,AbortSignal.timeout($b)),le=0,xe=void 0;}catch(b){if(b instanceof G&&(b.reason==="forbidden"||b.reason==="not_found")){i(`the platform no longer holds this match under this host (${b.reason}); heartbeats stop`),De();return}if(qb(b)){if(z)return;le+=1;let M=e.tokens.current(),N=M===void 0?"this host holds no play token":nt(M)?"this host's play token has expired":M.token===xe?"the platform refused this host's play token again":le>=Fb?`the platform refused this host's play token ${le} times in a row`:null;if(xe=M?.token,N!==null){jn(N);return}}else le=0,xe=void 0;i(`heartbeat failed: ${ft(b)}`);}z||(te=e.clock.setTimeout(()=>{We();},wu));}},$e=()=>{z||te!==null||(te=e.clock.setTimeout(()=>{We();},wu));};{let b=F;F=()=>{De(),Se?.dispose(),Se=null,b();};}let Ut=Promise.resolve().then(()=>s.init(O));a=Ut.then(()=>{},()=>{}),u("join",()=>s.join?.(r,{playerNumber:ku,transport:"loopback"})),W.push(n.on("peerJoined",q)),W.push(n.on("peerLeft",(b,M)=>{S(b);let N=e.clock.now();for(let[Z,ke]of I)N-ke>=Su&&I.delete(Z);I.set(b,N),x.delete(b),u("leave",()=>s.leave?.(b,{cause:M}));})),W.push(n.on("error",b=>{i(`\u26A0 session error: ${b.message}`);})),W.push(n.on("matchEnded",b=>{J||Sa(f,b),ge("match ended",{reason:"match_ended",platform_reason:b});})),W.push(n.on("hostChanged",b=>{b!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let b of n.peers)q(b);try{await Ut,$e();}catch(b){l=false,De(),d=true;for(let M of W.splice(0))M();for(let M of [...P.keys()])S(M);throw n.leave().catch(()=>{}),F(),b}return {matchId:n.matchId,localLink:R,onMatchEnded(b){f=b;},end:Be,leave:X,stop:b=>ge(b,{reason:"stopped"}),done:B}}function Sa(t,e){try{t?.(e);}catch{}}function qb(t){return t instanceof G&&t.status===401||ne.isAuthError(t)}function ft(t){return t instanceof Error?t.message:String(t)}function ka(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 Au(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async a=>{r.isHost&&!ba(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!==mt)return ka("dedicated",d.matchId);let u=t.p2p.session?.(d.matchId)??null;if(u===null&&!r.isHost||u!==null&&!u.isHost)return ka("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 g=u??await t.p2p.connect(s(l)),p=await Ru(a,{session:g,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:g.playerId!==""?g.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return o.set(d.matchId,p),p.done.then(()=>{o.get(d.matchId)===p&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>p.end(),leave:()=>p.leave(),stop:()=>p.stop()}},async connect(a={}){let l=await i(a),d=a.onMatchEnded;if(l.protocol===mt){let p=o.get(l.matchId);if(p!==void 0)return r.notifyMatchConnected(l.matchId),Ub(l.matchId,p,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 Rn(),y=async()=>t.p2p.connect({...s(a),certificate:f}),R=await y(),k=Hb(R,y,d,P=>{r.notifyMatchDisconnected(P).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(R.matchId,{redial:k.redial,abandon:k.abandon}),k.onClosed(()=>{e.get(R.matchId)?.abandon===k.abandon&&e.delete(R.matchId);})),k}let u=async(p=null)=>await t.dedicated.connect({...p===null?{}:{reportConnected:false,redial:true,...p.deadlineAt===void 0?{}:{deadlineAt:p.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 u(),g=Wb(c,u,r,n);return n&&(e.set(c.matchId,{redial:g.redial,abandon:g.abandon}),g.onClosed(()=>{e.get(c.matchId)?.abandon===g.abandon&&e.delete(c.matchId);})),g},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 xu="link_closed",Nb="host_unreachable",jb=new Set(["failed","closed"]);function Bb(t){return jb.has(t)?xu:Nb}function Ub(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 Wb(t,e,n,r){let o=t.matchId,i=t,s="connected",a,l,d=[],u=false,c=false,g=f=>{if(s!=="closed"){s="closed";for(let y of d.splice(0))y();l?.(f);}},p=f=>{f.link.onMessage((y,R)=>a?.(y,R)),f.link.onClose(y=>{if(f!==i||s==="closed")return;if(u||!r){g(y);return}let R=n.matchSession;if(R.phase==="suspended"&&R.matchId===o){s="suspended";return}g(y);});};return p(t),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return s},send(f,y){s==="connected"&&i.link.send(f,y);},onMessage(f){a=f;},onClose(f){l=f;},close(){if(s!=="closed"){if(u=true,s==="suspended"){g("closed");return}i.close(),g("closed");}},async redial(f){if(s==="closed"||u)return "closed";if(c)return "connected";c=true;let y;try{y=await e(f===void 0?{}:{deadlineAt:f});}finally{c=false;}return u||s==="closed"?(y.close(),"closed"):(i=y,p(y),s="connected",n.notifyMatchConnected(o),"connected")},abandon(f){s!=="closed"&&(s==="connected"&&i.close(),g(f));},onClosed(f){s==="closed"?f():d.push(f);}}}function Hb(t,e,n,r,o,i=false){let s=t.matchId,a=t,l,d,u=[],c=[],g=[],p=false,f=false,y=false,R=false,k="connected",P=A=>{if(p)return;p=true,k="closed";for(let F of u.splice(0))F();for(let F of c.splice(0))F();for(let F of g.splice(0))F();let O=d;O&&queueMicrotask(()=>O(A));},h=A=>{for(let O of u.splice(0))O();for(let O of je){let F=A.channels[O];try{F.binaryType="arraybuffer";}catch{}let B=Nt(O),W=J=>{let ie=po(J?.data);ie!==null&&l?.(ie.data,B);};F.addEventListener("message",W),u.push(()=>F.removeEventListener("message",W));}},S=()=>a.peer(a.hostPlayerId),C=A=>{if(!(p||a.isHost)&&k!=="suspended"){if(r?.(A),i){k="suspended";return}P(A);}},I=A=>{for(let O of je){let F=A.channels[O];if(typeof F.addEventListener!="function")continue;let B=()=>{S()===A&&C(xu);};F.addEventListener("close",B),u.push(()=>F.removeEventListener?.("close",B));}},U=A=>{h(A),I(A),!p&&(k="connected",o?.());},q=A=>{for(let O of c.splice(0))O();c.push(A.on("migrating",()=>{R=true;})),c.push(A.on("hostChanged",O=>{if(R=false,O===A.playerId){P("host_migrated_here");return}let F=S();F!==null&&U(F);})),c.push(A.on("peerJoined",O=>{O.playerId===A.hostPlayerId&&U(O);})),c.push(A.on("matchEnded",O=>{p||Sa(n,O),P(O);})),c.push(A.on("peerLeft",(O,F)=>{O===A.hostPlayerId&&C(Bb(F));}));};q(a);let x=S();return x!==null&&U(x),{matchId:s,protocol:"p2p",get state(){return k},send(A,O){k==="connected"&&S()?.send(Mn(A),gt(O));},onMessage(A){l=A;},onClose(A){d=A;},close(){f=true,P("closed"),a.leave().catch(()=>{});},async redial(){if(k==="closed")return "closed";if(k==="connected"||y)return "connected";if(R)throw new $("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");y=true;let A;try{for(let F of u.splice(0))F();for(let F of c.splice(0))F();a.close(),A=await e();}finally{y=false;}if(p)return f?A.leave().catch(()=>{}):A.close(),"closed";a=A,q(a);let O=S();if(O===null)throw a.close(),new $("connection_failed","this peer rejoined the match but the host never answered with a link");return U(O),"connected"},abandon(A){P(A);},onClosed(A){p?A():g.push(A);}}}function Pu(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 Vb=12e4;function yt(t,e){return {outcome:t,reason:e}}function Tu(t){let e=false,n=new Map,r=(o,i,s,a)=>{if(!t.bridge.parentSupports(o))return Promise.resolve(yt("unavailable","error"));if(e)return Promise.resolve(yt("declined","busy"));let l=`purchase-${_e()}`;return new Promise(d=>{let u={},c=p=>{n.delete(l)&&(e=false,t.clock.clearTimeout(u.timer),d(p));};e=true,n.set(l,{finish:c,check:s,label:a}),u.timer=t.clock.setTimeout(()=>c(yt("unavailable","error")),t.timeoutMs??Vb);let g=false;try{g=i(l);}catch{}g||c(yt("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(yt(i,Ol(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(yt("unavailable","error"));return}(async()=>{let u;try{u=await d;}catch{u="unknown";}if(u==="granted"){a(l===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:l});return}u==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(yt("unavailable","error"));})();}}}async function Eu(t,e){try{return (await Ys(t,e)).granted?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}var Kb="small_human",Iu=/^[a-z][a-z0-9_]{0,31}$/,Cu=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Jb=8;function Ra(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:Kb,id:e,modelUrl:n,iconUrl:r}]}function zb(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 Xb(t){let e=t??{},n=typeof e.item_id=="string"&&Cu.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&Iu.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=Tt(e.icon_url),l=Tt(e.model_url),d=[];for(let u of Array.isArray(e.prices)?e.prices:[]){let c=u??{};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 Yb(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&Iu.test(n)&&!e.includes(n)&&e.push(n),e.length===Jb)break;return e}function Mu(t){let e=new Set,n=Ra(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=Ra(o);if(!zb(n,i)){n=i;for(let s of [...e])try{s(i);}catch(a){r(a);}}}),{async families(){return Yb(await t.configFamilies())},worn(o){let i=Ra(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=Xb(s);a!==void 0&&i.push(a);}return i},purchase(o){let i=o?.itemId,s=o?.currencySlug;return typeof i!="string"||!Cu.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 Ou(t,e){try{return (await Is(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}function Gu(t){return Ws(t)}var Qb=6e5;function Lu(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??Qb);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 Zb=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),ev=["utm_"];function Du(t){return Zb.has(t)||ev.some(e=>t.startsWith(e))}var $u=16,Fu=512,tv=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,nv=/[\p{Cc}\p{Cf}]/u,rv=/\p{Cs}/u,Oe="[gem] gem.share.request:";function qu(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(`${Oe} 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(`${Oe} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!ov(l))throw new TypeError(`${Oe} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>$u)throw new TypeError(`${Oe} at most ${$u} params; got ${d.length}`);let u=[];for(let[c,g]of d){let p=JSON.stringify(c);if(!tv.test(c))throw new TypeError(`${Oe} param ${p}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Du(c))throw new TypeError(`${Oe} param ${p} is reserved: the arcade reads it itself and never forwards it`);if(typeof g!="string")throw new TypeError(`${Oe} param ${p}: values must be strings`);if(g.length>Fu)throw new TypeError(`${Oe} param ${p}: a value is at most ${Fu} characters`);if(nv.test(g))throw new TypeError(`${Oe} param ${p}: control and format characters are not allowed`);if(rv.test(g))throw new TypeError(`${Oe} param ${p}: a value must be well-formed text`);u.push({key:c,value:g});}!a.requestShare(u)&&!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 ov(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var On=3e4,Aa=12e4;function Gn(t,e,n){return t.held?Promise.resolve(n):(t.held=true,e().then(r=>(t.held=false,r)))}function ue(t,e,n){return {outcome:t,reason:e,...n}}function et(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 Nu(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 u=false;try{u=r(s);}catch{}u||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 iv=12,av=24,xa=Object.freeze({games:Object.freeze([])});function sv(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 go(t){return ue("unavailable","error",t)}function ju(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 u=l().then(c=>(i.delete(a),c));return i.set(a,u),u};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 go({});let l=a;return {...et(a),...l.arcade===void 0?{}:{arcade:{store:l.arcade.store}},...l.game===void 0?{}:{game:{store:l.game.store}}}},On)):Promise.resolve(ue("unavailable","unsupported",{}))},openApp(a){return e.parentSupports("appLinks")?a!=="arcade"&&a!=="game"?Promise.resolve(ue("unavailable","invalid_argument",{})):Gn(r,()=>n.ask("gem.openAppResult",l=>e.requestArcade({type:"gem.requestOpenApp",requestId:l,target:a}),l=>l===null?go({}):et(l),Aa),ue("declined","busy",{})):Promise.resolve(ue("unavailable","unsupported",{}))},openGame(a){if(!e.parentSupports("openGame"))return Promise.resolve(ue("unavailable","unsupported",{}));let l=typeof a=="string"?a.toLowerCase():"";return El({gem:j,type:"gem.requestOpenGame",requestId:"-",ref:l})!==null?Promise.resolve(ue("unavailable","invalid_argument",{})):Gn(r,()=>n.ask("gem.openGameResult",u=>e.requestArcade({type:"gem.requestOpenGame",requestId:u,ref:l}),u=>u===null?go({}):et(u),Aa),ue("declined","busy",{}))},similarGames(a){if(!e.parentSupports("openGame"))return Promise.resolve(ue("unavailable","unsupported",xa));let l=a?.limit;return l!==void 0&&(typeof l!="number"||!Number.isInteger(l)||l<1||l>av)?Promise.resolve(ue("unavailable","invalid_argument",xa)):s(`similar:${l??iv}`,()=>n.ask("gem.similarGamesResult",d=>e.requestArcade({type:"gem.requestSimilarGames",requestId:d,...l===void 0?{}:{limit:l}}),d=>{if(d===null)return go(xa);let u=et(d),c=d,g=u.outcome==="ok"?Object.freeze(c.games.map(sv)):[];return {...u,games:g}},On))}}}var lv=64,Bu=Object.freeze({offers:Object.freeze([])});function dv(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 Uu(t){let{bridge:e,asker:n,acting:r}=t,o=new Set,i=null;function s(a,l,d,u){return e.parentSupports(a)?typeof u!="string"||u.length===0||u.length>lv?Promise.resolve(ue("unavailable","invalid_argument",{})):Gn(r,()=>n.ask(d,c=>e.requestArcade({type:l,requestId:c,skuId:u}),c=>c===null?ue("unavailable","error",{}):et(c)).then(c=>((c.outcome==="ok"||c.reason==="error")&&t.onPurchaseEnded?.(),c)),ue("declined","busy",{})):Promise.resolve(ue("unavailable","unsupported",{}))}return {api:{get available(){return e.currentState==="connected"&&e.parentSupports("store")},get showOfferAvailable(){return e.currentState==="connected"&&e.parentSupports("storeOfferSheet")},offers(){return e.parentSupports("store")?(i!==null||(i=n.ask("gem.storeOffersResult",a=>e.requestArcade({type:"gem.requestStoreOffers",requestId:a}),a=>{if(a===null)return ue("unavailable","error",Bu);let l=et(a),d=a,u=l.outcome==="ok"?Object.freeze(d.offers.map(dv)):[];return {...l,offers:u}},On).then(a=>(i=null,a))),i):Promise.resolve(ue("unavailable","unsupported",Bu))},purchase(a){return s("store","gem.requestStorePurchase","gem.storePurchaseResult",a)},showOffer(a){return s("storeOfferSheet","gem.requestStoreOfferSheet","gem.storeOfferSheetResult",a)},onSettled(a){return o.add(a),()=>{o.delete(a);}}},settled(a){t.onPurchaseEnded?.();let l=Object.freeze({skuId:a.skuId});for(let d of [...o])try{d(l);}catch(u){t.onListenerError?.(u);}}}}var zu="https://gemarcade.com/branding/manifest.json",cv=1,Wu=256*1024,uv=256,mv=64,pv=256,Hu=8e3,gv=6e4,fv=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Vu={GEMS:"gems-mark",ARCADE_TICKETS:"ticket-mark"},Ku=Object.freeze({outcome:"unavailable"}),Ju=Object.freeze({outcome:"not_found"});function ht(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function yo(t){return typeof t=="string"&&t!==""&&t.length<=pv}function yv(t,e){if(!yo(t))return;let n;try{n=new URL(t,e);}catch{return}let r=Tt(n.href);if(r!==void 0)return n.origin===new URL(e).origin?r:ei(r)}function hv(t,e){let n=t??{},r=yv(n.url,e);if(!(r===void 0||!yo(n.type))&&!(typeof n.bytes!="number"||!(n.bytes>=0))&&!(n.theme!==void 0&&n.theme!=="light"&&n.theme!=="dark"))return Object.freeze({url:r,type:n.type,bytes:n.bytes,...ht(n.width)?{width:n.width}:{},...ht(n.height)?{height:n.height}:{},...ht(n.size)?{size:n.size}:{},...ht(n.density)?{density:n.density}:{},...n.vector===true?{vector:true}:{},...n.theme===void 0?{}:{theme:n.theme}})}function bv(t,e=zu){let n;try{n=JSON.parse(t);}catch{return null}let r=n??{};if(r.format!==cv||!Array.isArray(r.assets))return null;let o=[],i=new Set;for(let s of r.assets.slice(0,uv)){let a=s??{};if(!yo(a.id)||!fv.test(a.id)||i.has(a.id)||!yo(a.kind)||!Array.isArray(a.variants))continue;let l=[];for(let d of a.variants.slice(0,mv)){let u=hv(d,e);u!==void 0&&l.push(u);}l.length!==0&&(i.add(a.id),o.push(Object.freeze({id:a.id,kind:a.kind,variants:Object.freeze(l)})));}return Object.freeze(o)}function fo(t){let e;for(let n of t)(e===void 0||(n.width??0)>(e.width??0))&&(e=n);return e}function vv(t,e,n){let r=t.find(l=>l.vector===true),o=t.filter(l=>l.size===void 0);if(e===void 0)return r??fo(o)??fo(t);let i=t.filter(l=>l.size===e);if(i.length>0){let l=u=>u.density??1,d=i.filter(u=>l(u)>=n);return d.length>0?d.reduce((u,c)=>l(c)<l(u)?c:u):i.reduce((u,c)=>l(c)>l(u)?c:u)}if(r!==void 0)return r;let s=o.filter(l=>(l.width??0)>=e*n);return (s.length>0?s.reduce((l,d)=>(d.width??0)<(l.width??0)?d:l):void 0)??fo(o)??fo(t)}function _v(t,e){let n=e.theme===void 0?[]:t.variants.filter(a=>a.theme===e.theme),r=t.variants.filter(a=>a.theme===void 0),o=[n,r].filter(a=>a.length>0);if(t.kind!=="image")return o[0]?.[0];let s=(e.size===void 0?void 0:o.find(a=>a.some(l=>l.size===e.size)))??o[0];return s&&vv(s,e.size,e.density)}function wv(t,e){if(e!==void 0){if(e===null||typeof e!="object")throw new TypeError(`[gem] branding.${t}: options must be an object`);if(e.size!==void 0&&!ht(e.size))throw new RangeError(`[gem] branding.${t}: size must be a positive number of CSS px`);if(e.density!==void 0&&!ht(e.density))throw new RangeError(`[gem] branding.${t}: density must be a positive number`);if(e.theme!==void 0&&e.theme!=="light"&&e.theme!=="dark")throw new TypeError(`[gem] branding.${t}: theme must be 'light' or 'dark'`)}}function Xu(t){let e=t.manifestUrl??zu,n=null,r=null,o=-1/0,i=false,s=u=>(o=t.clock.now(),i||(i=true,t.log?.(`[gem] gem.branding could not read the platform's branding (${u}), so every lookup answers 'unavailable' and your bundled fallback shows. If your page sets a Content-Security-Policy, allow ${new URL(e).origin} in connect-src and img-src.`)),null),a=async()=>{if(t.fetch===null)return s("this page has no fetch");let u=t.fetch,c=typeof AbortController=="function"?new AbortController:null,g,p=new Promise(y=>{g=t.clock.setTimeout(()=>{c?.abort(),y(s(`no answer in ${Hu} ms`));},Hu);}),f=(async()=>{let y=await u(e,{credentials:"omit",redirect:"error",...c?{signal:c.signal}:{}});if(!y.ok)return s("the manifest answered an error");if(Number(y.headers.get("content-length"))>Wu)return s("the manifest is too large");let R=await y.text();return R.length>Wu?s("the manifest is too large"):bv(R,e)??s("the manifest is not format 1 JSON")})().catch(()=>s("the request failed"));try{return await Promise.race([f,p])}finally{t.clock.clearTimeout(g);}},l=()=>n!==null?Promise.resolve(n):r!==null?r:t.clock.now()-o<gv?Promise.resolve(null):(r=a().then(u=>(r=null,u!==null&&(n=u),u)),r),d=async(u,c,g,p)=>{wv(u,p);let f=await l();if(f===null)return Ku;let y=f.find(P=>P.id===c&&P.kind===g);if(y===void 0)return Ju;let R=t.devicePixelRatio(),k=_v(y,{...p?.size===void 0?{}:{size:p.size},density:p?.density??(ht(R)?R:1),...p?.theme===void 0?{}:{theme:p.theme}});return k===void 0?Ju:Object.freeze({outcome:"ok",url:k.url,variant:k,asset:y})};return Object.freeze({get:async(u,c)=>{if(typeof u!="string"||u==="")throw new TypeError("[gem] branding.get: id must be a non-empty string");if(c===null||typeof c!="object"||typeof c.kind!="string")throw new TypeError("[gem] branding.get: options.kind must be a string, such as 'image'");return d("get",u,c.kind,c)},logo:u=>d("logo","gem-logo","image",u),wordmark:u=>d("wordmark","gem-wordmark","image",u),currencyMark:async(u,c)=>{let g=Object.prototype.hasOwnProperty.call(Vu,u)?Vu[u]:void 0;if(g===void 0)throw new TypeError("[gem] branding.currencyMark: currency must be 'GEMS' or 'ARCADE_TICKETS', not "+JSON.stringify(String(u).slice(0,40)));return d("currencyMark",g,"image",c)},trophy:u=>d("trophy","trophy-mark","image",u),list:async()=>{let u=await l();return u===null?Ku:Object.freeze({outcome:"ok",assets:u})}})}var Av="(any-pointer: coarse)";function xv(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 Yu(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?u=>matchMedia(u):void 0},o=r.navigator,i,s=new Set,a=()=>typeof o?.vibrate!="function"||r.matchMedia===void 0?false:(i??=r.matchMedia(Av),i.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(u,c)=>{s.has(u)||(s.add(u),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return a()||l()},vibrate(u){let c=a();if(!c&&!l())return false;let g=xv(u);if(g===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(g)===!0}catch{return false}let p=e.requestVibrate(g);return p||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),p}}}var jt=Math.PI/180,Ge=Object.freeze({touch:Object.freeze({yaw:1*jt,pitch:.66*jt}),mouse:Object.freeze({yaw:.5*jt,pitch:.5*.77*jt}),stick:Object.freeze({yaw:240*jt,pitch:240*.77*jt}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Pa="[gem.controls]",Ta=Object.freeze({yaw:0,pitch:0}),ho=t=>Number.isFinite(t)?t:0,Qu=(t,e)=>({yaw:t+0,pitch:e+0});function Zu(t){let e=ho(t),n=(Math.abs(e)-Ge.stickDeadzone)/(1-Ge.stickDeadzone),r=Ge.stickCurve,o=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,o))+0}function Pv(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Ge.touchPitchMin)+Ge.touchPitchMin}function em(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${Pa} ${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(`${Pa} ${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(`${Pa} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function Tv(t,e){let n=em(e,"look()"),r=n.sensitivity,o=n.gamepadSensitivity,i=n.invertY,s=a=>i??a?.invertLookY??false;return {fromPointer(a,l,d,u){let c=ho(a),g=ho(l);if(c===0&&g===0)return Ta;let p=t(),f=r??(p===null?void 0:p.lookSensitivity/100)??1,y=d==="touch"||d==="pen",R=y?Ge.touch:Ge.mouse,k=c*R.yaw*f,P=-g*R.pitch*f;return s(p)&&(P=-P),y&&u!==void 0&&Number.isFinite(u)&&P*u>0&&(P*=Pv(u)),Qu(k,P)},fromStick(a,l,d){let u=ho(d);if(u<=0)return Ta;let c=Zu(a),g=Zu(l);if(c===0&&g===0)return Ta;let p=t(),f=o??(p===null?void 0:p.gamepadLookSensitivity/100)??1,y=c*Ge.stick.yaw*u*f,R=-g*Ge.stick.pitch*u*f;return s(p)&&(R=-R),Qu(y,R)},set(a){let l=em(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(o=l.gamepadSensitivity),"invertY"in l&&(i=l.invertY);}}}function tm(t){return {look:e=>Tv(t.recommended,e),LOOK_BASE:Ge}}var nm=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),rm=/^[A-Za-z0-9_-]{1,40}$/;function Ea(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function om(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function im(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 am(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 im(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 sm(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"||!rm.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(g=>g.id===l)){e(`${d} was dropped: an earlier setting has the same id.`);continue}let u=om(a.label);if(u===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:u,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 g=a.min??0,p=a.max??100,f=a.step??1;if(!Ea(g)||!Ea(p)||!Ea(f)||g>=p||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:u,kind:"slider",value:im(a.value,g,p,f),min:g,max:p,step:f};break}case "choice":{let g=[];for(let p of Array.isArray(a.options)?a.options:[]){if(g.length===4)break;if(typeof p!="object"||p===null)continue;let f=p,y=om(f.label);typeof f.id!="string"||!rm.test(f.id)||y===void 0||g.some(R=>R.id===f.id)||g.push({id:f.id,label:y});}if(g.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"||!g.some(p=>p.id===a.value)){e(`${d} was dropped: a choice's value is the id of one of its options.`);continue}c={id:l,label:u,kind:"choice",value:a.value,options:g};break}default:e(`${d} was dropped: its kind must be 'toggle', 'slider' or 'choice'.`);continue}a.icon!==void 0&&(nm.includes(a.icon)?c.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${nm.join(", ")}.`)),n.push(c);}return n}var Ev=500;function lm(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")},u=()=>{if(n===null||i!==null)return;let c=JSON.stringify(n);if(c===r)return;let g=o+Ev-e.now();if(g>0){i=e.setTimeout(()=>{i=null,u();},g);return}t.frame().declareSettings(n)&&(r=c,o=e.now());};return {api:{declare(c){let g=sm(c,p=>l(`[gem] gem.settings.declare: ${p}`));return g===null?(l("[gem] gem.settings.declare did nothing: pass an array of settings, or [] for none."),false):(n=g,u(),d())},onChange(c){if(typeof c!="function")return ()=>{};let g=p=>c(p);return s.add(g),()=>{s.delete(g);}}},forgetSent(){r=null,o=-1/0;},flush:u,onSettingChange(c){let g=n?.findIndex(k=>k.id===c.id)??-1,p=n?.[g];if(n===null||p===void 0)return;let f=am(p,c.value);if(f===void 0)return;let y=JSON.stringify(n);n=n.map((k,P)=>P===g?{...k,value:f}:k),r===y&&(r=JSON.stringify(n));let R={id:p.id,value:f};for(let k of [...s])try{k(R);}catch(P){console.error("[gem] a gem.settings.onChange handler threw:",P);}}}}function dm(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var Iv=/(?:Z|[+-]\d{2}:?\d{2})$/i;function cm(t){if(typeof t!="string"||!Iv.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function Ln(){return {declared:false,grantable:false,heldLimitReached:false}}function um(t,e){let n=typeof t=="object"&&t!==null?t:{},r=cm(n.resets_at),o=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...Ln(),...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=cm(a),d=n.held_limit_reached===true,u=a!=null,c=i!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!c&&!u&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...o}}var Cv=18e4,Ia=32,Mv=/^[a-z0-9_-]+$/,Ov="rewarded_requires_user_gesture";function Gv(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var Lv=1e3;function Dv(){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<=Lv)return true}return false}var mm=1e4;function $v(t){return t==="interstitial"||t==="rewarded"}function pm(t){return typeof t=="string"&&t!==""&&t.length<=Ia&&Mv.test(t)}function Fv(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function bo(t){return typeof t=="string"?JSON.stringify(t):typeof t}function gm(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 u=t.log;if(u!==null)try{u===void 0?console.warn(`[gem] ${d}`):u(`[gem] ${d}`);}catch{}},l=d=>{let u=t.readAvailability;if(u===void 0)return Promise.resolve(Ln());let c=r.get(d);if(c!==void 0)return c;let g=new Promise(p=>{let f={},y=h=>f.done===true?false:(f.done=true,t.clock.clearTimeout(f.timer),p(h),true),R=(h,S)=>{!y(Ln())||o.has(h)||(o.add(h),i(`gem.ads.rewardedStatus("${d}") answered not grantable: ${S}. Said once.`));},k=h=>{R(Fv(h),`the read failed (${h instanceof Error?h.message:bo(h)})`);},P;try{P=Promise.resolve(u(d,AbortSignal.timeout(mm)));}catch(h){P=Promise.reject(h);}f.timer=t.clock.setTimeout(()=>{R("timeout","no answer within 10 s");},mm),P.then(h=>{try{y(um(h,t.bridge.parentSupports("ads")));}catch(S){k(S);}},k);});return r.set(d,g),g.then(()=>{r.get(d)===g&&r.delete(d);}),g};return {api:{rewardedStatus(d){return pm(d)?l(d):(i(`gem.ads.rewardedStatus(${bo(d)}) answered not grantable: a placement is 1..${String(Ia)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(Ln()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let u=d?.placement,c=d?.format;if(!pm(u)||!$v(c))return i(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${bo(u)}, format ${bo(c)}. A placement is 1..${String(Ia)} 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 p;try{p=(t.userActivation??Gv)();}catch{p=void 0;}if(p===false)try{(t.recentGamepadInput??Dv)()===!0&&(p=!0);}catch{}if(p===false){let f=`${Ov}: gem.ads.requestAd("${u}", '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(f),a(f),Promise.resolve({outcome:"no_ad"})}}let g=`ad-${_e()}`;return new Promise(p=>{let f={},y=k=>{n.delete(g)&&(e=false,t.clock.clearTimeout(f.timer),p(k));};e=true,n.set(g,y),f.timer=t.clock.setTimeout(()=>{y({outcome:"unavailable"});},t.timeoutMs??Cv);let R=false;try{R=t.bridge.requestAd(g,u,c);}catch{}R||y({outcome:"no_ad"});})}},settle(d){let u=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${u}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:u});}}}var fm=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),ym=18e4,qv=1e4,Nv=/^[a-z0-9_-]{1,32}$/;function Ca(t){return typeof t=="string"?JSON.stringify(t):typeof t}var Dn=Object.freeze({shown:false});function hm(t){let e=new Map,n,r=false,o=i=>{try{t.onDropped?.(i);}catch{}return Dn};return {api:{signal(i){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(Dn):(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,l=i?.wall;if(!fm.includes(s)||a!==void 0&&(typeof a!="string"||!Nv.test(a))||l!==void 0&&typeof l!="boolean")return Promise.resolve(o(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${Ca(s)}, placement ${Ca(a)}, wall ${Ca(l)}. A kind is one of ${fm.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(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 d=t.clock.now();if(n!==void 0&&d-n<qv)return Promise.resolve(o(`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 u=`moment-${_e()}`;return new Promise(c=>{let g={},p=(y,R)=>{e.delete(u)&&(t.clock.clearTimeout(g.timer),R&&(n=t.clock.now()),c(y));};e.set(u,y=>p(y,!0)),g.timer=t.clock.setTimeout(()=>{e.has(u)&&(p(Dn,!0),o(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??ym)/1e3)} s. Answering shown: false.`));},t.timeoutMs??ym);let f=!1;try{f=t.bridge.signalMoment(u,s,a,l===!0?!0:void 0);}catch{}f||p(Dn,!1);})}catch{return Promise.resolve(Dn)}}},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 Ma=16384;function bm(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:jv(e)}function jv(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 Bv=1e4,Uv=5e3;function vm(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=Uv){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(u),l(),a(e);},u=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=bm(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(u=>{let c={},g=f=>{o.delete(d)&&(t.clock.clearTimeout(c.timer),f==="stored"&&(e=l,n=true,i()),u(f));};o.set(d,g),c.timer=t.clock.setTimeout(()=>g("unavailable"),t.timeoutMs??Bv);let p=false;try{p=t.bridge.putDeviceSettings(d,l);}catch{}p||g("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 $n=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 Wv=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Hv(t){return typeof t=="string"&&Wv.test(t)}function vo(t){if(t===null||Hv(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 _m(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Ga(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 _o(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 wm(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Vv(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,u=t.avatar3dId,c={displayName:n,displayHandle:o??n,badges:(t.badges??[]).map(y=>({itemId:y.itemId,iconUrl:y.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),u&&l.test(u)&&(c.avatar3dId=u),t.avatar3dModelUrl&&(c.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(c.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(c.avatars3d=t.avatars3d.filter(y=>l.test(y.id)&&/^[a-z][a-z0-9_]*$/.test(y.family)).filter((y,R,k)=>k.findIndex(P=>P.family==y.family)==R).map(({family:y,id:R,modelUrl:k,iconUrl:P})=>({family:y,id:R,modelUrl:k,iconUrl:P})));let g=t.boost,p=(g?.multipliers??[]).map(y=>({currencyId:y.currencyId,currencySlug:y.currencySlug,multiplier:y.multiplierBp/1e4})),f=p.some(y=>y.multiplier>1);return c.boost=f&&g?.expiresInDays?{active:f,multipliers:p,expiresInDays:g.expiresInDays}:{active:f,multipliers:p},c}var Kv=1e4,Jv=["appLinks","openGame","store","storeOfferSheet"],Oa=new WeakMap;function km(t,e){if(Oa.has(t))throw new Error("admitBuildEmbedders: already admitted");Oa.set(t,Object.freeze([...e]));}var Fn=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??de,this.inbound=new zt(this.clock),this.outbound=new zt(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=>kt(a,e.origin))||cr(e.origin,this.options.selfOrigin)||(Oa.get(this)??[]).some(a=>kt(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=dr["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!kt(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=Il(ar,o.versions);return s===null?(i.onmessage=null,i.postMessage({gem:j,type:"gem.error",code:"version_mismatch",message:`frame supports v${ar.min}..v${ar.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=Kv){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:_m(e.origin.x),y:_m(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=vo(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",...Ga(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:j,type:"gem.menu",..._o(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}setMenuStyle(e){return this.gated("menuStyle")?this.send(e===null?{gem:j,type:"gem.menuStyle"}:{gem:j,type:"gem.menuStyle",ground:e.ground,accent:e.accent}):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:wm(e.fps,1e3),frameTimeP95Ms:wm(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,o){return this.send({gem:j,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r},...o===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,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(lr(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(sr)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(sr)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(sr)&&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=dr[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||Sm(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=dr[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=lr(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 Sm(n.slice(1)),this.options.onScreenshot(d,l,(u,c)=>this.screenshotDenied(u,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?.(Vv(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(Jv.includes(lr(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 Sm(t){for(let e of t)try{e?.close?.();}catch{}}var Rm="https://api.gemarcade.com";function La(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 zv=new Set(["localhost","127.0.0.1","[::1]"]);function Am(t){let e=La(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!zv.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 Tm="/gem-embedders.json",wo=4096,xm=16,Pm=5e3,qn=Object.freeze({origins:Object.freeze([])});function tt(t){return {origins:[],refused:`[gem] ${Tm} was ignored: ${t}`}}function Xv(t){if(t.trim()==="")return qn;let e;try{e=JSON.parse(t);}catch{return tt("it is not JSON.")}if(e===null||typeof e!="object"||Array.isArray(e))return tt('it must be an object, { "embedders": [...] }.');let n=e.embedders;if(n===void 0)return qn;if(!Array.isArray(n))return tt('"embedders" must be an array of origins.');if(n.length>xm)return tt(`"embedders" has more than ${xm} entries.`);let r=n.filter(o=>typeof o!="string"||!St(o)||!o.toLowerCase().startsWith("https://")||Je(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 tt(`${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 Em(t){let e=typeof AbortController=="function"?new AbortController:null,n,r=new Promise(i=>{n=t.clock.setTimeout(()=>{e?.abort(),i(tt(`it took more than ${Pm} ms to read.`));},Pm);}),o=(async()=>{let i=await t.fetch(t.selfOrigin+Tm,{credentials:"omit",redirect:"error",...e?{signal:e.signal}:{}});if(!i.ok||(i.headers.get("content-type")??"").toLowerCase().includes("text/html"))return qn;if(Number(i.headers.get("content-length"))>wo)return tt(`it is larger than ${wo} bytes.`);let a=await i.text();return a.length>wo?tt(`it is larger than ${wo} bytes.`):Xv(a)})().catch(()=>qn);try{return await Promise.race([o,r])}finally{t.clock.clearTimeout(n);}}function Im(t){if(typeof t!="string"||!St(t))return null;let e=t.slice(0,t.indexOf(":")).toLowerCase();return e==="https"||e==="http"?t:null}function Cm(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function Yv(){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 Qv=Object.freeze({small_human:Cm([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:Cm(Yv())});var e_=Object.freeze(["https://gemarcade.com","https://developer.gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),t_=Rm,n_=["top-left","top-right","bottom-left","bottom-right"];function Mm(t){let e=[1,3,5].map(n=>{let r=parseInt(t.slice(n,n+2),16)/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function r_(t){if(t===null)return null;let{ground:e,accent:n}=Object(t);for(let[s,a]of [["ground",e],["accent",n]]){if(typeof a=="string"&&/^#[0-9a-fA-F]{6}$/.test(a))continue;let l=typeof a=="string"?JSON.stringify(a.slice(0,48)):`a value of type ${typeof a}`;console.warn(`[gem] setMenuStyle: ${s} is ${l}, which is not #rrggbb, so nothing was sent.`);return}let r={ground:e.toLowerCase(),accent:n.toLowerCase()},o=[Mm(r.ground),Mm(r.accent)],i=(Math.max(...o)+.05)/(Math.min(...o)+.05);if(i>=3)return r;console.warn(`[gem] setMenuStyle: accent ${r.accent} reaches ${Math.floor(i*100)/100}:1 against ground ${r.ground}, under the 3:1 it needs, so nothing was sent.`);}var Om=8e3,So=15e3,o_=9e4,i_=1/0,a_=8e3,s_=5e3,l_=5e3;async function d_(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 Nn(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 RE(t={}){let e=t.clock??de,n=t.log===void 0?m=>console.info(m):t.log,r=t.baseUrl??void 0;if(r!=null){let m=La(r);if(m!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${m}. 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=pd(o),s=Nd(o),a=ea();a.mark("sdk created");let l=()=>Nr(ae.gameVersion,t.clientVersion?.gameVersion),d=new cn({client:()=>vt,clock:e,gameId:()=>ae.identity?.gameId??null,playerId:()=>ae.identity?.playerId??null,awaitPlayerId:async()=>(await er(So)).playerId,declarations:async()=>(await Zn.load())?.analytics_events,environment:()=>{let m=l();return {sdk_version:ss(),...m===null?{}:{game_version:m}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),u=Ac(()=>{a.mark("engaged"),d.release(),D.reportEngaged();},typeof window>"u"?{}:window),c=m=>{if(m===false)return null;let T=m?.attempts??i_,L=m?.budgetMs??o_;return !(T>0)||!(L>0)?null:{attempts:T,budgetMs:L,maxDelayMs:m?.maxDelayMs??a_}},g=m=>{m.on("created",()=>{a.mark("room created");}),m.on("joined",()=>{a.mark("room joined");}),m.on("matchAllocationStarted",()=>{a.mark("allocation started");}),m.on("matchReady",()=>{a.mark("match ready");}),m.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 $n;let p=t.allowedEmbedders;if(p!=null&&!Array.isArray(p))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(p??[]),y=f.filter(m=>typeof m!="string"||!St(m));if(y.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${y.length===1?"an entry":"entries"} that ${y.length===1?"is":"are"} not an origin: ${y.map(m=>typeof m=="string"?JSON.stringify(m):String(m)).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([...e_,...f])]),k=Nn(e),P=new Set,h=Nn(e),S=false,C=Nn(e),I=vd(n),U=Nn(e),q=t.manageAudio===false?null:Fc();t.selectableText!==true&&qc(),t.onScreenshot===void 0&&Pc(window);let x=null,A=null,O=null,F=()=>{x===null||x===A||D.reportMuted(x)&&(A=x);},B,W,J=-1/0,ie=null,ge=()=>{if(B===void 0||ie!==null||B===W)return;let m=J+1e3-e.now();if(m>0){ie=e.setTimeout(()=>{ie=null,ge();},m);return}D.showPortraitBorders(B)&&(W=B,J=e.now());},X=null,Be=null,Se=()=>{if(X===null)return false;let m=JSON.stringify(Ga(X.visible,X.only));return m===Be?D.parentSupports("walletDisplay"):D.setWalletVisible(X.visible,X)?(Be=m,true):false},fe=null,Ue=null,te=()=>{if(fe===null)return false;let m=JSON.stringify(_o(fe.items));return m===Ue?D.parentSupports("gameMenu"):D.setMenu(fe.items)?(Ue=m,true):false},z=null,le=null,xe,Le=null,De=lm({frame:()=>D,clock:e,log:t.log}),jn=()=>z===null?false:z===le?D.parentSupports("gemCorner"):D.setGemCorner(z)?(le=z,true):false,Bt=()=>{if(xe===void 0)return false;let m=JSON.stringify(xe);return m===Le?D.parentSupports("menuStyle"):D.setMenuStyle(xe)?(Le=m,true):false},nt=Nc({report:m=>D.reportFrameStats(m)}),We=false,$e=Kc(()=>es,()=>We),Ut=m=>{let T=We&&!m,L=We!==m;if(We=m,T&&$e.close(),!!L)try{t.onDevToolsPermissionChange?.(m);}catch(ee){n?.(`[gem] onDevToolsPermissionChange threw: ${ee instanceof Error?ee.message:String(ee)}`),queueMicrotask(()=>{throw ee});}},b=r??t_,M=r!==void 0,N,Z=m=>(n?.(`[gem] token refused: ${m}`),t.onError?.("internal",m),false),ke=(m,T)=>{if(m===void 0)return T!==void 0?Z("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 L=Am(m);return L!==null?Z(`the embedder named an API root that cannot be used: ${L}. Its value is withheld here rather than written to logs.`):N!==void 0&&N!==m?Z("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."):(N=m,M||(b=m),true)},Fe=window.location?.origin,Wt=null,bt=-1/0,$m=2e3,Bn=new Set,Fm=m=>Wt!==false?Promise.resolve(true):new Promise(T=>{let L=e.setTimeout(()=>{Bn.delete(ee),T(false);},m),ee=()=>{e.clearTimeout(L),Bn.delete(ee),T(true);};Bn.add(ee);}),ko=()=>{},Ro=null,Un=()=>{},Wn=Nu(e),D=new Fn({allowedEmbedders:R,...typeof Fe=="string"&&Fe!==""?{selfOrigin:Fe}:{},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","menuStyle","gameSettings","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges","appLinks","openGame","store","storeOfferSheet",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[]],onRefused:m=>{Ro=m,t.onRefused?.(m);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:m=>{ae.onBridgeState(m),m!=="connected"&&Wn.abandon(),m!=="connected"&&nt.setRequested(false),A=null,Be=null,Ue=null,le=null,Le=null,De.forgetSent(),W=void 0,m==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Ro===null?"":` (${Ro})`)+", 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."),ko()),m==="connected"&&(a.mark("bridge connected"),qm(),F(),ge(),Se(),te(),jn(),Bt(),De.flush(),D.unbiddenLaunch&&!u.engaged&&d.hold(),d.startSession(),u.engaged&&D.reportEngaged()),t.onStateChange?.(m);},onPlayer:m=>{k.set(m);for(let T of [...P])T(m);t.onPlayer?.(m);},onPrefs:m=>{let T={reducedMotion:m.reducedMotion,muted:m.muted,locale:m.locale,showFrameStats:m.showFrameStats===true,music:m.music!==false,sounds:m.sounds!==false,recommended:m.recommended===void 0?null:Object.freeze({volume:m.recommended.volume,batterySaver:m.recommended.batterySaver,keyboardLayout:m.recommended.keyboardLayout,gamepadConfirm:m.recommended.gamepadConfirm,vibration:m.recommended.vibration,lookSensitivity:m.recommended.lookSensitivity??100,gamepadLookSensitivity:m.recommended.gamepadLookSensitivity??100,invertLookY:m.recommended.invertLookY??false,touchMovement:m.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:dm(m.recommended.graphicsQuality,m.recommended.batterySaver),graphicsQualityAuto:m.recommended.graphicsQualityAuto??true,colorHelp:typeof m.recommended.colorHelp=="boolean"?m.recommended.colorHelp:null})};h.set(T),A=T.muted,q?.setMuted(T.muted),nt.setRequested(T.showFrameStats&&D.parentSupports("frameStats")),t.onPrefs?.(T),t.onAudioChannels!==void 0&&(O===null||O.music!==T.music||O.sounds!==T.sounds)&&(O=Object.freeze({music:T.music,sounds:T.sounds}),t.onAudioChannels(O));},onCohorts:m=>{let T=Object.freeze(m.cohorts.map(L=>Object.freeze({experimentId:L.experimentId,variantKey:L.variantKey})));C.set(T),t.onCohorts?.(T);},onEarnAllowanceChanged:()=>I.emit(),onViewport:m=>{let T=Object.freeze({insets:Object.freeze({top:m.insets.top,right:m.insets.right,bottom:m.insets.bottom,left:m.insets.left}),reserved:Object.freeze((m.reserved??[]).map(({x:ee,y:ts,width:ns,height:rs,control:Vt})=>Object.freeze(Vt?{x:ee,y:ts,width:ns,height:rs,control:Object.freeze({x:Vt.x,y:Vt.y,width:Vt.width,height:Vt.height})}:{x:ee,y:ts,width:ns,height:rs})))});U.set(T);let L=Bc();Uc(L,T.insets),Hc(L,T.reserved,Wc()),t.onViewport?.(T);},onPause:m=>{m.paused||Un(),S=m.paused,q?.setPaused?.(m.paused),d.setPaused(m.paused),nt.setPaused(m.paused),t.onPause?.(m.paused);},onSettingChange:m=>De.onSettingChange(m),onMenuSelect:m=>{fe===null||m.entry!=="item"||!(_o(fe.items).items??[]).some(L=>L.id===m.id)||fe.items?.find(L=>L.id===m.id)?.onSelect?.();},onWillTerminate:m=>{d.endSession(m.reason),t.onWillTerminate?.({reason:m.reason,graceMs:m.graceMs});},onToken:m=>{let T=m.garden;if(Ut(m.allowDevTools===true),!ke(m.apiBaseUrl,T))return;let L=m;ae.onToken(L);let ee=ae.identity;ee&&(Ao.set(ee),Fa||(Fa=true,me.reconcileSeats().catch(()=>{}))),qa.push({token:L.token,expiresAt:L.expiresAt});},onTokenDenied:m=>{Ut(false),ae.onDenied(m);},onScreenshot:(m,T,L)=>{Gc(m,T,L,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Lc(D,t.onFeedbackContext);},onDevtools:m=>{m==="close"?$e.close():m==="open"?$e.openFrom("platform").catch(()=>{}):$e.isOpen?$e.close():$e.openFrom("platform").catch(()=>{});},onRoomEvent:m=>me.handleRoomEvent({event:m.event,roomId:m.roomId,...m.matchId===void 0?{}:{matchId:m.matchId},...m.version===void 0?{}:{version:m.version},...m.reason===void 0?{}:{reason:m.reason},...m.platform===void 0?{}:{platform:m.platform}}),onSeatedEvent:m=>me.handleSeated(m.roomId),onAutoStartFailedEvent:m=>me.handleAutoStartFailed(m.roomId,m.code),onTicketEvent:m=>me.handleTicketEvent({event:m.event,ticketId:m.ticketId,...m.partySize===void 0?{}:{partySize:m.partySize},...m.queuedAt===void 0?{}:{queuedAt:m.queuedAt},...m.expiresAt===void 0?{}:{expiresAt:m.expiresAt},...m.reason===void 0?{}:{reason:m.reason},...m.roomId===void 0?{}:{roomId:m.roomId}}),onSocketState:m=>{let T=Wt;if(Wt=m.connected,m.connected)for(let ee of [...Bn])ee();if(!m.connected||T===true)return;let L=e.now();L-bt<$m||(bt=L,me.reconcile().catch(()=>{}));},onSignalEvent:m=>{let T=typeof m.data=="object"&&m.data!==null&&!Array.isArray(m.data)?m.data:{};_t.handleSignalEvent(m.matchId,m.event,T),m.event==="matchEnded"&&me.reconcile({matchId:m.matchId,...typeof T.reason=="string"?{reason:T.reason}:{}}).catch(()=>{});},onDedicatedEvent:m=>{m.event==="matchEnded"&&(Ht.handleMatchEnded(m.matchId,m.reason),me.reconcile({matchId:m.matchId,...m.reason===void 0?{}:{reason:m.reason}}).catch(()=>{})),$a.handleEvent(m);},onClusterTarget:m=>Jn.accept(m.clusterTargetId,m.clusterTargetIds),onLocalServer:m=>zn.accept(m),onLocalServerDenied:m=>zn.refuse(m),onPartyResult:m=>ja.settle(m.requestId,m.partyId),onPurchaseResult:m=>Po.settle(m),onDeviceSettings:m=>{Kn.receive(m),t.onDeviceSettings?.(Kn.api.current);},onDeviceSettingsResult:m=>Kn.settle(m),onAdResult:m=>Ua.settle(m),onMomentResult:m=>Wa.settle(m),onSignInResult:m=>{m.outcome==="signed_in"&&Un(),Ha.settle(m);},onFriendChallengeResult:m=>Ja.settle(m),onArcadeAnswer:m=>{m.type==="gem.storePurchaseSettled"?Ka.settled(m):jm(m);}}),$a=new Cn({bridge:D}),Ao=Nn(e);ko=()=>{Ao.release(),k.release(),C.release();},D.currentState==="refused"&&ko();let Fa=false,xo=new Set,Hn,qa={current:()=>Hn,subscribe:m=>(xo.add(m),Hn!==void 0&&m(Hn),()=>xo.delete(m)),push:m=>{Hn=m;for(let T of [...xo])try{T(m);}catch(L){n?.(`[gem] a server-token listener threw: ${L instanceof Error?L.message:String(L)}`);}}},ae=zc({bridge:D,clock:e,onStateChange:(m,T)=>{if(m==="ready"){if(a.mark("token ready")){let L=a.marks.find(ee=>ee.name==="token ready")?.at;d.trackPlatform("gem_boot_ready",L===void 0?{}:{boot_ms:Math.max(0,Math.round(L))});}}else m==="lost"&&(a.mark("token lost"),d.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(m,T);}}),Na=()=>{let m=ae.identity;return !m||ae.source.currentState==="lost"?null:`${m.playerId}\0${m.gameId}\0${m.channel}`},qm=()=>{a.mark("token requested"),ae.source.get().catch(()=>{});},ja=Pu({bridge:D,clock:e}),Vn={},Po=Tu({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m),confirm:async m=>Vn.confirm?.(m)??"unknown",confirmAvatar3d:async m=>Vn.confirmAvatar3d?.(m)??"unknown"}),Kn=vm({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),Ba={},Ua=gm({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m),readAvailability:(m,T)=>Ba.read?.(m,T)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),Wa=hm({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),Ha=Lu({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),Va={held:false},Nm=ju({bridge:D,asker:Wn,acting:Va}),Ka=Uu({bridge:D,asker:Wn,acting:Va,onListenerError:m=>t.onError?.("internal",`gem.store.onSettled listener threw: ${String(m)}`),onPurchaseEnded:()=>Un()}),jm=m=>{Wn.settle(m)||t.onError?.("internal",`${m.type} (${m.outcome}) for an unknown requestId: `+JSON.stringify(m.requestId));},Ja=bd({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),Jn=Pd({bridge:D,clock:e}),zn=Vc({bridge:D,clock:e}),To=Im(Fe),za=window.fetch,Xn=To!==null&&typeof za=="function"?"unread":"read",Yn=null,Eo=false,Bm=m=>{if(Xn==="read"||m.source!==window.parent)return false;let T=m.origin;return typeof T!="string"||R.some(L=>kt(L,T))||cr(T,typeof Fe=="string"?Fe:void 0)?false:((Yn===null||!Eo)&&(Yn=m),Xn==="unread"&&To!==null&&(Xn="reading",Em({fetch:(L,ee)=>za.call(window,L,ee),selfOrigin:To,clock:e}).then(L=>{"refused"in L&&n?.(L.refused),L.origins.length>0&&km(D,L.origins),Xn="read";let ee=Yn;Yn=null,ee!==null&&D.currentState==="waiting"&&Qn(ee);})),true)},Qn=m=>{if(Bm(m))return false;let T=D.handleWindowMessage({data:m.data,origin:m.origin,source:m.source,ports:m.ports});return T&&window.removeEventListener("message",Qn),T};window.addEventListener("message",Qn),Eo=true;let rt;try{rt=as(window,Qn);}finally{Eo=false;}let Um=rt?.capture,Io=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Io?.domInteractive!==void 0&&Io.domInteractive>0&&a.mark("document parsed",Io.domInteractive),Um?.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 Co=t.handshakeWarningMs;Co!==null&&n&&e.setTimeout(()=>{let m=rt===null?"no capture script ran":`capture: ${rt.delivered} offer(s) delivered, ${rt.stale} stale, ${rt.capture.dropped} evicted${rt.capture.late?", installed late":""}`;if(D.currentState==="connected"){n(`[gem] handshake connected. boot: ${a.timeline()} \xB7 ${m}`);return}n(`[gem] no completed handshake after ${Co??Om}ms (bridge state: ${D.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 `+m);},Co??Om);let Wm=br({get baseUrl(){return b},tokenSource:ae.source,get defaultQuery(){let m=ae.identity;return m?{game_id:m.gameId,channel:m.channel}:{}}}),vt=new He({transport:Wm,clock:e}),ye={client:vt,gameId:()=>ae.identity?.gameId??""};Vn.confirm=m=>Eu(ye,m),Vn.confirmAvatar3d=m=>Ou(ye,m),Ba.read=(m,T)=>vl(ye,"players","me",m,{signal:T});let Hm=()=>ae.identity?.channel??"release",Zn=new Tr(ye,Hm),Vm=Mu({player:()=>k.current,subscribe:m=>(P.add(m),()=>{P.delete(m);}),configFamilies:async()=>(await Zn.load())?.avatar_3d_families,readOffers:()=>Gu(ye),purchase:m=>Po.requestAvatar3d(m),log:t.log}),Xa=async m=>(await Zn.load())?.currency(m)?.id??void 0,Ya=Jl(ye,Yo,{identity:Na,resolveCurrencyId:Xa,watch:{clock:e,log:t.log}}),Qa=Ya.scope;Un=Ya.recheckPasses;let er=async m=>{let T=await Ao.wait(m);if(T)return T;throw D.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).")},Mo=c(t.autoReconnect),me=ic(s===void 0?{}:{playWithTicket:s},{client:vt,clock:e,gameId:()=>ae.identity?.gameId??null,playerId:()=>ae.identity?.playerId??null,awaitGameId:async()=>(await er(So)).gameId,resolveParty:ja.resolve,resolveClusterTargets:Jn.resolveList,refreshClusterTargets:Jn.refresh,ensureLocalServer:zn.ensure,localHostAvailable:zn.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},...Mo===null?{}:{autoReconnect:{...Mo,redial:(m,T)=>Oo.redialMatch(m,T),abandon:(m,T)=>Oo.abandonMatch(m,T)}}});g(me),kc({analytics:d,rooms:me});let _t=Sc({client:vt,clock:e,rooms:me,bridge:D,gameId:()=>ae.identity?.gameId??"",baseUrl:()=>b,resolveClusterTarget:Jn.resolve,boot:a,...t.log===void 0?{}:{log:t.log}}),Za=Zi(a,n),Ht=mu({client:vt,clock:e,rooms:me,signaling:()=>$a.channel(),signalingReady:Fm,log:n??(()=>{})}),Oo=Au({rooms:me,p2p:{connect:m=>Za(_t.connect(m)),session:m=>_t.session(m)},dedicated:{connect:(m=>oo(a,"welcome",Ht.connect(m),n))},clock:e,identity:()=>ae.identity,apiBaseUrl:()=>b,tokens:qa,room:()=>me.currentRoom,autoReconnect:Mo!==null,...t.log===void 0?{}:{log:t.log}}),Km=async()=>(await er(So)).playerId,es={client:vt,boot:a,get identity(){return ae.identity},awaitIdentity:(m=So)=>er(m),awaitBridge:m=>D.settled(m),get player(){return k.current},awaitPlayer:(m=s_)=>k.wait(m),me:Qa,characters:new Rr(ye,void 0,Na,Xa),transfers:new xr(ye,Yo,Qa.inventory),gameConfig:Zn,purchases:Po.api,deviceSettings:Kn.api,moments:Wa.api,ads:Ua.api,account:Ha.api,share:qu({frame:D,log:t.log}),arcade:Nm,store:Ka.api,branding:Xu({fetch:typeof window.fetch=="function"?(m,T)=>window.fetch.call(window,m,T):null,clock:e,devicePixelRatio:()=>window.devicePixelRatio??1,log:n}),vibration:Yu({frame:D,log:t.log}),get avatarPickerAvailable(){return D.currentState==="connected"&&D.parentSupports("avatarPicker")},openAvatarPicker:m=>D.requestAvatarPicker(m?.tab),avatars3d:Vm,settings:De.api,controls:tm({recommended:()=>h.current?.recommended??null}),analytics:d,leaderboards:new nn(ye),challenges:new Zt(ye),showcase:new rn(ye,Km),friends:new on(ye,{challenge:Ja.challenge,...i===void 0?{}:{launchedChallengeId:i}}),platform:new sn(ye,I,n),profiles:new ln(ye),functions:new Xe((m,T)=>il(ye,m,T)),get prefs(){return h.current},get paused(){return S},get cohorts(){return C.current},get viewport(){return U.current},awaitCohorts:(m=l_)=>C.wait(m),reportMuted:m=>{x=!!m,F();},showPortraitBorders:m=>{let T=vo(m);T!==void 0&&(B=T,ge());},cueReward:m=>D.cueReward(m),setWalletVisible:(m,T)=>{let L=Array.isArray(T?.only)?[...T.only]:void 0;return X=L===void 0?{visible:m===true}:{visible:m===true,only:L},Se()},setMenu:m=>(fe=Array.isArray(m?.items)?{items:m.items.map(T=>({...T}))}:{},te()),setGemCorner:m=>{if(!n_.includes(m)){let T=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setGemCorner: ${T} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return z=m,jn()},setMenuStyle:m=>{let T=r_(m);return T===void 0?false:(xe=T,Bt())},reportFrame:()=>nt.draw(),exit:m=>d_(me,D,m,d),frame:D,devtools:$e,rooms:me,dedicatedServer:{listClusterTargets:m=>Ht.listClusterTargets(m),connect:(m=>oo(a,"welcome",Ht.connect(m),n)),handleMatchEnded:(m,T)=>Ht.handleMatchEnded(m,T)},p2p:{handleSignalEvent:(m,T,L)=>_t.handleSignalEvent(m,T,L),session:m=>_t.session(m),connect:m=>Za(_t.connect(m))},match:Oo};return es}var Gm="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 Da(t,e={}){let n=e.clock??de,r=()=>{let a=t();if(a===null)throw new Error(Gm);return a},o=null,i=()=>{if(o===null)throw new Error(Gm);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 u=d.displayName;return typeof u!="string"||u===""?null:{displayName:he(u,"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=qt(r(),{...e,clock:n});}}}function Lm(t,e={}){let{server:n,attach:r}=Da(()=>t,e);return r(),n}function c_(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:Ye(e)}}}var u_=1e4;function m_(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout(u_));}catch{return}r.catch(o=>{o instanceof G&&o.status>=400&&o.status<500&&(e=o.status!==429);});}}function Dm(t,e={}){return ()=>{let n=null,{server:r,attach:o}=Da(()=>n,e),i=t(r),s={async init(l){n=l,o(),await i.init?.();},async shutdown(l){let d=c_(l);try{await i.shutdown?.(d);}finally{r.dispose();}}},a=m_(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,u,c)=>i.message?.(l,d,u,c)),s}}is();
3
3
  exports.ARCADE_EMBEDDERS=e_;exports.AVATAR_RIGS=Qv;exports.AnalyticsApi=cn;exports.AuthError=ne;exports.CONDITIONAL_HEADERS=tr;exports.ChallengesApi=Zt;exports.DEVICE_SETTINGS_MAX_BYTES=Ma;exports.DedicatedServerError=w;exports.FriendChallengeError=lt;exports.FriendsApi=on;exports.FunctionsApi=Xe;exports.GemApiError=G;exports.GemClient=He;exports.GemConfigError=pe;exports.GemFrame=Fn;exports.GemFunctionError=dn;exports.GemSaveError=oe;exports.GemUnframedError=$n;exports.LeaderboardsApi=nn;exports.MAX_PERIODS_BACK=nd;exports.PLATFORM_EVENTS=zg;exports.PlatformApi=sn;exports.PlatformCurrenciesApi=Or;exports.PlatformEarnAllowanceApi=Gr;exports.PlayerText=ve;exports.ProfilesApi=ln;exports.PurchaseRefusal=ze;exports.ShowcaseApi=rn;exports.TransportRefusal=se;exports.UNRELIABLE_CHANNEL_LABEL=fn;exports.asPlayerText=he;exports.createBootTimeline=ea;exports.createGem=RE;exports.createGemServer=qt;exports.createHostTokenSource=fu;exports.createMatchServer=Lm;exports.defineServer=Dm;exports.experimentSelection=Dr;exports.leaveAndExit=d_;exports.mapIdentity=Pe;exports.markOnResolve=oo;exports.platformIconUrl=ei;exports.presentJoinCredential=pn;exports.readTemplateTransports=Ct;exports.readTransportAdvert=yn;exports.reportOnResolve=Zi;exports.systemClock=de;exports.text=it;exports.toBase64=nr;exports.webTransportAvailable=Hr;return exports;})({});