@indiegems/gem-web-sdk 13.4.0 → 13.4.1

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 au=Object.defineProperty;var su=(t,e)=>{for(var n in e)au(t,n,{get:e[n],enumerable:true});};var eo="GemWebSdkHandshake";function lu(){return typeof document>"u"?void 0:document.readyState}var aa=()=>Date.now();function sa(t={}){let e=t.win??window,n=e,r=n[eo];if(r!==void 0)return r;let o=t.readyState??lu,i=t.now??aa,s=[],a=[],l=m=>{let u=m.data;!u||u.type!=="gem.handshake"||(s.length>=4&&(s.shift(),a.shift(),d.dropped+=1),s.push(m),a.push(i()));};e.addEventListener("message",l);let d={events:s,times:a,dropped:0,late:o()==="complete",uninstall(){e.removeEventListener("message",l);}};return n[eo]=d,d}function la(t,e,n={}){let r=t[eo];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??aa,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,m=false,u=i()-o;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(s[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:13.4.0]";function da(){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 du={initialDelayMs:2e3,maxDelayMs:6e4};function cu(t,e){return e!==void 0?!e:t==="chain_exhausted"}var ut=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 ee(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 ee("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new ee(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}=du,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 ee("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=uu(o),{retryable:s,retryAfterMs:a}=o??{};throw n===this.generation&&(cu(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 ee?o:new ee(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)}},ee=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 uu(t){if(t instanceof ee)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var oe=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}},Mn=["if-match","if-none-match"],ca=4096;function mu(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!Mn.includes(o)||r===void 0)continue;let i=typeof r=="string"?pu(r):r;if(typeof i!="string"||i.length>ca||!gu(i))throw new oe(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${ca} 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 pu(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 gu(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 yu(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new oe("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new oe("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function ua(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=mu(o.headers),s=yu(o),a=Object.freeze({...o,headers:i,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await t(a,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),u=await t(a,m);if(u.status===401)throw e.tokenSource.close("unavailable"),new ee("unavailable","the server refused a freshly minted token");return u}}}function On(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(fu(e))}function Gn(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 to(t){return new TextDecoder().decode(Gn(t))}function fu(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var M=class extends Error{constructor(n,r,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"}},pa=new WeakMap;function ga(t){return pa.get(t)??{}}var hu=new Set([408,429,500,502,503,504]),bu=6e4;function vu(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new oe(`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 Fe=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,...Gt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...Gt(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,...Gt(o)},o.replaySafe===true,o.retryRateLimited!==false);return {bytes:_u(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,...Gt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Gt(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?vu(this.options.maxRetries)+1:1,i=null;if(e.signal?.aborted)throw ma(e.signal);for(let s=0;s<o;s++){if(s>0&&await this.backoff(s,i,e.signal),e.signal?.aborted)throw ma(e.signal);let a;try{a=await this.options.transport.request(e);}catch(d){if(ee.isAuthError(d)||oe.isRefusal(d)||e.signal?.aborted||wu(d))throw d;i=new M("unavailable",0,String(d));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let l=ku(a);if(!hu.has(a.status)||a.status===429&&!r)throw l;i=l;}throw i??new M("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let o=n?.retryAfterSeconds,i=o!==void 0?o*1e3:2**(e-1)*250,s=2**(e-1)*250,a=Math.min(Math.max(i,s),bu);return new Promise(l=>{let d=this.options.clock,m=false,u=false,p,g=()=>{m||(m=true,u&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,a),u=true,m&&d.clearTimeout(p);})}};function _u(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 Gt(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function ma(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function wu(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function ku(t){let e=Ru(t),n=Au(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&pa.set(e,r),e}var Su=new Map([["insufficient_funds","insufficient_funds"]]);function Ru(t){let{status:e,body:n}=t,r=xu(n),o=t.retryAfterSeconds??Tu(n),i=Pu(n),s=i===void 0?void 0:Su.get(i);if(s!==void 0)return new M(s,e,r,void 0,i);switch(e){case 304:return new M("not_modified",e,r);case 400:case 422:return new M("invalid",e,r,void 0,i);case 403:return new M("forbidden",e,r,void 0,i);case 404:return new M("not_found",e,r,void 0,i);case 402:return new M("insufficient_funds",e,r,void 0,i);case 409:return new M("conflict",e,r,void 0,i);case 412:return new M("precondition_failed",e,r,void 0,i);case 413:return new M("too_large",e,r,void 0,i);case 429:return new M("rate_limited",e,r,o,i);default:return new M("unavailable",e,r,o,i)}}function xu(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 Au(t){let n=t?.error?.details;return n===null?void 0:n}function Pu(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Tu(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}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 ya(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function fa(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 ha(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function ba(t,e,n){let r=`/v1/games/${v(t.gameId())}/matchmaking/tickets/${v(e)}`;return t.client.delete(r,n?.signal)}async function va(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 _a(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function wa(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 ka(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 Sa(t,e,n){let r=`/v1/games/${v(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function Ra(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function xa(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Aa(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(o,r?.signal)}async function Pa(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 Ta(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 Ea(t,e,n){let r=`/v1/games/${v(t.gameId())}/avatars-3d/${v(e)}/owned`;return t.client.get(r,n?.signal)}async function Ia(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 Ca(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.get(r,n?.signal)}async function Ma(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Oa(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 Ga(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 La(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 Da(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 $a(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 Fa(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 qa(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 Na(t,e,n,r){let o=new URLSearchParams;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 no(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 ja(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)}/friends`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Ua(t,e,n){let r=`/v1/showcase/friends/${v(e)}`;return t.client.get(r,n?.signal)}async function Ba(t,e){let n=`/v1/games/${v(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function Wa(t,e,n){let r=`/v1/inbox/friend-challenges/${v(e)}`;return t.client.get(r,n?.signal)}async function Ha(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 Va(t,e){let n=`/v1/games/${v(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function Ln(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Ka(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function Ja(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 za(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${v(e)}`;return t.client.get(r,n?.signal)}async function Ya(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function Qa(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function Xa(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function Za(t,e,n){let r=`/v1/games/${v(t.gameId())}/matchmaking/tickets/${v(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function es(t,e,n){let r=`/v1/games/${v(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 ts(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ns(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/platform-funded-game-inventory-purchases`;return t.client.post(i,r,o?.signal)}async function rs(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function os(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 is(t,e){return t.client.get("/v1/characters",e?.signal)}async function as(t,e,n,r){let o=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function ss(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 ls(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 ds(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 cs(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 us(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 ms(t,e,n){let r=`/v1/inbox/friend-challenges/${v(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function ps(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/matches/${v(e)}/end`;return t.client.post(o,n,r?.signal)}async function gs(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 ys(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 fs(t,e,n,r,o){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(i,r,o?.signal)}async function hs(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/rewarded-placements/${v(r)}/availability`;return t.client.get(i,o?.signal)}async function bs(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function vs(t,e,n,r){let o=`/v1/characters/${v(e)}`;return t.client.patch(o,n,r?.signal)}async function _s(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 ws(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 ks(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.delete(r,n?.signal)}var U="gem-web-bridge",$n={min:1,max:1},mt=65536,Ss=8,Dn=5e3,Rs=1024;var Lt=Object.create(null),Fn="__malformed";var oo=Object.create(null),Eu=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"]]);function xs(t){let e=oo[t];if(e!==void 0)return e;for(let[n,r]of Eu)if(t.startsWith(n))return r}function io(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 Iu(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 Cu(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Mu(t){return /^[a-z_]+$/.test(t)}function ro(t,e,n){if(e>Ss)return `nesting deeper than ${Ss}`;if(++n.nodes>Dn)return `more than ${Dn} values`;if(n.bytes>mt)return `over the ${mt} 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>Rs)return `an array of ${t.length} entries, over the ${Rs} limit`;n.bytes+=2;for(let a of t){let l=ro(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>Dn)return `more than ${Dn} values`;if(n.bytes+=a.length*3+4,n.bytes>mt)return `over the ${mt} byte limit`;let l=ro(s[a],e+1,n);if(l)return l}return null}function Ou(t){let e={nodes:0,bytes:0,seen:new Set},n=ro(t,0,e);return n?`message contains ${n}`:e.bytes>mt?`message is over the ${mt} byte limit`:null}var Gu={origin:[io,"not a well-formed origin"],url:[Iu,"not a safe absolute http(s) URL"],bcp47:[Cu,"not a well-formed BCP 47 tag"],code:[Mu,"not a code of lower-case letters and underscores"]};function As(t,e,n){for(let r of e){let o=n===""?r.n:`${n}.${r.n}`,i=t[r.n];if(i==null){if(r.o)continue;return `${o}: required`}let s=Ps(i,r,o);if(s)return s}return null}function Ps(t,e,n){switch(e.k){case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e.max)return `${n}: exceeds ${e.max} characters`;if(e.f){let[r,o]=Gu[e.f];if(!r(t))return `${n}: ${o}`}return null}case "i":return typeof t!="number"||!Number.isInteger(t)?`${n}: expected integer`:t<e.lo||t>e.hi?`${n}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let r=e.v;return r.includes(t)?null:`${n}: not one of ${r.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:As(t,e.fs,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.max)return `${n}: exceeds ${e.max} items`;let r=e.it,o=`${n}[]`;for(let i of t){if(i==null){if(r.o)continue;return `${o}: required`}let s=Ps(i,r,o);if(s)return s}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}var Ts=Object.create(null);function P(t,e,n,r){return Lt[t]=n,r&&(oo[t]=r),Ts[t]=o=>{let i=Ou(o);if(i)return i;if(typeof o!="object"||o===null||Array.isArray(o))return "message: expected object";let s=o;return s.gem!==U?"gem: wrong protocol marker":s.type!==t?`type: expected ${t}`:As(s,e,"")}}P("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}],30);P("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}],5);P("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}],30);P("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}],30);P("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"avatar3dId",k:"s",o:1,max:64},{n:"avatar3dModelUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatar3dIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatars3d",k:"a",o:1,max:8,it:{n:"",k:"o",fs:[{n:"family",k:"s",max:32},{n:"id",k:"s",max:64},{n:"modelUrl",k:"s",max:256,f:"url"},{n:"iconUrl",k:"s",max:256,f:"url"}]}},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}],12);P("gem.pause",[{n:"paused",k:"b"}],120);P("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"},{n:"graphicsQuality",k:"s",o:1,max:16,f:"code"},{n:"graphicsQualityAuto",k:"b",o:1}]}],60);P("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}],12,"cohorts");P("gem.earnAllowanceChanged",[],30,"earnAllowance");P("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384},{n:"control",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}]}}],60,"viewport");P("gem.deviceSettings",[{n:"settings",k:"j",o:1}],12,"deviceSettings");P("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}],10);P("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}],120,"rooms");P("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}],12,"socketState");P("gem.seatedEvent",[{n:"roomId",k:"s",max:64}],60,"partySeating");P("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}],30,"autoStartFailure");P("gem.ticketEvent",[{n:"event",k:"e",v:["queued","matched","expired","cancelled","failed"]},{n:"ticketId",k:"s",max:64},{n:"partySize",k:"i",o:1,lo:1,hi:64},{n:"queuedAt",k:"i",o:1,lo:0,hi:4102444800},{n:"expiresAt",k:"i",o:1,lo:0,hi:4102444800},{n:"reason",k:"s",o:1,max:64},{n:"roomId",k:"s",o:1,max:64}],60,"ticketEvents");P("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1800,"p2p");P("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}],120,"dedicated");P("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}],30,"parties");P("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}],12,"clusterTarget");P("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}],30,"devtools");P("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}],6,"screenshot");P("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}],12,"screenshot");P("gem.requestContext",[],12,"feedbackContext");P("gem.gameContext",[{n:"context",k:"j"}],12,"feedbackContext");P("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1200,"p2p");P("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}],60,"dedicated");P("gem.partyRequest",[{n:"requestId",k:"s",max:64}],12,"parties");P("gem.ready",[],5);P("gem.engaged",[],5,"engagement");P("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}],600);P("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}],12);P("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}],6,"localHost");P("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}],30,"localHost");P("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}],30,"localHost");P("gem.exit",[{n:"reason",k:"s",o:1,max:64}],5);P("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}],6);P("gem.requestFullscreen",[{n:"enabled",k:"b"}],30);P("gem.audioState",[{n:"muted",k:"b"}],120,"audioState");P("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}],60,"rewardCue");P("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}],60,"walletDisplay");P("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}],60,"controls");P("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}],60,"gameMenu");P("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}],60,"gameMenu");P("gem.gemCorner",[{n:"corner",k:"e",v:["top-left","top-right","bottom-left","bottom-right"]}],12,"gemCorner");P("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}],6,"share");P("gem.requestAvatarPicker",[{n:"tab",k:"e",o:1,v:["2d","3d"]}],6,"avatarPicker");P("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}],600,"vibration");P("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5},{n:"counts",k:"e",o:1,v:["pageFrames","gameDraws"]}],120,"frameStats");P("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}],60,"portraitBorders");P("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}],60);P("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}],12,"purchases");P("gem.requestAvatar3dPurchase",[{n:"requestId",k:"s",max:64},{n:"itemId",k:"s",max:64},{n:"currencySlug",k:"s",max:32}],12,"avatar3dPurchases");P("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}],30,"purchases");P("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}],30,"deviceSettings");P("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}],30,"deviceSettings");P("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}],6,"ads");P("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}],12,"ads");P("gem.signalMoment",[{n:"requestId",k:"s",max:64},{n:"kind",k:"e",v:["level_end","run_end","match_end","menu_return","other_break"]},{n:"placement",k:"s",o:1,max:32}],6,"moments");P("gem.momentResult",[{n:"requestId",k:"s",max:64},{n:"shown",k:"b"}],12,"moments");P("gem.requestSignIn",[{n:"requestId",k:"s",max:64}],6,"signIn");P("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}],12,"signIn");P("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}],12,"friendChallenges");P("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}],30,"friendChallenges");var qn=Object.freeze(Ts);Lt.__malformed=60;Object.freeze(Lt);Object.freeze(oo);var ue={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Dt=class{constructor(e=ue){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Lt[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 ao(t,e){return t.toLowerCase()===e.toLowerCase()}function pt(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Es(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:pt(n.hostname)&&pt(r.hostname)}function Is(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 Nn=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let o=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,i=o.find(a=>a.currencyId===e),s;return !i&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(i=o.find(a=>a.currencyId===s))),{currencyId:i?i.currencyId:s??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function lo(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let o=r??{};typeof o.id!="string"||o.id===""||typeof o.threshold!="number"||!Number.isFinite(o.threshold)||n.push({id:o.id,threshold:o.threshold,points:typeof o.points=="number"?o.points:0,hidden:o.hidden===true,...typeof o.unlocked_at=="number"&&Number.isFinite(o.unlocked_at)?{unlockedAt:o.unlocked_at}:{},...o.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var Cs="inventory",gt=t=>typeof t=="number"?t:0,$t=t=>typeof t=="string"?t:"";function so(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 Ms(t){let e=t??{};return {itemDefinitionId:$t(e.item_definition_id),instanceId:$t(e.instance_id),quantity:gt(e.quantity),acquiredAt:gt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function Lu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:so(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(s=>{let a=s??{};return {bucket:$t(a.bucket),balance:gt(a.balance)}}):void 0;return {currencyId:$t(o.currency_id),total:gt(o.total),...i===void 0?{}:{buckets:i}}}),items:so(e.items,Ms),progressions:so(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:$t(o.progression_definition_id),currentValue:gt(o.current_value),completionCount:gt(o.completion_count),isCompleted:o.is_completed===true,...lo(o)}}),...n===void 0?{}:{etag:n}}}var jn=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Cs}#buckets`:Cs;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 La(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(Ms):[]}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 Ga(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 Lu(n)}};var Du={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},$u=new Set(Object.keys(Du));function Os(t){return typeof t=="string"&&$u.has(t)?t:"error"}var qe=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var te=t=>typeof t=="string"?t:"",Fu=t=>typeof t=="string"?t:te(t&&typeof t=="object"?t.type:void 0),Ee=t=>typeof t=="number"?t:0;function qu(t){let e=t??{};return {prerequisiteType:te(e.prerequisite_type),referenceId:te(e.reference_id),required:Ee(e.required),current:Ee(e.current)}}function Ft(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:te(e.order_id),status:te(e.status),...n===void 0?{}:{etag:n}}}function Un(){return crypto.randomUUID()}var Nu="recipe-usage",Gs=100;function Bn(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:te(e.currency_id),bucket:te(e.bucket),delta:Ee(e.delta),balanceAfter:Ee(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:te(e.item_definition_id),instanceId:te(e.instance_id),delta:Ee(e.delta),quantityAfter:Ee(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:te(e.progression_definition_id),delta:Ee(e.delta),valueAfter:Ee(e.value_after),completed:e.completed===true};default:return {kind:"other",type:te(e.type)}}}function ju(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:te(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(Bn):[]}}function Uu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(ju):void 0;return {orderId:te(e.order_id),status:te(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(Bn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(Bn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(Bn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Bu(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:te(e.target_order_id)||te(e.source_order_id),status:te(e.status),purchaseId:te(e.purchase_id),sourceOrderId:te(e.source_order_id),price:{currencyId:te(n.platform_currency_id),amount:Ee(n.price)}}}function Wu(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:te(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 Ls(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 Wn=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(()=>ka(this.api,this.entity.type,this.entity.id,{operations:e.map(Ls),source:n.source??"play",nonce:Un()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Ft(r)}async createMany(e,n={}){return this.write(()=>wa(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Ls),nonce:Un()})),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 qa(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(qu):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>Fu(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(Nu,[],async()=>{let n=await Na(this.api,this.entity.type,this.entity.id,{limit:Gs})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(Wu),truncated:r.length>=Gs}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let u=e,p=await this.write(()=>Pa(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:Un()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...Uu(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,o]=await Promise.all([Ja(this.api,n.signal===void 0?{}:{signal:n.signal}),Ln(this.api,n.signal===void 0?{}:{signal:n.signal})]),i=e.payment.currencySlug.toLowerCase(),s=o.currencies.find(u=>u.currency_id.toLowerCase()===i||u.slug.toLowerCase()===i);if(s===void 0){let u=o.currencies.map(p=>p.slug);throw new qe("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let a=e.kind==="item"?r.items.find(u=>u.item_id===e.targetId):r.recipes.find(u=>u.recipe_id===e.targetId&&u.catalog_id===e.catalogId);if(a===void 0)throw new qe("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=a.platform_prices.find(u=>u.platform_currency_id===s.currency_id);if(l===void 0){let u=g=>o.currencies.find(y=>y.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new qe("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new qe("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>ns(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:Un(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return Bu(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let o=await this.write(()=>fa(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Ft(o)}async maxProgression(e,n,r){let o=await this.write(()=>gs(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Ft(o)}async claimProgression(e,n){let r=await this.write(()=>va(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Ft(r)}async resetProgression(e,n){let r=await this.write(()=>ws(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Ft(r)}async write(e){return this.cache.invalidate(),e()}};var co=t=>typeof t=="string"?t:"",Hu=t=>typeof t=="number"?t:0;function Ds(t){let e=t??{};return {orderId:co(e.order_id),status:co(e.status),source:co(e.source),createdAt:Hu(e.created_at)}}var Hn=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await ss(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(Ds):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await $a(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Ds(r)}};var $s=t=>typeof t=="number"?t:0,Vu=t=>typeof t=="string"?t:"";function Ku(t){let e=t??{};return {progressionDefinitionId:Vu(e.progression_definition_id),currentValue:$s(e.current_value),completionCount:$s(e.completion_count),isCompleted:e.is_completed===true,...lo(e)}}var Vn=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 Fa(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Ku(i)}catch{return o??null}}};var Kn=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 u=a.filledAt;if(u!==void 0&&(o===void 0||this.clock.now()-u<=o))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,m=r().then(u=>(i&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function uo(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 mo(t){try{let e=uo(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var se=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},Ju=3e4,Fs="the save payload could not reach storage. From a browser this is almost always the storage account's CORS rule, which the platform owns and your game cannot change. If every save fails this way, report it rather than working around it",zu=/^[A-Za-z0-9_]{1,64}$/;function Ie(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(!zu.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function qs(t,e){let n=new AbortController,r=AbortSignal.timeout(e),o=()=>n.abort(r.reason),i=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",i,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",o),t?.removeEventListener("abort",i);}}}function po(t,e){return t.aborted&&e?.aborted!==true}var Yu=new Set(["x-ms-blob-type"]),Qu=/^[ -~]+$/;function Xu(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new se("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(!Yu.has(i))throw new se("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"||!Qu.test(o))throw new se("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 se("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function go(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 yo(t){return t?.reason==="not_found"}var Jn=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let o;try{o=JSON.stringify(n);}catch(i){throw new se("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 se("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),s=qs(r.signal,i);try{let a=await _s(this.api,this.entity.type,this.entity.id,Ie(e),{size_bytes:n.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:s.signal});if(typeof a.upload_url!="string"||typeof a.session_id!="string")throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=Xu(a.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(a.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:n,credentials:"omit",signal:s.signal});}catch(u){throw po(s.signal,r.signal)?this.timeout("upload",i):new se("upload_failed",`${Fs} for PUT. Underlying error: ${u}`)}if(!d.ok){let u=await mo(d);throw new se("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+u:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+u)}return go(await Ta(this.api,this.entity.type,this.entity.id,Ie(e),{session_id:a.session_id},{signal:s.signal}))}catch(a){throw this.rethrow(a,r.signal,s.signal,"save",i)}finally{s.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new se("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${o}`)}}async getBytes(e,n={}){let r=this.budget(n.timeoutMs),o=qs(n.signal,r);try{let i;try{let l=await no(this.api,this.entity.type,this.entity.id,Ie(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(yo(l))return null;throw l}if(typeof i.download_url!="string")throw new se("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let s=this.options.fetch??globalThis.fetch.bind(globalThis),a;try{a=await s(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw po(o.signal,n.signal)?this.timeout("download",r):new se("download_failed",`${Fs} for GET. Underlying error: ${l}`)}if(!a.ok){let l=await mo(a);throw new se("download_failed",`the save download answered ${a.status}. `+(a.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await a.arrayBuffer())}catch(i){throw this.rethrow(i,n.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,n={}){try{let r=await no(this.api,this.entity.type,this.entity.id,Ie(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?go(r.body):null}catch(r){if(yo(r))return null;throw r}}async list(e={}){let n=await ls(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(go),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await xa(this.api,this.entity.type,this.entity.id,Ie(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!yo(r))throw r}}budget(e){return e??this.options.timeoutMs??Ju}timeout(e,n){return new se("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof se?e:po(r,n)?this.timeout(o,i):e}};function Zu(t){try{return to(t)}catch{return t}}function fo(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"?Zu(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var zn=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await as(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>fo(o)):[]}async get(e,n={}){try{let r=await Oa(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?fo(r.body,r.etag):null}catch(r){if(Ns(r))return null;throw r}}async put(e,n,r={}){let o=await ys(this.api,this.entity.type,this.entity.id,e,{value:On(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return fo(o)}async delete(e,n){try{await Ra(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!Ns(r))throw r}}};function Ns(t){return t?.reason==="not_found"}function Yn(t,e,n={}){let r=new Kn(ue,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new jn(t,e,r);return {settings:new zn(t,e),inventory:o,saves:new Jn(t,e,n.saves??{}),currencies:new Nn(o,n.resolveCurrencyId),mutations:new Wn(t,e,r),orders:new Hn(t,e),progressions:new Vn(t,e,o)}}var ho={type:"players",id:"me"};var ze=t=>typeof t=="string"?t:"",yt=t=>typeof t=="number"?t:0;function Qn(t,e){let n=e??{},r=ze(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:ze(n.player_id),gameId:ze(n.game_id),channel:ze(n.channel)||"release",name:ze(n.name),slotIndex:yt(n.slot_index),isActive:n.is_active!==false,createdAt:ze(n.created_at),updatedAt:ze(n.updated_at)}}var Xn=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=Yn(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 is(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>Qn(this.scope,o)):[]}async get(e,n){let r=await Ca(this.api,e,n===void 0?{}:{signal:n});return Qn(this.scope,r)}async create(e){let n=await _a(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Qn(this.scope,n)}async update(e,n,r){let o=await vs(this.api,e,{name:n},r===void 0?{}:{signal:r});return Qn(this.scope,o)}async delete(e,n){await ks(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await Qa(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:yt(r?.total_slots),availableSlots:yt(r?.available_slots),activeCharacterCount:yt(r?.active_character_count),defaultMaxSlots:yt(r?.default_max_slots),purchasedExtraSlots:yt(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var Bs="[gem: use gem.text.toPlain()]",js=new Set,Us;function em(t){try{if(js.has(t))return;let e=globalThis.location;if(Us??=!!e?.port&&pt(e.hostname??""),!Us)return;js.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${Bs}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
2
- ${new Error().stack}`);}catch{}}var he=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return em(this.#n),Bs}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function be(t,e){return new he(t,e)}var Ye={toPlain(t){return he.unwrap(t)},compare(t,e,n){let r=t instanceof he?he.unwrap(t):t,o=e instanceof he?he.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 he?he.unwrap(t):t,r=e instanceof he?he.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var ft=t=>typeof t=="string"?t:"";function Zn(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:ft(e.transfer_id),status:ft(e.status),sourceEntityId:ft(e.source_entity_id),targetEntityId:ft(e.target_entity_id),...n===void 0?{}:{message:be(n,"transfer.message")},createdAt:ft(e.created_at),expiresAt:ft(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function tm(){return crypto.randomUUID()}var er=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 ts(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:tm()},e.signal===void 0?{}:{signal:e.signal});return Zn(n)}async list(e={}){let r=await us(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(Zn):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Xa(this.api,e,n===void 0?{}:{signal:n});return Zn(r)}async accept(e,n){return this.resolve(()=>ya(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>bs(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>ha(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Zn(await e())}};var nm=t=>typeof t=="string"?t:"",rm=t=>typeof t=="string"&&t?t:void 0,om=t=>typeof t=="number"?t:void 0;function Ws(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 im(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=om(e.version);if(r===void 0)throw new pe("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let u=nm(l.id);if(!u)throw new pe("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},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:Ws(i),currency:Ws(s)}}var pe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Hs=10*1024*1024,Vs=15e3,Ks=new Set(["dev","test","release"]);function am(t){if(!Ks.has(t))throw new pe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Ks].join(", ")}. gem-api would reject the assignment read.`);return t}var tr=t=>typeof t=="number"?t:0,bo=t=>typeof t=="string"?t:"";function sm(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:bo(o.entry_id),weight:tr(o.weight),dropRate:tr(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:bo(e.loot_table_id),name:bo(e.name),rollCount:tr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:tr(e.total_weight),entries:n}}var nr=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 Ma(this.api,e,n===void 0?{}:{signal:n});return sm(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??Vs),n;try{let l=await Ia(this.api,am(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=rm(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??Vs}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=>uo(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>Hs)throw new pe("config_too_large",`the config document is ${s.length} bytes, over the ${Hs} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new pe("config_malformed",`config document is not JSON: ${String(l)}`)}return im(a)}};var Js=400,Ce=t=>typeof t=="string"?t:"",lm=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Qe(t){let e=Ce(t);if(!lm.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var dm=/^[0-9a-f]{1,64}$/,cm=/^[0-9a-f]{16}$/,um=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,mm=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function vo(t){let e=Ce(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 pm=4096,gm=new TextEncoder;function ym(t){let e=Ce(t.challenge_data),n=Ce(t.challenge_data_hash);return e===""||!cm.test(n)?{}:gm.encode(e).length>pm?{}:{data:e,dataHash:n}}function fm(t){let e=t??{},n=Qe(e.period_start_at),r=Qe(e.period_ends_at);if(n===0||r===0)return;let o=Ce(e.slug),i=Ce(e.seed),s=vo(e.period_local_date),a=Ce(e.boundary),l=Ce(e.reset_time);return {id:Ce(e.progression_definition_id),...o===""?{}:{slug:o},window:Ce(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:um.test(a)?a:"",resetTime:mm.test(l)?l:"",seed:dm.test(i)?i:"",...ym(e)}}function ht(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function rr(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(fm).filter(n=>n!==void 0):[]}var qt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;ht(n);let r=await os(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return rr(r)}};function Me(t){return typeof t=="string"&&t!==""?t:void 0}var zs=new Set(["localhost","127.0.0.1","[::1]"]);function Xe(t){return or(t)}function or(t){let e=Me(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&zs.has(n.hostname)))return e}var hm=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,bm=/^[a-z][a-z0-9_]{0,31}$/;function vm(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let o=r??{},i=Me(o.family),s=Me(o.avatar_3d_id),a=Xe(o.model_url),l=Xe(o.icon_url);i===void 0||!bm.test(i)||n.has(i)||s===void 0||!hm.test(s)||a===void 0||l===void 0||(n.add(i),e.push({family:i,id:s,modelUrl:a,iconUrl:l}));}return e}function _m(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=Me(r.item_id),i=Xe(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function Ae(t){let e=t??{},n=Me(e.player_id),r=Me(e.display_name),o=Me(e.discriminator),i=Me(e.display_tag),s=Me(e.avatar_icon_id),a=Xe(e.avatar_icon_url),l=Me(e.avatar_3d_id),d=Xe(e.avatar_3d_model_url),m=Xe(e.avatar_3d_icon_url),u=vm(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:be(r,"displayName")},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:be(i,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...m===void 0?{}:{avatar3dIconUrl:m},...u===void 0?{}:{avatars3d:u},badges:_m(e.badges)}}var wm=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function km(t){if(t===void 0)return;let e=Xe(t);if(e===void 0)return;let n=new URL(e);return zs.has(n.hostname)||wm.has(n.origin)?e:void 0}var Ys=100,Zs=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function _o(t){let{periodsBack:e,period:n,playerId:r}=t;if(ht(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!Zs.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 el(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!Zs.test(e))return;let n=vo(t.period_local_date),r=Qe(t.period_start_at),o=Qe(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:Qe(t.opens_at),closesAt:Qe(t.closes_at),final:t.final===true}}var Nt=t=>typeof t=="string"?t:"",bt=t=>typeof t=="number"?t:0,jt=t=>typeof t=="string"?t:void 0,Sm=t=>typeof t=="number"?t:void 0,tl={player:"players",character:"characters"};function Rm(t,e){let n=t??{},r=jt(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(tl,n.entity_type)?n.entity_type:void 0,i=nl(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...Ae(n),rank:bt(n.rank),occurredAt:bt(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 Qs(t,e){let n=t??{},r=jt(n.bucket_1),o=jt(n.bucket_2),i=Sm(n.update_frequency_seconds),s=el(n);return {leaderboardType:Nt(n.leaderboard_type),runType:Nt(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(a=>Rm(a,e)):[],generatedAt:bt(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...s===void 0?{}:{period:s}}}function Xs(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=nl(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:bt(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function nl(t){if(t===null||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t))typeof r=="number"&&(e[n]=r);return e}function xm(t,e,n){let r=t??{},o=jt(r.bucket_1),i=jt(r.bucket_2),s=el(r);return {leaderboardType:Nt(r.leaderboard_type),runType:Nt(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(Xs).filter(a=>a!==void 0):[],personalBest:Xs(r.personal_best)??null,totalRuns:bt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:bt(r.generated_at),...s===void 0?{}:{period:s}}}var Ut=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=_o(n),o=await Ha(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 Qs(o,false)}async friends(e,n={}){let r=_o(n),o=await ja(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 Qs(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>Ys)throw new TypeError(`limit must be an integer between 1 and ${Ys}, got ${String(l)}`)}let i=_o(o),s=await Da(this.#e,e,tl[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"&&Nt((s??{}).entity_id)||r;return xm(s,n,a)}};var ir=t=>typeof t=="string"?t:"",wo=t=>typeof t=="number"?t:0;function rl(t){let e=t??{};return {playerId:ir(e.player_id),key:ir(e.key),value:e.value,updatedAt:wo(e.updated_at)}}function Am(t){let e=t??{};return {...Ae(e),playerId:ir(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:wo(e.updated_at)}}function Pm(t){return t?.reason==="not_found"}var Bt=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await Ua(this.api,Ie(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:ir(o.key),entries:Array.isArray(o.entries)?o.entries.map(Am):[],generatedAt:wo(o.generated_at)}}async of(e,n,r={}){try{return rl(await Ya(this.api,e,Ie(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(Pm(o))return null;throw o}}async set(e,n,r={}){if(Ie(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 rl(await fs(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Aa(this.api,r,Ie(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var Tm="gemChallenge",ol=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function il(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(Tm)??void 0}catch{return}}var Ze=class extends M{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});}},ar=t=>typeof t=="string"?t:void 0;function al(t){let e=t??{};return {...Ae(e),playerId:ar(e.player_id)??""}}function sl(t){let e=t.has_more===true?ar(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function Em(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(al):[],...sl(e)}}var ko=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Im(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 ll(t){let e=t??{},n=ko(e.opened_at),r=ko(e.answered_at);return {id:ar(e.item_id)??"",from:al(e.sender),template:ar(e.template)??"",params:Im(e.params),createdAt:ko(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function Cm(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(ll):[],...sl(e)}}function Mm(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Wt=class{#e;#n;#i;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#i=n.launchedChallengeId;}async list(e={}){let n=await cs(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Em(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await ds(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Cm(n)}async launchedChallenge(e={}){let n=this.#i;if(n===void 0||!ol.test(n))return null;try{return ll(await Wa(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(Mm(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!ol.test(e))throw new M("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await ms(this.#e,e);}};var Om=0;function we(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++Om)}-${String(Date.now())}-${t}`}}var Gm=12e4,dl=8,Lm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Dm=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Ht(t,e,n={}){return new Ze(new M("invalid",400,e,void 0,t),n)}function $m(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Fm(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!Lm.test(e))return {error:Ht("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!Dm.test(n))return {error:Ht("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(!$m(r))return {error:Ht("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:Ht("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return i.length>dl?{error:Ht("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(dl)}`)}:{playerId:e,template:n,params:o}}function qm(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 Ze(new M("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new Ze(new M("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function Nm(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function cl(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=Fm(n);if("error"in r)return Promise.reject(r.error);let o=`challenge-${we()}`;return new Promise((i,s)=>{let a={},l=m=>{e.delete(o)&&(t.clock.clearTimeout(a.timer),"error"in m?s(m.error):i(m.outcome));};e.set(o,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??Gm);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 (${Nm(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(qm(n));}}}var sr=t=>typeof t=="string"?t:void 0;function jm(t){let e=t??{},n=sr(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:sr(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var lr=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await Ln(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=jm(i);s!==void 0&&o.push(s);}return o}},So=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function Um(t){let e=t??{},n=sr(e.currency_id);if(n===void 0||n==="")return;let r=So(e.limit),o=Math.min(So(e.earned),r),i=Math.min(So(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:sr(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 ul(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 dr=class{#e;#n;#i;constructor(e,n,r){this.#e=e,this.#n=n,this.#i=r;}async get(e={}){let r=(await Va(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=Um(i);s!==void 0&&o.push(s);}return o}on(e,n){return e!=="changed"?(this.#i?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},Vt=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new lr(e),this.earnAllowance=new dr(e,n,r);}};var Ro=t=>typeof t=="string"?t:"",ml=t=>typeof t=="number"?t:0;function Bm(t){let e=t??{};return {key:Ro(e.key),visibility:Ro(e.visibility),value:e.value,updatedAt:ml(e.updated_at)}}function Wm(t){let e=t??{};return {...Ae(e),playerId:Ro(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Bm):[],generatedAt:ml(e.generated_at)}}function Hm(t){return t?.reason==="not_found"}var Kt=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return Wm(await Ka(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Hm(r))return null;throw r}}};var Vm=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]]),Jt=class extends M{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:Vm.get(this.code))??super.retryable}},Ne=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Km(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof M?zm(i):i}return Jm(o)}};function Km(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 oe(`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 oe(`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 Jm(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 zm(t){let{details:e,invocationId:n}=ga(t),o=e?.untrusted?.message,i=e?.reason;return new Jt(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 cr(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 Ym=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],xo="gem_";function pl(t){return t.startsWith(xo)}var gl=1e4,yl=50,Qm=500,Xm=65536-4*1024,Zm=24*1024;function fl(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 hl=t=>typeof t=="number"?t:0,ep=t=>typeof t=="string"?t:"";function ur(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function tp(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:hl(i.index),code:ep(i.code)}}):[];return {accepted:hl(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Ao(){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 np(t){return t?.retryable===true}var zt=class{#e;#n;#i;#f;#t=[];#h={};#a=0;#s=null;#b=false;#v=false;#m=0;#_=0;#w=0;#r=false;#k=null;#l=null;#c=false;#o=false;#p=false;#S=false;#R=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#i=Math.max(gl,e.options?.flushIntervalMs??gl),this.#f=Math.max(1,Math.floor(e.options?.maxQueue??Qm));}track(e,n={}){if(!(!this.#n||this.#r)){if(pl(e)){this.#R||(this.#R=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.#x(e,fl({...this.#h,...n}));}}setContext(e){this.#h={...this.#h,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return ur();let n=this.#C();if(n===null||n==="")return this.#t.length>0&&!this.#S&&(this.#S=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.")),ur();if(this.#P(),this.#t.length===0)return ur();let r=e.keepalive===true;if(this.#m>0&&!r)return ur();this.#u();let o=this.#t.splice(0,this.#E(r)),i=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:Ao(),sent_at_ms:s,events:o.map(d=>bl(d,s))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await es(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=tp(d,i);return this.#_=0,this.#w=0,this.#I(m),m}catch(d){throw np(d)?(this.#T(o,i),this.#_+=1,this.#w=this.#e.clock.now()+cr(this.#_,d)):this.#y(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#m-=1,this.#t.length>0&&this.#d();}}trackPlatform(e,n={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#x(e,fl(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:Ao(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=yl?this.#g():this.#t.length>0&&this.#d();}get held(){return this.#o}startSession(){if(!(this.#r||this.#l!==null)){if(this.#o){this.#p=true;return}this.#l=this.#e.clock.now(),this.#c=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#c)return;if(this.#c=true,this.#o){this.#p=false,this.#t=[],this.#a=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#g({keepalive:true});}setPaused(e){this.#r||e===this.#b||(this.#b=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#v||(this.#v=e,e?this.#u():this.#t.length>0&&this.#d());}dispose(){this.#r=true,this.#u(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#x(e,n){let{dimensions:r,measures:o}=n;for(this.#P();this.#t.length>=this.#f;)this.#t.shift(),this.#a+=1;this.#t.push({uid:Ao(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=yl?this.#g():this.#d();}#g(e={}){if(e.keepalive!==true&&this.#A()>0){this.#d();return}this.flush(e).catch(()=>{});}#A(){return Math.max(0,this.#w-this.#e.clock.now())}#T(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#f;)this.#t.shift(),this.#a+=1;}#E(e){let n=e?Zm:Xm,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(bl(s,0)).length+1,o>n)return Math.max(1,i)}return r}#d(){this.#s!==null||this.#b||this.#v||this.#o||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#g();},Math.max(this.#i,this.#A())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#P(){let e=this.#M();e===null||e===""||(this.#k!==null&&this.#k!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#k=e);}#I(e){for(let n of e.rejected)this.#y(`[gem] analytics: an event was refused (${n.code}). `+rp(n.code));}#y(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#C(){try{return this.#e.gameId()}catch{return null}}#M(){try{return this.#e.playerId()}catch{return null}}};function bl(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function rp(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 fe(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function Yt(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=fe(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var op=2e3,ip=5e3;function _l(t){let e=[],n=false,r=null,o=new Map,i=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,m=null;s=u=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(u));},m=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??op);});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 !vl(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=m=>{o.delete(d)&&(t.clock.clearTimeout(l),a(m));};o.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??ip);})},accept(s,a){let l=Yt(a),d=fe(s),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...o])vl(m,p)||u(m);}}}}function vl(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var ap=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=ap.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var wl=["explicit","stale_cleanup","game_room_closed","replaced","migration_failed","host_left","insufficient_players","all_left","expired","migration_rate_exceeded","game_room_gone","failed","idle","reclaimed"],sp=new Set(wl);function je(t){return typeof t=="string"&&sp.has(t)?t:"unknown"}var mr="webrtc_dedicated",Io=["universal","mobile","web"];var lp="p2p_unavailable",dp="capacity_unavailable",cp=2,kl=3e4,Sl=1e3,Rl=2e4;async function Co(t){let e=fe(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??ue,i=t.retry??{},s=i.budgetMs??kl,a=i.maxDelayMs??Rl,l=i.initialDelayMs??Sl,d=o.now(),m=d+s,u=0;for(;;){u++;try{let p=await Lo(t.signal,"while allocating",()=>t.client.post(`${Pl(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!up(p)||s<=0)throw p;if(p.status===503&&p.code===lp)throw new w("p2p_unavailable",`room ${t.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});if(r=p.code===dp?r+1:0,n!==void 0&&r>=cp){let x=n;n=void 0;let C=fe(await x());C!==void 0&&(e=C,r=0);}let g=Math.min(a,l*2**(u-1)),y=Math.min(a,(p.retryAfterSeconds??0)*1e3),S=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+S>m)throw mp(t,p,u,o.now()-d,s);if(i.onWaiting?.({attempt:u,elapsedMs:o.now()-d,budgetMs:s,nextAttemptInMs:S,status:p.status,message:p.message}),await pr(o,S,t.signal),t.signal?.aborted)throw Eo("while waiting to allocate")}}}function up(t){return t instanceof M?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function mp(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 pp=12e4,gp=1e3;async function Mo(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??gp,o=t.timeoutMs??pp,i=e.now()+o,s=xl(t),a={seen:t.knownToExist===true};for(;;){let l=await Al(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 pr(e,r,t.signal);}}async function Oo(t){return (await Al(t,xl(t),{seen:t.knownToExist===true})).outcome}function xl(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Pl(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Al(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await Lo(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof M&&s.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(n.seen=true,i.status==="ready")return {status:"ready",outcome:yp(r,i,o)};if(i.status==="failed"){let s=i.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:je(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function Go(t){let e=await Lo(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 Lo(t,e,n){if(t?.aborted)throw Eo(e);try{return await n()}catch(r){throw t?.aborted?Eo(e,r):r}}function Eo(t,e){return new w("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function yp(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 Pl(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function pr(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 Tl(t){return typeof t=="string"&&t.trim()!==""}function gr(t,e){return Tl(t)?t.trim():Tl(e)?e:null}var yr="0.1.0-beta",El="0-beta",vt="web",fp=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;function hp(t){let e=fp.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Il(t,e){let n=bp(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:yr};let o=hp(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 '${yr}' for it.`);if(o!==El)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${El}' 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 '${yr}' for it.`);return {...t,platform:n,engineVersion:r}}function bp(t,e){if(t===void 0||t===vt)return vt;if(!Io.includes(t))throw new w("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${Io.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${vt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${vt}' 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.`),vt}function Qt(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:Cl(e.queued_at),expiresAt:Cl(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function Cl(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var vp=3,Ml=1e3,fr=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?Ml:Math.max(Ml,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},n);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,n=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){n=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(n);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof M&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<vp){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof M&&e.code==="matchmaking_unavailable";this.settle({status:n?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let n=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:n});}catch(n){this.busy=false,this.fail(n);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var _p="gemPlayWith",wp=/^[A-Za-z0-9_-]{16,128}$/;function Ol(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(_p);}catch{return}return e!==null&&wp.test(e)?e:void 0}function Gl(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var kp="join",Sp="welcome",Rp="rejected",Ll=25e3,xp=1e3,Do=1;function $o(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Ap={credential_expired:"credential_expired",credential_reused:"credential_reused",credential_timeout:"timeout",join_rate_limited:"join_rate_limited",expected_join:"join_refused",invalid_credential:"join_refused",credential_not_for_this_channel:"join_refused"};function Fo(t){let e=typeof t=="string"?t:"unknown";return new w(Ap[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Xt(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Ll),a=n.setTimeout(()=>_(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,xp)),l=S=>{let x=S.data;if(typeof x!="string"){u(x);return}let C;try{C=JSON.parse(x);}catch{u(x);return}if(i){u(x);return}if(C.t===Sp){let h=$o(C.heartbeat_interval);y({...typeof C.player_id=="string"?{playerId:C.player_id}:{},...typeof C.match_id=="string"?{matchId:C.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(C.t===Rp){_(Fo(C.reason));return}u(x);},d=()=>{_(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{_(new w("aborted","the caller aborted during the join exchange"));},u=S=>{i&&t.onMessage?.(S);},p=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=S=>{i=true,p(),t.onMessage===void 0&&g(),r({welcome:S,detach:g});},_=S=>{i||(i=true,p(),g(),o(S));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:kp,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:Do}:{}}));}catch(S){_(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(S)}`,{cause:S}));}})}var et=1,Zt=2,qo=4,Uo=8,Pp=2,Tp=1e3,Bo="heartbeat timeout",en="gem-uu",hr=2,$l="gem_transports";function _t(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Ep(r)||e.includes(r)||e.push(r);}return e}function Ep(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function tn(t,e){if(typeof t!="object"||t===null)return null;let n=t[$l];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 br(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Fl=new TextEncoder,ql=new TextDecoder;function Wo(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function Ho(t){let e=0;return t?.reliable===false&&(e|=et),t?.ordered===false&&(e|=Zt),e}function Vo(t){return {reliable:(t&et)===0,ordered:(t&Zt)===0}}var Ko={reliable:true,ordered:true};function Nl(t){return JSON.stringify({t:"join",credential:t,wire:hr,heartbeat:Do})}function jl(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=$o(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"?Fo(e.reason):new w("join_refused","the server answered the join out of protocol")}function vr(){return typeof globalThis.WebTransport=="function"&&Jo===null}function _r(){return Jo}var Jo=null;var Dl="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Ip(t){let e=Gn(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 No=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 jo(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 nn(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:Ip(t.certHashBase64)}]});}let r=n,o=a=>{try{r.close();}catch{}throw a},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(Jo=Dl,o(new w("connection_failed",`${Dl}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new w("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return o(new w("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(jo(qo,Fl.encode(Nl(t.credential))));let u=new No,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),s]);if(y.done||y.value===void 0)return o(new w("connection_failed","the control stream closed before the join was answered"));for(let _ of u.push(y.value)){g=jl(ql.decode(_.payload));break}}return {link:Cp(r,m,p,u,t.log??(y=>console.warn(y)),Bl(g,t.clock)),welcome:g}}catch(a){return o(a)}}function Cp(t,e,n,r,o,i){let s,a,l=false,d=y=>{if(!l){l=true,m.stop();try{t.close();}catch{}a?.(y);}},m=Yo(i,()=>d(Bo)),u=(y,_)=>{m.heard(),(y&Uo)===0&&s!==void 0&&((y&qo)!==0?s(ql.decode(_),Ko):s(_,Vo(y)));};(async()=>{try{for(;;){let y=await n.read();if(y.done||y.value===void 0)break;for(let _ of r.push(y.value))u(_.flags,_.payload);}}catch{}d("stream closed");})();let p,g;try{let y=t.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let _=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let S=await _.read();if(S.done||S.value===void 0)break;let x=S.value;x.byteLength!==0&&u((x[0]??0)|et|Zt,x.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,o(`[gem] webtransport datagram lane unusable (${br(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(Ul(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,_){if(l)return;if(typeof y=="string"){e.write(jo(qo,Fl.encode(y))).catch(()=>d("write failed"));return}let S=Ho(_);if((S&et)!==0&&g!==void 0){let x=Wo(S,y),C=p?.maxDatagramSize;if(C===void 0||x.byteLength<=C){g.write(x).catch(()=>{});return}}e.write(jo(S,y)).catch(()=>d("write failed"));},onMessage(y){s=y;},onClose(y){a=y;},close(){d("closed");}}}function zo(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let o=globalThis.WebSocket;if(o===void 0)return Promise.reject(new w("connection_failed","this environment has no WebSocket"));n=new o(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((o,i)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),i(new w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),i(g));},d=()=>{r.send(Nl(t.credential));},m=g=>{if(s)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let y;try{y=jl(g.data);}catch(_){l(_);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),o({link:Mp(r,Bl(y,t.clock)),welcome:y});},u=()=>{l(new w("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new w("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",u),r.addEventListener("error",p),r.readyState===1&&d();})}function Ul(t){return typeof t=="string"&&t.length>0?t:void 0}function Bl(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function Yo(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Tp)*Pp,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 Mp(t,e){let n,r,o=false,i=a=>{if(!o){o=true,s.stop();try{t.close();}catch{}r?.(a);}},s=Yo(e,()=>i(Bo));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,Ko);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Uo)===0&&n?.(l.slice(1),Vo(d));})),t.addEventListener("close",(a=>i(Ul(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!o){if(typeof a=="string"){t.send(a);return}t.send(Wo(Ho(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){i("closed");}}}function Qo(t,e,n,r){let o,i,s=false,a=n,l=u=>{if(!s){s=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}i?.(u);}},d=Yo(r,()=>l(Bo)),m=(u,p)=>{if(d.heard(),typeof u=="string"){o?.(u,Ko);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let y=g[0]??0;(y&Uo)===0&&o?.(g.slice(1),Vo(y|p));};if(t.addEventListener("message",(u=>m(u.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(p=>m(p.data,et|Zt))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,p){if(s)return;if(typeof u=="string"){t.send(u);return}let g=Ho(p),y=Wo(g,u);if((g&et)!==0&&a!==void 0&&a.readyState==="open"){a.send(y);return}t.send(y);},onMessage(u){o=u;},onClose(u){i=u;},close(){l("closed");}}}function Wl(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=Xo(r);o!==void 0&&(e[n]=o);}return e}function Hl(t){if(Array.isArray(t))return t.map(Op).filter(e=>!!e)}function Xo(t){if(Zo(t)||Array.isArray(t)&&t.every(Zo))return t}function Zo(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function Op(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Xo(e.fixed),r=Xo(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},...wt("description",Gp(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Zo)?{allowed:e.allowed}:{},...wt("min",rn(e.min)),...wt("max",rn(e.max)),...wt("minItems",rn(e.min_items)),...wt("maxItems",rn(e.max_items)),...wt("maxLength",rn(e.max_length))}}function Gp(t){return typeof t=="string"&&t.length>0?t:void 0}function rn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function wt(t,e){return e===void 0?{}:{[t]:e}}function De(t){let e=t??{},n=Y(e.id)??Y(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(Lp):[];return {id:n,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Oe(e.max_players)??0,memberCount:Oe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...ke("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...ke("roomArgs",Wl(e.room_args)),...ke("roomArgsTemplate",Hl(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",...ke("region",Y(e.region)),...ke("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,...ke("matchId",Y(e.match_id)),version:Oe(e.version)??0,...ke("templateId",Y(e.template_id)),...ke("templateSlug",Y(e.template_slug)),roomType:Y(e.game_room_type)??"Standard",...ke("transports",_t(e.transports)??void 0),createdAt:Oe(e.created_at)??0,updatedAt:Oe(e.updated_at)??0,...ke("startedAt",Oe(e.started_at))}}function Lp(t){let e=t??{};return {...Ae(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Oe(e.joined_at)??0,...ke("groupId",Y(e.group_id)),...ke("platform",Y(e.platform))}}function ei(t){let e=t??{};return {id:Y(e.id)??Y(e.game_room_id)??"",gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Oe(e.max_players)??0,memberCount:Oe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:Oe(e.created_at)??0}}function Y(t){return typeof t=="string"&&t.length>0?t:void 0}function Oe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ke(t,e){return e===void 0?{}:{[t]:e}}var wr=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(ei),...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(ei)}))}create(e,n,r){return $p(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},...on(n)},e.signal).then(De)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(De)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...on(r)},n.signal).then(De)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...on(r)},n.signal).then(De)}quickJoin(e,n,r=[]){return ti(this.options,e,n,r).then(o=>o.room)}createTicket(e,n,r=[]){return Sa(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},...on(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Qt)}heartbeatTicket(e){return Za(this.generated(),e).then(Qt)}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(Qt):ba(this.generated(),e).then(Qt)}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 Kl(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(De)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(De)}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(De)}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 Vl(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 Vl(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function Kl(t,e){return e===void 0&&t.selfHosted?.()===true}function ti(t,e,n,r=[],o){let i=Kl(t,e.partyId);return t.client.post(`${Vl(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...Dp(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},...on(n)},e.signal).then(s=>({room:De(s),playWith:o===void 0?null:Gl(s)}))}function Dp(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function on(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function $p(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 kr=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 Sr=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 Fp(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var qp=1e3,Np=3e3,jp=6e4,Up=2,Jl=new Set(["game_room_closed","game_room_gone"]),Bp=12e4,Wp=5e3,Hp=new Set(["invalid_cluster_target","capacity_unavailable"]),Vp=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Xl(t,e){return new ni(e,t)}var ni=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 wr(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new kr;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"),zp(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||Ql(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"),Jp(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||Ql(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 fr({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 M&&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(()=>Oo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...n===void 0?{}:{signal:n}})));}catch(s){return s instanceof M&&s.reason==="not_found"?o??null:(this.reportError("reconcile",s),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=je(n.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),o=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(o),o}async kick(e,n){let r=this.requireRoom("kick"),o=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(o),o}async transferHost(e,n){let r=this.requireRoom("transferHost"),o=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(o),o}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new w("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let o=fe(n.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(m,u)=>Co({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...o===void 0?{nextClusterTarget:()=>this.nextCluster(u)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(i,[s]).catch(async m=>{if(o!==void 0||!Yl(m))throw m;let u=await this.nextCluster([s],true);if(u===void 0)throw m;return a(u,[s,u])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new w("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let 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 Mo({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,!Jl.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(!tt()){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<qp){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(Fp(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!tt()){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(()=>Oo({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,!Jl.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||!Hp.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 Sr({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&&tt())){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(),!!tt())){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 Rr)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 Rr)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??Wp}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=gr(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 Il({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Yt(await this.options.resolveClusterTargets());let e=fe(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Yl(e)||n.length===0?[]:Yt(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(Yt(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 M)||e.reason!=="conflict"||!Vp.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let o;try{o=await this.leaveAll(n.signal);}catch{throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(o.length===0)throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.postQuickJoin(n,r)}postQuickJoin(e,n){return ti(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}assertNotInRoom(e){if(this.room!==null)throw new w("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new w("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new w("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,n){let r=n instanceof M?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof w?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(n,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(a=>[a.playerId,a])),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=Kp(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??Bp;return new Promise((o,i)=>{let s=u=>{a(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>o(u))),l=this.emitter.on("matchFailed",(u,p)=>s(()=>i(new w("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>s(()=>i(new w("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>s(()=>i(new w("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Np}pushedInterval(){return this.options.pushedPollIntervalMs??jp}pushed(){return this.options.clock.now()-this.lastPushAt<Up*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 tt(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Rr=["visibilitychange","focus","pageshow","online"];function Kp(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||zl(t)!==zl(e)}function zl(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Yl(t){return t instanceof M&&t.code==="invalid_cluster_target"}var xr=8;function Jp(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=xr&&t.every(n=>typeof n=="string"&&n.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${xr} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function zp(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=xr&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${xr} 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 Ql(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Yp=["p2p","dedicated","unknown"],ri=["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 kt=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=Qp(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 Qp(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>ri.includes(o.type)).slice(0,100).map(o=>{let i=Xp(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function Xp(t){if(t!==void 0)return Yp.includes(t)?t:"unknown"}var an=class{constructor(e){this.options=e;this.reporter=new kt({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:Ar(o.credential)??"",hostFingerprint:Ar(o.host_fingerprint)??"",hostEpoch:Pr(o.host_epoch)??0,expiresAt:(Pr(o.expires_at)??0)*1e3}}async turnLease(e,n,r){let o=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),i=[];for(let l of Array.isArray(o.ice_servers)?o.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);m.length!==0&&i.push({urls:m,username:Ar(d.username)??"",credential:Ar(d.credential)??""});}let s=Pr(o.expires_at),a=Pr(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 Ar(t){return typeof t=="string"&&t.length>0?t:void 0}function Pr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var Zp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),L=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=Zp.has(n);}reason;retryable};var Zl=10240,ed=2048,eg=new TextEncoder;function td(t){return eg.encode(t).length}function Ue(t,e){let n=o=>{throw new w("invalid_sdp",`the ${e} ${o}`)},r=td(t);r>=Zl&&n(`is ${r} bytes, over the ${Zl} 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=td(o);i>ed&&n(`has a ${i}-byte line, over the ${ed} limit`);}}function Tr(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 Er=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 tg=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function St(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=Ir(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Ir(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 tg.test(r)?r:null}function sn(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 oi=5e3,ng=12e4+oi,rg=1024,og=6e4,ig=1e4,nd=64*1024,rd=5;function ii(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 L("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 L("keys_unavailable",o.reason);let a=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ig)});}catch{throw new L("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 L("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>nd)throw new L("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${nd} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof L?p:new L("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>rd)throw new L("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${rd} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=i();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await u.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!o.ok)throw new L("keys_unavailable",o.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new L("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<og?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var ln=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>=rg){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+ng),true}};function id(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 od(t){try{let e=new TextDecoder().decode(id(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function ai(t,e,n,r,o){let i=j=>{throw new L("peer_unauthenticated",`the peer's join credential is not usable: ${j}`)},s=t.split(".");s.length!==3&&i("it is not a three-part JWT");let[a,l,d]=s,m=od(a);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let u=m.kid;(typeof u!="string"||u.length===0)&&i("it names no key");let p=await n.key(u);p===null&&i("it was signed by a key this build cannot resolve");let g=o.subtle??globalThis.crypto?.subtle;g||i("this environment has no WebCrypto");let y=new TextEncoder().encode(`${a}.${l}`),_;try{_=id(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,_,y)||i("its signature does not verify");let x=od(l);x===null&&i("its payload does not decode");let C=x,h=j=>typeof C[j]=="string"?C[j]:"",k=j=>typeof C[j]=="number"&&Number.isFinite(C[j])?C[j]: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 E=k("exp")*1e3,A=k("nbf")*1e3;(!Number.isFinite(E)||e.now>E+oi)&&i("it has expired"),Number.isFinite(A)&&e.now<A-oi&&i("it is not valid yet");let W=h("role");W!=="host"&&W!=="client"&&i("it names no usable role");let $=k("host_epoch");$!==e.hostEpoch&&i("it names a different host epoch");let F=Ir(h("fingerprint"));F===null&&i("its fingerprint claim is malformed"),sn(F,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let T=Ir(h("host_fingerprint"));T===null&&i("its host fingerprint claim is malformed"),sn(T,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 G=h("sub");return G.length===0&&i("it names no player"),{playerId:G.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:$,role:W,fingerprint:F,hostFingerprint:T,jti:O,expiresAt:E}}function si(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function li(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function di(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function ci(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 ad(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 sd(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var dn=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 ui={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}},$e=["reliable","ordered","unreliable"];function mi(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 cn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var dd=1,cg=3e4,cd=2e3,ug=5e3,ud=6e4,mg=8,gi=class{constructor(e=mg){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;}},pg=new gi,gg=8,yg=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),mn=class{constructor(e){this.options=e;this.keys=e.keys??ii({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Er;links=new Map;replays=new ln;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=dd+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??cg;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),o=fe(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: ${pi(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 L("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 L("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 L("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=le(e.playerId),r=le(e.hostPlayerId),o=Cr(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new dn(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,dd),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new L("invalid_sdp","the browser produced an offer with no SDP");Ue(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:St(r);if(o===null)throw new L("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??pg,s=()=>this.closed||e!==this.credentialGeneration,a=ug;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let m=d.status,u;if(m===409)u=cd;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=a,a=Math.min(a*2,ud)),u=Math.min(Math.max(u,cd),ud);}else throw d;if(!await this.waitForCredential(u,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=le(e.fromPlayerId),r=le(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=gg){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let o=le(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;Ue(r,"offer"),this.refuseMedia(r,"offer");let i=St(r);if(i===null)throw new L("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 L("invalid_sdp","the browser produced an answer with no SDP");Ue(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=le(e.fromPlayerId),r=le(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;Ue(r,"answer"),this.refuseMedia(r,"answer");let i=St(r);if(i===null)throw new L("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:sn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new L("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=le(e.fromPlayerId),r=le(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=le(e.sdpMid),s=Cr(e.sdpMLineIndex)??Cr(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=le(e.playerId);if(n===null)return;let r=le(e.reason)??"left";if(n===this.localPlayerId){this.fail(new L("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=le(e.hostPlayerId),r=Cr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...le(e.reason)===null?{}:{reason:le(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 L("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 L("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=le(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new L("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=le(e.code)??"unknown",r=le(e.message)??"the platform refused a signaling message";this.report_(new L("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??mi)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of $e){let g=o.createDataChannel(p,ui[p]);g.binaryType="arraybuffer",i[p]=g;}let s={playerId:e,assignedPeerId:n,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),m=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",a),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",u),i.reliable.addEventListener("message",m),s.detachHandshake=()=>{i.reliable.removeEventListener("open",u),i.reliable.removeEventListener("message",m);},s.detachAll=()=>{s.detachHandshake(),o.removeEventListener("icecandidate",a),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}flushCandidates(e){let 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 L("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 L("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(si({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=ci(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 L(sd(r.reason),ad(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=St(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 ai(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 L&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",pi(s)),a&&this.fail(s);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(li({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,o){this.warn(`refused to admit ${e.playerId}: ${o}`);try{e.channels.reliable.send(di(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let o of $e)md(e.channels[o]);md(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 L?e:new L("connection_failed",pi(e),{cause:e}));}count(e){this.counted||!yg.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(Tr(e))throw new L("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 le(t){return typeof t=="string"&&t.length>0?t:null}function Cr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function pi(t){return t instanceof Error?t.message:String(t)}function md(t){try{t.close();}catch{}}var fg=100,hg=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??fg)){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 L("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new L("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??hg));}};function V(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Be(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function Rt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function pd(t){return typeof t=="boolean"?t:void 0}var ve=V(64),gn=Be(0,2147483647);function yi(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=ve(n);typeof r=="string"&&e.push(r);}return e}function z(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 _g=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=Rt("disconnected","failed","closed")(e.iceState),r=Be(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:[z("sdp","sdp",V(10240)),z("signaling_intent","intent",Rt("initial","ice_restart","full_reconnect")),K("sdp_hash","sdpHash",V(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[z("peer_id","peerId",ve),z("sdp","sdp",V(10240)),z("assigned_peer_id","assignedPeerId",Be(0,4294967295)),K("sdp_hash","sdpHash",V(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[z("peer_id","peerId",ve),z("candidate","candidate",V(512)),K("sdp_mid","sdpMid",V(64)),K("sdp_mline_index","sdpMLineIndex",Be(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[z("host_epoch","hostEpoch",gn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[z("host_epoch","hostEpoch",gn),K("evidence","evidence",_g)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[z("playerId","player_id",ve),z("hostPlayerId","host_player_id",ve),z("hostEpoch","host_epoch",gn),K("members","members",yi)],offer:[z("fromPlayerId","from_player_id",ve),z("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",Rt("initial","ice_restart","full_reconnect"))],answer:[z("fromPlayerId","from_player_id",ve),z("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",Be(0,4294967295))],ice:[z("fromPlayerId","from_player_id",ve),z("candidate","candidate",V(512)),K("sdpMid","sdp_mid",V(64)),K("sdpMLineIndex","sdp_m_line_index",Be(0,255)),K("sdpMLineIndexAlt","sdp_mline_index",Be(0,255))],peerJoined:[z("playerId","player_id",ve)],peerLeft:[z("playerId","player_id",ve),K("reason","reason",V(64))],migration:[z("hostPlayerId","new_host_player_id",ve),z("hostEpoch","host_epoch",gn),K("reason","reason",V(64)),K("kickedPlayerIds","kicked_player_ids",yi),K("migrationComplete","migration_complete",pd)],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 rt="webrtc_p2p";function yd(t){let e=new an({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 L("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=fe(r.clusterTargetId),i=o??fe(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!==rt)throw new L("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${rt}'. 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 mn({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 cn(),...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 fd(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(!tt());for(let d of Rr)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(!tt());}let s=new Map;return i.push(n.on("matchReady",a=>{let l=a.protocol===rt?"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 hd=["pointerdown","keydown"];function bd(t,e=globalThis){let n=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},s=()=>{if(!r){r=true,i();for(let g of hd)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(g){g?.isTrusted===true&&a();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(_=>_.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(o=null,!(n||r)){if(d()){a();return}m()&&(o=e.requestAnimationFrame?.(u)??null);}};function p(){o===null&&!n&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of hd)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(o=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return n},stop:s}}async function Mr(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function fi(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function hi(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 bi=false;async function kd(t,e,n,r){if(bi){e.close(),n("busy",true);return}bi=true;let o=null;try{let i=await kg(t,r);if(typeof i=="string"){e.close(),n(i,wg(i));return}o=i;let a=await(r.encodeRef??(l=>Ag(l,r)))(o);if(o.close(),o=null,a===null){e.close(),n("failed",!0);return}if(a.size>xg){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{bi=false,o?.close();}}function wg(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}}async function kg(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":vd(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Rg(n);if(!r)return "no_source";let o=Sg(r);if(o!==null)return o;try{return vd(await createImageBitmap(r),t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function Sg(t){let e;try{e=t.getContext("webgl2")??t.getContext("webgl");}catch{return "unreadable"}if(e){let n=e.getContextAttributes();return !n||n.preserveDrawingBuffer!==true?"unsupported":null}try{if(t.getContext("2d"))return null}catch{return "unreadable"}return "unreadable"}function Rg(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||o>n&&(e=r,n=o);}return e}async function vd(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 xg=8*1024*1024,_d="image/webp",wd=.92;async function Ag(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:_d,quality:wd});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),_d,wd);})}async function Sd(t,e){if(!e)return;let n;try{n=await Pg(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 Pg(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 Rd=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function xd(t=globalThis){let n=t[Rd];if(n!==void 0)return n;let r=false,o=()=>r,i=[],s=Tg(t,o);s!==null&&i.push(s);let a=Eg(t,o);a!==null&&i.push(a);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let u of i)u();}}};return Object.defineProperty(t,Rd,{value:l,configurable:true}),l}function Tg(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let o=t.OfflineAudioContext,i=n.connect,s=n.disconnect,a=new Map,l=m=>{let u=m.gain,p=m.context.currentTime;u.cancelScheduledValues(p),e()?u.setValueAtTime(0,p):u.setTargetAtTime(1,p,.01);},d=m=>{let u=m.context;if(o!==void 0&&u instanceof o)return null;let p=a.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,i.call(p,m),a.set(u,p)),p};return n.connect=function(...u){let[p,...g]=u;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return i.call(this,y,...g),p}return i.apply(this,u)},n.disconnect=function(...u){let[p,...g]=u;if(p instanceof r){let y=a.get(p.context);if(y!==void 0&&y!==this)try{return s.call(this,y,...g)}catch{}}return s.apply(this,u)},()=>{for(let[m,u]of a){if(m.state==="closed"){a.delete(m);continue}try{l(u);}catch{}}}}function Eg(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,s=o?.set;if(i===void 0||s===void 0)return null;let a=r.play,l=new WeakMap,d=new WeakSet,m=new Set,u=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),s.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),u(this);}}),r.play=function(){try{u(this);}catch{}return a.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{u(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{s.call(g,(l.get(g)??!1)||e());}catch{}}}}var Ig=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Cg=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Mg=`${Ig}${Cg}`,vi=new WeakSet;function Ad(t=globalThis.document){if(t==null||vi.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(Mg),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],vi.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"),vi.add(t),"inline")}catch{return null}}function Pd(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=t.now??(()=>globalThis.performance?.now()??Date.now()),o=false,i=false,s=false,a=null,l=null,d=null,m=[],u=false,p=0,g=null,y=[],_=()=>o&&!i&&!s,S=()=>{l=null,d=null,m=[],p=0,g=null,y=[];},x=k=>{if(a=null,!_()){S();return}if(d!==null&&m.push(k-d),d=k,l===null)l=k;else {let E=k-l;if(E>=e&&m.length>0){if(u){let A=g===null?E:r()-g;t.report(Gg(p,y,E,A));}else t.report(Og(m,E));l=k,m=[],p=0,y=[];}}C();},C=()=>{let k=n.requestAnimationFrame;typeof k=="function"&&(a=k.call(n,x));},h=()=>{if(_()){a===null&&(S(),C());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),S();};return {setRequested(k){o=k,h();},setPaused(k){i=k,h();},draw(){if(!u){u=true,a!==null&&S();return}if(a===null||l===null)return;let k=r();g!==null&&y.length<1e3&&y.push(k-g),g=k,p+=1;},get running(){return a!==null},dispose(){s=true,h();}}}function Og(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:Td(t),counts:"pageFrames"}}function Gg(t,e,n,r){let o=r;return e.length>0&&(o=Td(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:o,counts:"gameDraws"}}function Td(t){let e=[...t].sort((r,o)=>r-o),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var Or=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Ed(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Id(t,e){t!==null&&(t.style.setProperty(Or.top,`${e.top}px`),t.style.setProperty(Or.right,`${e.right}px`),t.style.setProperty(Or.bottom,`${e.bottom}px`),t.style.setProperty(Or.left,`${e.left}px`));}var Gr=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 Cd(){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 Lg(t,e){let n={tl:{width:0,height:0,control:null},tr:{width:0,height:0,control:null},bl:{width:0,height:0,control:null},br:{width:0,height:0,control:null}};for(let r of t){let o=e?r.x+r.width/2<=e.width/2:r.x===0,i=e?r.y+r.height/2<=e.height/2:r.y===0,s=o?r.x+r.width:e?e.width-r.x:r.width,a=i?r.y+r.height:e?e.height-r.y:r.height,l=n[`${i?"t":"b"}${o?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));let d=r.control;if(d){let m=l.control;l.control=m?{top:Math.min(m.top,d.y),bottom:Math.max(m.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Md(t,e,n){if(t===null)return;let r=Lg(e,n);for(let o of ["tl","tr","bl","br"]){t.style.setProperty(Gr[o].width,`${r[o].width}px`),t.style.setProperty(Gr[o].height,`${r[o].height}px`);let i=r[o].control;t.style.setProperty(Gr[o].centerY,i?`${(i.top+i.bottom)/2}px`:""),t.style.setProperty(Gr[o].controlHeight,i?`${i.bottom-i.top}px`:"");}}var Dg=3e4,Lr=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Od(t){let e=t.clock??ue,n=t.timeoutMs??Dg,r=new Map,o=new Map,i=0,s=a=>{let l=r.get(a);return l?(r.delete(a),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(a){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(a);if(l)return l;let d=new Promise((m,u)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(a),u(new Lr("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(p,{room:a,resolve:m,reject:u,timer:g}),t.bridge.requestLocalServer(p,a)||(s(p),m());});return o.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new Lr(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 yn={url:"https://downloads.indiegems.games/sdk/v13.4.0/gem-web-sdk.devtools.min.js",integrity:"sha384-kHZbkOmcw0p21hD5fK4JFdtscchOSRSR2P6VF8Y7eJulKeNd9G3LPcie9hNsFzaY"};var At=null;function $g(){return At!==null||(At=new Promise((t,e)=>{let n=document.createElement("script");n.src=yn.url,n.integrity=yn.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){At=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${yn.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{At=null,e(new Error(`gem devtools: could not load ${yn.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);})),At}function Gd(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 $g();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:i,text:Ye,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 Fg=1e4,Ld={reason:"unavailable",retryable:false};function Dd(t){let e=new Map,n=null,r=null,o=0,i=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??Fg);},s=(d,m)=>{let u=a(d);u&&m(u);},a=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new ut({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,u)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){u(Ld);return}let g=`t${++o}`,y={resolve:m,reject:u,reason:d,timer:null,held:p!=="connected"};e.set(g,y),i(g,y),y.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,u=>u.resolve(m));return}l.accept(m);},onDenied(d){s(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,u]of e)u.held&&(u.held=false,t.clock.clearTimeout(u.timer),i(m,u),t.bridge.requestToken(m,u.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])s(m,u=>u.reject(Ld));},get identity(){return n},get gameVersion(){return r}}}function qg(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Ng=new Set(Mn);function jg(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Ng.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function Dr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return ua(async(n,r)=>{let o;try{o=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new oe("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let i;try{i=new URL(o.href.replace(/\/+$/,"")+n.path);}catch{throw new oe(`${JSON.stringify(typeof n.path=="string"?qg(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 oe(`${JSON.stringify(i.pathname)} resolves to ${i.protocol}//${i.host}, not ${o.protocol}//${o.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(i.username!==""||i.password!==""){let g=o.username!==""||o.password!=="",y=i.username!==o.username||i.password!==o.password,_=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new oe(`the ${_} puts credentials in the URL, which cannot be fetched (${n.method} ${i.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(t.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,y);let s=n.bytes,a=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(s=JSON.stringify(n.body),a="application/json");}catch(g){throw new oe(`the body of ${n.method} ${JSON.stringify(i.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(i.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...jg(n.headers)},body:s,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),u=Ug(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},t)}function Ug(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}var Bg=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),wi="embedder_relay_unavailable",Wg="embedder_no_relay",Hg=new Set([wi]),ki=new Set([Wg]),fn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new _i(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(Vg(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 Vg(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new w(Kg(t),r,{platformCode:t})}function Kg(t){return t===void 0||Hg.has(t)?"signaling_failed":ki.has(t)?"offer_refused":Bg.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var _i=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 $d="match_ended:",Fd="server_shutdown:",qd="kicked:",Jg=123;function zg(t){if(typeof t!="string"||t.length===0||t.length>Jg)return {kind:"other"};if(t.startsWith($d)){let e=je(t.slice($d.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Fd)?{kind:"server_shutdown",cause:t.slice(Fd.length)}:t.startsWith(qd)?{kind:"kicked",detail:t.slice(qd.length)}:{kind:"other"}}function Si(t,e,n){let r=zg(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 Ri(){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 Yg=3e3,Qg=1e4,Xg=15e3;async function $r(t){let e=t.peerConnection;try{jd(t,"before the handshake started"),xi(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 ty(e,t),xi(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new w("invalid_sdp","the offer carried no SDP");Ue(o,"offer"),Nd(o,"offer");let i=await ey(t,o);if(xi(t),typeof i?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return Ue(i.sdp,"answer"),Nd(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await ny(n,t),jd(t,"before the channel opened"),n}catch(n){throw e.close(),Zg(n)}}function Zg(t){return t instanceof w?t:Wd(t)?ot():new w("connection_failed",Hd(t),{cause:t})}function Nd(t,e){if(Tr(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 ey(t,e){let n=t.exchangeTimeoutMs??Qg,r=Bd(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof w?i:Wd(i)?ot():new w("signaling_failed",Hd(i),{cause:i})});return ry(o,t,r,()=>r.exhausted?Ai("while the offer was in flight"):new w("timeout",`no answer arrived within ${n}ms`))}function ty(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??Yg);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function ny(t,e){if(e.signal?.aborted)return Promise.reject(ot());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??Xg,o=Bd(e,r);return new Promise((i,s)=>{let a=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{a(),i();},d=g=>{a(),s(new w("connection_failed","the data channel failed before it opened",Ud(g)===void 0?void 0:{cause:Ud(g)}));},m=()=>{a(),s(ot());},u=()=>{a(),s(o.exhausted?Ai("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(u,o.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Bd(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 ry(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(ot()):new Promise((s,a)=>{let l=u=>{o.clearTimeout(m),i?.removeEventListener("abort",d),u();},d=()=>l(()=>a(ot())),m=o.setTimeout(()=>l(()=>a(r())),n.ms);i?.addEventListener("abort",d),t.then(u=>l(()=>s(u)),u=>l(()=>a(u)));})}function jd(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Ai(`already ${e}`)}function Ai(t){return new w("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function xi(t){if(t.signal?.aborted)throw ot()}function ot(){return new w("aborted","the caller aborted the connection attempt")}function Wd(t){return t?.name==="AbortError"}function Ud(t){return t?.error}function Hd(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:[z("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 Zd(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??Ri,i=t.log??(h=>console.warn(h)),s=new kt({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,k)=>{let E=a.get(h)??new Set;E.add(k),a.set(h,E);},d=(h,k)=>{let E=a.get(h);E!==void 0&&(E.delete(k),E.size===0&&a.delete(h));},m=async h=>{if(r.isHost&&!Ti(r)&&r.currentRoom?.matchId===void 0){let k=fe(h.clusterTargetId);await r.startMatch({...k===void 0?{}:{clusterTargetId:k},...h.retry===void 0?{}:{retry:h.retry},...h.signal===void 0?{}:{signal:h.signal}});}return Qd(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Pi(h)):await r.awaitMatch(Pi(h)))},u=async h=>Qd(await r.pollMatchStatus(Pi(h))),p=async(h,k)=>{let E=false;try{let A=await m(h),W=r.currentRoom?.transports;if(W!==void 0&&!W.includes("webrtc"))throw new w("misconfigured",`the room template offers (${W.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let $=h.peerConnection??Xd();E=!0;let F=await $r({peerConnection:$,signaling:k,clock:n,matchId:A.matchId,credentialExpiresAt:A.credentialExpiresAt,...Fr(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),T=null;if(h.presentCredential!==!1)try{T=await Xt({channel:F,clock:n,credential:A.joinCredential,credentialExpiresAt:A.credentialExpiresAt,...Fr(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(O){throw Pe(F),Pe($),O}return my(r,A,F,$,k,h.reportDisconnect!==!1,h.reportConnected!==!1,T,{remember:l,forget:d},h.onMatchEnded)}catch(A){throw E&&Yd(s,A),Pe(k),A}},g=async(h,k,E,A,W,$)=>{if(h==="webtransport"){let B=A?.webtransport;if(B===void 0)throw new w("misconfigured","webtransport is not advertised");let H={credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n};if(typeof B.named_url=="string"&&B.named_url!==""){let ne=Math.max(Math.floor($/2),1e3);try{return await nn({url:B.named_url,timeoutMs:ne,log:i,...H})}catch(ie){if(_r()!==null)throw ie;return i(`[gem] webtransport named dial failed (${br(ie)}); retrying the pinned dial`),nn({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:ne,log:i,...H})}}return nn({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:$,...H})}if(h==="websocket"){let B=A?.websocket;if(B===void 0)throw new w("misconfigured","websocket is not advertised");return zo({url:B.url,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n,timeoutMs:$})}let F=k.peerConnection??Xd(),T,O=await $r({peerConnection:F,signaling:W,clock:n,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,extraChannels:[{label:en,ordered:false,maxRetransmits:0}],onExtraChannel:(B,H)=>{B===en&&(T=H);},...Fr(k,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...k.exchangeTimeoutMs===void 0&&k.redial===true?{exchangeTimeoutMs:ay}:{}}),G;try{G=await Xt({channel:O,clock:n,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,wire:hr,heartbeat:!0,...Fr(k,"signal"),...k.welcomeTimeoutMs===void 0?{}:{ceilingMs:k.welcomeTimeoutMs}});}catch(B){throw Pe(O),Pe(F),B}let j=G.welcome.heartbeatIntervalMs;return {link:Qo(O,F,T,j===void 0?void 0:{clock:n,intervalMs:j}),welcome:G.welcome,channel:O,peerConnection:F}},y=(h,k,E,A,W)=>{let $=false,F;A.link.onClose(j=>{!$&&h.reportDisconnect!==false&&Si(r,k.matchId,j),F?.(j);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(k.matchId);let T={transport:A.link.transport,send:(j,B)=>A.link.send(j,B),onMessage:j=>A.link.onMessage(j),onClose:j=>{F=j;},close:()=>A.link.close()},O=()=>{$||($=true,Pe(A.link),Pe(W));},G=j=>{if(!$){try{h.onMatchEnded?.(j);}catch{}O();}};return l(k.matchId,G),{matchId:k.matchId,transport:E,link:T,joinCredential:k.joinCredential,credentialExpiresAt:k.credentialExpiresAt,welcome:A.welcome,...A.channel===void 0?{}:{channel:A.channel},...A.peerConnection===void 0?{}:{peerConnection:A.peerConnection},close(){d(k.matchId,G),O();}}},_=async(h,k)=>{let E=r.currentRoom?.id,A=r.gameId,W=()=>({advert:tn(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(E===void 0||A===null)return W();try{let $=await e.get(`/v2/games/${encodeURIComponent(A)}/game-rooms/${encodeURIComponent(E)}`,k);return {advert:tn($.settings,h),template:_t($.transports)??r.currentRoom?.transports??null}}catch{return W()}},S=(h,k)=>{let E=h??Vd;return k.length===0?E:E.filter(A=>k.includes(A))},x=async(h,k,E)=>{try{let A=await m(h),{advert:W,template:$}=await _(A.matchId,h.signal),F=S($,k),T=F.filter(Q=>dy(Q,W)),O=_r();if(O!==null&&F.includes("webtransport")&&W?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${O} (learned on an earlier dial in this page)`),T.length===0){let Q=$===null?`the default order (${Vd.join(", ")})`:`the room template's transports (${$.join(", ")||"none"})`;throw new w("misconfigured",`none of ${Q}`+(k.length>0?`, narrowed to (${k.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let G=h.transportAttemptTimeoutMs??iy,j=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-n.now(),B=Q=>t.signalingReady===void 0||Q<=0?Promise.resolve(!0):t.signalingReady(Q),H=[],ne=[];for(let Q of T){if(j()<Jd){i(`[gem] ${Q} rung not tried: the reconnect budget is spent`);break}ne.length>0&&A.credentialExpiresAt-n.now()<zd&&(A=await u(h)),ne.push(Q);let We=!1,de=!1,Re={attempts:0,waitedMs:0};for(;;){if(Q==="webrtc"&&h.redial===!0){let X=Math.min(Kd,j());await B(X)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(X)}ms; offering anyway`);}let He=Math.max(Math.min(G,j()),Jd);try{return y(h,A,Q,await g(Q,h,A,W,E,He),E)}catch(X){let J=X instanceof w?X:new w("connection_failed",X instanceof Error?X.message:String(X),{cause:X});if(Q==="webrtc"&&Yd(s,J),(J.reason==="credential_expired"||J.reason==="credential_reused")&&!We){We=!0,A=await u(h);continue}if(Q==="webrtc"&&J.reason==="signaling_failed"&&J.platformCode===wi&&!de){de=!0;let ce=Math.min(Kd,j());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ce)}ms for the socket before offering again`),await B(ce))continue}if(J.reason==="join_rate_limited"){let ce=ly(Re,Math.random,j());if(ce!==null){if(Re.attempts+=1,Re.waitedMs+=ce,i(`[gem] ${Q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ce)}ms before presenting again (retry ${Re.attempts} of ${tc.maxAttempts})`),await pr(n,ce,h.signal),h.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");A.credentialExpiresAt-n.now()<zd&&(A=await u(h));continue}}if(sy.has(J.reason)||J.reason==="credential_expired"||Q==="webrtc"&&ec(J)){i(`[gem] ${Q} rung failed (${J.reason}): ${br(J.cause??J)} \u2014 `+(ne.length<T.length?`falling through to ${T[ne.length]}`:"no rungs left")),H.push(J);break}throw i(`[gem] ${Q} rung refused the session (${J.reason}): ${J.message}`),J}}}let ie=H[H.length-1];throw ie===void 0?new w("timeout",`the reconnect budget ran out before any transport (${T.join(", ")}) could be tried`):new w(ie.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${ie.message}`,{cause:H,platformCode:ie.platformCode})}catch(A){throw Pe(E),A}};return {listClusterTargets:async(h={})=>Go({client:e,...h}),handleMatchEnded(h,k){let E=a.get(h);if(E!==void 0){a.delete(h);for(let A of E)A(k);}},connect:(async(h={})=>{let k=h.signaling??o();return h.transports===void 0?p(h,k):x(h,h.transports,k)})}}var Vd=["webtransport","webrtc","websocket"],iy=1e4,ay=5e3,Kd=3e3,Jd=1e3,zd=1e4,sy=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function ec(t){return t.platformCode!==void 0&&ki.has(t.platformCode)}var tc={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function ly(t,e=Math.random,n=1/0){let r=tc;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 dy(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&vr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||cy(e.websocket.url)}function cy(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return pt(e)}function Pi(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var uy=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Yd(t,e){e instanceof w&&(!uy.has(e.reason)&&!ec(e)||t.report([{type:"connection_failures_total",value:1}]));}function my(t,e,n,r,o,i,s,a,l,d){let m=false,u=()=>{m||Si(t,e.matchId,void 0);};i&&(n.addEventListener("close",u),s&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",u),a?.detach(),Pe(n),Pe(r),Pe(o));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function Ti(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Qd(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!==mr)throw new w("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${mr}' 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 Xd(){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 Pe(t){try{t.close();}catch{}}function Fr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var py=1e4;function nc(t,e){return Ei(t,e)}function Ei(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 ut({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??py);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 Ci={};su(Ci,{acceptTransfer:()=>gy,addEntityProgression:()=>yy,adminAction:()=>fy,cancelInventoryTransfer:()=>hy,claimEntityProgressionRewards:()=>by,closeGameRoom:()=>vy,createEntityBatchOrder:()=>_y,createEntityOrder:()=>wy,createSession:()=>ky,deleteEntityGameSetting:()=>Sy,deleteEntitySave:()=>Ry,deleteSession:()=>xy,deleteShowcaseValue:()=>Ay,executeEntityRecipe:()=>Py,finalizeSaveUpload:()=>Ty,getChannelAssignment:()=>Ey,getDropRates:()=>Iy,getEntityCurrency:()=>Cy,getEntityGameSetting:()=>My,getEntityInventory:()=>Oy,getEntityInventoryItem:()=>Gy,getEntityLeaderboard:()=>Ly,getEntityOrder:()=>Dy,getEntityProgression:()=>$y,getEntityRecipeAvailability:()=>Fy,getEntityRecipeUsage:()=>qy,getEntitySave:()=>Ny,getEvent:()=>jy,getGameRoomV2:()=>Uy,getLeaderboard:()=>By,getPlayerGameProfile:()=>Wy,getPurchaseCatalog:()=>Hy,getResolvedTemplate:()=>Vy,getRoomArgs:()=>Ky,getShowcaseValue:()=>Jy,getTransferDetails:()=>zy,ingestAnalyticsEvents:()=>Ii,initiateInventoryTransfer:()=>Yy,invokeFunction:()=>Qy,kickPlayer:()=>Xy,listChallenges:()=>Zy,listEntityGameSettings:()=>ef,listEntityOrders:()=>tf,listEntityProgressions:()=>nf,listEntitySaves:()=>rf,listEvents:()=>of,listGameRooms:()=>af,listResolvedTemplates:()=>sf,listTransfers:()=>lf,maxEntityProgression:()=>df,putEntityGameSetting:()=>cf,putRoomArgs:()=>uf,putShowcaseValue:()=>mf,rejectTransfer:()=>pf,reportMatchPlayers:()=>gf,requestSaveUploadUrl:()=>yf,resetEntityProgression:()=>ff,setMatchBackfill:()=>hf,simulateEntityOrder:()=>bf,transferHostV2:()=>vf,updateGameRoomV2:()=>_f});function b(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function gy(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function yy(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/add`;return t.client.post(s,o,i?.signal)}async function fy(t,e,n,r){let o=`/v1/voice/sessions/${b(e)}/admin`;return t.client.post(o,n,r?.signal)}async function hy(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function by(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/claim`;return t.client.post(s,o,i?.signal)}async function vy(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.delete(r,n?.signal)}async function _y(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function wy(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ky(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Sy(t,e,n,r,o){let i=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(i,o?.signal)}async function Ry(t,e,n,r,o){let i=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(i,o?.signal)}async function xy(t,e,n){let r=`/v1/voice/sessions/${b(e)}`;return t.client.delete(r,n?.signal)}async function Ay(t,e,n,r){let o=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.delete(o,r?.signal)}async function Py(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ty(t,e,n,r,o,i){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/finalize`;return t.client.post(s,o,i?.signal)}async function Ey(t,e,n){let r=`/v1/games/${b(t.gameId())}/config/channels/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Iy(t,e,n){let r=`/v1/inventory/loot-tables/${b(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Cy(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/currencies/${b(r)}`;return t.client.get(i,o?.signal)}async function My(t,e,n,r,o){let i=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Oy(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),s=`/v1/inventory/${b(e)}/${b(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Gy(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/items/${b(r)}`;return t.client.get(i,o?.signal)}async function Ly(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let s=i.toString(),a=`/v1/leaderboards/${b(e)}/${b(n)}/${b(r)}`+(s?`?${s}`:"");return t.client.get(a,o?.signal)}async function Dy(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders/${b(r)}`;return t.client.get(i,o?.signal)}async function $y(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}`;return t.client.get(i,o?.signal)}async function Fy(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/catalogs/${b(r)}/recipes/${b(o)}/availability`;return t.client.get(s,i?.signal)}async function qy(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),s=`/v1/inventory/${b(e)}/${b(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Ny(t,e,n,r,o){let i=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function jy(t,e,n){let r=`/v1/events/${b(e)}`;return t.client.get(r,n?.signal)}async function Uy(t,e,n){let r=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function By(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${b(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Wy(t,e,n){let r=`/v1/profiles/players/${b(e)}`;return t.client.get(r,n?.signal)}async function Hy(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 Vy(t,e,n){let r=`/v1/game-room-templates/${b(e)}`;return t.client.get(r,n?.signal)}async function Ky(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.get(r,n?.signal)}async function Jy(t,e,n,r){let o=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.get(o,r?.signal)}async function zy(t,e,n){let r=`/v1/inventory/transfers/${b(e)}`;return t.client.get(r,n?.signal)}async function Ii(t,e,n){let r=`/v1/games/${b(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function Yy(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Qy(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Xy(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/kick/${b(n)}`;return t.client.post(o,void 0,r?.signal)}async function Zy(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 ef(t,e,n,r){let o=`/v1/settings/${b(e)}/${b(n)}`;return t.client.get(o,r?.signal)}async function tf(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),s=`/v1/inventory/${b(e)}/${b(n)}/orders`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function nf(t,e,n,r){let o=`/v1/inventory/${b(e)}/${b(n)}/progressions`;return t.client.get(o,r?.signal)}async function rf(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),s=`/v1/saves/${b(e)}/${b(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function of(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 af(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o=`/v1/games/${b(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function sf(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function lf(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 df(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/max`;return t.client.post(s,o,i?.signal)}async function cf(t,e,n,r,o,i){let s=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.put(s,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function uf(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.put(o,n,r?.signal)}async function mf(t,e,n,r,o){let i=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.put(i,r,o?.signal)}async function pf(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function gf(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/matches/${b(e)}/players/report`;return t.client.post(o,n,r?.signal)}async function yf(t,e,n,r,o,i){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/upload-url`;return t.client.post(s,o,i?.signal,{replaySafe:true})}async function ff(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/reset`;return t.client.post(s,o,i?.signal)}async function hf(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/matches/${b(e)}/backfill`;return t.client.put(o,n,r?.signal)}async function bf(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders/simulate`;return t.client.post(i,r,o?.signal)}async function vf(t,e,n,r){let o=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}/transfer/${b(n)}`;return t.client.post(o,void 0,r?.signal)}async function _f(t,e,n,r){let o=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.patch(o,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var wf=1e4,kf=50,Sf=1e3,Rf=65536-4*1024,rc=t=>typeof t=="number"?t:0,xf=t=>typeof t=="string"?t:"";function oc(){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 Af(t){return t?.retryable===true}function Pf(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:rc(i.index),code:xf(i.code)}}):[];return {accepted:rc(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function ic(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 ac(t){let e=Math.max(1,Math.floor(t.maxQueue??Sf)),n={client:t.client,gameId:()=>t.gameId},r=[],o=0,i=null,s=false,a=null,l=0,d=0,m=false,u=false,p=h=>{t.log?.(h);},g=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},y=()=>Math.max(0,d-t.clock.now()),_=()=>{i!==null||s||a!==null||(i=t.clock.setTimeout(()=>{i=null,x().catch(()=>{});},Math.max(wf,y())));},S=()=>{let h=Math.min(r.length,100),k=128;for(let E=0;E<h;E+=1){let A=r[E];if(A===void 0)break;if(k+=JSON.stringify(ic(A,0)).length+1,k>Rf)return Math.max(1,E)}return h};async function x(h){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let k=C(h);a=k;try{return await k}finally{a===k&&(a=null),r.length>0&&_();}}async function C(h){g();let k=r.splice(0,S()),E=o;o=0;let A=Math.round(t.clock.now()),W={batch_id:oc(),sent_at_ms:A,events:k.map($=>ic($,A))};try{let $=await Ii(n,W,h===void 0?void 0:{signal:h}),F=Pf($,E);l=0,d=0;for(let T of F.rejected)p(`[gem] analytics: an event was refused (${T.code}). See the analytics_events section of your game config.`);return F}catch($){if(Af($)){for(r=[...k,...r],o+=E;r.length>e;)r.shift(),o+=1;l+=1,d=t.clock.now()+cr(l,$);}else p(`[gem] analytics: ${k.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String($)}`);throw $}}return {track(h,k,E={}){if(s)return;if(typeof h!="string"||h===""){u||(u=true,p(`[gem] analytics: '${k}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(k.startsWith(xo)){m||(m=true,p(`[gem] analytics: '${k}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let A={},W={};for(let[$,F]of Object.entries(E))typeof F=="string"?A[$]=F:typeof F=="number"&&Number.isFinite(F)&&(W[$]=F);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:oc(),playerId:h,name:k,atMs:t.clock.now(),dimensions:A,measures:W}),r.length>=kf&&a===null&&y()===0?x().catch(()=>{}):_();},flush:h=>x(h),get pending(){return r.length},dispose(){s=true,g(),r=[],o=0;}}}function sc(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().");ht(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return rr(i)}}}function Tf(t){let e={};for(let[n,r]of Object.entries(Ci))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function Pt(t,e={}){let n=e.clock??ue,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let o=Ei(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=Dr({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new Fe({transport:i,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=Tf({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,m=t.endMatch,u=t.log,p=ac({client:s,clock:n,gameId:a.gameId,...typeof u=="function"?{log:y=>u.call(t,y)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);},setBackfill:async(y,_)=>{let S=await l.setMatchBackfill(a.matchId,{open:y.open,...y.seats===void 0?{}:{seats:y.seats}},_===void 0?{}:{signal:_});return {open:S.open,seats:S.seats??null}},reportPlayers:async(y,_)=>(await l.reportMatchPlayers(a.matchId,{players:y.map(x=>({player_id:x.playerId,state:x.state}))},_===void 0?{}:{signal:_})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new Ne(l.invokeFunction),challenges:sc(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let _=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),S=_.modified?_.body:void 0;if(S?.room_args==null||S.room_args_template==null)throw new M("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:S.room_args,room_args_template:S.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function it(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Tt(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function hn(t){return typeof t=="string"?t:t.slice().buffer}function qr(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 Ef=5e3,lc=3e4,dc=2e3,If=1e4,Cf=3,cc=1;async function uc(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let o=e.log===void 0?f=>console.info(f):e.log,i=f=>o?.(`[gem host] ${f}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,m=(f,I)=>{l&&(a=a.then(async()=>{if(!d)try{await I();}catch(D){i(`the bundle's ${f} handler threw: ${at(D)}. Serving continues.`);}}));},u=true,p,g,y,_=f=>{if(!u)return;u=false,m("leave",()=>s.leave?.(r,{cause:f??"left"}));let I=g;I&&queueMicrotask(()=>I(f));},S={send(f,I){if(!u)return;let D=Tt(it(I));m("message",()=>s.message?.(r,f,typeof f=="string",{reliable:D.reliable,ordered:D.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){_("closed");}},x=(f,I)=>{if(!u)return;let D=Tt(it(I));queueMicrotask(()=>{u&&p?.(f,D);});},C=new Map,h=f=>{let I=[];for(let D of $e){let Z=f.channels[D];try{Z.binaryType="arraybuffer";}catch{}let ge=Tt(D),An=Ct=>{let Je=qr(Ct?.data);Je!==null&&m("message",()=>s.message?.(f.playerId,Je.data,Je.isText,{reliable:ge.reliable,ordered:ge.ordered}));};Z.addEventListener("message",An),I.push(()=>Z.removeEventListener("message",An));}C.get(f.playerId)?.forEach(D=>D()),C.set(f.playerId,I);},k=f=>{C.get(f)?.forEach(I=>I()),C.delete(f);},E=new Set,A=new Map,W=(f,I,D)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...I?{rejoin:true}:{},...D?{superseded:true}:{}}),$=f=>{let I=C.has(f.playerId),D=E.has(f.playerId);E.add(f.playerId),h(f),I&&m("leave",()=>s.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>s.join?.(f.playerId,W(f,D,I)));},F=new Set,T=(f,I,D)=>{if(f===r){x(I,D);return}let Z=n.peer(f);if(Z===null){let ge=A.get(f);if(ge!==void 0&&e.clock.now()-ge<dc)return;F.has(f)||(F.add(f),i(`send to '${f}' dropped: no such connected player`));return}Z.send(hn(I),it(D));},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:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=u?[r]:[];for(let I of n.peers)f.push(I.playerId);return f},profile(f){let I=e.room()?.members.find(D=>D.playerId===f);if(!(!I||I.displayName===void 0))return {displayName:Ye.toPlain(I.displayName),...I.displayTag===void 0?{}:{displayTag:Ye.toPlain(I.displayTag)},...I.discriminator===void 0?{}:{discriminator:I.discriminator}}},playerNumber(f){return f===r?cc:n.peer(f)?.assignedPeerId},send(f,I,D){T(f,I,D);},broadcast(f,I){let D=I?.except;u&&r!==D&&x(f,I);for(let Z of n.peers)Z.playerId!==D&&Z.send(hn(f),it(I));},async endMatch(){let f=await He();return f.answer!=="ok"&&i(f.cause),f.answer},kick(f,I){if(f===r){_(I??"kicked");return}n.kick(f).catch(D=>{i(`kick of '${f}' failed: ${at(D)}`);});},log(f){i(f);},warn(f){i(`\u26A0 ${f}`);}},G=()=>{},j=new Promise(f=>{G=f;}),B=[],H=null,ne=async(f,I)=>{l=false;let D=a.then(async()=>{try{await s.shutdown(f);}catch(Z){i(`the bundle's shutdown threw: ${at(Z)}`);}});a=D,await D,_e();for(let Z of B.splice(0))Z();for(let Z of [...C.keys()])k(Z);_(I);},ie=(f,I)=>H||(H=(async()=>{await ne(I,f),n.close(),G();})(),H),Q=()=>H||(H=(async()=>{await ne({reason:"signal"},"left"),await n.leave().catch(f=>i(`leaving the match failed: ${at(f)}`)),G();})(),H),We=()=>H||(H=(async()=>{l=false;let f=await He();f.answer==="ok"?(await ne({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${f.cause}; leaving instead`),await ne({reason:"signal"},"left"),await n.leave().catch(I=>i(`leaving the match failed: ${at(I)}`))),G();})(),H),de=null,Re=()=>(de??=Pt(O,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),de),He=async()=>{try{return await ps({client:Re().client,gameId:()=>O.gameId},O.matchId,{},{signal:AbortSignal.timeout(Ef)}),{answer:"ok"}}catch(f){return f instanceof M&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${at(f)}`}}},X=null,J=false,ce=0,xe,Te=null,_e=()=>{J=true,X!==null&&(e.clock.clearTimeout(X),X=null),Te?.(),Te=null;},Sn=f=>{i(`heartbeats paused: ${f}; they resume when a fresh play token arrives`),Ve();let I=xe,D=false,Z=e.tokens.subscribe(ge=>{D||J||ge.token===I||Rn(ge)||(D=true,Te?.(),Te=null,ce=0,xe=void 0,Ve(),i("a fresh play token arrived; heartbeats resume"),X=e.clock.setTimeout(()=>{Ke();},0));});D?Z():Te=Z;},Ve=()=>{let f=de;de=null,f?.dispose();},Rn=f=>f.expiresAt*1e3<=e.clock.now(),Ke=async()=>{if(X=null,!J){try{await Re().client.post(`/v1/games/${encodeURIComponent(O.gameId)}/matches/${encodeURIComponent(O.matchId)}/heartbeat`,void 0,AbortSignal.timeout(If)),ce=0,xe=void 0;}catch(f){if(f instanceof M&&(f.reason==="forbidden"||f.reason==="not_found")){i(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),_e();return}if(Mf(f)){if(J)return;ce+=1;let I=e.tokens.current(),D=I===void 0?"this host holds no play token":Rn(I)?"this host's play token has expired":I.token===xe?"the platform refused this host's play token again":ce>=Cf?`the platform refused this host's play token ${ce} times in a row`:null;if(xe=I?.token,D!==null){Sn(D);return}}else ce=0,xe=void 0;i(`heartbeat failed: ${at(f)}`);}J||(X=e.clock.setTimeout(()=>{Ke();},lc));}},It=()=>{J||X!==null||(X=e.clock.setTimeout(()=>{Ke();},lc));};{let f=G;G=()=>{_e(),de?.dispose(),de=null,f();};}let xn=Promise.resolve().then(()=>s.init(O));a=xn.then(()=>{},()=>{}),m("join",()=>s.join?.(r,{playerNumber:cc,transport:"loopback"})),B.push(n.on("peerJoined",$)),B.push(n.on("peerLeft",(f,I)=>{k(f);let D=e.clock.now();for(let[Z,ge]of A)D-ge>=dc&&A.delete(Z);A.set(f,D),F.delete(f),m("leave",()=>s.leave?.(f,{cause:I}));})),B.push(n.on("error",f=>{i(`\u26A0 session error: ${f.message}`);})),B.push(n.on("matchEnded",f=>{H||Mi(y,f),ie("match ended",{reason:"match_ended",platform_reason:f});})),B.push(n.on("hostChanged",f=>{f!==r&&ie("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)$(f);try{await xn,It();}catch(f){l=false,_e(),d=true;for(let I of B.splice(0))I();for(let I of [...C.keys()])k(I);throw n.leave().catch(()=>{}),G(),f}return {matchId:n.matchId,localLink:S,onMatchEnded(f){y=f;},end:We,leave:Q,stop:f=>ie(f,{reason:"stopped"}),done:j}}function Mi(t,e){try{t?.(e);}catch{}}function Mf(t){return t instanceof M&&t.status===401||ee.isAuthError(t)}function at(t){return t instanceof Error?t.message:String(t)}function Oi(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 mc(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async a=>{r.isHost&&!Ti(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!==rt)return Oi("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return Oi("peer",d.matchId);let u=t.identity();if(u===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(s(l)),g=await uc(a,{session:p,clock:t.clock,gameId:u.gameId,channel:u.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:u.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return o.set(d.matchId,g),g.done.then(()=>{o.get(d.matchId)===g&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(a={}){let l=await i(a),d=a.onMatchEnded;if(l.protocol===rt){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Df(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let y=await cn(),_=async()=>t.p2p.connect({...s(a),certificate:y}),S=await _(),x=Ff(S,_,d,C=>{r.notifyMatchDisconnected(C).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(S.matchId,{redial:x.redial,abandon:x.abandon}),x.onClosed(()=>{e.get(S.matchId)?.abandon===x.abandon&&e.delete(S.matchId);})),x}let m=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),u=await m(),p=$f(u,m,r,n);return n&&(e.set(u.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(u.matchId)?.abandon===p.abandon&&e.delete(u.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var pc="link_closed",Of="host_unreachable",Gf=new Set(["failed","closed"]);function Lf(t){return Gf.has(t)?pc:Of}function Df(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 $f(t,e,n,r){let o=t.matchId,i=t,s="connected",a,l,d=[],m=false,u=false,p=y=>{if(s!=="closed"){s="closed";for(let _ of d.splice(0))_();l?.(y);}},g=y=>{y.link.onMessage((_,S)=>a?.(_,S)),y.link.onClose(_=>{if(y!==i||s==="closed")return;if(m||!r){p(_);return}let S=n.matchSession;if(S.phase==="suspended"&&S.matchId===o){s="suspended";return}p(_);});};return g(t),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return s},send(y,_){s==="connected"&&i.link.send(y,_);},onMessage(y){a=y;},onClose(y){l=y;},close(){if(s!=="closed"){if(m=true,s==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(s==="closed"||m)return "closed";if(u)return "connected";u=true;let _;try{_=await e(y===void 0?{}:{deadlineAt:y});}finally{u=false;}return m||s==="closed"?(_.close(),"closed"):(i=_,g(_),s="connected",n.notifyMatchConnected(o),"connected")},abandon(y){s!=="closed"&&(s==="connected"&&i.close(),p(y));},onClosed(y){s==="closed"?y():d.push(y);}}}function Ff(t,e,n,r,o,i=false){let s=t.matchId,a=t,l,d,m=[],u=[],p=[],g=false,y=false,_=false,S=false,x="connected",C=T=>{if(g)return;g=true,x="closed";for(let G of m.splice(0))G();for(let G of u.splice(0))G();for(let G of p.splice(0))G();let O=d;O&&queueMicrotask(()=>O(T));},h=T=>{for(let O of m.splice(0))O();for(let O of $e){let G=T.channels[O];try{G.binaryType="arraybuffer";}catch{}let j=Tt(O),B=H=>{let ne=qr(H?.data);ne!==null&&l?.(ne.data,j);};G.addEventListener("message",B),m.push(()=>G.removeEventListener("message",B));}},k=()=>a.peer(a.hostPlayerId),E=T=>{if(!(g||a.isHost)&&x!=="suspended"){if(r?.(T),i){x="suspended";return}C(T);}},A=T=>{for(let O of $e){let G=T.channels[O];if(typeof G.addEventListener!="function")continue;let j=()=>{k()===T&&E(pc);};G.addEventListener("close",j),m.push(()=>G.removeEventListener?.("close",j));}},W=T=>{h(T),A(T),!g&&(x="connected",o?.());},$=T=>{for(let O of u.splice(0))O();u.push(T.on("migrating",()=>{S=true;})),u.push(T.on("hostChanged",O=>{if(S=false,O===T.playerId){C("host_migrated_here");return}let G=k();G!==null&&W(G);})),u.push(T.on("peerJoined",O=>{O.playerId===T.hostPlayerId&&W(O);})),u.push(T.on("matchEnded",O=>{g||Mi(n,O),C(O);})),u.push(T.on("peerLeft",(O,G)=>{O===T.hostPlayerId&&E(Lf(G));}));};$(a);let F=k();return F!==null&&W(F),{matchId:s,protocol:"p2p",get state(){return x},send(T,O){x==="connected"&&k()?.send(hn(T),it(O));},onMessage(T){l=T;},onClose(T){d=T;},close(){y=true,C("closed"),a.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||_)return "connected";if(S)throw new L("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");_=true;let T;try{for(let G of m.splice(0))G();for(let G of u.splice(0))G();a.close(),T=await e();}finally{_=false;}if(g)return y?T.leave().catch(()=>{}):T.close(),"closed";a=T,$(a);let O=k();if(O===null)throw a.close(),new L("connection_failed","this peer rejoined the match but the host never answered with a link");return W(O),"connected"},abandon(T){C(T);},onClosed(T){g?T():p.push(T);}}}function gc(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 qf=12e4;function st(t,e){return {outcome:t,reason:e}}function yc(t){let e=false,n=new Map,r=(o,i,s,a)=>{if(!t.bridge.parentSupports(o))return Promise.resolve(st("unavailable","error"));if(e)return Promise.resolve(st("declined","busy"));let l=`purchase-${we()}`;return new Promise(d=>{let m={},u=g=>{n.delete(l)&&(e=false,t.clock.clearTimeout(m.timer),d(g));};e=true,n.set(l,{finish:u,check:s,label:a}),m.timer=t.clock.setTimeout(()=>u(st("unavailable","error")),t.timeoutMs??qf);let p=false;try{p=i(l);}catch{}p||u(st("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(st(i,Os(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(st("unavailable","error"));return}(async()=>{let m;try{m=await d;}catch{m="unknown";}if(m==="granted"){a(l===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:l});return}m==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(st("unavailable","error"));})();}}}async function fc(t,e){try{return (await za(t,e)).granted?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}var Nf="small_human",hc=/^[a-z][a-z0-9_]{0,31}$/,bc=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,jf=8;function Gi(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:Nf,id:e,modelUrl:n,iconUrl:r}]}function Uf(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 Bf(t){let e=t??{},n=typeof e.item_id=="string"&&bc.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&hc.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=or(e.icon_url),l=or(e.model_url),d=[];for(let m of Array.isArray(e.prices)?e.prices:[]){let u=m??{};typeof u.currency_slug=="string"&&u.currency_slug!==""&&typeof u.price=="number"&&Number.isSafeInteger(u.price)&&u.price>0&&d.push({currencySlug:u.currency_slug,price:u.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 Wf(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&hc.test(n)&&!e.includes(n)&&e.push(n),e.length===jf)break;return e}function vc(t){let e=new Set,n=Gi(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=Gi(o);if(!Uf(n,i)){n=i;for(let s of [...e])try{s(i);}catch(a){r(a);}}}),{async families(){return Wf(await t.configFamilies())},worn(o){let i=Gi(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=Bf(s);a!==void 0&&i.push(a);}return i},purchase(o){let i=o?.itemId,s=o?.currencySlug;return typeof i!="string"||!bc.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 _c(t,e){try{return (await Ea(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}function wc(t){return Ba(t)}var Hf=6e5;function kc(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-${we()}`;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??Hf);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 Vf=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),Kf=["utm_"];function Sc(t){return Vf.has(t)||Kf.some(e=>t.startsWith(e))}var Rc=16,xc=512,Jf=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,zf=/[\p{Cc}\p{Cf}]/u,Yf=/\p{Cs}/u,Ge="[gem] gem.share.request:";function Ac(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(`${Ge} the arcade does not handle share here \u2014 check gem.share.available first`);if(s!==void 0&&(typeof s!="object"||s===null))throw new TypeError(`${Ge} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!Qf(l))throw new TypeError(`${Ge} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>Rc)throw new TypeError(`${Ge} at most ${Rc} params; got ${d.length}`);let m=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!Jf.test(u))throw new TypeError(`${Ge} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Sc(u))throw new TypeError(`${Ge} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Ge} param ${g}: values must be strings`);if(p.length>xc)throw new TypeError(`${Ge} param ${g}: a value is at most ${xc} characters`);if(zf.test(p))throw new TypeError(`${Ge} param ${g}: control and format characters are not allowed`);if(Yf.test(p))throw new TypeError(`${Ge} param ${g}: a value must be well-formed text`);m.push({key:u,value:p});}!a.requestShare(m)&&!r&&(r=true,i("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function Qf(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var th="(any-pointer: coarse)";function nh(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 Pc(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},o=r.navigator,i,s=new Set,a=()=>typeof o?.vibrate!="function"||r.matchMedia===void 0?false:(i??=r.matchMedia(th),i.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,u)=>{s.has(m)||(s.add(m),n!==null&&(n===void 0?console.warn(u):n(u)));};return {get available(){return a()||l()},vibrate(m){let u=a();if(!u&&!l())return false;let p=nh(m);if(p===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(o?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(u)try{return o.vibrate(p)===!0}catch{return false}let g=e.requestVibrate(p);return g||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),g}}}var Et=Math.PI/180,Le=Object.freeze({touch:Object.freeze({yaw:1*Et,pitch:.66*Et}),mouse:Object.freeze({yaw:.5*Et,pitch:.5*.77*Et}),stick:Object.freeze({yaw:240*Et,pitch:240*.77*Et}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Li="[gem.controls]",Di=Object.freeze({yaw:0,pitch:0}),Nr=t=>Number.isFinite(t)?t:0,Tc=(t,e)=>({yaw:t+0,pitch:e+0});function Ec(t){let e=Nr(t),n=(Math.abs(e)-Le.stickDeadzone)/(1-Le.stickDeadzone),r=Le.stickCurve,o=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,o))+0}function rh(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Le.touchPitchMin)+Le.touchPitchMin}function Ic(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${Li} ${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(`${Li} ${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(`${Li} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function oh(t,e){let n=Ic(e,"look()"),r=n.sensitivity,o=n.gamepadSensitivity,i=n.invertY,s=a=>i??a?.invertLookY??false;return {fromPointer(a,l,d,m){let u=Nr(a),p=Nr(l);if(u===0&&p===0)return Di;let g=t(),y=r??(g===null?void 0:g.lookSensitivity/100)??1,_=d==="touch"||d==="pen",S=_?Le.touch:Le.mouse,x=u*S.yaw*y,C=-p*S.pitch*y;return s(g)&&(C=-C),_&&m!==void 0&&Number.isFinite(m)&&C*m>0&&(C*=rh(m)),Tc(x,C)},fromStick(a,l,d){let m=Nr(d);if(m<=0)return Di;let u=Ec(a),p=Ec(l);if(u===0&&p===0)return Di;let g=t(),y=o??(g===null?void 0:g.gamepadLookSensitivity/100)??1,_=u*Le.stick.yaw*m*y,S=-p*Le.stick.pitch*m*y;return s(g)&&(S=-S),Tc(_,S)},set(a){let l=Ic(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(o=l.gamepadSensitivity),"invertY"in l&&(i=l.invertY);}}}function Cc(t){return {look:e=>oh(t.recommended,e),LOOK_BASE:Le}}function Mc(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var ih=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Oc(t){if(typeof t!="string"||!ih.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function bn(){return {declared:false,grantable:false,heldLimitReached:false}}function Gc(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Oc(n.resets_at),o=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...bn(),...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=Oc(a),d=n.held_limit_reached===true,m=a!=null,u=i!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!u&&!m&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...o}}var ah=18e4,$i=32,sh=/^[a-z0-9_-]+$/,lh="rewarded_requires_user_gesture";function dh(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var ch=1e3;function uh(){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<=ch)return true}return false}var Lc=1e4;function mh(t){return t==="interstitial"||t==="rewarded"}function Dc(t){return typeof t=="string"&&t!==""&&t.length<=$i&&sh.test(t)}function ph(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function jr(t){return typeof t=="string"?JSON.stringify(t):typeof t}function $c(t){let e=false,n=new Map,r=new Map,o=new Set,i=d=>{try{t.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let m=t.log;if(m!==null)try{m===void 0?console.warn(`[gem] ${d}`):m(`[gem] ${d}`);}catch{}},l=d=>{let m=t.readAvailability;if(m===void 0)return Promise.resolve(bn());let u=r.get(d);if(u!==void 0)return u;let p=new Promise(g=>{let y={},_=h=>y.done===true?false:(y.done=true,t.clock.clearTimeout(y.timer),g(h),true),S=(h,k)=>{!_(bn())||o.has(h)||(o.add(h),i(`gem.ads.rewardedStatus("${d}") answered not grantable: ${k}. Said once.`));},x=h=>{S(ph(h),`the read failed (${h instanceof Error?h.message:jr(h)})`);},C;try{C=Promise.resolve(m(d,AbortSignal.timeout(Lc)));}catch(h){C=Promise.reject(h);}y.timer=t.clock.setTimeout(()=>{S("timeout","no answer within 10 s");},Lc),C.then(h=>{try{_(Gc(h,t.bridge.parentSupports("ads")));}catch(k){x(k);}},x);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return Dc(d)?l(d):(i(`gem.ads.rewardedStatus(${jr(d)}) answered not grantable: a placement is 1..${String($i)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(bn()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let m=d?.placement,u=d?.format;if(!Dc(m)||!mh(u))return i(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${jr(m)}, format ${jr(u)}. A placement is 1..${String($i)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});if(u==="rewarded"){let g;try{g=(t.userActivation??dh)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??uh)()===!0&&(g=!0);}catch{}if(g===false){let y=`${lh}: gem.ads.requestAd("${m}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return i(y),a(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${we()}`;return new Promise(g=>{let y={},_=x=>{n.delete(p)&&(e=false,t.clock.clearTimeout(y.timer),g(x));};e=true,n.set(p,_),y.timer=t.clock.setTimeout(()=>{_({outcome:"unavailable"});},t.timeoutMs??ah);let S=false;try{S=t.bridge.requestAd(p,m,u);}catch{}S||_({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",u=n.get(d.requestId);if(u===void 0){t.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}u({outcome:m});}}}var Fc=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),qc=18e4,gh=1e4,yh=/^[a-z0-9_-]{1,32}$/;function Nc(t){return typeof t=="string"?JSON.stringify(t):typeof t}var vn=Object.freeze({shown:false});function jc(t){let e=new Map,n,r=false,o=i=>{try{t.onDropped?.(i);}catch{}return vn};return {api:{signal(i){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(vn):(r=!0,Promise.resolve(o("moments_unsupported: gem.moments.signal answered shown: false without asking: this arcade does not do platform moments. Keep the call; it costs nothing. Said once.")));let s=i?.kind,a=i?.placement;if(!Fc.includes(s)||a!==void 0&&(typeof a!="string"||!yh.test(a)))return Promise.resolve(o(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${Nc(s)}, placement ${Nc(a)}. A kind is one of ${Fc.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'. Answering shown: false.`));if(!t.bridge.readyCalled())return Promise.resolve(o(`moments_before_ready: gem.moments.signal({ kind: '${s}' }) before gem.frame.ready(): a moment is a break in play, and play has not started. Signal from the press that leaves a break, never on boot. Answering shown: false.`));if(e.size>0)return Promise.resolve(o(`moments_in_flight: gem.moments.signal({ kind: '${s}' }) while another moment is still waiting for its answer. Signal once per break, and await the answer before play resumes. Answering shown: false.`));let l=t.clock.now();if(n!==void 0&&l-n<gh)return Promise.resolve(o(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(l-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let d=`moment-${we()}`;return new Promise(m=>{let u={},p=(y,_)=>{e.delete(d)&&(t.clock.clearTimeout(u.timer),_&&(n=t.clock.now()),m(y));};e.set(d,y=>p(y,!0)),u.timer=t.clock.setTimeout(()=>{e.has(d)&&(p(vn,!0),o(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??qc)/1e3)} s. Answering shown: false.`));},t.timeoutMs??qc);let g=!1;try{g=t.bridge.signalMoment(d,s,a);}catch{}g||p(vn,!1);})}catch{return Promise.resolve(vn)}}},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 Fi=16384;function Uc(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:fh(e)}function fh(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 hh=1e4,bh=5e3;function Bc(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=bh){return n?Promise.resolve(e):new Promise(a=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{t.clock.clearTimeout(m),l(),a(e);},m=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=Uc(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-${we()}`;return new Promise(m=>{let u={},p=y=>{o.delete(d)&&(t.clock.clearTimeout(u.timer),y==="stored"&&(e=l,n=true,i()),m(y));};o.set(d,p),u.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??hh);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,n=true,i();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=o.get(s.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var _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 vh=/^[a-z0-9][a-z0-9_-]{0,39}$/;function _h(t){return typeof t=="string"&&vh.test(t)}function Ur(t){if(t===null||_h(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 Wc(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function qi(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 Br(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 Hc(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function wh(t){let e=t.untrusted,n=be(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,o=r?be(r,"gem.player.displayTag"):void 0,i=t.discriminator||t.displayTag,s=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,a=t.avatarIconUrl||t.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=t.avatarIconId,m=t.avatar3dId,u={displayName:n,displayHandle:o??n,badges:(t.badges??[]).map(_=>({itemId:_.itemId,iconUrl:_.iconUrl}))};t.playerId&&(u.playerId=t.playerId),s&&(u.discriminator=s),o&&(u.displayTag=o),a&&(u.avatarIconUrl=u.avatarUrl=a),d&&l.test(d)&&(u.avatarIconId=d),m&&l.test(m)&&(u.avatar3dId=m),t.avatar3dModelUrl&&(u.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(u.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(u.avatars3d=t.avatars3d.filter(_=>l.test(_.id)&&/^[a-z][a-z0-9_]*$/.test(_.family)).filter((_,S,x)=>x.findIndex(C=>C.family==_.family)==S).map(({family:_,id:S,modelUrl:x,iconUrl:C})=>({family:_,id:S,modelUrl:x,iconUrl:C})));let p=t.boost,g=(p?.multipliers??[]).map(_=>({currencyId:_.currencyId,currencySlug:_.currencySlug,multiplier:_.multiplierBp/1e4})),y=g.some(_=>_.multiplier>1);return u.boost=y&&p?.expiresInDays?{active:y,multipliers:g,expiresInDays:p.expiresInDays}:{active:y,multipliers:g},u}var kh=1e4,wn=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??ue,this.inbound=new Dt(this.clock),this.outbound=new Dt(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=>ao(a,e.origin))||Es(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=qn["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!ao(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=Is($n,o.versions);return s===null?(i.onmessage=null,i.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${$n.min}..v${$n.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=s,i.onmessage=a=>this.receive(a.data,a.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:U,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:U,type:"gem.ready"});}settled(e=kh){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:U,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:U,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:U,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:U,type:"gem.exit"}:{gem:U,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:U,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:U,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:U,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:U,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:U,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:Wc(e.origin.x),y:Wc(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=Ur(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:U,type:"gem.portraitBorders"}:{gem:U,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:U,type:"gem.walletDisplay",...qi(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:U,type:"gem.menu",...Br(e)}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:U,type:"gem.gemCorner",corner:e}):false}requestShare(e){return this.gated("share")?this.send({gem:U,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:U,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:U,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:U,type:"gem.frameStats",fps:Hc(e.fps,1e3),frameTimeP95Ms:Hc(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:U,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:U,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:U,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:U,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,o,i,s){return this.send({gem:U,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:U,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:U,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:U,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r){return this.send({gem:U,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:U,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,o){return this.send({gem:U,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...o===void 0?{}:{params:o}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(Fn)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(Fn)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(Fn)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:U,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=qn[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||Vc(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=qn[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=xs(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let s=o(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=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 Vc(n.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(wh(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:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:U,type:"gem.screenshot.denied",reason:e,retryable:n});}};function Vc(t){for(let e of t)try{e?.close?.();}catch{}}var Kc="https://api.gemarcade.com";function Ni(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 Sh=new Set(["localhost","127.0.0.1","[::1]"]);function Jc(t){let e=Ni(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!Sh.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}function zc(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function Rh(){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 xh=Object.freeze({small_human:zc([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:zc(Rh())});var Ph=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),Th=Kc,Eh=["top-left","top-right","bottom-left","bottom-right"],Yc=8e3,ji=15e3,Ih=9e4,Ch=1/0,Mh=8e3,Oh=5e3,Gh=5e3;async function Lh(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 kn(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 tA(t={}){let e=t.clock??ue,n=t.log===void 0?c=>console.info(c):t.log,r=t.baseUrl??void 0;if(r!=null){let c=Ni(r);if(c!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${c}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=typeof window>"u"?void 0:window.location?.search,i=il(o),s=Ol(o),a=hi();a.mark("sdk created");let l=()=>gr(re.gameVersion,t.clientVersion?.gameVersion),d=new zt({client:()=>dt,clock:e,gameId:()=>re.identity?.gameId??null,playerId:()=>re.identity?.playerId??null,environment:()=>{let c=l();return {sdk_version:da(),...c===null?{}:{game_version:c}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),m=bd(()=>{a.mark("engaged"),d.release(),q.reportEngaged();},typeof window>"u"?{}:window),u=c=>{if(c===false)return null;let R=c?.attempts??Ch,N=c?.budgetMs??Ih;return !(R>0)||!(N>0)?null:{attempts:R,budgetMs:N,maxDelayMs:c?.maxDelayMs??Mh}},p=c=>{c.on("created",()=>{a.mark("room created");}),c.on("joined",()=>{a.mark("room joined");}),c.on("matchAllocationStarted",()=>{a.mark("allocation started");}),c.on("matchReady",()=>{a.mark("match ready");}),c.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 g=t.allowedEmbedders;if(g!=null&&!Array.isArray(g))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let y=Array.from(g??[]),_=y.filter(c=>typeof c!="string"||!io(c));if(_.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${_.length===1?"an entry":"entries"} that ${_.length===1?"is":"are"} not an origin: ${_.map(c=>typeof c=="string"?JSON.stringify(c):String(c)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let S=Object.freeze([...new Set([...Ph,...y])]),x=kn(e),C=new Set,h=kn(e),k=false,E=kn(e),A=ul(n),W=kn(e),$=t.manageAudio===false?null:xd();t.selectableText!==true&&Ad();let F=null,T=null,O=()=>{F===null||F===T||q.reportMuted(F)&&(T=F);},G,j,B=-1/0,H=null,ne=()=>{if(G===void 0||H!==null||G===j)return;let c=B+1e3-e.now();if(c>0){H=e.setTimeout(()=>{H=null,ne();},c);return}q.showPortraitBorders(G)&&(j=G,B=e.now());},ie=null,Q=null,We=()=>{if(ie===null)return false;let c=JSON.stringify(qi(ie.visible,ie.only));return c===Q?q.parentSupports("walletDisplay"):q.setWalletVisible(ie.visible,ie)?(Q=c,true):false},de=null,Re=null,He=()=>{if(de===null)return false;let c=JSON.stringify(Br(de.items));return c===Re?q.parentSupports("gameMenu"):q.setMenu(de.items)?(Re=c,true):false},X=null,J=null,ce=()=>X===null?false:X===J?q.parentSupports("gemCorner"):q.setGemCorner(X)?(J=X,true):false,xe=Pd({report:c=>q.reportFrameStats(c)}),Te=false,_e=Gd(()=>na,()=>Te),Sn=c=>{let R=Te&&!c,N=Te!==c;if(Te=c,R&&_e.close(),!!N)try{t.onDevToolsPermissionChange?.(c);}catch(ae){n?.(`[gem] onDevToolsPermissionChange threw: ${ae instanceof Error?ae.message:String(ae)}`),queueMicrotask(()=>{throw ae});}},Ve=r??Th,Rn=r!==void 0,Ke,It=c=>(n?.(`[gem] token refused: ${c}`),t.onError?.("internal",c),false),xn=(c,R)=>{if(c===void 0)return R!==void 0?It("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let N=Jc(c);return N!==null?It(`the embedder named an API root that cannot be used: ${N}. Its value is withheld here rather than written to logs.`):Ke!==void 0&&Ke!==c?It("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."):(Ke=c,Rn||(Ve=c),true)},f=window.location?.origin,I=null,D=-1/0,Z=2e3,ge=new Set,An=c=>I!==false?Promise.resolve(true):new Promise(R=>{let N=e.setTimeout(()=>{ge.delete(ae),R(false);},c),ae=()=>{e.clearTimeout(N),ge.delete(ae),R(true);};ge.add(ae);}),Ct=()=>{},Je=null,q=new wn({allowedEmbedders:S,...typeof f=="string"&&f!==""?{selfOrigin:f}:{},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","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:c=>{Je=c,t.onRefused?.(c);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:c=>{re.onBridgeState(c),c!=="connected"&&xe.setRequested(false),T=null,Q=null,Re=null,J=null,j=void 0,c==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Je===null?"":` (${Je})`)+", 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."),Ct()),c==="connected"&&(a.mark("bridge connected"),eu(),O(),ne(),We(),He(),ce(),q.unbiddenLaunch&&!m.engaged&&d.hold(),d.startSession(),m.engaged&&q.reportEngaged()),t.onStateChange?.(c);},onPlayer:c=>{x.set(c);for(let R of [...C])R(c);t.onPlayer?.(c);},onPrefs:c=>{let R={reducedMotion:c.reducedMotion,muted:c.muted,locale:c.locale,showFrameStats:c.showFrameStats===true,recommended:c.recommended===void 0?null:Object.freeze({volume:c.recommended.volume,batterySaver:c.recommended.batterySaver,keyboardLayout:c.recommended.keyboardLayout,gamepadConfirm:c.recommended.gamepadConfirm,vibration:c.recommended.vibration,lookSensitivity:c.recommended.lookSensitivity??100,gamepadLookSensitivity:c.recommended.gamepadLookSensitivity??100,invertLookY:c.recommended.invertLookY??false,touchMovement:c.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:Mc(c.recommended.graphicsQuality,c.recommended.batterySaver),graphicsQualityAuto:c.recommended.graphicsQualityAuto??true})};h.set(R),T=R.muted,$?.setMuted(R.muted),xe.setRequested(R.showFrameStats&&q.parentSupports("frameStats")),t.onPrefs?.(R);},onCohorts:c=>{let R=Object.freeze(c.cohorts.map(N=>Object.freeze({experimentId:N.experimentId,variantKey:N.variantKey})));E.set(R),t.onCohorts?.(R);},onEarnAllowanceChanged:()=>A.emit(),onViewport:c=>{let R=Object.freeze({insets:Object.freeze({top:c.insets.top,right:c.insets.right,bottom:c.insets.bottom,left:c.insets.left}),reserved:Object.freeze((c.reserved??[]).map(({x:ae,y:ra,width:oa,height:ia,control:Ot})=>Object.freeze(Ot?{x:ae,y:ra,width:oa,height:ia,control:Object.freeze({x:Ot.x,y:Ot.y,width:Ot.width,height:Ot.height})}:{x:ae,y:ra,width:oa,height:ia})))});W.set(R);let N=Ed();Id(N,R.insets),Md(N,R.reserved,Cd()),t.onViewport?.(R);},onPause:c=>{k=c.paused,d.setPaused(c.paused),xe.setPaused(c.paused),t.onPause?.(c.paused);},onMenuSelect:c=>{de===null||c.entry!=="item"||!(Br(de.items).items??[]).some(N=>N.id===c.id)||de.items?.find(N=>N.id===c.id)?.onSelect?.();},onWillTerminate:c=>{d.endSession(c.reason),t.onWillTerminate?.({reason:c.reason,graceMs:c.graceMs});},onToken:c=>{let R=c.garden;if(Sn(c.allowDevTools===true),!xn(c.apiBaseUrl,R))return;let N=c;re.onToken(N);let ae=re.identity;ae&&(Wr.set(ae),Wi||(Wi=true,me.reconcileSeats().catch(()=>{}))),Hi.push({token:N.token,expiresAt:N.expiresAt});},onTokenDenied:c=>{Sn(false),re.onDenied(c);},onScreenshot:(c,R,N)=>{kd(c,R,N,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Sd(q,t.onFeedbackContext);},onDevtools:c=>{c==="close"?_e.close():c==="open"?_e.openFrom("platform").catch(()=>{}):_e.isOpen?_e.close():_e.openFrom("platform").catch(()=>{});},onRoomEvent:c=>me.handleRoomEvent({event:c.event,roomId:c.roomId,...c.matchId===void 0?{}:{matchId:c.matchId},...c.version===void 0?{}:{version:c.version},...c.reason===void 0?{}:{reason:c.reason},...c.platform===void 0?{}:{platform:c.platform}}),onSeatedEvent:c=>me.handleSeated(c.roomId),onAutoStartFailedEvent:c=>me.handleAutoStartFailed(c.roomId,c.code),onTicketEvent:c=>me.handleTicketEvent({event:c.event,ticketId:c.ticketId,...c.partySize===void 0?{}:{partySize:c.partySize},...c.queuedAt===void 0?{}:{queuedAt:c.queuedAt},...c.expiresAt===void 0?{}:{expiresAt:c.expiresAt},...c.reason===void 0?{}:{reason:c.reason},...c.roomId===void 0?{}:{roomId:c.roomId}}),onSocketState:c=>{let R=I;if(I=c.connected,c.connected)for(let ae of [...ge])ae();if(!c.connected||R===true)return;let N=e.now();N-D<Z||(D=N,me.reconcile().catch(()=>{}));},onSignalEvent:c=>{let R=typeof c.data=="object"&&c.data!==null&&!Array.isArray(c.data)?c.data:{};ct.handleSignalEvent(c.matchId,c.event,R),c.event==="matchEnded"&&me.reconcile({matchId:c.matchId,...typeof R.reason=="string"?{reason:R.reason}:{}}).catch(()=>{});},onDedicatedEvent:c=>{c.event==="matchEnded"&&(Mt.handleMatchEnded(c.matchId,c.reason),me.reconcile({matchId:c.matchId,...c.reason===void 0?{}:{reason:c.reason}}).catch(()=>{})),Bi.handleEvent(c);},onClusterTarget:c=>In.accept(c.clusterTargetId,c.clusterTargetIds),onLocalServer:c=>Cn.accept(c),onLocalServerDenied:c=>Cn.refuse(c),onPartyResult:c=>Ki.settle(c.requestId,c.partyId),onPurchaseResult:c=>Vr.settle(c),onDeviceSettings:c=>{En.receive(c),t.onDeviceSettings?.(En.api.current);},onDeviceSettingsResult:c=>En.settle(c),onAdResult:c=>zi.settle(c),onMomentResult:c=>Yi.settle(c),onSignInResult:c=>Qi.settle(c),onFriendChallengeResult:c=>Xi.settle(c)}),Bi=new fn({bridge:q}),Wr=kn(e);Ct=()=>{Wr.release(),x.release(),E.release();},q.currentState==="refused"&&Ct();let Wi=false,Hr=new Set,Pn,Hi={current:()=>Pn,subscribe:c=>(Hr.add(c),Pn!==void 0&&c(Pn),()=>Hr.delete(c)),push:c=>{Pn=c;for(let R of [...Hr])try{R(c);}catch(N){n?.(`[gem] a server-token listener threw: ${N instanceof Error?N.message:String(N)}`);}}},re=Dd({bridge:q,clock:e,onStateChange:(c,R)=>{if(c==="ready"){if(a.mark("token ready")){let N=a.marks.find(ae=>ae.name==="token ready")?.at;d.trackPlatform("gem_boot_ready",N===void 0?{}:{boot_ms:Math.max(0,Math.round(N))});}}else c==="lost"&&(a.mark("token lost"),d.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(c,R);}}),Vi=()=>{let c=re.identity;return !c||re.source.currentState==="lost"?null:`${c.playerId}\0${c.gameId}\0${c.channel}`},eu=()=>{a.mark("token requested"),re.source.get().catch(()=>{});},Ki=gc({bridge:q,clock:e}),Tn={},Vr=yc({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c),confirm:async c=>Tn.confirm?.(c)??"unknown",confirmAvatar3d:async c=>Tn.confirmAvatar3d?.(c)??"unknown"}),En=Bc({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c)}),Ji={},zi=$c({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c),readAvailability:(c,R)=>Ji.read?.(c,R)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),Yi=jc({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c)}),Qi=kc({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c)}),Xi=cl({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c)}),In=_l({bridge:q,clock:e}),Cn=Od({bridge:q,clock:e}),Kr=c=>{let R=q.handleWindowMessage({data:c.data,origin:c.origin,source:c.source,ports:c.ports});return R&&window.removeEventListener("message",Kr),R};window.addEventListener("message",Kr);let lt=la(window,Kr),tu=lt?.capture,Jr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Jr?.domInteractive!==void 0&&Jr.domInteractive>0&&a.mark("document parsed",Jr.domInteractive),tu?.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 zr=t.handshakeWarningMs;zr!==null&&n&&e.setTimeout(()=>{let c=lt===null?"no capture script ran":`capture: ${lt.delivered} offer(s) delivered, ${lt.stale} stale, ${lt.capture.dropped} evicted${lt.capture.late?", installed late":""}`;if(q.currentState==="connected"){n(`[gem] handshake connected. boot: ${a.timeline()} \xB7 ${c}`);return}n(`[gem] no completed handshake after ${zr??Yc}ms (bridge state: ${q.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 `+c);},zr??Yc);let nu=Dr({get baseUrl(){return Ve},tokenSource:re.source,get defaultQuery(){let c=re.identity;return c?{game_id:c.gameId,channel:c.channel}:{}}}),dt=new Fe({transport:nu,clock:e}),ye={client:dt,gameId:()=>re.identity?.gameId??""};Tn.confirm=c=>fc(ye,c),Tn.confirmAvatar3d=c=>_c(ye,c),Ji.read=(c,R)=>hs(ye,"players","me",c,{signal:R});let ru=()=>re.identity?.channel??"release",Yr=new nr(ye,ru),ou=vc({player:()=>x.current,subscribe:c=>(C.add(c),()=>{C.delete(c);}),configFamilies:async()=>(await Yr.load())?.avatar_3d_families,readOffers:()=>wc(ye),purchase:c=>Vr.requestAvatar3d(c),log:t.log}),Zi=async c=>(await Yr.load())?.currency(c)?.id??void 0,ea=Yn(ye,ho,{identity:Vi,resolveCurrencyId:Zi}),Qr=async c=>{let R=await Wr.wait(c);if(R)return R;throw q.currentState==="refused"?new ee("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 ee("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).")},Xr=u(t.autoReconnect),me=Xl(s===void 0?{}:{playWithTicket:s},{client:dt,clock:e,gameId:()=>re.identity?.gameId??null,playerId:()=>re.identity?.playerId??null,awaitGameId:async()=>(await Qr(ji)).gameId,resolveParty:Ki.resolve,resolveClusterTargets:In.resolveList,refreshClusterTargets:In.refresh,ensureLocalServer:Cn.ensure,localHostAvailable:Cn.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>re.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},...Xr===null?{}:{autoReconnect:{...Xr,redial:(c,R)=>Zr.redialMatch(c,R),abandon:(c,R)=>Zr.abandonMatch(c,R)}}});p(me),fd({analytics:d,rooms:me});let ct=yd({client:dt,clock:e,rooms:me,bridge:q,gameId:()=>re.identity?.gameId??"",baseUrl:()=>Ve,resolveClusterTarget:In.resolve,boot:a,...t.log===void 0?{}:{log:t.log}}),ta=fi(a,n),Mt=Zd({client:dt,clock:e,rooms:me,signaling:()=>Bi.channel(),signalingReady:An,log:n??(()=>{})}),Zr=mc({rooms:me,p2p:{connect:c=>ta(ct.connect(c)),session:c=>ct.session(c)},dedicated:{connect:(c=>Mr(a,"welcome",Mt.connect(c),n))},clock:e,identity:()=>re.identity,apiBaseUrl:()=>Ve,tokens:Hi,room:()=>me.currentRoom,autoReconnect:Xr!==null,...t.log===void 0?{}:{log:t.log}}),iu=async()=>(await Qr(ji)).playerId,na={client:dt,boot:a,get identity(){return re.identity},awaitIdentity:(c=ji)=>Qr(c),awaitBridge:c=>q.settled(c),get player(){return x.current},awaitPlayer:(c=Oh)=>x.wait(c),me:ea,characters:new Xn(ye,void 0,Vi,Zi),transfers:new er(ye,ho,ea.inventory),gameConfig:Yr,purchases:Vr.api,deviceSettings:En.api,moments:Yi.api,ads:zi.api,account:Qi.api,share:Ac({frame:q,log:t.log}),vibration:Pc({frame:q,log:t.log}),get avatarPickerAvailable(){return q.currentState==="connected"&&q.parentSupports("avatarPicker")},openAvatarPicker:c=>q.requestAvatarPicker(c?.tab),avatars3d:ou,controls:Cc({recommended:()=>h.current?.recommended??null}),analytics:d,leaderboards:new Ut(ye),challenges:new qt(ye),showcase:new Bt(ye,iu),friends:new Wt(ye,{challenge:Xi.challenge,...i===void 0?{}:{launchedChallengeId:i}}),platform:new Vt(ye,A,n),profiles:new Kt(ye),functions:new Ne((c,R)=>rs(ye,c,R)),get prefs(){return h.current},get paused(){return k},get cohorts(){return E.current},get viewport(){return W.current},awaitCohorts:(c=Gh)=>E.wait(c),reportMuted:c=>{F=!!c,O();},showPortraitBorders:c=>{let R=Ur(c);R!==void 0&&(G=R,ne());},cueReward:c=>q.cueReward(c),setWalletVisible:(c,R)=>{let N=Array.isArray(R?.only)?[...R.only]:void 0;return ie=N===void 0?{visible:c===true}:{visible:c===true,only:N},We()},setMenu:c=>(de=Array.isArray(c?.items)?{items:c.items.map(R=>({...R}))}:{},He()),setGemCorner:c=>{if(!Eh.includes(c)){let R=typeof c=="string"?JSON.stringify(c.slice(0,48)):`a value of type ${typeof c}`;return console.warn(`[gem] setGemCorner: ${R} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return X=c,ce()},reportFrame:()=>xe.draw(),exit:c=>Lh(me,q,c,d),frame:q,devtools:_e,rooms:me,dedicatedServer:{listClusterTargets:c=>Mt.listClusterTargets(c),connect:(c=>Mr(a,"welcome",Mt.connect(c),n)),handleMatchEnded:(c,R)=>Mt.handleMatchEnded(c,R)},p2p:{handleSignalEvent:(c,R,N)=>ct.handleSignalEvent(c,R,N),session:c=>ct.session(c),connect:c=>ta(ct.connect(c))},match:Zr};return na}var Qc="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 Ui(t,e={}){let n=e.clock??ue,r=()=>{let a=t();if(a===null)throw new Error(Qc);return a},o=null,i=()=>{if(o===null)throw new Error(Qc);return o};return {server:{get identity(){return i().identity},get client(){return i().client},get api(){return i().api},get match(){return i().match},get analytics(){return i().analytics},get functions(){return i().functions},get challenges(){return i().challenges},get room(){return i().room},dispose(){o?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(a){let d=r().profile?.(a);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:be(m,"profile.displayName"),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:be(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=Pt(r(),{...e,clock:n});}}}function Xc(t,e={}){let{server:n,attach:r}=Ui(()=>t,e);return r(),n}function Dh(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:je(e)}}}var $h=1e4;function Fh(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout($h));}catch{return}r.catch(o=>{o instanceof M&&o.status>=400&&o.status<500&&(e=o.status!==429);});}}function Zc(t,e={}){return ()=>{let n=null,{server:r,attach:o}=Ui(()=>n,e),i=t(r),s={async init(l){n=l,o(),await i.init?.();},async shutdown(l){let d=Dh(l);try{await i.shutdown?.(d);}finally{r.dispose();}}},a=Fh(r);return s.join=(l,d)=>(a(l),i.join?.(l,d)),i.leave&&(s.leave=(l,d)=>i.leave?.(l,d)),i.message&&(s.message=(l,d,m,u)=>i.message?.(l,d,m,u)),s}}sa();
1
+ var GemWebSdkGame=(function(exports){'use strict';var au=Object.defineProperty;var su=(t,e)=>{for(var n in e)au(t,n,{get:e[n],enumerable:true});};var eo="GemWebSdkHandshake";function lu(){return typeof document>"u"?void 0:document.readyState}var aa=()=>Date.now();function sa(t={}){let e=t.win??window,n=e,r=n[eo];if(r!==void 0)return r;let o=t.readyState??lu,i=t.now??aa,s=[],a=[],l=m=>{let u=m.data;!u||u.type!=="gem.handshake"||(s.length>=4&&(s.shift(),a.shift(),d.dropped+=1),s.push(m),a.push(i()));};e.addEventListener("message",l);let d={events:s,times:a,dropped:0,late:o()==="complete",uninstall(){e.removeEventListener("message",l);}};return n[eo]=d,d}function la(t,e,n={}){let r=t[eo];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??aa,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,m=false,u=i()-o;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(s[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:13.4.1]";function da(){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 du={initialDelayMs:2e3,maxDelayMs:6e4};function cu(t,e){return e!==void 0?!e:t==="chain_exhausted"}var ut=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 ee(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 ee("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new ee(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}=du,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 ee("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=uu(o),{retryable:s,retryAfterMs:a}=o??{};throw n===this.generation&&(cu(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 ee?o:new ee(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)}},ee=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 uu(t){if(t instanceof ee)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var oe=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}},Mn=["if-match","if-none-match"],ca=4096;function mu(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!Mn.includes(o)||r===void 0)continue;let i=typeof r=="string"?pu(r):r;if(typeof i!="string"||i.length>ca||!gu(i))throw new oe(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${ca} 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 pu(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 gu(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 yu(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new oe("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new oe("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function ua(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=mu(o.headers),s=yu(o),a=Object.freeze({...o,headers:i,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await t(a,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),u=await t(a,m);if(u.status===401)throw e.tokenSource.close("unavailable"),new ee("unavailable","the server refused a freshly minted token");return u}}}function On(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(fu(e))}function Gn(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 to(t){return new TextDecoder().decode(Gn(t))}function fu(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var M=class extends Error{constructor(n,r,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"}},pa=new WeakMap;function ga(t){return pa.get(t)??{}}var hu=new Set([408,429,500,502,503,504]),bu=6e4;function vu(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new oe(`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 Fe=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,...Gt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...Gt(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,...Gt(o)},o.replaySafe===true,o.retryRateLimited!==false);return {bytes:_u(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,...Gt(o)},o.replaySafe===true,o.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Gt(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?vu(this.options.maxRetries)+1:1,i=null;if(e.signal?.aborted)throw ma(e.signal);for(let s=0;s<o;s++){if(s>0&&await this.backoff(s,i,e.signal),e.signal?.aborted)throw ma(e.signal);let a;try{a=await this.options.transport.request(e);}catch(d){if(ee.isAuthError(d)||oe.isRefusal(d)||e.signal?.aborted||wu(d))throw d;i=new M("unavailable",0,String(d));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let l=ku(a);if(!hu.has(a.status)||a.status===429&&!r)throw l;i=l;}throw i??new M("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let o=n?.retryAfterSeconds,i=o!==void 0?o*1e3:2**(e-1)*250,s=2**(e-1)*250,a=Math.min(Math.max(i,s),bu);return new Promise(l=>{let d=this.options.clock,m=false,u=false,p,g=()=>{m||(m=true,u&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,a),u=true,m&&d.clearTimeout(p);})}};function _u(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 Gt(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function ma(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function wu(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function ku(t){let e=Ru(t),n=Au(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&pa.set(e,r),e}var Su=new Map([["insufficient_funds","insufficient_funds"]]);function Ru(t){let{status:e,body:n}=t,r=xu(n),o=t.retryAfterSeconds??Tu(n),i=Pu(n),s=i===void 0?void 0:Su.get(i);if(s!==void 0)return new M(s,e,r,void 0,i);switch(e){case 304:return new M("not_modified",e,r);case 400:case 422:return new M("invalid",e,r,void 0,i);case 403:return new M("forbidden",e,r,void 0,i);case 404:return new M("not_found",e,r,void 0,i);case 402:return new M("insufficient_funds",e,r,void 0,i);case 409:return new M("conflict",e,r,void 0,i);case 412:return new M("precondition_failed",e,r,void 0,i);case 413:return new M("too_large",e,r,void 0,i);case 429:return new M("rate_limited",e,r,o,i);default:return new M("unavailable",e,r,o,i)}}function xu(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 Au(t){let n=t?.error?.details;return n===null?void 0:n}function Pu(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Tu(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}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 ya(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function fa(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 ha(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function ba(t,e,n){let r=`/v1/games/${v(t.gameId())}/matchmaking/tickets/${v(e)}`;return t.client.delete(r,n?.signal)}async function va(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 _a(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function wa(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 ka(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 Sa(t,e,n){let r=`/v1/games/${v(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function Ra(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function xa(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Aa(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(o,r?.signal)}async function Pa(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 Ta(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 Ea(t,e,n){let r=`/v1/games/${v(t.gameId())}/avatars-3d/${v(e)}/owned`;return t.client.get(r,n?.signal)}async function Ia(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 Ca(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.get(r,n?.signal)}async function Ma(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Oa(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 Ga(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 La(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 Da(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 $a(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 Fa(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 qa(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 Na(t,e,n,r){let o=new URLSearchParams;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 no(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 ja(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)}/friends`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Ua(t,e,n){let r=`/v1/showcase/friends/${v(e)}`;return t.client.get(r,n?.signal)}async function Ba(t,e){let n=`/v1/games/${v(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function Wa(t,e,n){let r=`/v1/inbox/friend-challenges/${v(e)}`;return t.client.get(r,n?.signal)}async function Ha(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 Va(t,e){let n=`/v1/games/${v(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function Ln(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Ka(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function Ja(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 za(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${v(e)}`;return t.client.get(r,n?.signal)}async function Ya(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function Qa(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function Xa(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function Za(t,e,n){let r=`/v1/games/${v(t.gameId())}/matchmaking/tickets/${v(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function es(t,e,n){let r=`/v1/games/${v(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 ts(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ns(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/platform-funded-game-inventory-purchases`;return t.client.post(i,r,o?.signal)}async function rs(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function os(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 is(t,e){return t.client.get("/v1/characters",e?.signal)}async function as(t,e,n,r){let o=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function ss(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 ls(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 ds(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 cs(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 us(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 ms(t,e,n){let r=`/v1/inbox/friend-challenges/${v(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function ps(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/matches/${v(e)}/end`;return t.client.post(o,n,r?.signal)}async function gs(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 ys(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 fs(t,e,n,r,o){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(i,r,o?.signal)}async function hs(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/rewarded-placements/${v(r)}/availability`;return t.client.get(i,o?.signal)}async function bs(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function vs(t,e,n,r){let o=`/v1/characters/${v(e)}`;return t.client.patch(o,n,r?.signal)}async function _s(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 ws(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 ks(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.delete(r,n?.signal)}var U="gem-web-bridge",$n={min:1,max:1},mt=65536,Ss=8,Dn=5e3,Rs=1024;var Lt=Object.create(null),Fn="__malformed";var oo=Object.create(null),Eu=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"]]);function xs(t){let e=oo[t];if(e!==void 0)return e;for(let[n,r]of Eu)if(t.startsWith(n))return r}function io(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 Iu(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 Cu(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Mu(t){return /^[a-z_]+$/.test(t)}function ro(t,e,n){if(e>Ss)return `nesting deeper than ${Ss}`;if(++n.nodes>Dn)return `more than ${Dn} values`;if(n.bytes>mt)return `over the ${mt} 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>Rs)return `an array of ${t.length} entries, over the ${Rs} limit`;n.bytes+=2;for(let a of t){let l=ro(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>Dn)return `more than ${Dn} values`;if(n.bytes+=a.length*3+4,n.bytes>mt)return `over the ${mt} byte limit`;let l=ro(s[a],e+1,n);if(l)return l}return null}function Ou(t){let e={nodes:0,bytes:0,seen:new Set},n=ro(t,0,e);return n?`message contains ${n}`:e.bytes>mt?`message is over the ${mt} byte limit`:null}var Gu={origin:[io,"not a well-formed origin"],url:[Iu,"not a safe absolute http(s) URL"],bcp47:[Cu,"not a well-formed BCP 47 tag"],code:[Mu,"not a code of lower-case letters and underscores"]};function As(t,e,n){for(let r of e){let o=n===""?r.n:`${n}.${r.n}`,i=t[r.n];if(i==null){if(r.o)continue;return `${o}: required`}let s=Ps(i,r,o);if(s)return s}return null}function Ps(t,e,n){switch(e.k){case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e.max)return `${n}: exceeds ${e.max} characters`;if(e.f){let[r,o]=Gu[e.f];if(!r(t))return `${n}: ${o}`}return null}case "i":return typeof t!="number"||!Number.isInteger(t)?`${n}: expected integer`:t<e.lo||t>e.hi?`${n}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let r=e.v;return r.includes(t)?null:`${n}: not one of ${r.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:As(t,e.fs,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.max)return `${n}: exceeds ${e.max} items`;let r=e.it,o=`${n}[]`;for(let i of t){if(i==null){if(r.o)continue;return `${o}: required`}let s=Ps(i,r,o);if(s)return s}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}var Ts=Object.create(null);function P(t,e,n,r){return Lt[t]=n,r&&(oo[t]=r),Ts[t]=o=>{let i=Ou(o);if(i)return i;if(typeof o!="object"||o===null||Array.isArray(o))return "message: expected object";let s=o;return s.gem!==U?"gem: wrong protocol marker":s.type!==t?`type: expected ${t}`:As(s,e,"")}}P("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}],30);P("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}],5);P("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}],30);P("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}],30);P("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"avatar3dId",k:"s",o:1,max:64},{n:"avatar3dModelUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatar3dIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatars3d",k:"a",o:1,max:8,it:{n:"",k:"o",fs:[{n:"family",k:"s",max:32},{n:"id",k:"s",max:64},{n:"modelUrl",k:"s",max:256,f:"url"},{n:"iconUrl",k:"s",max:256,f:"url"}]}},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}],12);P("gem.pause",[{n:"paused",k:"b"}],120);P("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"},{n:"graphicsQuality",k:"s",o:1,max:16,f:"code"},{n:"graphicsQualityAuto",k:"b",o:1}]}],60);P("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}],12,"cohorts");P("gem.earnAllowanceChanged",[],30,"earnAllowance");P("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384},{n:"control",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}]}}],60,"viewport");P("gem.deviceSettings",[{n:"settings",k:"j",o:1}],12,"deviceSettings");P("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}],10);P("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}],120,"rooms");P("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}],12,"socketState");P("gem.seatedEvent",[{n:"roomId",k:"s",max:64}],60,"partySeating");P("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}],30,"autoStartFailure");P("gem.ticketEvent",[{n:"event",k:"e",v:["queued","matched","expired","cancelled","failed"]},{n:"ticketId",k:"s",max:64},{n:"partySize",k:"i",o:1,lo:1,hi:64},{n:"queuedAt",k:"i",o:1,lo:0,hi:4102444800},{n:"expiresAt",k:"i",o:1,lo:0,hi:4102444800},{n:"reason",k:"s",o:1,max:64},{n:"roomId",k:"s",o:1,max:64}],60,"ticketEvents");P("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1800,"p2p");P("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}],120,"dedicated");P("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}],30,"parties");P("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}],12,"clusterTarget");P("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}],30,"devtools");P("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}],6,"screenshot");P("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}],12,"screenshot");P("gem.requestContext",[],12,"feedbackContext");P("gem.gameContext",[{n:"context",k:"j"}],12,"feedbackContext");P("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1200,"p2p");P("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}],60,"dedicated");P("gem.partyRequest",[{n:"requestId",k:"s",max:64}],12,"parties");P("gem.ready",[],5);P("gem.engaged",[],5,"engagement");P("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}],600);P("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}],12);P("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}],6,"localHost");P("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}],30,"localHost");P("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}],30,"localHost");P("gem.exit",[{n:"reason",k:"s",o:1,max:64}],5);P("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}],6);P("gem.requestFullscreen",[{n:"enabled",k:"b"}],30);P("gem.audioState",[{n:"muted",k:"b"}],120,"audioState");P("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}],60,"rewardCue");P("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}],60,"walletDisplay");P("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}],60,"controls");P("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}],60,"gameMenu");P("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}],60,"gameMenu");P("gem.gemCorner",[{n:"corner",k:"e",v:["top-left","top-right","bottom-left","bottom-right"]}],12,"gemCorner");P("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}],6,"share");P("gem.requestAvatarPicker",[{n:"tab",k:"e",o:1,v:["2d","3d"]}],6,"avatarPicker");P("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}],600,"vibration");P("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5},{n:"counts",k:"e",o:1,v:["pageFrames","gameDraws"]}],120,"frameStats");P("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}],60,"portraitBorders");P("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}],60);P("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}],12,"purchases");P("gem.requestAvatar3dPurchase",[{n:"requestId",k:"s",max:64},{n:"itemId",k:"s",max:64},{n:"currencySlug",k:"s",max:32}],12,"avatar3dPurchases");P("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}],30,"purchases");P("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}],30,"deviceSettings");P("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}],30,"deviceSettings");P("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}],6,"ads");P("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}],12,"ads");P("gem.signalMoment",[{n:"requestId",k:"s",max:64},{n:"kind",k:"e",v:["level_end","run_end","match_end","menu_return","other_break"]},{n:"placement",k:"s",o:1,max:32}],6,"moments");P("gem.momentResult",[{n:"requestId",k:"s",max:64},{n:"shown",k:"b"}],12,"moments");P("gem.requestSignIn",[{n:"requestId",k:"s",max:64}],6,"signIn");P("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}],12,"signIn");P("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}],12,"friendChallenges");P("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}],30,"friendChallenges");var qn=Object.freeze(Ts);Lt.__malformed=60;Object.freeze(Lt);Object.freeze(oo);var ue={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Dt=class{constructor(e=ue){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Lt[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 ao(t,e){return t.toLowerCase()===e.toLowerCase()}function pt(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Es(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:pt(n.hostname)&&pt(r.hostname)}function Is(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 Nn=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let o=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,i=o.find(a=>a.currencyId===e),s;return !i&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(i=o.find(a=>a.currencyId===s))),{currencyId:i?i.currencyId:s??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function lo(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let o=r??{};typeof o.id!="string"||o.id===""||typeof o.threshold!="number"||!Number.isFinite(o.threshold)||n.push({id:o.id,threshold:o.threshold,points:typeof o.points=="number"?o.points:0,hidden:o.hidden===true,...typeof o.unlocked_at=="number"&&Number.isFinite(o.unlocked_at)?{unlockedAt:o.unlocked_at}:{},...o.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var Cs="inventory",gt=t=>typeof t=="number"?t:0,$t=t=>typeof t=="string"?t:"";function so(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 Ms(t){let e=t??{};return {itemDefinitionId:$t(e.item_definition_id),instanceId:$t(e.instance_id),quantity:gt(e.quantity),acquiredAt:gt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function Lu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:so(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(s=>{let a=s??{};return {bucket:$t(a.bucket),balance:gt(a.balance)}}):void 0;return {currencyId:$t(o.currency_id),total:gt(o.total),...i===void 0?{}:{buckets:i}}}),items:so(e.items,Ms),progressions:so(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:$t(o.progression_definition_id),currentValue:gt(o.current_value),completionCount:gt(o.completion_count),isCompleted:o.is_completed===true,...lo(o)}}),...n===void 0?{}:{etag:n}}}var jn=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Cs}#buckets`:Cs;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 La(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(Ms):[]}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 Ga(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 Lu(n)}};var Du={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},$u=new Set(Object.keys(Du));function Os(t){return typeof t=="string"&&$u.has(t)?t:"error"}var qe=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var te=t=>typeof t=="string"?t:"",Fu=t=>typeof t=="string"?t:te(t&&typeof t=="object"?t.type:void 0),Ee=t=>typeof t=="number"?t:0;function qu(t){let e=t??{};return {prerequisiteType:te(e.prerequisite_type),referenceId:te(e.reference_id),required:Ee(e.required),current:Ee(e.current)}}function Ft(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:te(e.order_id),status:te(e.status),...n===void 0?{}:{etag:n}}}function Un(){return crypto.randomUUID()}var Nu="recipe-usage",Gs=100;function Bn(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:te(e.currency_id),bucket:te(e.bucket),delta:Ee(e.delta),balanceAfter:Ee(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:te(e.item_definition_id),instanceId:te(e.instance_id),delta:Ee(e.delta),quantityAfter:Ee(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:te(e.progression_definition_id),delta:Ee(e.delta),valueAfter:Ee(e.value_after),completed:e.completed===true};default:return {kind:"other",type:te(e.type)}}}function ju(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:te(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(Bn):[]}}function Uu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(ju):void 0;return {orderId:te(e.order_id),status:te(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(Bn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(Bn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(Bn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Bu(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:te(e.target_order_id)||te(e.source_order_id),status:te(e.status),purchaseId:te(e.purchase_id),sourceOrderId:te(e.source_order_id),price:{currencyId:te(n.platform_currency_id),amount:Ee(n.price)}}}function Wu(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:te(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 Ls(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 Wn=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(()=>ka(this.api,this.entity.type,this.entity.id,{operations:e.map(Ls),source:n.source??"play",nonce:Un()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Ft(r)}async createMany(e,n={}){return this.write(()=>wa(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Ls),nonce:Un()})),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 qa(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(qu):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>Fu(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(Nu,[],async()=>{let n=await Na(this.api,this.entity.type,this.entity.id,{limit:Gs})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(Wu),truncated:r.length>=Gs}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let u=e,p=await this.write(()=>Pa(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:Un()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...Uu(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,o]=await Promise.all([Ja(this.api,n.signal===void 0?{}:{signal:n.signal}),Ln(this.api,n.signal===void 0?{}:{signal:n.signal})]),i=e.payment.currencySlug.toLowerCase(),s=o.currencies.find(u=>u.currency_id.toLowerCase()===i||u.slug.toLowerCase()===i);if(s===void 0){let u=o.currencies.map(p=>p.slug);throw new qe("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let a=e.kind==="item"?r.items.find(u=>u.item_id===e.targetId):r.recipes.find(u=>u.recipe_id===e.targetId&&u.catalog_id===e.catalogId);if(a===void 0)throw new qe("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=a.platform_prices.find(u=>u.platform_currency_id===s.currency_id);if(l===void 0){let u=g=>o.currencies.find(y=>y.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new qe("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new qe("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>ns(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:Un(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return Bu(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let o=await this.write(()=>fa(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Ft(o)}async maxProgression(e,n,r){let o=await this.write(()=>gs(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Ft(o)}async claimProgression(e,n){let r=await this.write(()=>va(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Ft(r)}async resetProgression(e,n){let r=await this.write(()=>ws(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Ft(r)}async write(e){return this.cache.invalidate(),e()}};var co=t=>typeof t=="string"?t:"",Hu=t=>typeof t=="number"?t:0;function Ds(t){let e=t??{};return {orderId:co(e.order_id),status:co(e.status),source:co(e.source),createdAt:Hu(e.created_at)}}var Hn=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await ss(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(Ds):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await $a(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Ds(r)}};var $s=t=>typeof t=="number"?t:0,Vu=t=>typeof t=="string"?t:"";function Ku(t){let e=t??{};return {progressionDefinitionId:Vu(e.progression_definition_id),currentValue:$s(e.current_value),completionCount:$s(e.completion_count),isCompleted:e.is_completed===true,...lo(e)}}var Vn=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 Fa(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Ku(i)}catch{return o??null}}};var Kn=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 u=a.filledAt;if(u!==void 0&&(o===void 0||this.clock.now()-u<=o))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,m=r().then(u=>(i&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function uo(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 mo(t){try{let e=uo(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var se=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},Ju=3e4,Fs="the save payload could not reach storage. From a browser this is almost always the storage account's CORS rule, which the platform owns and your game cannot change. If every save fails this way, report it rather than working around it",zu=/^[A-Za-z0-9_]{1,64}$/;function Ie(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(!zu.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function qs(t,e){let n=new AbortController,r=AbortSignal.timeout(e),o=()=>n.abort(r.reason),i=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",i,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",o),t?.removeEventListener("abort",i);}}}function po(t,e){return t.aborted&&e?.aborted!==true}var Yu=new Set(["x-ms-blob-type"]),Qu=/^[ -~]+$/;function Xu(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new se("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(!Yu.has(i))throw new se("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"||!Qu.test(o))throw new se("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 se("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function go(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 yo(t){return t?.reason==="not_found"}var Jn=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let o;try{o=JSON.stringify(n);}catch(i){throw new se("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 se("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),s=qs(r.signal,i);try{let a=await _s(this.api,this.entity.type,this.entity.id,Ie(e),{size_bytes:n.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:s.signal});if(typeof a.upload_url!="string"||typeof a.session_id!="string")throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=Xu(a.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(a.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:n,credentials:"omit",signal:s.signal});}catch(u){throw po(s.signal,r.signal)?this.timeout("upload",i):new se("upload_failed",`${Fs} for PUT. Underlying error: ${u}`)}if(!d.ok){let u=await mo(d);throw new se("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+u:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+u)}return go(await Ta(this.api,this.entity.type,this.entity.id,Ie(e),{session_id:a.session_id},{signal:s.signal}))}catch(a){throw this.rethrow(a,r.signal,s.signal,"save",i)}finally{s.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new se("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${o}`)}}async getBytes(e,n={}){let r=this.budget(n.timeoutMs),o=qs(n.signal,r);try{let i;try{let l=await no(this.api,this.entity.type,this.entity.id,Ie(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(yo(l))return null;throw l}if(typeof i.download_url!="string")throw new se("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let s=this.options.fetch??globalThis.fetch.bind(globalThis),a;try{a=await s(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw po(o.signal,n.signal)?this.timeout("download",r):new se("download_failed",`${Fs} for GET. Underlying error: ${l}`)}if(!a.ok){let l=await mo(a);throw new se("download_failed",`the save download answered ${a.status}. `+(a.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await a.arrayBuffer())}catch(i){throw this.rethrow(i,n.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,n={}){try{let r=await no(this.api,this.entity.type,this.entity.id,Ie(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?go(r.body):null}catch(r){if(yo(r))return null;throw r}}async list(e={}){let n=await ls(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(go),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await xa(this.api,this.entity.type,this.entity.id,Ie(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!yo(r))throw r}}budget(e){return e??this.options.timeoutMs??Ju}timeout(e,n){return new se("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof se?e:po(r,n)?this.timeout(o,i):e}};function Zu(t){try{return to(t)}catch{return t}}function fo(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"?Zu(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var zn=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await as(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>fo(o)):[]}async get(e,n={}){try{let r=await Oa(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?fo(r.body,r.etag):null}catch(r){if(Ns(r))return null;throw r}}async put(e,n,r={}){let o=await ys(this.api,this.entity.type,this.entity.id,e,{value:On(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return fo(o)}async delete(e,n){try{await Ra(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!Ns(r))throw r}}};function Ns(t){return t?.reason==="not_found"}function Yn(t,e,n={}){let r=new Kn(ue,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new jn(t,e,r);return {settings:new zn(t,e),inventory:o,saves:new Jn(t,e,n.saves??{}),currencies:new Nn(o,n.resolveCurrencyId),mutations:new Wn(t,e,r),orders:new Hn(t,e),progressions:new Vn(t,e,o)}}var ho={type:"players",id:"me"};var ze=t=>typeof t=="string"?t:"",yt=t=>typeof t=="number"?t:0;function Qn(t,e){let n=e??{},r=ze(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:ze(n.player_id),gameId:ze(n.game_id),channel:ze(n.channel)||"release",name:ze(n.name),slotIndex:yt(n.slot_index),isActive:n.is_active!==false,createdAt:ze(n.created_at),updatedAt:ze(n.updated_at)}}var Xn=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=Yn(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 is(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>Qn(this.scope,o)):[]}async get(e,n){let r=await Ca(this.api,e,n===void 0?{}:{signal:n});return Qn(this.scope,r)}async create(e){let n=await _a(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Qn(this.scope,n)}async update(e,n,r){let o=await vs(this.api,e,{name:n},r===void 0?{}:{signal:r});return Qn(this.scope,o)}async delete(e,n){await ks(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await Qa(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:yt(r?.total_slots),availableSlots:yt(r?.available_slots),activeCharacterCount:yt(r?.active_character_count),defaultMaxSlots:yt(r?.default_max_slots),purchasedExtraSlots:yt(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var Bs="[gem: use gem.text.toPlain()]",js=new Set,Us;function em(t){try{if(js.has(t))return;let e=globalThis.location;if(Us??=!!e?.port&&pt(e.hostname??""),!Us)return;js.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${Bs}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
2
+ ${new Error().stack}`);}catch{}}var he=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return em(this.#n),Bs}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function be(t,e){return new he(t,e)}var Ye={toPlain(t){return he.unwrap(t)},compare(t,e,n){let r=t instanceof he?he.unwrap(t):t,o=e instanceof he?he.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 he?he.unwrap(t):t,r=e instanceof he?he.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var ft=t=>typeof t=="string"?t:"";function Zn(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:ft(e.transfer_id),status:ft(e.status),sourceEntityId:ft(e.source_entity_id),targetEntityId:ft(e.target_entity_id),...n===void 0?{}:{message:be(n,"transfer.message")},createdAt:ft(e.created_at),expiresAt:ft(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function tm(){return crypto.randomUUID()}var er=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 ts(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:tm()},e.signal===void 0?{}:{signal:e.signal});return Zn(n)}async list(e={}){let r=await us(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(Zn):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Xa(this.api,e,n===void 0?{}:{signal:n});return Zn(r)}async accept(e,n){return this.resolve(()=>ya(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>bs(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>ha(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Zn(await e())}};var nm=t=>typeof t=="string"?t:"",rm=t=>typeof t=="string"&&t?t:void 0,om=t=>typeof t=="number"?t:void 0;function Ws(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 im(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=om(e.version);if(r===void 0)throw new pe("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let u=nm(l.id);if(!u)throw new pe("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},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:Ws(i),currency:Ws(s)}}var pe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Hs=10*1024*1024,Vs=15e3,Ks=new Set(["dev","test","release"]);function am(t){if(!Ks.has(t))throw new pe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Ks].join(", ")}. gem-api would reject the assignment read.`);return t}var tr=t=>typeof t=="number"?t:0,bo=t=>typeof t=="string"?t:"";function sm(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:bo(o.entry_id),weight:tr(o.weight),dropRate:tr(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:bo(e.loot_table_id),name:bo(e.name),rollCount:tr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:tr(e.total_weight),entries:n}}var nr=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 Ma(this.api,e,n===void 0?{}:{signal:n});return sm(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??Vs),n;try{let l=await Ia(this.api,am(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=rm(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??Vs}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=>uo(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>Hs)throw new pe("config_too_large",`the config document is ${s.length} bytes, over the ${Hs} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new pe("config_malformed",`config document is not JSON: ${String(l)}`)}return im(a)}};var Js=400,Ce=t=>typeof t=="string"?t:"",lm=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Qe(t){let e=Ce(t);if(!lm.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var dm=/^[0-9a-f]{1,64}$/,cm=/^[0-9a-f]{16}$/,um=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,mm=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function vo(t){let e=Ce(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 pm=4096,gm=new TextEncoder;function ym(t){let e=Ce(t.challenge_data),n=Ce(t.challenge_data_hash);return e===""||!cm.test(n)?{}:gm.encode(e).length>pm?{}:{data:e,dataHash:n}}function fm(t){let e=t??{},n=Qe(e.period_start_at),r=Qe(e.period_ends_at);if(n===0||r===0)return;let o=Ce(e.slug),i=Ce(e.seed),s=vo(e.period_local_date),a=Ce(e.boundary),l=Ce(e.reset_time);return {id:Ce(e.progression_definition_id),...o===""?{}:{slug:o},window:Ce(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:um.test(a)?a:"",resetTime:mm.test(l)?l:"",seed:dm.test(i)?i:"",...ym(e)}}function ht(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function rr(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(fm).filter(n=>n!==void 0):[]}var qt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;ht(n);let r=await os(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return rr(r)}};function Me(t){return typeof t=="string"&&t!==""?t:void 0}var zs=new Set(["localhost","127.0.0.1","[::1]"]);function Xe(t){return or(t)}function or(t){let e=Me(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&zs.has(n.hostname)))return e}var hm=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,bm=/^[a-z][a-z0-9_]{0,31}$/;function vm(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let o=r??{},i=Me(o.family),s=Me(o.avatar_3d_id),a=Xe(o.model_url),l=Xe(o.icon_url);i===void 0||!bm.test(i)||n.has(i)||s===void 0||!hm.test(s)||a===void 0||l===void 0||(n.add(i),e.push({family:i,id:s,modelUrl:a,iconUrl:l}));}return e}function _m(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=Me(r.item_id),i=Xe(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function Ae(t){let e=t??{},n=Me(e.player_id),r=Me(e.display_name),o=Me(e.discriminator),i=Me(e.display_tag),s=Me(e.avatar_icon_id),a=Xe(e.avatar_icon_url),l=Me(e.avatar_3d_id),d=Xe(e.avatar_3d_model_url),m=Xe(e.avatar_3d_icon_url),u=vm(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:be(r,"displayName")},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:be(i,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...m===void 0?{}:{avatar3dIconUrl:m},...u===void 0?{}:{avatars3d:u},badges:_m(e.badges)}}var wm=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function km(t){if(t===void 0)return;let e=Xe(t);if(e===void 0)return;let n=new URL(e);return zs.has(n.hostname)||wm.has(n.origin)?e:void 0}var Ys=100,Zs=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function _o(t){let{periodsBack:e,period:n,playerId:r}=t;if(ht(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!Zs.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 el(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!Zs.test(e))return;let n=vo(t.period_local_date),r=Qe(t.period_start_at),o=Qe(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:Qe(t.opens_at),closesAt:Qe(t.closes_at),final:t.final===true}}var Nt=t=>typeof t=="string"?t:"",bt=t=>typeof t=="number"?t:0,jt=t=>typeof t=="string"?t:void 0,Sm=t=>typeof t=="number"?t:void 0,tl={player:"players",character:"characters"};function Rm(t,e){let n=t??{},r=jt(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(tl,n.entity_type)?n.entity_type:void 0,i=nl(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...Ae(n),rank:bt(n.rank),occurredAt:bt(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 Qs(t,e){let n=t??{},r=jt(n.bucket_1),o=jt(n.bucket_2),i=Sm(n.update_frequency_seconds),s=el(n);return {leaderboardType:Nt(n.leaderboard_type),runType:Nt(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(a=>Rm(a,e)):[],generatedAt:bt(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...s===void 0?{}:{period:s}}}function Xs(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=nl(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:bt(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function nl(t){if(t===null||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t))typeof r=="number"&&(e[n]=r);return e}function xm(t,e,n){let r=t??{},o=jt(r.bucket_1),i=jt(r.bucket_2),s=el(r);return {leaderboardType:Nt(r.leaderboard_type),runType:Nt(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(Xs).filter(a=>a!==void 0):[],personalBest:Xs(r.personal_best)??null,totalRuns:bt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:bt(r.generated_at),...s===void 0?{}:{period:s}}}var Ut=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=_o(n),o=await Ha(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 Qs(o,false)}async friends(e,n={}){let r=_o(n),o=await ja(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 Qs(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>Ys)throw new TypeError(`limit must be an integer between 1 and ${Ys}, got ${String(l)}`)}let i=_o(o),s=await Da(this.#e,e,tl[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"&&Nt((s??{}).entity_id)||r;return xm(s,n,a)}};var ir=t=>typeof t=="string"?t:"",wo=t=>typeof t=="number"?t:0;function rl(t){let e=t??{};return {playerId:ir(e.player_id),key:ir(e.key),value:e.value,updatedAt:wo(e.updated_at)}}function Am(t){let e=t??{};return {...Ae(e),playerId:ir(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:wo(e.updated_at)}}function Pm(t){return t?.reason==="not_found"}var Bt=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await Ua(this.api,Ie(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:ir(o.key),entries:Array.isArray(o.entries)?o.entries.map(Am):[],generatedAt:wo(o.generated_at)}}async of(e,n,r={}){try{return rl(await Ya(this.api,e,Ie(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(Pm(o))return null;throw o}}async set(e,n,r={}){if(Ie(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 rl(await fs(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Aa(this.api,r,Ie(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var Tm="gemChallenge",ol=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function il(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(Tm)??void 0}catch{return}}var Ze=class extends M{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});}},ar=t=>typeof t=="string"?t:void 0;function al(t){let e=t??{};return {...Ae(e),playerId:ar(e.player_id)??""}}function sl(t){let e=t.has_more===true?ar(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function Em(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(al):[],...sl(e)}}var ko=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Im(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 ll(t){let e=t??{},n=ko(e.opened_at),r=ko(e.answered_at);return {id:ar(e.item_id)??"",from:al(e.sender),template:ar(e.template)??"",params:Im(e.params),createdAt:ko(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function Cm(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(ll):[],...sl(e)}}function Mm(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Wt=class{#e;#n;#i;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#i=n.launchedChallengeId;}async list(e={}){let n=await cs(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Em(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await ds(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Cm(n)}async launchedChallenge(e={}){let n=this.#i;if(n===void 0||!ol.test(n))return null;try{return ll(await Wa(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(Mm(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!ol.test(e))throw new M("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await ms(this.#e,e);}};var Om=0;function we(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++Om)}-${String(Date.now())}-${t}`}}var Gm=12e4,dl=8,Lm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Dm=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Ht(t,e,n={}){return new Ze(new M("invalid",400,e,void 0,t),n)}function $m(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Fm(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!Lm.test(e))return {error:Ht("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!Dm.test(n))return {error:Ht("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(!$m(r))return {error:Ht("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:Ht("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return i.length>dl?{error:Ht("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(dl)}`)}:{playerId:e,template:n,params:o}}function qm(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 Ze(new M("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new Ze(new M("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function Nm(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function cl(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=Fm(n);if("error"in r)return Promise.reject(r.error);let o=`challenge-${we()}`;return new Promise((i,s)=>{let a={},l=m=>{e.delete(o)&&(t.clock.clearTimeout(a.timer),"error"in m?s(m.error):i(m.outcome));};e.set(o,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??Gm);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 (${Nm(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(qm(n));}}}var sr=t=>typeof t=="string"?t:void 0;function jm(t){let e=t??{},n=sr(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:sr(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var lr=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await Ln(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=jm(i);s!==void 0&&o.push(s);}return o}},So=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function Um(t){let e=t??{},n=sr(e.currency_id);if(n===void 0||n==="")return;let r=So(e.limit),o=Math.min(So(e.earned),r),i=Math.min(So(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:sr(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 ul(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 dr=class{#e;#n;#i;constructor(e,n,r){this.#e=e,this.#n=n,this.#i=r;}async get(e={}){let r=(await Va(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=Um(i);s!==void 0&&o.push(s);}return o}on(e,n){return e!=="changed"?(this.#i?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},Vt=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new lr(e),this.earnAllowance=new dr(e,n,r);}};var Ro=t=>typeof t=="string"?t:"",ml=t=>typeof t=="number"?t:0;function Bm(t){let e=t??{};return {key:Ro(e.key),visibility:Ro(e.visibility),value:e.value,updatedAt:ml(e.updated_at)}}function Wm(t){let e=t??{};return {...Ae(e),playerId:Ro(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Bm):[],generatedAt:ml(e.generated_at)}}function Hm(t){return t?.reason==="not_found"}var Kt=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return Wm(await Ka(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Hm(r))return null;throw r}}};var Vm=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]]),Jt=class extends M{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:Vm.get(this.code))??super.retryable}},Ne=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Km(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof M?zm(i):i}return Jm(o)}};function Km(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 oe(`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 oe(`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 Jm(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 zm(t){let{details:e,invocationId:n}=ga(t),o=e?.untrusted?.message,i=e?.reason;return new Jt(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 cr(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 Ym=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],xo="gem_";function pl(t){return t.startsWith(xo)}var gl=1e4,yl=50,Qm=500,Xm=65536-4*1024,Zm=24*1024;function fl(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 hl=t=>typeof t=="number"?t:0,ep=t=>typeof t=="string"?t:"";function ur(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function tp(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:hl(i.index),code:ep(i.code)}}):[];return {accepted:hl(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Ao(){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 np(t){return t?.retryable===true}var zt=class{#e;#n;#i;#f;#t=[];#h={};#a=0;#s=null;#b=false;#v=false;#m=0;#_=0;#w=0;#r=false;#k=null;#l=null;#c=false;#o=false;#p=false;#S=false;#R=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#i=Math.max(gl,e.options?.flushIntervalMs??gl),this.#f=Math.max(1,Math.floor(e.options?.maxQueue??Qm));}track(e,n={}){if(!(!this.#n||this.#r)){if(pl(e)){this.#R||(this.#R=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.#x(e,fl({...this.#h,...n}));}}setContext(e){this.#h={...this.#h,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return ur();let n=this.#C();if(n===null||n==="")return this.#t.length>0&&!this.#S&&(this.#S=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.")),ur();if(this.#P(),this.#t.length===0)return ur();let r=e.keepalive===true;if(this.#m>0&&!r)return ur();this.#u();let o=this.#t.splice(0,this.#E(r)),i=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:Ao(),sent_at_ms:s,events:o.map(d=>bl(d,s))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await es(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=tp(d,i);return this.#_=0,this.#w=0,this.#I(m),m}catch(d){throw np(d)?(this.#T(o,i),this.#_+=1,this.#w=this.#e.clock.now()+cr(this.#_,d)):this.#y(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#m-=1,this.#t.length>0&&this.#d();}}trackPlatform(e,n={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#x(e,fl(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:Ao(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=yl?this.#g():this.#t.length>0&&this.#d();}get held(){return this.#o}startSession(){if(!(this.#r||this.#l!==null)){if(this.#o){this.#p=true;return}this.#l=this.#e.clock.now(),this.#c=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#c)return;if(this.#c=true,this.#o){this.#p=false,this.#t=[],this.#a=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#g({keepalive:true});}setPaused(e){this.#r||e===this.#b||(this.#b=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#v||(this.#v=e,e?this.#u():this.#t.length>0&&this.#d());}dispose(){this.#r=true,this.#u(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#x(e,n){let{dimensions:r,measures:o}=n;for(this.#P();this.#t.length>=this.#f;)this.#t.shift(),this.#a+=1;this.#t.push({uid:Ao(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=yl?this.#g():this.#d();}#g(e={}){if(e.keepalive!==true&&this.#A()>0){this.#d();return}this.flush(e).catch(()=>{});}#A(){return Math.max(0,this.#w-this.#e.clock.now())}#T(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#f;)this.#t.shift(),this.#a+=1;}#E(e){let n=e?Zm:Xm,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(bl(s,0)).length+1,o>n)return Math.max(1,i)}return r}#d(){this.#s!==null||this.#b||this.#v||this.#o||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#g();},Math.max(this.#i,this.#A())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#P(){let e=this.#M();e===null||e===""||(this.#k!==null&&this.#k!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#k=e);}#I(e){for(let n of e.rejected)this.#y(`[gem] analytics: an event was refused (${n.code}). `+rp(n.code));}#y(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#C(){try{return this.#e.gameId()}catch{return null}}#M(){try{return this.#e.playerId()}catch{return null}}};function bl(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function rp(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 fe(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function Yt(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=fe(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var op=2e3,ip=5e3;function _l(t){let e=[],n=false,r=null,o=new Map,i=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,m=null;s=u=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(u));},m=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??op);});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 !vl(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=m=>{o.delete(d)&&(t.clock.clearTimeout(l),a(m));};o.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??ip);})},accept(s,a){let l=Yt(a),d=fe(s),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...o])vl(m,p)||u(m);}}}}function vl(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var ap=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=ap.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var wl=["explicit","stale_cleanup","game_room_closed","replaced","migration_failed","host_left","insufficient_players","all_left","expired","migration_rate_exceeded","game_room_gone","failed","idle","reclaimed"],sp=new Set(wl);function je(t){return typeof t=="string"&&sp.has(t)?t:"unknown"}var mr="webrtc_dedicated",Io=["universal","mobile","web"];var lp="p2p_unavailable",dp="capacity_unavailable",cp=2,kl=3e4,Sl=1e3,Rl=2e4;async function Co(t){let e=fe(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??ue,i=t.retry??{},s=i.budgetMs??kl,a=i.maxDelayMs??Rl,l=i.initialDelayMs??Sl,d=o.now(),m=d+s,u=0;for(;;){u++;try{let p=await Lo(t.signal,"while allocating",()=>t.client.post(`${Pl(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!up(p)||s<=0)throw p;if(p.status===503&&p.code===lp)throw new w("p2p_unavailable",`room ${t.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});if(r=p.code===dp?r+1:0,n!==void 0&&r>=cp){let x=n;n=void 0;let C=fe(await x());C!==void 0&&(e=C,r=0);}let g=Math.min(a,l*2**(u-1)),y=Math.min(a,(p.retryAfterSeconds??0)*1e3),S=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+S>m)throw mp(t,p,u,o.now()-d,s);if(i.onWaiting?.({attempt:u,elapsedMs:o.now()-d,budgetMs:s,nextAttemptInMs:S,status:p.status,message:p.message}),await pr(o,S,t.signal),t.signal?.aborted)throw Eo("while waiting to allocate")}}}function up(t){return t instanceof M?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function mp(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 pp=12e4,gp=1e3;async function Mo(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??gp,o=t.timeoutMs??pp,i=e.now()+o,s=xl(t),a={seen:t.knownToExist===true};for(;;){let l=await Al(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 pr(e,r,t.signal);}}async function Oo(t){return (await Al(t,xl(t),{seen:t.knownToExist===true})).outcome}function xl(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Pl(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Al(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await Lo(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof M&&s.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(n.seen=true,i.status==="ready")return {status:"ready",outcome:yp(r,i,o)};if(i.status==="failed"){let s=i.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:je(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function Go(t){let e=await Lo(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 Lo(t,e,n){if(t?.aborted)throw Eo(e);try{return await n()}catch(r){throw t?.aborted?Eo(e,r):r}}function Eo(t,e){return new w("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function yp(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 Pl(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function pr(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 Tl(t){return typeof t=="string"&&t.trim()!==""}function gr(t,e){return Tl(t)?t.trim():Tl(e)?e:null}var yr="0.1.0-beta",El="0-beta",vt="web",fp=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;function hp(t){let e=fp.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Il(t,e){let n=bp(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:yr};let o=hp(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 '${yr}' for it.`);if(o!==El)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${El}' 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 '${yr}' for it.`);return {...t,platform:n,engineVersion:r}}function bp(t,e){if(t===void 0||t===vt)return vt;if(!Io.includes(t))throw new w("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${Io.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${vt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${vt}' 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.`),vt}function Qt(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:Cl(e.queued_at),expiresAt:Cl(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function Cl(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var vp=3,Ml=1e3,fr=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?Ml:Math.max(Ml,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},n);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,n=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){n=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(n);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof M&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<vp){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof M&&e.code==="matchmaking_unavailable";this.settle({status:n?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let n=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:n});}catch(n){this.busy=false,this.fail(n);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var _p="gemPlayWith",wp=/^[A-Za-z0-9_-]{16,128}$/;function Ol(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(_p);}catch{return}return e!==null&&wp.test(e)?e:void 0}function Gl(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var kp="join",Sp="welcome",Rp="rejected",Ll=25e3,xp=1e3,Do=1;function $o(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Ap={credential_expired:"credential_expired",credential_reused:"credential_reused",credential_timeout:"timeout",join_rate_limited:"join_rate_limited",expected_join:"join_refused",invalid_credential:"join_refused",credential_not_for_this_channel:"join_refused"};function Fo(t){let e=typeof t=="string"?t:"unknown";return new w(Ap[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Xt(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Ll),a=n.setTimeout(()=>_(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,xp)),l=S=>{let x=S.data;if(typeof x!="string"){u(x);return}let C;try{C=JSON.parse(x);}catch{u(x);return}if(i){u(x);return}if(C.t===Sp){let h=$o(C.heartbeat_interval);y({...typeof C.player_id=="string"?{playerId:C.player_id}:{},...typeof C.match_id=="string"?{matchId:C.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(C.t===Rp){_(Fo(C.reason));return}u(x);},d=()=>{_(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{_(new w("aborted","the caller aborted during the join exchange"));},u=S=>{i&&t.onMessage?.(S);},p=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=S=>{i=true,p(),t.onMessage===void 0&&g(),r({welcome:S,detach:g});},_=S=>{i||(i=true,p(),g(),o(S));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:kp,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:Do}:{}}));}catch(S){_(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(S)}`,{cause:S}));}})}var et=1,Zt=2,qo=4,Uo=8,Pp=2,Tp=1e3,Bo="heartbeat timeout",en="gem-uu",hr=2,$l="gem_transports";function _t(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Ep(r)||e.includes(r)||e.push(r);}return e}function Ep(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function tn(t,e){if(typeof t!="object"||t===null)return null;let n=t[$l];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 br(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Fl=new TextEncoder,ql=new TextDecoder;function Wo(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function Ho(t){let e=0;return t?.reliable===false&&(e|=et),t?.ordered===false&&(e|=Zt),e}function Vo(t){return {reliable:(t&et)===0,ordered:(t&Zt)===0}}var Ko={reliable:true,ordered:true};function Nl(t){return JSON.stringify({t:"join",credential:t,wire:hr,heartbeat:Do})}function jl(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=$o(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"?Fo(e.reason):new w("join_refused","the server answered the join out of protocol")}function vr(){return typeof globalThis.WebTransport=="function"&&Jo===null}function _r(){return Jo}var Jo=null;var Dl="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Ip(t){let e=Gn(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 No=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 jo(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 nn(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:Ip(t.certHashBase64)}]});}let r=n,o=a=>{try{r.close();}catch{}throw a},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(Jo=Dl,o(new w("connection_failed",`${Dl}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new w("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return o(new w("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(jo(qo,Fl.encode(Nl(t.credential))));let u=new No,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),s]);if(y.done||y.value===void 0)return o(new w("connection_failed","the control stream closed before the join was answered"));for(let _ of u.push(y.value)){g=jl(ql.decode(_.payload));break}}return {link:Cp(r,m,p,u,t.log??(y=>console.warn(y)),Bl(g,t.clock)),welcome:g}}catch(a){return o(a)}}function Cp(t,e,n,r,o,i){let s,a,l=false,d=y=>{if(!l){l=true,m.stop();try{t.close();}catch{}a?.(y);}},m=Yo(i,()=>d(Bo)),u=(y,_)=>{m.heard(),(y&Uo)===0&&s!==void 0&&((y&qo)!==0?s(ql.decode(_),Ko):s(_,Vo(y)));};(async()=>{try{for(;;){let y=await n.read();if(y.done||y.value===void 0)break;for(let _ of r.push(y.value))u(_.flags,_.payload);}}catch{}d("stream closed");})();let p,g;try{let y=t.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let _=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let S=await _.read();if(S.done||S.value===void 0)break;let x=S.value;x.byteLength!==0&&u((x[0]??0)|et|Zt,x.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,o(`[gem] webtransport datagram lane unusable (${br(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(Ul(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,_){if(l)return;if(typeof y=="string"){e.write(jo(qo,Fl.encode(y))).catch(()=>d("write failed"));return}let S=Ho(_);if((S&et)!==0&&g!==void 0){let x=Wo(S,y),C=p?.maxDatagramSize;if(C===void 0||x.byteLength<=C){g.write(x).catch(()=>{});return}}e.write(jo(S,y)).catch(()=>d("write failed"));},onMessage(y){s=y;},onClose(y){a=y;},close(){d("closed");}}}function zo(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let o=globalThis.WebSocket;if(o===void 0)return Promise.reject(new w("connection_failed","this environment has no WebSocket"));n=new o(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((o,i)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),i(new w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),i(g));},d=()=>{r.send(Nl(t.credential));},m=g=>{if(s)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let y;try{y=jl(g.data);}catch(_){l(_);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),o({link:Mp(r,Bl(y,t.clock)),welcome:y});},u=()=>{l(new w("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new w("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",u),r.addEventListener("error",p),r.readyState===1&&d();})}function Ul(t){return typeof t=="string"&&t.length>0?t:void 0}function Bl(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function Yo(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Tp)*Pp,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 Mp(t,e){let n,r,o=false,i=a=>{if(!o){o=true,s.stop();try{t.close();}catch{}r?.(a);}},s=Yo(e,()=>i(Bo));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,Ko);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Uo)===0&&n?.(l.slice(1),Vo(d));})),t.addEventListener("close",(a=>i(Ul(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!o){if(typeof a=="string"){t.send(a);return}t.send(Wo(Ho(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){i("closed");}}}function Qo(t,e,n,r){let o,i,s=false,a=n,l=u=>{if(!s){s=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}i?.(u);}},d=Yo(r,()=>l(Bo)),m=(u,p)=>{if(d.heard(),typeof u=="string"){o?.(u,Ko);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let y=g[0]??0;(y&Uo)===0&&o?.(g.slice(1),Vo(y|p));};if(t.addEventListener("message",(u=>m(u.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(p=>m(p.data,et|Zt))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,p){if(s)return;if(typeof u=="string"){t.send(u);return}let g=Ho(p),y=Wo(g,u);if((g&et)!==0&&a!==void 0&&a.readyState==="open"){a.send(y);return}t.send(y);},onMessage(u){o=u;},onClose(u){i=u;},close(){l("closed");}}}function Wl(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=Xo(r);o!==void 0&&(e[n]=o);}return e}function Hl(t){if(Array.isArray(t))return t.map(Op).filter(e=>!!e)}function Xo(t){if(Zo(t)||Array.isArray(t)&&t.every(Zo))return t}function Zo(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function Op(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Xo(e.fixed),r=Xo(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},...wt("description",Gp(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Zo)?{allowed:e.allowed}:{},...wt("min",rn(e.min)),...wt("max",rn(e.max)),...wt("minItems",rn(e.min_items)),...wt("maxItems",rn(e.max_items)),...wt("maxLength",rn(e.max_length))}}function Gp(t){return typeof t=="string"&&t.length>0?t:void 0}function rn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function wt(t,e){return e===void 0?{}:{[t]:e}}function De(t){let e=t??{},n=Y(e.id)??Y(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(Lp):[];return {id:n,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Oe(e.max_players)??0,memberCount:Oe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...ke("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...ke("roomArgs",Wl(e.room_args)),...ke("roomArgsTemplate",Hl(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",...ke("region",Y(e.region)),...ke("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,...ke("matchId",Y(e.match_id)),version:Oe(e.version)??0,...ke("templateId",Y(e.template_id)),...ke("templateSlug",Y(e.template_slug)),roomType:Y(e.game_room_type)??"Standard",...ke("transports",_t(e.transports)??void 0),createdAt:Oe(e.created_at)??0,updatedAt:Oe(e.updated_at)??0,...ke("startedAt",Oe(e.started_at))}}function Lp(t){let e=t??{};return {...Ae(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Oe(e.joined_at)??0,...ke("groupId",Y(e.group_id)),...ke("platform",Y(e.platform))}}function ei(t){let e=t??{};return {id:Y(e.id)??Y(e.game_room_id)??"",gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Oe(e.max_players)??0,memberCount:Oe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:Oe(e.created_at)??0}}function Y(t){return typeof t=="string"&&t.length>0?t:void 0}function Oe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ke(t,e){return e===void 0?{}:{[t]:e}}var wr=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(ei),...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(ei)}))}create(e,n,r){return $p(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},...on(n)},e.signal).then(De)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(De)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...on(r)},n.signal).then(De)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...on(r)},n.signal).then(De)}quickJoin(e,n,r=[]){return ti(this.options,e,n,r).then(o=>o.room)}createTicket(e,n,r=[]){return Sa(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},...on(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Qt)}heartbeatTicket(e){return Za(this.generated(),e).then(Qt)}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(Qt):ba(this.generated(),e).then(Qt)}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 Kl(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(De)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(De)}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(De)}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 Vl(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 Vl(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function Kl(t,e){return e===void 0&&t.selfHosted?.()===true}function ti(t,e,n,r=[],o){let i=Kl(t,e.partyId);return t.client.post(`${Vl(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...Dp(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},...on(n)},e.signal).then(s=>({room:De(s),playWith:o===void 0?null:Gl(s)}))}function Dp(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function on(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function $p(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 kr=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 Sr=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 Fp(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var qp=1e3,Np=3e3,jp=6e4,Up=2,Jl=new Set(["game_room_closed","game_room_gone"]),Bp=12e4,Wp=5e3,Hp=new Set(["invalid_cluster_target","capacity_unavailable"]),Vp=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Xl(t,e){return new ni(e,t)}var ni=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 wr(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new kr;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"),zp(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||Ql(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"),Jp(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||Ql(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 fr({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 M&&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(()=>Oo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...n===void 0?{}:{signal:n}})));}catch(s){return s instanceof M&&s.reason==="not_found"?o??null:(this.reportError("reconcile",s),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=je(n.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),o=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(o),o}async kick(e,n){let r=this.requireRoom("kick"),o=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(o),o}async transferHost(e,n){let r=this.requireRoom("transferHost"),o=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(o),o}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new w("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let o=fe(n.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(m,u)=>Co({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...o===void 0?{nextClusterTarget:()=>this.nextCluster(u)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(i,[s]).catch(async m=>{if(o!==void 0||!Yl(m))throw m;let u=await this.nextCluster([s],true);if(u===void 0)throw m;return a(u,[s,u])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new w("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let 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 Mo({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,!Jl.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(!tt()){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<qp){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(Fp(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!tt()){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(()=>Oo({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,!Jl.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||!Hp.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 Sr({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&&tt())){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(),!!tt())){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 Rr)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 Rr)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??Wp}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=gr(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 Il({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Yt(await this.options.resolveClusterTargets());let e=fe(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Yl(e)||n.length===0?[]:Yt(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(Yt(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 M)||e.reason!=="conflict"||!Vp.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let o;try{o=await this.leaveAll(n.signal);}catch{throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(o.length===0)throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.postQuickJoin(n,r)}postQuickJoin(e,n){return ti(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}assertNotInRoom(e){if(this.room!==null)throw new w("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new w("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new w("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,n){let r=n instanceof M?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof w?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(n,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(a=>[a.playerId,a])),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=Kp(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??Bp;return new Promise((o,i)=>{let s=u=>{a(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>o(u))),l=this.emitter.on("matchFailed",(u,p)=>s(()=>i(new w("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>s(()=>i(new w("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>s(()=>i(new w("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Np}pushedInterval(){return this.options.pushedPollIntervalMs??jp}pushed(){return this.options.clock.now()-this.lastPushAt<Up*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 tt(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Rr=["visibilitychange","focus","pageshow","online"];function Kp(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||zl(t)!==zl(e)}function zl(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Yl(t){return t instanceof M&&t.code==="invalid_cluster_target"}var xr=8;function Jp(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=xr&&t.every(n=>typeof n=="string"&&n.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${xr} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function zp(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=xr&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${xr} 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 Ql(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Yp=["p2p","dedicated","unknown"],ri=["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 kt=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=Qp(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 Qp(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>ri.includes(o.type)).slice(0,100).map(o=>{let i=Xp(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function Xp(t){if(t!==void 0)return Yp.includes(t)?t:"unknown"}var an=class{constructor(e){this.options=e;this.reporter=new kt({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:Ar(o.credential)??"",hostFingerprint:Ar(o.host_fingerprint)??"",hostEpoch:Pr(o.host_epoch)??0,expiresAt:(Pr(o.expires_at)??0)*1e3}}async turnLease(e,n,r){let o=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),i=[];for(let l of Array.isArray(o.ice_servers)?o.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);m.length!==0&&i.push({urls:m,username:Ar(d.username)??"",credential:Ar(d.credential)??""});}let s=Pr(o.expires_at),a=Pr(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 Ar(t){return typeof t=="string"&&t.length>0?t:void 0}function Pr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var Zp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),L=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=Zp.has(n);}reason;retryable};var Zl=10240,ed=2048,eg=new TextEncoder;function td(t){return eg.encode(t).length}function Ue(t,e){let n=o=>{throw new w("invalid_sdp",`the ${e} ${o}`)},r=td(t);r>=Zl&&n(`is ${r} bytes, over the ${Zl} 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=td(o);i>ed&&n(`has a ${i}-byte line, over the ${ed} limit`);}}function Tr(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 Er=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 tg=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function St(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=Ir(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Ir(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 tg.test(r)?r:null}function sn(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 oi=5e3,ng=12e4+oi,rg=1024,og=6e4,ig=1e4,nd=64*1024,rd=5;function ii(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 L("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 L("keys_unavailable",o.reason);let a=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ig)});}catch{throw new L("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 L("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>nd)throw new L("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${nd} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof L?p:new L("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>rd)throw new L("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${rd} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=i();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await u.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!o.ok)throw new L("keys_unavailable",o.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new L("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<og?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var ln=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>=rg){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+ng),true}};function id(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 od(t){try{let e=new TextDecoder().decode(id(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function ai(t,e,n,r,o){let i=j=>{throw new L("peer_unauthenticated",`the peer's join credential is not usable: ${j}`)},s=t.split(".");s.length!==3&&i("it is not a three-part JWT");let[a,l,d]=s,m=od(a);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let u=m.kid;(typeof u!="string"||u.length===0)&&i("it names no key");let p=await n.key(u);p===null&&i("it was signed by a key this build cannot resolve");let g=o.subtle??globalThis.crypto?.subtle;g||i("this environment has no WebCrypto");let y=new TextEncoder().encode(`${a}.${l}`),_;try{_=id(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,_,y)||i("its signature does not verify");let x=od(l);x===null&&i("its payload does not decode");let C=x,h=j=>typeof C[j]=="string"?C[j]:"",k=j=>typeof C[j]=="number"&&Number.isFinite(C[j])?C[j]: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 E=k("exp")*1e3,A=k("nbf")*1e3;(!Number.isFinite(E)||e.now>E+oi)&&i("it has expired"),Number.isFinite(A)&&e.now<A-oi&&i("it is not valid yet");let W=h("role");W!=="host"&&W!=="client"&&i("it names no usable role");let $=k("host_epoch");$!==e.hostEpoch&&i("it names a different host epoch");let F=Ir(h("fingerprint"));F===null&&i("its fingerprint claim is malformed"),sn(F,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let T=Ir(h("host_fingerprint"));T===null&&i("its host fingerprint claim is malformed"),sn(T,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 G=h("sub");return G.length===0&&i("it names no player"),{playerId:G.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:$,role:W,fingerprint:F,hostFingerprint:T,jti:O,expiresAt:E}}function si(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function li(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function di(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function ci(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 ad(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 sd(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var dn=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 ui={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}},$e=["reliable","ordered","unreliable"];function mi(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 cn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var dd=1,cg=3e4,cd=2e3,ug=5e3,ud=6e4,mg=8,gi=class{constructor(e=mg){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;}},pg=new gi,gg=8,yg=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),mn=class{constructor(e){this.options=e;this.keys=e.keys??ii({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Er;links=new Map;replays=new ln;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=dd+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??cg;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),o=fe(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: ${pi(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 L("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 L("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 L("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=le(e.playerId),r=le(e.hostPlayerId),o=Cr(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new dn(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,dd),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new L("invalid_sdp","the browser produced an offer with no SDP");Ue(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:St(r);if(o===null)throw new L("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??pg,s=()=>this.closed||e!==this.credentialGeneration,a=ug;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let m=d.status,u;if(m===409)u=cd;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=a,a=Math.min(a*2,ud)),u=Math.min(Math.max(u,cd),ud);}else throw d;if(!await this.waitForCredential(u,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=le(e.fromPlayerId),r=le(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=gg){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let o=le(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;Ue(r,"offer"),this.refuseMedia(r,"offer");let i=St(r);if(i===null)throw new L("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 L("invalid_sdp","the browser produced an answer with no SDP");Ue(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=le(e.fromPlayerId),r=le(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;Ue(r,"answer"),this.refuseMedia(r,"answer");let i=St(r);if(i===null)throw new L("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:sn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new L("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=le(e.fromPlayerId),r=le(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=le(e.sdpMid),s=Cr(e.sdpMLineIndex)??Cr(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=le(e.playerId);if(n===null)return;let r=le(e.reason)??"left";if(n===this.localPlayerId){this.fail(new L("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=le(e.hostPlayerId),r=Cr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...le(e.reason)===null?{}:{reason:le(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 L("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 L("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=le(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new L("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=le(e.code)??"unknown",r=le(e.message)??"the platform refused a signaling message";this.report_(new L("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??mi)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of $e){let g=o.createDataChannel(p,ui[p]);g.binaryType="arraybuffer",i[p]=g;}let s={playerId:e,assignedPeerId:n,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),m=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",a),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",u),i.reliable.addEventListener("message",m),s.detachHandshake=()=>{i.reliable.removeEventListener("open",u),i.reliable.removeEventListener("message",m);},s.detachAll=()=>{s.detachHandshake(),o.removeEventListener("icecandidate",a),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}flushCandidates(e){let 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 L("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 L("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(si({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=ci(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 L(sd(r.reason),ad(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=St(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 ai(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 L&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",pi(s)),a&&this.fail(s);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(li({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,o){this.warn(`refused to admit ${e.playerId}: ${o}`);try{e.channels.reliable.send(di(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let o of $e)md(e.channels[o]);md(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 L?e:new L("connection_failed",pi(e),{cause:e}));}count(e){this.counted||!yg.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(Tr(e))throw new L("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 le(t){return typeof t=="string"&&t.length>0?t:null}function Cr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function pi(t){return t instanceof Error?t.message:String(t)}function md(t){try{t.close();}catch{}}var fg=100,hg=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??fg)){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 L("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new L("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??hg));}};function V(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Be(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function Rt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function pd(t){return typeof t=="boolean"?t:void 0}var ve=V(64),gn=Be(0,2147483647);function yi(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=ve(n);typeof r=="string"&&e.push(r);}return e}function z(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 _g=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=Rt("disconnected","failed","closed")(e.iceState),r=Be(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:[z("sdp","sdp",V(10240)),z("signaling_intent","intent",Rt("initial","ice_restart","full_reconnect")),K("sdp_hash","sdpHash",V(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[z("peer_id","peerId",ve),z("sdp","sdp",V(10240)),z("assigned_peer_id","assignedPeerId",Be(0,4294967295)),K("sdp_hash","sdpHash",V(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[z("peer_id","peerId",ve),z("candidate","candidate",V(512)),K("sdp_mid","sdpMid",V(64)),K("sdp_mline_index","sdpMLineIndex",Be(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[z("host_epoch","hostEpoch",gn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[z("host_epoch","hostEpoch",gn),K("evidence","evidence",_g)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[z("playerId","player_id",ve),z("hostPlayerId","host_player_id",ve),z("hostEpoch","host_epoch",gn),K("members","members",yi)],offer:[z("fromPlayerId","from_player_id",ve),z("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",Rt("initial","ice_restart","full_reconnect"))],answer:[z("fromPlayerId","from_player_id",ve),z("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",Be(0,4294967295))],ice:[z("fromPlayerId","from_player_id",ve),z("candidate","candidate",V(512)),K("sdpMid","sdp_mid",V(64)),K("sdpMLineIndex","sdp_m_line_index",Be(0,255)),K("sdpMLineIndexAlt","sdp_mline_index",Be(0,255))],peerJoined:[z("playerId","player_id",ve)],peerLeft:[z("playerId","player_id",ve),K("reason","reason",V(64))],migration:[z("hostPlayerId","new_host_player_id",ve),z("hostEpoch","host_epoch",gn),K("reason","reason",V(64)),K("kickedPlayerIds","kicked_player_ids",yi),K("migrationComplete","migration_complete",pd)],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 rt="webrtc_p2p";function yd(t){let e=new an({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 L("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=fe(r.clusterTargetId),i=o??fe(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!==rt)throw new L("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${rt}'. 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 mn({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 cn(),...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 fd(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(!tt());for(let d of Rr)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(!tt());}let s=new Map;return i.push(n.on("matchReady",a=>{let l=a.protocol===rt?"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 hd=["pointerdown","keydown"];function bd(t,e=globalThis){let n=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},s=()=>{if(!r){r=true,i();for(let g of hd)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(g){g?.isTrusted===true&&a();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(_=>_.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(o=null,!(n||r)){if(d()){a();return}m()&&(o=e.requestAnimationFrame?.(u)??null);}};function p(){o===null&&!n&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of hd)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(o=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return n},stop:s}}async function Mr(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function fi(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function hi(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 bi=false;async function kd(t,e,n,r){if(bi){e.close(),n("busy",true);return}bi=true;let o=null;try{let i=await kg(t,r);if(typeof i=="string"){e.close(),n(i,wg(i));return}o=i;let a=await(r.encodeRef??(l=>Ag(l,r)))(o);if(o.close(),o=null,a===null){e.close(),n("failed",!0);return}if(a.size>xg){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{bi=false,o?.close();}}function wg(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}}async function kg(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":vd(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Rg(n);if(!r)return "no_source";let o=Sg(r);if(o!==null)return o;try{return vd(await createImageBitmap(r),t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function Sg(t){let e;try{e=t.getContext("webgl2")??t.getContext("webgl");}catch{return "unreadable"}if(e){let n=e.getContextAttributes();return !n||n.preserveDrawingBuffer!==true?"unsupported":null}try{if(t.getContext("2d"))return null}catch{return "unreadable"}return "unreadable"}function Rg(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||o>n&&(e=r,n=o);}return e}async function vd(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 xg=8*1024*1024,_d="image/webp",wd=.92;async function Ag(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:_d,quality:wd});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),_d,wd);})}async function Sd(t,e){if(!e)return;let n;try{n=await Pg(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 Pg(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 Rd=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function xd(t=globalThis){let n=t[Rd];if(n!==void 0)return n;let r=false,o=()=>r,i=[],s=Tg(t,o);s!==null&&i.push(s);let a=Eg(t,o);a!==null&&i.push(a);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let u of i)u();}}};return Object.defineProperty(t,Rd,{value:l,configurable:true}),l}function Tg(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let o=t.OfflineAudioContext,i=n.connect,s=n.disconnect,a=new Map,l=m=>{let u=m.gain,p=m.context.currentTime;u.cancelScheduledValues(p),e()?u.setValueAtTime(0,p):u.setTargetAtTime(1,p,.01);},d=m=>{let u=m.context;if(o!==void 0&&u instanceof o)return null;let p=a.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,i.call(p,m),a.set(u,p)),p};return n.connect=function(...u){let[p,...g]=u;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return i.call(this,y,...g),p}return i.apply(this,u)},n.disconnect=function(...u){let[p,...g]=u;if(p instanceof r){let y=a.get(p.context);if(y!==void 0&&y!==this)try{return s.call(this,y,...g)}catch{}}return s.apply(this,u)},()=>{for(let[m,u]of a){if(m.state==="closed"){a.delete(m);continue}try{l(u);}catch{}}}}function Eg(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,s=o?.set;if(i===void 0||s===void 0)return null;let a=r.play,l=new WeakMap,d=new WeakSet,m=new Set,u=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),s.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),u(this);}}),r.play=function(){try{u(this);}catch{}return a.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{u(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{s.call(g,(l.get(g)??!1)||e());}catch{}}}}var Ig=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Cg=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Mg=`${Ig}${Cg}`,vi=new WeakSet;function Ad(t=globalThis.document){if(t==null||vi.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(Mg),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],vi.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"),vi.add(t),"inline")}catch{return null}}function Pd(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=t.now??(()=>globalThis.performance?.now()??Date.now()),o=false,i=false,s=false,a=null,l=null,d=null,m=[],u=false,p=0,g=null,y=[],_=()=>o&&!i&&!s,S=()=>{l=null,d=null,m=[],p=0,g=null,y=[];},x=k=>{if(a=null,!_()){S();return}if(d!==null&&m.push(k-d),d=k,l===null)l=k;else {let E=k-l;if(E>=e&&m.length>0){if(u){let A=g===null?E:r()-g;t.report(Gg(p,y,E,A));}else t.report(Og(m,E));l=k,m=[],p=0,y=[];}}C();},C=()=>{let k=n.requestAnimationFrame;typeof k=="function"&&(a=k.call(n,x));},h=()=>{if(_()){a===null&&(S(),C());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),S();};return {setRequested(k){o=k,h();},setPaused(k){i=k,h();},draw(){if(!u){u=true,a!==null&&S();return}if(a===null||l===null)return;let k=r();g!==null&&y.length<1e3&&y.push(k-g),g=k,p+=1;},get running(){return a!==null},dispose(){s=true,h();}}}function Og(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:Td(t),counts:"pageFrames"}}function Gg(t,e,n,r){let o=r;return e.length>0&&(o=Td(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:o,counts:"gameDraws"}}function Td(t){let e=[...t].sort((r,o)=>r-o),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var Or=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Ed(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Id(t,e){t!==null&&(t.style.setProperty(Or.top,`${e.top}px`),t.style.setProperty(Or.right,`${e.right}px`),t.style.setProperty(Or.bottom,`${e.bottom}px`),t.style.setProperty(Or.left,`${e.left}px`));}var Gr=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 Cd(){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 Lg(t,e){let n={tl:{width:0,height:0,control:null},tr:{width:0,height:0,control:null},bl:{width:0,height:0,control:null},br:{width:0,height:0,control:null}};for(let r of t){let o=e?r.x+r.width/2<=e.width/2:r.x===0,i=e?r.y+r.height/2<=e.height/2:r.y===0,s=o?r.x+r.width:e?e.width-r.x:r.width,a=i?r.y+r.height:e?e.height-r.y:r.height,l=n[`${i?"t":"b"}${o?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));let d=r.control;if(d){let m=l.control;l.control=m?{top:Math.min(m.top,d.y),bottom:Math.max(m.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Md(t,e,n){if(t===null)return;let r=Lg(e,n);for(let o of ["tl","tr","bl","br"]){t.style.setProperty(Gr[o].width,`${r[o].width}px`),t.style.setProperty(Gr[o].height,`${r[o].height}px`);let i=r[o].control;t.style.setProperty(Gr[o].centerY,i?`${(i.top+i.bottom)/2}px`:""),t.style.setProperty(Gr[o].controlHeight,i?`${i.bottom-i.top}px`:"");}}var Dg=3e4,Lr=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Od(t){let e=t.clock??ue,n=t.timeoutMs??Dg,r=new Map,o=new Map,i=0,s=a=>{let l=r.get(a);return l?(r.delete(a),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(a){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(a);if(l)return l;let d=new Promise((m,u)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(a),u(new Lr("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(p,{room:a,resolve:m,reject:u,timer:g}),t.bridge.requestLocalServer(p,a)||(s(p),m());});return o.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new Lr(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 yn={url:"https://downloads.indiegems.games/sdk/v13.4.1/gem-web-sdk.devtools.min.js",integrity:"sha384-V8oF6SgV9s9ytpBHnvts+v983AJJ1r1/7Bn+N29FQrkR1Q8cHsONfHA5V/pMwbcT"};var At=null;function $g(){return At!==null||(At=new Promise((t,e)=>{let n=document.createElement("script");n.src=yn.url,n.integrity=yn.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){At=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${yn.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{At=null,e(new Error(`gem devtools: could not load ${yn.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);})),At}function Gd(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 $g();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:i,text:Ye,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 Fg=1e4,Ld={reason:"unavailable",retryable:false};function Dd(t){let e=new Map,n=null,r=null,o=0,i=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??Fg);},s=(d,m)=>{let u=a(d);u&&m(u);},a=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new ut({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,u)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){u(Ld);return}let g=`t${++o}`,y={resolve:m,reject:u,reason:d,timer:null,held:p!=="connected"};e.set(g,y),i(g,y),y.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,u=>u.resolve(m));return}l.accept(m);},onDenied(d){s(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,u]of e)u.held&&(u.held=false,t.clock.clearTimeout(u.timer),i(m,u),t.bridge.requestToken(m,u.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])s(m,u=>u.reject(Ld));},get identity(){return n},get gameVersion(){return r}}}function qg(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Ng=new Set(Mn);function jg(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Ng.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function Dr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return ua(async(n,r)=>{let o;try{o=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new oe("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let i;try{i=new URL(o.href.replace(/\/+$/,"")+n.path);}catch{throw new oe(`${JSON.stringify(typeof n.path=="string"?qg(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 oe(`${JSON.stringify(i.pathname)} resolves to ${i.protocol}//${i.host}, not ${o.protocol}//${o.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(i.username!==""||i.password!==""){let g=o.username!==""||o.password!=="",y=i.username!==o.username||i.password!==o.password,_=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new oe(`the ${_} puts credentials in the URL, which cannot be fetched (${n.method} ${i.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(t.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,y);let s=n.bytes,a=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(s=JSON.stringify(n.body),a="application/json");}catch(g){throw new oe(`the body of ${n.method} ${JSON.stringify(i.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(i.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...jg(n.headers)},body:s,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),u=Ug(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},t)}function Ug(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}var Bg=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),wi="embedder_relay_unavailable",Wg="embedder_no_relay",Hg=new Set([wi]),ki=new Set([Wg]),fn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new _i(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(Vg(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 Vg(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new w(Kg(t),r,{platformCode:t})}function Kg(t){return t===void 0||Hg.has(t)?"signaling_failed":ki.has(t)?"offer_refused":Bg.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var _i=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 $d="match_ended:",Fd="server_shutdown:",qd="kicked:",Jg=123;function zg(t){if(typeof t!="string"||t.length===0||t.length>Jg)return {kind:"other"};if(t.startsWith($d)){let e=je(t.slice($d.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Fd)?{kind:"server_shutdown",cause:t.slice(Fd.length)}:t.startsWith(qd)?{kind:"kicked",detail:t.slice(qd.length)}:{kind:"other"}}function Si(t,e,n){let r=zg(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 Ri(){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 Yg=3e3,Qg=1e4,Xg=15e3;async function $r(t){let e=t.peerConnection;try{jd(t,"before the handshake started"),xi(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 ty(e,t),xi(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new w("invalid_sdp","the offer carried no SDP");Ue(o,"offer"),Nd(o,"offer");let i=await ey(t,o);if(xi(t),typeof i?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return Ue(i.sdp,"answer"),Nd(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await ny(n,t),jd(t,"before the channel opened"),n}catch(n){throw e.close(),Zg(n)}}function Zg(t){return t instanceof w?t:Wd(t)?ot():new w("connection_failed",Hd(t),{cause:t})}function Nd(t,e){if(Tr(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 ey(t,e){let n=t.exchangeTimeoutMs??Qg,r=Bd(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof w?i:Wd(i)?ot():new w("signaling_failed",Hd(i),{cause:i})});return ry(o,t,r,()=>r.exhausted?Ai("while the offer was in flight"):new w("timeout",`no answer arrived within ${n}ms`))}function ty(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??Yg);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function ny(t,e){if(e.signal?.aborted)return Promise.reject(ot());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??Xg,o=Bd(e,r);return new Promise((i,s)=>{let a=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{a(),i();},d=g=>{a(),s(new w("connection_failed","the data channel failed before it opened",Ud(g)===void 0?void 0:{cause:Ud(g)}));},m=()=>{a(),s(ot());},u=()=>{a(),s(o.exhausted?Ai("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(u,o.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Bd(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 ry(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(ot()):new Promise((s,a)=>{let l=u=>{o.clearTimeout(m),i?.removeEventListener("abort",d),u();},d=()=>l(()=>a(ot())),m=o.setTimeout(()=>l(()=>a(r())),n.ms);i?.addEventListener("abort",d),t.then(u=>l(()=>s(u)),u=>l(()=>a(u)));})}function jd(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Ai(`already ${e}`)}function Ai(t){return new w("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function xi(t){if(t.signal?.aborted)throw ot()}function ot(){return new w("aborted","the caller aborted the connection attempt")}function Wd(t){return t?.name==="AbortError"}function Ud(t){return t?.error}function Hd(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:[z("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 Zd(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??Ri,i=t.log??(h=>console.warn(h)),s=new kt({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,k)=>{let E=a.get(h)??new Set;E.add(k),a.set(h,E);},d=(h,k)=>{let E=a.get(h);E!==void 0&&(E.delete(k),E.size===0&&a.delete(h));},m=async h=>{if(r.isHost&&!Ti(r)&&r.currentRoom?.matchId===void 0){let k=fe(h.clusterTargetId);await r.startMatch({...k===void 0?{}:{clusterTargetId:k},...h.retry===void 0?{}:{retry:h.retry},...h.signal===void 0?{}:{signal:h.signal}});}return Qd(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Pi(h)):await r.awaitMatch(Pi(h)))},u=async h=>Qd(await r.pollMatchStatus(Pi(h))),p=async(h,k)=>{let E=false;try{let A=await m(h),W=r.currentRoom?.transports;if(W!==void 0&&!W.includes("webrtc"))throw new w("misconfigured",`the room template offers (${W.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let $=h.peerConnection??Xd();E=!0;let F=await $r({peerConnection:$,signaling:k,clock:n,matchId:A.matchId,credentialExpiresAt:A.credentialExpiresAt,...Fr(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),T=null;if(h.presentCredential!==!1)try{T=await Xt({channel:F,clock:n,credential:A.joinCredential,credentialExpiresAt:A.credentialExpiresAt,...Fr(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(O){throw Pe(F),Pe($),O}return my(r,A,F,$,k,h.reportDisconnect!==!1,h.reportConnected!==!1,T,{remember:l,forget:d},h.onMatchEnded)}catch(A){throw E&&Yd(s,A),Pe(k),A}},g=async(h,k,E,A,W,$)=>{if(h==="webtransport"){let B=A?.webtransport;if(B===void 0)throw new w("misconfigured","webtransport is not advertised");let H={credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n};if(typeof B.named_url=="string"&&B.named_url!==""){let ne=Math.max(Math.floor($/2),1e3);try{return await nn({url:B.named_url,timeoutMs:ne,log:i,...H})}catch(ie){if(_r()!==null)throw ie;return i(`[gem] webtransport named dial failed (${br(ie)}); retrying the pinned dial`),nn({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:ne,log:i,...H})}}return nn({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:$,...H})}if(h==="websocket"){let B=A?.websocket;if(B===void 0)throw new w("misconfigured","websocket is not advertised");return zo({url:B.url,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n,timeoutMs:$})}let F=k.peerConnection??Xd(),T,O=await $r({peerConnection:F,signaling:W,clock:n,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,extraChannels:[{label:en,ordered:false,maxRetransmits:0}],onExtraChannel:(B,H)=>{B===en&&(T=H);},...Fr(k,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...k.exchangeTimeoutMs===void 0&&k.redial===true?{exchangeTimeoutMs:ay}:{}}),G;try{G=await Xt({channel:O,clock:n,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,wire:hr,heartbeat:!0,...Fr(k,"signal"),...k.welcomeTimeoutMs===void 0?{}:{ceilingMs:k.welcomeTimeoutMs}});}catch(B){throw Pe(O),Pe(F),B}let j=G.welcome.heartbeatIntervalMs;return {link:Qo(O,F,T,j===void 0?void 0:{clock:n,intervalMs:j}),welcome:G.welcome,channel:O,peerConnection:F}},y=(h,k,E,A,W)=>{let $=false,F;A.link.onClose(j=>{!$&&h.reportDisconnect!==false&&Si(r,k.matchId,j),F?.(j);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(k.matchId);let T={transport:A.link.transport,send:(j,B)=>A.link.send(j,B),onMessage:j=>A.link.onMessage(j),onClose:j=>{F=j;},close:()=>A.link.close()},O=()=>{$||($=true,Pe(A.link),Pe(W));},G=j=>{if(!$){try{h.onMatchEnded?.(j);}catch{}O();}};return l(k.matchId,G),{matchId:k.matchId,transport:E,link:T,joinCredential:k.joinCredential,credentialExpiresAt:k.credentialExpiresAt,welcome:A.welcome,...A.channel===void 0?{}:{channel:A.channel},...A.peerConnection===void 0?{}:{peerConnection:A.peerConnection},close(){d(k.matchId,G),O();}}},_=async(h,k)=>{let E=r.currentRoom?.id,A=r.gameId,W=()=>({advert:tn(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(E===void 0||A===null)return W();try{let $=await e.get(`/v2/games/${encodeURIComponent(A)}/game-rooms/${encodeURIComponent(E)}`,k);return {advert:tn($.settings,h),template:_t($.transports)??r.currentRoom?.transports??null}}catch{return W()}},S=(h,k)=>{let E=h??Vd;return k.length===0?E:E.filter(A=>k.includes(A))},x=async(h,k,E)=>{try{let A=await m(h),{advert:W,template:$}=await _(A.matchId,h.signal),F=S($,k),T=F.filter(Q=>dy(Q,W)),O=_r();if(O!==null&&F.includes("webtransport")&&W?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${O} (learned on an earlier dial in this page)`),T.length===0){let Q=$===null?`the default order (${Vd.join(", ")})`:`the room template's transports (${$.join(", ")||"none"})`;throw new w("misconfigured",`none of ${Q}`+(k.length>0?`, narrowed to (${k.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let G=h.transportAttemptTimeoutMs??iy,j=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-n.now(),B=Q=>t.signalingReady===void 0||Q<=0?Promise.resolve(!0):t.signalingReady(Q),H=[],ne=[];for(let Q of T){if(j()<Jd){i(`[gem] ${Q} rung not tried: the reconnect budget is spent`);break}ne.length>0&&A.credentialExpiresAt-n.now()<zd&&(A=await u(h)),ne.push(Q);let We=!1,de=!1,Re={attempts:0,waitedMs:0};for(;;){if(Q==="webrtc"&&h.redial===!0){let X=Math.min(Kd,j());await B(X)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(X)}ms; offering anyway`);}let He=Math.max(Math.min(G,j()),Jd);try{return y(h,A,Q,await g(Q,h,A,W,E,He),E)}catch(X){let J=X instanceof w?X:new w("connection_failed",X instanceof Error?X.message:String(X),{cause:X});if(Q==="webrtc"&&Yd(s,J),(J.reason==="credential_expired"||J.reason==="credential_reused")&&!We){We=!0,A=await u(h);continue}if(Q==="webrtc"&&J.reason==="signaling_failed"&&J.platformCode===wi&&!de){de=!0;let ce=Math.min(Kd,j());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ce)}ms for the socket before offering again`),await B(ce))continue}if(J.reason==="join_rate_limited"){let ce=ly(Re,Math.random,j());if(ce!==null){if(Re.attempts+=1,Re.waitedMs+=ce,i(`[gem] ${Q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ce)}ms before presenting again (retry ${Re.attempts} of ${tc.maxAttempts})`),await pr(n,ce,h.signal),h.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");A.credentialExpiresAt-n.now()<zd&&(A=await u(h));continue}}if(sy.has(J.reason)||J.reason==="credential_expired"||Q==="webrtc"&&ec(J)){i(`[gem] ${Q} rung failed (${J.reason}): ${br(J.cause??J)} \u2014 `+(ne.length<T.length?`falling through to ${T[ne.length]}`:"no rungs left")),H.push(J);break}throw i(`[gem] ${Q} rung refused the session (${J.reason}): ${J.message}`),J}}}let ie=H[H.length-1];throw ie===void 0?new w("timeout",`the reconnect budget ran out before any transport (${T.join(", ")}) could be tried`):new w(ie.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${ie.message}`,{cause:H,platformCode:ie.platformCode})}catch(A){throw Pe(E),A}};return {listClusterTargets:async(h={})=>Go({client:e,...h}),handleMatchEnded(h,k){let E=a.get(h);if(E!==void 0){a.delete(h);for(let A of E)A(k);}},connect:(async(h={})=>{let k=h.signaling??o();return h.transports===void 0?p(h,k):x(h,h.transports,k)})}}var Vd=["webtransport","webrtc","websocket"],iy=1e4,ay=5e3,Kd=3e3,Jd=1e3,zd=1e4,sy=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function ec(t){return t.platformCode!==void 0&&ki.has(t.platformCode)}var tc={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function ly(t,e=Math.random,n=1/0){let r=tc;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 dy(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&vr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||cy(e.websocket.url)}function cy(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return pt(e)}function Pi(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var uy=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Yd(t,e){e instanceof w&&(!uy.has(e.reason)&&!ec(e)||t.report([{type:"connection_failures_total",value:1}]));}function my(t,e,n,r,o,i,s,a,l,d){let m=false,u=()=>{m||Si(t,e.matchId,void 0);};i&&(n.addEventListener("close",u),s&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",u),a?.detach(),Pe(n),Pe(r),Pe(o));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function Ti(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Qd(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!==mr)throw new w("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${mr}' 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 Xd(){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 Pe(t){try{t.close();}catch{}}function Fr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var py=1e4;function nc(t,e){return Ei(t,e)}function Ei(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 ut({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??py);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 Ci={};su(Ci,{acceptTransfer:()=>gy,addEntityProgression:()=>yy,adminAction:()=>fy,cancelInventoryTransfer:()=>hy,claimEntityProgressionRewards:()=>by,closeGameRoom:()=>vy,createEntityBatchOrder:()=>_y,createEntityOrder:()=>wy,createSession:()=>ky,deleteEntityGameSetting:()=>Sy,deleteEntitySave:()=>Ry,deleteSession:()=>xy,deleteShowcaseValue:()=>Ay,executeEntityRecipe:()=>Py,finalizeSaveUpload:()=>Ty,getChannelAssignment:()=>Ey,getDropRates:()=>Iy,getEntityCurrency:()=>Cy,getEntityGameSetting:()=>My,getEntityInventory:()=>Oy,getEntityInventoryItem:()=>Gy,getEntityLeaderboard:()=>Ly,getEntityOrder:()=>Dy,getEntityProgression:()=>$y,getEntityRecipeAvailability:()=>Fy,getEntityRecipeUsage:()=>qy,getEntitySave:()=>Ny,getEvent:()=>jy,getGameRoomV2:()=>Uy,getLeaderboard:()=>By,getPlayerGameProfile:()=>Wy,getPurchaseCatalog:()=>Hy,getResolvedTemplate:()=>Vy,getRoomArgs:()=>Ky,getShowcaseValue:()=>Jy,getTransferDetails:()=>zy,ingestAnalyticsEvents:()=>Ii,initiateInventoryTransfer:()=>Yy,invokeFunction:()=>Qy,kickPlayer:()=>Xy,listChallenges:()=>Zy,listEntityGameSettings:()=>ef,listEntityOrders:()=>tf,listEntityProgressions:()=>nf,listEntitySaves:()=>rf,listEvents:()=>of,listGameRooms:()=>af,listResolvedTemplates:()=>sf,listTransfers:()=>lf,maxEntityProgression:()=>df,putEntityGameSetting:()=>cf,putRoomArgs:()=>uf,putShowcaseValue:()=>mf,rejectTransfer:()=>pf,reportMatchPlayers:()=>gf,requestSaveUploadUrl:()=>yf,resetEntityProgression:()=>ff,setMatchBackfill:()=>hf,simulateEntityOrder:()=>bf,transferHostV2:()=>vf,updateGameRoomV2:()=>_f});function b(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function gy(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function yy(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/add`;return t.client.post(s,o,i?.signal)}async function fy(t,e,n,r){let o=`/v1/voice/sessions/${b(e)}/admin`;return t.client.post(o,n,r?.signal)}async function hy(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function by(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/claim`;return t.client.post(s,o,i?.signal)}async function vy(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.delete(r,n?.signal)}async function _y(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function wy(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ky(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Sy(t,e,n,r,o){let i=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(i,o?.signal)}async function Ry(t,e,n,r,o){let i=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(i,o?.signal)}async function xy(t,e,n){let r=`/v1/voice/sessions/${b(e)}`;return t.client.delete(r,n?.signal)}async function Ay(t,e,n,r){let o=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.delete(o,r?.signal)}async function Py(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ty(t,e,n,r,o,i){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/finalize`;return t.client.post(s,o,i?.signal)}async function Ey(t,e,n){let r=`/v1/games/${b(t.gameId())}/config/channels/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Iy(t,e,n){let r=`/v1/inventory/loot-tables/${b(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Cy(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/currencies/${b(r)}`;return t.client.get(i,o?.signal)}async function My(t,e,n,r,o){let i=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Oy(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),s=`/v1/inventory/${b(e)}/${b(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Gy(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/items/${b(r)}`;return t.client.get(i,o?.signal)}async function Ly(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let s=i.toString(),a=`/v1/leaderboards/${b(e)}/${b(n)}/${b(r)}`+(s?`?${s}`:"");return t.client.get(a,o?.signal)}async function Dy(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders/${b(r)}`;return t.client.get(i,o?.signal)}async function $y(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}`;return t.client.get(i,o?.signal)}async function Fy(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/catalogs/${b(r)}/recipes/${b(o)}/availability`;return t.client.get(s,i?.signal)}async function qy(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),s=`/v1/inventory/${b(e)}/${b(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Ny(t,e,n,r,o){let i=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function jy(t,e,n){let r=`/v1/events/${b(e)}`;return t.client.get(r,n?.signal)}async function Uy(t,e,n){let r=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function By(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${b(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Wy(t,e,n){let r=`/v1/profiles/players/${b(e)}`;return t.client.get(r,n?.signal)}async function Hy(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 Vy(t,e,n){let r=`/v1/game-room-templates/${b(e)}`;return t.client.get(r,n?.signal)}async function Ky(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.get(r,n?.signal)}async function Jy(t,e,n,r){let o=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.get(o,r?.signal)}async function zy(t,e,n){let r=`/v1/inventory/transfers/${b(e)}`;return t.client.get(r,n?.signal)}async function Ii(t,e,n){let r=`/v1/games/${b(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function Yy(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Qy(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Xy(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/kick/${b(n)}`;return t.client.post(o,void 0,r?.signal)}async function Zy(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 ef(t,e,n,r){let o=`/v1/settings/${b(e)}/${b(n)}`;return t.client.get(o,r?.signal)}async function tf(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),s=`/v1/inventory/${b(e)}/${b(n)}/orders`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function nf(t,e,n,r){let o=`/v1/inventory/${b(e)}/${b(n)}/progressions`;return t.client.get(o,r?.signal)}async function rf(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),s=`/v1/saves/${b(e)}/${b(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function of(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 af(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o=`/v1/games/${b(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function sf(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function lf(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 df(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/max`;return t.client.post(s,o,i?.signal)}async function cf(t,e,n,r,o,i){let s=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.put(s,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function uf(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.put(o,n,r?.signal)}async function mf(t,e,n,r,o){let i=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.put(i,r,o?.signal)}async function pf(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function gf(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/matches/${b(e)}/players/report`;return t.client.post(o,n,r?.signal)}async function yf(t,e,n,r,o,i){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/upload-url`;return t.client.post(s,o,i?.signal,{replaySafe:true})}async function ff(t,e,n,r,o,i){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/reset`;return t.client.post(s,o,i?.signal)}async function hf(t,e,n,r){let o=`/v1/games/${b(t.gameId())}/matches/${b(e)}/backfill`;return t.client.put(o,n,r?.signal)}async function bf(t,e,n,r,o){let i=`/v1/inventory/${b(e)}/${b(n)}/orders/simulate`;return t.client.post(i,r,o?.signal)}async function vf(t,e,n,r){let o=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}/transfer/${b(n)}`;return t.client.post(o,void 0,r?.signal)}async function _f(t,e,n,r){let o=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.patch(o,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var wf=1e4,kf=50,Sf=1e3,Rf=65536-4*1024,rc=t=>typeof t=="number"?t:0,xf=t=>typeof t=="string"?t:"";function oc(){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 Af(t){return t?.retryable===true}function Pf(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:rc(i.index),code:xf(i.code)}}):[];return {accepted:rc(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function ic(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 ac(t){let e=Math.max(1,Math.floor(t.maxQueue??Sf)),n={client:t.client,gameId:()=>t.gameId},r=[],o=0,i=null,s=false,a=null,l=0,d=0,m=false,u=false,p=h=>{t.log?.(h);},g=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},y=()=>Math.max(0,d-t.clock.now()),_=()=>{i!==null||s||a!==null||(i=t.clock.setTimeout(()=>{i=null,x().catch(()=>{});},Math.max(wf,y())));},S=()=>{let h=Math.min(r.length,100),k=128;for(let E=0;E<h;E+=1){let A=r[E];if(A===void 0)break;if(k+=JSON.stringify(ic(A,0)).length+1,k>Rf)return Math.max(1,E)}return h};async function x(h){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let k=C(h);a=k;try{return await k}finally{a===k&&(a=null),r.length>0&&_();}}async function C(h){g();let k=r.splice(0,S()),E=o;o=0;let A=Math.round(t.clock.now()),W={batch_id:oc(),sent_at_ms:A,events:k.map($=>ic($,A))};try{let $=await Ii(n,W,h===void 0?void 0:{signal:h}),F=Pf($,E);l=0,d=0;for(let T of F.rejected)p(`[gem] analytics: an event was refused (${T.code}). See the analytics_events section of your game config.`);return F}catch($){if(Af($)){for(r=[...k,...r],o+=E;r.length>e;)r.shift(),o+=1;l+=1,d=t.clock.now()+cr(l,$);}else p(`[gem] analytics: ${k.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String($)}`);throw $}}return {track(h,k,E={}){if(s)return;if(typeof h!="string"||h===""){u||(u=true,p(`[gem] analytics: '${k}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(k.startsWith(xo)){m||(m=true,p(`[gem] analytics: '${k}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let A={},W={};for(let[$,F]of Object.entries(E))typeof F=="string"?A[$]=F:typeof F=="number"&&Number.isFinite(F)&&(W[$]=F);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:oc(),playerId:h,name:k,atMs:t.clock.now(),dimensions:A,measures:W}),r.length>=kf&&a===null&&y()===0?x().catch(()=>{}):_();},flush:h=>x(h),get pending(){return r.length},dispose(){s=true,g(),r=[],o=0;}}}function sc(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().");ht(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return rr(i)}}}function Tf(t){let e={};for(let[n,r]of Object.entries(Ci))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function Pt(t,e={}){let n=e.clock??ue,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let o=Ei(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=Dr({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new Fe({transport:i,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=Tf({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,m=t.endMatch,u=t.log,p=ac({client:s,clock:n,gameId:a.gameId,...typeof u=="function"?{log:y=>u.call(t,y)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);},setBackfill:async(y,_)=>{let S=await l.setMatchBackfill(a.matchId,{open:y.open,...y.seats===void 0?{}:{seats:y.seats}},_===void 0?{}:{signal:_});return {open:S.open,seats:S.seats??null}},reportPlayers:async(y,_)=>(await l.reportMatchPlayers(a.matchId,{players:y.map(x=>({player_id:x.playerId,state:x.state}))},_===void 0?{}:{signal:_})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new Ne(l.invokeFunction),challenges:sc(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let _=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),S=_.modified?_.body:void 0;if(S?.room_args==null||S.room_args_template==null)throw new M("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:S.room_args,room_args_template:S.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function it(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Tt(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function hn(t){return typeof t=="string"?t:t.slice().buffer}function qr(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 Ef=5e3,lc=3e4,dc=2e3,If=1e4,Cf=3,cc=1;async function uc(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let o=e.log===void 0?f=>console.info(f):e.log,i=f=>o?.(`[gem host] ${f}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,m=(f,I)=>{l&&(a=a.then(async()=>{if(!d)try{await I();}catch(D){i(`the bundle's ${f} handler threw: ${at(D)}. Serving continues.`);}}));},u=true,p,g,y,_=f=>{if(!u)return;u=false,m("leave",()=>s.leave?.(r,{cause:f??"left"}));let I=g;I&&queueMicrotask(()=>I(f));},S={send(f,I){if(!u)return;let D=Tt(it(I));m("message",()=>s.message?.(r,f,typeof f=="string",{reliable:D.reliable,ordered:D.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){_("closed");}},x=(f,I)=>{if(!u)return;let D=Tt(it(I));queueMicrotask(()=>{u&&p?.(f,D);});},C=new Map,h=f=>{let I=[];for(let D of $e){let Z=f.channels[D];try{Z.binaryType="arraybuffer";}catch{}let ge=Tt(D),An=Ct=>{let Je=qr(Ct?.data);Je!==null&&m("message",()=>s.message?.(f.playerId,Je.data,Je.isText,{reliable:ge.reliable,ordered:ge.ordered}));};Z.addEventListener("message",An),I.push(()=>Z.removeEventListener("message",An));}C.get(f.playerId)?.forEach(D=>D()),C.set(f.playerId,I);},k=f=>{C.get(f)?.forEach(I=>I()),C.delete(f);},E=new Set,A=new Map,W=(f,I,D)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...I?{rejoin:true}:{},...D?{superseded:true}:{}}),$=f=>{let I=C.has(f.playerId),D=E.has(f.playerId);E.add(f.playerId),h(f),I&&m("leave",()=>s.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>s.join?.(f.playerId,W(f,D,I)));},F=new Set,T=(f,I,D)=>{if(f===r){x(I,D);return}let Z=n.peer(f);if(Z===null){let ge=A.get(f);if(ge!==void 0&&e.clock.now()-ge<dc)return;F.has(f)||(F.add(f),i(`send to '${f}' dropped: no such connected player`));return}Z.send(hn(I),it(D));},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:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=u?[r]:[];for(let I of n.peers)f.push(I.playerId);return f},profile(f){let I=e.room()?.members.find(D=>D.playerId===f);if(!(!I||I.displayName===void 0))return {displayName:Ye.toPlain(I.displayName),...I.displayTag===void 0?{}:{displayTag:Ye.toPlain(I.displayTag)},...I.discriminator===void 0?{}:{discriminator:I.discriminator}}},playerNumber(f){return f===r?cc:n.peer(f)?.assignedPeerId},send(f,I,D){T(f,I,D);},broadcast(f,I){let D=I?.except;u&&r!==D&&x(f,I);for(let Z of n.peers)Z.playerId!==D&&Z.send(hn(f),it(I));},async endMatch(){let f=await He();return f.answer!=="ok"&&i(f.cause),f.answer},kick(f,I){if(f===r){_(I??"kicked");return}n.kick(f).catch(D=>{i(`kick of '${f}' failed: ${at(D)}`);});},log(f){i(f);},warn(f){i(`\u26A0 ${f}`);}},G=()=>{},j=new Promise(f=>{G=f;}),B=[],H=null,ne=async(f,I)=>{l=false;let D=a.then(async()=>{try{await s.shutdown(f);}catch(Z){i(`the bundle's shutdown threw: ${at(Z)}`);}});a=D,await D,_e();for(let Z of B.splice(0))Z();for(let Z of [...C.keys()])k(Z);_(I);},ie=(f,I)=>H||(H=(async()=>{await ne(I,f),n.close(),G();})(),H),Q=()=>H||(H=(async()=>{await ne({reason:"signal"},"left"),await n.leave().catch(f=>i(`leaving the match failed: ${at(f)}`)),G();})(),H),We=()=>H||(H=(async()=>{l=false;let f=await He();f.answer==="ok"?(await ne({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${f.cause}; leaving instead`),await ne({reason:"signal"},"left"),await n.leave().catch(I=>i(`leaving the match failed: ${at(I)}`))),G();})(),H),de=null,Re=()=>(de??=Pt(O,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),de),He=async()=>{try{return await ps({client:Re().client,gameId:()=>O.gameId},O.matchId,{},{signal:AbortSignal.timeout(Ef)}),{answer:"ok"}}catch(f){return f instanceof M&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${at(f)}`}}},X=null,J=false,ce=0,xe,Te=null,_e=()=>{J=true,X!==null&&(e.clock.clearTimeout(X),X=null),Te?.(),Te=null;},Sn=f=>{i(`heartbeats paused: ${f}; they resume when a fresh play token arrives`),Ve();let I=xe,D=false,Z=e.tokens.subscribe(ge=>{D||J||ge.token===I||Rn(ge)||(D=true,Te?.(),Te=null,ce=0,xe=void 0,Ve(),i("a fresh play token arrived; heartbeats resume"),X=e.clock.setTimeout(()=>{Ke();},0));});D?Z():Te=Z;},Ve=()=>{let f=de;de=null,f?.dispose();},Rn=f=>f.expiresAt*1e3<=e.clock.now(),Ke=async()=>{if(X=null,!J){try{await Re().client.post(`/v1/games/${encodeURIComponent(O.gameId)}/matches/${encodeURIComponent(O.matchId)}/heartbeat`,void 0,AbortSignal.timeout(If)),ce=0,xe=void 0;}catch(f){if(f instanceof M&&(f.reason==="forbidden"||f.reason==="not_found")){i(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),_e();return}if(Mf(f)){if(J)return;ce+=1;let I=e.tokens.current(),D=I===void 0?"this host holds no play token":Rn(I)?"this host's play token has expired":I.token===xe?"the platform refused this host's play token again":ce>=Cf?`the platform refused this host's play token ${ce} times in a row`:null;if(xe=I?.token,D!==null){Sn(D);return}}else ce=0,xe=void 0;i(`heartbeat failed: ${at(f)}`);}J||(X=e.clock.setTimeout(()=>{Ke();},lc));}},It=()=>{J||X!==null||(X=e.clock.setTimeout(()=>{Ke();},lc));};{let f=G;G=()=>{_e(),de?.dispose(),de=null,f();};}let xn=Promise.resolve().then(()=>s.init(O));a=xn.then(()=>{},()=>{}),m("join",()=>s.join?.(r,{playerNumber:cc,transport:"loopback"})),B.push(n.on("peerJoined",$)),B.push(n.on("peerLeft",(f,I)=>{k(f);let D=e.clock.now();for(let[Z,ge]of A)D-ge>=dc&&A.delete(Z);A.set(f,D),F.delete(f),m("leave",()=>s.leave?.(f,{cause:I}));})),B.push(n.on("error",f=>{i(`\u26A0 session error: ${f.message}`);})),B.push(n.on("matchEnded",f=>{H||Mi(y,f),ie("match ended",{reason:"match_ended",platform_reason:f});})),B.push(n.on("hostChanged",f=>{f!==r&&ie("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)$(f);try{await xn,It();}catch(f){l=false,_e(),d=true;for(let I of B.splice(0))I();for(let I of [...C.keys()])k(I);throw n.leave().catch(()=>{}),G(),f}return {matchId:n.matchId,localLink:S,onMatchEnded(f){y=f;},end:We,leave:Q,stop:f=>ie(f,{reason:"stopped"}),done:j}}function Mi(t,e){try{t?.(e);}catch{}}function Mf(t){return t instanceof M&&t.status===401||ee.isAuthError(t)}function at(t){return t instanceof Error?t.message:String(t)}function Oi(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 mc(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async a=>{r.isHost&&!Ti(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!==rt)return Oi("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return Oi("peer",d.matchId);let u=t.identity();if(u===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(s(l)),g=await uc(a,{session:p,clock:t.clock,gameId:u.gameId,channel:u.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:u.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return o.set(d.matchId,g),g.done.then(()=>{o.get(d.matchId)===g&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(a={}){let l=await i(a),d=a.onMatchEnded;if(l.protocol===rt){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Df(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let y=await cn(),_=async()=>t.p2p.connect({...s(a),certificate:y}),S=await _(),x=Ff(S,_,d,C=>{r.notifyMatchDisconnected(C).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(S.matchId,{redial:x.redial,abandon:x.abandon}),x.onClosed(()=>{e.get(S.matchId)?.abandon===x.abandon&&e.delete(S.matchId);})),x}let m=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),u=await m(),p=$f(u,m,r,n);return n&&(e.set(u.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(u.matchId)?.abandon===p.abandon&&e.delete(u.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var pc="link_closed",Of="host_unreachable",Gf=new Set(["failed","closed"]);function Lf(t){return Gf.has(t)?pc:Of}function Df(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 $f(t,e,n,r){let o=t.matchId,i=t,s="connected",a,l,d=[],m=false,u=false,p=y=>{if(s!=="closed"){s="closed";for(let _ of d.splice(0))_();l?.(y);}},g=y=>{y.link.onMessage((_,S)=>a?.(_,S)),y.link.onClose(_=>{if(y!==i||s==="closed")return;if(m||!r){p(_);return}let S=n.matchSession;if(S.phase==="suspended"&&S.matchId===o){s="suspended";return}p(_);});};return g(t),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return s},send(y,_){s==="connected"&&i.link.send(y,_);},onMessage(y){a=y;},onClose(y){l=y;},close(){if(s!=="closed"){if(m=true,s==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(s==="closed"||m)return "closed";if(u)return "connected";u=true;let _;try{_=await e(y===void 0?{}:{deadlineAt:y});}finally{u=false;}return m||s==="closed"?(_.close(),"closed"):(i=_,g(_),s="connected",n.notifyMatchConnected(o),"connected")},abandon(y){s!=="closed"&&(s==="connected"&&i.close(),p(y));},onClosed(y){s==="closed"?y():d.push(y);}}}function Ff(t,e,n,r,o,i=false){let s=t.matchId,a=t,l,d,m=[],u=[],p=[],g=false,y=false,_=false,S=false,x="connected",C=T=>{if(g)return;g=true,x="closed";for(let G of m.splice(0))G();for(let G of u.splice(0))G();for(let G of p.splice(0))G();let O=d;O&&queueMicrotask(()=>O(T));},h=T=>{for(let O of m.splice(0))O();for(let O of $e){let G=T.channels[O];try{G.binaryType="arraybuffer";}catch{}let j=Tt(O),B=H=>{let ne=qr(H?.data);ne!==null&&l?.(ne.data,j);};G.addEventListener("message",B),m.push(()=>G.removeEventListener("message",B));}},k=()=>a.peer(a.hostPlayerId),E=T=>{if(!(g||a.isHost)&&x!=="suspended"){if(r?.(T),i){x="suspended";return}C(T);}},A=T=>{for(let O of $e){let G=T.channels[O];if(typeof G.addEventListener!="function")continue;let j=()=>{k()===T&&E(pc);};G.addEventListener("close",j),m.push(()=>G.removeEventListener?.("close",j));}},W=T=>{h(T),A(T),!g&&(x="connected",o?.());},$=T=>{for(let O of u.splice(0))O();u.push(T.on("migrating",()=>{S=true;})),u.push(T.on("hostChanged",O=>{if(S=false,O===T.playerId){C("host_migrated_here");return}let G=k();G!==null&&W(G);})),u.push(T.on("peerJoined",O=>{O.playerId===T.hostPlayerId&&W(O);})),u.push(T.on("matchEnded",O=>{g||Mi(n,O),C(O);})),u.push(T.on("peerLeft",(O,G)=>{O===T.hostPlayerId&&E(Lf(G));}));};$(a);let F=k();return F!==null&&W(F),{matchId:s,protocol:"p2p",get state(){return x},send(T,O){x==="connected"&&k()?.send(hn(T),it(O));},onMessage(T){l=T;},onClose(T){d=T;},close(){y=true,C("closed"),a.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||_)return "connected";if(S)throw new L("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");_=true;let T;try{for(let G of m.splice(0))G();for(let G of u.splice(0))G();a.close(),T=await e();}finally{_=false;}if(g)return y?T.leave().catch(()=>{}):T.close(),"closed";a=T,$(a);let O=k();if(O===null)throw a.close(),new L("connection_failed","this peer rejoined the match but the host never answered with a link");return W(O),"connected"},abandon(T){C(T);},onClosed(T){g?T():p.push(T);}}}function gc(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 qf=12e4;function st(t,e){return {outcome:t,reason:e}}function yc(t){let e=false,n=new Map,r=(o,i,s,a)=>{if(!t.bridge.parentSupports(o))return Promise.resolve(st("unavailable","error"));if(e)return Promise.resolve(st("declined","busy"));let l=`purchase-${we()}`;return new Promise(d=>{let m={},u=g=>{n.delete(l)&&(e=false,t.clock.clearTimeout(m.timer),d(g));};e=true,n.set(l,{finish:u,check:s,label:a}),m.timer=t.clock.setTimeout(()=>u(st("unavailable","error")),t.timeoutMs??qf);let p=false;try{p=i(l);}catch{}p||u(st("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(st(i,Os(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(st("unavailable","error"));return}(async()=>{let m;try{m=await d;}catch{m="unknown";}if(m==="granted"){a(l===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:l});return}m==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(st("unavailable","error"));})();}}}async function fc(t,e){try{return (await za(t,e)).granted?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}var Nf="small_human",hc=/^[a-z][a-z0-9_]{0,31}$/,bc=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,jf=8;function Gi(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:Nf,id:e,modelUrl:n,iconUrl:r}]}function Uf(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 Bf(t){let e=t??{},n=typeof e.item_id=="string"&&bc.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&hc.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=or(e.icon_url),l=or(e.model_url),d=[];for(let m of Array.isArray(e.prices)?e.prices:[]){let u=m??{};typeof u.currency_slug=="string"&&u.currency_slug!==""&&typeof u.price=="number"&&Number.isSafeInteger(u.price)&&u.price>0&&d.push({currencySlug:u.currency_slug,price:u.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 Wf(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&hc.test(n)&&!e.includes(n)&&e.push(n),e.length===jf)break;return e}function vc(t){let e=new Set,n=Gi(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=Gi(o);if(!Uf(n,i)){n=i;for(let s of [...e])try{s(i);}catch(a){r(a);}}}),{async families(){return Wf(await t.configFamilies())},worn(o){let i=Gi(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=Bf(s);a!==void 0&&i.push(a);}return i},purchase(o){let i=o?.itemId,s=o?.currencySlug;return typeof i!="string"||!bc.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 _c(t,e){try{return (await Ea(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}function wc(t){return Ba(t)}var Hf=6e5;function kc(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-${we()}`;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??Hf);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 Vf=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),Kf=["utm_"];function Sc(t){return Vf.has(t)||Kf.some(e=>t.startsWith(e))}var Rc=16,xc=512,Jf=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,zf=/[\p{Cc}\p{Cf}]/u,Yf=/\p{Cs}/u,Ge="[gem] gem.share.request:";function Ac(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(`${Ge} the arcade does not handle share here \u2014 check gem.share.available first`);if(s!==void 0&&(typeof s!="object"||s===null))throw new TypeError(`${Ge} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!Qf(l))throw new TypeError(`${Ge} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>Rc)throw new TypeError(`${Ge} at most ${Rc} params; got ${d.length}`);let m=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!Jf.test(u))throw new TypeError(`${Ge} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Sc(u))throw new TypeError(`${Ge} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Ge} param ${g}: values must be strings`);if(p.length>xc)throw new TypeError(`${Ge} param ${g}: a value is at most ${xc} characters`);if(zf.test(p))throw new TypeError(`${Ge} param ${g}: control and format characters are not allowed`);if(Yf.test(p))throw new TypeError(`${Ge} param ${g}: a value must be well-formed text`);m.push({key:u,value:p});}!a.requestShare(m)&&!r&&(r=true,i("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function Qf(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var th="(any-pointer: coarse)";function nh(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 Pc(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},o=r.navigator,i,s=new Set,a=()=>typeof o?.vibrate!="function"||r.matchMedia===void 0?false:(i??=r.matchMedia(th),i.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,u)=>{s.has(m)||(s.add(m),n!==null&&(n===void 0?console.warn(u):n(u)));};return {get available(){return a()||l()},vibrate(m){let u=a();if(!u&&!l())return false;let p=nh(m);if(p===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(o?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(u)try{return o.vibrate(p)===!0}catch{return false}let g=e.requestVibrate(p);return g||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),g}}}var Et=Math.PI/180,Le=Object.freeze({touch:Object.freeze({yaw:1*Et,pitch:.66*Et}),mouse:Object.freeze({yaw:.5*Et,pitch:.5*.77*Et}),stick:Object.freeze({yaw:240*Et,pitch:240*.77*Et}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Li="[gem.controls]",Di=Object.freeze({yaw:0,pitch:0}),Nr=t=>Number.isFinite(t)?t:0,Tc=(t,e)=>({yaw:t+0,pitch:e+0});function Ec(t){let e=Nr(t),n=(Math.abs(e)-Le.stickDeadzone)/(1-Le.stickDeadzone),r=Le.stickCurve,o=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,o))+0}function rh(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Le.touchPitchMin)+Le.touchPitchMin}function Ic(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${Li} ${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(`${Li} ${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(`${Li} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function oh(t,e){let n=Ic(e,"look()"),r=n.sensitivity,o=n.gamepadSensitivity,i=n.invertY,s=a=>i??a?.invertLookY??false;return {fromPointer(a,l,d,m){let u=Nr(a),p=Nr(l);if(u===0&&p===0)return Di;let g=t(),y=r??(g===null?void 0:g.lookSensitivity/100)??1,_=d==="touch"||d==="pen",S=_?Le.touch:Le.mouse,x=u*S.yaw*y,C=-p*S.pitch*y;return s(g)&&(C=-C),_&&m!==void 0&&Number.isFinite(m)&&C*m>0&&(C*=rh(m)),Tc(x,C)},fromStick(a,l,d){let m=Nr(d);if(m<=0)return Di;let u=Ec(a),p=Ec(l);if(u===0&&p===0)return Di;let g=t(),y=o??(g===null?void 0:g.gamepadLookSensitivity/100)??1,_=u*Le.stick.yaw*m*y,S=-p*Le.stick.pitch*m*y;return s(g)&&(S=-S),Tc(_,S)},set(a){let l=Ic(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(o=l.gamepadSensitivity),"invertY"in l&&(i=l.invertY);}}}function Cc(t){return {look:e=>oh(t.recommended,e),LOOK_BASE:Le}}function Mc(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var ih=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Oc(t){if(typeof t!="string"||!ih.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function bn(){return {declared:false,grantable:false,heldLimitReached:false}}function Gc(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Oc(n.resets_at),o=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...bn(),...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=Oc(a),d=n.held_limit_reached===true,m=a!=null,u=i!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!u&&!m&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...o}}var ah=18e4,$i=32,sh=/^[a-z0-9_-]+$/,lh="rewarded_requires_user_gesture";function dh(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var ch=1e3;function uh(){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<=ch)return true}return false}var Lc=1e4;function mh(t){return t==="interstitial"||t==="rewarded"}function Dc(t){return typeof t=="string"&&t!==""&&t.length<=$i&&sh.test(t)}function ph(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function jr(t){return typeof t=="string"?JSON.stringify(t):typeof t}function $c(t){let e=false,n=new Map,r=new Map,o=new Set,i=d=>{try{t.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let m=t.log;if(m!==null)try{m===void 0?console.warn(`[gem] ${d}`):m(`[gem] ${d}`);}catch{}},l=d=>{let m=t.readAvailability;if(m===void 0)return Promise.resolve(bn());let u=r.get(d);if(u!==void 0)return u;let p=new Promise(g=>{let y={},_=h=>y.done===true?false:(y.done=true,t.clock.clearTimeout(y.timer),g(h),true),S=(h,k)=>{!_(bn())||o.has(h)||(o.add(h),i(`gem.ads.rewardedStatus("${d}") answered not grantable: ${k}. Said once.`));},x=h=>{S(ph(h),`the read failed (${h instanceof Error?h.message:jr(h)})`);},C;try{C=Promise.resolve(m(d,AbortSignal.timeout(Lc)));}catch(h){C=Promise.reject(h);}y.timer=t.clock.setTimeout(()=>{S("timeout","no answer within 10 s");},Lc),C.then(h=>{try{_(Gc(h,t.bridge.parentSupports("ads")));}catch(k){x(k);}},x);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return Dc(d)?l(d):(i(`gem.ads.rewardedStatus(${jr(d)}) answered not grantable: a placement is 1..${String($i)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(bn()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let m=d?.placement,u=d?.format;if(!Dc(m)||!mh(u))return i(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${jr(m)}, format ${jr(u)}. A placement is 1..${String($i)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});if(u==="rewarded"){let g;try{g=(t.userActivation??dh)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??uh)()===!0&&(g=!0);}catch{}if(g===false){let y=`${lh}: gem.ads.requestAd("${m}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return i(y),a(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${we()}`;return new Promise(g=>{let y={},_=x=>{n.delete(p)&&(e=false,t.clock.clearTimeout(y.timer),g(x));};e=true,n.set(p,_),y.timer=t.clock.setTimeout(()=>{_({outcome:"unavailable"});},t.timeoutMs??ah);let S=false;try{S=t.bridge.requestAd(p,m,u);}catch{}S||_({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",u=n.get(d.requestId);if(u===void 0){t.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}u({outcome:m});}}}var Fc=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),qc=18e4,gh=1e4,yh=/^[a-z0-9_-]{1,32}$/;function Nc(t){return typeof t=="string"?JSON.stringify(t):typeof t}var vn=Object.freeze({shown:false});function jc(t){let e=new Map,n,r=false,o=i=>{try{t.onDropped?.(i);}catch{}return vn};return {api:{signal(i){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(vn):(r=!0,Promise.resolve(o("moments_unsupported: gem.moments.signal answered shown: false without asking: this arcade does not do platform moments. Keep the call; it costs nothing. Said once.")));let s=i?.kind,a=i?.placement;if(!Fc.includes(s)||a!==void 0&&(typeof a!="string"||!yh.test(a)))return Promise.resolve(o(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${Nc(s)}, placement ${Nc(a)}. A kind is one of ${Fc.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'. Answering shown: false.`));if(!t.bridge.readyCalled())return Promise.resolve(o(`moments_before_ready: gem.moments.signal({ kind: '${s}' }) before gem.frame.ready(): a moment is a break in play, and play has not started. Signal from the press that leaves a break, never on boot. Answering shown: false.`));if(e.size>0)return Promise.resolve(o(`moments_in_flight: gem.moments.signal({ kind: '${s}' }) while another moment is still waiting for its answer. Signal once per break, and await the answer before play resumes. Answering shown: false.`));let l=t.clock.now();if(n!==void 0&&l-n<gh)return Promise.resolve(o(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(l-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let d=`moment-${we()}`;return new Promise(m=>{let u={},p=(y,_)=>{e.delete(d)&&(t.clock.clearTimeout(u.timer),_&&(n=t.clock.now()),m(y));};e.set(d,y=>p(y,!0)),u.timer=t.clock.setTimeout(()=>{e.has(d)&&(p(vn,!0),o(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??qc)/1e3)} s. Answering shown: false.`));},t.timeoutMs??qc);let g=!1;try{g=t.bridge.signalMoment(d,s,a);}catch{}g||p(vn,!1);})}catch{return Promise.resolve(vn)}}},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 Fi=16384;function Uc(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:fh(e)}function fh(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 hh=1e4,bh=5e3;function Bc(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=bh){return n?Promise.resolve(e):new Promise(a=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{t.clock.clearTimeout(m),l(),a(e);},m=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=Uc(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-${we()}`;return new Promise(m=>{let u={},p=y=>{o.delete(d)&&(t.clock.clearTimeout(u.timer),y==="stored"&&(e=l,n=true,i()),m(y));};o.set(d,p),u.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??hh);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,n=true,i();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=o.get(s.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var _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 vh=/^[a-z0-9][a-z0-9_-]{0,39}$/;function _h(t){return typeof t=="string"&&vh.test(t)}function Ur(t){if(t===null||_h(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 Wc(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function qi(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 Br(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 Hc(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function wh(t){let e=t.untrusted,n=be(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,o=r?be(r,"gem.player.displayTag"):void 0,i=t.discriminator||t.displayTag,s=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,a=t.avatarIconUrl||t.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=t.avatarIconId,m=t.avatar3dId,u={displayName:n,displayHandle:o??n,badges:(t.badges??[]).map(_=>({itemId:_.itemId,iconUrl:_.iconUrl}))};t.playerId&&(u.playerId=t.playerId),s&&(u.discriminator=s),o&&(u.displayTag=o),a&&(u.avatarIconUrl=u.avatarUrl=a),d&&l.test(d)&&(u.avatarIconId=d),m&&l.test(m)&&(u.avatar3dId=m),t.avatar3dModelUrl&&(u.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(u.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(u.avatars3d=t.avatars3d.filter(_=>l.test(_.id)&&/^[a-z][a-z0-9_]*$/.test(_.family)).filter((_,S,x)=>x.findIndex(C=>C.family==_.family)==S).map(({family:_,id:S,modelUrl:x,iconUrl:C})=>({family:_,id:S,modelUrl:x,iconUrl:C})));let p=t.boost,g=(p?.multipliers??[]).map(_=>({currencyId:_.currencyId,currencySlug:_.currencySlug,multiplier:_.multiplierBp/1e4})),y=g.some(_=>_.multiplier>1);return u.boost=y&&p?.expiresInDays?{active:y,multipliers:g,expiresInDays:p.expiresInDays}:{active:y,multipliers:g},u}var kh=1e4,wn=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??ue,this.inbound=new Dt(this.clock),this.outbound=new Dt(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=>ao(a,e.origin))||Es(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=qn["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!ao(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=Is($n,o.versions);return s===null?(i.onmessage=null,i.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${$n.min}..v${$n.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=s,i.onmessage=a=>this.receive(a.data,a.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:U,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:U,type:"gem.ready"});}settled(e=kh){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:U,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:U,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:U,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:U,type:"gem.exit"}:{gem:U,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:U,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:U,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:U,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:U,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:U,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:Wc(e.origin.x),y:Wc(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=Ur(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:U,type:"gem.portraitBorders"}:{gem:U,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:U,type:"gem.walletDisplay",...qi(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:U,type:"gem.menu",...Br(e)}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:U,type:"gem.gemCorner",corner:e}):false}requestShare(e){return this.gated("share")?this.send({gem:U,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:U,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:U,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:U,type:"gem.frameStats",fps:Hc(e.fps,1e3),frameTimeP95Ms:Hc(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:U,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:U,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:U,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:U,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,o,i,s){return this.send({gem:U,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:U,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:U,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:U,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r){return this.send({gem:U,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:U,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,o){return this.send({gem:U,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...o===void 0?{}:{params:o}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(Fn)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(Fn)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(Fn)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:U,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=qn[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||Vc(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=qn[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=xs(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let s=o(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=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 Vc(n.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(wh(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:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:U,type:"gem.screenshot.denied",reason:e,retryable:n});}};function Vc(t){for(let e of t)try{e?.close?.();}catch{}}var Kc="https://api.gemarcade.com";function Ni(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 Sh=new Set(["localhost","127.0.0.1","[::1]"]);function Jc(t){let e=Ni(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!Sh.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}function zc(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function Rh(){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 xh=Object.freeze({small_human:zc([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:zc(Rh())});var Ph=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),Th=Kc,Eh=["top-left","top-right","bottom-left","bottom-right"],Yc=8e3,ji=15e3,Ih=9e4,Ch=1/0,Mh=8e3,Oh=5e3,Gh=5e3;async function Lh(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 kn(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 tA(t={}){let e=t.clock??ue,n=t.log===void 0?c=>console.info(c):t.log,r=t.baseUrl??void 0;if(r!=null){let c=Ni(r);if(c!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${c}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=typeof window>"u"?void 0:window.location?.search,i=il(o),s=Ol(o),a=hi();a.mark("sdk created");let l=()=>gr(re.gameVersion,t.clientVersion?.gameVersion),d=new zt({client:()=>dt,clock:e,gameId:()=>re.identity?.gameId??null,playerId:()=>re.identity?.playerId??null,environment:()=>{let c=l();return {sdk_version:da(),...c===null?{}:{game_version:c}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),m=bd(()=>{a.mark("engaged"),d.release(),q.reportEngaged();},typeof window>"u"?{}:window),u=c=>{if(c===false)return null;let R=c?.attempts??Ch,N=c?.budgetMs??Ih;return !(R>0)||!(N>0)?null:{attempts:R,budgetMs:N,maxDelayMs:c?.maxDelayMs??Mh}},p=c=>{c.on("created",()=>{a.mark("room created");}),c.on("joined",()=>{a.mark("room joined");}),c.on("matchAllocationStarted",()=>{a.mark("allocation started");}),c.on("matchReady",()=>{a.mark("match ready");}),c.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 g=t.allowedEmbedders;if(g!=null&&!Array.isArray(g))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let y=Array.from(g??[]),_=y.filter(c=>typeof c!="string"||!io(c));if(_.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${_.length===1?"an entry":"entries"} that ${_.length===1?"is":"are"} not an origin: ${_.map(c=>typeof c=="string"?JSON.stringify(c):String(c)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let S=Object.freeze([...new Set([...Ph,...y])]),x=kn(e),C=new Set,h=kn(e),k=false,E=kn(e),A=ul(n),W=kn(e),$=t.manageAudio===false?null:xd();t.selectableText!==true&&Ad();let F=null,T=null,O=()=>{F===null||F===T||q.reportMuted(F)&&(T=F);},G,j,B=-1/0,H=null,ne=()=>{if(G===void 0||H!==null||G===j)return;let c=B+1e3-e.now();if(c>0){H=e.setTimeout(()=>{H=null,ne();},c);return}q.showPortraitBorders(G)&&(j=G,B=e.now());},ie=null,Q=null,We=()=>{if(ie===null)return false;let c=JSON.stringify(qi(ie.visible,ie.only));return c===Q?q.parentSupports("walletDisplay"):q.setWalletVisible(ie.visible,ie)?(Q=c,true):false},de=null,Re=null,He=()=>{if(de===null)return false;let c=JSON.stringify(Br(de.items));return c===Re?q.parentSupports("gameMenu"):q.setMenu(de.items)?(Re=c,true):false},X=null,J=null,ce=()=>X===null?false:X===J?q.parentSupports("gemCorner"):q.setGemCorner(X)?(J=X,true):false,xe=Pd({report:c=>q.reportFrameStats(c)}),Te=false,_e=Gd(()=>na,()=>Te),Sn=c=>{let R=Te&&!c,N=Te!==c;if(Te=c,R&&_e.close(),!!N)try{t.onDevToolsPermissionChange?.(c);}catch(ae){n?.(`[gem] onDevToolsPermissionChange threw: ${ae instanceof Error?ae.message:String(ae)}`),queueMicrotask(()=>{throw ae});}},Ve=r??Th,Rn=r!==void 0,Ke,It=c=>(n?.(`[gem] token refused: ${c}`),t.onError?.("internal",c),false),xn=(c,R)=>{if(c===void 0)return R!==void 0?It("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let N=Jc(c);return N!==null?It(`the embedder named an API root that cannot be used: ${N}. Its value is withheld here rather than written to logs.`):Ke!==void 0&&Ke!==c?It("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."):(Ke=c,Rn||(Ve=c),true)},f=window.location?.origin,I=null,D=-1/0,Z=2e3,ge=new Set,An=c=>I!==false?Promise.resolve(true):new Promise(R=>{let N=e.setTimeout(()=>{ge.delete(ae),R(false);},c),ae=()=>{e.clearTimeout(N),ge.delete(ae),R(true);};ge.add(ae);}),Ct=()=>{},Je=null,q=new wn({allowedEmbedders:S,...typeof f=="string"&&f!==""?{selfOrigin:f}:{},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","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:c=>{Je=c,t.onRefused?.(c);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:c=>{re.onBridgeState(c),c!=="connected"&&xe.setRequested(false),T=null,Q=null,Re=null,J=null,j=void 0,c==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Je===null?"":` (${Je})`)+", 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."),Ct()),c==="connected"&&(a.mark("bridge connected"),eu(),O(),ne(),We(),He(),ce(),q.unbiddenLaunch&&!m.engaged&&d.hold(),d.startSession(),m.engaged&&q.reportEngaged()),t.onStateChange?.(c);},onPlayer:c=>{x.set(c);for(let R of [...C])R(c);t.onPlayer?.(c);},onPrefs:c=>{let R={reducedMotion:c.reducedMotion,muted:c.muted,locale:c.locale,showFrameStats:c.showFrameStats===true,recommended:c.recommended===void 0?null:Object.freeze({volume:c.recommended.volume,batterySaver:c.recommended.batterySaver,keyboardLayout:c.recommended.keyboardLayout,gamepadConfirm:c.recommended.gamepadConfirm,vibration:c.recommended.vibration,lookSensitivity:c.recommended.lookSensitivity??100,gamepadLookSensitivity:c.recommended.gamepadLookSensitivity??100,invertLookY:c.recommended.invertLookY??false,touchMovement:c.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:Mc(c.recommended.graphicsQuality,c.recommended.batterySaver),graphicsQualityAuto:c.recommended.graphicsQualityAuto??true})};h.set(R),T=R.muted,$?.setMuted(R.muted),xe.setRequested(R.showFrameStats&&q.parentSupports("frameStats")),t.onPrefs?.(R);},onCohorts:c=>{let R=Object.freeze(c.cohorts.map(N=>Object.freeze({experimentId:N.experimentId,variantKey:N.variantKey})));E.set(R),t.onCohorts?.(R);},onEarnAllowanceChanged:()=>A.emit(),onViewport:c=>{let R=Object.freeze({insets:Object.freeze({top:c.insets.top,right:c.insets.right,bottom:c.insets.bottom,left:c.insets.left}),reserved:Object.freeze((c.reserved??[]).map(({x:ae,y:ra,width:oa,height:ia,control:Ot})=>Object.freeze(Ot?{x:ae,y:ra,width:oa,height:ia,control:Object.freeze({x:Ot.x,y:Ot.y,width:Ot.width,height:Ot.height})}:{x:ae,y:ra,width:oa,height:ia})))});W.set(R);let N=Ed();Id(N,R.insets),Md(N,R.reserved,Cd()),t.onViewport?.(R);},onPause:c=>{k=c.paused,d.setPaused(c.paused),xe.setPaused(c.paused),t.onPause?.(c.paused);},onMenuSelect:c=>{de===null||c.entry!=="item"||!(Br(de.items).items??[]).some(N=>N.id===c.id)||de.items?.find(N=>N.id===c.id)?.onSelect?.();},onWillTerminate:c=>{d.endSession(c.reason),t.onWillTerminate?.({reason:c.reason,graceMs:c.graceMs});},onToken:c=>{let R=c.garden;if(Sn(c.allowDevTools===true),!xn(c.apiBaseUrl,R))return;let N=c;re.onToken(N);let ae=re.identity;ae&&(Wr.set(ae),Wi||(Wi=true,me.reconcileSeats().catch(()=>{}))),Hi.push({token:N.token,expiresAt:N.expiresAt});},onTokenDenied:c=>{Sn(false),re.onDenied(c);},onScreenshot:(c,R,N)=>{kd(c,R,N,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Sd(q,t.onFeedbackContext);},onDevtools:c=>{c==="close"?_e.close():c==="open"?_e.openFrom("platform").catch(()=>{}):_e.isOpen?_e.close():_e.openFrom("platform").catch(()=>{});},onRoomEvent:c=>me.handleRoomEvent({event:c.event,roomId:c.roomId,...c.matchId===void 0?{}:{matchId:c.matchId},...c.version===void 0?{}:{version:c.version},...c.reason===void 0?{}:{reason:c.reason},...c.platform===void 0?{}:{platform:c.platform}}),onSeatedEvent:c=>me.handleSeated(c.roomId),onAutoStartFailedEvent:c=>me.handleAutoStartFailed(c.roomId,c.code),onTicketEvent:c=>me.handleTicketEvent({event:c.event,ticketId:c.ticketId,...c.partySize===void 0?{}:{partySize:c.partySize},...c.queuedAt===void 0?{}:{queuedAt:c.queuedAt},...c.expiresAt===void 0?{}:{expiresAt:c.expiresAt},...c.reason===void 0?{}:{reason:c.reason},...c.roomId===void 0?{}:{roomId:c.roomId}}),onSocketState:c=>{let R=I;if(I=c.connected,c.connected)for(let ae of [...ge])ae();if(!c.connected||R===true)return;let N=e.now();N-D<Z||(D=N,me.reconcile().catch(()=>{}));},onSignalEvent:c=>{let R=typeof c.data=="object"&&c.data!==null&&!Array.isArray(c.data)?c.data:{};ct.handleSignalEvent(c.matchId,c.event,R),c.event==="matchEnded"&&me.reconcile({matchId:c.matchId,...typeof R.reason=="string"?{reason:R.reason}:{}}).catch(()=>{});},onDedicatedEvent:c=>{c.event==="matchEnded"&&(Mt.handleMatchEnded(c.matchId,c.reason),me.reconcile({matchId:c.matchId,...c.reason===void 0?{}:{reason:c.reason}}).catch(()=>{})),Bi.handleEvent(c);},onClusterTarget:c=>In.accept(c.clusterTargetId,c.clusterTargetIds),onLocalServer:c=>Cn.accept(c),onLocalServerDenied:c=>Cn.refuse(c),onPartyResult:c=>Ki.settle(c.requestId,c.partyId),onPurchaseResult:c=>Vr.settle(c),onDeviceSettings:c=>{En.receive(c),t.onDeviceSettings?.(En.api.current);},onDeviceSettingsResult:c=>En.settle(c),onAdResult:c=>zi.settle(c),onMomentResult:c=>Yi.settle(c),onSignInResult:c=>Qi.settle(c),onFriendChallengeResult:c=>Xi.settle(c)}),Bi=new fn({bridge:q}),Wr=kn(e);Ct=()=>{Wr.release(),x.release(),E.release();},q.currentState==="refused"&&Ct();let Wi=false,Hr=new Set,Pn,Hi={current:()=>Pn,subscribe:c=>(Hr.add(c),Pn!==void 0&&c(Pn),()=>Hr.delete(c)),push:c=>{Pn=c;for(let R of [...Hr])try{R(c);}catch(N){n?.(`[gem] a server-token listener threw: ${N instanceof Error?N.message:String(N)}`);}}},re=Dd({bridge:q,clock:e,onStateChange:(c,R)=>{if(c==="ready"){if(a.mark("token ready")){let N=a.marks.find(ae=>ae.name==="token ready")?.at;d.trackPlatform("gem_boot_ready",N===void 0?{}:{boot_ms:Math.max(0,Math.round(N))});}}else c==="lost"&&(a.mark("token lost"),d.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(c,R);}}),Vi=()=>{let c=re.identity;return !c||re.source.currentState==="lost"?null:`${c.playerId}\0${c.gameId}\0${c.channel}`},eu=()=>{a.mark("token requested"),re.source.get().catch(()=>{});},Ki=gc({bridge:q,clock:e}),Tn={},Vr=yc({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c),confirm:async c=>Tn.confirm?.(c)??"unknown",confirmAvatar3d:async c=>Tn.confirmAvatar3d?.(c)??"unknown"}),En=Bc({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c)}),Ji={},zi=$c({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c),readAvailability:(c,R)=>Ji.read?.(c,R)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),Yi=jc({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c)}),Qi=kc({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c)}),Xi=cl({bridge:q,clock:e,onDropped:c=>t.onError?.("internal",c)}),In=_l({bridge:q,clock:e}),Cn=Od({bridge:q,clock:e}),Kr=c=>{let R=q.handleWindowMessage({data:c.data,origin:c.origin,source:c.source,ports:c.ports});return R&&window.removeEventListener("message",Kr),R};window.addEventListener("message",Kr);let lt=la(window,Kr),tu=lt?.capture,Jr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Jr?.domInteractive!==void 0&&Jr.domInteractive>0&&a.mark("document parsed",Jr.domInteractive),tu?.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 zr=t.handshakeWarningMs;zr!==null&&n&&e.setTimeout(()=>{let c=lt===null?"no capture script ran":`capture: ${lt.delivered} offer(s) delivered, ${lt.stale} stale, ${lt.capture.dropped} evicted${lt.capture.late?", installed late":""}`;if(q.currentState==="connected"){n(`[gem] handshake connected. boot: ${a.timeline()} \xB7 ${c}`);return}n(`[gem] no completed handshake after ${zr??Yc}ms (bridge state: ${q.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 `+c);},zr??Yc);let nu=Dr({get baseUrl(){return Ve},tokenSource:re.source,get defaultQuery(){let c=re.identity;return c?{game_id:c.gameId,channel:c.channel}:{}}}),dt=new Fe({transport:nu,clock:e}),ye={client:dt,gameId:()=>re.identity?.gameId??""};Tn.confirm=c=>fc(ye,c),Tn.confirmAvatar3d=c=>_c(ye,c),Ji.read=(c,R)=>hs(ye,"players","me",c,{signal:R});let ru=()=>re.identity?.channel??"release",Yr=new nr(ye,ru),ou=vc({player:()=>x.current,subscribe:c=>(C.add(c),()=>{C.delete(c);}),configFamilies:async()=>(await Yr.load())?.avatar_3d_families,readOffers:()=>wc(ye),purchase:c=>Vr.requestAvatar3d(c),log:t.log}),Zi=async c=>(await Yr.load())?.currency(c)?.id??void 0,ea=Yn(ye,ho,{identity:Vi,resolveCurrencyId:Zi}),Qr=async c=>{let R=await Wr.wait(c);if(R)return R;throw q.currentState==="refused"?new ee("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 ee("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).")},Xr=u(t.autoReconnect),me=Xl(s===void 0?{}:{playWithTicket:s},{client:dt,clock:e,gameId:()=>re.identity?.gameId??null,playerId:()=>re.identity?.playerId??null,awaitGameId:async()=>(await Qr(ji)).gameId,resolveParty:Ki.resolve,resolveClusterTargets:In.resolveList,refreshClusterTargets:In.refresh,ensureLocalServer:Cn.ensure,localHostAvailable:Cn.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>re.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},...Xr===null?{}:{autoReconnect:{...Xr,redial:(c,R)=>Zr.redialMatch(c,R),abandon:(c,R)=>Zr.abandonMatch(c,R)}}});p(me),fd({analytics:d,rooms:me});let ct=yd({client:dt,clock:e,rooms:me,bridge:q,gameId:()=>re.identity?.gameId??"",baseUrl:()=>Ve,resolveClusterTarget:In.resolve,boot:a,...t.log===void 0?{}:{log:t.log}}),ta=fi(a,n),Mt=Zd({client:dt,clock:e,rooms:me,signaling:()=>Bi.channel(),signalingReady:An,log:n??(()=>{})}),Zr=mc({rooms:me,p2p:{connect:c=>ta(ct.connect(c)),session:c=>ct.session(c)},dedicated:{connect:(c=>Mr(a,"welcome",Mt.connect(c),n))},clock:e,identity:()=>re.identity,apiBaseUrl:()=>Ve,tokens:Hi,room:()=>me.currentRoom,autoReconnect:Xr!==null,...t.log===void 0?{}:{log:t.log}}),iu=async()=>(await Qr(ji)).playerId,na={client:dt,boot:a,get identity(){return re.identity},awaitIdentity:(c=ji)=>Qr(c),awaitBridge:c=>q.settled(c),get player(){return x.current},awaitPlayer:(c=Oh)=>x.wait(c),me:ea,characters:new Xn(ye,void 0,Vi,Zi),transfers:new er(ye,ho,ea.inventory),gameConfig:Yr,purchases:Vr.api,deviceSettings:En.api,moments:Yi.api,ads:zi.api,account:Qi.api,share:Ac({frame:q,log:t.log}),vibration:Pc({frame:q,log:t.log}),get avatarPickerAvailable(){return q.currentState==="connected"&&q.parentSupports("avatarPicker")},openAvatarPicker:c=>q.requestAvatarPicker(c?.tab),avatars3d:ou,controls:Cc({recommended:()=>h.current?.recommended??null}),analytics:d,leaderboards:new Ut(ye),challenges:new qt(ye),showcase:new Bt(ye,iu),friends:new Wt(ye,{challenge:Xi.challenge,...i===void 0?{}:{launchedChallengeId:i}}),platform:new Vt(ye,A,n),profiles:new Kt(ye),functions:new Ne((c,R)=>rs(ye,c,R)),get prefs(){return h.current},get paused(){return k},get cohorts(){return E.current},get viewport(){return W.current},awaitCohorts:(c=Gh)=>E.wait(c),reportMuted:c=>{F=!!c,O();},showPortraitBorders:c=>{let R=Ur(c);R!==void 0&&(G=R,ne());},cueReward:c=>q.cueReward(c),setWalletVisible:(c,R)=>{let N=Array.isArray(R?.only)?[...R.only]:void 0;return ie=N===void 0?{visible:c===true}:{visible:c===true,only:N},We()},setMenu:c=>(de=Array.isArray(c?.items)?{items:c.items.map(R=>({...R}))}:{},He()),setGemCorner:c=>{if(!Eh.includes(c)){let R=typeof c=="string"?JSON.stringify(c.slice(0,48)):`a value of type ${typeof c}`;return console.warn(`[gem] setGemCorner: ${R} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return X=c,ce()},reportFrame:()=>xe.draw(),exit:c=>Lh(me,q,c,d),frame:q,devtools:_e,rooms:me,dedicatedServer:{listClusterTargets:c=>Mt.listClusterTargets(c),connect:(c=>Mr(a,"welcome",Mt.connect(c),n)),handleMatchEnded:(c,R)=>Mt.handleMatchEnded(c,R)},p2p:{handleSignalEvent:(c,R,N)=>ct.handleSignalEvent(c,R,N),session:c=>ct.session(c),connect:c=>ta(ct.connect(c))},match:Zr};return na}var Qc="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 Ui(t,e={}){let n=e.clock??ue,r=()=>{let a=t();if(a===null)throw new Error(Qc);return a},o=null,i=()=>{if(o===null)throw new Error(Qc);return o};return {server:{get identity(){return i().identity},get client(){return i().client},get api(){return i().api},get match(){return i().match},get analytics(){return i().analytics},get functions(){return i().functions},get challenges(){return i().challenges},get room(){return i().room},dispose(){o?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(a){let d=r().profile?.(a);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:be(m,"profile.displayName"),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:be(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=Pt(r(),{...e,clock:n});}}}function Xc(t,e={}){let{server:n,attach:r}=Ui(()=>t,e);return r(),n}function Dh(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:je(e)}}}var $h=1e4;function Fh(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout($h));}catch{return}r.catch(o=>{o instanceof M&&o.status>=400&&o.status<500&&(e=o.status!==429);});}}function Zc(t,e={}){return ()=>{let n=null,{server:r,attach:o}=Ui(()=>n,e),i=t(r),s={async init(l){n=l,o(),await i.init?.();},async shutdown(l){let d=Dh(l);try{await i.shutdown?.(d);}finally{r.dispose();}}},a=Fh(r);return s.join=(l,d)=>(a(l),i.join?.(l,d)),i.leave&&(s.leave=(l,d)=>i.leave?.(l,d)),i.message&&(s.message=(l,d,m,u)=>i.message?.(l,d,m,u)),s}}sa();
3
3
  exports.ARCADE_EMBEDDERS=Ph;exports.AVATAR_RIGS=xh;exports.AnalyticsApi=zt;exports.AuthError=ee;exports.CONDITIONAL_HEADERS=Mn;exports.ChallengesApi=qt;exports.DEVICE_SETTINGS_MAX_BYTES=Fi;exports.DedicatedServerError=w;exports.FriendChallengeError=Ze;exports.FriendsApi=Wt;exports.FunctionsApi=Ne;exports.GemApiError=M;exports.GemClient=Fe;exports.GemConfigError=pe;exports.GemFrame=wn;exports.GemFunctionError=Jt;exports.GemSaveError=se;exports.GemUnframedError=_n;exports.LeaderboardsApi=Ut;exports.MAX_PERIODS_BACK=Js;exports.PLATFORM_EVENTS=Ym;exports.PlatformApi=Vt;exports.PlatformCurrenciesApi=lr;exports.PlatformEarnAllowanceApi=dr;exports.PlayerText=he;exports.ProfilesApi=Kt;exports.PurchaseRefusal=qe;exports.ShowcaseApi=Bt;exports.TransportRefusal=oe;exports.UNRELIABLE_CHANNEL_LABEL=en;exports.asPlayerText=be;exports.createBootTimeline=hi;exports.createGem=tA;exports.createGemServer=Pt;exports.createHostTokenSource=nc;exports.createMatchServer=Xc;exports.defineServer=Zc;exports.leaveAndExit=Lh;exports.mapIdentity=Ae;exports.markOnResolve=Mr;exports.platformIconUrl=km;exports.presentJoinCredential=Xt;exports.readTemplateTransports=_t;exports.readTransportAdvert=tn;exports.reportOnResolve=fi;exports.systemClock=ue;exports.text=Ye;exports.toBase64=On;exports.webTransportAvailable=vr;return exports;})({});