@indiegems/gem-web-sdk 9.1.1 → 9.1.3
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.
- package/CHANGELOG.md +12 -0
- package/dist/gem-web-sdk.esm.js +1 -1
- package/dist/gem-web-sdk.function.js +1 -1
- package/dist/gem-web-sdk.game.js +1 -1
- package/dist/gem-web-sdk.min.js +1 -1
- package/dist/gem-web-sdk.sdk.js +1 -1
- package/dist/gem-web-sdk.server.js +1 -1
- package/docs/api/api-reference-game.md +20 -10
- package/docs/api/api-reference-server.md +1 -1
- package/docs/api/reference.json +5 -5
- package/docs/arcade-economy.md +13 -8
- package/docs/changelog.md +12 -0
- package/docs/getting-started.md +1 -1
- package/docs/inventory-and-catalogs.md +3 -1
- package/docs/manifest.json +16 -16
- package/docs/platform-rules.md +3 -3
- package/docs/server-bundles.md +2 -2
- package/docs/serverless-functions-js.md +26 -0
- package/docs/what-a-game-must-do.md +24 -14
- package/package.json +1 -1
- package/schema/bridge.v1.json +25 -6
package/dist/gem-web-sdk.game.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Kd=Object.defineProperty;var Jd=(t,e)=>{for(var n in e)Kd(t,n,{get:e[n],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:9.1.1]";function Io(){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)}function zd(t,e){return e!==void 0?!e:t==="chain_exhausted"}var on=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new se(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new se("chain_exhausted","the token chain reached its ceiling");return this.refresh(this.nextReason())}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}refresh(e){if(this.inFlight)return this.inFlight;let n=this.generation;this.enter("pending");let r=this.options.request(e).then(i=>{if(n!==this.generation)throw new se("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=Yd(i),a=i?.retryable;throw n===this.generation&&this.enter(zd(o,typeof a=="boolean"?a:void 0)?"lost":"degraded",o),i instanceof se?i:new se(o,String(i))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){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)}},se=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 Yd(t){if(t instanceof se)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var ie=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}},Pr=["if-match","if-none-match"],Mo=4096;function Xd(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let i=n.toLowerCase();if(!Pr.includes(i)||r===void 0)continue;let o=typeof r=="string"?Qd(r):r;if(typeof o!="string"||o.length>Mo||!Zd(o))throw new ie(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${Mo} characters, or contains a character outside the range an HTTP header value may carry. This is a malformed request, not a server failure; the value is withheld here rather than written to logs.`);o!==""&&(e[i]=o);}return Object.freeze(e)}function Qd(t){let e=i=>i===32||i===9||i===10||i===13,n=0,r=t.length;for(;n<r&&e(t.charCodeAt(n));)n++;for(;r>n&&e(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function Zd(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 ec(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new ie("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new ie("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function Oo(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=Xd(i.headers),a=ec(i),s=Object.freeze({...i,headers:o,...a===void 0?{}:{bytes:a}}),l=await e.tokenSource.get(),d=await t(s,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),c=await t(s,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new se("unavailable","the server refused a freshly minted token");return c}}}function Er(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(nc(e))}function yt(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 Tr(t){return new TextDecoder().decode(yt(t))}function nc(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var G=class extends Error{constructor(n,r,i,o,a){super(`${n} (${r}): ${i}`);this.reason=n;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Go=new WeakMap;function Do(t){return Go.get(t)??{}}var tc=new Set([408,429,500,502,503,504]),rc=6e4;function ic(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new ie(`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),i=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...i}:{modified:true,body:r.body,...i}}async put(e,n,r,i={}){return this.send({method:"PUT",path:e,body:n,signal:r,...xn(i)},i.replaySafe===true)}async post(e,n,r,i={}){return this.send({method:"POST",path:e,body:n,signal:r,...xn(i)},i.replaySafe===true)}async postBytes(e,n,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...xn(i)},i.replaySafe===true);return {bytes:oc(o.body),...o.invocationId===void 0?{}:{invocationId:o.invocationId}}}async patch(e,n,r,i={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...xn(i)},i.replaySafe===true)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...xn(r)},r.replaySafe===true)}async send(e,n){return (await this.sendRaw(e,n)).body}async sendRaw(e,n){let r=n?ic(this.options.maxRetries)+1:1,i=null;if(e.signal?.aborted)throw Lo(e.signal);for(let o=0;o<r;o++){if(o>0&&await this.backoff(o,i,e.signal),e.signal?.aborted)throw Lo(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(se.isAuthError(l)||ie.isRefusal(l)||e.signal?.aborted||ac(l))throw l;i=new G("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=sc(a);if(!tc.has(a.status))throw s;i=s;}throw i??new G("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let i=n?.retryAfterSeconds,o=i!==void 0?i*1e3:2**(e-1)*250,a=2**(e-1)*250,s=Math.min(Math.max(o,a),rc);return new Promise(l=>{let d=this.options.clock,m=false,c=false,p,g=()=>{m||(m=true,c&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,s),c=true,m&&d.clearTimeout(p);})}};function oc(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 xn(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function Lo(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function ac(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function sc(t){let e=dc(t),n=uc(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Go.set(e,r),e}var lc=new Map([["insufficient_funds","insufficient_funds"]]);function dc(t){let{status:e,body:n}=t,r=cc(n),i=t.retryAfterSeconds??pc(n),o=mc(n),a=o===void 0?void 0:lc.get(o);if(a!==void 0)return new G(a,e,r,void 0,o);switch(e){case 304:return new G("not_modified",e,r);case 400:case 422:return new G("invalid",e,r,void 0,o);case 403:return new G("forbidden",e,r,void 0,o);case 404:return new G("not_found",e,r,void 0,o);case 402:return new G("insufficient_funds",e,r,void 0,o);case 409:return new G("conflict",e,r,void 0,o);case 412:return new G("precondition_failed",e,r,void 0,o);case 413:return new G("too_large",e,r,void 0,o);case 429:return new G("rate_limited",e,r,i,o);default:return new G("unavailable",e,r,i,o)}}function cc(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 uc(t){let n=t?.error?.details;return n===null?void 0:n}function mc(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function pc(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 $o(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Fo(t,e,n,r,i,o){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/add`;return t.client.post(a,i,o?.signal)}async function qo(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function jo(t,e,n,r,i,o){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/claim`;return t.client.post(a,i,o?.signal)}async function No(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Uo(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Bo(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Vo(t,e,n,r,i){let o=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(o,i?.signal)}async function Ho(t,e,n,r,i){let o=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(o,i?.signal)}async function Wo(t,e,n,r){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(i,r?.signal)}async function Ko(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Jo(t,e,n,r,i,o){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/finalize`;return t.client.post(a,i,o?.signal)}async function zo(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 Yo(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.get(r,n?.signal)}async function Xo(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Qo(t,e,n,r,i){let o=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Zo(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),a=`/v1/inventory/${v(e)}/${v(n)}`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function ea(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/items/${v(r)}`;return t.client.get(o,i?.signal)}async function na(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let a=o.toString(),s=`/v1/leaderboards/${v(e)}/${v(n)}/${v(r)}`+(a?`?${a}`:"");return t.client.get(s,i?.signal)}async function ta(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/orders/${v(r)}`;return t.client.get(o,i?.signal)}async function ra(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}`;return t.client.get(o,i?.signal)}async function ia(t,e,n,r,i,o){let a=`/v1/inventory/${v(e)}/${v(n)}/catalogs/${v(r)}/recipes/${v(i)}/availability`;return t.client.get(a,o?.signal)}async function oa(t,e,n,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function Cr(t,e,n,r,i){let o=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function aa(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${v(e)}/friends`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function sa(t,e,n){let r=`/v1/showcase/friends/${v(e)}`;return t.client.get(r,n?.signal)}async function la(t,e,n){let r=`/v1/inbox/friend-challenges/${v(e)}`;return t.client.get(r,n?.signal)}async function da(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${v(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function ca(t,e){let n=`/v1/games/${v(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function ft(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function ua(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function ma(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function pa(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 ga(t,e,n,r){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(i,r?.signal)}async function ya(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function fa(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function ha(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})}async function ba(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function _a(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/platform-funded-game-inventory-purchases`;return t.client.post(o,r,i?.signal)}async function va(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function wa(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Sa(t,e){return t.client.get("/v1/characters",e?.signal)}async function Ra(t,e,n,r){let i=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(i,r?.signal)}async function ka(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/orders`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function xa(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),a=`/v1/saves/${v(e)}/${v(n)}`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function Aa(t,e){let n=new URLSearchParams;e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Pa(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i="/v1/friends"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ea(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ta(t,e,n){let r=`/v1/inbox/friend-challenges/${v(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function Ca(t,e,n,r){let i=`/v1/games/${v(t.gameId())}/matches/${v(e)}/end`;return t.client.post(i,n,r?.signal)}async function Ia(t,e,n,r,i,o){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/max`;return t.client.post(a,i,o?.signal)}async function Ma(t,e,n,r,i,o){let a=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.put(a,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Oa(t,e,n,r,i){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(o,r,i?.signal)}async function La(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/rewarded-placements/${v(r)}/availability`;return t.client.get(o,i?.signal)}async function Ga(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Da(t,e,n,r){let i=`/v1/characters/${v(e)}`;return t.client.patch(i,n,r?.signal)}async function $a(t,e,n,r,i,o){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/upload-url`;return t.client.post(a,i,o?.signal,{replaySafe:true})}async function Fa(t,e,n,r,i,o){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/reset`;return t.client.post(a,i,o?.signal)}async function qa(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.delete(r,n?.signal)}var U="gem-web-bridge",bt={min:1,max:1},an=65536,ja=8,ht=5e3,Na=1024;function Mr(t){return Object.freeze(Object.assign(Object.create(null),t))}var Ua=Mr({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.earnAllowanceChanged":30,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.engaged":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.walletDisplay":60,"gem.menu":60,"gem.menuSelect":60,"gem.requestShare":6,"gem.vibrate":600,"gem.frameStats":120,"gem.portraitBorders":60,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,"gem.requestFriendChallenge":12,"gem.friendChallengeResult":30,__malformed:60}),_t="__malformed";var gc=Mr({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.requestFriendChallenge":"friendChallenges","gem.friendChallengeResult":"friendChallenges","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.autoStartFailedEvent":"autoStartFailure","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.portraitBorders":"portraitBorders","gem.engaged":"engagement","gem.viewport":"viewport","gem.walletDisplay":"walletDisplay","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.earnAllowanceChanged":"earnAllowance","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings","gem.requestShare":"share","gem.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu"}),yc=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function Ba(t){let e=gc[t];if(e!==void 0)return e;for(let[n,r]of yc)if(t.startsWith(n))return r}function Or(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 fc(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 hc(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function bc(t){return /^[a-z_]+$/.test(t)}function Ir(t,e,n){if(e>ja)return `nesting deeper than ${ja}`;if(++n.nodes>ht)return `more than ${ht} values`;if(n.bytes>an)return `over the ${an} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=t;if(n.seen.has(i))return "a repeated or cyclic object reference";if(n.seen.add(i),Array.isArray(t)){if(t.length>Na)return `an array of ${t.length} entries, over the ${Na} limit`;n.bytes+=2;for(let s of t){let l=Ir(s,e+1,n);if(l)return l}return null}let o=Object.getPrototypeOf(t);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";n.bytes+=2;let a=t;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++n.nodes>ht)return `more than ${ht} values`;if(n.bytes+=s.length*3+4,n.bytes>an)return `over the ${an} byte limit`;let l=Ir(a[s],e+1,n);if(l)return l}return null}function _c(t){let e={nodes:0,bytes:0,seen:new Set},n=Ir(t,0,e);return n?`message contains ${n}`:e.bytes>an?`message is over the ${an} byte limit`:null}var vc={origin:[Or,"not a well-formed origin"],url:[fc,"not a safe absolute http(s) URL"],bcp47:[hc,"not a well-formed BCP 47 tag"],code:[bc,"not a code of lower-case letters and underscores"]};function Va(t,e,n){for(let r of e){let i=n===""?r.n:`${n}.${r.n}`,o=t[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let a=Ha(o,r,i);if(a)return a}return null}function Ha(t,e,n){switch(e.k){case "string":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e.max)return `${n}: exceeds ${e.max} characters`;if(e.f){let[r,i]=vc[e.f];if(!r(t))return `${n}: ${i}`}return null}case "int":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 "boolean":return typeof t=="boolean"?null:`${n}: expected boolean`;case "enum":{let r=e.v;return r.includes(t)?null:`${n}: not one of ${r.join("|")}`}case "object":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:Va(t,e.fs,n);case "json":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "array":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e.max)return `${n}: exceeds ${e.max} items`;let r=e.it,i=`${n}[]`;for(let o of t){if(o==null){if(r.o)continue;return `${i}: required`}let a=Ha(o,r,i);if(a)return a}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}function P(t,e){return n=>{let r=_c(n);if(r)return r;if(typeof n!="object"||n===null||Array.isArray(n))return "message: expected object";let i=n;return i.gem!==U?"gem: wrong protocol marker":i.type!==t?`type: expected ${t}`:Va(i,e,"")}}var wc=P("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"},{n:"unbidden",k:"boolean",o:1}]),Sc=P("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),Rc=P("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),kc=P("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),xc=P("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"},{n:"boost",k:"object",o:1,fs:[{n:"multipliers",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"currencyId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"multiplierBp",k:"int",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"int",o:1,lo:1,hi:7}]}]),Ac=P("gem.pause",[{n:"paused",k:"boolean"}]),Pc=P("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),Ec=P("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),Tc=P("gem.earnAllowanceChanged",[]),Cc=P("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]},{n:"reserved",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384},{n:"width",k:"int",lo:0,hi:16384},{n:"height",k:"int",lo:0,hi:16384}]}}]),Ic=P("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),Mc=P("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),Oc=P("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),Lc=P("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),Gc=P("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),Dc=P("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),$c=P("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Fc=P("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),qc=P("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),jc=P("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),Nc=P("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Uc=P("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Bc=P("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),Vc=P("gem.requestContext",[]),Hc=P("gem.gameContext",[{n:"context",k:"json"}]),Wc=P("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Kc=P("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),Jc=P("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),zc=P("gem.ready",[]),Yc=P("gem.engaged",[]),Xc=P("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Qc=P("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Zc=P("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),eu=P("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),nu=P("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),tu=P("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),ru=P("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),iu=P("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),ou=P("gem.audioState",[{n:"muted",k:"boolean"}]),au=P("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),su=P("gem.walletDisplay",[{n:"visible",k:"boolean"},{n:"currencies",k:"array",o:1,max:8,it:{n:"",k:"string",max:64}},{n:"score",k:"boolean",o:1}]),lu=P("gem.menu",[{n:"settings",k:"boolean"},{n:"items",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"id",k:"string",max:32},{n:"label",k:"string",max:40}]}}]),du=P("gem.menuSelect",[{n:"entry",k:"enum",v:["settings","item"]},{n:"id",k:"string",o:1,max:32}]),cu=P("gem.requestShare",[{n:"params",k:"array",max:16,it:{n:"",k:"object",fs:[{n:"key",k:"string",max:64},{n:"value",k:"string",max:512}]}}]),uu=P("gem.vibrate",[{n:"pattern",k:"array",max:99,it:{n:"",k:"int",lo:0,hi:1e4}}]),mu=P("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),pu=P("gem.portraitBorders",[{n:"name",k:"string",o:1,max:40}]),gu=P("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),yu=P("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),fu=P("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"reason",k:"string",o:1,max:64,f:"code"},{n:"purchaseId",k:"string",o:1,max:64}]),hu=P("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),bu=P("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),_u=P("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),vu=P("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),wu=P("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),Su=P("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),Ru=P("gem.requestFriendChallenge",[{n:"requestId",k:"string",max:64},{n:"playerId",k:"string",max:64},{n:"template",k:"string",max:64},{n:"params",k:"json",o:1}]),ku=P("gem.friendChallengeResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"string",o:1,max:64},{n:"param",k:"string",o:1,max:64},{n:"channel",k:"string",o:1,max:16},{n:"configVersion",k:"int",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:864e5},{n:"detail",k:"string",o:1,max:300}]),vt=Mr({"gem.handshake":wc,"gem.handshake.accept":Sc,"gem.token":Rc,"gem.token.denied":kc,"gem.player":xc,"gem.pause":Ac,"gem.prefs":Pc,"gem.cohorts":Ec,"gem.earnAllowanceChanged":Tc,"gem.viewport":Cc,"gem.deviceSettings":Ic,"gem.willTerminate":Mc,"gem.roomEvent":Oc,"gem.socketState":Lc,"gem.seatedEvent":Gc,"gem.autoStartFailedEvent":Dc,"gem.signalEvent":$c,"gem.dedicatedEvent":Fc,"gem.partyResult":qc,"gem.clusterTarget":jc,"gem.devtools":Nc,"gem.screenshot":Uc,"gem.screenshot.denied":Bc,"gem.requestContext":Vc,"gem.gameContext":Hc,"gem.signal":Wc,"gem.dedicatedOffer":Kc,"gem.partyRequest":Jc,"gem.ready":zc,"gem.engaged":Yc,"gem.progress":Xc,"gem.requestToken":Qc,"gem.requestLocalServer":Zc,"gem.localServer":eu,"gem.localServer.denied":nu,"gem.exit":tu,"gem.openExternal":ru,"gem.requestFullscreen":iu,"gem.audioState":ou,"gem.rewardCue":au,"gem.walletDisplay":su,"gem.menu":lu,"gem.menuSelect":du,"gem.requestShare":cu,"gem.vibrate":uu,"gem.frameStats":mu,"gem.portraitBorders":pu,"gem.error":gu,"gem.requestPurchase":yu,"gem.purchaseResult":fu,"gem.deviceSettings.put":hu,"gem.deviceSettings.result":bu,"gem.requestAd":_u,"gem.adResult":vu,"gem.requestSignIn":wu,"gem.signInResult":Su,"gem.requestFriendChallenge":Ru,"gem.friendChallengeResult":ku});var ye={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},An=class{constructor(e=ye){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Ua[e];if(n===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??n,a=Math.max(0,r-i),s=Math.min(n,o+a*n/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function Lr(t,e){return t.toLowerCase()===e.toLowerCase()}function wt(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Wa(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:wt(n.hostname)&&wt(r.hostname)}function Ka(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 St=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let i=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,o=i.find(s=>s.currencyId===e),a;return !o&&this.resolveCurrencyId&&(a=await this.resolveCurrencyId(e).catch(()=>{}),a!==void 0&&(o=i.find(s=>s.currencyId===a))),{currencyId:o?o.currencyId:a??e,total:o?o.total:null,...o?.buckets===void 0?{}:{buckets:o.buckets}}}};function Dr(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let i=r??{};typeof i.id!="string"||i.id===""||typeof i.threshold!="number"||!Number.isFinite(i.threshold)||n.push({id:i.id,threshold:i.threshold,points:typeof i.points=="number"?i.points:0,hidden:i.hidden===true,...typeof i.unlocked_at=="number"&&Number.isFinite(i.unlocked_at)?{unlockedAt:i.unlocked_at}:{},...i.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var Ja="inventory",sn=t=>typeof t=="number"?t:0,Pn=t=>typeof t=="string"?t:"";function Gr(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 za(t){let e=t??{};return {itemDefinitionId:Pn(e.item_definition_id),instanceId:Pn(e.instance_id),quantity:sn(e.quantity),acquiredAt:sn(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function xu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Gr(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(a=>{let s=a??{};return {bucket:Pn(s.bucket),balance:sn(s.balance)}}):void 0;return {currencyId:Pn(i.currency_id),total:sn(i.total),...o===void 0?{}:{buckets:o}}}),items:Gr(e.items,za),progressions:Gr(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:Pn(i.progression_definition_id),currentValue:sn(i.current_value),completionCount:sn(i.completion_count),isCompleted:i.is_completed===true,...Dr(i)}}),...n===void 0?{}:{etag:n}}}var Rt=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Ja}#buckets`:Ja;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let o=r.items.data.filter(a=>a.itemDefinitionId===e);if(o.length>0)return o}let i=await ea(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(i)?i.map(za):[]}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 Zo(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 xu(n)}};var Au={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},Pu=new Set(Object.keys(Au));function Ya(t){return typeof t=="string"&&Pu.has(t)?t:"error"}var Ge=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var Q=t=>typeof t=="string"?t:"",Eu=t=>typeof t=="string"?t:Q(t&&typeof t=="object"?t.type:void 0),ke=t=>typeof t=="number"?t:0;function Tu(t){let e=t??{};return {prerequisiteType:Q(e.prerequisite_type),referenceId:Q(e.reference_id),required:ke(e.required),current:ke(e.current)}}function En(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:Q(e.order_id),status:Q(e.status),...n===void 0?{}:{etag:n}}}function kt(){return crypto.randomUUID()}var Cu="recipe-usage",Xa=100;function xt(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:Q(e.currency_id),bucket:Q(e.bucket),delta:ke(e.delta),balanceAfter:ke(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:Q(e.item_definition_id),instanceId:Q(e.instance_id),delta:ke(e.delta),quantityAfter:ke(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:Q(e.progression_definition_id),delta:ke(e.delta),valueAfter:ke(e.value_after),completed:e.completed===true};default:return {kind:"other",type:Q(e.type)}}}function Iu(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:Q(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:ke(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(xt):[]}}function Mu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(Iu):void 0;return {orderId:Q(e.order_id),status:Q(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(xt):[],consumed:Array.isArray(e.consumed)?e.consumed.map(xt):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(xt):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Ou(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:Q(e.target_order_id)||Q(e.source_order_id),status:Q(e.status),purchaseId:Q(e.purchase_id),sourceOrderId:Q(e.source_order_id),price:{currencyId:Q(n.platform_currency_id),amount:ke(n.price)}}}function Lu(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:Q(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 Qa(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 At=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(()=>Bo(this.api,this.entity.type,this.entity.id,{operations:e.map(Qa),source:n.source??"play",nonce:kt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return En(r)}async createMany(e,n={}){return this.write(()=>Uo(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Qa),nonce:kt()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let o=await ia(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},a=typeof o.uses_remaining=="number"?o.uses_remaining:void 0,s=typeof o.cooldown_expires_at=="string"?o.cooldown_expires_at:void 0,l=Array.isArray(o.lock_reasons)?o.lock_reasons.map(Tu):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>Eu(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(Cu,[],async()=>{let n=await oa(this.api,this.entity.type,this.entity.id,{limit:Xa})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(Lu),truncated:r.length>=Xa}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>Ko(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:kt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...Mu(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,i]=await Promise.all([ma(this.api,n.signal===void 0?{}:{signal:n.signal}),ft(this.api,n.signal===void 0?{}:{signal:n.signal})]),o=e.payment.currencySlug.toLowerCase(),a=i.currencies.find(c=>c.currency_id.toLowerCase()===o||c.slug.toLowerCase()===o);if(a===void 0){let c=i.currencies.map(p=>p.slug);throw new Ge("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let s=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(s===void 0)throw new Ge("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=s.platform_prices.find(c=>c.platform_currency_id===a.currency_id);if(l===void 0){let c=g=>i.currencies.find(y=>y.currency_id===g)?.slug??g,p=s.platform_prices.map(g=>`${c(g.platform_currency_id)} ${g.price}`);throw new Ge("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${a.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Ge("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>_a(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:a.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:kt(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return Ou(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let i=await this.write(()=>Fo(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return En(i)}async maxProgression(e,n,r){let i=await this.write(()=>Ia(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return En(i)}async claimProgression(e,n){let r=await this.write(()=>jo(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return En(r)}async resetProgression(e,n){let r=await this.write(()=>Fa(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return En(r)}async write(e){return this.cache.invalidate(),e()}};var $r=t=>typeof t=="string"?t:"",Gu=t=>typeof t=="number"?t:0;function Za(t){let e=t??{};return {orderId:$r(e.order_id),status:$r(e.status),source:$r(e.source),createdAt:Gu(e.created_at)}}var Pt=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await ka(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(Za):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await ta(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Za(r)}};var es=t=>typeof t=="number"?t:0,Du=t=>typeof t=="string"?t:"";function $u(t){let e=t??{};return {progressionDefinitionId:Du(e.progression_definition_id),currentValue:es(e.current_value),completionCount:es(e.completion_count),isCompleted:e.is_completed===true,...Dr(e)}}var Et=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let i=(await this.inventory.snapshot()).progressions.data.find(o=>o.progressionDefinitionId===e);if(i&&i.achievementsUnavailable!==true)return i;try{let o=await ra(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return $u(o)}catch{return i??null}}};var Tt=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,i){this.rebind();let o=n.length===0,a=o?e:e+"\0"+n.join("\0"),s=this.slots.get(a);if(s){let c=s.filledAt;if(c!==void 0&&(i===void 0||this.clock.now()-c<=i))return Promise.resolve(s.value);if(s.inFlight)return s.inFlight}let l=s??{};this.slots.set(a,l);let d=this.generation,m=r().then(c=>(o&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(a)===l&&this.slots.delete(a));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function Fr(t){let e=i=>new RegExp(`<${i}>([^<]{0,300})</${i}>`).exec(t)?.[1]?.trim()||void 0,n=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(n.length>0)return n.join(" \u2014 ");let r=t.trim();return r?r.slice(0,300):""}async function qr(t){try{let e=Fr(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var oe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},Fu=3e4,ns="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",qu=/^[A-Za-z0-9_]{1,64}$/;function xe(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(!qu.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function ts(t,e){let n=new AbortController,r=AbortSignal.timeout(e),i=()=>n.abort(r.reason),o=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",i,{once:true}),t?.addEventListener("abort",o,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",i),t?.removeEventListener("abort",o);}}}function jr(t,e){return t.aborted&&e?.aborted!==true}var ju=new Set(["x-ms-blob-type"]),Nu=/^[ -~]+$/;function Uu(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,i]of Object.entries(t)){let o=r.toLowerCase();if(!ju.has(o))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof i!="string"||!Nu.test(i))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(o in n)throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);n[o]=i;}return n}function Nr(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 Ur(t){return t?.reason==="not_found"}var Ct=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let i;try{i=JSON.stringify(n);}catch(o){throw new oe("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}. Retrying stores the same unserialisable value.`)}if(i===void 0)throw new oe("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(i),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){let i=r.contentType??"application/octet-stream",o=this.budget(r.timeoutMs),a=ts(r.signal,o);try{let s=await $a(this.api,this.entity.type,this.entity.id,xe(e),{size_bytes:n.byteLength,content_type:i,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:a.signal});if(typeof s.upload_url!="string"||typeof s.session_id!="string")throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=Uu(s.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(s.upload_url,{method:"PUT",headers:{"content-type":i,...l},body:n,credentials:"omit",signal:a.signal});}catch(c){throw jr(a.signal,r.signal)?this.timeout("upload",o):new oe("upload_failed",`${ns} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await qr(d);throw new oe("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+c:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+c)}return Nr(await Jo(this.api,this.entity.type,this.entity.id,xe(e),{session_id:s.session_id},{signal:a.signal}))}catch(s){throw this.rethrow(s,r.signal,a.signal,"save",o)}finally{a.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(i){throw new oe("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${i}`)}}async getBytes(e,n={}){let r=this.budget(n.timeoutMs),i=ts(n.signal,r);try{let o;try{let l=await Cr(this.api,this.entity.type,this.entity.id,xe(e),{signal:i.signal});if(!l.modified)return null;o=l.body;}catch(l){if(Ur(l))return null;throw l}if(typeof o.download_url!="string")throw new oe("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),s;try{s=await a(o.download_url,{credentials:"omit",signal:i.signal});}catch(l){throw jr(i.signal,n.signal)?this.timeout("download",r):new oe("download_failed",`${ns} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await qr(s);throw new oe("download_failed",`the save download answered ${s.status}. `+(s.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await s.arrayBuffer())}catch(o){throw this.rethrow(o,n.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,n={}){try{let r=await Cr(this.api,this.entity.type,this.entity.id,xe(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Nr(r.body):null}catch(r){if(Ur(r))return null;throw r}}async list(e={}){let n=await xa(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(Nr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Ho(this.api,this.entity.type,this.entity.id,xe(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Ur(r))throw r}}budget(e){return e??this.options.timeoutMs??Fu}timeout(e,n){return new oe("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,i,o){return e instanceof oe?e:jr(r,n)?this.timeout(i,o):e}};function Bu(t){try{return Tr(t)}catch{return t}}function Br(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"?Bu(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var It=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await Ra(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>Br(i)):[]}async get(e,n={}){try{let r=await Qo(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?Br(r.body,r.etag):null}catch(r){if(rs(r))return null;throw r}}async put(e,n,r={}){let i=await Ma(this.api,this.entity.type,this.entity.id,e,{value:Er(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Br(i)}async delete(e,n){try{await Vo(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!rs(r))throw r}}};function rs(t){return t?.reason==="not_found"}function Mt(t,e,n={}){let r=new Tt(ye,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let i=new Rt(t,e,r);return {settings:new It(t,e),inventory:i,saves:new Ct(t,e,n.saves??{}),currencies:new St(i,n.resolveCurrencyId),mutations:new At(t,e,r),orders:new Pt(t,e),progressions:new Et(t,e,i)}}var Vr={type:"players",id:"me"};var qe=t=>typeof t=="string"?t:"",ln=t=>typeof t=="number"?t:0;function Ot(t,e){let n=e??{},r=qe(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:qe(n.player_id),gameId:qe(n.game_id),channel:qe(n.channel)||"release",name:qe(n.name),slotIndex:ln(n.slot_index),isActive:n.is_active!==false,createdAt:qe(n.created_at),updatedAt:qe(n.updated_at)}}var Lt=class{constructor(e,n,r,i){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=i;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=Mt(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 Sa(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>Ot(this.scope,i)):[]}async get(e,n){let r=await Yo(this.api,e,n===void 0?{}:{signal:n});return Ot(this.scope,r)}async create(e){let n=await No(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Ot(this.scope,n)}async update(e,n,r){let i=await Da(this.api,e,{name:n},r===void 0?{}:{signal:r});return Ot(this.scope,i)}async delete(e,n){await qa(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await ya(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:ln(r?.total_slots),availableSlots:ln(r?.available_slots),activeCharacterCount:ln(r?.active_character_count),defaultMaxSlots:ln(r?.default_max_slots),purchasedExtraSlots:ln(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var fe=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function Oe(t){return new fe(t)}var dn={toPlain(t){return fe.unwrap(t)},compare(t,e,n){let r=t instanceof fe?fe.unwrap(t):t,i=e instanceof fe?fe.unwrap(e):e,o;try{o=new Intl.Collator(n);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(t,e){let n=t instanceof fe?fe.unwrap(t):t,r=e instanceof fe?fe.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var cn=t=>typeof t=="string"?t:"";function Gt(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:cn(e.transfer_id),status:cn(e.status),sourceEntityId:cn(e.source_entity_id),targetEntityId:cn(e.target_entity_id),...n===void 0?{}:{message:Oe(n)},createdAt:cn(e.created_at),expiresAt:cn(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Vu(){return crypto.randomUUID()}var Dt=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 ba(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:Vu()},e.signal===void 0?{}:{signal:e.signal});return Gt(n)}async list(e={}){let r=await Ea(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Gt):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await fa(this.api,e,n===void 0?{}:{signal:n});return Gt(r)}async accept(e,n){return this.resolve(()=>$o(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>Ga(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>qo(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Gt(await e())}};var Hu=t=>typeof t=="string"?t:"",Wu=t=>typeof t=="string"&&t?t:void 0,Ku=t=>typeof t=="number"?t:void 0;function is(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 Ju(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new de("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 de("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Ku(e.version);if(r===void 0)throw new de("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,m)=>{let c=Hu(l.id);if(!c)throw new de("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},o=n("items");o.forEach((l,d)=>i(l??{},"items",d));let a=n("currencies");a.forEach((l,d)=>i(l??{},"currencies",d));let s=t;return {...s,version:r,hash:typeof s.hash=="string"?s.hash:"",items:o,currencies:a,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 s.kv=="object"&&s.kv!==null&&!Array.isArray(s.kv)?s.kv:{},item:is(o),currency:is(a)}}var de=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},os=10*1024*1024,as=15e3,ss=new Set(["dev","test","release"]);function zu(t){if(!ss.has(t))throw new de("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...ss].join(", ")}. gem-api would reject the assignment read.`);return t}var $t=t=>typeof t=="number"?t:0,Hr=t=>typeof t=="string"?t:"";function Yu(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let i=r??{},o=typeof i.rarity_tier=="string"?i.rarity_tier:void 0;return {entryId:Hr(i.entry_id),weight:$t(i.weight),dropRate:$t(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:Hr(e.loot_table_id),name:Hr(e.name),rollCount:$t(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:$t(e.total_weight),entries:n}}var Ft=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=null;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,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=null,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new de("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let i=this.dropRatesByConfig.get(r);i===void 0&&(i=new Map,this.dropRatesByConfig.set(r,i));let o=i.get(e);if(o!==void 0)return o;let a=(async()=>{let s=await Xo(this.api,e,n===void 0?{}:{signal:n});return Yu(s)})().catch(s=>{throw i?.get(e)===a&&i.delete(e),s});return i.set(e,a),a}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??as),n;try{let l=await zo(this.api,zu(this.channel()),{signal:e});if(!l.modified)throw new de("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof de)throw l;if(l?.reason==="not_found")return null;throw l}let r=Wu(n.config_url);if(r===void 0)return null;let i=this.options.fetch??globalThis.fetch.bind(globalThis),o;try{o=await i(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new de("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??as}ms`):new de("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!o.ok){let l=await o.text().then(d=>Fr(d)).catch(()=>"");throw new de("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await o.text();if(a.length>os)throw new de("config_too_large",`the config document is ${a.length} bytes, over the ${os} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new de("config_malformed",`config document is not JSON: ${String(l)}`)}return Ju(s)}};var ls=400,Ae=t=>typeof t=="string"?t:"",Xu=/(?:Z|[+-]\d{2}:?\d{2})$/i;function je(t){let e=Ae(t);if(!Xu.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Qu=/^[0-9a-f]{1,64}$/,Zu=/^[0-9a-f]{16}$/,em=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,nm=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Wr(t){let e=Ae(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,i,o]=[Number(n[1]),Number(n[2]),Number(n[3])],a=new Date(Date.UTC(r,i-1,o));return a.getUTCFullYear()===r&&a.getUTCMonth()===i-1&&a.getUTCDate()===o?e:void 0}var tm=4096,rm=new TextEncoder;function im(t){let e=Ae(t.challenge_data),n=Ae(t.challenge_data_hash);return e===""||!Zu.test(n)?{}:rm.encode(e).length>tm?{}:{data:e,dataHash:n}}function om(t){let e=t??{},n=je(e.period_start_at),r=je(e.period_ends_at);if(n===0||r===0)return;let i=Ae(e.slug),o=Ae(e.seed),a=Wr(e.period_local_date),s=Ae(e.boundary),l=Ae(e.reset_time);return {id:Ae(e.progression_definition_id),...i===""?{}:{slug:i},window:Ae(e.window),periodStartAt:n,periodEndsAt:r,...a===void 0?{}:{periodLocalDate:a},boundary:em.test(s)?s:"",resetTime:nm.test(l)?l:"",seed:Qu.test(o)?o:"",...im(e)}}function un(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 qt(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(om).filter(n=>n!==void 0):[]}var Tn=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;un(n);let r=await wa(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return qt(r)}};function Ne(t){return typeof t=="string"&&t!==""?t:void 0}var ds=new Set(["localhost","127.0.0.1","[::1]"]);function Kr(t){let e=Ne(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:"&&ds.has(n.hostname)))return e}function am(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},i=Ne(r.item_id),o=Kr(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function ve(t){let e=t??{},n=Ne(e.player_id),r=Ne(e.display_name),i=Ne(e.discriminator),o=Ne(e.display_tag),a=Ne(e.avatar_icon_id),s=Kr(e.avatar_icon_url);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:Oe(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:Oe(o)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:am(e.badges)}}var sm=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function lm(t){if(t===void 0)return;let e=Kr(t);if(e===void 0)return;let n=new URL(e);return ds.has(n.hostname)||sm.has(n.origin)?e:void 0}var cs=100,ps=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Jr(t){let{periodsBack:e,period:n,playerId:r}=t;if(un(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!ps.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 gs(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!ps.test(e))return;let n=Wr(t.period_local_date),r=je(t.period_start_at),i=je(t.period_ends_at),o=r>0&&i>0;return {id:e,...n===void 0?{}:{localDate:n},...o?{startAt:r,endsAt:i}:{},opensAt:je(t.opens_at),closesAt:je(t.closes_at),final:t.final===true}}var Cn=t=>typeof t=="string"?t:"",mn=t=>typeof t=="number"?t:0,In=t=>typeof t=="string"?t:void 0,dm=t=>typeof t=="number"?t:void 0,ys={player:"players",character:"characters"};function cm(t,e){let n=t??{},r=In(n.entity_id),i=typeof n.entity_type=="string"&&Object.hasOwn(ys,n.entity_type)?n.entity_type:void 0,o=fs(n.stats),a=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,s=e?n.is_viewer===true:void 0;return {...ve(n),rank:mn(n.rank),occurredAt:mn(n.occurred_at),...s===void 0?{}:{isViewer:s},...r===void 0?{}:{entityId:r},...i===void 0?{}:{entityType:i},...o===void 0?{}:{stats:o},...a===void 0?{}:{properties:a}}}function us(t,e){let n=t??{},r=In(n.bucket_1),i=In(n.bucket_2),o=dm(n.update_frequency_seconds),a=gs(n);return {leaderboardType:Cn(n.leaderboard_type),runType:Cn(n.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(n.entries)?n.entries.map(s=>cm(s,e)):[],generatedAt:mn(n.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...a===void 0?{}:{period:a}}}function ms(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=fs(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:mn(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function fs(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 um(t,e,n){let r=t??{},i=In(r.bucket_1),o=In(r.bucket_2),a=gs(r);return {leaderboardType:Cn(r.leaderboard_type),runType:Cn(r.run_type),entityType:e,entityId:n,...i===void 0?{}:{bucket1:i},...o===void 0?{}:{bucket2:o},entries:Array.isArray(r.entries)?r.entries.map(ms).filter(s=>s!==void 0):[],personalBest:ms(r.personal_best)??null,totalRuns:mn(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:mn(r.generated_at),...a===void 0?{}:{period:a}}}var Mn=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Jr(n),i=await da(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 us(i,false)}async friends(e,n={}){let r=Jr(n),i=await aa(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 us(i,true)}async mine(e,n={}){return this.#t(e,"player","me",n)}async character(e,n,r={}){return this.#t(e,"character",n,r)}async#t(e,n,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>cs)throw new TypeError(`limit must be an integer between 1 and ${cs}, got ${String(l)}`)}let o=Jr(i),a=await na(this.#e,e,ys[n],r,{...o,...i.bucket1===void 0?{}:{bucket_1:i.bucket1},...i.bucket2===void 0?{}:{bucket_2:i.bucket2},...i.limit===void 0?{}:{limit:i.limit},...i.signal===void 0?{}:{signal:i.signal}}),s=n==="player"&&r==="me"&&Cn((a??{}).entity_id)||r;return um(a,n,s)}};var jt=t=>typeof t=="string"?t:"",zr=t=>typeof t=="number"?t:0;function hs(t){let e=t??{};return {playerId:jt(e.player_id),key:jt(e.key),value:e.value,updatedAt:zr(e.updated_at)}}function mm(t){let e=t??{};return {...ve(e),playerId:jt(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:zr(e.updated_at)}}function pm(t){return t?.reason==="not_found"}var On=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let i=await sa(this.api,xe(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:jt(i.key),entries:Array.isArray(i.entries)?i.entries.map(mm):[],generatedAt:zr(i.generated_at)}}async of(e,n,r={}){try{return hs(await ga(this.api,e,xe(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(pm(i))return null;throw i}}async set(e,n,r={}){if(xe(e),n===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(n);}catch(o){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}.`,{cause:o})}let i=await this.selfPlayerId();return hs(await Oa(this.api,i,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Wo(this.api,r,xe(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var gm="gemChallenge",bs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function _s(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(gm)??void 0}catch{return}}var Ue=class extends G{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(n))i!==void 0&&Object.assign(this,{[r]:i});}},Nt=t=>typeof t=="string"?t:void 0;function vs(t){let e=t??{};return {...ve(e),playerId:Nt(e.player_id)??""}}function ws(t){let e=t.has_more===true?Nt(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function ym(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(vs):[],...ws(e)}}var Yr=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function fm(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 Ss(t){let e=t??{},n=Yr(e.opened_at),r=Yr(e.answered_at);return {id:Nt(e.item_id)??"",from:vs(e.sender),template:Nt(e.template)??"",params:fm(e.params),createdAt:Yr(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function hm(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(Ss):[],...ws(e)}}function bm(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Ln=class{#e;#t;#o;constructor(e,n={}){this.#e=e,this.#t=n.challenge,this.#o=n.launchedChallengeId;}async list(e={}){let n=await Pa(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return ym(n)}challenge(e){return this.#t===void 0?Promise.resolve({outcome:"unavailable"}):this.#t(e)}async inbox(e={}){let n=await Aa(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return hm(n)}async launchedChallenge(e={}){let n=this.#o;if(n===void 0||!bs.test(n))return null;try{return Ss(await la(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(bm(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!bs.test(e))throw new G("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await Ta(this.#e,e);}};var _m=0;function Pe(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++_m)}-${String(Date.now())}-${t}`}}var vm=12e4,Rs=8,wm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Sm=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Gn(t,e,n={}){return new Ue(new G("invalid",400,e,void 0,t),n)}function Rm(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function km(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!wm.test(e))return {error:Gn("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!Sm.test(n))return {error:Gn("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(!Rm(r))return {error:Gn("param_invalid","params must be a plain object of strings and integers")};let i={},o=Object.keys(r);for(let a of o){let s=r[a];if(typeof s=="string"||typeof s=="number"&&Number.isSafeInteger(s)){Object.defineProperty(i,a,{value:s,enumerable:true,writable:true,configurable:true});continue}return {error:Gn("param_invalid",`params.${a} must be a string or a safe integer`,{param:a})}}return o.length>Rs?{error:Gn("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(Rs)}`)}:{playerId:e,template:n,params:i}}function xm(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 Ue(new G("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new Ue(new G("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function Am(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function ks(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=km(n);if("error"in r)return Promise.reject(r.error);let i=`challenge-${Pe()}`;return new Promise((o,a)=>{let s={},l=m=>{e.delete(i)&&(t.clock.clearTimeout(s.timer),"error"in m?a(m.error):o(m.outcome));};e.set(i,l),s.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??vm);let d=false;try{d=t.bridge.requestFriendChallenge(i,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(n){let r=e.get(n.requestId);if(r===void 0){t.onDropped?.(`gem.friendChallengeResult (${Am(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(xm(n));}}}var Ut=t=>typeof t=="string"?t:void 0;function Pm(t){let e=t??{},n=Ut(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Ut(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Bt=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await ft(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let a=Pm(o);a!==void 0&&i.push(a);}return i}},Xr=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function Em(t){let e=t??{},n=Ut(e.currency_id);if(n===void 0||n==="")return;let r=Xr(e.limit),i=Math.min(Xr(e.earned),r),o=Math.min(Xr(e.remaining),r-i),a=e.period_days,s=typeof a=="number"&&Number.isInteger(a)&&a>=1?a:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Ut(e.currency_slug)??"",currencyId:n,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:s,...d===void 0?{}:{resetsAt:d}}}function xs(t){let e=new Set,n=r=>{t?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let i=r();typeof i?.then=="function"&&i.then(void 0,n);}catch(i){n(i);}}}}var Vt=class{#e;#t;#o;constructor(e,n,r){this.#e=e,this.#t=n,this.#o=r;}async get(e={}){let r=(await ca(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let a=Em(o);a!==void 0&&i.push(a);}return i}on(e,n){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#t?.on(n)??(()=>{})}},Dn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Bt(e),this.earnAllowance=new Vt(e,n,r);}};var Qr=t=>typeof t=="string"?t:"",As=t=>typeof t=="number"?t:0;function Tm(t){let e=t??{};return {key:Qr(e.key),visibility:Qr(e.visibility),value:e.value,updatedAt:As(e.updated_at)}}function Cm(t){let e=t??{};return {...ve(e),playerId:Qr(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Tm):[],generatedAt:As(e.generated_at)}}function Im(t){return t?.reason==="not_found"}var $n=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return Cm(await ua(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Im(r))return null;throw r}}};var Mm=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]]),Ht=class extends G{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:Mm.get(this.code))??super.retryable}},Be=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Om(e),i;try{i=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(o){throw o instanceof G?Gm(o):o}return Lm(i)}};function Om(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 ie(`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 ie(`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 Lm(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 Gm(t){let{details:e,invocationId:n}=Do(t),i=e?.untrusted?.message,o=e?.reason;return new Ht(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...t.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}var Dm=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Zr="gem_";function Ps(t){return t.startsWith(Zr)}var Es=1e4,Ts=50,$m=500,Fm=65536-4*1024,qm=24*1024;function Cs(t){let e={},n={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=i:typeof i=="number"&&Number.isFinite(i)&&(n[r]=i);return {dimensions:e,measures:n}}var Is=t=>typeof t=="number"?t:0,jm=t=>typeof t=="string"?t:"";function ei(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function Nm(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:Is(o.index),code:jm(o.code)}}):[];return {accepted:Is(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function ni(){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 Um(t){return t?.retryable===true}var Fn=class{#e;#t;#o;#y;#n=[];#f={};#a=0;#s=null;#h=false;#b=false;#_=false;#r=false;#v=null;#l=null;#d=false;#i=false;#m=false;#w=false;#S=false;constructor(e){this.#e=e,this.#t=e.options?.enabled!==false,this.#o=Math.max(Es,e.options?.flushIntervalMs??Es),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??$m));}track(e,n={}){if(!(!this.#t||this.#r)){if(Ps(e)){this.#S||(this.#S=true,this.#g(`[gem] analytics: '${e}' was not recorded \u2014 the gem_ prefix is reserved for the platform's own events, which the SDK emits for you. Name your event something else.`));return}this.#R(e,Cs({...this.#f,...n}));}}setContext(e){this.#f={...this.#f,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return ei();let n=this.#E();if(n===null||n==="")return this.#n.length>0&&!this.#w&&(this.#w=true,this.#g("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),ei();if(this.#k(),this.#n.length===0)return ei();let r=e.keepalive===true;this.#u();let i=this.#n.splice(0,this.#A(r)),o=this.#a;this.#a=0;let a=Math.round(this.#e.clock.now()),s={batch_id:ni(),sent_at_ms:a,events:i.map(d=>Ms(d,a))},l={client:this.#e.client(),gameId:()=>n};this.#_=true;try{let d=await ha(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=Nm(d,o);return this.#P(m),m}catch(d){throw Um(d)?this.#x(i,o):this.#g(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#_=false,this.#n.length>0&&this.#c();}}trackPlatform(e,n={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#R(e,Cs(n));}hold(){this.#r||this.#l!==null||(this.#i=true,this.#u());}release(){if(!this.#i||this.#r)return;this.#i=false;let e=this.#e.clock.now(),n=this.#n.map(r=>({...r,atMs:e}));this.#n=n,this.#m&&(this.#m=false,this.#l=e,this.#d=false,this.#n.unshift({uid:ni(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#n.length>=Ts?this.#p():this.#n.length>0&&this.#c();}get held(){return this.#i}startSession(){if(!(this.#r||this.#l!==null)){if(this.#i){this.#m=true;return}this.#l=this.#e.clock.now(),this.#d=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#d)return;if(this.#d=true,this.#i){this.#m=false,this.#n=[],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.#p({keepalive:true});}setPaused(e){this.#r||e===this.#h||(this.#h=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#n.length>0&&this.#c());}setHidden(e){this.#r||e===this.#b||(this.#b=e,e?this.#u():this.#n.length>0&&this.#c());}dispose(){this.#r=true,this.#u(),this.#n=[],this.#a=0;}get pending(){return this.#n.length}#R(e,n){let{dimensions:r,measures:i}=n;for(this.#k();this.#n.length>=this.#y;)this.#n.shift(),this.#a+=1;this.#n.push({uid:ni(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#n.length>=Ts?this.#p():this.#c();}#p(e={}){this.flush(e).catch(()=>{});}#x(e,n){for(this.#n=[...e,...this.#n],this.#a+=n;this.#n.length>this.#y;)this.#n.shift(),this.#a+=1;}#A(e){let n=e?qm:Fm,r=Math.min(this.#n.length,100),i=128;for(let o=0;o<r;o+=1){let a=this.#n[o];if(a===void 0)break;if(i+=JSON.stringify(Ms(a,0)).length+1,i>n)return Math.max(1,o)}return r}#c(){this.#s!==null||this.#h||this.#b||this.#i||this.#r||this.#_||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#p();},this.#o));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#k(){let e=this.#T();e===null||e===""||(this.#v!==null&&this.#v!==e&&(this.#n=[],this.#a=0,this.#l=null,this.#d=false),this.#v=e);}#P(e){for(let n of e.rejected)this.#g(`[gem] analytics: an event was refused (${n.code}). `+Bm(n.code));}#g(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#E(){try{return this.#e.gameId()}catch{return null}}#T(){try{return this.#e.playerId()}catch{return null}}};function Ms(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function Bm(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 me(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function qn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=me(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Vm=2e3,Hm=5e3;function Ls(t){let e=[],n=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=c=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(c));},m=t.clock.setTimeout(()=>{n=true,a([]);},t.timeoutMs??Vm);});return r={promise:s,settle:a},s};return {resolveList:o,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(a=>a[0])},refresh(a){return !Os(e,a)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{i.delete(d)&&(t.clock.clearTimeout(l),s(m));};i.set(d,a),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??Hm);})},accept(a,s){let l=qn(s),d=me(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...i])Os(m,p)||c(m);}}}}function Os(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Wm=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),_=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="DedicatedServerError",this.retryable=Wm.has(n),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var Gs=["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"],Km=new Set(Gs);function pn(t){return typeof t=="string"&&Km.has(t)?t:"unknown"}var Wt="webrtc_dedicated",oi=["universal","mobile","web"];var Jm="p2p_unavailable",zm="capacity_unavailable",Ym=2,Ds=3e4,$s=1e3,Fs=2e4;async function ai(t){let e=me(t.clusterTargetId),n=t.nextClusterTarget,r=0,i=t.clock??ye,o=t.retry??{},a=o.budgetMs??Ds,s=o.maxDelayMs??Fs,l=o.initialDelayMs??$s,d=i.now(),m=d+a,c=0;for(;;){c++;try{let p=await ci(t.signal,"while allocating",()=>t.client.post(`${Ns(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Xm(p)||a<=0)throw p;if(p.status===503&&p.code===Jm)throw new _("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===zm?r+1:0,n!==void 0&&r>=Ym){let A=n;n=void 0;let C=me(await A());C!==void 0&&(e=C,r=0);}let g=Math.min(s,l*2**(c-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),S=Math.max(g/2,y)+Math.random()*(g/2);if(i.now()+S>m)throw Qm(t,p,c,i.now()-d,a);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:a,nextAttemptInMs:S,status:p.status,message:p.message}),await Kt(i,S,t.signal),t.signal?.aborted)throw ii("while waiting to allocate")}}}function Xm(t){return t instanceof G?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Qm(t,e,n,r,i){let o=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new _("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${o}: ${e.message}`,{cause:e}):new _("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${o}: ${e.message}`,{cause:e})}var Zm=12e4,ep=1e3;async function si(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??ep,i=t.timeoutMs??Zm,o=e.now()+i,a=qs(t),s={seen:t.knownToExist===true};for(;;){let l=await js(t,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new _("timeout",`match ${n} was still ${l.status} after ${i}ms`);await Kt(e,r,t.signal);}}async function li(t){return (await js(t,qs(t),{seen:t.knownToExist===true})).outcome}function qs(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Ns(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function js(t,e,n){let{matchId:r}=t,i=t.clock.now(),o;try{o=await ci(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(a){if(a instanceof G&&a.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(n.seen=true,o.status==="ready")return {status:"ready",outcome:np(r,o,i)};if(o.status==="failed"){let a=o.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:pn(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function di(t){let e=await ci(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||n.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function ci(t,e,n){if(t?.aborted)throw ii(e);try{return await n()}catch(r){throw t?.aborted?ii(e,r):r}}function ii(t,e){return new _("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function np(t,e,n){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:n+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function Ns(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Kt(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{t.clearTimeout(o),n?.removeEventListener("abort",i),r();},o=t.setTimeout(i,e);n?.addEventListener("abort",i);})}function Us(t){return typeof t=="string"&&t.trim()!==""}function Jt(t,e){return Us(t)?t.trim():Us(e)?e:null}var zt="0.1.0-beta",Bs="0-beta",gn="web",tp=/^(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 rp(t){let e=tp.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Vs(t,e){let n=ip(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:zt};let i=rp(r);if(i===null)throw new _("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${zt}' for it.`);if(i!==Bs)throw new _("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Bs}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${zt}' for it.`);return {...t,platform:n,engineVersion:r}}function ip(t,e){if(t===void 0||t===gn)return gn;if(!oi.includes(t))throw new _("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${oi.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${gn}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${gn}' 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.`),gn}var op="join",ap="welcome",sp="rejected",Hs=25e3,lp=1e3,ui=1;function mi(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var dp={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 pi(t){let e=typeof t=="string"?t:"unknown";return new _(dp[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function jn(t){let{channel:e,clock:n}=t;return new Promise((r,i)=>{let o=false,a=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Hs),s=n.setTimeout(()=>w(new _("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(a,lp)),l=S=>{let A=S.data;if(typeof A!="string"){c(A);return}let C;try{C=JSON.parse(A);}catch{c(A);return}if(o){c(A);return}if(C.t===ap){let b=mi(C.heartbeat_interval);y({...typeof C.player_id=="string"?{playerId:C.player_id}:{},...typeof C.match_id=="string"?{matchId:C.match_id}:{},...b===void 0?{}:{heartbeatIntervalMs:b}});return}if(C.t===sp){w(pi(C.reason));return}c(A);},d=()=>{w(new _("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new _("aborted","the caller aborted during the join exchange"));},c=S=>{o&&t.onMessage?.(S);},p=()=>{n.clearTimeout(s),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=S=>{o=true,p(),t.onMessage===void 0&&g(),r({welcome:S,detach:g});},w=S=>{o||(o=true,p(),g(),i(S));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:op,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:ui}:{}}));}catch(S){w(new _("connection_failed",`the join frame could not be sent on the open channel: ${String(S)}`,{cause:S}));}})}var Ve=1,Nn=2,gi=4,hi=8,cp=2,up=1e3,bi="heartbeat timeout",Un="gem-uu",Yt=2,Ks="gem_transports";function yn(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!mp(r)||e.includes(r)||e.push(r);}return e}function mp(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function Bn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Ks];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 Xt(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Js=new TextEncoder,zs=new TextDecoder;function _i(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function vi(t){let e=0;return t?.reliable===false&&(e|=Ve),t?.ordered===false&&(e|=Nn),e}function wi(t){return {reliable:(t&Ve)===0,ordered:(t&Nn)===0}}var Si={reliable:true,ordered:true};function Ys(t){return JSON.stringify({t:"join",credential:t,wire:Yt,heartbeat:ui})}function Xs(t){let e;try{e=JSON.parse(t);}catch{throw new _("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=mi(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"?pi(e.reason):new _("join_refused","the server answered the join out of protocol")}function Qt(){return typeof globalThis.WebTransport=="function"&&Ri===null}function Zt(){return Ri}var Ri=null;var Ws="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function pp(t){let e=yt(t);if(e.byteLength!==32)throw new _("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var yi=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new _("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let a=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function fi(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 Vn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new _("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new s(t.url):new s(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:pp(t.certHashBase64)}]});}let r=n,i=s=>{try{r.close();}catch{}throw s},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Ri=Ws,i(new _("connection_failed",`${Ws}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new _("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return i(new _("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(fi(gi,Js.encode(Ys(t.credential))));let c=new yi,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),a]);if(y.done||y.value===void 0)return i(new _("connection_failed","the control stream closed before the join was answered"));for(let w of c.push(y.value)){g=Xs(zs.decode(w.payload));break}}return {link:gp(r,m,p,c,t.log??(y=>console.warn(y)),Zs(g,t.clock)),welcome:g}}catch(s){return i(s)}}function gp(t,e,n,r,i,o){let a,s,l=false,d=y=>{if(!l){l=true,m.stop();try{t.close();}catch{}s?.(y);}},m=xi(o,()=>d(bi)),c=(y,w)=>{m.heard(),(y&hi)===0&&a!==void 0&&((y&gi)!==0?a(zs.decode(w),Si):a(w,wi(y)));};(async()=>{try{for(;;){let y=await n.read();if(y.done||y.value===void 0)break;for(let w of r.push(y.value))c(w.flags,w.payload);}}catch{}d("stream closed");})();let p,g;try{let y=t.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let w=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let S=await w.read();if(S.done||S.value===void 0)break;let A=S.value;A.byteLength!==0&&c((A[0]??0)|Ve|Nn,A.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,i(`[gem] webtransport datagram lane unusable (${Xt(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(Qs(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,w){if(l)return;if(typeof y=="string"){e.write(fi(gi,Js.encode(y))).catch(()=>d("write failed"));return}let S=vi(w);if((S&Ve)!==0&&g!==void 0){let A=_i(S,y),C=p?.maxDatagramSize;if(C===void 0||A.byteLength<=C){g.write(A).catch(()=>{});return}}e.write(fi(S,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function ki(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new _("connection_failed","this environment has no WebSocket"));n=new i(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((i,o)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),o(new _("timeout","websocket did not come up in time")));},e),l=g=>{a||(a=true,clearTimeout(s),r.close(),o(g));},d=()=>{r.send(Ys(t.credential));},m=g=>{if(a)return;if(typeof g.data!="string"){l(new _("join_refused","the server sent binary before answering the join"));return}let y;try{y=Xs(g.data);}catch(w){l(w);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),i({link:yp(r,Zs(y,t.clock)),welcome:y});},c=()=>{l(new _("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new _("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Qs(t){return typeof t=="string"&&t.length>0?t:void 0}function Zs(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function xi(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,up)*cp,i=n.now(),o=null,a=()=>{o=null;let s=n.now()-i;if(s>=r){e();return}o=n.setTimeout(a,r-s);};return o=n.setTimeout(a,r),{heard:()=>{i=n.now();},stop:()=>{o!==null&&(n.clearTimeout(o),o=null);}}}function yp(t,e){let n,r,i=false,o=s=>{if(!i){i=true,a.stop();try{t.close();}catch{}r?.(s);}},a=xi(e,()=>o(bi));return t.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){n?.(s.data,Si);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&hi)===0&&n?.(l.slice(1),wi(d));})),t.addEventListener("close",(s=>o(Qs(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!i){if(typeof s=="string"){t.send(s);return}t.send(_i(vi(l),s));}},onMessage(s){n=s;},onClose(s){r=s;},close(){o("closed");}}}function Ai(t,e,n,r){let i,o,a=false,s=n,l=c=>{if(!a){a=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}o?.(c);}},d=xi(r,()=>l(bi)),m=(c,p)=>{if(d.heard(),typeof c=="string"){i?.(c,Si);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&hi)===0&&i?.(g.slice(1),wi(y|p));};if(t.addEventListener("message",(c=>m(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),s!==void 0){let c=s;c.addEventListener("message",(p=>m(p.data,Ve|Nn))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){t.send(c);return}let g=vi(p),y=_i(g,c);if((g&Ve)!==0&&s!==void 0&&s.readyState==="open"){s.send(y);return}t.send(y);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}function Ti(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let i=Pi(r);i!==void 0&&(e[n]=i);}return e}function Ci(t){if(Array.isArray(t))return t.map(fp).filter(e=>!!e)}function Pi(t){if(Ei(t)||Array.isArray(t)&&t.every(Ei))return t}function Ei(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function fp(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Pi(e.fixed),r=Pi(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},...fn("description",hp(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Ei)?{allowed:e.allowed}:{},...fn("min",Hn(e.min)),...fn("max",Hn(e.max)),...fn("minItems",Hn(e.min_items)),...fn("maxItems",Hn(e.max_items)),...fn("maxLength",Hn(e.max_length))}}function hp(t){return typeof t=="string"&&t.length>0?t:void 0}function Hn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function fn(t,e){return e===void 0?{}:{[t]:e}}function Te(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(el):[];return {id:n,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Ee(e.max_players)??0,memberCount:Ee(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...we("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...we("roomArgs",Ti(e.room_args)),...we("roomArgsTemplate",Ci(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",...we("region",Y(e.region)),...we("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,...we("matchId",Y(e.match_id)),version:Ee(e.version)??0,...we("templateId",Y(e.template_id)),roomType:Y(e.game_room_type)??"Standard",...we("transports",yn(e.transports)??void 0),createdAt:Ee(e.created_at)??0,updatedAt:Ee(e.updated_at)??0,...we("startedAt",Ee(e.started_at))}}function el(t){let e=t??{};return {...ve(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Ee(e.joined_at)??0,...we("groupId",Y(e.group_id)),...we("platform",Y(e.platform))}}function er(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:Ee(e.max_players)??0,memberCount:Ee(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:Ee(e.created_at)??0}}function Y(t){return typeof t=="string"&&t.length>0?t:void 0}function Ee(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function we(t,e){return e===void 0?{}:{[t]:e}}var Wn=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(er),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(n=>({rooms:(n.game_rooms??[]).map(er)}))}create(e,n,r){return bp(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},...nr(n)},e.signal).then(Te)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Te)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...nr(r)},n.signal).then(Te)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...nr(r)},n.signal).then(Te)}quickJoin(e,n,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...nr(n)},e.signal).then(Te)}leave(e,n,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}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(Te)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Te)}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(Te)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function nr(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function bp(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 Kn=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===i&&n(i);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function _p(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var vp=1e3,wp=3e3,Sp=6e4,Rp=2,nl=new Set(["game_room_closed","game_room_gone"]),kp=12e4,xp=5e3,Ap=new Set(["invalid_cluster_target","capacity_unavailable"]),Pp=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Mi(t){return new Ii(t)}var Ii=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Wn({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Kn;api;room=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");let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await n;return this.api.create(r,this.version("create"),o[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,o);if(s[0]===void 0||s[0]===o[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,n={}){this.assertNotInRoom("join");let r=await this.attachParty(n),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode");let r=await this.attachParty(n),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin");let n=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),o=await this.run("quickJoin",async()=>{let a=await n;return i(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||Tp(l,a))throw s;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let i of n)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(i){if(i instanceof G&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let a=await this.askWhyEnded(o,e);this.endMatch(o,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>li({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(a){return a instanceof G&&a.reason==="not_found"?i??null:(this.reportError("reconcile",a),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=pn(n.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(i),i}async kick(e,n){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(i),i}async transferHost(e,n){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(i),i}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new _("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let i=me(n.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>ai({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>s(o,[a]).catch(async m=>{if(i!==void 0||!rl(m))throw m;let c=await this.nextCluster([a],true);if(c===void 0)throw m;return s(c,[a,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new _("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(i)}chase(e,n,r){return si({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 _("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!nl.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new _("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let i={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!He()){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<vp){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(_p(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!He()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>li({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(o){this.reportError("reconcile",o);}if(this.reconnecting(e)){if(i?.status==="ended"){this.endMatch(i.matchId,i.reason,!nl.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await n.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let n=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):n&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new _("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 _("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 _("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 currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,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.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Ap.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(i=>i.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.seatPollMs>0&&He())){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(),!!He())){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}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of tr)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.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 tr)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??xp}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new _("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let n=this.options.clientVersion,r=Jt(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new _("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return Vs({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return qn(await this.options.resolveClusterTargets());let e=me(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !rl(e)||n.length===0?[]:qn(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=a=>a.find(s=>!e.includes(s)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!n?o:r(qn(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof G)||e.reason!=="conflict"||!Pp.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(n.signal);}catch{throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(n,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new _("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}requireRoom(e){if(this.room===null)throw new _("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,n){let r=n instanceof G?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof _?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.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(s=>[s.playerId,s])),i=new Map(e.members.map(s=>[s.playerId,s])),o=this.playerId();for(let s of i.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!i.has(s)){if(s===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of i){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=Ep(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??kp;return new Promise((i,o)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>i(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>o(new _("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>o(new _("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>o(new _("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??wp}pushedInterval(){return this.options.pushedPollIntervalMs??Sp}pushed(){return this.options.clock.now()-this.lastPushAt<Rp*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=>{n?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function He(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var tr=["visibilitychange","focus","pageshow","online"];function Ep(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||tl(t)!==tl(e)}function tl(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function rl(t){return t instanceof G&&t.code==="invalid_cluster_target"}function Tp(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Cp=["p2p","dedicated","unknown"],Oi=["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 hn=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let i=Ip(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},n);}report(e){this.post(e).catch(()=>{});}};function Ip(t,e,n){let r=Math.floor(n/1e3);return t.filter(i=>Oi.includes(i.type)).slice(0,100).map(i=>{let o=Mp(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Mp(t){if(t!==void 0)return Cp.includes(t)?t:"unknown"}var Jn=class{constructor(e){this.options=e;this.reporter=new hn({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:rr(i.credential)??"",hostFingerprint:rr(i.host_fingerprint)??"",hostEpoch:ir(i.host_epoch)??0,expiresAt:(ir(i.expires_at)??0)*1e3}}async turnLease(e,n,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&o.push({urls:m,username:rr(d.username)??"",credential:rr(d.credential)??""});}let a=ir(i.expires_at),s=ir(i.ttl_seconds);return {iceServers:o,expiresAt:a!==void 0?a*1e3:Date.now()+(s??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 rr(t){return typeof t=="string"&&t.length>0?t:void 0}function ir(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var Op=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),L=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="P2pError",this.retryable=Op.has(n);}reason;retryable};var il=10240,ol=2048,Lp=new TextEncoder;function al(t){return Lp.encode(t).length}function De(t,e){let n=i=>{throw new _("invalid_sdp",`the ${e} ${i}`)},r=al(t);r>=il&&n(`is ${r} bytes, over the ${il} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let i of t.split(/\r\n|\n/)){let o=al(i);o>ol&&n(`has a ${o}-byte line, over the ${ol} limit`);}}function or(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 ar=class{listeners=new Map;on(e,n){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(n),()=>this.off(e,n)}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}clear(){this.listeners.clear();}};var Gp=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function bn(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=sr(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function sr(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 Gp.test(r)?r:null}function zn(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 Li=5e3,Dp=12e4+Li,$p=1024,Fp=6e4,qp=1e4,sl=64*1024,ll=5;function Gi(t){let e=new Map,n=-1/0,r=null,i=(()=>{let s;try{s=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 s.username!==""||s.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:s.href,shown:`${s.protocol}//${s.host}`}})(),o=()=>{let s=t.subtle??globalThis.crypto?.subtle;if(!s)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 s},a=async()=>{if(!i.ok)throw new L("keys_unavailable",i.reason);let s=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await s(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(qp)});}catch{throw new L("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new L("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>sl)throw new L("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${sl} 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 ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>ll)throw new L("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${ll} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!i.ok)throw new L("keys_unavailable",i.reason);if(r)return await r,e.get(s)??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<Fp?null:(n=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var Yn=class{seen=new Map;admit(e,n){for(let[r,i]of this.seen)i<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=$p){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+Dp),true}};function cl(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}function dl(t){try{let e=new TextDecoder().decode(cl(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Di(t,e,n,r,i){let o=$=>{throw new L("peer_unauthenticated",`the peer's join credential is not usable: ${$}`)},a=t.split(".");a.length!==3&&o("it is not a three-part JWT");let[s,l,d]=a,m=dl(s);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let p=await n.key(c);p===null&&o("it was signed by a key this build cannot resolve");let g=i.subtle??globalThis.crypto?.subtle;g||o("this environment has no WebCrypto");let y=new TextEncoder().encode(`${s}.${l}`),w;try{w=cl(d);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,w,y)||o("its signature does not verify");let A=dl(l);A===null&&o("its payload does not decode");let C=A,b=$=>typeof C[$]=="string"?C[$]:"",R=$=>typeof C[$]=="number"&&Number.isFinite(C[$])?C[$]:NaN;b("iss")!==i.issuer&&o("it was issued by someone else"),b("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),b("match_id")!==e.matchId&&o("it is for another match"),b("game_id")!==e.gameId&&o("it is for another game");let E=R("exp")*1e3,T=R("nbf")*1e3;(!Number.isFinite(E)||e.now>E+Li)&&o("it has expired"),Number.isFinite(T)&&e.now<T-Li&&o("it is not valid yet");let V=b("role");V!=="host"&&V!=="client"&&o("it names no usable role");let B=R("host_epoch");B!==e.hostEpoch&&o("it names a different host epoch");let K=sr(b("fingerprint"));K===null&&o("its fingerprint claim is malformed"),zn(K,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let x=sr(b("host_fingerprint"));x===null&&o("its host fingerprint claim is malformed"),zn(x,e.hostFingerprint)||o("it was issued against a different host certificate");let I=b("jti");I.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(I,e.now)||o("it has already been used");let O=b("sub");return O.length===0&&o("it names no player"),{playerId:O.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:B,role:V,fingerprint:K,hostFingerprint:x,jti:I,expiresAt:E}}function $i(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 Fi(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 qi(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function ji(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 ul(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 ml(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Xn=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 Ni={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Le=["reliable","ordered","unreliable"];function Ui(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 Qn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var gl=1,Vp=3e4,yl=2e3,Hp=5e3,fl=6e4,Wp=8,Vi=class{constructor(e=Wp){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;}},Kp=new Vi,Jp=8,zp=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),et=class{constructor(e){this.options=e;this.keys=e.keys??Gi({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new ar;links=new Map;replays=new Yn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=gl+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??Vp;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),i=me(this.options.clusterTargetId);if(i!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Bi(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=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),a=()=>this.fail(new L("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",a),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=ae(e.playerId),r=ae(e.hostPlayerId),i=lr(e.hostEpoch);if(!(n===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Xn(n,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,gl),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new L("invalid_sdp","the browser produced an offer with no SDP");De(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:bn(r);if(i===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 o=this.options.credentialPacing??Kp,a=()=>this.closed||e!==this.credentialGeneration,s=Hp;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,c;if(m===409)c=yl;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=s,s=Math.min(s*2,fl)),c=Math.min(Math.max(c,yl),fl);}else throw d;if(!await this.waitForCredential(c,a))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=ae(e.fromPlayerId),r=ae(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=Jp){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let i=ae(e.sessionId);if(i!==null&&this.answeredSessions.get(n)===i)return;De(r,"offer"),this.refuseMedia(r,"offer");let o=bn(r);if(o===null)throw new L("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(n,i);let a=this.links.get(n);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(n,this.nextPeerId++);s.remoteFingerprint=o,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new L("invalid_sdp","the browser produced an answer with no SDP");De(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=ae(e.fromPlayerId),r=ae(e.sdp);if(n===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||n!==this.hostPlayerId)return;De(r,"answer"),this.refuseMedia(r,"answer");let o=bn(r);if(o===null)throw new L("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:zn(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=ae(e.fromPlayerId),r=ae(e.candidate);if(n===null||r===null)return;let i=this.links.get(n);if(!i)return;let o=ae(e.sdpMid),a=lr(e.sdpMLineIndex)??lr(e.sdpMLineIndexAlt),s={candidate:r,...o===null?{}:{sdpMid:o},...a===null?{}:{sdpMLineIndex:a}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(s);return}await i.connection.addIceCandidate(s);}onPeerLeft(e){let n=ae(e.playerId);if(n===null)return;let r=ae(e.reason)??"left";if(n===this.localPlayerId){this.fail(new L("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(n);i&&this.dropLink(i,r,true);}async onMigration(e){let n=ae(e.hostPlayerId),r=lr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:n,hostEpoch:r,...ae(e.reason)===null?{}:{reason:ae(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(i.kind==="refused"){this.report_(new L("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new 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=ae(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=ae(e.code)??"unknown",r=ae(e.message)??"the platform refused a signaling message";this.report_(new L("signaling_failed",`${n}: ${r}`));}openLink(e,n){let i=(this.options.peerConnectionFactory??Ui)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of Le){let g=i.createDataChannel(p,Ni[p]);g.binaryType="arraybuffer",o[p]=g;}let a={playerId:e,assignedPeerId:n,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",s),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",m),a.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),i.removeEventListener("icecandidate",s),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}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($i({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=ji(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(ml(r.reason),ul(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=bn(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await Di(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof L&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Bi(a)),s&&this.fail(a);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Fi({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(qi(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let i of Le)hl(e.channels[i]);hl(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",Bi(e),{cause:e}));}count(e){this.counted||!zp.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(or(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 ae(t){return typeof t=="string"&&t.length>0?t:null}function lr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Bi(t){return t instanceof Error?t.message:String(t)}function hl(t){try{t.close();}catch{}}var Yp=100,Xp=50,nt=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,n){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:n});}answer(e,n,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:n,assignedPeerId:r});}candidate(e,n,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Yp)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new 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:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??Xp));}};function H(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function $e(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function _n(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function bl(t){return typeof t=="boolean"?t:void 0}var he=H(64),tt=$e(0,2147483647);function Hi(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=he(n);typeof r=="string"&&e.push(r);}return e}function J(t,e,n){return {to:t,from:e,read:n,required:true}}function W(t,e,n){return {to:t,from:e,read:n,required:false}}var eg=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=_n("disconnected","failed","closed")(e.iceState),r=$e(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:[J("sdp","sdp",H(10240)),J("signaling_intent","intent",_n("initial","ice_restart","full_reconnect")),W("sdp_hash","sdpHash",H(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[J("peer_id","peerId",he),J("sdp","sdp",H(10240)),J("assigned_peer_id","assignedPeerId",$e(0,4294967295)),W("sdp_hash","sdpHash",H(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[J("peer_id","peerId",he),J("candidate","candidate",H(512)),W("sdp_mid","sdpMid",H(64)),W("sdp_mline_index","sdpMLineIndex",$e(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[J("host_epoch","hostEpoch",tt)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[J("host_epoch","hostEpoch",tt),W("evidence","evidence",eg)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[J("playerId","player_id",he),J("hostPlayerId","host_player_id",he),J("hostEpoch","host_epoch",tt),W("members","members",Hi)],offer:[J("fromPlayerId","from_player_id",he),J("sdp","sdp",H(10240)),W("sessionId","signaling_session_id",H(128)),W("sdpHash","sdp_hash",H(128)),W("iceUfrag","ice_ufrag",H(64)),W("intent","signaling_intent",_n("initial","ice_restart","full_reconnect"))],answer:[J("fromPlayerId","from_player_id",he),J("sdp","sdp",H(10240)),W("sessionId","signaling_session_id",H(128)),W("sdpHash","sdp_hash",H(128)),W("iceUfrag","ice_ufrag",H(64)),W("assignedPeerId","assigned_peer_id",$e(0,4294967295))],ice:[J("fromPlayerId","from_player_id",he),J("candidate","candidate",H(512)),W("sdpMid","sdp_mid",H(64)),W("sdpMLineIndex","sdp_m_line_index",$e(0,255)),W("sdpMLineIndexAlt","sdp_mline_index",$e(0,255))],peerJoined:[J("playerId","player_id",he)],peerLeft:[J("playerId","player_id",he),W("reason","reason",H(64))],migration:[J("hostPlayerId","new_host_player_id",he),J("hostEpoch","host_epoch",tt),W("reason","reason",H(64)),W("kickedPlayerIds","kicked_player_ids",Hi),W("migrationComplete","migration_complete",bl)],matchEnded:[W("reason","reason",H(64))],error:[W("code","code",H(64)),W("message","message",H(256))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var Ke="webrtc_p2p";function vl(t){let e=new Jn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,i,o){n.get(r)?.handleSignal(i,o);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new 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 i=me(r.clusterTargetId),o=i??me(await t.resolveClusterTarget?.());t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let a=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==Ke)throw new L("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${Ke}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new nt({bridge:t.bridge,matchId:a.matchId,clock:t.clock}),l=new et({api:e,clock:t.clock,matchId:a.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:s,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Qn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(a.matchId,l),l.on("matchEnded",()=>n.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(a.matchId),l.close(),d}return l}}}function wl(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,i=t.document??globalThis.document,o=[];if(typeof r.addEventListener=="function"){let s=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",s),o.push(()=>r.removeEventListener?.("pagehide",s));let l=()=>e.setHidden(!He());for(let d of tr)r.addEventListener(d,l),o.push(()=>r.removeEventListener?.(d,l));typeof i?.addEventListener=="function"&&(i.addEventListener("resume",l),o.push(()=>i.removeEventListener?.("resume",l))),e.setHidden(!He());}let a=new Map;return o.push(n.on("matchReady",s=>{let l=s.protocol===Ke?"p2p":"dedicated";a.set(s.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(n.on("matchEnded",s=>{let l=a.get(s.matchId);l!==void 0&&(a.delete(s.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let s of o.splice(0))try{s();}catch{}a.clear();}}var Sl=["pointerdown","keydown"];function Rl(t,e=globalThis){let n=false,r=false,i=null,o=()=>{if(i!==null){try{e.cancelAnimationFrame?.(i);}catch{}i=null;}},a=()=>{if(!r){r=true,o();for(let g of Sl)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},s=()=>{if(!(n||r)){n=true,a();try{t();}catch{}}};function l(g){g?.isTrusted===true&&s();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(w=>w.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},c=()=>{if(i=null,!(n||r)){if(d()){s();return}m()&&(i=e.requestAnimationFrame?.(c)??null);}};function p(){i===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let g of Sl)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(i=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:a}}async function dr(t,e,n,r){let i=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),i}function Wi(t,e){let n=false;return async r=>{let i=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),i}}function Ki(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(i,o){return r.has(i)?false:(r.add(i),n.push({name:i,at:o??e()}),true)},timeline(){let i=[...n].sort((o,a)=>o.at-a.at);return i.map((o,a)=>{let s=i[a-1],l=s===void 0?"":` (+${Math.round(o.at-s.at)}ms)`;return `${o.name}@${Math.round(o.at)}ms${l}`}).join(" \u2192 ")}}}var ng="GemWebSdkHandshake";var tg=()=>Date.now();function kl(t,e,n={}){let r=t[ng];if(r===void 0)return null;let i=n.ttlMs??9500,o=n.now??tg,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,c=o()-i;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var Ji=false;async function El(t,e,n,r){if(Ji){e.close(),n("busy",true);return}Ji=true;let i=null;try{let o=await ig(t,r);if(typeof o=="string"){e.close(),n(o,rg(o));return}i=o;let s=await(r.encodeRef??(l=>lg(l,r)))(i);if(i.close(),i=null,s===null){e.close(),n("failed",!0);return}if(s.size>sg){e.close(),n("too_large",!1);return}e.postMessage(s);}catch(o){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",o);}finally{Ji=false,i?.close();}}function rg(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 ig(t,e){if(e.handler){let o=await e.handler(t);return o===null?"declined":xl(o,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=ag(n);if(!r)return "no_source";let i=og(r);if(i!==null)return i;try{return xl(await createImageBitmap(r),t)}catch(o){if(o instanceof DOMException&&o.name==="SecurityError")return "tainted";throw o}}function og(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 ag(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let i=r.width*r.height;i<=0||r.clientWidth<=0||r.clientHeight<=0||i>n&&(e=r,n=i);}return e}async function xl(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let i=Math.min(n/t.width,r/t.height),o=Math.max(1,Math.floor(t.width*i)),a=Math.max(1,Math.floor(t.height*i));try{let s=await createImageBitmap(t,{resizeWidth:o,resizeHeight:a,resizeQuality:"high"});return t.close(),s}catch{return t.close(),"too_large"}}var sg=8*1024*1024,Al="image/webp",Pl=.92;async function lg(t,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(t.width,t.height),a=o.getContext("2d");if(a){a.drawImage(t,0,0);let s=await o.convertToBlob({type:Al,quality:Pl});if(s&&s.size>0)return s}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let i=r.getContext("2d");return !i||(i.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(a=>o(a),Al,Pl);})}async function Tl(t,e){if(!e)return;let n;try{n=await dg(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 dg(t){return new Promise((e,n)=>{let r=false,i=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>t())().then(o=>{r||(r=true,clearTimeout(i),e(o??null));},o=>{r||(r=true,clearTimeout(i),n(o instanceof Error?o:new Error(String(o))));});})}var Cl=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Il(t=globalThis){let n=t[Cl];if(n!==void 0)return n;let r=false,i=()=>r,o=[],a=cg(t,i);a!==null&&o.push(a);let s=ug(t,i);s!==null&&o.push(s);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of o)c();}}};return Object.defineProperty(t,Cl,{value:l,configurable:true}),l}function cg(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let i=t.OfflineAudioContext,o=n.connect,a=n.disconnect,s=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(i!==void 0&&c instanceof i)return null;let p=s.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,o.call(p,m),s.set(c,p)),p};return n.connect=function(...c){let[p,...g]=c;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return o.call(this,y,...g),p}return o.apply(this,c)},n.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let y=s.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...g)}catch{}}return a.apply(this,c)},()=>{for(let[m,c]of s){if(m.state==="closed"){s.delete(m);continue}try{l(c);}catch{}}}}function ug(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,i=Object.getOwnPropertyDescriptor(r,"muted"),o=i?.get,a=i?.set;if(o===void 0||a===void 0)return null;let s=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!o.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),a.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!o.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return s.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{a.call(g,(l.get(g)??!1)||e());}catch{}}}}var mg=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",pg=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',gg=`${mg}${pg}`,zi=new WeakSet;function Ml(t=globalThis.document){if(t==null||zi.has(t))return null;try{let e=t.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(t.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(gg),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],zi.add(t),"sheet"}let n=t.documentElement?.style;return n===void 0||typeof n.setProperty!="function"?null:(n.setProperty("-webkit-user-select","none"),n.setProperty("user-select","none"),n.setProperty("-webkit-tap-highlight-color","transparent"),zi.add(t),"inline")}catch{return null}}function Ol(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=false,i=false,o=false,a=null,s=null,l=null,d=[],m=()=>r&&!i&&!o,c=()=>{s=null,l=null,d=[];},p=w=>{if(a=null,!m()){c();return}if(l!==null&&d.push(w-l),l=w,s===null)s=w;else {let S=w-s;S>=e&&d.length>0&&(t.report(yg(d,S)),s=w,d=[]);}g();},g=()=>{let w=n.requestAnimationFrame;typeof w=="function"&&(a=w.call(n,p));},y=()=>{if(m()){a===null&&(c(),g());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),c();};return {setRequested(w){r=w,y();},setPaused(w){i=w,y();},get running(){return a!==null},dispose(){o=true,y();}}}function yg(t,e){let n=[...t].sort((i,o)=>i-o),r=Math.max(1,Math.ceil(n.length*.95));return {fps:t.length*1e3/e,frameTimeP95Ms:n[r-1]}}var cr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Gl(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Dl(t,e){t!==null&&(t.style.setProperty(cr.top,`${e.top}px`),t.style.setProperty(cr.right,`${e.right}px`),t.style.setProperty(cr.bottom,`${e.bottom}px`),t.style.setProperty(cr.left,`${e.left}px`));}var Ll=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height"}});function $l(){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 fg(t,e){let n={tl:{width:0,height:0},tr:{width:0,height:0},bl:{width:0,height:0},br:{width:0,height:0}};for(let r of t){let i=e?r.x+r.width/2<=e.width/2:r.x===0,o=e?r.y+r.height/2<=e.height/2:r.y===0,a=i?r.x+r.width:e?e.width-r.x:r.width,s=o?r.y+r.height:e?e.height-r.y:r.height,l=n[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(a)),l.height=Math.max(l.height,Math.ceil(s));}return n}function Fl(t,e,n){if(t===null)return;let r=fg(e,n);for(let i of ["tl","tr","bl","br"])t.style.setProperty(Ll[i].width,`${r[i].width}px`),t.style.setProperty(Ll[i].height,`${r[i].height}px`);}var hg=3e4,ur=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function ql(t){let e=t.clock??ye,n=t.timeoutMs??hg,r=new Map,i=new Map,o=0,a=s=>{let l=r.get(s);return l?(r.delete(s),i.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(s){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(s);if(l)return l;let d=new Promise((m,c)=>{let p=`ls${++o}`,g=e.setTimeout(()=>{r.delete(p),i.delete(s),c(new ur("timeout",true,`the embedder did not answer a local-server request for room ${s} within ${String(n)}ms`));},n);r.set(p,{room:s,resolve:m,reject:c,timer:g}),t.bridge.requestLocalServer(p,s)||(a(p),m());});return i.set(s,d),d.catch(()=>{}),d},accept(s){a(s.requestId)?.resolve();},refuse(s){let l=a(s.requestId);l&&l.reject(new ur(s.reason,s.retryable,s.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var rt={url:"https://downloads.indiegems.games/sdk/v9.1.1/gem-web-sdk.devtools.min.js",integrity:"sha384-EoxrwhtXXol3Rn0UPe8TQL78O6ly9g1ox7fLSPOqhwbOVKjNkFhNVv4aL1DzSmR3"};var wn=null;function bg(){return wn!==null||(wn=new Promise((t,e)=>{let n=document.createElement("script");n.src=rt.url,n.integrity=rt.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){wn=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${rt.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{wn=null,e(new Error(`gem devtools: could not load ${rt.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);})),wn}function jl(t,e){let n=null,r=0;async function i(o){if(n!==null)return true;let a=++r;if(!e())return false;let s=await bg();return !e()||a!==r?false:(n!==null||(n=s.mount(t(),{openedBy:o,text:dn,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>i("game"),openFrom:i}}var _g=1e4,Nl={reason:"unavailable",retryable:false};function Ul(t){let e=new Map,n=null,r=null,i=0,o=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??_g);},a=(d,m)=>{let c=s(d);c&&m(c);},s=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new on({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,c)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){c(Nl);return}let g=`t${++i}`,y={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,y),o(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)){a(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){a(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),o(m,c),t.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])a(m,c=>c.reject(Nl));},get identity(){return n},get gameVersion(){return r}}}function vg(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var wg=new Set(Pr);function Sg(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))wg.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function mr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return Oo(async(n,r)=>{let i;try{i=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new ie("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let o;try{o=new URL(i.href.replace(/\/+$/,"")+n.path);}catch{throw new ie(`${JSON.stringify(typeof n.path=="string"?vg(n.path):"(a non-string path)")} does not form a valid URL against ${i.protocol}//${i.host}. This is a malformed request, not a server failure.`)}if(o.protocol!==i.protocol||o.host!==i.host)throw new ie(`${JSON.stringify(o.pathname)} resolves to ${o.protocol}//${o.host}, not ${i.protocol}//${i.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(o.username!==""||o.password!==""){let g=i.username!==""||i.password!=="",y=o.username!==i.username||o.password!==i.password,w=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new ie(`the ${w} puts credentials in the URL, which cannot be fetched (${n.method} ${o.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(t.defaultQuery??{}))o.searchParams.has(g)||o.searchParams.set(g,y);let a=n.bytes,s=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(a=JSON.stringify(n.body),s="application/json");}catch(g){throw new ie(`the body of ${n.method} ${JSON.stringify(o.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(o.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...s===void 0?{}:{"content-type":s},...Sg(n.headers)},body:a,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),c=Rg(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},t)}function Rg(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 kg=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Xi="embedder_relay_unavailable",xg="embedder_no_relay",Ag=new Set([Xi]),Qi=new Set([xg]),it=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Yi(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new _("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){n.refuse(new _("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(Pg(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new _("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 _("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new _("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function Pg(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new _(Eg(t),r,{platformCode:t})}function Eg(t){return t===void 0||Ag.has(t)?"signaling_failed":Qi.has(t)?"offer_refused":kg.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Yi=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new _("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return n?.aborted?Promise.reject(new _("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let a=()=>{s(),o(new _("aborted","the caller aborted the signaling exchange"));},s=()=>{n?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),i(d);},refuse:d=>{s(),o(d);}};this.teardown=s,n?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof _?d:new _("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var Bl="match_ended:",Vl="server_shutdown:",Hl="kicked:",Tg=123;function Cg(t){if(typeof t!="string"||t.length===0||t.length>Tg)return {kind:"other"};if(t.startsWith(Bl)){let e=pn(t.slice(Bl.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Vl)?{kind:"server_shutdown",cause:t.slice(Vl.length)}:t.startsWith(Hl)?{kind:"kicked",detail:t.slice(Hl.length)}:{kind:"other"}}function Zi(t,e,n){let r=Cg(n),i=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function eo(){return {exchange(){return Promise.reject(new _("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var Ig=3e3,Mg=1e4,Og=15e3;async function pr(t){let e=t.peerConnection;try{Kl(t,"before the handshake started"),no(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let a of t.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});t.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await Dg(e,t),no(t);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new _("invalid_sdp","the offer carried no SDP");De(i,"offer"),Wl(i,"offer");let o=await Gg(t,i);if(no(t),typeof o?.sdp!="string")throw new _("invalid_sdp","the signaling channel answered without an SDP");return De(o.sdp,"answer"),Wl(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await $g(n,t),Kl(t,"before the channel opened"),n}catch(n){throw e.close(),Lg(n)}}function Lg(t){return t instanceof _?t:Yl(t)?Je():new _("connection_failed",Xl(t),{cause:t})}function Wl(t,e){if(or(t))throw new _("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function Gg(t,e){let n=t.exchangeTimeoutMs??Mg,r=zl(t,n),i=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(o=>{throw o instanceof _?o:Yl(o)?Je():new _("signaling_failed",Xl(o),{cause:o})});return Fg(i,t,r,()=>r.exhausted?to("while the offer was in flight"):new _("timeout",`no answer arrived within ${n}ms`))}function Dg(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let i=()=>{n.clearTimeout(a),t.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{t.iceGatheringState==="complete"&&i();},a=n.setTimeout(i,e.gatherTimeoutMs??Ig);t.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function $g(t,e){if(e.signal?.aborted)return Promise.reject(Je());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new _("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??Og,i=zl(e,r);return new Promise((o,a)=>{let s=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),o();},d=g=>{s(),a(new _("connection_failed","the data channel failed before it opened",Jl(g)===void 0?void 0:{cause:Jl(g)}));},m=()=>{s(),a(Je());},c=()=>{s(),a(i.exhausted?to("while the channel was still opening"):new _("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(c,i.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function zl(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 Fg(t,e,n,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(Je()):new Promise((a,s)=>{let l=c=>{i.clearTimeout(m),o?.removeEventListener("abort",d),c();},d=()=>l(()=>s(Je())),m=i.setTimeout(()=>l(()=>s(r())),n.ms);o?.addEventListener("abort",d),t.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Kl(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw to(`already ${e}`)}function to(t){return new _("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function no(t){if(t.signal?.aborted)throw Je()}function Je(){return new _("aborted","the caller aborted the connection attempt")}function Yl(t){return t?.name==="AbortError"}function Jl(t){return t?.error}function Xl(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:[J("sdp","sdp",H(10240)),W("sessionId","session_id",H(64))],error:[W("code","code",H(64)),W("message","message",H(256))],matchEnded:[W("reason","reason",H(64))]}));function od(t){let{client:e,clock:n,rooms:r}=t,i=t.signaling??eo,o=t.log??(b=>console.warn(b)),a=new hn({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(b,R)=>{let E=s.get(b)??new Set;E.add(R),s.set(b,E);},d=(b,R)=>{let E=s.get(b);E!==void 0&&(E.delete(R),E.size===0&&s.delete(b));},m=async b=>{if(r.isHost&&!io(r)&&r.currentRoom?.matchId===void 0){let R=me(b.clusterTargetId);await r.startMatch({...R===void 0?{}:{clusterTargetId:R},...b.retry===void 0?{}:{retry:b.retry},...b.signal===void 0?{}:{signal:b.signal}});}return rd(r.matchConnectionState==="suspended"?await r.reconnectToMatch(ro(b)):await r.awaitMatch(ro(b)))},c=async b=>rd(await r.pollMatchStatus(ro(b))),p=async(b,R)=>{let E=false;try{let T=await m(b),V=r.currentRoom?.transports;if(V!==void 0&&!V.includes("webrtc"))throw new _("misconfigured",`the room template offers (${V.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let B=b.peerConnection??id();E=!0;let K=await pr({peerConnection:B,signaling:R,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...gr(b,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),x=null;if(b.presentCredential!==!1)try{x=await jn({channel:K,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...gr(b,"onMessage","signal"),...b.welcomeTimeoutMs===void 0?{}:{ceilingMs:b.welcomeTimeoutMs}});}catch(I){throw Se(K),Se(B),I}return Kg(r,T,K,B,R,b.reportDisconnect!==!1,b.reportConnected!==!1,x,{remember:l,forget:d},b.onMatchEnded)}catch(T){throw E&&td(a,T),Se(R),T}},g=async(b,R,E,T,V,B)=>{if(b==="webtransport"){let N=T?.webtransport;if(N===void 0)throw new _("misconfigured","webtransport is not advertised");let q={credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n};if(typeof N.named_url=="string"&&N.named_url!==""){let Z=Math.max(Math.floor(B/2),1e3);try{return await Vn({url:N.named_url,timeoutMs:Z,log:o,...q})}catch(pe){if(Zt()!==null)throw pe;return o(`[gem] webtransport named dial failed (${Xt(pe)}); retrying the pinned dial`),Vn({url:N.url,certHashBase64:N.cert_sha256_b64,timeoutMs:Z,log:o,...q})}}return Vn({url:N.url,certHashBase64:N.cert_sha256_b64,timeoutMs:B,...q})}if(b==="websocket"){let N=T?.websocket;if(N===void 0)throw new _("misconfigured","websocket is not advertised");return ki({url:N.url,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n,timeoutMs:B})}let K=R.peerConnection??id(),x,I=await pr({peerConnection:K,signaling:V,clock:n,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,extraChannels:[{label:Un,ordered:false,maxRetransmits:0}],onExtraChannel:(N,q)=>{N===Un&&(x=q);},...gr(R,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...R.exchangeTimeoutMs===void 0&&R.redial===true?{exchangeTimeoutMs:Ng}:{}}),O;try{O=await jn({channel:I,clock:n,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,wire:Yt,heartbeat:!0,...gr(R,"signal"),...R.welcomeTimeoutMs===void 0?{}:{ceilingMs:R.welcomeTimeoutMs}});}catch(N){throw Se(I),Se(K),N}let $=O.welcome.heartbeatIntervalMs;return {link:Ai(I,K,x,$===void 0?void 0:{clock:n,intervalMs:$}),welcome:O.welcome,channel:I,peerConnection:K}},y=(b,R,E,T,V)=>{let B=false,K;T.link.onClose($=>{!B&&b.reportDisconnect!==false&&Zi(r,R.matchId,$),K?.($);}),b.reportDisconnect!==false&&b.reportConnected!==false&&r.notifyMatchConnected(R.matchId);let x={transport:T.link.transport,send:($,N)=>T.link.send($,N),onMessage:$=>T.link.onMessage($),onClose:$=>{K=$;},close:()=>T.link.close()},I=()=>{B||(B=true,Se(T.link),Se(V));},O=$=>{if(!B){try{b.onMatchEnded?.($);}catch{}I();}};return l(R.matchId,O),{matchId:R.matchId,transport:E,link:x,joinCredential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(R.matchId,O),I();}}},w=async(b,R)=>{let E=r.currentRoom?.id,T=r.gameId,V=()=>({advert:Bn(r.currentRoom?.settings,b),template:r.currentRoom?.transports??null});if(E===void 0||T===null)return V();try{let B=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(E)}`,R);return {advert:Bn(B.settings,b),template:yn(B.transports)??r.currentRoom?.transports??null}}catch{return V()}},S=(b,R)=>{let E=b??Ql;return R.length===0?E:E.filter(T=>R.includes(T))},A=async(b,R,E)=>{try{let T=await m(b),{advert:V,template:B}=await w(T.matchId,b.signal),K=S(B,R),x=K.filter(X=>Vg(X,V)),I=Zt();if(I!==null&&K.includes("webtransport")&&V?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${I} (learned on an earlier dial in this page)`),x.length===0){let X=B===null?`the default order (${Ql.join(", ")})`:`the room template's transports (${B.join(", ")||"none"})`;throw new _("misconfigured",`none of ${X}`+(R.length>0?`, narrowed to (${R.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let O=b.transportAttemptTimeoutMs??jg,$=()=>b.deadlineAt===void 0?1/0:b.deadlineAt-n.now(),N=X=>t.signalingReady===void 0||X<=0?Promise.resolve(!0):t.signalingReady(X),q=[],Z=[];for(let X of x){if($()<ed){o(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}Z.length>0&&T.credentialExpiresAt-n.now()<nd&&(T=await c(b)),Z.push(X);let Ie=!1,ce=!1,Re={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&b.redial===!0){let te=Math.min(Zl,$());await N(te)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let Me=Math.max(Math.min(O,$()),ed);try{return y(b,T,X,await g(X,b,T,V,E,Me),E)}catch(te){let z=te instanceof _?te:new _("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(X==="webrtc"&&td(a,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Ie){Ie=!0,T=await c(b);continue}if(X==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===Xi&&!ce){ce=!0;let le=Math.min(Zl,$());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(le)}ms for the socket before offering again`),await N(le))continue}if(z.reason==="join_rate_limited"){let le=Bg(Re,Math.random,$());if(le!==null){if(Re.attempts+=1,Re.waitedMs+=le,o(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(le)}ms before presenting again (retry ${Re.attempts} of ${sd.maxAttempts})`),await Kt(n,le,b.signal),b.signal?.aborted)throw new _("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<nd&&(T=await c(b));continue}}if(Ug.has(z.reason)||z.reason==="credential_expired"||X==="webrtc"&&ad(z)){o(`[gem] ${X} rung failed (${z.reason}): ${Xt(z.cause??z)} \u2014 `+(Z.length<x.length?`falling through to ${x[Z.length]}`:"no rungs left")),q.push(z);break}throw o(`[gem] ${X} rung refused the session (${z.reason}): ${z.message}`),z}}}let pe=q[q.length-1];throw pe===void 0?new _("timeout",`the reconnect budget ran out before any transport (${x.join(", ")}) could be tried`):new _(pe.reason,`every transport tried (${Z.join(", ")}) failed; the last said: ${pe.message}`,{cause:q,platformCode:pe.platformCode})}catch(T){throw Se(E),T}};return {listClusterTargets:async(b={})=>di({client:e,...b}),handleMatchEnded(b,R){let E=s.get(b);if(E!==void 0){s.delete(b);for(let T of E)T(R);}},connect:(async(b={})=>{let R=b.signaling??i();return b.transports===void 0?p(b,R):A(b,b.transports,R)})}}var Ql=["webtransport","webrtc","websocket"],jg=1e4,Ng=5e3,Zl=3e3,ed=1e3,nd=1e4,Ug=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function ad(t){return t.platformCode!==void 0&&Qi.has(t.platformCode)}var sd={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Bg(t,e=Math.random,n=1/0){let r=sd;if(t.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-t.waitedMs,n);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**t.attempts;return Math.min(o+e()*r.jitterMs,i)}function Vg(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Qt():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Hg(e.websocket.url)}function Hg(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return wt(e)}function ro(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var Wg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function td(t,e){e instanceof _&&(!Wg.has(e.reason)&&!ad(e)||t.report([{type:"connection_failures_total",value:1}]));}function Kg(t,e,n,r,i,o,a,s,l,d){let m=false,c=()=>{m||Zi(t,e.matchId,void 0);};o&&(n.addEventListener("close",c),a&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",c),s?.detach(),Se(n),Se(r),Se(i));},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:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function io(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function rd(t){if(t.status==="failed")throw new _("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new _("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Wt)throw new _("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Wt}' 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 _("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 id(){let t=globalThis.RTCPeerConnection;if(!t)throw new _("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new t({iceServers:[]})}function Se(t){try{t.close();}catch{}}function gr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var Jg=1e4;function ld(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=a=>({token:a.token,expiresAt:a.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new on({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((a,s)=>{let l=e.clock.setTimeout(()=>{r=null,s({reason:"unavailable",retryable:true});},e.timeoutMs??Jg);r={resolve:d=>{e.clock.clearTimeout(l),a(d);},reject:s,timer:l};})}),o=t.onServerToken(a=>{let s=n(a),l=r;if(l){r=null,l.resolve(s);return}i.accept(s);});return {source:i,dispose(){o(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var ao={};Jd(ao,{acceptTransfer:()=>zg,addEntityProgression:()=>Yg,adminAction:()=>Xg,cancelInventoryTransfer:()=>Qg,claimEntityProgressionRewards:()=>Zg,closeGameRoom:()=>ey,createEntityBatchOrder:()=>ny,createEntityOrder:()=>ty,createSession:()=>ry,deleteEntityGameSetting:()=>iy,deleteEntitySave:()=>oy,deleteSession:()=>ay,deleteShowcaseValue:()=>sy,executeEntityRecipe:()=>ly,finalizeSaveUpload:()=>dy,getChannelAssignment:()=>cy,getDropRates:()=>uy,getEntityCurrency:()=>my,getEntityGameSetting:()=>py,getEntityInventory:()=>gy,getEntityInventoryItem:()=>yy,getEntityLeaderboard:()=>fy,getEntityOrder:()=>hy,getEntityProgression:()=>by,getEntityRecipeAvailability:()=>_y,getEntityRecipeUsage:()=>vy,getEntitySave:()=>wy,getEvent:()=>Sy,getGameRoomV2:()=>Ry,getLeaderboard:()=>ky,getPlayerGameProfile:()=>xy,getPurchaseCatalog:()=>Ay,getResolvedTemplate:()=>Py,getRoomArgs:()=>Ey,getShowcaseValue:()=>Ty,getTransferDetails:()=>Cy,ingestAnalyticsEvents:()=>oo,initiateInventoryTransfer:()=>Iy,invokeFunction:()=>My,kickPlayer:()=>Oy,listChallenges:()=>Ly,listEntityGameSettings:()=>Gy,listEntityOrders:()=>Dy,listEntityProgressions:()=>$y,listEntitySaves:()=>Fy,listEvents:()=>qy,listGameRooms:()=>jy,listResolvedTemplates:()=>Ny,listTransfers:()=>Uy,maxEntityProgression:()=>By,putEntityGameSetting:()=>Vy,putRoomArgs:()=>Hy,putShowcaseValue:()=>Wy,rejectTransfer:()=>Ky,requestSaveUploadUrl:()=>Jy,resetEntityProgression:()=>zy,simulateEntityOrder:()=>Yy,transferHostV2:()=>Xy,updateGameRoomV2:()=>Qy});function h(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 zg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Yg(t,e,n,r,i,o){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/add`;return t.client.post(a,i,o?.signal)}async function Xg(t,e,n,r){let i=`/v1/voice/sessions/${h(e)}/admin`;return t.client.post(i,n,r?.signal)}async function Qg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Zg(t,e,n,r,i,o){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/claim`;return t.client.post(a,i,o?.signal)}async function ey(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.delete(r,n?.signal)}async function ny(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ty(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ry(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function iy(t,e,n,r,i){let o=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(o,i?.signal)}async function oy(t,e,n,r,i){let o=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(o,i?.signal)}async function ay(t,e,n){let r=`/v1/voice/sessions/${h(e)}`;return t.client.delete(r,n?.signal)}async function sy(t,e,n,r){let i=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.delete(i,r?.signal)}async function ly(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function dy(t,e,n,r,i,o){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/finalize`;return t.client.post(a,i,o?.signal)}async function cy(t,e,n){let r=`/v1/games/${h(t.gameId())}/config/channels/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function uy(t,e,n){let r=`/v1/inventory/loot-tables/${h(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function my(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/currencies/${h(r)}`;return t.client.get(o,i?.signal)}async function py(t,e,n,r,i){let o=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function gy(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),a=`/v1/inventory/${h(e)}/${h(n)}`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function yy(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/items/${h(r)}`;return t.client.get(o,i?.signal)}async function fy(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let a=o.toString(),s=`/v1/leaderboards/${h(e)}/${h(n)}/${h(r)}`+(a?`?${a}`:"");return t.client.get(s,i?.signal)}async function hy(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/orders/${h(r)}`;return t.client.get(o,i?.signal)}async function by(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}`;return t.client.get(o,i?.signal)}async function _y(t,e,n,r,i,o){let a=`/v1/inventory/${h(e)}/${h(n)}/catalogs/${h(r)}/recipes/${h(i)}/availability`;return t.client.get(a,o?.signal)}async function vy(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit));let o=i.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function wy(t,e,n,r,i){let o=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Sy(t,e,n){let r=`/v1/events/${h(e)}`;return t.client.get(r,n?.signal)}async function Ry(t,e,n){let r=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function ky(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${h(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function xy(t,e,n){let r=`/v1/profiles/players/${h(e)}`;return t.client.get(r,n?.signal)}async function Ay(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Py(t,e,n){let r=`/v1/game-room-templates/${h(e)}`;return t.client.get(r,n?.signal)}async function Ey(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.get(r,n?.signal)}async function Ty(t,e,n,r){let i=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.get(i,r?.signal)}async function Cy(t,e,n){let r=`/v1/inventory/transfers/${h(e)}`;return t.client.get(r,n?.signal)}async function oo(t,e,n){let r=`/v1/games/${h(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true})}async function Iy(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function My(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Oy(t,e,n,r){let i=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/kick/${h(n)}`;return t.client.post(i,void 0,r?.signal)}async function Ly(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Gy(t,e,n,r){let i=`/v1/settings/${h(e)}/${h(n)}`;return t.client.get(i,r?.signal)}async function Dy(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/orders`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function $y(t,e,n,r){let i=`/v1/inventory/${h(e)}/${h(n)}/progressions`;return t.client.get(i,r?.signal)}async function Fy(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),a=`/v1/saves/${h(e)}/${h(n)}`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function qy(t,e){let n=new URLSearchParams;e?.include_inactive!==void 0&&n.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.offset!==void 0&&n.set("offset",String(e?.offset));let r=n.toString(),i="/v1/events"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function jy(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i=`/v1/games/${h(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ny(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function Uy(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function By(t,e,n,r,i,o){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/max`;return t.client.post(a,i,o?.signal)}async function Vy(t,e,n,r,i,o){let a=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.put(a,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Hy(t,e,n,r){let i=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.put(i,n,r?.signal)}async function Wy(t,e,n,r,i){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.put(o,r,i?.signal)}async function Ky(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Jy(t,e,n,r,i,o){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/upload-url`;return t.client.post(a,i,o?.signal,{replaySafe:true})}async function zy(t,e,n,r,i,o){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/reset`;return t.client.post(a,i,o?.signal)}async function Yy(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/orders/simulate`;return t.client.post(o,r,i?.signal)}async function Xy(t,e,n,r){let i=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}/transfer/${h(n)}`;return t.client.post(i,void 0,r?.signal)}async function Qy(t,e,n,r){let i=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.patch(i,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Zy=1e4,ef=50,nf=1e3,tf=65536-4*1024,dd=t=>typeof t=="number"?t:0,rf=t=>typeof t=="string"?t:"";function cd(){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 of(t){return t?.retryable===true}function af(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:dd(o.index),code:rf(o.code)}}):[];return {accepted:dd(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function ud(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 md(t){let e=Math.max(1,Math.floor(t.maxQueue??nf)),n={client:t.client,gameId:()=>t.gameId},r=[],i=0,o=null,a=false,s=false,l=false,d=false,m=w=>{t.log?.(w);},c=()=>{o!==null&&(t.clock.clearTimeout(o),o=null);},p=()=>{o!==null||a||s||(o=t.clock.setTimeout(()=>{o=null,y().catch(()=>{});},Zy));},g=()=>{let w=Math.min(r.length,100),S=128;for(let A=0;A<w;A+=1){let C=r[A];if(C===void 0)break;if(S+=JSON.stringify(ud(C,0)).length+1,S>tf)return Math.max(1,A)}return w};async function y(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};c();let S=r.splice(0,g()),A=i;i=0;let C=Math.round(t.clock.now()),b={batch_id:cd(),sent_at_ms:C,events:S.map(R=>ud(R,C))};s=true;try{let R=await oo(n,b,w===void 0?void 0:{signal:w}),E=af(R,A);for(let T of E.rejected)m(`[gem] analytics: an event was refused (${T.code}). See the analytics_events section of your game config.`);return E}catch(R){if(of(R))for(r=[...S,...r],i+=A;r.length>e;)r.shift(),i+=1;else m(`[gem] analytics: ${S.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(R)}`);throw R}finally{s=false,r.length>0&&p();}}return {track(w,S,A={}){if(a)return;if(typeof w!="string"||w===""){d||(d=true,m(`[gem] analytics: '${S}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(S.startsWith(Zr)){l||(l=true,m(`[gem] analytics: '${S}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let C={},b={};for(let[R,E]of Object.entries(A))typeof E=="string"?C[R]=E:typeof E=="number"&&Number.isFinite(E)&&(b[R]=E);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:cd(),playerId:w,name:S,atMs:t.clock.now(),dimensions:C,measures:b}),r.length>=ef?y().catch(()=>{}):p();},flush:w=>y(w),get pending(){return r.length},dispose(){a=true,c(),r=[],i=0;}}}function pd(t){return {async list(e){let{playerId:n,periodsBack:r,signal:i}=e??{};if(typeof n!="string"||n==="")throw new TypeError("gem.challenges.list needs { playerId }: a game-server token names no player, so the platform cannot tell whose period you mean. Pass the id from join() or gem.players().");un(r);let o=await t({player_id:n,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return qt(o)}}}function sf(t){let e={};for(let[n,r]of Object.entries(ao))if(typeof r=="function"){let i=r;e[n]=(...o)=>i(t,...o);}return e}function gd(t,e={}){let n=e.clock??ye,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let i=ld(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=mr({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),a=new Fe({transport:o,clock:n}),s={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=sf({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=t.endMatch,c=t.log,p=md({client:a,clock:n,gameId:s.gameId,...typeof c=="function"?{log:y=>c.call(t,y)}:{}});return {identity:s,client:a,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);}},analytics:p,functions:new Be(l.invokeFunction),challenges:pd(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let w=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),S=w.modified?w.body:void 0;if(S?.room_args==null||S.room_args_template==null)throw new G("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:S.room_args,room_args_template:S.room_args_template}}}},dispose:()=>{p.dispose(),i.dispose();}}}function ze(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Sn(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function ot(t){return typeof t=="string"?t:t.slice().buffer}function yr(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 lf=5e3,yd=3e4,fd=2e3,df=1e4,hd=1;async function bd(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let i=e.log===void 0?f=>console.info(f):e.log,o=f=>i?.(`[gem host] ${f}`),a=typeof t=="function"?t():t,s=Promise.resolve(),l=true,d=false,m=(f,M)=>{l&&(s=s.then(async()=>{if(!d)try{await M();}catch(F){o(`the bundle's ${f} handler threw: ${Ye(F)}. Serving continues.`);}}));},c=true,p,g,y,w=f=>{if(!c)return;c=false,m("leave",()=>a.leave?.(r,{cause:f??"left"}));let M=g;M&&queueMicrotask(()=>M(f));},S={send(f,M){if(!c)return;let F=Sn(ze(M));m("message",()=>a.message?.(r,f,typeof f=="string",{reliable:F.reliable,ordered:F.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){w("closed");}},A=(f,M)=>{if(!c)return;let F=Sn(ze(M));queueMicrotask(()=>{c&&p?.(f,F);});},C=new Map,b=f=>{let M=[];for(let F of Le){let re=f.channels[F];try{re.binaryType="arraybuffer";}catch{}let _e=Sn(F),Ze=j=>{let en=yr(j?.data);en!==null&&m("message",()=>a.message?.(f.playerId,en.data,en.isText,{reliable:_e.reliable,ordered:_e.ordered}));};re.addEventListener("message",Ze),M.push(()=>re.removeEventListener("message",Ze));}C.get(f.playerId)?.forEach(F=>F()),C.set(f.playerId,M);},R=f=>{C.get(f)?.forEach(M=>M()),C.delete(f);},E=new Set,T=new Map,V=(f,M,F)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...M?{rejoin:true}:{},...F?{superseded:true}:{}}),B=f=>{let M=C.has(f.playerId),F=E.has(f.playerId);E.add(f.playerId),b(f),M&&m("leave",()=>a.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>a.join?.(f.playerId,V(f,F,M)));},K=new Set,x=(f,M,F)=>{if(f===r){A(M,F);return}let re=n.peer(f);if(re===null){let _e=T.get(f);if(_e!==void 0&&e.clock.now()-_e<fd)return;K.has(f)||(K.add(f),o(`send to '${f}' dropped: no such connected player`));return}re.send(ot(M),ze(F));},I={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=c?[r]:[];for(let M of n.peers)f.push(M.playerId);return f},profile(f){let M=e.room()?.members.find(F=>F.playerId===f);if(!(!M||M.displayName===void 0))return {displayName:dn.toPlain(M.displayName),...M.displayTag===void 0?{}:{displayTag:dn.toPlain(M.displayTag)},...M.discriminator===void 0?{}:{discriminator:M.discriminator}}},playerNumber(f){return f===r?hd:n.peer(f)?.assignedPeerId},send(f,M,F){x(f,M,F);},broadcast(f,M){let F=M?.except;c&&r!==F&&A(f,M);for(let re of n.peers)re.playerId!==F&&re.send(ot(f),ze(M));},async endMatch(){let f=await Me();return f.answer!=="ok"&&o(f.cause),f.answer},kick(f,M){if(f===r){w(M??"kicked");return}n.kick(f).catch(F=>{o(`kick of '${f}' failed: ${Ye(F)}`);});},log(f){o(f);},warn(f){o(`\u26A0 ${f}`);}},O=()=>{},$=new Promise(f=>{O=f;}),N=[],q=null,Z=async(f,M)=>{l=false;let F=s.then(async()=>{try{await a.shutdown(f);}catch(re){o(`the bundle's shutdown threw: ${Ye(re)}`);}});s=F,await F,le();for(let re of N.splice(0))re();for(let re of [...C.keys()])R(re);w(M);},pe=(f,M)=>q||(q=(async()=>{await Z(M,f),n.close(),O();})(),q),X=()=>q||(q=(async()=>{await Z({reason:"signal"},"left"),await n.leave().catch(f=>o(`leaving the match failed: ${Ye(f)}`)),O();})(),q),Ie=()=>q||(q=(async()=>{l=false;let f=await Me();f.answer==="ok"?(await Z({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(o(`${f.cause}; leaving instead`),await Z({reason:"signal"},"left"),await n.leave().catch(M=>o(`leaving the match failed: ${Ye(M)}`))),O();})(),q),ce=null,Re=()=>(ce??=gd(I,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),ce),Me=async()=>{try{return await Ca({client:Re().client,gameId:()=>I.gameId},I.matchId,{},{signal:AbortSignal.timeout(lf)}),{answer:"ok"}}catch(f){return f instanceof G&&(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: ${Ye(f)}`}}},te=null,z=false,le=()=>{z=true,te!==null&&(e.clock.clearTimeout(te),te=null);},ct=async()=>{if(te=null,!z){try{await Re().client.post(`/v1/games/${encodeURIComponent(I.gameId)}/matches/${encodeURIComponent(I.matchId)}/heartbeat`,void 0,AbortSignal.timeout(df));}catch(f){if(f instanceof G&&(f.reason==="forbidden"||f.reason==="not_found")){o(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),le();return}o(`heartbeat failed: ${Ye(f)}`);}z||(te=e.clock.setTimeout(()=>{ct();},yd));}},Rn=()=>{z||te!==null||(te=e.clock.setTimeout(()=>{ct();},yd));};{let f=O;O=()=>{le(),ce?.dispose(),ce=null,f();};}let Qe=Promise.resolve().then(()=>a.init(I));s=Qe.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:hd,transport:"loopback"})),N.push(n.on("peerJoined",B)),N.push(n.on("peerLeft",(f,M)=>{R(f);let F=e.clock.now();for(let[re,_e]of T)F-_e>=fd&&T.delete(re);T.set(f,F),K.delete(f),m("leave",()=>a.leave?.(f,{cause:M}));})),N.push(n.on("error",f=>{o(`\u26A0 session error: ${f.message}`);})),N.push(n.on("matchEnded",f=>{q||so(y,f),pe("match ended",{reason:"match_ended",platform_reason:f});})),N.push(n.on("hostChanged",f=>{f!==r&&pe("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)B(f);try{await Qe,Rn();}catch(f){l=false,le(),d=true;for(let M of N.splice(0))M();for(let M of [...C.keys()])R(M);throw n.leave().catch(()=>{}),O(),f}return {matchId:n.matchId,localLink:S,onMatchEnded(f){y=f;},end:Ie,leave:X,stop:f=>pe(f,{reason:"stopped"}),done:$}}function so(t,e){try{t?.(e);}catch{}}function Ye(t){return t instanceof Error?t.message:String(t)}function lo(t,e){let n=async()=>{throw new _("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 _d(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,i=new Map,o=async s=>{r.isHost&&!io(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...s.signal===void 0?{}:{signal:s.signal}});let l={...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},a=s=>({...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0?{}:{clusterTargetId:s.clusterTargetId}});return {async serve(s,l={}){let d=await o(l);if(d.protocol!==Ke)return lo("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return lo("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(a(l)),g=await bd(s,{session:p,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return i.set(d.matchId,g),g.done.then(()=>{i.get(d.matchId)===g&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(s={}){let l=await o(s),d=s.onMatchEnded;if(l.protocol===Ke){let g=i.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),pf(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 Qn(),w=async()=>t.p2p.connect({...a(s),certificate:y}),S=await w(),A=yf(S,w,d,C=>{r.notifyMatchDisconnected(C).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(S.matchId,{redial:A.redial,abandon:A.abandon}),A.onClosed(()=>{e.get(S.matchId)?.abandon===A.abandon&&e.delete(S.matchId);})),A}let m=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:s.transports??[]}),c=await m(),p=gf(c,m,r,n);return n&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var vd="link_closed",cf="host_unreachable",uf=new Set(["failed","closed"]);function mf(t){return uf.has(t)?vd:cf}function pf(t,e,n){let r=e.localLink;e.onMatchEnded(n);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:t,protocol:"loopback",get state(){return i},send:(a,s)=>r.send(a,s),onMessage:a=>r.onMessage(a),onClose:a=>{o=a,r.onClose(s=>{i="closed",o?.(s);});},close:()=>r.close()}}function gf(t,e,n,r){let i=t.matchId,o=t,a="connected",s,l,d=[],m=false,c=false,p=y=>{if(a!=="closed"){a="closed";for(let w of d.splice(0))w();l?.(y);}},g=y=>{y.link.onMessage((w,S)=>s?.(w,S)),y.link.onClose(w=>{if(y!==o||a==="closed")return;if(m||!r){p(w);return}let S=n.matchSession;if(S.phase==="suspended"&&S.matchId===i){a="suspended";return}p(w);});};return g(t),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return a},send(y,w){a==="connected"&&o.link.send(y,w);},onMessage(y){s=y;},onClose(y){l=y;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}o.close(),p("closed");}},async redial(y){if(a==="closed"||m)return "closed";if(c)return "connected";c=true;let w;try{w=await e(y===void 0?{}:{deadlineAt:y});}finally{c=false;}return m||a==="closed"?(w.close(),"closed"):(o=w,g(w),a="connected",n.notifyMatchConnected(i),"connected")},abandon(y){a!=="closed"&&(a==="connected"&&o.close(),p(y));},onClosed(y){a==="closed"?y():d.push(y);}}}function yf(t,e,n,r,i,o=false){let a=t.matchId,s=t,l,d,m=[],c=[],p=[],g=false,y=false,w=false,S=false,A="connected",C=x=>{if(g)return;g=true,A="closed";for(let O of m.splice(0))O();for(let O of c.splice(0))O();for(let O of p.splice(0))O();let I=d;I&&queueMicrotask(()=>I(x));},b=x=>{for(let I of m.splice(0))I();for(let I of Le){let O=x.channels[I];try{O.binaryType="arraybuffer";}catch{}let $=Sn(I),N=q=>{let Z=yr(q?.data);Z!==null&&l?.(Z.data,$);};O.addEventListener("message",N),m.push(()=>O.removeEventListener("message",N));}},R=()=>s.peer(s.hostPlayerId),E=x=>{if(!(g||s.isHost)&&A!=="suspended"){if(r?.(x),o){A="suspended";return}C(x);}},T=x=>{for(let I of Le){let O=x.channels[I];if(typeof O.addEventListener!="function")continue;let $=()=>{R()===x&&E(vd);};O.addEventListener("close",$),m.push(()=>O.removeEventListener?.("close",$));}},V=x=>{b(x),T(x),!g&&(A="connected",i?.());},B=x=>{for(let I of c.splice(0))I();c.push(x.on("migrating",()=>{S=true;})),c.push(x.on("hostChanged",I=>{if(S=false,I===x.playerId){C("host_migrated_here");return}let O=R();O!==null&&V(O);})),c.push(x.on("peerJoined",I=>{I.playerId===x.hostPlayerId&&V(I);})),c.push(x.on("matchEnded",I=>{g||so(n,I),C(I);})),c.push(x.on("peerLeft",(I,O)=>{I===x.hostPlayerId&&E(mf(O));}));};B(s);let K=R();return K!==null&&V(K),{matchId:a,protocol:"p2p",get state(){return A},send(x,I){A==="connected"&&R()?.send(ot(x),ze(I));},onMessage(x){l=x;},onClose(x){d=x;},close(){y=true,C("closed"),s.leave().catch(()=>{});},async redial(){if(A==="closed")return "closed";if(A==="connected"||w)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");w=true;let x;try{for(let O of m.splice(0))O();for(let O of c.splice(0))O();s.close(),x=await e();}finally{w=false;}if(g)return y?x.leave().catch(()=>{}):x.close(),"closed";s=x,B(s);let I=R();if(I===null)throw s.close(),new L("connection_failed","this peer rejoined the match but the host never answered with a link");return V(I),"connected"},abandon(x){C(x);},onClosed(x){g?x():p.push(x);}}}function co(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},a=l=>{n.delete(r)&&(t.clock.clearTimeout(o.timer),i(l));};n.set(r,a),o.timer=t.clock.setTimeout(()=>a(void 0),t.timeoutMs??2e3);let s=false;try{s=t.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,i){n.get(r)?.(i);}}}var ff=12e4;function Xe(t,e){return {outcome:t,reason:e}}function wd(t){let e=false,n=new Map;return {api:{request(r){if(!t.bridge.parentSupports("purchases"))return Promise.resolve(Xe("unavailable","error"));if(e)return Promise.resolve(Xe("declined","busy"));let i=`purchase-${Pe()}`;return new Promise(o=>{let a={},s=d=>{n.delete(i)&&(e=false,t.clock.clearTimeout(a.timer),o(d));};e=true,n.set(i,s),a.timer=t.clock.setTimeout(()=>s(Xe("unavailable","error")),t.timeoutMs??ff);let l=false;try{l=t.bridge.requestPurchase(i,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(Xe("unavailable","error"));})}},settle(r){let i=r.outcome==="ok"||r.outcome==="declined"?r.outcome:"unavailable",o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.purchaseResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}if(i!=="ok"){o(Xe(i,Ya(r.reason)));return}let a=r.purchaseId;if(a===void 0){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),o(Xe("unavailable","error"));return}(async()=>{let s;try{s=await t.confirm(a);}catch{s="unknown";}if(s==="granted"){o({outcome:"ok",purchaseId:a});return}s==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(a)),o(Xe("unavailable","error"));})();}}}async function Sd(t,e){try{return (await pa(t,e)).granted?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}var hf=6e5;function Rd(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-${Pe()}`;return e=new Promise(i=>{let o={},a=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(o.timer),i(l));};n.set(r,a),o.timer=t.clock.setTimeout(()=>{a({outcome:"unavailable"});},t.timeoutMs??hf);let s=false;try{s=t.bridge.requestSignIn(r);}catch{}s||a({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var bf=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),_f=["utm_"];function kd(t){return bf.has(t)||_f.some(e=>t.startsWith(e))}var xd=16,Ad=512,vf=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,wf=/[\p{Cc}\p{Cf}]/u,Sf=/\p{Cs}/u,Ce="[gem] gem.share.request:";function Pd(t){let{frame:e,log:n}=t,r=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,o=a=>{n!==null&&(n===void 0?console.warn(a):n(a));};return {get available(){return i()!==null},request(a){let s=i();if(s===null)throw new Error(`${Ce} the arcade does not handle share here \u2014 check gem.share.available first`);if(a!==void 0&&(typeof a!="object"||a===null))throw new TypeError(`${Ce} pass { params }, or nothing`);let l=a?.params===void 0?{}:a.params;if(!Rf(l))throw new TypeError(`${Ce} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>xd)throw new TypeError(`${Ce} at most ${xd} params; got ${d.length}`);let m=[];for(let[c,p]of d){let g=JSON.stringify(c);if(!vf.test(c))throw new TypeError(`${Ce} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(kd(c))throw new TypeError(`${Ce} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Ce} param ${g}: values must be strings`);if(p.length>Ad)throw new TypeError(`${Ce} param ${g}: a value is at most ${Ad} characters`);if(wf.test(p))throw new TypeError(`${Ce} param ${g}: control and format characters are not allowed`);if(Sf.test(p))throw new TypeError(`${Ce} param ${g}: a value must be well-formed text`);m.push({key:c,value:p});}!s.requestShare(m)&&!r&&(r=true,o("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function Rf(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Pf="(any-pointer: coarse)";function Ef(t){let e=Array.isArray(t)?t:[t],n=[],r=1e4;for(let i of e){if(typeof i!="number"||!Number.isFinite(i)||i<0)return null;if(n.length===99||r===0)continue;let o=Math.min(Math.trunc(i),1e4,r);n.push(o),r-=o;}return n.length%2===0&&n.pop(),n.every(i=>i===0)?[]:n}function Ed(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},i=r.navigator,o,a=new Set,s=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia(Pf),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,c)=>{a.has(m)||(a.add(m),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return s()||l()},vibrate(m){let c=s();if(!c&&!l())return false;let p=Ef(m);if(p===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(i?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(c)try{return i.vibrate(p)===!0}catch{return false}let g=e.requestVibrate(p);return g||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),g}}}var Tf=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Td(t){if(typeof t!="string"||!Tf.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function at(){return {declared:false,grantable:false,heldLimitReached:false}}function Cd(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Td(n.resets_at),i=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...at(),...i};let o=n.remaining_today,a=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,s=n.next_eligible_at,l=Td(s),d=n.held_limit_reached===true,m=s!=null,c=o!=null&&a===void 0;return {declared:true,grantable:n.grantable===true&&e&&a!==0&&!c&&!m&&!d,...a===void 0?{}:{remainingToday:a},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var Cf=18e4,uo=32,If=/^[a-z0-9_-]+$/,Mf="rewarded_requires_user_gesture";function Of(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var Lf=1e3;function Gf(){let t=globalThis,e=t.navigator?.getGamepads,n=t.performance?.now;if(typeof e!="function"||typeof n!="function")return;let r=n.call(t.performance),i=e.call(t.navigator);for(let o=0;o<i.length;o+=1){let a=i[o]?.timestamp;if(typeof a=="number"&&r-a>=0&&r-a<=Lf)return true}return false}var Id=1e4;function Df(t){return t==="interstitial"||t==="rewarded"}function Md(t){return typeof t=="string"&&t!==""&&t.length<=uo&&If.test(t)}function $f(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function fr(t){return typeof t=="string"?JSON.stringify(t):typeof t}function Od(t){let e=false,n=new Map,r=new Map,i=new Set,o=d=>{try{t.onDropped?.(d);}catch{}},a=false,s=d=>{if(a)return;a=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(at());let c=r.get(d);if(c!==void 0)return c;let p=new Promise(g=>{let y={},w=b=>y.done===true?false:(y.done=true,t.clock.clearTimeout(y.timer),g(b),true),S=(b,R)=>{!w(at())||i.has(b)||(i.add(b),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${R}. Said once.`));},A=b=>{S($f(b),`the read failed (${b instanceof Error?b.message:fr(b)})`);},C;try{C=Promise.resolve(m(d,AbortSignal.timeout(Id)));}catch(b){C=Promise.reject(b);}y.timer=t.clock.setTimeout(()=>{S("timeout","no answer within 10 s");},Id),C.then(b=>{try{w(Cd(b,t.bridge.parentSupports("ads")));}catch(R){A(R);}},A);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return Md(d)?l(d):(o(`gem.ads.rewardedStatus(${fr(d)}) answered not grantable: a placement is 1..${String(uo)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(at()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let m=d?.placement,c=d?.format;if(!Md(m)||!Df(c))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${fr(m)}, format ${fr(c)}. A placement is 1..${String(uo)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});if(c==="rewarded"){let g;try{g=(t.userActivation??Of)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??Gf)()===!0&&(g=!0);}catch{}if(g===false){let y=`${Mf}: gem.ads.requestAd("${m}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return o(y),s(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${Pe()}`;return new Promise(g=>{let y={},w=A=>{n.delete(p)&&(e=false,t.clock.clearTimeout(y.timer),g(A));};e=true,n.set(p,w),y.timer=t.clock.setTimeout(()=>{w({outcome:"unavailable"});},t.timeoutMs??Cf);let S=false;try{S=t.bridge.requestAd(p,m,c);}catch{}S||w({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:m});}}}var mo=16384;function Ld(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:Ff(e)}function Ff(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var qf=1e4,jf=5e3;function Gd(t){let e=null,n=false,r=[],i=new Map,o=()=>{for(let a of r.splice(0))a();};return {api:{get current(){return e},wait(a=jf){return n?Promise.resolve(e):new Promise(s=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{t.clock.clearTimeout(m),l(),s(e);},m=t.clock.setTimeout(()=>{l(),s(e);},a);r.push(d);})},put(a){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let s=Ld(a);if(s===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(s>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(a)),d=`device-settings-${Pe()}`;return new Promise(m=>{let c={},p=y=>{i.delete(d)&&(t.clock.clearTimeout(c.timer),y==="stored"&&(e=l,n=true,o()),m(y));};i.set(d,p),c.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??qf);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(a){let s=a.settings;e=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,n=true,o();},settle(a){let s=a.outcome==="stored"||a.outcome==="too_large"?a.outcome:"unavailable",l=i.get(a.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${s}) for an unknown requestId: `+JSON.stringify(a.requestId));return}l(s);}}}var st=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 Nf=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Uf(t){return typeof t=="string"&&Nf.test(t)}function hr(t){if(t===null||Uf(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 Dd(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function po(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!n.includes(i)&&n.push(i);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function br(t,e){let n=[];for(let r of Array.isArray(e)?e:[]){if(n.length===4)break;if(typeof r!="object"||r===null)continue;let{id:i,label:o}=r;typeof i!="string"||i.length===0||i.length>32||typeof o!="string"||o.trim().length===0||n.some(a=>a.id===i)||n.push({id:i,label:o.trim().slice(0,40)});}return n.length===0?{settings:t===true}:{settings:t===true,items:n}}function $d(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Bf(t){let e=t.untrusted,n=Oe(e.displayName),r=e.displayTag||e.displayHandle,i=r?Oe(r):void 0,o=t.discriminator||t.displayTag,a=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,s=t.avatarIconUrl||t.avatarUrl,l={displayName:n,displayHandle:i??n,badges:(t.badges??[]).map(p=>({itemId:p.itemId,iconUrl:p.iconUrl}))};t.playerId&&(l.playerId=t.playerId),a&&(l.discriminator=a),i&&(l.displayTag=i),s&&(l.avatarIconUrl=l.avatarUrl=s);let d=t.boost,m=(d?.multipliers??[]).map(p=>({currencyId:p.currencyId,currencySlug:p.currencySlug,multiplier:p.multiplierBp/1e4})),c=m.some(p=>p.multiplier>1);return l.boost=c&&d?.expiresInDays?{active:c,multipliers:m,expiresInDays:d.expiresInDays}:{active:c,multipliers:m},l}var Vf=1e4,lt=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??ye,this.inbound=new An(this.clock),this.outbound=new An(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>Lr(s,e.origin))||Wa(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=vt["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!Lr(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=Ka(bt,i.versions);return a===null?(o.onmessage=null,o.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${bt.min}..v${bt.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=a,o.onmessage=s=>this.receive(s.data,s.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:U,type:"gem.handshake.accept",v:a,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:U,type:"gem.ready"});}settled(e=Vf){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=o=>{this.clock.clearTimeout(i),n(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem: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.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:U,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:U,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let 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:Dd(e.origin.x),y:Dd(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=hr(e);return n===void 0||this.state!=="connected"||!this.parentSupports("portraitBorders")?false:this.send(n===null?{gem:U,type:"gem.portraitBorders"}:{gem:U,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:U,type:"gem.walletDisplay",...po(e,n?.only)})}setMenu(e,n){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:U,type:"gem.menu",...br(e,n)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:U,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:U,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:U,type:"gem.frameStats",fps:$d(e.fps,1e3),frameTimeP95Ms:$d(e.frameTimeP95Ms,1e5)}),true)}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,i,o,a){return this.send({gem:U,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...a===void 0?{}:{catalogId:a}})}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})}requestSignIn(e){return this.send({gem:U,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,i){return this.send({gem:U,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...i===void 0?{}:{params:i}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(_t)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(_t)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(_t)&&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}});}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=vt[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||Fd(n);}}dispatchInbound(e,n){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=vt[r];if(!i)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let o=Ba(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let a=i(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.menuSelect":this.options.onMenuSelect?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=n[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return Fd(n.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(Bf(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:U,type:"gem.screenshot.denied",reason:e,retryable:n});}};function Fd(t){for(let e of t)try{e?.close?.();}catch{}}var qd="https://api.gemarcade.com";function go(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 Hf=new Set(["localhost","127.0.0.1","[::1]"]);function jd(t){let e=go(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!Hf.has(n.hostname)?"it is a plaintext http address that is not loopback. An embedder may name an https root, or http on localhost for a rig running the whole stack on one machine \u2014 the play token travels on every request to it":null}var Kf=Object.freeze(["https://gemarcade.com","https://meme-games.com","http://gemarcade.localhost","gemarcade://localhost"]),Jf=qd,Nd=8e3,yo=15e3,zf=9e4,Yf=1/0,Xf=8e3,Qf=5e3,Zf=5e3;async function eh(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 dt(t){let e=null,n=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){n=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||n?Promise.resolve(e):new Promise(o=>{let a=()=>{let d=r.indexOf(s);d>=0&&r.splice(d,1);},s=d=>{t.clearTimeout(l),a(),o(d);},l=t.setTimeout(()=>{a(),o(e);},i);r.push(s);})}}}function qR(t={}){let e=t.clock??ye,n=t.log===void 0?u=>console.info(u):t.log,r=t.baseUrl??void 0;if(r!=null){let u=go(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=_s(typeof window>"u"?void 0:window.location?.search),o=Ki();o.mark("sdk created");let a=()=>Jt(ee.gameVersion,t.clientVersion?.gameVersion),s=new Fn({client:()=>tn,clock:e,gameId:()=>ee.identity?.gameId??null,playerId:()=>ee.identity?.playerId??null,environment:()=>{let u=a();return {sdk_version:Io(),...u===null?{}:{game_version:u}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),l=Rl(()=>{o.mark("engaged"),s.release(),j.reportEngaged();},typeof window>"u"?{}:window),d=u=>{if(u===false)return null;let k=u?.attempts??Yf,D=u?.budgetMs??zf;return !(k>0)||!(D>0)?null:{attempts:k,budgetMs:D,maxDelayMs:u?.maxDelayMs??Xf}},m=u=>{u.on("created",()=>{o.mark("room created");}),u.on("joined",()=>{o.mark("room joined");}),u.on("matchAllocationStarted",()=>{o.mark("allocation started");}),u.on("matchReady",()=>{o.mark("match ready");}),u.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new st;let c=t.allowedEmbedders;if(c!=null&&!Array.isArray(c))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let p=Array.from(c??[]),g=p.filter(u=>typeof u!="string"||!Or(u));if(g.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${g.length===1?"an entry":"entries"} that ${g.length===1?"is":"are"} not an origin: ${g.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let y=Object.freeze([...new Set([...Kf,...p])]),w=dt(e),S=dt(e),A=dt(e),C=xs(n),b=dt(e),R=t.manageAudio===false?null:Il();t.selectableText!==true&&Ml();let E=null,T=()=>{E!==null&&(S.current!==null&&S.current.muted===E||j.reportMuted(E));},V,B,K=-1/0,x=null,I=()=>{if(V===void 0||x!==null||V===B)return;let u=K+1e3-e.now();if(u>0){x=e.setTimeout(()=>{x=null,I();},u);return}j.showPortraitBorders(V)&&(B=V,K=e.now());},O=null,$=null,N=()=>{if(O===null)return false;let u=JSON.stringify(po(O.visible,O.only));return u===$?j.parentSupports("walletDisplay"):j.setWalletVisible(O.visible,O)?($=u,true):false},q=null,Z=null,pe=()=>{if(q===null)return false;let u=typeof q.onSettings=="function",k=JSON.stringify(br(u,q.items));return k===Z?j.parentSupports("gameMenu"):j.setMenu(u,q.items)?(Z=k,true):false},X=Ol({report:u=>j.reportFrameStats(u)}),Ie=false,ce=jl(()=>Co,()=>Ie),Re=u=>{let k=Ie&&!u,D=Ie!==u;if(Ie=u,k&&ce.close(),!!D)try{t.onDevToolsPermissionChange?.(u);}catch(ne){n?.(`[gem] onDevToolsPermissionChange threw: ${ne instanceof Error?ne.message:String(ne)}`),queueMicrotask(()=>{throw ne});}},Me=r??Jf,te=r!==void 0,z,le=u=>(n?.(`[gem] token refused: ${u}`),t.onError?.("internal",u),false),ct=(u,k)=>{if(u===void 0)return k!==void 0?le("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let D=jd(u);return D!==null?le(`the embedder named an API root that cannot be used: ${D}. Its value is withheld here rather than written to logs.`):z!==void 0&&z!==u?le("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(z=u,te||(Me=u),true)},Rn=window.location?.origin,Qe=null,f=-1/0,M=2e3,F=new Set,re=u=>Qe!==false?Promise.resolve(true):new Promise(k=>{let D=e.setTimeout(()=>{F.delete(ne),k(false);},u),ne=()=>{e.clearTimeout(D),F.delete(ne),k(true);};F.add(ne);}),_e=()=>{},Ze=null,j=new lt({allowedEmbedders:y,...typeof Rn=="string"&&Rn!==""?{selfOrigin:Rn}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","vibration","frameStats","walletDisplay","gameMenu","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:u=>{Ze=u,t.onRefused?.(u);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:u=>{ee.onBridgeState(u),u!=="connected"&&X.setRequested(false),$=null,Z=null,B=void 0,u==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Ze===null?"":` (${Ze})`)+", so it has no player, saves, config or rooms. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders."),_e()),u==="connected"&&(o.mark("bridge connected"),Ud(),T(),I(),N(),pe(),j.unbiddenLaunch&&!l.engaged&&s.hold(),s.startSession(),l.engaged&&j.reportEngaged()),t.onStateChange?.(u);},onPlayer:u=>{w.set(u),t.onPlayer?.(u);},onPrefs:u=>{let k={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true};S.set(k),R?.setMuted(k.muted),X.setRequested(k.showFrameStats&&j.parentSupports("frameStats")),t.onPrefs?.(k);},onCohorts:u=>{let k=Object.freeze(u.cohorts.map(D=>Object.freeze({experimentId:D.experimentId,variantKey:D.variantKey})));A.set(k),t.onCohorts?.(k);},onEarnAllowanceChanged:()=>C.emit(),onViewport:u=>{let k=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left}),reserved:Object.freeze((u.reserved??[]).map(ne=>Object.freeze({x:ne.x,y:ne.y,width:ne.width,height:ne.height})))});b.set(k);let D=Gl();Dl(D,k.insets),Fl(D,k.reserved,$l()),t.onViewport?.(k);},onPause:u=>{s.setPaused(u.paused),X.setPaused(u.paused),t.onPause?.(u.paused);},onMenuSelect:u=>{if(q===null)return;if(u.entry==="settings"){q.onSettings?.();return}(br(false,q.items).items??[]).some(D=>D.id===u.id)&&q.items?.find(D=>D.id===u.id)?.onSelect?.();},onWillTerminate:u=>{s.endSession(u.reason),t.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let k=u.garden;if(Re(u.allowDevTools===true),!ct(u.apiBaseUrl,k))return;let D=u;ee.onToken(D);let ne=ee.identity;ne&&(_r.set(ne),fo||(fo=true,ue.reconcileSeats().catch(()=>{}))),ho.push({token:D.token,expiresAt:D.expiresAt});},onTokenDenied:u=>{Re(false),ee.onDenied(u);},onScreenshot:(u,k,D)=>{El(u,k,D,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Tl(j,t.onFeedbackContext);},onDevtools:u=>{u==="close"?ce.close():u==="open"?ce.openFrom("platform").catch(()=>{}):ce.isOpen?ce.close():ce.openFrom("platform").catch(()=>{});},onRoomEvent:u=>ue.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>ue.handleSeated(u.roomId),onAutoStartFailedEvent:u=>ue.handleAutoStartFailed(u.roomId,u.code),onSocketState:u=>{let k=Qe;if(Qe=u.connected,u.connected)for(let ne of [...F])ne();if(!u.connected||k===true)return;let D=e.now();D-f<M||(f=D,ue.reconcile().catch(()=>{}));},onSignalEvent:u=>{let k=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};rn.handleSignalEvent(u.matchId,u.event,k),u.event==="matchEnded"&&ue.reconcile({matchId:u.matchId,...typeof k.reason=="string"?{reason:k.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(kn.handleMatchEnded(u.matchId,u.reason),ue.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),en.handleEvent(u);},onClusterTarget:u=>pt.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>gt.accept(u),onLocalServerDenied:u=>gt.refuse(u),onPartyResult:u=>_o.settle(u.requestId,u.partyId),onPurchaseResult:u=>wo.settle(u),onDeviceSettings:u=>{mt.receive(u),t.onDeviceSettings?.(mt.api.current);},onDeviceSettingsResult:u=>mt.settle(u),onAdResult:u=>Ro.settle(u),onSignInResult:u=>ko.settle(u),onFriendChallengeResult:u=>xo.settle(u)}),en=new it({bridge:j}),_r=dt(e);_e=()=>{_r.release(),w.release(),A.release();},j.currentState==="refused"&&_e();let fo=false,vr=new Set,ut,ho={current:()=>ut,subscribe:u=>(vr.add(u),ut!==void 0&&u(ut),()=>vr.delete(u)),push:u=>{ut=u;for(let k of [...vr])try{k(u);}catch(D){n?.(`[gem] a server-token listener threw: ${D instanceof Error?D.message:String(D)}`);}}},ee=Ul({bridge:j,clock:e,onStateChange:(u,k)=>{if(u==="ready"){if(o.mark("token ready")){let D=o.marks.find(ne=>ne.name==="token ready")?.at;s.trackPlatform("gem_boot_ready",D===void 0?{}:{boot_ms:Math.max(0,Math.round(D))});}}else u==="lost"&&(o.mark("token lost"),s.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(u,k);}}),bo=()=>{let u=ee.identity;return !u||ee.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},Ud=()=>{o.mark("token requested"),ee.source.get().catch(()=>{});},_o=co({bridge:j,clock:e}),vo={},wo=wd({bridge:j,clock:e,onDropped:u=>t.onError?.("internal",u),confirm:async u=>vo.confirm?.(u)??"unknown"}),mt=Gd({bridge:j,clock:e,onDropped:u=>t.onError?.("internal",u)}),So={},Ro=Od({bridge:j,clock:e,onDropped:u=>t.onError?.("internal",u),readAvailability:(u,k)=>So.read?.(u,k)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),ko=Rd({bridge:j,clock:e,onDropped:u=>t.onError?.("internal",u)}),xo=ks({bridge:j,clock:e,onDropped:u=>t.onError?.("internal",u)}),pt=Ls({bridge:j,clock:e}),gt=ql({bridge:j,clock:e}),wr=u=>{let k=j.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return k&&window.removeEventListener("message",wr),k};window.addEventListener("message",wr);let nn=kl(window,wr),Bd=nn?.capture,Sr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Sr?.domInteractive!==void 0&&Sr.domInteractive>0&&o.mark("document parsed",Sr.domInteractive),Bd?.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 Rr=t.handshakeWarningMs;Rr!==null&&n&&e.setTimeout(()=>{let u=nn===null?"no capture script ran":`capture: ${nn.delivered} offer(s) delivered, ${nn.stale} stale, ${nn.capture.dropped} evicted${nn.capture.late?", installed late":""}`;if(j.currentState==="connected"){n(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${u}`);return}n(`[gem] no completed handshake after ${Rr??Nd}ms (bridge state: ${j.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+u);},Rr??Nd);let Vd=mr({get baseUrl(){return Me},tokenSource:ee.source,get defaultQuery(){let u=ee.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),tn=new Fe({transport:Vd,clock:e}),ge={client:tn,gameId:()=>ee.identity?.gameId??""};vo.confirm=u=>Sd(ge,u),So.read=(u,k)=>La(ge,"players","me",u,{signal:k});let Hd=()=>ee.identity?.channel??"release",Ao=new Ft(ge,Hd),Po=async u=>(await Ao.load())?.currency(u)?.id??void 0,Eo=Mt(ge,Vr,{identity:bo,resolveCurrencyId:Po}),kr=async u=>{let k=await _r.wait(u);if(k)return k;throw j.currentState==="refused"?new se("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new se("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},xr=d(t.autoReconnect),ue=Mi({client:tn,clock:e,gameId:()=>ee.identity?.gameId??null,playerId:()=>ee.identity?.playerId??null,awaitGameId:async()=>(await kr(yo)).gameId,resolveParty:_o.resolve,resolveClusterTargets:pt.resolveList,refreshClusterTargets:pt.refresh,ensureLocalServer:gt.ensure,localHostAvailable:gt.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>ee.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:(u,k)=>Ar.redialMatch(u,k),abandon:(u,k)=>Ar.abandonMatch(u,k)}}});m(ue),wl({analytics:s,rooms:ue});let rn=vl({client:tn,clock:e,rooms:ue,bridge:j,gameId:()=>ee.identity?.gameId??"",baseUrl:()=>Me,resolveClusterTarget:pt.resolve,boot:o,...t.log===void 0?{}:{log:t.log}}),To=Wi(o,n),kn=od({client:tn,clock:e,rooms:ue,signaling:()=>en.channel(),signalingReady:re,log:n??(()=>{})}),Ar=_d({rooms:ue,p2p:{connect:u=>To(rn.connect(u)),session:u=>rn.session(u)},dedicated:{connect:(u=>dr(o,"welcome",kn.connect(u),n))},clock:e,identity:()=>ee.identity,apiBaseUrl:()=>Me,tokens:ho,room:()=>ue.currentRoom,autoReconnect:xr!==null,...t.log===void 0?{}:{log:t.log}}),Wd=async()=>(await kr(yo)).playerId,Co={client:tn,boot:o,get identity(){return ee.identity},awaitIdentity:(u=yo)=>kr(u),awaitBridge:u=>j.settled(u),get player(){return w.current},awaitPlayer:(u=Qf)=>w.wait(u),me:Eo,characters:new Lt(ge,void 0,bo,Po),transfers:new Dt(ge,Vr,Eo.inventory),gameConfig:Ao,purchases:wo.api,deviceSettings:mt.api,ads:Ro.api,account:ko.api,share:Pd({frame:j,log:t.log}),vibration:Ed({frame:j,log:t.log}),analytics:s,leaderboards:new Mn(ge),challenges:new Tn(ge),showcase:new On(ge,Wd),friends:new Ln(ge,{challenge:xo.challenge,...i===void 0?{}:{launchedChallengeId:i}}),platform:new Dn(ge,C,n),profiles:new $n(ge),functions:new Be((u,k)=>va(ge,u,k)),get prefs(){return S.current},get cohorts(){return A.current},get viewport(){return b.current},awaitCohorts:(u=Zf)=>A.wait(u),reportMuted:u=>{E=!!u,T();},showPortraitBorders:u=>{let k=hr(u);k!==void 0&&(V=k,I());},cueReward:u=>j.cueReward(u),setWalletVisible:(u,k)=>{let D=Array.isArray(k?.only)?[...k.only]:void 0;return O=D===void 0?{visible:u===true}:{visible:u===true,only:D},N()},setMenu:u=>(q={...typeof u?.onSettings=="function"?{onSettings:u.onSettings}:{},...Array.isArray(u?.items)?{items:u.items.map(k=>({...k}))}:{}},pe()),exit:u=>eh(ue,j,u,s),frame:j,devtools:ce,rooms:ue,dedicatedServer:{listClusterTargets:u=>kn.listClusterTargets(u),connect:(u=>dr(o,"welcome",kn.connect(u),n)),handleMatchEnded:(u,k)=>kn.handleMatchEnded(u,k)},p2p:{handleSignalEvent:(u,k,D)=>rn.handleSignalEvent(u,k,D),session:u=>rn.session(u),connect:u=>To(rn.connect(u))},match:Ar};return Co}
|
|
1
|
+
var Kd=Object.defineProperty;var Jd=(t,e)=>{for(var n in e)Kd(t,n,{get:e[n],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:9.1.3]";function Io(){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)}function zd(t,e){return e!==void 0?!e:t==="chain_exhausted"}var on=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new se(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new se("chain_exhausted","the token chain reached its ceiling");return this.refresh(this.nextReason())}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}refresh(e){if(this.inFlight)return this.inFlight;let n=this.generation;this.enter("pending");let r=this.options.request(e).then(i=>{if(n!==this.generation)throw new se("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=Yd(i),a=i?.retryable;throw n===this.generation&&this.enter(zd(o,typeof a=="boolean"?a:void 0)?"lost":"degraded",o),i instanceof se?i:new se(o,String(i))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){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)}},se=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 Yd(t){if(t instanceof se)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var ie=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}},Pr=["if-match","if-none-match"],Mo=4096;function Xd(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let i=n.toLowerCase();if(!Pr.includes(i)||r===void 0)continue;let o=typeof r=="string"?Qd(r):r;if(typeof o!="string"||o.length>Mo||!Zd(o))throw new ie(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${Mo} characters, or contains a character outside the range an HTTP header value may carry. This is a malformed request, not a server failure; the value is withheld here rather than written to logs.`);o!==""&&(e[i]=o);}return Object.freeze(e)}function Qd(t){let e=i=>i===32||i===9||i===10||i===13,n=0,r=t.length;for(;n<r&&e(t.charCodeAt(n));)n++;for(;r>n&&e(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function Zd(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 ec(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new ie("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new ie("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function Oo(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=Xd(i.headers),a=ec(i),s=Object.freeze({...i,headers:o,...a===void 0?{}:{bytes:a}}),l=await e.tokenSource.get(),d=await t(s,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),c=await t(s,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new se("unavailable","the server refused a freshly minted token");return c}}}function Er(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(nc(e))}function yt(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 Tr(t){return new TextDecoder().decode(yt(t))}function nc(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var G=class extends Error{constructor(n,r,i,o,a){super(`${n} (${r}): ${i}`);this.reason=n;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Go=new WeakMap;function Do(t){return Go.get(t)??{}}var tc=new Set([408,429,500,502,503,504]),rc=6e4;function ic(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new ie(`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),i=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...i}:{modified:true,body:r.body,...i}}async put(e,n,r,i={}){return this.send({method:"PUT",path:e,body:n,signal:r,...xn(i)},i.replaySafe===true)}async post(e,n,r,i={}){return this.send({method:"POST",path:e,body:n,signal:r,...xn(i)},i.replaySafe===true)}async postBytes(e,n,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...xn(i)},i.replaySafe===true);return {bytes:oc(o.body),...o.invocationId===void 0?{}:{invocationId:o.invocationId}}}async patch(e,n,r,i={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...xn(i)},i.replaySafe===true)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...xn(r)},r.replaySafe===true)}async send(e,n){return (await this.sendRaw(e,n)).body}async sendRaw(e,n){let r=n?ic(this.options.maxRetries)+1:1,i=null;if(e.signal?.aborted)throw Lo(e.signal);for(let o=0;o<r;o++){if(o>0&&await this.backoff(o,i,e.signal),e.signal?.aborted)throw Lo(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(se.isAuthError(l)||ie.isRefusal(l)||e.signal?.aborted||ac(l))throw l;i=new G("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=sc(a);if(!tc.has(a.status))throw s;i=s;}throw i??new G("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let i=n?.retryAfterSeconds,o=i!==void 0?i*1e3:2**(e-1)*250,a=2**(e-1)*250,s=Math.min(Math.max(o,a),rc);return new Promise(l=>{let d=this.options.clock,m=false,c=false,p,g=()=>{m||(m=true,c&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,s),c=true,m&&d.clearTimeout(p);})}};function oc(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 xn(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function Lo(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function ac(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function sc(t){let e=dc(t),n=uc(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Go.set(e,r),e}var lc=new Map([["insufficient_funds","insufficient_funds"]]);function dc(t){let{status:e,body:n}=t,r=cc(n),i=t.retryAfterSeconds??pc(n),o=mc(n),a=o===void 0?void 0:lc.get(o);if(a!==void 0)return new G(a,e,r,void 0,o);switch(e){case 304:return new G("not_modified",e,r);case 400:case 422:return new G("invalid",e,r,void 0,o);case 403:return new G("forbidden",e,r,void 0,o);case 404:return new G("not_found",e,r,void 0,o);case 402:return new G("insufficient_funds",e,r,void 0,o);case 409:return new G("conflict",e,r,void 0,o);case 412:return new G("precondition_failed",e,r,void 0,o);case 413:return new G("too_large",e,r,void 0,o);case 429:return new G("rate_limited",e,r,i,o);default:return new G("unavailable",e,r,i,o)}}function cc(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 uc(t){let n=t?.error?.details;return n===null?void 0:n}function mc(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function pc(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 $o(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Fo(t,e,n,r,i,o){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/add`;return t.client.post(a,i,o?.signal)}async function qo(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function jo(t,e,n,r,i,o){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/claim`;return t.client.post(a,i,o?.signal)}async function No(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Uo(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Bo(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Vo(t,e,n,r,i){let o=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(o,i?.signal)}async function Ho(t,e,n,r,i){let o=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(o,i?.signal)}async function Wo(t,e,n,r){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(i,r?.signal)}async function Ko(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Jo(t,e,n,r,i,o){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/finalize`;return t.client.post(a,i,o?.signal)}async function zo(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 Yo(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.get(r,n?.signal)}async function Xo(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Qo(t,e,n,r,i){let o=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Zo(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),a=`/v1/inventory/${v(e)}/${v(n)}`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function ea(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/items/${v(r)}`;return t.client.get(o,i?.signal)}async function na(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let a=o.toString(),s=`/v1/leaderboards/${v(e)}/${v(n)}/${v(r)}`+(a?`?${a}`:"");return t.client.get(s,i?.signal)}async function ta(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/orders/${v(r)}`;return t.client.get(o,i?.signal)}async function ra(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}`;return t.client.get(o,i?.signal)}async function ia(t,e,n,r,i,o){let a=`/v1/inventory/${v(e)}/${v(n)}/catalogs/${v(r)}/recipes/${v(i)}/availability`;return t.client.get(a,o?.signal)}async function oa(t,e,n,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function Cr(t,e,n,r,i){let o=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function aa(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${v(e)}/friends`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function sa(t,e,n){let r=`/v1/showcase/friends/${v(e)}`;return t.client.get(r,n?.signal)}async function la(t,e,n){let r=`/v1/inbox/friend-challenges/${v(e)}`;return t.client.get(r,n?.signal)}async function da(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${v(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function ca(t,e){let n=`/v1/games/${v(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function ft(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function ua(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function ma(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function pa(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 ga(t,e,n,r){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(i,r?.signal)}async function ya(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function fa(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function ha(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})}async function ba(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function _a(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/platform-funded-game-inventory-purchases`;return t.client.post(o,r,i?.signal)}async function va(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function wa(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Sa(t,e){return t.client.get("/v1/characters",e?.signal)}async function Ra(t,e,n,r){let i=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(i,r?.signal)}async function ka(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/orders`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function xa(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),a=`/v1/saves/${v(e)}/${v(n)}`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function Aa(t,e){let n=new URLSearchParams;e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Pa(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i="/v1/friends"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ea(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ta(t,e,n){let r=`/v1/inbox/friend-challenges/${v(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function Ca(t,e,n,r){let i=`/v1/games/${v(t.gameId())}/matches/${v(e)}/end`;return t.client.post(i,n,r?.signal)}async function Ia(t,e,n,r,i,o){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/max`;return t.client.post(a,i,o?.signal)}async function Ma(t,e,n,r,i,o){let a=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.put(a,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Oa(t,e,n,r,i){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(o,r,i?.signal)}async function La(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/rewarded-placements/${v(r)}/availability`;return t.client.get(o,i?.signal)}async function Ga(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Da(t,e,n,r){let i=`/v1/characters/${v(e)}`;return t.client.patch(i,n,r?.signal)}async function $a(t,e,n,r,i,o){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/upload-url`;return t.client.post(a,i,o?.signal,{replaySafe:true})}async function Fa(t,e,n,r,i,o){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/reset`;return t.client.post(a,i,o?.signal)}async function qa(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.delete(r,n?.signal)}var U="gem-web-bridge",bt={min:1,max:1},an=65536,ja=8,ht=5e3,Na=1024;function Mr(t){return Object.freeze(Object.assign(Object.create(null),t))}var Ua=Mr({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.earnAllowanceChanged":30,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.engaged":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.walletDisplay":60,"gem.menu":60,"gem.menuSelect":60,"gem.requestShare":6,"gem.vibrate":600,"gem.frameStats":120,"gem.portraitBorders":60,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,"gem.requestFriendChallenge":12,"gem.friendChallengeResult":30,__malformed:60}),_t="__malformed";var gc=Mr({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.requestFriendChallenge":"friendChallenges","gem.friendChallengeResult":"friendChallenges","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.autoStartFailedEvent":"autoStartFailure","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.portraitBorders":"portraitBorders","gem.engaged":"engagement","gem.viewport":"viewport","gem.walletDisplay":"walletDisplay","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.earnAllowanceChanged":"earnAllowance","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings","gem.requestShare":"share","gem.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu"}),yc=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function Ba(t){let e=gc[t];if(e!==void 0)return e;for(let[n,r]of yc)if(t.startsWith(n))return r}function Or(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 fc(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 hc(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function bc(t){return /^[a-z_]+$/.test(t)}function Ir(t,e,n){if(e>ja)return `nesting deeper than ${ja}`;if(++n.nodes>ht)return `more than ${ht} values`;if(n.bytes>an)return `over the ${an} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=t;if(n.seen.has(i))return "a repeated or cyclic object reference";if(n.seen.add(i),Array.isArray(t)){if(t.length>Na)return `an array of ${t.length} entries, over the ${Na} limit`;n.bytes+=2;for(let s of t){let l=Ir(s,e+1,n);if(l)return l}return null}let o=Object.getPrototypeOf(t);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";n.bytes+=2;let a=t;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++n.nodes>ht)return `more than ${ht} values`;if(n.bytes+=s.length*3+4,n.bytes>an)return `over the ${an} byte limit`;let l=Ir(a[s],e+1,n);if(l)return l}return null}function _c(t){let e={nodes:0,bytes:0,seen:new Set},n=Ir(t,0,e);return n?`message contains ${n}`:e.bytes>an?`message is over the ${an} byte limit`:null}var vc={origin:[Or,"not a well-formed origin"],url:[fc,"not a safe absolute http(s) URL"],bcp47:[hc,"not a well-formed BCP 47 tag"],code:[bc,"not a code of lower-case letters and underscores"]};function Va(t,e,n){for(let r of e){let i=n===""?r.n:`${n}.${r.n}`,o=t[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let a=Ha(o,r,i);if(a)return a}return null}function Ha(t,e,n){switch(e.k){case "string":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e.max)return `${n}: exceeds ${e.max} characters`;if(e.f){let[r,i]=vc[e.f];if(!r(t))return `${n}: ${i}`}return null}case "int":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 "boolean":return typeof t=="boolean"?null:`${n}: expected boolean`;case "enum":{let r=e.v;return r.includes(t)?null:`${n}: not one of ${r.join("|")}`}case "object":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:Va(t,e.fs,n);case "json":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "array":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e.max)return `${n}: exceeds ${e.max} items`;let r=e.it,i=`${n}[]`;for(let o of t){if(o==null){if(r.o)continue;return `${i}: required`}let a=Ha(o,r,i);if(a)return a}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}function P(t,e){return n=>{let r=_c(n);if(r)return r;if(typeof n!="object"||n===null||Array.isArray(n))return "message: expected object";let i=n;return i.gem!==U?"gem: wrong protocol marker":i.type!==t?`type: expected ${t}`:Va(i,e,"")}}var wc=P("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"},{n:"unbidden",k:"boolean",o:1}]),Sc=P("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),Rc=P("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),kc=P("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),xc=P("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"},{n:"boost",k:"object",o:1,fs:[{n:"multipliers",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"currencyId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"multiplierBp",k:"int",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"int",o:1,lo:1,hi:7}]}]),Ac=P("gem.pause",[{n:"paused",k:"boolean"}]),Pc=P("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),Ec=P("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),Tc=P("gem.earnAllowanceChanged",[]),Cc=P("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]},{n:"reserved",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384},{n:"width",k:"int",lo:0,hi:16384},{n:"height",k:"int",lo:0,hi:16384}]}}]),Ic=P("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),Mc=P("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),Oc=P("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),Lc=P("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),Gc=P("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),Dc=P("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),$c=P("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Fc=P("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),qc=P("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),jc=P("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),Nc=P("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Uc=P("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Bc=P("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),Vc=P("gem.requestContext",[]),Hc=P("gem.gameContext",[{n:"context",k:"json"}]),Wc=P("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Kc=P("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),Jc=P("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),zc=P("gem.ready",[]),Yc=P("gem.engaged",[]),Xc=P("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Qc=P("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Zc=P("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),eu=P("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),nu=P("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),tu=P("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),ru=P("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),iu=P("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),ou=P("gem.audioState",[{n:"muted",k:"boolean"}]),au=P("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),su=P("gem.walletDisplay",[{n:"visible",k:"boolean"},{n:"currencies",k:"array",o:1,max:8,it:{n:"",k:"string",max:64}},{n:"score",k:"boolean",o:1}]),lu=P("gem.menu",[{n:"settings",k:"boolean"},{n:"items",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"id",k:"string",max:32},{n:"label",k:"string",max:40}]}}]),du=P("gem.menuSelect",[{n:"entry",k:"enum",v:["settings","item"]},{n:"id",k:"string",o:1,max:32}]),cu=P("gem.requestShare",[{n:"params",k:"array",max:16,it:{n:"",k:"object",fs:[{n:"key",k:"string",max:64},{n:"value",k:"string",max:512}]}}]),uu=P("gem.vibrate",[{n:"pattern",k:"array",max:99,it:{n:"",k:"int",lo:0,hi:1e4}}]),mu=P("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),pu=P("gem.portraitBorders",[{n:"name",k:"string",o:1,max:40}]),gu=P("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),yu=P("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),fu=P("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"reason",k:"string",o:1,max:64,f:"code"},{n:"purchaseId",k:"string",o:1,max:64}]),hu=P("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),bu=P("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),_u=P("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),vu=P("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),wu=P("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),Su=P("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),Ru=P("gem.requestFriendChallenge",[{n:"requestId",k:"string",max:64},{n:"playerId",k:"string",max:64},{n:"template",k:"string",max:64},{n:"params",k:"json",o:1}]),ku=P("gem.friendChallengeResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"string",o:1,max:64},{n:"param",k:"string",o:1,max:64},{n:"channel",k:"string",o:1,max:16},{n:"configVersion",k:"int",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:864e5},{n:"detail",k:"string",o:1,max:300}]),vt=Mr({"gem.handshake":wc,"gem.handshake.accept":Sc,"gem.token":Rc,"gem.token.denied":kc,"gem.player":xc,"gem.pause":Ac,"gem.prefs":Pc,"gem.cohorts":Ec,"gem.earnAllowanceChanged":Tc,"gem.viewport":Cc,"gem.deviceSettings":Ic,"gem.willTerminate":Mc,"gem.roomEvent":Oc,"gem.socketState":Lc,"gem.seatedEvent":Gc,"gem.autoStartFailedEvent":Dc,"gem.signalEvent":$c,"gem.dedicatedEvent":Fc,"gem.partyResult":qc,"gem.clusterTarget":jc,"gem.devtools":Nc,"gem.screenshot":Uc,"gem.screenshot.denied":Bc,"gem.requestContext":Vc,"gem.gameContext":Hc,"gem.signal":Wc,"gem.dedicatedOffer":Kc,"gem.partyRequest":Jc,"gem.ready":zc,"gem.engaged":Yc,"gem.progress":Xc,"gem.requestToken":Qc,"gem.requestLocalServer":Zc,"gem.localServer":eu,"gem.localServer.denied":nu,"gem.exit":tu,"gem.openExternal":ru,"gem.requestFullscreen":iu,"gem.audioState":ou,"gem.rewardCue":au,"gem.walletDisplay":su,"gem.menu":lu,"gem.menuSelect":du,"gem.requestShare":cu,"gem.vibrate":uu,"gem.frameStats":mu,"gem.portraitBorders":pu,"gem.error":gu,"gem.requestPurchase":yu,"gem.purchaseResult":fu,"gem.deviceSettings.put":hu,"gem.deviceSettings.result":bu,"gem.requestAd":_u,"gem.adResult":vu,"gem.requestSignIn":wu,"gem.signInResult":Su,"gem.requestFriendChallenge":Ru,"gem.friendChallengeResult":ku});var ye={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},An=class{constructor(e=ye){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Ua[e];if(n===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??n,a=Math.max(0,r-i),s=Math.min(n,o+a*n/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function Lr(t,e){return t.toLowerCase()===e.toLowerCase()}function wt(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Wa(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:wt(n.hostname)&&wt(r.hostname)}function Ka(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 St=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let i=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,o=i.find(s=>s.currencyId===e),a;return !o&&this.resolveCurrencyId&&(a=await this.resolveCurrencyId(e).catch(()=>{}),a!==void 0&&(o=i.find(s=>s.currencyId===a))),{currencyId:o?o.currencyId:a??e,total:o?o.total:null,...o?.buckets===void 0?{}:{buckets:o.buckets}}}};function Dr(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let i=r??{};typeof i.id!="string"||i.id===""||typeof i.threshold!="number"||!Number.isFinite(i.threshold)||n.push({id:i.id,threshold:i.threshold,points:typeof i.points=="number"?i.points:0,hidden:i.hidden===true,...typeof i.unlocked_at=="number"&&Number.isFinite(i.unlocked_at)?{unlockedAt:i.unlocked_at}:{},...i.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var Ja="inventory",sn=t=>typeof t=="number"?t:0,Pn=t=>typeof t=="string"?t:"";function Gr(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 za(t){let e=t??{};return {itemDefinitionId:Pn(e.item_definition_id),instanceId:Pn(e.instance_id),quantity:sn(e.quantity),acquiredAt:sn(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function xu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Gr(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(a=>{let s=a??{};return {bucket:Pn(s.bucket),balance:sn(s.balance)}}):void 0;return {currencyId:Pn(i.currency_id),total:sn(i.total),...o===void 0?{}:{buckets:o}}}),items:Gr(e.items,za),progressions:Gr(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:Pn(i.progression_definition_id),currentValue:sn(i.current_value),completionCount:sn(i.completion_count),isCompleted:i.is_completed===true,...Dr(i)}}),...n===void 0?{}:{etag:n}}}var Rt=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Ja}#buckets`:Ja;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let o=r.items.data.filter(a=>a.itemDefinitionId===e);if(o.length>0)return o}let i=await ea(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(i)?i.map(za):[]}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 Zo(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 xu(n)}};var Au={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},Pu=new Set(Object.keys(Au));function Ya(t){return typeof t=="string"&&Pu.has(t)?t:"error"}var Ge=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var Q=t=>typeof t=="string"?t:"",Eu=t=>typeof t=="string"?t:Q(t&&typeof t=="object"?t.type:void 0),ke=t=>typeof t=="number"?t:0;function Tu(t){let e=t??{};return {prerequisiteType:Q(e.prerequisite_type),referenceId:Q(e.reference_id),required:ke(e.required),current:ke(e.current)}}function En(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:Q(e.order_id),status:Q(e.status),...n===void 0?{}:{etag:n}}}function kt(){return crypto.randomUUID()}var Cu="recipe-usage",Xa=100;function xt(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:Q(e.currency_id),bucket:Q(e.bucket),delta:ke(e.delta),balanceAfter:ke(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:Q(e.item_definition_id),instanceId:Q(e.instance_id),delta:ke(e.delta),quantityAfter:ke(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:Q(e.progression_definition_id),delta:ke(e.delta),valueAfter:ke(e.value_after),completed:e.completed===true};default:return {kind:"other",type:Q(e.type)}}}function Iu(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:Q(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:ke(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(xt):[]}}function Mu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(Iu):void 0;return {orderId:Q(e.order_id),status:Q(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(xt):[],consumed:Array.isArray(e.consumed)?e.consumed.map(xt):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(xt):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Ou(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:Q(e.target_order_id)||Q(e.source_order_id),status:Q(e.status),purchaseId:Q(e.purchase_id),sourceOrderId:Q(e.source_order_id),price:{currencyId:Q(n.platform_currency_id),amount:ke(n.price)}}}function Lu(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:Q(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 Qa(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 At=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(()=>Bo(this.api,this.entity.type,this.entity.id,{operations:e.map(Qa),source:n.source??"play",nonce:kt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return En(r)}async createMany(e,n={}){return this.write(()=>Uo(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Qa),nonce:kt()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let o=await ia(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},a=typeof o.uses_remaining=="number"?o.uses_remaining:void 0,s=typeof o.cooldown_expires_at=="string"?o.cooldown_expires_at:void 0,l=Array.isArray(o.lock_reasons)?o.lock_reasons.map(Tu):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>Eu(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(Cu,[],async()=>{let n=await oa(this.api,this.entity.type,this.entity.id,{limit:Xa})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(Lu),truncated:r.length>=Xa}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>Ko(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:kt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...Mu(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,i]=await Promise.all([ma(this.api,n.signal===void 0?{}:{signal:n.signal}),ft(this.api,n.signal===void 0?{}:{signal:n.signal})]),o=e.payment.currencySlug.toLowerCase(),a=i.currencies.find(c=>c.currency_id.toLowerCase()===o||c.slug.toLowerCase()===o);if(a===void 0){let c=i.currencies.map(p=>p.slug);throw new Ge("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let s=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(s===void 0)throw new Ge("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=s.platform_prices.find(c=>c.platform_currency_id===a.currency_id);if(l===void 0){let c=g=>i.currencies.find(y=>y.currency_id===g)?.slug??g,p=s.platform_prices.map(g=>`${c(g.platform_currency_id)} ${g.price}`);throw new Ge("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${a.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Ge("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>_a(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:a.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:kt(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return Ou(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let i=await this.write(()=>Fo(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return En(i)}async maxProgression(e,n,r){let i=await this.write(()=>Ia(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return En(i)}async claimProgression(e,n){let r=await this.write(()=>jo(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return En(r)}async resetProgression(e,n){let r=await this.write(()=>Fa(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return En(r)}async write(e){return this.cache.invalidate(),e()}};var $r=t=>typeof t=="string"?t:"",Gu=t=>typeof t=="number"?t:0;function Za(t){let e=t??{};return {orderId:$r(e.order_id),status:$r(e.status),source:$r(e.source),createdAt:Gu(e.created_at)}}var Pt=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await ka(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(Za):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await ta(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Za(r)}};var es=t=>typeof t=="number"?t:0,Du=t=>typeof t=="string"?t:"";function $u(t){let e=t??{};return {progressionDefinitionId:Du(e.progression_definition_id),currentValue:es(e.current_value),completionCount:es(e.completion_count),isCompleted:e.is_completed===true,...Dr(e)}}var Et=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let i=(await this.inventory.snapshot()).progressions.data.find(o=>o.progressionDefinitionId===e);if(i&&i.achievementsUnavailable!==true)return i;try{let o=await ra(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return $u(o)}catch{return i??null}}};var Tt=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,i){this.rebind();let o=n.length===0,a=o?e:e+"\0"+n.join("\0"),s=this.slots.get(a);if(s){let c=s.filledAt;if(c!==void 0&&(i===void 0||this.clock.now()-c<=i))return Promise.resolve(s.value);if(s.inFlight)return s.inFlight}let l=s??{};this.slots.set(a,l);let d=this.generation,m=r().then(c=>(o&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(a)===l&&this.slots.delete(a));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function Fr(t){let e=i=>new RegExp(`<${i}>([^<]{0,300})</${i}>`).exec(t)?.[1]?.trim()||void 0,n=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(n.length>0)return n.join(" \u2014 ");let r=t.trim();return r?r.slice(0,300):""}async function qr(t){try{let e=Fr(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var oe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},Fu=3e4,ns="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",qu=/^[A-Za-z0-9_]{1,64}$/;function xe(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(!qu.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function ts(t,e){let n=new AbortController,r=AbortSignal.timeout(e),i=()=>n.abort(r.reason),o=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",i,{once:true}),t?.addEventListener("abort",o,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",i),t?.removeEventListener("abort",o);}}}function jr(t,e){return t.aborted&&e?.aborted!==true}var ju=new Set(["x-ms-blob-type"]),Nu=/^[ -~]+$/;function Uu(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,i]of Object.entries(t)){let o=r.toLowerCase();if(!ju.has(o))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof i!="string"||!Nu.test(i))throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(o in n)throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);n[o]=i;}return n}function Nr(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 Ur(t){return t?.reason==="not_found"}var Ct=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let i;try{i=JSON.stringify(n);}catch(o){throw new oe("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}. Retrying stores the same unserialisable value.`)}if(i===void 0)throw new oe("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(i),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){let i=r.contentType??"application/octet-stream",o=this.budget(r.timeoutMs),a=ts(r.signal,o);try{let s=await $a(this.api,this.entity.type,this.entity.id,xe(e),{size_bytes:n.byteLength,content_type:i,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:a.signal});if(typeof s.upload_url!="string"||typeof s.session_id!="string")throw new oe("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=Uu(s.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(s.upload_url,{method:"PUT",headers:{"content-type":i,...l},body:n,credentials:"omit",signal:a.signal});}catch(c){throw jr(a.signal,r.signal)?this.timeout("upload",o):new oe("upload_failed",`${ns} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await qr(d);throw new oe("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+c:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+c)}return Nr(await Jo(this.api,this.entity.type,this.entity.id,xe(e),{session_id:s.session_id},{signal:a.signal}))}catch(s){throw this.rethrow(s,r.signal,a.signal,"save",o)}finally{a.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(i){throw new oe("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${i}`)}}async getBytes(e,n={}){let r=this.budget(n.timeoutMs),i=ts(n.signal,r);try{let o;try{let l=await Cr(this.api,this.entity.type,this.entity.id,xe(e),{signal:i.signal});if(!l.modified)return null;o=l.body;}catch(l){if(Ur(l))return null;throw l}if(typeof o.download_url!="string")throw new oe("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),s;try{s=await a(o.download_url,{credentials:"omit",signal:i.signal});}catch(l){throw jr(i.signal,n.signal)?this.timeout("download",r):new oe("download_failed",`${ns} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await qr(s);throw new oe("download_failed",`the save download answered ${s.status}. `+(s.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await s.arrayBuffer())}catch(o){throw this.rethrow(o,n.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,n={}){try{let r=await Cr(this.api,this.entity.type,this.entity.id,xe(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Nr(r.body):null}catch(r){if(Ur(r))return null;throw r}}async list(e={}){let n=await xa(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(Nr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Ho(this.api,this.entity.type,this.entity.id,xe(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Ur(r))throw r}}budget(e){return e??this.options.timeoutMs??Fu}timeout(e,n){return new oe("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,i,o){return e instanceof oe?e:jr(r,n)?this.timeout(i,o):e}};function Bu(t){try{return Tr(t)}catch{return t}}function Br(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"?Bu(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var It=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await Ra(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>Br(i)):[]}async get(e,n={}){try{let r=await Qo(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?Br(r.body,r.etag):null}catch(r){if(rs(r))return null;throw r}}async put(e,n,r={}){let i=await Ma(this.api,this.entity.type,this.entity.id,e,{value:Er(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Br(i)}async delete(e,n){try{await Vo(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!rs(r))throw r}}};function rs(t){return t?.reason==="not_found"}function Mt(t,e,n={}){let r=new Tt(ye,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let i=new Rt(t,e,r);return {settings:new It(t,e),inventory:i,saves:new Ct(t,e,n.saves??{}),currencies:new St(i,n.resolveCurrencyId),mutations:new At(t,e,r),orders:new Pt(t,e),progressions:new Et(t,e,i)}}var Vr={type:"players",id:"me"};var qe=t=>typeof t=="string"?t:"",ln=t=>typeof t=="number"?t:0;function Ot(t,e){let n=e??{},r=qe(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:qe(n.player_id),gameId:qe(n.game_id),channel:qe(n.channel)||"release",name:qe(n.name),slotIndex:ln(n.slot_index),isActive:n.is_active!==false,createdAt:qe(n.created_at),updatedAt:qe(n.updated_at)}}var Lt=class{constructor(e,n,r,i){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=i;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=Mt(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 Sa(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>Ot(this.scope,i)):[]}async get(e,n){let r=await Yo(this.api,e,n===void 0?{}:{signal:n});return Ot(this.scope,r)}async create(e){let n=await No(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Ot(this.scope,n)}async update(e,n,r){let i=await Da(this.api,e,{name:n},r===void 0?{}:{signal:r});return Ot(this.scope,i)}async delete(e,n){await qa(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await ya(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:ln(r?.total_slots),availableSlots:ln(r?.available_slots),activeCharacterCount:ln(r?.active_character_count),defaultMaxSlots:ln(r?.default_max_slots),purchasedExtraSlots:ln(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var fe=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function Oe(t){return new fe(t)}var dn={toPlain(t){return fe.unwrap(t)},compare(t,e,n){let r=t instanceof fe?fe.unwrap(t):t,i=e instanceof fe?fe.unwrap(e):e,o;try{o=new Intl.Collator(n);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(t,e){let n=t instanceof fe?fe.unwrap(t):t,r=e instanceof fe?fe.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var cn=t=>typeof t=="string"?t:"";function Gt(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:cn(e.transfer_id),status:cn(e.status),sourceEntityId:cn(e.source_entity_id),targetEntityId:cn(e.target_entity_id),...n===void 0?{}:{message:Oe(n)},createdAt:cn(e.created_at),expiresAt:cn(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Vu(){return crypto.randomUUID()}var Dt=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 ba(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:Vu()},e.signal===void 0?{}:{signal:e.signal});return Gt(n)}async list(e={}){let r=await Ea(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Gt):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await fa(this.api,e,n===void 0?{}:{signal:n});return Gt(r)}async accept(e,n){return this.resolve(()=>$o(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>Ga(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>qo(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Gt(await e())}};var Hu=t=>typeof t=="string"?t:"",Wu=t=>typeof t=="string"&&t?t:void 0,Ku=t=>typeof t=="number"?t:void 0;function is(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 Ju(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new de("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 de("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Ku(e.version);if(r===void 0)throw new de("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,m)=>{let c=Hu(l.id);if(!c)throw new de("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},o=n("items");o.forEach((l,d)=>i(l??{},"items",d));let a=n("currencies");a.forEach((l,d)=>i(l??{},"currencies",d));let s=t;return {...s,version:r,hash:typeof s.hash=="string"?s.hash:"",items:o,currencies:a,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 s.kv=="object"&&s.kv!==null&&!Array.isArray(s.kv)?s.kv:{},item:is(o),currency:is(a)}}var de=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},os=10*1024*1024,as=15e3,ss=new Set(["dev","test","release"]);function zu(t){if(!ss.has(t))throw new de("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...ss].join(", ")}. gem-api would reject the assignment read.`);return t}var $t=t=>typeof t=="number"?t:0,Hr=t=>typeof t=="string"?t:"";function Yu(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let i=r??{},o=typeof i.rarity_tier=="string"?i.rarity_tier:void 0;return {entryId:Hr(i.entry_id),weight:$t(i.weight),dropRate:$t(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:Hr(e.loot_table_id),name:Hr(e.name),rollCount:$t(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:$t(e.total_weight),entries:n}}var Ft=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=null;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,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=null,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new de("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let i=this.dropRatesByConfig.get(r);i===void 0&&(i=new Map,this.dropRatesByConfig.set(r,i));let o=i.get(e);if(o!==void 0)return o;let a=(async()=>{let s=await Xo(this.api,e,n===void 0?{}:{signal:n});return Yu(s)})().catch(s=>{throw i?.get(e)===a&&i.delete(e),s});return i.set(e,a),a}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??as),n;try{let l=await zo(this.api,zu(this.channel()),{signal:e});if(!l.modified)throw new de("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof de)throw l;if(l?.reason==="not_found")return null;throw l}let r=Wu(n.config_url);if(r===void 0)return null;let i=this.options.fetch??globalThis.fetch.bind(globalThis),o;try{o=await i(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new de("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??as}ms`):new de("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!o.ok){let l=await o.text().then(d=>Fr(d)).catch(()=>"");throw new de("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await o.text();if(a.length>os)throw new de("config_too_large",`the config document is ${a.length} bytes, over the ${os} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new de("config_malformed",`config document is not JSON: ${String(l)}`)}return Ju(s)}};var ls=400,Ae=t=>typeof t=="string"?t:"",Xu=/(?:Z|[+-]\d{2}:?\d{2})$/i;function je(t){let e=Ae(t);if(!Xu.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Qu=/^[0-9a-f]{1,64}$/,Zu=/^[0-9a-f]{16}$/,em=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,nm=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Wr(t){let e=Ae(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,i,o]=[Number(n[1]),Number(n[2]),Number(n[3])],a=new Date(Date.UTC(r,i-1,o));return a.getUTCFullYear()===r&&a.getUTCMonth()===i-1&&a.getUTCDate()===o?e:void 0}var tm=4096,rm=new TextEncoder;function im(t){let e=Ae(t.challenge_data),n=Ae(t.challenge_data_hash);return e===""||!Zu.test(n)?{}:rm.encode(e).length>tm?{}:{data:e,dataHash:n}}function om(t){let e=t??{},n=je(e.period_start_at),r=je(e.period_ends_at);if(n===0||r===0)return;let i=Ae(e.slug),o=Ae(e.seed),a=Wr(e.period_local_date),s=Ae(e.boundary),l=Ae(e.reset_time);return {id:Ae(e.progression_definition_id),...i===""?{}:{slug:i},window:Ae(e.window),periodStartAt:n,periodEndsAt:r,...a===void 0?{}:{periodLocalDate:a},boundary:em.test(s)?s:"",resetTime:nm.test(l)?l:"",seed:Qu.test(o)?o:"",...im(e)}}function un(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 qt(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(om).filter(n=>n!==void 0):[]}var Tn=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;un(n);let r=await wa(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return qt(r)}};function Ne(t){return typeof t=="string"&&t!==""?t:void 0}var ds=new Set(["localhost","127.0.0.1","[::1]"]);function Kr(t){let e=Ne(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:"&&ds.has(n.hostname)))return e}function am(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},i=Ne(r.item_id),o=Kr(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function ve(t){let e=t??{},n=Ne(e.player_id),r=Ne(e.display_name),i=Ne(e.discriminator),o=Ne(e.display_tag),a=Ne(e.avatar_icon_id),s=Kr(e.avatar_icon_url);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:Oe(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:Oe(o)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:am(e.badges)}}var sm=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function lm(t){if(t===void 0)return;let e=Kr(t);if(e===void 0)return;let n=new URL(e);return ds.has(n.hostname)||sm.has(n.origin)?e:void 0}var cs=100,ps=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Jr(t){let{periodsBack:e,period:n,playerId:r}=t;if(un(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!ps.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 gs(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!ps.test(e))return;let n=Wr(t.period_local_date),r=je(t.period_start_at),i=je(t.period_ends_at),o=r>0&&i>0;return {id:e,...n===void 0?{}:{localDate:n},...o?{startAt:r,endsAt:i}:{},opensAt:je(t.opens_at),closesAt:je(t.closes_at),final:t.final===true}}var Cn=t=>typeof t=="string"?t:"",mn=t=>typeof t=="number"?t:0,In=t=>typeof t=="string"?t:void 0,dm=t=>typeof t=="number"?t:void 0,ys={player:"players",character:"characters"};function cm(t,e){let n=t??{},r=In(n.entity_id),i=typeof n.entity_type=="string"&&Object.hasOwn(ys,n.entity_type)?n.entity_type:void 0,o=fs(n.stats),a=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,s=e?n.is_viewer===true:void 0;return {...ve(n),rank:mn(n.rank),occurredAt:mn(n.occurred_at),...s===void 0?{}:{isViewer:s},...r===void 0?{}:{entityId:r},...i===void 0?{}:{entityType:i},...o===void 0?{}:{stats:o},...a===void 0?{}:{properties:a}}}function us(t,e){let n=t??{},r=In(n.bucket_1),i=In(n.bucket_2),o=dm(n.update_frequency_seconds),a=gs(n);return {leaderboardType:Cn(n.leaderboard_type),runType:Cn(n.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(n.entries)?n.entries.map(s=>cm(s,e)):[],generatedAt:mn(n.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...a===void 0?{}:{period:a}}}function ms(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=fs(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:mn(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function fs(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 um(t,e,n){let r=t??{},i=In(r.bucket_1),o=In(r.bucket_2),a=gs(r);return {leaderboardType:Cn(r.leaderboard_type),runType:Cn(r.run_type),entityType:e,entityId:n,...i===void 0?{}:{bucket1:i},...o===void 0?{}:{bucket2:o},entries:Array.isArray(r.entries)?r.entries.map(ms).filter(s=>s!==void 0):[],personalBest:ms(r.personal_best)??null,totalRuns:mn(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:mn(r.generated_at),...a===void 0?{}:{period:a}}}var Mn=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Jr(n),i=await da(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 us(i,false)}async friends(e,n={}){let r=Jr(n),i=await aa(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 us(i,true)}async mine(e,n={}){return this.#t(e,"player","me",n)}async character(e,n,r={}){return this.#t(e,"character",n,r)}async#t(e,n,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>cs)throw new TypeError(`limit must be an integer between 1 and ${cs}, got ${String(l)}`)}let o=Jr(i),a=await na(this.#e,e,ys[n],r,{...o,...i.bucket1===void 0?{}:{bucket_1:i.bucket1},...i.bucket2===void 0?{}:{bucket_2:i.bucket2},...i.limit===void 0?{}:{limit:i.limit},...i.signal===void 0?{}:{signal:i.signal}}),s=n==="player"&&r==="me"&&Cn((a??{}).entity_id)||r;return um(a,n,s)}};var jt=t=>typeof t=="string"?t:"",zr=t=>typeof t=="number"?t:0;function hs(t){let e=t??{};return {playerId:jt(e.player_id),key:jt(e.key),value:e.value,updatedAt:zr(e.updated_at)}}function mm(t){let e=t??{};return {...ve(e),playerId:jt(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:zr(e.updated_at)}}function pm(t){return t?.reason==="not_found"}var On=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let i=await sa(this.api,xe(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:jt(i.key),entries:Array.isArray(i.entries)?i.entries.map(mm):[],generatedAt:zr(i.generated_at)}}async of(e,n,r={}){try{return hs(await ga(this.api,e,xe(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(pm(i))return null;throw i}}async set(e,n,r={}){if(xe(e),n===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(n);}catch(o){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}.`,{cause:o})}let i=await this.selfPlayerId();return hs(await Oa(this.api,i,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await Wo(this.api,r,xe(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var gm="gemChallenge",bs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function _s(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(gm)??void 0}catch{return}}var Ue=class extends G{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(n))i!==void 0&&Object.assign(this,{[r]:i});}},Nt=t=>typeof t=="string"?t:void 0;function vs(t){let e=t??{};return {...ve(e),playerId:Nt(e.player_id)??""}}function ws(t){let e=t.has_more===true?Nt(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function ym(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(vs):[],...ws(e)}}var Yr=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function fm(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 Ss(t){let e=t??{},n=Yr(e.opened_at),r=Yr(e.answered_at);return {id:Nt(e.item_id)??"",from:vs(e.sender),template:Nt(e.template)??"",params:fm(e.params),createdAt:Yr(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function hm(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(Ss):[],...ws(e)}}function bm(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Ln=class{#e;#t;#o;constructor(e,n={}){this.#e=e,this.#t=n.challenge,this.#o=n.launchedChallengeId;}async list(e={}){let n=await Pa(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return ym(n)}challenge(e){return this.#t===void 0?Promise.resolve({outcome:"unavailable"}):this.#t(e)}async inbox(e={}){let n=await Aa(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return hm(n)}async launchedChallenge(e={}){let n=this.#o;if(n===void 0||!bs.test(n))return null;try{return Ss(await la(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(bm(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!bs.test(e))throw new G("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await Ta(this.#e,e);}};var _m=0;function Pe(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++_m)}-${String(Date.now())}-${t}`}}var vm=12e4,Rs=8,wm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Sm=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Gn(t,e,n={}){return new Ue(new G("invalid",400,e,void 0,t),n)}function Rm(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function km(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!wm.test(e))return {error:Gn("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!Sm.test(n))return {error:Gn("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(!Rm(r))return {error:Gn("param_invalid","params must be a plain object of strings and integers")};let i={},o=Object.keys(r);for(let a of o){let s=r[a];if(typeof s=="string"||typeof s=="number"&&Number.isSafeInteger(s)){Object.defineProperty(i,a,{value:s,enumerable:true,writable:true,configurable:true});continue}return {error:Gn("param_invalid",`params.${a} must be a string or a safe integer`,{param:a})}}return o.length>Rs?{error:Gn("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(Rs)}`)}:{playerId:e,template:n,params:i}}function xm(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 Ue(new G("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new Ue(new G("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function Am(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function ks(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=km(n);if("error"in r)return Promise.reject(r.error);let i=`challenge-${Pe()}`;return new Promise((o,a)=>{let s={},l=m=>{e.delete(i)&&(t.clock.clearTimeout(s.timer),"error"in m?a(m.error):o(m.outcome));};e.set(i,l),s.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??vm);let d=false;try{d=t.bridge.requestFriendChallenge(i,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(n){let r=e.get(n.requestId);if(r===void 0){t.onDropped?.(`gem.friendChallengeResult (${Am(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(xm(n));}}}var Ut=t=>typeof t=="string"?t:void 0;function Pm(t){let e=t??{},n=Ut(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Ut(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Bt=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await ft(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let a=Pm(o);a!==void 0&&i.push(a);}return i}},Xr=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function Em(t){let e=t??{},n=Ut(e.currency_id);if(n===void 0||n==="")return;let r=Xr(e.limit),i=Math.min(Xr(e.earned),r),o=Math.min(Xr(e.remaining),r-i),a=e.period_days,s=typeof a=="number"&&Number.isInteger(a)&&a>=1?a:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Ut(e.currency_slug)??"",currencyId:n,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:s,...d===void 0?{}:{resetsAt:d}}}function xs(t){let e=new Set,n=r=>{t?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let i=r();typeof i?.then=="function"&&i.then(void 0,n);}catch(i){n(i);}}}}var Vt=class{#e;#t;#o;constructor(e,n,r){this.#e=e,this.#t=n,this.#o=r;}async get(e={}){let r=(await ca(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let a=Em(o);a!==void 0&&i.push(a);}return i}on(e,n){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#t?.on(n)??(()=>{})}},Dn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Bt(e),this.earnAllowance=new Vt(e,n,r);}};var Qr=t=>typeof t=="string"?t:"",As=t=>typeof t=="number"?t:0;function Tm(t){let e=t??{};return {key:Qr(e.key),visibility:Qr(e.visibility),value:e.value,updatedAt:As(e.updated_at)}}function Cm(t){let e=t??{};return {...ve(e),playerId:Qr(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Tm):[],generatedAt:As(e.generated_at)}}function Im(t){return t?.reason==="not_found"}var $n=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return Cm(await ua(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Im(r))return null;throw r}}};var Mm=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]]),Ht=class extends G{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:Mm.get(this.code))??super.retryable}},Be=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Om(e),i;try{i=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(o){throw o instanceof G?Gm(o):o}return Lm(i)}};function Om(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 ie(`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 ie(`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 Lm(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 Gm(t){let{details:e,invocationId:n}=Do(t),i=e?.untrusted?.message,o=e?.reason;return new Ht(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...t.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}var Dm=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Zr="gem_";function Ps(t){return t.startsWith(Zr)}var Es=1e4,Ts=50,$m=500,Fm=65536-4*1024,qm=24*1024;function Cs(t){let e={},n={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=i:typeof i=="number"&&Number.isFinite(i)&&(n[r]=i);return {dimensions:e,measures:n}}var Is=t=>typeof t=="number"?t:0,jm=t=>typeof t=="string"?t:"";function ei(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function Nm(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:Is(o.index),code:jm(o.code)}}):[];return {accepted:Is(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function ni(){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 Um(t){return t?.retryable===true}var Fn=class{#e;#t;#o;#y;#n=[];#f={};#a=0;#s=null;#h=false;#b=false;#_=false;#r=false;#v=null;#l=null;#d=false;#i=false;#m=false;#w=false;#S=false;constructor(e){this.#e=e,this.#t=e.options?.enabled!==false,this.#o=Math.max(Es,e.options?.flushIntervalMs??Es),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??$m));}track(e,n={}){if(!(!this.#t||this.#r)){if(Ps(e)){this.#S||(this.#S=true,this.#g(`[gem] analytics: '${e}' was not recorded \u2014 the gem_ prefix is reserved for the platform's own events, which the SDK emits for you. Name your event something else.`));return}this.#R(e,Cs({...this.#f,...n}));}}setContext(e){this.#f={...this.#f,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return ei();let n=this.#E();if(n===null||n==="")return this.#n.length>0&&!this.#w&&(this.#w=true,this.#g("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),ei();if(this.#k(),this.#n.length===0)return ei();let r=e.keepalive===true;this.#u();let i=this.#n.splice(0,this.#A(r)),o=this.#a;this.#a=0;let a=Math.round(this.#e.clock.now()),s={batch_id:ni(),sent_at_ms:a,events:i.map(d=>Ms(d,a))},l={client:this.#e.client(),gameId:()=>n};this.#_=true;try{let d=await ha(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=Nm(d,o);return this.#P(m),m}catch(d){throw Um(d)?this.#x(i,o):this.#g(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#_=false,this.#n.length>0&&this.#c();}}trackPlatform(e,n={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#R(e,Cs(n));}hold(){this.#r||this.#l!==null||(this.#i=true,this.#u());}release(){if(!this.#i||this.#r)return;this.#i=false;let e=this.#e.clock.now(),n=this.#n.map(r=>({...r,atMs:e}));this.#n=n,this.#m&&(this.#m=false,this.#l=e,this.#d=false,this.#n.unshift({uid:ni(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#n.length>=Ts?this.#p():this.#n.length>0&&this.#c();}get held(){return this.#i}startSession(){if(!(this.#r||this.#l!==null)){if(this.#i){this.#m=true;return}this.#l=this.#e.clock.now(),this.#d=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#d)return;if(this.#d=true,this.#i){this.#m=false,this.#n=[],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.#p({keepalive:true});}setPaused(e){this.#r||e===this.#h||(this.#h=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#n.length>0&&this.#c());}setHidden(e){this.#r||e===this.#b||(this.#b=e,e?this.#u():this.#n.length>0&&this.#c());}dispose(){this.#r=true,this.#u(),this.#n=[],this.#a=0;}get pending(){return this.#n.length}#R(e,n){let{dimensions:r,measures:i}=n;for(this.#k();this.#n.length>=this.#y;)this.#n.shift(),this.#a+=1;this.#n.push({uid:ni(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#n.length>=Ts?this.#p():this.#c();}#p(e={}){this.flush(e).catch(()=>{});}#x(e,n){for(this.#n=[...e,...this.#n],this.#a+=n;this.#n.length>this.#y;)this.#n.shift(),this.#a+=1;}#A(e){let n=e?qm:Fm,r=Math.min(this.#n.length,100),i=128;for(let o=0;o<r;o+=1){let a=this.#n[o];if(a===void 0)break;if(i+=JSON.stringify(Ms(a,0)).length+1,i>n)return Math.max(1,o)}return r}#c(){this.#s!==null||this.#h||this.#b||this.#i||this.#r||this.#_||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#p();},this.#o));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#k(){let e=this.#T();e===null||e===""||(this.#v!==null&&this.#v!==e&&(this.#n=[],this.#a=0,this.#l=null,this.#d=false),this.#v=e);}#P(e){for(let n of e.rejected)this.#g(`[gem] analytics: an event was refused (${n.code}). `+Bm(n.code));}#g(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#E(){try{return this.#e.gameId()}catch{return null}}#T(){try{return this.#e.playerId()}catch{return null}}};function Ms(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function Bm(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 me(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function qn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=me(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Vm=2e3,Hm=5e3;function Ls(t){let e=[],n=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=c=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(c));},m=t.clock.setTimeout(()=>{n=true,a([]);},t.timeoutMs??Vm);});return r={promise:s,settle:a},s};return {resolveList:o,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(a=>a[0])},refresh(a){return !Os(e,a)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{i.delete(d)&&(t.clock.clearTimeout(l),s(m));};i.set(d,a),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??Hm);})},accept(a,s){let l=qn(s),d=me(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...i])Os(m,p)||c(m);}}}}function Os(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Wm=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),_=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="DedicatedServerError",this.retryable=Wm.has(n),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var Gs=["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"],Km=new Set(Gs);function pn(t){return typeof t=="string"&&Km.has(t)?t:"unknown"}var Wt="webrtc_dedicated",oi=["universal","mobile","web"];var Jm="p2p_unavailable",zm="capacity_unavailable",Ym=2,Ds=3e4,$s=1e3,Fs=2e4;async function ai(t){let e=me(t.clusterTargetId),n=t.nextClusterTarget,r=0,i=t.clock??ye,o=t.retry??{},a=o.budgetMs??Ds,s=o.maxDelayMs??Fs,l=o.initialDelayMs??$s,d=i.now(),m=d+a,c=0;for(;;){c++;try{let p=await ci(t.signal,"while allocating",()=>t.client.post(`${Ns(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Xm(p)||a<=0)throw p;if(p.status===503&&p.code===Jm)throw new _("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===zm?r+1:0,n!==void 0&&r>=Ym){let A=n;n=void 0;let C=me(await A());C!==void 0&&(e=C,r=0);}let g=Math.min(s,l*2**(c-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),S=Math.max(g/2,y)+Math.random()*(g/2);if(i.now()+S>m)throw Qm(t,p,c,i.now()-d,a);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:a,nextAttemptInMs:S,status:p.status,message:p.message}),await Kt(i,S,t.signal),t.signal?.aborted)throw ii("while waiting to allocate")}}}function Xm(t){return t instanceof G?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Qm(t,e,n,r,i){let o=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new _("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${o}: ${e.message}`,{cause:e}):new _("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${o}: ${e.message}`,{cause:e})}var Zm=12e4,ep=1e3;async function si(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??ep,i=t.timeoutMs??Zm,o=e.now()+i,a=qs(t),s={seen:t.knownToExist===true};for(;;){let l=await js(t,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new _("timeout",`match ${n} was still ${l.status} after ${i}ms`);await Kt(e,r,t.signal);}}async function li(t){return (await js(t,qs(t),{seen:t.knownToExist===true})).outcome}function qs(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Ns(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function js(t,e,n){let{matchId:r}=t,i=t.clock.now(),o;try{o=await ci(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(a){if(a instanceof G&&a.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(n.seen=true,o.status==="ready")return {status:"ready",outcome:np(r,o,i)};if(o.status==="failed"){let a=o.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:pn(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function di(t){let e=await ci(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||n.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function ci(t,e,n){if(t?.aborted)throw ii(e);try{return await n()}catch(r){throw t?.aborted?ii(e,r):r}}function ii(t,e){return new _("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function np(t,e,n){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:n+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function Ns(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Kt(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{t.clearTimeout(o),n?.removeEventListener("abort",i),r();},o=t.setTimeout(i,e);n?.addEventListener("abort",i);})}function Us(t){return typeof t=="string"&&t.trim()!==""}function Jt(t,e){return Us(t)?t.trim():Us(e)?e:null}var zt="0.1.0-beta",Bs="0-beta",gn="web",tp=/^(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 rp(t){let e=tp.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Vs(t,e){let n=ip(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:zt};let i=rp(r);if(i===null)throw new _("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${zt}' for it.`);if(i!==Bs)throw new _("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Bs}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${zt}' for it.`);return {...t,platform:n,engineVersion:r}}function ip(t,e){if(t===void 0||t===gn)return gn;if(!oi.includes(t))throw new _("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${oi.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${gn}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${gn}' 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.`),gn}var op="join",ap="welcome",sp="rejected",Hs=25e3,lp=1e3,ui=1;function mi(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var dp={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 pi(t){let e=typeof t=="string"?t:"unknown";return new _(dp[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function jn(t){let{channel:e,clock:n}=t;return new Promise((r,i)=>{let o=false,a=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Hs),s=n.setTimeout(()=>w(new _("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(a,lp)),l=S=>{let A=S.data;if(typeof A!="string"){c(A);return}let C;try{C=JSON.parse(A);}catch{c(A);return}if(o){c(A);return}if(C.t===ap){let b=mi(C.heartbeat_interval);y({...typeof C.player_id=="string"?{playerId:C.player_id}:{},...typeof C.match_id=="string"?{matchId:C.match_id}:{},...b===void 0?{}:{heartbeatIntervalMs:b}});return}if(C.t===sp){w(pi(C.reason));return}c(A);},d=()=>{w(new _("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new _("aborted","the caller aborted during the join exchange"));},c=S=>{o&&t.onMessage?.(S);},p=()=>{n.clearTimeout(s),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=S=>{o=true,p(),t.onMessage===void 0&&g(),r({welcome:S,detach:g});},w=S=>{o||(o=true,p(),g(),i(S));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:op,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:ui}:{}}));}catch(S){w(new _("connection_failed",`the join frame could not be sent on the open channel: ${String(S)}`,{cause:S}));}})}var Ve=1,Nn=2,gi=4,hi=8,cp=2,up=1e3,bi="heartbeat timeout",Un="gem-uu",Yt=2,Ks="gem_transports";function yn(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!mp(r)||e.includes(r)||e.push(r);}return e}function mp(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function Bn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Ks];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 Xt(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Js=new TextEncoder,zs=new TextDecoder;function _i(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function vi(t){let e=0;return t?.reliable===false&&(e|=Ve),t?.ordered===false&&(e|=Nn),e}function wi(t){return {reliable:(t&Ve)===0,ordered:(t&Nn)===0}}var Si={reliable:true,ordered:true};function Ys(t){return JSON.stringify({t:"join",credential:t,wire:Yt,heartbeat:ui})}function Xs(t){let e;try{e=JSON.parse(t);}catch{throw new _("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=mi(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"?pi(e.reason):new _("join_refused","the server answered the join out of protocol")}function Qt(){return typeof globalThis.WebTransport=="function"&&Ri===null}function Zt(){return Ri}var Ri=null;var Ws="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function pp(t){let e=yt(t);if(e.byteLength!==32)throw new _("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var yi=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new _("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let a=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function fi(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 Vn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new _("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new s(t.url):new s(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:pp(t.certHashBase64)}]});}let r=n,i=s=>{try{r.close();}catch{}throw s},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Ri=Ws,i(new _("connection_failed",`${Ws}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new _("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return i(new _("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(fi(gi,Js.encode(Ys(t.credential))));let c=new yi,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),a]);if(y.done||y.value===void 0)return i(new _("connection_failed","the control stream closed before the join was answered"));for(let w of c.push(y.value)){g=Xs(zs.decode(w.payload));break}}return {link:gp(r,m,p,c,t.log??(y=>console.warn(y)),Zs(g,t.clock)),welcome:g}}catch(s){return i(s)}}function gp(t,e,n,r,i,o){let a,s,l=false,d=y=>{if(!l){l=true,m.stop();try{t.close();}catch{}s?.(y);}},m=xi(o,()=>d(bi)),c=(y,w)=>{m.heard(),(y&hi)===0&&a!==void 0&&((y&gi)!==0?a(zs.decode(w),Si):a(w,wi(y)));};(async()=>{try{for(;;){let y=await n.read();if(y.done||y.value===void 0)break;for(let w of r.push(y.value))c(w.flags,w.payload);}}catch{}d("stream closed");})();let p,g;try{let y=t.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let w=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let S=await w.read();if(S.done||S.value===void 0)break;let A=S.value;A.byteLength!==0&&c((A[0]??0)|Ve|Nn,A.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,i(`[gem] webtransport datagram lane unusable (${Xt(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(Qs(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,w){if(l)return;if(typeof y=="string"){e.write(fi(gi,Js.encode(y))).catch(()=>d("write failed"));return}let S=vi(w);if((S&Ve)!==0&&g!==void 0){let A=_i(S,y),C=p?.maxDatagramSize;if(C===void 0||A.byteLength<=C){g.write(A).catch(()=>{});return}}e.write(fi(S,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function ki(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new _("connection_failed","this environment has no WebSocket"));n=new i(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((i,o)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),o(new _("timeout","websocket did not come up in time")));},e),l=g=>{a||(a=true,clearTimeout(s),r.close(),o(g));},d=()=>{r.send(Ys(t.credential));},m=g=>{if(a)return;if(typeof g.data!="string"){l(new _("join_refused","the server sent binary before answering the join"));return}let y;try{y=Xs(g.data);}catch(w){l(w);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),i({link:yp(r,Zs(y,t.clock)),welcome:y});},c=()=>{l(new _("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new _("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Qs(t){return typeof t=="string"&&t.length>0?t:void 0}function Zs(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function xi(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,up)*cp,i=n.now(),o=null,a=()=>{o=null;let s=n.now()-i;if(s>=r){e();return}o=n.setTimeout(a,r-s);};return o=n.setTimeout(a,r),{heard:()=>{i=n.now();},stop:()=>{o!==null&&(n.clearTimeout(o),o=null);}}}function yp(t,e){let n,r,i=false,o=s=>{if(!i){i=true,a.stop();try{t.close();}catch{}r?.(s);}},a=xi(e,()=>o(bi));return t.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){n?.(s.data,Si);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&hi)===0&&n?.(l.slice(1),wi(d));})),t.addEventListener("close",(s=>o(Qs(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!i){if(typeof s=="string"){t.send(s);return}t.send(_i(vi(l),s));}},onMessage(s){n=s;},onClose(s){r=s;},close(){o("closed");}}}function Ai(t,e,n,r){let i,o,a=false,s=n,l=c=>{if(!a){a=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}o?.(c);}},d=xi(r,()=>l(bi)),m=(c,p)=>{if(d.heard(),typeof c=="string"){i?.(c,Si);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&hi)===0&&i?.(g.slice(1),wi(y|p));};if(t.addEventListener("message",(c=>m(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),s!==void 0){let c=s;c.addEventListener("message",(p=>m(p.data,Ve|Nn))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){t.send(c);return}let g=vi(p),y=_i(g,c);if((g&Ve)!==0&&s!==void 0&&s.readyState==="open"){s.send(y);return}t.send(y);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}function Ti(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let i=Pi(r);i!==void 0&&(e[n]=i);}return e}function Ci(t){if(Array.isArray(t))return t.map(fp).filter(e=>!!e)}function Pi(t){if(Ei(t)||Array.isArray(t)&&t.every(Ei))return t}function Ei(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function fp(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Pi(e.fixed),r=Pi(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},...fn("description",hp(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Ei)?{allowed:e.allowed}:{},...fn("min",Hn(e.min)),...fn("max",Hn(e.max)),...fn("minItems",Hn(e.min_items)),...fn("maxItems",Hn(e.max_items)),...fn("maxLength",Hn(e.max_length))}}function hp(t){return typeof t=="string"&&t.length>0?t:void 0}function Hn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function fn(t,e){return e===void 0?{}:{[t]:e}}function Te(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(el):[];return {id:n,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Ee(e.max_players)??0,memberCount:Ee(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...we("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...we("roomArgs",Ti(e.room_args)),...we("roomArgsTemplate",Ci(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",...we("region",Y(e.region)),...we("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,...we("matchId",Y(e.match_id)),version:Ee(e.version)??0,...we("templateId",Y(e.template_id)),roomType:Y(e.game_room_type)??"Standard",...we("transports",yn(e.transports)??void 0),createdAt:Ee(e.created_at)??0,updatedAt:Ee(e.updated_at)??0,...we("startedAt",Ee(e.started_at))}}function el(t){let e=t??{};return {...ve(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Ee(e.joined_at)??0,...we("groupId",Y(e.group_id)),...we("platform",Y(e.platform))}}function er(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:Ee(e.max_players)??0,memberCount:Ee(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:Ee(e.created_at)??0}}function Y(t){return typeof t=="string"&&t.length>0?t:void 0}function Ee(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function we(t,e){return e===void 0?{}:{[t]:e}}var Wn=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(er),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(n=>({rooms:(n.game_rooms??[]).map(er)}))}create(e,n,r){return bp(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},...nr(n)},e.signal).then(Te)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Te)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...nr(r)},n.signal).then(Te)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...nr(r)},n.signal).then(Te)}quickJoin(e,n,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...nr(n)},e.signal).then(Te)}leave(e,n,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}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(Te)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Te)}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(Te)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function nr(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function bp(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 Kn=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===i&&n(i);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function _p(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var vp=1e3,wp=3e3,Sp=6e4,Rp=2,nl=new Set(["game_room_closed","game_room_gone"]),kp=12e4,xp=5e3,Ap=new Set(["invalid_cluster_target","capacity_unavailable"]),Pp=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Mi(t){return new Ii(t)}var Ii=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Wn({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Kn;api;room=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");let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await n;return this.api.create(r,this.version("create"),o[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,o);if(s[0]===void 0||s[0]===o[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,n={}){this.assertNotInRoom("join");let r=await this.attachParty(n),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode");let r=await this.attachParty(n),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin");let n=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),o=await this.run("quickJoin",async()=>{let a=await n;return i(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||Tp(l,a))throw s;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let i of n)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(i){if(i instanceof G&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let a=await this.askWhyEnded(o,e);this.endMatch(o,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>li({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(a){return a instanceof G&&a.reason==="not_found"?i??null:(this.reportError("reconcile",a),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=pn(n.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(i),i}async kick(e,n){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(i),i}async transferHost(e,n){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(i),i}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new _("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let i=me(n.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>ai({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>s(o,[a]).catch(async m=>{if(i!==void 0||!rl(m))throw m;let c=await this.nextCluster([a],true);if(c===void 0)throw m;return s(c,[a,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new _("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(i)}chase(e,n,r){return si({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 _("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!nl.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new _("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let i={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!He()){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<vp){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(_p(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!He()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>li({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(o){this.reportError("reconcile",o);}if(this.reconnecting(e)){if(i?.status==="ended"){this.endMatch(i.matchId,i.reason,!nl.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await n.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let n=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):n&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new _("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 _("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 _("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 currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,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.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Ap.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(i=>i.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.seatPollMs>0&&He())){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(),!!He())){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}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of tr)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.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 tr)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??xp}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new _("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let n=this.options.clientVersion,r=Jt(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new _("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return Vs({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return qn(await this.options.resolveClusterTargets());let e=me(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !rl(e)||n.length===0?[]:qn(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=a=>a.find(s=>!e.includes(s)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!n?o:r(qn(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof G)||e.reason!=="conflict"||!Pp.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(n.signal);}catch{throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new G(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(n,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new _("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}requireRoom(e){if(this.room===null)throw new _("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,n){let r=n instanceof G?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof _?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.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(s=>[s.playerId,s])),i=new Map(e.members.map(s=>[s.playerId,s])),o=this.playerId();for(let s of i.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!i.has(s)){if(s===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of i){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=Ep(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??kp;return new Promise((i,o)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>i(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>o(new _("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>o(new _("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>o(new _("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??wp}pushedInterval(){return this.options.pushedPollIntervalMs??Sp}pushed(){return this.options.clock.now()-this.lastPushAt<Rp*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=>{n?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function He(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var tr=["visibilitychange","focus","pageshow","online"];function Ep(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||tl(t)!==tl(e)}function tl(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function rl(t){return t instanceof G&&t.code==="invalid_cluster_target"}function Tp(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Cp=["p2p","dedicated","unknown"],Oi=["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 hn=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let i=Ip(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},n);}report(e){this.post(e).catch(()=>{});}};function Ip(t,e,n){let r=Math.floor(n/1e3);return t.filter(i=>Oi.includes(i.type)).slice(0,100).map(i=>{let o=Mp(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Mp(t){if(t!==void 0)return Cp.includes(t)?t:"unknown"}var Jn=class{constructor(e){this.options=e;this.reporter=new hn({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:rr(i.credential)??"",hostFingerprint:rr(i.host_fingerprint)??"",hostEpoch:ir(i.host_epoch)??0,expiresAt:(ir(i.expires_at)??0)*1e3}}async turnLease(e,n,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&o.push({urls:m,username:rr(d.username)??"",credential:rr(d.credential)??""});}let a=ir(i.expires_at),s=ir(i.ttl_seconds);return {iceServers:o,expiresAt:a!==void 0?a*1e3:Date.now()+(s??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 rr(t){return typeof t=="string"&&t.length>0?t:void 0}function ir(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var Op=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),L=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="P2pError",this.retryable=Op.has(n);}reason;retryable};var il=10240,ol=2048,Lp=new TextEncoder;function al(t){return Lp.encode(t).length}function De(t,e){let n=i=>{throw new _("invalid_sdp",`the ${e} ${i}`)},r=al(t);r>=il&&n(`is ${r} bytes, over the ${il} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let i of t.split(/\r\n|\n/)){let o=al(i);o>ol&&n(`has a ${o}-byte line, over the ${ol} limit`);}}function or(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 ar=class{listeners=new Map;on(e,n){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(n),()=>this.off(e,n)}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}clear(){this.listeners.clear();}};var Gp=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function bn(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=sr(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function sr(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 Gp.test(r)?r:null}function zn(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 Li=5e3,Dp=12e4+Li,$p=1024,Fp=6e4,qp=1e4,sl=64*1024,ll=5;function Gi(t){let e=new Map,n=-1/0,r=null,i=(()=>{let s;try{s=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 s.username!==""||s.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:s.href,shown:`${s.protocol}//${s.host}`}})(),o=()=>{let s=t.subtle??globalThis.crypto?.subtle;if(!s)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 s},a=async()=>{if(!i.ok)throw new L("keys_unavailable",i.reason);let s=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await s(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(qp)});}catch{throw new L("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new L("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>sl)throw new L("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${sl} 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 ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>ll)throw new L("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${ll} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!i.ok)throw new L("keys_unavailable",i.reason);if(r)return await r,e.get(s)??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<Fp?null:(n=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var Yn=class{seen=new Map;admit(e,n){for(let[r,i]of this.seen)i<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=$p){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+Dp),true}};function cl(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}function dl(t){try{let e=new TextDecoder().decode(cl(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Di(t,e,n,r,i){let o=$=>{throw new L("peer_unauthenticated",`the peer's join credential is not usable: ${$}`)},a=t.split(".");a.length!==3&&o("it is not a three-part JWT");let[s,l,d]=a,m=dl(s);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let p=await n.key(c);p===null&&o("it was signed by a key this build cannot resolve");let g=i.subtle??globalThis.crypto?.subtle;g||o("this environment has no WebCrypto");let y=new TextEncoder().encode(`${s}.${l}`),w;try{w=cl(d);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,w,y)||o("its signature does not verify");let A=dl(l);A===null&&o("its payload does not decode");let C=A,b=$=>typeof C[$]=="string"?C[$]:"",R=$=>typeof C[$]=="number"&&Number.isFinite(C[$])?C[$]:NaN;b("iss")!==i.issuer&&o("it was issued by someone else"),b("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),b("match_id")!==e.matchId&&o("it is for another match"),b("game_id")!==e.gameId&&o("it is for another game");let E=R("exp")*1e3,T=R("nbf")*1e3;(!Number.isFinite(E)||e.now>E+Li)&&o("it has expired"),Number.isFinite(T)&&e.now<T-Li&&o("it is not valid yet");let V=b("role");V!=="host"&&V!=="client"&&o("it names no usable role");let B=R("host_epoch");B!==e.hostEpoch&&o("it names a different host epoch");let K=sr(b("fingerprint"));K===null&&o("its fingerprint claim is malformed"),zn(K,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let x=sr(b("host_fingerprint"));x===null&&o("its host fingerprint claim is malformed"),zn(x,e.hostFingerprint)||o("it was issued against a different host certificate");let I=b("jti");I.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(I,e.now)||o("it has already been used");let O=b("sub");return O.length===0&&o("it names no player"),{playerId:O.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:B,role:V,fingerprint:K,hostFingerprint:x,jti:I,expiresAt:E}}function $i(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 Fi(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 qi(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function ji(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 ul(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 ml(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Xn=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 Ni={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Le=["reliable","ordered","unreliable"];function Ui(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 Qn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var gl=1,Vp=3e4,yl=2e3,Hp=5e3,fl=6e4,Wp=8,Vi=class{constructor(e=Wp){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;}},Kp=new Vi,Jp=8,zp=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),et=class{constructor(e){this.options=e;this.keys=e.keys??Gi({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new ar;links=new Map;replays=new Yn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=gl+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??Vp;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),i=me(this.options.clusterTargetId);if(i!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Bi(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=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),a=()=>this.fail(new L("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",a),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=ae(e.playerId),r=ae(e.hostPlayerId),i=lr(e.hostEpoch);if(!(n===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Xn(n,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,gl),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new L("invalid_sdp","the browser produced an offer with no SDP");De(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:bn(r);if(i===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 o=this.options.credentialPacing??Kp,a=()=>this.closed||e!==this.credentialGeneration,s=Hp;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,c;if(m===409)c=yl;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=s,s=Math.min(s*2,fl)),c=Math.min(Math.max(c,yl),fl);}else throw d;if(!await this.waitForCredential(c,a))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=ae(e.fromPlayerId),r=ae(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=Jp){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let i=ae(e.sessionId);if(i!==null&&this.answeredSessions.get(n)===i)return;De(r,"offer"),this.refuseMedia(r,"offer");let o=bn(r);if(o===null)throw new L("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(n,i);let a=this.links.get(n);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(n,this.nextPeerId++);s.remoteFingerprint=o,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new L("invalid_sdp","the browser produced an answer with no SDP");De(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=ae(e.fromPlayerId),r=ae(e.sdp);if(n===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||n!==this.hostPlayerId)return;De(r,"answer"),this.refuseMedia(r,"answer");let o=bn(r);if(o===null)throw new L("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:zn(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=ae(e.fromPlayerId),r=ae(e.candidate);if(n===null||r===null)return;let i=this.links.get(n);if(!i)return;let o=ae(e.sdpMid),a=lr(e.sdpMLineIndex)??lr(e.sdpMLineIndexAlt),s={candidate:r,...o===null?{}:{sdpMid:o},...a===null?{}:{sdpMLineIndex:a}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(s);return}await i.connection.addIceCandidate(s);}onPeerLeft(e){let n=ae(e.playerId);if(n===null)return;let r=ae(e.reason)??"left";if(n===this.localPlayerId){this.fail(new L("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(n);i&&this.dropLink(i,r,true);}async onMigration(e){let n=ae(e.hostPlayerId),r=lr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:n,hostEpoch:r,...ae(e.reason)===null?{}:{reason:ae(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(i.kind==="refused"){this.report_(new L("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new 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=ae(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=ae(e.code)??"unknown",r=ae(e.message)??"the platform refused a signaling message";this.report_(new L("signaling_failed",`${n}: ${r}`));}openLink(e,n){let i=(this.options.peerConnectionFactory??Ui)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of Le){let g=i.createDataChannel(p,Ni[p]);g.binaryType="arraybuffer",o[p]=g;}let a={playerId:e,assignedPeerId:n,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",s),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",m),a.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),i.removeEventListener("icecandidate",s),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}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($i({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=ji(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(ml(r.reason),ul(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=bn(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await Di(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof L&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Bi(a)),s&&this.fail(a);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Fi({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(qi(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let i of Le)hl(e.channels[i]);hl(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",Bi(e),{cause:e}));}count(e){this.counted||!zp.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(or(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 ae(t){return typeof t=="string"&&t.length>0?t:null}function lr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Bi(t){return t instanceof Error?t.message:String(t)}function hl(t){try{t.close();}catch{}}var Yp=100,Xp=50,nt=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,n){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:n});}answer(e,n,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:n,assignedPeerId:r});}candidate(e,n,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Yp)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new 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:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??Xp));}};function H(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function $e(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function _n(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function bl(t){return typeof t=="boolean"?t:void 0}var he=H(64),tt=$e(0,2147483647);function Hi(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=he(n);typeof r=="string"&&e.push(r);}return e}function J(t,e,n){return {to:t,from:e,read:n,required:true}}function W(t,e,n){return {to:t,from:e,read:n,required:false}}var eg=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=_n("disconnected","failed","closed")(e.iceState),r=$e(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:[J("sdp","sdp",H(10240)),J("signaling_intent","intent",_n("initial","ice_restart","full_reconnect")),W("sdp_hash","sdpHash",H(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[J("peer_id","peerId",he),J("sdp","sdp",H(10240)),J("assigned_peer_id","assignedPeerId",$e(0,4294967295)),W("sdp_hash","sdpHash",H(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[J("peer_id","peerId",he),J("candidate","candidate",H(512)),W("sdp_mid","sdpMid",H(64)),W("sdp_mline_index","sdpMLineIndex",$e(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[J("host_epoch","hostEpoch",tt)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[J("host_epoch","hostEpoch",tt),W("evidence","evidence",eg)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[J("playerId","player_id",he),J("hostPlayerId","host_player_id",he),J("hostEpoch","host_epoch",tt),W("members","members",Hi)],offer:[J("fromPlayerId","from_player_id",he),J("sdp","sdp",H(10240)),W("sessionId","signaling_session_id",H(128)),W("sdpHash","sdp_hash",H(128)),W("iceUfrag","ice_ufrag",H(64)),W("intent","signaling_intent",_n("initial","ice_restart","full_reconnect"))],answer:[J("fromPlayerId","from_player_id",he),J("sdp","sdp",H(10240)),W("sessionId","signaling_session_id",H(128)),W("sdpHash","sdp_hash",H(128)),W("iceUfrag","ice_ufrag",H(64)),W("assignedPeerId","assigned_peer_id",$e(0,4294967295))],ice:[J("fromPlayerId","from_player_id",he),J("candidate","candidate",H(512)),W("sdpMid","sdp_mid",H(64)),W("sdpMLineIndex","sdp_m_line_index",$e(0,255)),W("sdpMLineIndexAlt","sdp_mline_index",$e(0,255))],peerJoined:[J("playerId","player_id",he)],peerLeft:[J("playerId","player_id",he),W("reason","reason",H(64))],migration:[J("hostPlayerId","new_host_player_id",he),J("hostEpoch","host_epoch",tt),W("reason","reason",H(64)),W("kickedPlayerIds","kicked_player_ids",Hi),W("migrationComplete","migration_complete",bl)],matchEnded:[W("reason","reason",H(64))],error:[W("code","code",H(64)),W("message","message",H(256))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var Ke="webrtc_p2p";function vl(t){let e=new Jn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,i,o){n.get(r)?.handleSignal(i,o);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new 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 i=me(r.clusterTargetId),o=i??me(await t.resolveClusterTarget?.());t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let a=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==Ke)throw new L("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${Ke}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new nt({bridge:t.bridge,matchId:a.matchId,clock:t.clock}),l=new et({api:e,clock:t.clock,matchId:a.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:s,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Qn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(a.matchId,l),l.on("matchEnded",()=>n.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(a.matchId),l.close(),d}return l}}}function wl(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,i=t.document??globalThis.document,o=[];if(typeof r.addEventListener=="function"){let s=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",s),o.push(()=>r.removeEventListener?.("pagehide",s));let l=()=>e.setHidden(!He());for(let d of tr)r.addEventListener(d,l),o.push(()=>r.removeEventListener?.(d,l));typeof i?.addEventListener=="function"&&(i.addEventListener("resume",l),o.push(()=>i.removeEventListener?.("resume",l))),e.setHidden(!He());}let a=new Map;return o.push(n.on("matchReady",s=>{let l=s.protocol===Ke?"p2p":"dedicated";a.set(s.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(n.on("matchEnded",s=>{let l=a.get(s.matchId);l!==void 0&&(a.delete(s.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let s of o.splice(0))try{s();}catch{}a.clear();}}var Sl=["pointerdown","keydown"];function Rl(t,e=globalThis){let n=false,r=false,i=null,o=()=>{if(i!==null){try{e.cancelAnimationFrame?.(i);}catch{}i=null;}},a=()=>{if(!r){r=true,o();for(let g of Sl)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},s=()=>{if(!(n||r)){n=true,a();try{t();}catch{}}};function l(g){g?.isTrusted===true&&s();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(w=>w.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},c=()=>{if(i=null,!(n||r)){if(d()){s();return}m()&&(i=e.requestAnimationFrame?.(c)??null);}};function p(){i===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let g of Sl)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(i=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:a}}async function dr(t,e,n,r){let i=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),i}function Wi(t,e){let n=false;return async r=>{let i=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),i}}function Ki(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(i,o){return r.has(i)?false:(r.add(i),n.push({name:i,at:o??e()}),true)},timeline(){let i=[...n].sort((o,a)=>o.at-a.at);return i.map((o,a)=>{let s=i[a-1],l=s===void 0?"":` (+${Math.round(o.at-s.at)}ms)`;return `${o.name}@${Math.round(o.at)}ms${l}`}).join(" \u2192 ")}}}var ng="GemWebSdkHandshake";var tg=()=>Date.now();function kl(t,e,n={}){let r=t[ng];if(r===void 0)return null;let i=n.ttlMs??9500,o=n.now??tg,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,c=o()-i;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var Ji=false;async function El(t,e,n,r){if(Ji){e.close(),n("busy",true);return}Ji=true;let i=null;try{let o=await ig(t,r);if(typeof o=="string"){e.close(),n(o,rg(o));return}i=o;let s=await(r.encodeRef??(l=>lg(l,r)))(i);if(i.close(),i=null,s===null){e.close(),n("failed",!0);return}if(s.size>sg){e.close(),n("too_large",!1);return}e.postMessage(s);}catch(o){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",o);}finally{Ji=false,i?.close();}}function rg(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 ig(t,e){if(e.handler){let o=await e.handler(t);return o===null?"declined":xl(o,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=ag(n);if(!r)return "no_source";let i=og(r);if(i!==null)return i;try{return xl(await createImageBitmap(r),t)}catch(o){if(o instanceof DOMException&&o.name==="SecurityError")return "tainted";throw o}}function og(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 ag(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let i=r.width*r.height;i<=0||r.clientWidth<=0||r.clientHeight<=0||i>n&&(e=r,n=i);}return e}async function xl(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let i=Math.min(n/t.width,r/t.height),o=Math.max(1,Math.floor(t.width*i)),a=Math.max(1,Math.floor(t.height*i));try{let s=await createImageBitmap(t,{resizeWidth:o,resizeHeight:a,resizeQuality:"high"});return t.close(),s}catch{return t.close(),"too_large"}}var sg=8*1024*1024,Al="image/webp",Pl=.92;async function lg(t,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(t.width,t.height),a=o.getContext("2d");if(a){a.drawImage(t,0,0);let s=await o.convertToBlob({type:Al,quality:Pl});if(s&&s.size>0)return s}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let i=r.getContext("2d");return !i||(i.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(a=>o(a),Al,Pl);})}async function Tl(t,e){if(!e)return;let n;try{n=await dg(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 dg(t){return new Promise((e,n)=>{let r=false,i=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>t())().then(o=>{r||(r=true,clearTimeout(i),e(o??null));},o=>{r||(r=true,clearTimeout(i),n(o instanceof Error?o:new Error(String(o))));});})}var Cl=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Il(t=globalThis){let n=t[Cl];if(n!==void 0)return n;let r=false,i=()=>r,o=[],a=cg(t,i);a!==null&&o.push(a);let s=ug(t,i);s!==null&&o.push(s);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of o)c();}}};return Object.defineProperty(t,Cl,{value:l,configurable:true}),l}function cg(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let i=t.OfflineAudioContext,o=n.connect,a=n.disconnect,s=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(i!==void 0&&c instanceof i)return null;let p=s.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,o.call(p,m),s.set(c,p)),p};return n.connect=function(...c){let[p,...g]=c;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return o.call(this,y,...g),p}return o.apply(this,c)},n.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let y=s.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...g)}catch{}}return a.apply(this,c)},()=>{for(let[m,c]of s){if(m.state==="closed"){s.delete(m);continue}try{l(c);}catch{}}}}function ug(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,i=Object.getOwnPropertyDescriptor(r,"muted"),o=i?.get,a=i?.set;if(o===void 0||a===void 0)return null;let s=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!o.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),a.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!o.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return s.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{a.call(g,(l.get(g)??!1)||e());}catch{}}}}var mg=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",pg=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',gg=`${mg}${pg}`,zi=new WeakSet;function Ml(t=globalThis.document){if(t==null||zi.has(t))return null;try{let e=t.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(t.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(gg),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],zi.add(t),"sheet"}let n=t.documentElement?.style;return n===void 0||typeof n.setProperty!="function"?null:(n.setProperty("-webkit-user-select","none"),n.setProperty("user-select","none"),n.setProperty("-webkit-tap-highlight-color","transparent"),zi.add(t),"inline")}catch{return null}}function Ol(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=false,i=false,o=false,a=null,s=null,l=null,d=[],m=()=>r&&!i&&!o,c=()=>{s=null,l=null,d=[];},p=w=>{if(a=null,!m()){c();return}if(l!==null&&d.push(w-l),l=w,s===null)s=w;else {let S=w-s;S>=e&&d.length>0&&(t.report(yg(d,S)),s=w,d=[]);}g();},g=()=>{let w=n.requestAnimationFrame;typeof w=="function"&&(a=w.call(n,p));},y=()=>{if(m()){a===null&&(c(),g());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),c();};return {setRequested(w){r=w,y();},setPaused(w){i=w,y();},get running(){return a!==null},dispose(){o=true,y();}}}function yg(t,e){let n=[...t].sort((i,o)=>i-o),r=Math.max(1,Math.ceil(n.length*.95));return {fps:t.length*1e3/e,frameTimeP95Ms:n[r-1]}}var cr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Gl(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Dl(t,e){t!==null&&(t.style.setProperty(cr.top,`${e.top}px`),t.style.setProperty(cr.right,`${e.right}px`),t.style.setProperty(cr.bottom,`${e.bottom}px`),t.style.setProperty(cr.left,`${e.left}px`));}var Ll=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height"}});function $l(){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 fg(t,e){let n={tl:{width:0,height:0},tr:{width:0,height:0},bl:{width:0,height:0},br:{width:0,height:0}};for(let r of t){let i=e?r.x+r.width/2<=e.width/2:r.x===0,o=e?r.y+r.height/2<=e.height/2:r.y===0,a=i?r.x+r.width:e?e.width-r.x:r.width,s=o?r.y+r.height:e?e.height-r.y:r.height,l=n[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(a)),l.height=Math.max(l.height,Math.ceil(s));}return n}function Fl(t,e,n){if(t===null)return;let r=fg(e,n);for(let i of ["tl","tr","bl","br"])t.style.setProperty(Ll[i].width,`${r[i].width}px`),t.style.setProperty(Ll[i].height,`${r[i].height}px`);}var hg=3e4,ur=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function ql(t){let e=t.clock??ye,n=t.timeoutMs??hg,r=new Map,i=new Map,o=0,a=s=>{let l=r.get(s);return l?(r.delete(s),i.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(s){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(s);if(l)return l;let d=new Promise((m,c)=>{let p=`ls${++o}`,g=e.setTimeout(()=>{r.delete(p),i.delete(s),c(new ur("timeout",true,`the embedder did not answer a local-server request for room ${s} within ${String(n)}ms`));},n);r.set(p,{room:s,resolve:m,reject:c,timer:g}),t.bridge.requestLocalServer(p,s)||(a(p),m());});return i.set(s,d),d.catch(()=>{}),d},accept(s){a(s.requestId)?.resolve();},refuse(s){let l=a(s.requestId);l&&l.reject(new ur(s.reason,s.retryable,s.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var rt={url:"https://downloads.indiegems.games/sdk/v9.1.3/gem-web-sdk.devtools.min.js",integrity:"sha384-cVpHv9IVZIDH6h91hiJi1JbhXTv4C/qHSeUDSJI4SBIzhVlfCkoirCrTTCnkBs0E"};var wn=null;function bg(){return wn!==null||(wn=new Promise((t,e)=>{let n=document.createElement("script");n.src=rt.url,n.integrity=rt.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){wn=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${rt.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{wn=null,e(new Error(`gem devtools: could not load ${rt.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);})),wn}function jl(t,e){let n=null,r=0;async function i(o){if(n!==null)return true;let a=++r;if(!e())return false;let s=await bg();return !e()||a!==r?false:(n!==null||(n=s.mount(t(),{openedBy:o,text:dn,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>i("game"),openFrom:i}}var _g=1e4,Nl={reason:"unavailable",retryable:false};function Ul(t){let e=new Map,n=null,r=null,i=0,o=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??_g);},a=(d,m)=>{let c=s(d);c&&m(c);},s=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new on({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,c)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){c(Nl);return}let g=`t${++i}`,y={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,y),o(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)){a(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){a(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),o(m,c),t.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])a(m,c=>c.reject(Nl));},get identity(){return n},get gameVersion(){return r}}}function vg(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var wg=new Set(Pr);function Sg(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))wg.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function mr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return Oo(async(n,r)=>{let i;try{i=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new ie("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let o;try{o=new URL(i.href.replace(/\/+$/,"")+n.path);}catch{throw new ie(`${JSON.stringify(typeof n.path=="string"?vg(n.path):"(a non-string path)")} does not form a valid URL against ${i.protocol}//${i.host}. This is a malformed request, not a server failure.`)}if(o.protocol!==i.protocol||o.host!==i.host)throw new ie(`${JSON.stringify(o.pathname)} resolves to ${o.protocol}//${o.host}, not ${i.protocol}//${i.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(o.username!==""||o.password!==""){let g=i.username!==""||i.password!=="",y=o.username!==i.username||o.password!==i.password,w=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new ie(`the ${w} puts credentials in the URL, which cannot be fetched (${n.method} ${o.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(t.defaultQuery??{}))o.searchParams.has(g)||o.searchParams.set(g,y);let a=n.bytes,s=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(a=JSON.stringify(n.body),s="application/json");}catch(g){throw new ie(`the body of ${n.method} ${JSON.stringify(o.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(o.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...s===void 0?{}:{"content-type":s},...Sg(n.headers)},body:a,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),c=Rg(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},t)}function Rg(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 kg=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Xi="embedder_relay_unavailable",xg="embedder_no_relay",Ag=new Set([Xi]),Qi=new Set([xg]),it=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Yi(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new _("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){n.refuse(new _("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(Pg(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new _("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 _("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new _("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function Pg(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new _(Eg(t),r,{platformCode:t})}function Eg(t){return t===void 0||Ag.has(t)?"signaling_failed":Qi.has(t)?"offer_refused":kg.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Yi=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new _("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return n?.aborted?Promise.reject(new _("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let a=()=>{s(),o(new _("aborted","the caller aborted the signaling exchange"));},s=()=>{n?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),i(d);},refuse:d=>{s(),o(d);}};this.teardown=s,n?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof _?d:new _("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var Bl="match_ended:",Vl="server_shutdown:",Hl="kicked:",Tg=123;function Cg(t){if(typeof t!="string"||t.length===0||t.length>Tg)return {kind:"other"};if(t.startsWith(Bl)){let e=pn(t.slice(Bl.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Vl)?{kind:"server_shutdown",cause:t.slice(Vl.length)}:t.startsWith(Hl)?{kind:"kicked",detail:t.slice(Hl.length)}:{kind:"other"}}function Zi(t,e,n){let r=Cg(n),i=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function eo(){return {exchange(){return Promise.reject(new _("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var Ig=3e3,Mg=1e4,Og=15e3;async function pr(t){let e=t.peerConnection;try{Kl(t,"before the handshake started"),no(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let a of t.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});t.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await Dg(e,t),no(t);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new _("invalid_sdp","the offer carried no SDP");De(i,"offer"),Wl(i,"offer");let o=await Gg(t,i);if(no(t),typeof o?.sdp!="string")throw new _("invalid_sdp","the signaling channel answered without an SDP");return De(o.sdp,"answer"),Wl(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await $g(n,t),Kl(t,"before the channel opened"),n}catch(n){throw e.close(),Lg(n)}}function Lg(t){return t instanceof _?t:Yl(t)?Je():new _("connection_failed",Xl(t),{cause:t})}function Wl(t,e){if(or(t))throw new _("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function Gg(t,e){let n=t.exchangeTimeoutMs??Mg,r=zl(t,n),i=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(o=>{throw o instanceof _?o:Yl(o)?Je():new _("signaling_failed",Xl(o),{cause:o})});return Fg(i,t,r,()=>r.exhausted?to("while the offer was in flight"):new _("timeout",`no answer arrived within ${n}ms`))}function Dg(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let i=()=>{n.clearTimeout(a),t.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{t.iceGatheringState==="complete"&&i();},a=n.setTimeout(i,e.gatherTimeoutMs??Ig);t.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function $g(t,e){if(e.signal?.aborted)return Promise.reject(Je());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new _("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??Og,i=zl(e,r);return new Promise((o,a)=>{let s=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),o();},d=g=>{s(),a(new _("connection_failed","the data channel failed before it opened",Jl(g)===void 0?void 0:{cause:Jl(g)}));},m=()=>{s(),a(Je());},c=()=>{s(),a(i.exhausted?to("while the channel was still opening"):new _("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(c,i.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function zl(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 Fg(t,e,n,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(Je()):new Promise((a,s)=>{let l=c=>{i.clearTimeout(m),o?.removeEventListener("abort",d),c();},d=()=>l(()=>s(Je())),m=i.setTimeout(()=>l(()=>s(r())),n.ms);o?.addEventListener("abort",d),t.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Kl(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw to(`already ${e}`)}function to(t){return new _("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function no(t){if(t.signal?.aborted)throw Je()}function Je(){return new _("aborted","the caller aborted the connection attempt")}function Yl(t){return t?.name==="AbortError"}function Jl(t){return t?.error}function Xl(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:[J("sdp","sdp",H(10240)),W("sessionId","session_id",H(64))],error:[W("code","code",H(64)),W("message","message",H(256))],matchEnded:[W("reason","reason",H(64))]}));function od(t){let{client:e,clock:n,rooms:r}=t,i=t.signaling??eo,o=t.log??(b=>console.warn(b)),a=new hn({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(b,R)=>{let E=s.get(b)??new Set;E.add(R),s.set(b,E);},d=(b,R)=>{let E=s.get(b);E!==void 0&&(E.delete(R),E.size===0&&s.delete(b));},m=async b=>{if(r.isHost&&!io(r)&&r.currentRoom?.matchId===void 0){let R=me(b.clusterTargetId);await r.startMatch({...R===void 0?{}:{clusterTargetId:R},...b.retry===void 0?{}:{retry:b.retry},...b.signal===void 0?{}:{signal:b.signal}});}return rd(r.matchConnectionState==="suspended"?await r.reconnectToMatch(ro(b)):await r.awaitMatch(ro(b)))},c=async b=>rd(await r.pollMatchStatus(ro(b))),p=async(b,R)=>{let E=false;try{let T=await m(b),V=r.currentRoom?.transports;if(V!==void 0&&!V.includes("webrtc"))throw new _("misconfigured",`the room template offers (${V.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let B=b.peerConnection??id();E=!0;let K=await pr({peerConnection:B,signaling:R,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...gr(b,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),x=null;if(b.presentCredential!==!1)try{x=await jn({channel:K,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...gr(b,"onMessage","signal"),...b.welcomeTimeoutMs===void 0?{}:{ceilingMs:b.welcomeTimeoutMs}});}catch(I){throw Se(K),Se(B),I}return Kg(r,T,K,B,R,b.reportDisconnect!==!1,b.reportConnected!==!1,x,{remember:l,forget:d},b.onMatchEnded)}catch(T){throw E&&td(a,T),Se(R),T}},g=async(b,R,E,T,V,B)=>{if(b==="webtransport"){let N=T?.webtransport;if(N===void 0)throw new _("misconfigured","webtransport is not advertised");let q={credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n};if(typeof N.named_url=="string"&&N.named_url!==""){let Z=Math.max(Math.floor(B/2),1e3);try{return await Vn({url:N.named_url,timeoutMs:Z,log:o,...q})}catch(pe){if(Zt()!==null)throw pe;return o(`[gem] webtransport named dial failed (${Xt(pe)}); retrying the pinned dial`),Vn({url:N.url,certHashBase64:N.cert_sha256_b64,timeoutMs:Z,log:o,...q})}}return Vn({url:N.url,certHashBase64:N.cert_sha256_b64,timeoutMs:B,...q})}if(b==="websocket"){let N=T?.websocket;if(N===void 0)throw new _("misconfigured","websocket is not advertised");return ki({url:N.url,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n,timeoutMs:B})}let K=R.peerConnection??id(),x,I=await pr({peerConnection:K,signaling:V,clock:n,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,extraChannels:[{label:Un,ordered:false,maxRetransmits:0}],onExtraChannel:(N,q)=>{N===Un&&(x=q);},...gr(R,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...R.exchangeTimeoutMs===void 0&&R.redial===true?{exchangeTimeoutMs:Ng}:{}}),O;try{O=await jn({channel:I,clock:n,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,wire:Yt,heartbeat:!0,...gr(R,"signal"),...R.welcomeTimeoutMs===void 0?{}:{ceilingMs:R.welcomeTimeoutMs}});}catch(N){throw Se(I),Se(K),N}let $=O.welcome.heartbeatIntervalMs;return {link:Ai(I,K,x,$===void 0?void 0:{clock:n,intervalMs:$}),welcome:O.welcome,channel:I,peerConnection:K}},y=(b,R,E,T,V)=>{let B=false,K;T.link.onClose($=>{!B&&b.reportDisconnect!==false&&Zi(r,R.matchId,$),K?.($);}),b.reportDisconnect!==false&&b.reportConnected!==false&&r.notifyMatchConnected(R.matchId);let x={transport:T.link.transport,send:($,N)=>T.link.send($,N),onMessage:$=>T.link.onMessage($),onClose:$=>{K=$;},close:()=>T.link.close()},I=()=>{B||(B=true,Se(T.link),Se(V));},O=$=>{if(!B){try{b.onMatchEnded?.($);}catch{}I();}};return l(R.matchId,O),{matchId:R.matchId,transport:E,link:x,joinCredential:R.joinCredential,credentialExpiresAt:R.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(R.matchId,O),I();}}},w=async(b,R)=>{let E=r.currentRoom?.id,T=r.gameId,V=()=>({advert:Bn(r.currentRoom?.settings,b),template:r.currentRoom?.transports??null});if(E===void 0||T===null)return V();try{let B=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(E)}`,R);return {advert:Bn(B.settings,b),template:yn(B.transports)??r.currentRoom?.transports??null}}catch{return V()}},S=(b,R)=>{let E=b??Ql;return R.length===0?E:E.filter(T=>R.includes(T))},A=async(b,R,E)=>{try{let T=await m(b),{advert:V,template:B}=await w(T.matchId,b.signal),K=S(B,R),x=K.filter(X=>Vg(X,V)),I=Zt();if(I!==null&&K.includes("webtransport")&&V?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${I} (learned on an earlier dial in this page)`),x.length===0){let X=B===null?`the default order (${Ql.join(", ")})`:`the room template's transports (${B.join(", ")||"none"})`;throw new _("misconfigured",`none of ${X}`+(R.length>0?`, narrowed to (${R.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let O=b.transportAttemptTimeoutMs??jg,$=()=>b.deadlineAt===void 0?1/0:b.deadlineAt-n.now(),N=X=>t.signalingReady===void 0||X<=0?Promise.resolve(!0):t.signalingReady(X),q=[],Z=[];for(let X of x){if($()<ed){o(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}Z.length>0&&T.credentialExpiresAt-n.now()<nd&&(T=await c(b)),Z.push(X);let Ie=!1,ce=!1,Re={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&b.redial===!0){let te=Math.min(Zl,$());await N(te)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let Me=Math.max(Math.min(O,$()),ed);try{return y(b,T,X,await g(X,b,T,V,E,Me),E)}catch(te){let z=te instanceof _?te:new _("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(X==="webrtc"&&td(a,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Ie){Ie=!0,T=await c(b);continue}if(X==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===Xi&&!ce){ce=!0;let le=Math.min(Zl,$());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(le)}ms for the socket before offering again`),await N(le))continue}if(z.reason==="join_rate_limited"){let le=Bg(Re,Math.random,$());if(le!==null){if(Re.attempts+=1,Re.waitedMs+=le,o(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(le)}ms before presenting again (retry ${Re.attempts} of ${sd.maxAttempts})`),await Kt(n,le,b.signal),b.signal?.aborted)throw new _("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<nd&&(T=await c(b));continue}}if(Ug.has(z.reason)||z.reason==="credential_expired"||X==="webrtc"&&ad(z)){o(`[gem] ${X} rung failed (${z.reason}): ${Xt(z.cause??z)} \u2014 `+(Z.length<x.length?`falling through to ${x[Z.length]}`:"no rungs left")),q.push(z);break}throw o(`[gem] ${X} rung refused the session (${z.reason}): ${z.message}`),z}}}let pe=q[q.length-1];throw pe===void 0?new _("timeout",`the reconnect budget ran out before any transport (${x.join(", ")}) could be tried`):new _(pe.reason,`every transport tried (${Z.join(", ")}) failed; the last said: ${pe.message}`,{cause:q,platformCode:pe.platformCode})}catch(T){throw Se(E),T}};return {listClusterTargets:async(b={})=>di({client:e,...b}),handleMatchEnded(b,R){let E=s.get(b);if(E!==void 0){s.delete(b);for(let T of E)T(R);}},connect:(async(b={})=>{let R=b.signaling??i();return b.transports===void 0?p(b,R):A(b,b.transports,R)})}}var Ql=["webtransport","webrtc","websocket"],jg=1e4,Ng=5e3,Zl=3e3,ed=1e3,nd=1e4,Ug=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function ad(t){return t.platformCode!==void 0&&Qi.has(t.platformCode)}var sd={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Bg(t,e=Math.random,n=1/0){let r=sd;if(t.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-t.waitedMs,n);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**t.attempts;return Math.min(o+e()*r.jitterMs,i)}function Vg(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Qt():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Hg(e.websocket.url)}function Hg(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return wt(e)}function ro(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var Wg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function td(t,e){e instanceof _&&(!Wg.has(e.reason)&&!ad(e)||t.report([{type:"connection_failures_total",value:1}]));}function Kg(t,e,n,r,i,o,a,s,l,d){let m=false,c=()=>{m||Zi(t,e.matchId,void 0);};o&&(n.addEventListener("close",c),a&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",c),s?.detach(),Se(n),Se(r),Se(i));},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:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function io(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function rd(t){if(t.status==="failed")throw new _("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new _("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Wt)throw new _("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Wt}' 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 _("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 id(){let t=globalThis.RTCPeerConnection;if(!t)throw new _("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new t({iceServers:[]})}function Se(t){try{t.close();}catch{}}function gr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var Jg=1e4;function ld(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=a=>({token:a.token,expiresAt:a.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new on({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((a,s)=>{let l=e.clock.setTimeout(()=>{r=null,s({reason:"unavailable",retryable:true});},e.timeoutMs??Jg);r={resolve:d=>{e.clock.clearTimeout(l),a(d);},reject:s,timer:l};})}),o=t.onServerToken(a=>{let s=n(a),l=r;if(l){r=null,l.resolve(s);return}i.accept(s);});return {source:i,dispose(){o(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var ao={};Jd(ao,{acceptTransfer:()=>zg,addEntityProgression:()=>Yg,adminAction:()=>Xg,cancelInventoryTransfer:()=>Qg,claimEntityProgressionRewards:()=>Zg,closeGameRoom:()=>ey,createEntityBatchOrder:()=>ny,createEntityOrder:()=>ty,createSession:()=>ry,deleteEntityGameSetting:()=>iy,deleteEntitySave:()=>oy,deleteSession:()=>ay,deleteShowcaseValue:()=>sy,executeEntityRecipe:()=>ly,finalizeSaveUpload:()=>dy,getChannelAssignment:()=>cy,getDropRates:()=>uy,getEntityCurrency:()=>my,getEntityGameSetting:()=>py,getEntityInventory:()=>gy,getEntityInventoryItem:()=>yy,getEntityLeaderboard:()=>fy,getEntityOrder:()=>hy,getEntityProgression:()=>by,getEntityRecipeAvailability:()=>_y,getEntityRecipeUsage:()=>vy,getEntitySave:()=>wy,getEvent:()=>Sy,getGameRoomV2:()=>Ry,getLeaderboard:()=>ky,getPlayerGameProfile:()=>xy,getPurchaseCatalog:()=>Ay,getResolvedTemplate:()=>Py,getRoomArgs:()=>Ey,getShowcaseValue:()=>Ty,getTransferDetails:()=>Cy,ingestAnalyticsEvents:()=>oo,initiateInventoryTransfer:()=>Iy,invokeFunction:()=>My,kickPlayer:()=>Oy,listChallenges:()=>Ly,listEntityGameSettings:()=>Gy,listEntityOrders:()=>Dy,listEntityProgressions:()=>$y,listEntitySaves:()=>Fy,listEvents:()=>qy,listGameRooms:()=>jy,listResolvedTemplates:()=>Ny,listTransfers:()=>Uy,maxEntityProgression:()=>By,putEntityGameSetting:()=>Vy,putRoomArgs:()=>Hy,putShowcaseValue:()=>Wy,rejectTransfer:()=>Ky,requestSaveUploadUrl:()=>Jy,resetEntityProgression:()=>zy,simulateEntityOrder:()=>Yy,transferHostV2:()=>Xy,updateGameRoomV2:()=>Qy});function h(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 zg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Yg(t,e,n,r,i,o){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/add`;return t.client.post(a,i,o?.signal)}async function Xg(t,e,n,r){let i=`/v1/voice/sessions/${h(e)}/admin`;return t.client.post(i,n,r?.signal)}async function Qg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Zg(t,e,n,r,i,o){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/claim`;return t.client.post(a,i,o?.signal)}async function ey(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.delete(r,n?.signal)}async function ny(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ty(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ry(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function iy(t,e,n,r,i){let o=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(o,i?.signal)}async function oy(t,e,n,r,i){let o=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(o,i?.signal)}async function ay(t,e,n){let r=`/v1/voice/sessions/${h(e)}`;return t.client.delete(r,n?.signal)}async function sy(t,e,n,r){let i=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.delete(i,r?.signal)}async function ly(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function dy(t,e,n,r,i,o){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/finalize`;return t.client.post(a,i,o?.signal)}async function cy(t,e,n){let r=`/v1/games/${h(t.gameId())}/config/channels/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function uy(t,e,n){let r=`/v1/inventory/loot-tables/${h(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function my(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/currencies/${h(r)}`;return t.client.get(o,i?.signal)}async function py(t,e,n,r,i){let o=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function gy(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),a=`/v1/inventory/${h(e)}/${h(n)}`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function yy(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/items/${h(r)}`;return t.client.get(o,i?.signal)}async function fy(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let a=o.toString(),s=`/v1/leaderboards/${h(e)}/${h(n)}/${h(r)}`+(a?`?${a}`:"");return t.client.get(s,i?.signal)}async function hy(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/orders/${h(r)}`;return t.client.get(o,i?.signal)}async function by(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}`;return t.client.get(o,i?.signal)}async function _y(t,e,n,r,i,o){let a=`/v1/inventory/${h(e)}/${h(n)}/catalogs/${h(r)}/recipes/${h(i)}/availability`;return t.client.get(a,o?.signal)}async function vy(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit));let o=i.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function wy(t,e,n,r,i){let o=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Sy(t,e,n){let r=`/v1/events/${h(e)}`;return t.client.get(r,n?.signal)}async function Ry(t,e,n){let r=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function ky(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${h(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function xy(t,e,n){let r=`/v1/profiles/players/${h(e)}`;return t.client.get(r,n?.signal)}async function Ay(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Py(t,e,n){let r=`/v1/game-room-templates/${h(e)}`;return t.client.get(r,n?.signal)}async function Ey(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.get(r,n?.signal)}async function Ty(t,e,n,r){let i=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.get(i,r?.signal)}async function Cy(t,e,n){let r=`/v1/inventory/transfers/${h(e)}`;return t.client.get(r,n?.signal)}async function oo(t,e,n){let r=`/v1/games/${h(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true})}async function Iy(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function My(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Oy(t,e,n,r){let i=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/kick/${h(n)}`;return t.client.post(i,void 0,r?.signal)}async function Ly(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Gy(t,e,n,r){let i=`/v1/settings/${h(e)}/${h(n)}`;return t.client.get(i,r?.signal)}async function Dy(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/orders`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function $y(t,e,n,r){let i=`/v1/inventory/${h(e)}/${h(n)}/progressions`;return t.client.get(i,r?.signal)}async function Fy(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),a=`/v1/saves/${h(e)}/${h(n)}`+(o?`?${o}`:"");return t.client.get(a,r?.signal)}async function qy(t,e){let n=new URLSearchParams;e?.include_inactive!==void 0&&n.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.offset!==void 0&&n.set("offset",String(e?.offset));let r=n.toString(),i="/v1/events"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function jy(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i=`/v1/games/${h(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ny(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function Uy(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function By(t,e,n,r,i,o){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/max`;return t.client.post(a,i,o?.signal)}async function Vy(t,e,n,r,i,o){let a=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.put(a,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Hy(t,e,n,r){let i=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.put(i,n,r?.signal)}async function Wy(t,e,n,r,i){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.put(o,r,i?.signal)}async function Ky(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Jy(t,e,n,r,i,o){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/upload-url`;return t.client.post(a,i,o?.signal,{replaySafe:true})}async function zy(t,e,n,r,i,o){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/reset`;return t.client.post(a,i,o?.signal)}async function Yy(t,e,n,r,i){let o=`/v1/inventory/${h(e)}/${h(n)}/orders/simulate`;return t.client.post(o,r,i?.signal)}async function Xy(t,e,n,r){let i=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}/transfer/${h(n)}`;return t.client.post(i,void 0,r?.signal)}async function Qy(t,e,n,r){let i=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.patch(i,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Zy=1e4,ef=50,nf=1e3,tf=65536-4*1024,dd=t=>typeof t=="number"?t:0,rf=t=>typeof t=="string"?t:"";function cd(){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 of(t){return t?.retryable===true}function af(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:dd(o.index),code:rf(o.code)}}):[];return {accepted:dd(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function ud(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 md(t){let e=Math.max(1,Math.floor(t.maxQueue??nf)),n={client:t.client,gameId:()=>t.gameId},r=[],i=0,o=null,a=false,s=false,l=false,d=false,m=w=>{t.log?.(w);},c=()=>{o!==null&&(t.clock.clearTimeout(o),o=null);},p=()=>{o!==null||a||s||(o=t.clock.setTimeout(()=>{o=null,y().catch(()=>{});},Zy));},g=()=>{let w=Math.min(r.length,100),S=128;for(let A=0;A<w;A+=1){let C=r[A];if(C===void 0)break;if(S+=JSON.stringify(ud(C,0)).length+1,S>tf)return Math.max(1,A)}return w};async function y(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};c();let S=r.splice(0,g()),A=i;i=0;let C=Math.round(t.clock.now()),b={batch_id:cd(),sent_at_ms:C,events:S.map(R=>ud(R,C))};s=true;try{let R=await oo(n,b,w===void 0?void 0:{signal:w}),E=af(R,A);for(let T of E.rejected)m(`[gem] analytics: an event was refused (${T.code}). See the analytics_events section of your game config.`);return E}catch(R){if(of(R))for(r=[...S,...r],i+=A;r.length>e;)r.shift(),i+=1;else m(`[gem] analytics: ${S.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(R)}`);throw R}finally{s=false,r.length>0&&p();}}return {track(w,S,A={}){if(a)return;if(typeof w!="string"||w===""){d||(d=true,m(`[gem] analytics: '${S}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(S.startsWith(Zr)){l||(l=true,m(`[gem] analytics: '${S}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let C={},b={};for(let[R,E]of Object.entries(A))typeof E=="string"?C[R]=E:typeof E=="number"&&Number.isFinite(E)&&(b[R]=E);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:cd(),playerId:w,name:S,atMs:t.clock.now(),dimensions:C,measures:b}),r.length>=ef?y().catch(()=>{}):p();},flush:w=>y(w),get pending(){return r.length},dispose(){a=true,c(),r=[],i=0;}}}function pd(t){return {async list(e){let{playerId:n,periodsBack:r,signal:i}=e??{};if(typeof n!="string"||n==="")throw new TypeError("gem.challenges.list needs { playerId }: a game-server token names no player, so the platform cannot tell whose period you mean. Pass the id from join() or gem.players().");un(r);let o=await t({player_id:n,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return qt(o)}}}function sf(t){let e={};for(let[n,r]of Object.entries(ao))if(typeof r=="function"){let i=r;e[n]=(...o)=>i(t,...o);}return e}function gd(t,e={}){let n=e.clock??ye,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let i=ld(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=mr({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),a=new Fe({transport:o,clock:n}),s={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=sf({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=t.endMatch,c=t.log,p=md({client:a,clock:n,gameId:s.gameId,...typeof c=="function"?{log:y=>c.call(t,y)}:{}});return {identity:s,client:a,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);}},analytics:p,functions:new Be(l.invokeFunction),challenges:pd(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let w=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),S=w.modified?w.body:void 0;if(S?.room_args==null||S.room_args_template==null)throw new G("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:S.room_args,room_args_template:S.room_args_template}}}},dispose:()=>{p.dispose(),i.dispose();}}}function ze(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Sn(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function ot(t){return typeof t=="string"?t:t.slice().buffer}function yr(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 lf=5e3,yd=3e4,fd=2e3,df=1e4,hd=1;async function bd(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let i=e.log===void 0?f=>console.info(f):e.log,o=f=>i?.(`[gem host] ${f}`),a=typeof t=="function"?t():t,s=Promise.resolve(),l=true,d=false,m=(f,M)=>{l&&(s=s.then(async()=>{if(!d)try{await M();}catch(F){o(`the bundle's ${f} handler threw: ${Ye(F)}. Serving continues.`);}}));},c=true,p,g,y,w=f=>{if(!c)return;c=false,m("leave",()=>a.leave?.(r,{cause:f??"left"}));let M=g;M&&queueMicrotask(()=>M(f));},S={send(f,M){if(!c)return;let F=Sn(ze(M));m("message",()=>a.message?.(r,f,typeof f=="string",{reliable:F.reliable,ordered:F.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){w("closed");}},A=(f,M)=>{if(!c)return;let F=Sn(ze(M));queueMicrotask(()=>{c&&p?.(f,F);});},C=new Map,b=f=>{let M=[];for(let F of Le){let re=f.channels[F];try{re.binaryType="arraybuffer";}catch{}let _e=Sn(F),Ze=j=>{let en=yr(j?.data);en!==null&&m("message",()=>a.message?.(f.playerId,en.data,en.isText,{reliable:_e.reliable,ordered:_e.ordered}));};re.addEventListener("message",Ze),M.push(()=>re.removeEventListener("message",Ze));}C.get(f.playerId)?.forEach(F=>F()),C.set(f.playerId,M);},R=f=>{C.get(f)?.forEach(M=>M()),C.delete(f);},E=new Set,T=new Map,V=(f,M,F)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...M?{rejoin:true}:{},...F?{superseded:true}:{}}),B=f=>{let M=C.has(f.playerId),F=E.has(f.playerId);E.add(f.playerId),b(f),M&&m("leave",()=>a.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>a.join?.(f.playerId,V(f,F,M)));},K=new Set,x=(f,M,F)=>{if(f===r){A(M,F);return}let re=n.peer(f);if(re===null){let _e=T.get(f);if(_e!==void 0&&e.clock.now()-_e<fd)return;K.has(f)||(K.add(f),o(`send to '${f}' dropped: no such connected player`));return}re.send(ot(M),ze(F));},I={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=c?[r]:[];for(let M of n.peers)f.push(M.playerId);return f},profile(f){let M=e.room()?.members.find(F=>F.playerId===f);if(!(!M||M.displayName===void 0))return {displayName:dn.toPlain(M.displayName),...M.displayTag===void 0?{}:{displayTag:dn.toPlain(M.displayTag)},...M.discriminator===void 0?{}:{discriminator:M.discriminator}}},playerNumber(f){return f===r?hd:n.peer(f)?.assignedPeerId},send(f,M,F){x(f,M,F);},broadcast(f,M){let F=M?.except;c&&r!==F&&A(f,M);for(let re of n.peers)re.playerId!==F&&re.send(ot(f),ze(M));},async endMatch(){let f=await Me();return f.answer!=="ok"&&o(f.cause),f.answer},kick(f,M){if(f===r){w(M??"kicked");return}n.kick(f).catch(F=>{o(`kick of '${f}' failed: ${Ye(F)}`);});},log(f){o(f);},warn(f){o(`\u26A0 ${f}`);}},O=()=>{},$=new Promise(f=>{O=f;}),N=[],q=null,Z=async(f,M)=>{l=false;let F=s.then(async()=>{try{await a.shutdown(f);}catch(re){o(`the bundle's shutdown threw: ${Ye(re)}`);}});s=F,await F,le();for(let re of N.splice(0))re();for(let re of [...C.keys()])R(re);w(M);},pe=(f,M)=>q||(q=(async()=>{await Z(M,f),n.close(),O();})(),q),X=()=>q||(q=(async()=>{await Z({reason:"signal"},"left"),await n.leave().catch(f=>o(`leaving the match failed: ${Ye(f)}`)),O();})(),q),Ie=()=>q||(q=(async()=>{l=false;let f=await Me();f.answer==="ok"?(await Z({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(o(`${f.cause}; leaving instead`),await Z({reason:"signal"},"left"),await n.leave().catch(M=>o(`leaving the match failed: ${Ye(M)}`))),O();})(),q),ce=null,Re=()=>(ce??=gd(I,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),ce),Me=async()=>{try{return await Ca({client:Re().client,gameId:()=>I.gameId},I.matchId,{},{signal:AbortSignal.timeout(lf)}),{answer:"ok"}}catch(f){return f instanceof G&&(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: ${Ye(f)}`}}},te=null,z=false,le=()=>{z=true,te!==null&&(e.clock.clearTimeout(te),te=null);},ct=async()=>{if(te=null,!z){try{await Re().client.post(`/v1/games/${encodeURIComponent(I.gameId)}/matches/${encodeURIComponent(I.matchId)}/heartbeat`,void 0,AbortSignal.timeout(df));}catch(f){if(f instanceof G&&(f.reason==="forbidden"||f.reason==="not_found")){o(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),le();return}o(`heartbeat failed: ${Ye(f)}`);}z||(te=e.clock.setTimeout(()=>{ct();},yd));}},Rn=()=>{z||te!==null||(te=e.clock.setTimeout(()=>{ct();},yd));};{let f=O;O=()=>{le(),ce?.dispose(),ce=null,f();};}let Qe=Promise.resolve().then(()=>a.init(I));s=Qe.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:hd,transport:"loopback"})),N.push(n.on("peerJoined",B)),N.push(n.on("peerLeft",(f,M)=>{R(f);let F=e.clock.now();for(let[re,_e]of T)F-_e>=fd&&T.delete(re);T.set(f,F),K.delete(f),m("leave",()=>a.leave?.(f,{cause:M}));})),N.push(n.on("error",f=>{o(`\u26A0 session error: ${f.message}`);})),N.push(n.on("matchEnded",f=>{q||so(y,f),pe("match ended",{reason:"match_ended",platform_reason:f});})),N.push(n.on("hostChanged",f=>{f!==r&&pe("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)B(f);try{await Qe,Rn();}catch(f){l=false,le(),d=true;for(let M of N.splice(0))M();for(let M of [...C.keys()])R(M);throw n.leave().catch(()=>{}),O(),f}return {matchId:n.matchId,localLink:S,onMatchEnded(f){y=f;},end:Ie,leave:X,stop:f=>pe(f,{reason:"stopped"}),done:$}}function so(t,e){try{t?.(e);}catch{}}function Ye(t){return t instanceof Error?t.message:String(t)}function lo(t,e){let n=async()=>{throw new _("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 _d(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,i=new Map,o=async s=>{r.isHost&&!io(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...s.signal===void 0?{}:{signal:s.signal}});let l={...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},a=s=>({...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0?{}:{clusterTargetId:s.clusterTargetId}});return {async serve(s,l={}){let d=await o(l);if(d.protocol!==Ke)return lo("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return lo("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(a(l)),g=await bd(s,{session:p,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return i.set(d.matchId,g),g.done.then(()=>{i.get(d.matchId)===g&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(s={}){let l=await o(s),d=s.onMatchEnded;if(l.protocol===Ke){let g=i.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),pf(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 Qn(),w=async()=>t.p2p.connect({...a(s),certificate:y}),S=await w(),A=yf(S,w,d,C=>{r.notifyMatchDisconnected(C).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(S.matchId,{redial:A.redial,abandon:A.abandon}),A.onClosed(()=>{e.get(S.matchId)?.abandon===A.abandon&&e.delete(S.matchId);})),A}let m=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:s.transports??[]}),c=await m(),p=gf(c,m,r,n);return n&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var vd="link_closed",cf="host_unreachable",uf=new Set(["failed","closed"]);function mf(t){return uf.has(t)?vd:cf}function pf(t,e,n){let r=e.localLink;e.onMatchEnded(n);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:t,protocol:"loopback",get state(){return i},send:(a,s)=>r.send(a,s),onMessage:a=>r.onMessage(a),onClose:a=>{o=a,r.onClose(s=>{i="closed",o?.(s);});},close:()=>r.close()}}function gf(t,e,n,r){let i=t.matchId,o=t,a="connected",s,l,d=[],m=false,c=false,p=y=>{if(a!=="closed"){a="closed";for(let w of d.splice(0))w();l?.(y);}},g=y=>{y.link.onMessage((w,S)=>s?.(w,S)),y.link.onClose(w=>{if(y!==o||a==="closed")return;if(m||!r){p(w);return}let S=n.matchSession;if(S.phase==="suspended"&&S.matchId===i){a="suspended";return}p(w);});};return g(t),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return a},send(y,w){a==="connected"&&o.link.send(y,w);},onMessage(y){s=y;},onClose(y){l=y;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}o.close(),p("closed");}},async redial(y){if(a==="closed"||m)return "closed";if(c)return "connected";c=true;let w;try{w=await e(y===void 0?{}:{deadlineAt:y});}finally{c=false;}return m||a==="closed"?(w.close(),"closed"):(o=w,g(w),a="connected",n.notifyMatchConnected(i),"connected")},abandon(y){a!=="closed"&&(a==="connected"&&o.close(),p(y));},onClosed(y){a==="closed"?y():d.push(y);}}}function yf(t,e,n,r,i,o=false){let a=t.matchId,s=t,l,d,m=[],c=[],p=[],g=false,y=false,w=false,S=false,A="connected",C=x=>{if(g)return;g=true,A="closed";for(let O of m.splice(0))O();for(let O of c.splice(0))O();for(let O of p.splice(0))O();let I=d;I&&queueMicrotask(()=>I(x));},b=x=>{for(let I of m.splice(0))I();for(let I of Le){let O=x.channels[I];try{O.binaryType="arraybuffer";}catch{}let $=Sn(I),N=q=>{let Z=yr(q?.data);Z!==null&&l?.(Z.data,$);};O.addEventListener("message",N),m.push(()=>O.removeEventListener("message",N));}},R=()=>s.peer(s.hostPlayerId),E=x=>{if(!(g||s.isHost)&&A!=="suspended"){if(r?.(x),o){A="suspended";return}C(x);}},T=x=>{for(let I of Le){let O=x.channels[I];if(typeof O.addEventListener!="function")continue;let $=()=>{R()===x&&E(vd);};O.addEventListener("close",$),m.push(()=>O.removeEventListener?.("close",$));}},V=x=>{b(x),T(x),!g&&(A="connected",i?.());},B=x=>{for(let I of c.splice(0))I();c.push(x.on("migrating",()=>{S=true;})),c.push(x.on("hostChanged",I=>{if(S=false,I===x.playerId){C("host_migrated_here");return}let O=R();O!==null&&V(O);})),c.push(x.on("peerJoined",I=>{I.playerId===x.hostPlayerId&&V(I);})),c.push(x.on("matchEnded",I=>{g||so(n,I),C(I);})),c.push(x.on("peerLeft",(I,O)=>{I===x.hostPlayerId&&E(mf(O));}));};B(s);let K=R();return K!==null&&V(K),{matchId:a,protocol:"p2p",get state(){return A},send(x,I){A==="connected"&&R()?.send(ot(x),ze(I));},onMessage(x){l=x;},onClose(x){d=x;},close(){y=true,C("closed"),s.leave().catch(()=>{});},async redial(){if(A==="closed")return "closed";if(A==="connected"||w)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");w=true;let x;try{for(let O of m.splice(0))O();for(let O of c.splice(0))O();s.close(),x=await e();}finally{w=false;}if(g)return y?x.leave().catch(()=>{}):x.close(),"closed";s=x,B(s);let I=R();if(I===null)throw s.close(),new L("connection_failed","this peer rejoined the match but the host never answered with a link");return V(I),"connected"},abandon(x){C(x);},onClosed(x){g?x():p.push(x);}}}function co(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},a=l=>{n.delete(r)&&(t.clock.clearTimeout(o.timer),i(l));};n.set(r,a),o.timer=t.clock.setTimeout(()=>a(void 0),t.timeoutMs??2e3);let s=false;try{s=t.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,i){n.get(r)?.(i);}}}var ff=12e4;function Xe(t,e){return {outcome:t,reason:e}}function wd(t){let e=false,n=new Map;return {api:{request(r){if(!t.bridge.parentSupports("purchases"))return Promise.resolve(Xe("unavailable","error"));if(e)return Promise.resolve(Xe("declined","busy"));let i=`purchase-${Pe()}`;return new Promise(o=>{let a={},s=d=>{n.delete(i)&&(e=false,t.clock.clearTimeout(a.timer),o(d));};e=true,n.set(i,s),a.timer=t.clock.setTimeout(()=>s(Xe("unavailable","error")),t.timeoutMs??ff);let l=false;try{l=t.bridge.requestPurchase(i,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(Xe("unavailable","error"));})}},settle(r){let i=r.outcome==="ok"||r.outcome==="declined"?r.outcome:"unavailable",o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.purchaseResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}if(i!=="ok"){o(Xe(i,Ya(r.reason)));return}let a=r.purchaseId;if(a===void 0){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),o(Xe("unavailable","error"));return}(async()=>{let s;try{s=await t.confirm(a);}catch{s="unknown";}if(s==="granted"){o({outcome:"ok",purchaseId:a});return}s==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(a)),o(Xe("unavailable","error"));})();}}}async function Sd(t,e){try{return (await pa(t,e)).granted?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}var hf=6e5;function Rd(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-${Pe()}`;return e=new Promise(i=>{let o={},a=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(o.timer),i(l));};n.set(r,a),o.timer=t.clock.setTimeout(()=>{a({outcome:"unavailable"});},t.timeoutMs??hf);let s=false;try{s=t.bridge.requestSignIn(r);}catch{}s||a({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var bf=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),_f=["utm_"];function kd(t){return bf.has(t)||_f.some(e=>t.startsWith(e))}var xd=16,Ad=512,vf=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,wf=/[\p{Cc}\p{Cf}]/u,Sf=/\p{Cs}/u,Ce="[gem] gem.share.request:";function Pd(t){let{frame:e,log:n}=t,r=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,o=a=>{n!==null&&(n===void 0?console.warn(a):n(a));};return {get available(){return i()!==null},request(a){let s=i();if(s===null)throw new Error(`${Ce} the arcade does not handle share here \u2014 check gem.share.available first`);if(a!==void 0&&(typeof a!="object"||a===null))throw new TypeError(`${Ce} pass { params }, or nothing`);let l=a?.params===void 0?{}:a.params;if(!Rf(l))throw new TypeError(`${Ce} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>xd)throw new TypeError(`${Ce} at most ${xd} params; got ${d.length}`);let m=[];for(let[c,p]of d){let g=JSON.stringify(c);if(!vf.test(c))throw new TypeError(`${Ce} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(kd(c))throw new TypeError(`${Ce} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Ce} param ${g}: values must be strings`);if(p.length>Ad)throw new TypeError(`${Ce} param ${g}: a value is at most ${Ad} characters`);if(wf.test(p))throw new TypeError(`${Ce} param ${g}: control and format characters are not allowed`);if(Sf.test(p))throw new TypeError(`${Ce} param ${g}: a value must be well-formed text`);m.push({key:c,value:p});}!s.requestShare(m)&&!r&&(r=true,o("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function Rf(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Pf="(any-pointer: coarse)";function Ef(t){let e=Array.isArray(t)?t:[t],n=[],r=1e4;for(let i of e){if(typeof i!="number"||!Number.isFinite(i)||i<0)return null;if(n.length===99||r===0)continue;let o=Math.min(Math.trunc(i),1e4,r);n.push(o),r-=o;}return n.length%2===0&&n.pop(),n.every(i=>i===0)?[]:n}function Ed(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},i=r.navigator,o,a=new Set,s=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia(Pf),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,c)=>{a.has(m)||(a.add(m),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return s()||l()},vibrate(m){let c=s();if(!c&&!l())return false;let p=Ef(m);if(p===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(i?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(c)try{return i.vibrate(p)===!0}catch{return false}let g=e.requestVibrate(p);return g||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),g}}}var Tf=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Td(t){if(typeof t!="string"||!Tf.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function at(){return {declared:false,grantable:false,heldLimitReached:false}}function Cd(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Td(n.resets_at),i=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...at(),...i};let o=n.remaining_today,a=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,s=n.next_eligible_at,l=Td(s),d=n.held_limit_reached===true,m=s!=null,c=o!=null&&a===void 0;return {declared:true,grantable:n.grantable===true&&e&&a!==0&&!c&&!m&&!d,...a===void 0?{}:{remainingToday:a},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var Cf=18e4,uo=32,If=/^[a-z0-9_-]+$/,Mf="rewarded_requires_user_gesture";function Of(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var Lf=1e3;function Gf(){let t=globalThis,e=t.navigator?.getGamepads,n=t.performance?.now;if(typeof e!="function"||typeof n!="function")return;let r=n.call(t.performance),i=e.call(t.navigator);for(let o=0;o<i.length;o+=1){let a=i[o]?.timestamp;if(typeof a=="number"&&r-a>=0&&r-a<=Lf)return true}return false}var Id=1e4;function Df(t){return t==="interstitial"||t==="rewarded"}function Md(t){return typeof t=="string"&&t!==""&&t.length<=uo&&If.test(t)}function $f(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function fr(t){return typeof t=="string"?JSON.stringify(t):typeof t}function Od(t){let e=false,n=new Map,r=new Map,i=new Set,o=d=>{try{t.onDropped?.(d);}catch{}},a=false,s=d=>{if(a)return;a=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(at());let c=r.get(d);if(c!==void 0)return c;let p=new Promise(g=>{let y={},w=b=>y.done===true?false:(y.done=true,t.clock.clearTimeout(y.timer),g(b),true),S=(b,R)=>{!w(at())||i.has(b)||(i.add(b),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${R}. Said once.`));},A=b=>{S($f(b),`the read failed (${b instanceof Error?b.message:fr(b)})`);},C;try{C=Promise.resolve(m(d,AbortSignal.timeout(Id)));}catch(b){C=Promise.reject(b);}y.timer=t.clock.setTimeout(()=>{S("timeout","no answer within 10 s");},Id),C.then(b=>{try{w(Cd(b,t.bridge.parentSupports("ads")));}catch(R){A(R);}},A);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return Md(d)?l(d):(o(`gem.ads.rewardedStatus(${fr(d)}) answered not grantable: a placement is 1..${String(uo)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(at()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let m=d?.placement,c=d?.format;if(!Md(m)||!Df(c))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${fr(m)}, format ${fr(c)}. A placement is 1..${String(uo)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});if(c==="rewarded"){let g;try{g=(t.userActivation??Of)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??Gf)()===!0&&(g=!0);}catch{}if(g===false){let y=`${Mf}: gem.ads.requestAd("${m}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return o(y),s(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${Pe()}`;return new Promise(g=>{let y={},w=A=>{n.delete(p)&&(e=false,t.clock.clearTimeout(y.timer),g(A));};e=true,n.set(p,w),y.timer=t.clock.setTimeout(()=>{w({outcome:"unavailable"});},t.timeoutMs??Cf);let S=false;try{S=t.bridge.requestAd(p,m,c);}catch{}S||w({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:m});}}}var mo=16384;function Ld(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:Ff(e)}function Ff(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var qf=1e4,jf=5e3;function Gd(t){let e=null,n=false,r=[],i=new Map,o=()=>{for(let a of r.splice(0))a();};return {api:{get current(){return e},wait(a=jf){return n?Promise.resolve(e):new Promise(s=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{t.clock.clearTimeout(m),l(),s(e);},m=t.clock.setTimeout(()=>{l(),s(e);},a);r.push(d);})},put(a){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let s=Ld(a);if(s===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(s>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(a)),d=`device-settings-${Pe()}`;return new Promise(m=>{let c={},p=y=>{i.delete(d)&&(t.clock.clearTimeout(c.timer),y==="stored"&&(e=l,n=true,o()),m(y));};i.set(d,p),c.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??qf);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(a){let s=a.settings;e=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,n=true,o();},settle(a){let s=a.outcome==="stored"||a.outcome==="too_large"?a.outcome:"unavailable",l=i.get(a.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${s}) for an unknown requestId: `+JSON.stringify(a.requestId));return}l(s);}}}var st=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 Nf=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Uf(t){return typeof t=="string"&&Nf.test(t)}function hr(t){if(t===null||Uf(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 Dd(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function po(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!n.includes(i)&&n.push(i);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function br(t,e){let n=[];for(let r of Array.isArray(e)?e:[]){if(n.length===4)break;if(typeof r!="object"||r===null)continue;let{id:i,label:o}=r;typeof i!="string"||i.length===0||i.length>32||typeof o!="string"||o.trim().length===0||n.some(a=>a.id===i)||n.push({id:i,label:o.trim().slice(0,40)});}return n.length===0?{settings:t===true}:{settings:t===true,items:n}}function $d(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Bf(t){let e=t.untrusted,n=Oe(e.displayName),r=e.displayTag||e.displayHandle,i=r?Oe(r):void 0,o=t.discriminator||t.displayTag,a=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,s=t.avatarIconUrl||t.avatarUrl,l={displayName:n,displayHandle:i??n,badges:(t.badges??[]).map(p=>({itemId:p.itemId,iconUrl:p.iconUrl}))};t.playerId&&(l.playerId=t.playerId),a&&(l.discriminator=a),i&&(l.displayTag=i),s&&(l.avatarIconUrl=l.avatarUrl=s);let d=t.boost,m=(d?.multipliers??[]).map(p=>({currencyId:p.currencyId,currencySlug:p.currencySlug,multiplier:p.multiplierBp/1e4})),c=m.some(p=>p.multiplier>1);return l.boost=c&&d?.expiresInDays?{active:c,multipliers:m,expiresInDays:d.expiresInDays}:{active:c,multipliers:m},l}var Vf=1e4,lt=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??ye,this.inbound=new An(this.clock),this.outbound=new An(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>Lr(s,e.origin))||Wa(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=vt["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!Lr(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=Ka(bt,i.versions);return a===null?(o.onmessage=null,o.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${bt.min}..v${bt.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=a,o.onmessage=s=>this.receive(s.data,s.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:U,type:"gem.handshake.accept",v:a,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:U,type:"gem.ready"});}settled(e=Vf){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=o=>{this.clock.clearTimeout(i),n(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem: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.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:U,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:U,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let 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:Dd(e.origin.x),y:Dd(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=hr(e);return n===void 0||this.state!=="connected"||!this.parentSupports("portraitBorders")?false:this.send(n===null?{gem:U,type:"gem.portraitBorders"}:{gem:U,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:U,type:"gem.walletDisplay",...po(e,n?.only)})}setMenu(e,n){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:U,type:"gem.menu",...br(e,n)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:U,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:U,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:U,type:"gem.frameStats",fps:$d(e.fps,1e3),frameTimeP95Ms:$d(e.frameTimeP95Ms,1e5)}),true)}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,i,o,a){return this.send({gem:U,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...a===void 0?{}:{catalogId:a}})}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})}requestSignIn(e){return this.send({gem:U,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,i){return this.send({gem:U,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...i===void 0?{}:{params:i}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(_t)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(_t)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(_t)&&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}});}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=vt[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||Fd(n);}}dispatchInbound(e,n){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=vt[r];if(!i)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let o=Ba(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let a=i(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.menuSelect":this.options.onMenuSelect?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=n[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return Fd(n.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(Bf(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:U,type:"gem.screenshot.denied",reason:e,retryable:n});}};function Fd(t){for(let e of t)try{e?.close?.();}catch{}}var qd="https://api.gemarcade.com";function go(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 Hf=new Set(["localhost","127.0.0.1","[::1]"]);function jd(t){let e=go(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!Hf.has(n.hostname)?"it is a plaintext http address that is not loopback. An embedder may name an https root, or http on localhost for a rig running the whole stack on one machine \u2014 the play token travels on every request to it":null}var Kf=Object.freeze(["https://gemarcade.com","https://meme-games.com","http://gemarcade.localhost","gemarcade://localhost"]),Jf=qd,Nd=8e3,yo=15e3,zf=9e4,Yf=1/0,Xf=8e3,Qf=5e3,Zf=5e3;async function eh(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 dt(t){let e=null,n=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){n=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||n?Promise.resolve(e):new Promise(o=>{let a=()=>{let d=r.indexOf(s);d>=0&&r.splice(d,1);},s=d=>{t.clearTimeout(l),a(),o(d);},l=t.setTimeout(()=>{a(),o(e);},i);r.push(s);})}}}function qR(t={}){let e=t.clock??ye,n=t.log===void 0?u=>console.info(u):t.log,r=t.baseUrl??void 0;if(r!=null){let u=go(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=_s(typeof window>"u"?void 0:window.location?.search),o=Ki();o.mark("sdk created");let a=()=>Jt(ee.gameVersion,t.clientVersion?.gameVersion),s=new Fn({client:()=>tn,clock:e,gameId:()=>ee.identity?.gameId??null,playerId:()=>ee.identity?.playerId??null,environment:()=>{let u=a();return {sdk_version:Io(),...u===null?{}:{game_version:u}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),l=Rl(()=>{o.mark("engaged"),s.release(),j.reportEngaged();},typeof window>"u"?{}:window),d=u=>{if(u===false)return null;let k=u?.attempts??Yf,D=u?.budgetMs??zf;return !(k>0)||!(D>0)?null:{attempts:k,budgetMs:D,maxDelayMs:u?.maxDelayMs??Xf}},m=u=>{u.on("created",()=>{o.mark("room created");}),u.on("joined",()=>{o.mark("room joined");}),u.on("matchAllocationStarted",()=>{o.mark("allocation started");}),u.on("matchReady",()=>{o.mark("match ready");}),u.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new st;let c=t.allowedEmbedders;if(c!=null&&!Array.isArray(c))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let p=Array.from(c??[]),g=p.filter(u=>typeof u!="string"||!Or(u));if(g.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${g.length===1?"an entry":"entries"} that ${g.length===1?"is":"are"} not an origin: ${g.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let y=Object.freeze([...new Set([...Kf,...p])]),w=dt(e),S=dt(e),A=dt(e),C=xs(n),b=dt(e),R=t.manageAudio===false?null:Il();t.selectableText!==true&&Ml();let E=null,T=()=>{E!==null&&(S.current!==null&&S.current.muted===E||j.reportMuted(E));},V,B,K=-1/0,x=null,I=()=>{if(V===void 0||x!==null||V===B)return;let u=K+1e3-e.now();if(u>0){x=e.setTimeout(()=>{x=null,I();},u);return}j.showPortraitBorders(V)&&(B=V,K=e.now());},O=null,$=null,N=()=>{if(O===null)return false;let u=JSON.stringify(po(O.visible,O.only));return u===$?j.parentSupports("walletDisplay"):j.setWalletVisible(O.visible,O)?($=u,true):false},q=null,Z=null,pe=()=>{if(q===null)return false;let u=typeof q.onSettings=="function",k=JSON.stringify(br(u,q.items));return k===Z?j.parentSupports("gameMenu"):j.setMenu(u,q.items)?(Z=k,true):false},X=Ol({report:u=>j.reportFrameStats(u)}),Ie=false,ce=jl(()=>Co,()=>Ie),Re=u=>{let k=Ie&&!u,D=Ie!==u;if(Ie=u,k&&ce.close(),!!D)try{t.onDevToolsPermissionChange?.(u);}catch(ne){n?.(`[gem] onDevToolsPermissionChange threw: ${ne instanceof Error?ne.message:String(ne)}`),queueMicrotask(()=>{throw ne});}},Me=r??Jf,te=r!==void 0,z,le=u=>(n?.(`[gem] token refused: ${u}`),t.onError?.("internal",u),false),ct=(u,k)=>{if(u===void 0)return k!==void 0?le("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let D=jd(u);return D!==null?le(`the embedder named an API root that cannot be used: ${D}. Its value is withheld here rather than written to logs.`):z!==void 0&&z!==u?le("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(z=u,te||(Me=u),true)},Rn=window.location?.origin,Qe=null,f=-1/0,M=2e3,F=new Set,re=u=>Qe!==false?Promise.resolve(true):new Promise(k=>{let D=e.setTimeout(()=>{F.delete(ne),k(false);},u),ne=()=>{e.clearTimeout(D),F.delete(ne),k(true);};F.add(ne);}),_e=()=>{},Ze=null,j=new lt({allowedEmbedders:y,...typeof Rn=="string"&&Rn!==""?{selfOrigin:Rn}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","vibration","frameStats","walletDisplay","gameMenu","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:u=>{Ze=u,t.onRefused?.(u);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:u=>{ee.onBridgeState(u),u!=="connected"&&X.setRequested(false),$=null,Z=null,B=void 0,u==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Ze===null?"":` (${Ze})`)+", so it has no player, saves, config or rooms. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders."),_e()),u==="connected"&&(o.mark("bridge connected"),Ud(),T(),I(),N(),pe(),j.unbiddenLaunch&&!l.engaged&&s.hold(),s.startSession(),l.engaged&&j.reportEngaged()),t.onStateChange?.(u);},onPlayer:u=>{w.set(u),t.onPlayer?.(u);},onPrefs:u=>{let k={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true};S.set(k),R?.setMuted(k.muted),X.setRequested(k.showFrameStats&&j.parentSupports("frameStats")),t.onPrefs?.(k);},onCohorts:u=>{let k=Object.freeze(u.cohorts.map(D=>Object.freeze({experimentId:D.experimentId,variantKey:D.variantKey})));A.set(k),t.onCohorts?.(k);},onEarnAllowanceChanged:()=>C.emit(),onViewport:u=>{let k=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left}),reserved:Object.freeze((u.reserved??[]).map(ne=>Object.freeze({x:ne.x,y:ne.y,width:ne.width,height:ne.height})))});b.set(k);let D=Gl();Dl(D,k.insets),Fl(D,k.reserved,$l()),t.onViewport?.(k);},onPause:u=>{s.setPaused(u.paused),X.setPaused(u.paused),t.onPause?.(u.paused);},onMenuSelect:u=>{if(q===null)return;if(u.entry==="settings"){q.onSettings?.();return}(br(false,q.items).items??[]).some(D=>D.id===u.id)&&q.items?.find(D=>D.id===u.id)?.onSelect?.();},onWillTerminate:u=>{s.endSession(u.reason),t.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let k=u.garden;if(Re(u.allowDevTools===true),!ct(u.apiBaseUrl,k))return;let D=u;ee.onToken(D);let ne=ee.identity;ne&&(_r.set(ne),fo||(fo=true,ue.reconcileSeats().catch(()=>{}))),ho.push({token:D.token,expiresAt:D.expiresAt});},onTokenDenied:u=>{Re(false),ee.onDenied(u);},onScreenshot:(u,k,D)=>{El(u,k,D,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Tl(j,t.onFeedbackContext);},onDevtools:u=>{u==="close"?ce.close():u==="open"?ce.openFrom("platform").catch(()=>{}):ce.isOpen?ce.close():ce.openFrom("platform").catch(()=>{});},onRoomEvent:u=>ue.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>ue.handleSeated(u.roomId),onAutoStartFailedEvent:u=>ue.handleAutoStartFailed(u.roomId,u.code),onSocketState:u=>{let k=Qe;if(Qe=u.connected,u.connected)for(let ne of [...F])ne();if(!u.connected||k===true)return;let D=e.now();D-f<M||(f=D,ue.reconcile().catch(()=>{}));},onSignalEvent:u=>{let k=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};rn.handleSignalEvent(u.matchId,u.event,k),u.event==="matchEnded"&&ue.reconcile({matchId:u.matchId,...typeof k.reason=="string"?{reason:k.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(kn.handleMatchEnded(u.matchId,u.reason),ue.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),en.handleEvent(u);},onClusterTarget:u=>pt.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>gt.accept(u),onLocalServerDenied:u=>gt.refuse(u),onPartyResult:u=>_o.settle(u.requestId,u.partyId),onPurchaseResult:u=>wo.settle(u),onDeviceSettings:u=>{mt.receive(u),t.onDeviceSettings?.(mt.api.current);},onDeviceSettingsResult:u=>mt.settle(u),onAdResult:u=>Ro.settle(u),onSignInResult:u=>ko.settle(u),onFriendChallengeResult:u=>xo.settle(u)}),en=new it({bridge:j}),_r=dt(e);_e=()=>{_r.release(),w.release(),A.release();},j.currentState==="refused"&&_e();let fo=false,vr=new Set,ut,ho={current:()=>ut,subscribe:u=>(vr.add(u),ut!==void 0&&u(ut),()=>vr.delete(u)),push:u=>{ut=u;for(let k of [...vr])try{k(u);}catch(D){n?.(`[gem] a server-token listener threw: ${D instanceof Error?D.message:String(D)}`);}}},ee=Ul({bridge:j,clock:e,onStateChange:(u,k)=>{if(u==="ready"){if(o.mark("token ready")){let D=o.marks.find(ne=>ne.name==="token ready")?.at;s.trackPlatform("gem_boot_ready",D===void 0?{}:{boot_ms:Math.max(0,Math.round(D))});}}else u==="lost"&&(o.mark("token lost"),s.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(u,k);}}),bo=()=>{let u=ee.identity;return !u||ee.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},Ud=()=>{o.mark("token requested"),ee.source.get().catch(()=>{});},_o=co({bridge:j,clock:e}),vo={},wo=wd({bridge:j,clock:e,onDropped:u=>t.onError?.("internal",u),confirm:async u=>vo.confirm?.(u)??"unknown"}),mt=Gd({bridge:j,clock:e,onDropped:u=>t.onError?.("internal",u)}),So={},Ro=Od({bridge:j,clock:e,onDropped:u=>t.onError?.("internal",u),readAvailability:(u,k)=>So.read?.(u,k)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),ko=Rd({bridge:j,clock:e,onDropped:u=>t.onError?.("internal",u)}),xo=ks({bridge:j,clock:e,onDropped:u=>t.onError?.("internal",u)}),pt=Ls({bridge:j,clock:e}),gt=ql({bridge:j,clock:e}),wr=u=>{let k=j.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return k&&window.removeEventListener("message",wr),k};window.addEventListener("message",wr);let nn=kl(window,wr),Bd=nn?.capture,Sr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Sr?.domInteractive!==void 0&&Sr.domInteractive>0&&o.mark("document parsed",Sr.domInteractive),Bd?.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 Rr=t.handshakeWarningMs;Rr!==null&&n&&e.setTimeout(()=>{let u=nn===null?"no capture script ran":`capture: ${nn.delivered} offer(s) delivered, ${nn.stale} stale, ${nn.capture.dropped} evicted${nn.capture.late?", installed late":""}`;if(j.currentState==="connected"){n(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${u}`);return}n(`[gem] no completed handshake after ${Rr??Nd}ms (bridge state: ${j.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+u);},Rr??Nd);let Vd=mr({get baseUrl(){return Me},tokenSource:ee.source,get defaultQuery(){let u=ee.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),tn=new Fe({transport:Vd,clock:e}),ge={client:tn,gameId:()=>ee.identity?.gameId??""};vo.confirm=u=>Sd(ge,u),So.read=(u,k)=>La(ge,"players","me",u,{signal:k});let Hd=()=>ee.identity?.channel??"release",Ao=new Ft(ge,Hd),Po=async u=>(await Ao.load())?.currency(u)?.id??void 0,Eo=Mt(ge,Vr,{identity:bo,resolveCurrencyId:Po}),kr=async u=>{let k=await _r.wait(u);if(k)return k;throw j.currentState==="refused"?new se("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new se("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},xr=d(t.autoReconnect),ue=Mi({client:tn,clock:e,gameId:()=>ee.identity?.gameId??null,playerId:()=>ee.identity?.playerId??null,awaitGameId:async()=>(await kr(yo)).gameId,resolveParty:_o.resolve,resolveClusterTargets:pt.resolveList,refreshClusterTargets:pt.refresh,ensureLocalServer:gt.ensure,localHostAvailable:gt.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>ee.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:(u,k)=>Ar.redialMatch(u,k),abandon:(u,k)=>Ar.abandonMatch(u,k)}}});m(ue),wl({analytics:s,rooms:ue});let rn=vl({client:tn,clock:e,rooms:ue,bridge:j,gameId:()=>ee.identity?.gameId??"",baseUrl:()=>Me,resolveClusterTarget:pt.resolve,boot:o,...t.log===void 0?{}:{log:t.log}}),To=Wi(o,n),kn=od({client:tn,clock:e,rooms:ue,signaling:()=>en.channel(),signalingReady:re,log:n??(()=>{})}),Ar=_d({rooms:ue,p2p:{connect:u=>To(rn.connect(u)),session:u=>rn.session(u)},dedicated:{connect:(u=>dr(o,"welcome",kn.connect(u),n))},clock:e,identity:()=>ee.identity,apiBaseUrl:()=>Me,tokens:ho,room:()=>ue.currentRoom,autoReconnect:xr!==null,...t.log===void 0?{}:{log:t.log}}),Wd=async()=>(await kr(yo)).playerId,Co={client:tn,boot:o,get identity(){return ee.identity},awaitIdentity:(u=yo)=>kr(u),awaitBridge:u=>j.settled(u),get player(){return w.current},awaitPlayer:(u=Qf)=>w.wait(u),me:Eo,characters:new Lt(ge,void 0,bo,Po),transfers:new Dt(ge,Vr,Eo.inventory),gameConfig:Ao,purchases:wo.api,deviceSettings:mt.api,ads:Ro.api,account:ko.api,share:Pd({frame:j,log:t.log}),vibration:Ed({frame:j,log:t.log}),analytics:s,leaderboards:new Mn(ge),challenges:new Tn(ge),showcase:new On(ge,Wd),friends:new Ln(ge,{challenge:xo.challenge,...i===void 0?{}:{launchedChallengeId:i}}),platform:new Dn(ge,C,n),profiles:new $n(ge),functions:new Be((u,k)=>va(ge,u,k)),get prefs(){return S.current},get cohorts(){return A.current},get viewport(){return b.current},awaitCohorts:(u=Zf)=>A.wait(u),reportMuted:u=>{E=!!u,T();},showPortraitBorders:u=>{let k=hr(u);k!==void 0&&(V=k,I());},cueReward:u=>j.cueReward(u),setWalletVisible:(u,k)=>{let D=Array.isArray(k?.only)?[...k.only]:void 0;return O=D===void 0?{visible:u===true}:{visible:u===true,only:D},N()},setMenu:u=>(q={...typeof u?.onSettings=="function"?{onSettings:u.onSettings}:{},...Array.isArray(u?.items)?{items:u.items.map(k=>({...k}))}:{}},pe()),exit:u=>eh(ue,j,u,s),frame:j,devtools:ce,rooms:ue,dedicatedServer:{listClusterTargets:u=>kn.listClusterTargets(u),connect:(u=>dr(o,"welcome",kn.connect(u),n)),handleMatchEnded:(u,k)=>kn.handleMatchEnded(u,k)},p2p:{handleSignalEvent:(u,k,D)=>rn.handleSignalEvent(u,k,D),session:u=>rn.session(u),connect:u=>To(rn.connect(u))},match:Ar};return Co}
|
|
2
2
|
export{Kf as ARCADE_EMBEDDERS,Fn as AnalyticsApi,se as AuthError,Tn as ChallengesApi,mo as DEVICE_SETTINGS_MAX_BYTES,_ as DedicatedServerError,Ue as FriendChallengeError,Ln as FriendsApi,Be as FunctionsApi,G as GemApiError,Fe as GemClient,de as GemConfigError,lt as GemFrame,Ht as GemFunctionError,oe as GemSaveError,st as GemUnframedError,Mn as LeaderboardsApi,ls as MAX_PERIODS_BACK,Dm as PLATFORM_EVENTS,Dn as PlatformApi,Bt as PlatformCurrenciesApi,Vt as PlatformEarnAllowanceApi,fe as PlayerText,$n as ProfilesApi,Ge as PurchaseRefusal,On as ShowcaseApi,ie as TransportRefusal,Un as UNRELIABLE_CHANNEL_LABEL,Oe as asPlayerText,Ki as createBootTimeline,qR as createGem,eh as leaveAndExit,ve as mapIdentity,dr as markOnResolve,lm as platformIconUrl,jn as presentJoinCredential,yn as readTemplateTransports,Bn as readTransportAdvert,Wi as reportOnResolve,dn as text,Qt as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.game.js.map
|
|
3
3
|
//# sourceMappingURL=gem-web-sdk.game.js.map
|