@indiegems/gem-web-sdk 17.0.0 → 18.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/dist/function.d.ts +4 -0
- package/dist/game.d.ts +11 -1
- package/dist/gem-web-sdk.bridge.js +2 -2
- package/dist/gem-web-sdk.conformance.js +3 -3
- package/dist/gem-web-sdk.esm.js +3 -3
- package/dist/gem-web-sdk.function.js +3 -3
- package/dist/gem-web-sdk.game.js +3 -3
- package/dist/gem-web-sdk.min.js +3 -3
- package/dist/gem-web-sdk.sdk.js +3 -3
- package/dist/gem-web-sdk.server.js +2 -2
- package/dist/index.d.ts +17 -3
- package/dist/sdk.d.ts +11 -1
- package/docs/analytics.md +15 -8
- package/docs/api/api-reference-function.md +16 -5
- package/docs/api/api-reference-game.md +109 -5
- package/docs/api/api-reference-server.md +6 -2
- package/docs/api/reference.json +102 -8
- package/docs/changelog.md +21 -0
- package/docs/getting-started.md +1 -1
- package/docs/manifest.json +10 -10
- package/docs/server-bundles.md +2 -2
- package/docs/what-a-game-must-do.md +29 -0
- package/package.json +1 -1
- package/schema/bridge.v1.json +58 -0
- package/schema/capabilities.public.json +6 -0
package/dist/gem-web-sdk.sdk.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Om=Object.defineProperty;var Gm=(t,e)=>{for(var n in e)Om(t,n,{get:e[n],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:17.0.0]";function Qa(){let t=globalThis.__gemWebSdkVersion;if(typeof t!="string")return "";let e=t.lastIndexOf(":"),n=t.lastIndexOf("]");return e<0||n<=e+1?"":t.slice(e+1,n)}var Lm={initialDelayMs:2e3,maxDelayMs:6e4};function Dm(t,e){return e!==void 0?!e:t==="chain_exhausted"}var wt=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;retry=null;failures=0;notBefore=0;disposed=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new ne(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.pastChainCeiling())throw new ne("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new ne(this.failure??"unavailable","the embedder asked for no new token yet; one is asked for when that wait is over");return this.refresh(this.nextReason())}pastChainCeiling(){return this.grant===null||this.seconds()<this.grant.chainEndsAt?false:(this.enter("lost","chain_exhausted"),true)}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}dispose(){this.disposed=true,this.cancelRetry();}scheduleRetry(e){if(this.cancelRetry(),this.failures+=1,this.notBefore=e===void 0?0:this.options.clock.now()+e,this.disposed)return;let{initialDelayMs:n,maxDelayMs:r}=Lm,i=Math.min(r,n*2**(this.failures-1)),o=Math.max(i/2,e??0)+Math.random()*(i/2);this.retry={handle:this.options.clock.setTimeout(()=>this.retryNow(),o)};}retryNow(){this.retry=null,this.notBefore=0,!(this.state==="lost"||this.pastChainCeiling())&&this.refresh(this.nextReason()).catch(()=>{});}cancelRetry(){this.retry!==null&&(this.options.clock.clearTimeout(this.retry.handle),this.retry=null);}refresh(e){if(this.inFlight)return this.inFlight;this.cancelRetry();let n=this.generation;this.enter("pending");let r=this.options.request(e).then(i=>{if(n!==this.generation)throw new ne("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=Fm(i),{retryable:s,retryAfterMs:a}=i??{};throw n===this.generation&&(Dm(o,typeof s=="boolean"?s:void 0)?this.enter("lost",o):(this.scheduleRetry(typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0),this.enter("degraded",o))),i instanceof ne?i:new ne(o,String(i))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){(e==="ready"||e==="lost")&&this.cancelRetry(),e==="ready"&&(this.failures=0,this.notBefore=0),this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},ne=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Fm(t){if(t instanceof ne)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var se=class t extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof t)return true;let n=e;return n?.name==="TransportRefusal"&&n.retryable===false}},Xn=["if-match","if-none-match"],Za=4096;function $m(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let i=n.toLowerCase();if(!Xn.includes(i)||r===void 0)continue;let o=typeof r=="string"?qm(r):r;if(typeof o!="string"||o.length>Za||!Nm(o))throw new se(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${Za} characters, or contains a character outside the range an HTTP header value may carry. This is a malformed request, not a server failure; the value is withheld here rather than written to logs.`);o!==""&&(e[i]=o);}return Object.freeze(e)}function qm(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 Nm(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 jm(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new se("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new se("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function es(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=$m(i.headers),s=jm(i),a=Object.freeze({...i,headers:o,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await t(a,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let c=await e.tokenSource.get(),u=await t(a,c);if(u.status===401)throw e.tokenSource.close("unavailable"),new ne("unavailable","the server refused a freshly minted token");return u}}}function Yn(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Bm(e))}function Qn(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 Mi(t){return new TextDecoder().decode(Qn(t))}function Bm(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var M=class extends Error{constructor(n,r,i,o,s){super(`${n} (${r}): ${i}`);this.reason=n;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},rs=new WeakMap;function is(t){return rs.get(t)??{}}var Um=new Set([408,429,500,502,503,504]),Wm=6e4,os=new WeakMap;function as(t,e){os.set(t,e);}function ts(t){return t!==null&&(t.reason==="rate_limited"||t.retryAfterSeconds!==void 0)}function Vm(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new se(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(t)}. This is a configuration fault, not a server failure.`);return t}var We=class{constructor(e){this.options=e;}options;async get(e,n){return this.send({method:"GET",path:e,signal:n},true)}async getWithEtag(e,n={}){let r=await this.sendRaw({method:"GET",path:e,...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{headers:{"if-none-match":n.ifNoneMatch}}},true),i=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...i}:{modified:true,body:r.body,...i}}async put(e,n,r,i={}){return this.send({method:"PUT",path:e,body:n,signal:r,...Ht(i)},i.replaySafe===true,i.retryRateLimited!==false)}async post(e,n,r,i={}){return this.send({method:"POST",path:e,body:n,signal:r,...Ht(i)},i.replaySafe===true,i.retryRateLimited!==false)}async postBytes(e,n,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...Ht(i)},i.replaySafe===true,i.retryRateLimited!==false);return {bytes:Hm(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,...Ht(i)},i.replaySafe===true,i.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Ht(r)},r.replaySafe===true,r.retryRateLimited!==false)}async send(e,n,r=true){return (await this.sendRaw(e,n,r)).body}async sendRaw(e,n,r=true){let i=n?Vm(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw ns(e.signal);let s=e.signal===void 0?void 0:os.get(e.signal);for(let a=0;a<i;a++){if(a>0){let c=this.backoffMs(a,o);if(ts(o)&&s!==void 0&&c>=s())throw o;await this.backoff(c,e.signal);}if(e.signal?.aborted)throw ts(o)&&s!==void 0&&s()<=0?o:ns(e.signal);let l;try{l=await this.options.transport.request(e);}catch(c){if(ne.isAuthError(c)||se.isRefusal(c)||e.signal?.aborted||Km(c))throw c;o=new M("unavailable",0,String(c));continue}if(l.status>=200&&l.status<300||l.status===304)return l;let d=Jm(l);if(!Um.has(l.status)||l.status===429&&!r)throw d;o=d;}throw o??new M("unavailable",0,"no attempt was made")}backoffMs(e,n){let r=n?.retryAfterSeconds,i=r!==void 0?r*1e3:2**(e-1)*250,o=2**(e-1)*250;return Math.min(Math.max(i,o),Wm)}backoff(e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=this.options.clock,o=false,s=false,a,l=()=>{o||(o=true,s&&i.clearTimeout(a),n?.removeEventListener("abort",l),r());};n?.addEventListener("abort",l,{once:true}),a=i.setTimeout(l,e),s=true,o&&i.clearTimeout(a);})}};function Hm(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 Ht(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function ns(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Km(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Jm(t){let e=Xm(t),n=Qm(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&rs.set(e,r),e}var zm=new Map([["insufficient_funds","insufficient_funds"]]);function Xm(t){let{status:e,body:n}=t,r=Ym(n),i=t.retryAfterSeconds??ep(n),o=Zm(n),s=o===void 0?void 0:zm.get(o);if(s!==void 0)return new M(s,e,r,void 0,o);switch(e){case 304:return new M("not_modified",e,r);case 400:case 422:return new M("invalid",e,r,void 0,o);case 403:return new M("forbidden",e,r,void 0,o);case 404:return new M("not_found",e,r,void 0,o);case 402:return new M("insufficient_funds",e,r,void 0,o);case 409:return new M("conflict",e,r,void 0,o);case 412:return new M("precondition_failed",e,r,void 0,o);case 413:return new M("too_large",e,r,void 0,o);case 429:return new M("rate_limited",e,r,i,o);default:return new M("unavailable",e,r,i,o)}}function Ym(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 Qm(t){let n=t?.error?.details;return n===null?void 0:n}function Zm(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function ep(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function ss(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function ls(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/add`;return t.client.post(s,i,o?.signal)}async function ds(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function cs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}`;return t.client.delete(r,n?.signal)}async function us(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/claim`;return t.client.post(s,i,o?.signal)}async function ms(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function ps(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function gs(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function fs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function ys(t,e,n,r,i){let o=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(o,i?.signal)}async function hs(t,e,n,r,i){let o=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(o,i?.signal)}async function bs(t,e,n,r){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.delete(i,r?.signal)}async function vs(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function _s(t,e,n,r,i,o){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function ws(t,e,n){let r=`/v1/games/${_(t.gameId())}/avatars-3d/${_(e)}/owned`;return t.client.get(r,n?.signal)}async function Ss(t,e,n){let r=`/v1/games/${_(t.gameId())}/config/channels/${_(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function ks(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.get(r,n?.signal)}async function Rs(t,e,n){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function As(t,e,n,r,i){let o=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function xs(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Ps(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/items/${_(r)}`;return t.client.get(o,i?.signal)}async function Ts(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${_(e)}/${_(n)}/${_(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function Es(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders/${_(r)}`;return t.client.get(o,i?.signal)}async function Is(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}`;return t.client.get(o,i?.signal)}async function Cs(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/catalogs/${_(r)}/recipes/${_(i)}/availability`;return t.client.get(s,o?.signal)}async function Ms(t,e,n,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Oi(t,e,n,r,i){let o=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Os(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}/friends`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function Gs(t,e,n){let r=`/v1/showcase/friends/${_(e)}`;return t.client.get(r,n?.signal)}async function Ls(t,e){let n=`/v1/games/${_(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function Ds(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}`;return t.client.get(r,n?.signal)}async function Fs(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function $s(t,e){let n=`/v1/games/${_(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function Zn(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function qs(t,e,n){let r=`/v1/profiles/players/${_(e)}`;return t.client.get(r,n?.signal)}async function Ns(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function js(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return t.client.get(r,n?.signal)}async function Bs(t,e,n,r){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.get(i,r?.signal)}async function Us(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function Ws(t,e,n){let r=`/v1/inventory/transfers/${_(e)}`;return t.client.get(r,n?.signal)}async function Vs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function Hs(t,e,n){let r=`/v1/games/${_(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true,retryRateLimited:false})}async function Ks(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Js(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/platform-funded-game-inventory-purchases`;return t.client.post(o,r,i?.signal)}async function zs(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Xs(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ys(t,e){return t.client.get("/v1/characters",e?.signal)}async function Qs(t,e,n,r){let i=`/v1/settings/${_(e)}/${_(n)}`;return t.client.get(i,r?.signal)}async function Zs(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function el(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${_(e)}/${_(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function tl(t,e){let n=new URLSearchParams;e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function nl(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i="/v1/friends"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function rl(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function il(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function ol(t,e,n,r){let i=`/v1/games/${_(t.gameId())}/matches/${_(e)}/end`;return t.client.post(i,n,r?.signal)}async function al(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/max`;return t.client.post(s,i,o?.signal)}async function sl(t,e,n,r,i,o){let s=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ll(t,e,n,r,i){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.put(o,r,i?.signal)}async function dl(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/rewarded-placements/${_(r)}/availability`;return t.client.get(o,i?.signal)}async function cl(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function ul(t,e,n,r){let i=`/v1/characters/${_(e)}`;return t.client.patch(i,n,r?.signal)}async function ml(t,e,n,r,i,o){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function pl(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/reset`;return t.client.post(s,i,o?.signal)}async function gl(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.delete(r,n?.signal)}var j="gem-web-bridge",tr={min:1,max:1},tp=65536,fl=8,er=5e3,yl=1024;var Kt=Object.create(null),nr="__malformed";var Di=Object.create(null),np=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"]]);function rr(t){let e=Di[t];if(e!==void 0)return e;for(let[n,r]of np)if(t.startsWith(n))return r}function St(t){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(t);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function rp(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 ip(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function op(t){return /^[a-z_]+$/.test(t)}function ap(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(t)&&!t.includes("--")}function Gi(t,e,n){if(e>fl)return `nesting deeper than ${fl}`;if(++n.nodes>er)return `more than ${er} values`;if(n.bytes>n.cap)return `over the ${n.cap} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=t;if(n.seen.has(i))return "a repeated or cyclic object reference";if(n.seen.add(i),Array.isArray(t)){if(t.length>yl)return `an array of ${t.length} entries, over the ${yl} limit`;n.bytes+=2;for(let a of t){let l=Gi(a,e+1,n);if(l)return l}return null}let o=Object.getPrototypeOf(t);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";n.bytes+=2;let s=t;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++n.nodes>er)return `more than ${er} values`;if(n.bytes+=a.length*3+4,n.bytes>n.cap)return `over the ${n.cap} byte limit`;let l=Gi(s[a],e+1,n);if(l)return l}return null}function sp(t,e=tp){let n={nodes:0,bytes:0,seen:new Set,cap:e},r=Gi(t,0,n);return r?`message contains ${r}`:n.bytes>e?`message is over the ${e} byte limit`:null}var lp={origin:[St,"not a well-formed origin"],url:[rp,"not a safe absolute http(s) URL"],bcp47:[ip,"not a well-formed BCP 47 tag"],code:[op,"not a code of lower-case letters and underscores"],gameRef:[ap,"not a game id or web address"]};function hl(t,e,n){for(let r of e){let i=n===""?r[0]:`${n}.${r[0]}`,o=t[r[0]];if(o==null){if(r[1]<"a")continue;return `${i}: required`}let s=Li(o,r,i);if(s)return s}return null}function Li(t,e,n){let r=e[1].toLowerCase();switch(r){case "u":return typeof t=="boolean"?null:Li(t,typeof t=="string"?[e[0],"s",e[2]]:[e[0],"n",e[3],e[4]],n);case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e[2])return `${n}: exceeds ${e[2]} characters`;if(e[3]){let[i,o]=lp[e[3]];if(!i(t))return `${n}: ${o}`}return null}case "n":case "i":return typeof t!="number"||!(r=="i"?Number.isInteger:Number.isFinite)(t)?`${n}: expected ${r=="i"?"integer":"number"}`:t<e[2]||t>e[3]?`${n}: out of range ${e[2]}..${e[3]}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let i=e[2];return i.includes(t)?null:`${n}: not one of ${i.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:hl(t,e[2],n);case "j":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "a":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e[2])return `${n}: exceeds ${e[2]} items`;let i=e[3],o=`${n}[]`;for(let s of t){if(s==null){if(i[1]<"a")continue;return `${o}: required`}let a=Li(s,i,o);if(a)return a}return null}default:return `${n}: unknown kind ${String(r)}`}}var bl=Object.create(null);function R(t,e,n,r,i){return Kt[t]=n,r&&(Di[t]=r),bl[t]=o=>{let s=sp(o,i);if(s)return s;if(typeof o!="object"||o===null||Array.isArray(o))return "message: expected object";let a=o;return a.gem!==j?"gem: wrong protocol marker":a.type!==t?`type: expected ${t}`:hl(a,e,"")}}var W=["requestId","s",64],Ve=["outcome","e",["ok","declined","unavailable"]],He=["reason","S",64,"code"];R("gem.handshake",[["versions","o",[["min","i",1,1e3],["max","i",1,1e3]]],["capabilities","A",64,["","s",64]],["embedder","s",2048,"origin"],["unbidden","B"]],30);R("gem.handshake.accept",[["v","i",1,1e3],["capabilities","A",64,["","s",64]]],5);R("gem.token",[["token","s",4096],["requestId","S",64],["generation","i",0,2147483647],["apiBaseUrl","S",512,"url"],["playerId","s",64],["gameId","s",64],["channel","e",["dev","test","release"]],["gameVersion","S",64],["expiresAt","i",0,4102444800],["chainEndsAt","i",0,4102444800],["allowDevTools","B"]],30);R("gem.token.denied",[W,["retryable","b"],["retryAfterMs","I",0,36e5],["reason","e",["chain_exhausted","unavailable"]],["correlationId","s",64]],30);R("gem.player",[["untrusted","o",[["displayName","s",64],["displayTag","S",80],["displayHandle","s",80]]],["playerId","S",64],["discriminator","S",8],["avatarIconUrl","S",2048,"url"],["avatarIconId","S",64],["avatar3dId","S",64],["avatar3dModelUrl","S",2048,"url"],["avatar3dIconUrl","S",2048,"url"],["avatars3d","A",8,["","o",[["family","s",32],["id","s",64],["modelUrl","s",256,"url"],["iconUrl","s",256,"url"]]]],["badges","A",2,["","o",[["itemId","s",64],["iconUrl","s",2048,"url"]]]],["displayTag","s",8],["avatarUrl","S",2048,"url"],["boost","O",[["multipliers","a",8,["","o",[["currencyId","s",64],["currencySlug","s",32],["multiplierBp","i",1e4,1e6]]]],["expiresInDays","I",1,7]]]],12);R("gem.pause",[["paused","b"]],120);R("gem.prefs",[["reducedMotion","b"],["muted","b"],["showFrameStats","B"],["music","B"],["sounds","B"],["locale","s",35,"bcp47"],["recommended","O",[["volume","i",0,100],["batterySaver","b"],["keyboardLayout","e",["wasd","arrows"]],["gamepadConfirm","e",["south","east"]],["vibration","b"],["lookSensitivity","I",20,400],["gamepadLookSensitivity","I",20,400],["invertLookY","B"],["touchMovement","S",16,"code"],["graphicsQuality","S",16,"code"],["graphicsQualityAuto","B"],["colorHelp","B"]]]],60);R("gem.cohorts",[["cohorts","a",8,["","o",[["experimentId","s",36],["variantKey","s",32]]]]],12,"cohorts");R("gem.earnAllowanceChanged",[],30,"earnAllowance");R("gem.viewport",[["insets","o",[["top","i",0,4096],["right","i",0,4096],["bottom","i",0,4096],["left","i",0,4096]]],["reserved","A",4,["","o",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384],["control","O",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384]]]]]]],60,"viewport");R("gem.deviceSettings",[["settings","J"]],12,"deviceSettings");R("gem.willTerminate",[["reason","e",["grant_expiring","session_ended","navigating","kill_switch"]],["graceMs","i",0,6e4]],10);R("gem.roomEvent",[["event","e",["updated","match_started","match_ready","match_failed","version_stale"]],["roomId","s",64],["matchId","S",64],["version","I",0,2147483647],["reason","S",64],["platform","E",["universal","mobile"]]],120,"rooms");R("gem.socketState",[["connected","b"],["reason","E",["connecting","dropped","watchdog","terminal"]]],12,"socketState");R("gem.seatedEvent",[["roomId","s",64]],60,"partySeating");R("gem.autoStartFailedEvent",[["roomId","s",64],["code","s",64]],30,"autoStartFailure");R("gem.ticketEvent",[["event","e",["queued","matched","expired","cancelled","failed"]],["ticketId","s",64],["partySize","I",1,64],["queuedAt","I",0,4102444800],["expiresAt","I",0,4102444800],["reason","S",64],["roomId","S",64]],60,"ticketEvents");R("gem.signalEvent",[["event","e",["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]],["matchId","s",64],["data","j"]],1800,"p2p");R("gem.dedicatedEvent",[["event","e",["answer","error","matchEnded"]],["matchId","s",64],["sdp","S",10240],["sessionId","S",64],["code","S",64],["message","S",256],["reason","S",64]],120,"dedicated");R("gem.partyResult",[W,["partyId","S",64]],30,"parties");R("gem.clusterTarget",[["clusterTargetId","s",64],["clusterTargetIds","A",3,["","s",64]]],12,"clusterTarget");R("gem.devtools",[["action","e",["open","close","toggle"]]],30,"devtools");R("gem.screenshot",[["maxWidth","i",1,7680],["maxHeight","i",1,4320]],6,"screenshot");R("gem.screenshot.denied",[["reason","e",["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]],["retryable","b"]],12,"screenshot");R("gem.requestContext",[],12,"feedbackContext");R("gem.gameContext",[["context","j"]],12,"feedbackContext");R("gem.signal",[["signal","e",["join","offer","answer","ice","migrationAck","hostUnreachable"]],["matchId","s",64],["data","j"]],1200,"p2p");R("gem.dedicatedOffer",[["matchId","s",64],["sdp","s",10240],["intent","e",["initial","ice_restart","full_reconnect"]]],60,"dedicated");R("gem.partyRequest",[W],12,"parties");R("gem.ready",[],5);R("gem.engaged",[],5,"engagement");R("gem.progress",[["loaded","i",0,1099511627776],["total","i",0,1099511627776]],600);R("gem.requestToken",[W,["reason","e",["initial","expiring","rejected"]]],12);R("gem.requestLocalServer",[W,["gameRoomId","s",64]],6,"localHost");R("gem.localServer",[W,["serverId","S",128]],30,"localHost");R("gem.localServer.denied",[W,["retryable","b"],["reason","e",["refused","unavailable"]]],30,"localHost");R("gem.exit",[["reason","S",64]],5);R("gem.openExternal",[["url","s",2048,"url"]],6);R("gem.requestFullscreen",[["enabled","b"]],30);R("gem.audioState",[["muted","b"]],120,"audioState");R("gem.rewardCue",[["currencySlug","s",32],["expected","I",1,1e9],["origin","O",[["x","i",0,16384],["y","i",0,16384]]]],60,"rewardCue");R("gem.walletDisplay",[["visible","b"],["currencies","A",8,["","s",64]],["score","B"]],60,"walletDisplay");R("gem.controlsDeclare",[["uses","o",[["lookSensitivity","S",16,"code"],["gamepadLookSensitivity","S",16,"code"],["invertLookY","S",16,"code"],["touchMovement","S",16,"code"]]]],60,"controls");R("gem.menu",[["settings","b"],["items","A",4,["","o",[["id","s",32],["label","s",40]]]]],60,"gameMenu");R("gem.menuSelect",[["entry","e",["settings","item"]],["id","S",32]],60,"gameMenu");R("gem.gemCorner",[["corner","e",["top-left","top-right","bottom-left","bottom-right"]]],12,"gemCorner");R("gem.settingsDeclare",[["settings","a",8,["","o",[["id","s",40],["label","s",40],["kind","e",["toggle","slider","choice"]],["value","u",40,-1e6,1e6],["quick","B"],["icon","S",16,"code"],["min","N",-1e6,1e6],["max","N",-1e6,1e6],["step","N",0,1e6],["options","A",4,["","o",[["id","s",40],["label","s",40]]]]]]]],120,"gameSettings");R("gem.settingChange",[["id","s",40],["value","u",40,-1e6,1e6]],120,"gameSettings");R("gem.requestShare",[["params","a",16,["","o",[["key","s",64],["value","s",512]]]]],6,"share");R("gem.requestAvatarPicker",[["tab","E",["2d","3d"]]],6,"avatarPicker");R("gem.vibrate",[["pattern","a",99,["","i",0,1e4]]],600,"vibration");R("gem.frameStats",[["fps","i",0,1e3],["frameTimeP95Ms","i",0,1e5],["counts","E",["pageFrames","gameDraws"]]],120,"frameStats");R("gem.portraitBorders",[["name","S",40]],60,"portraitBorders");R("gem.error",[["code","e",["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]],["message","S",256]],60);R("gem.requestPurchase",[W,["purchaseKind","e",["item","recipe"]],["targetId","s",64],["currencySlug","s",32],["quantity","I",1,10],["catalogId","S",64]],12,"purchases");R("gem.requestAvatar3dPurchase",[W,["itemId","s",64],["currencySlug","s",32]],12,"avatar3dPurchases");R("gem.purchaseResult",[W,Ve,He,["purchaseId","S",64]],30,"purchases");R("gem.deviceSettings.put",[W,["settings","j"]],30,"deviceSettings");R("gem.deviceSettings.result",[W,["outcome","e",["stored","too_large","unavailable"]]],30,"deviceSettings");R("gem.requestAd",[W,["placement","s",32],["format","e",["interstitial","rewarded"]]],6,"ads");R("gem.adResult",[W,["outcome","e",["shown","no_ad","unavailable"]]],12,"ads");R("gem.signalMoment",[W,["kind","e",["level_end","run_end","match_end","menu_return","other_break"]],["placement","S",32],["wall","B"]],6,"moments");R("gem.momentResult",[W,["shown","b"]],12,"moments");R("gem.requestSignIn",[W],6,"signIn");R("gem.signInResult",[W,["outcome","e",["signed_in","declined","unavailable"]]],12,"signIn");R("gem.requestFriendChallenge",[W,["playerId","s",64],["template","s",64],["params","J"]],12,"friendChallenges");R("gem.friendChallengeResult",[W,["outcome","e",["accepted","cancelled","refused","unavailable","rate_limited","invalid"]],["code","S",64],["param","S",64],["channel","S",16],["configVersion","I",0,9007199254740991],["retryAfterMs","I",0,864e5],["detail","S",300]],30,"friendChallenges");R("gem.requestAppLinks",[W],12,"appLinks");R("gem.appLinksResult",[W,Ve,He,["arcade","O",[["store","e",["app_store","google_play"]]]],["game","O",[["store","e",["app_store","google_play"]]]]],30,"appLinks");R("gem.requestOpenApp",[W,["target","e",["arcade","game"]]],6,"appLinks");R("gem.openAppResult",[W,Ve,He],30,"appLinks");var vl=R("gem.requestOpenGame",[W,["ref","s",40,"gameRef"]],6,"openGame");R("gem.openGameResult",[W,Ve,He],30,"openGame");R("gem.requestSimilarGames",[W,["limit","I",1,24]],12,"openGame");R("gem.similarGamesResult",[W,Ve,He,["games","a",24,["","o",[["gameId","s",36,"gameRef"],["slug","S",40,"gameRef"],["iconUrl","s",1024,"url"],["capsuleLandscapeUrl","s",1024,"url"],["capsulePortraitUrl","s",1024,"url"],["previewVideoUrl","S",1024,"url"],["previewPosterUrl","S",1024,"url"],["untrusted","o",[["name","s",64],["tagline","s",64],["shortDescription","s",320],["tags","a",10,["","s",32]]]]]]]],30,"openGame",524288);R("gem.requestStoreOffers",[W],12,"store");R("gem.storeOffersResult",[W,Ve,He,["offers","a",32,["","o",[["skuId","s",64],["kind","e",["gem_pack","boost","pass","bundle"]],["name","s",80],["description","s",400],["imageUrl","S",1024,"url"],["priceDisplay","s",32],["grant","O",[["currency","s",32],["amount","i",1,1e9]]]]]]],30,"store",262144);R("gem.requestStorePurchase",[W,["skuId","s",64]],12,"store");R("gem.storePurchaseResult",[W,Ve,He],30,"store");R("gem.storePurchaseSettled",[["skuId","s",64]],30,"store");R("gem.requestStoreOfferSheet",[W,["skuId","s",64]],12,"storeOfferSheet");R("gem.storeOfferSheetResult",[W,Ve,He],30,"storeOfferSheet");var ir=Object.freeze(bl);Kt.__malformed=60;Object.freeze(Kt);Object.freeze(Di);var ue={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Jt=class{constructor(e=ue){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Kt[e];if(n===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??n,s=Math.max(0,r-i),a=Math.min(n,o+s*n/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function kt(t,e){return t.toLowerCase()===e.toLowerCase()}function Ke(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function or(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:Ke(n.hostname)&&Ke(r.hostname)}function _l(t,e){if(e.min>e.max)return null;let n=Math.min(t.max,e.max),r=Math.max(t.min,e.min);return n>=r?n:null}var ar=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let i=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,o=i.find(a=>a.currencyId===e),s;return !o&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(o=i.find(a=>a.currencyId===s))),{currencyId:o?o.currencyId:s??e,total:o?o.total:null,...o?.buckets===void 0?{}:{buckets:o.buckets}}}};function $i(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let i=r??{};typeof i.id!="string"||i.id===""||typeof i.threshold!="number"||!Number.isFinite(i.threshold)||n.push({id:i.id,threshold:i.threshold,points:typeof i.points=="number"?i.points:0,hidden:i.hidden===true,...typeof i.unlocked_at=="number"&&Number.isFinite(i.unlocked_at)?{unlockedAt:i.unlocked_at}:{},...i.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var wl="inventory",Rt=t=>typeof t=="number"?t:0,zt=t=>typeof t=="string"?t:"";function Fi(t,e){let n=t??{},r=typeof n.next_cursor=="string"?n.next_cursor:void 0;return {data:Array.isArray(n.data)?n.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function Sl(t){let e=t??{};return {itemDefinitionId:zt(e.item_definition_id),instanceId:zt(e.instance_id),quantity:Rt(e.quantity),acquiredAt:Rt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function dp(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Fi(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:zt(a.bucket),balance:Rt(a.balance)}}):void 0;return {currencyId:zt(i.currency_id),total:Rt(i.total),...o===void 0?{}:{buckets:o}}}),items:Fi(e.items,Sl),progressions:Fi(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:zt(i.progression_definition_id),currentValue:Rt(i.current_value),completionCount:Rt(i.completion_count),isCompleted:i.is_completed===true,...$i(i)}}),...n===void 0?{}:{etag:n}}}var sr=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${wl}#buckets`:wl;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let o=r.items.data.filter(s=>s.itemDefinitionId===e);if(o.length>0)return o}let i=await Ps(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(i)?i.map(Sl):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let n=await xs(this.api,this.entity.type,this.entity.id,{...e.includeBuckets?{include_buckets:true}:{},...e.currencyCursor===void 0?{}:{currency_cursor:e.currencyCursor},...e.itemCursor===void 0?{}:{item_cursor:e.itemCursor},...e.progressionCursor===void 0?{}:{progression_cursor:e.progressionCursor},...e.currencyLimit===void 0?{}:{currency_limit:e.currencyLimit},...e.itemLimit===void 0?{}:{item_limit:e.itemLimit},...e.progressionLimit===void 0?{}:{progression_limit:e.progressionLimit},...e.signal===void 0?{}:{signal:e.signal}});return dp(n)}};var cp={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,already_owned:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},up=new Set(Object.keys(cp));function kl(t){return typeof t=="string"&&up.has(t)?t:"error"}var Je=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var re=t=>typeof t=="string"?t:"",mp=t=>typeof t=="string"?t:re(t&&typeof t=="object"?t.type:void 0),Ie=t=>typeof t=="number"?t:0;function pp(t){let e=t??{};return {prerequisiteType:re(e.prerequisite_type),referenceId:re(e.reference_id),required:Ie(e.required),current:Ie(e.current)}}function Xt(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:re(e.order_id),status:re(e.status),...n===void 0?{}:{etag:n}}}function lr(){return crypto.randomUUID()}var gp="recipe-usage",Rl=100;function dr(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:re(e.currency_id),bucket:re(e.bucket),delta:Ie(e.delta),balanceAfter:Ie(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:re(e.item_definition_id),instanceId:re(e.instance_id),delta:Ie(e.delta),quantityAfter:Ie(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:re(e.progression_definition_id),delta:Ie(e.delta),valueAfter:Ie(e.value_after),completed:e.completed===true};default:return {kind:"other",type:re(e.type)}}}function fp(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:re(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Ie(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(dr):[]}}function yp(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(fp):void 0;return {orderId:re(e.order_id),status:re(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(dr):[],consumed:Array.isArray(e.consumed)?e.consumed.map(dr):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(dr):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function hp(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:re(e.target_order_id)||re(e.source_order_id),status:re(e.status),purchaseId:re(e.purchase_id),sourceOrderId:re(e.source_order_id),price:{currencyId:re(n.platform_currency_id),amount:Ie(n.price)}}}function bp(t){let e=t??{},n=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:re(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...n===void 0?{}:{lastUsedAt:n},...r===void 0?{}:{cooldownExpiresAt:r}}}function Al(t){switch(t.type){case "currency_grant":case "currency_consume":return {type:t.type,currency_id:t.currencyId,amount:t.amount};default:return {type:t.type,item_definition_id:t.itemDefinitionId,quantity:t.quantity}}}var cr=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;async create(e,n={}){let r=await this.write(()=>gs(this.api,this.entity.type,this.entity.id,{operations:e.map(Al),source:n.source??"play",nonce:lr()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Xt(r)}async createMany(e,n={}){return this.write(()=>ps(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Al),nonce:lr()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let o=await Cs(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},s=typeof o.uses_remaining=="number"?o.uses_remaining:void 0,a=typeof o.cooldown_expires_at=="string"?o.cooldown_expires_at:void 0,l=Array.isArray(o.lock_reasons)?o.lock_reasons.map(pp):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>mp(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(gp,[],async()=>{let n=await Ms(this.api,this.entity.type,this.entity.id,{limit:Rl})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(bp),truncated:r.length>=Rl}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let u=e,p=await this.write(()=>vs(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:lr()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...yp(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,i]=await Promise.all([Ns(this.api,n.signal===void 0?{}:{signal:n.signal}),Zn(this.api,n.signal===void 0?{}:{signal:n.signal})]),o=e.payment.currencySlug.toLowerCase(),s=i.currencies.find(u=>u.currency_id.toLowerCase()===o||u.slug.toLowerCase()===o);if(s===void 0){let u=i.currencies.map(p=>p.slug);throw new Je("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let a=e.kind==="item"?r.items.find(u=>u.item_id===e.targetId):r.recipes.find(u=>u.recipe_id===e.targetId&&u.catalog_id===e.catalogId);if(a===void 0)throw new Je("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=a.platform_prices.find(u=>u.platform_currency_id===s.currency_id);if(l===void 0){let u=g=>i.currencies.find(f=>f.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new Je("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Je("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let c=await this.write(()=>Js(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:s.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:lr(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return hp(c)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let i=await this.write(()=>ls(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Xt(i)}async maxProgression(e,n,r){let i=await this.write(()=>al(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Xt(i)}async claimProgression(e,n){let r=await this.write(()=>us(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Xt(r)}async resetProgression(e,n){let r=await this.write(()=>pl(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Xt(r)}async write(e){return this.cache.invalidate(),e()}};var qi=t=>typeof t=="string"?t:"",vp=t=>typeof t=="number"?t:0;function xl(t){let e=t??{};return {orderId:qi(e.order_id),status:qi(e.status),source:qi(e.source),createdAt:vp(e.created_at)}}var ur=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await Zs(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(xl):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await Es(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return xl(r)}};var Pl=t=>typeof t=="number"?t:0,_p=t=>typeof t=="string"?t:"";function wp(t){let e=t??{};return {progressionDefinitionId:_p(e.progression_definition_id),currentValue:Pl(e.current_value),completionCount:Pl(e.completion_count),isCompleted:e.is_completed===true,...$i(e)}}var mr=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let i=(await this.inventory.snapshot()).progressions.data.find(o=>o.progressionDefinitionId===e);if(i&&i.achievementsUnavailable!==true)return i;try{let o=await Is(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return wp(o)}catch{return i??null}}};var pr=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,i){this.rebind();let o=n.length===0,s=o?e:e+"\0"+n.join("\0"),a=this.slots.get(s);if(a){let u=a.filledAt;if(u!==void 0&&(i===void 0||this.clock.now()-u<=i))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,c=r().then(u=>(o&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===c&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=c,c}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 Sp(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var kp=new Set(Xn);function Rp(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))kp.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function gr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return es(async(n,r)=>{let i;try{i=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new se("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let o;try{o=new URL(i.href.replace(/\/+$/,"")+n.path);}catch{throw new se(`${JSON.stringify(typeof n.path=="string"?Sp(n.path):"(a non-string path)")} does not form a valid URL against ${i.protocol}//${i.host}. This is a malformed request, not a server failure.`)}if(o.protocol!==i.protocol||o.host!==i.host)throw new se(`${JSON.stringify(o.pathname)} resolves to ${o.protocol}//${o.host}, not ${i.protocol}//${i.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(o.username!==""||o.password!==""){let g=i.username!==""||i.password!=="",f=o.username!==i.username||o.password!==i.password,h=g?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new se(`the ${h} puts credentials in the URL, which cannot be fetched (${n.method} ${o.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,f]of Object.entries(t.defaultQuery??{}))o.searchParams.has(g)||o.searchParams.set(g,f);let s=n.bytes,a=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(s=JSON.stringify(n.body),a="application/json");}catch(g){throw new se(`the body of ${n.method} ${JSON.stringify(o.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(o.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...Rp(n.headers)},body:s,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let c=l.headers.get("etag"),u=Ni(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...c===null?{}:{etag:c},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},t)}function Ni(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}function ji(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 fr(t){try{let e=ji(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ie=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},Ap=3e4,xp=5e3,Tl=6e4,Pp=2**31-1,El="the save payload could not reach storage. From a browser this is almost always the storage account's CORS rule, which the platform owns and your game cannot change. If every save fails this way, report it rather than working around it",Tp=/^[A-Za-z0-9_]{1,64}$/;function Fe(t){let e=t.length===0?"a save key cannot be empty":t.length>64?`it is ${t.length} characters; a save key is at most 64`:t.startsWith("_")||t.startsWith("$")?`it begins with ${JSON.stringify(t[0])}, and \`_\` and \`$\` are reserved prefixes`:"a save key is ASCII letters, digits and underscores only \u2014 no hyphens, spaces or other punctuation, unlike a template slug";if(!Tp.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Il(t,e){let n=new AbortController,r=Date.now()+e;as(n.signal,()=>r-Date.now());let i=AbortSignal.timeout(e),o=()=>n.abort(i.reason),s=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(i.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",s,{once:true})),{signal:n.signal,release:()=>{i.removeEventListener("abort",o),t?.removeEventListener("abort",s);}}}function Bi(t,e){return t.aborted&&e?.aborted!==true}var Ep=new Set(["x-ms-blob-type"]),Ip=/^[ -~]+$/;function Cp(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,i]of Object.entries(t)){let o=r.toLowerCase();if(!Ep.has(o))throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof i!="string"||!Ip.test(i))throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(o in n)throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);n[o]=i;}return n}function Ui(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 Wi(t){return t?.reason==="not_found"}function Mp(t){return t?.code==="save_conflict"}function Cl(t){return t instanceof M&&t.reason==="rate_limited"}async function Ml(t,e){let n=await fr(e);return new M("rate_limited",429,`the save ${t} answered 429: too many save calls. ${n}`.trim(),Ni(e.headers.get("retry-after")))}function yr(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Op(t,e,n,r,i){let o=false,s=()=>o?false:(o=true,a.detach?.(),true),a={signal:n.signal,budget:r,deadlineAt:Date.now()+r,teardown:n.teardown===true,overwrite:n.overwrite===true,identity:i,resolve:l=>{s()&&t(l);},reject:l=>{s()&&e(l);},detach:void 0};return a}function Ol(t,e){return t!==null&&e!==null&&e!==t}function Gl(t){return new ie("save_conflict",`save ${JSON.stringify(t)} was not written: the signed-in player changed while it waited for the write before it, and it holds the last player's progress.`)}var hr=class{constructor(e,n,r={},i){this.api=e;this.entity=n;this.options=r;this.identity=i;}api;entity;options;identity;versions=new Map;seq=0;versionsOf=null;writes=new Map;holdUntil=0;async put(e,n,r={}){let i;try{i=JSON.stringify(n);}catch(o){throw new ie("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}. Retrying stores the same unserialisable value.`)}if(i===void 0)throw new ie("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(i),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){if(Fe(e),r.signal?.aborted)throw yr(r.signal);let i=this.budget(r.timeoutMs),o=this.slotWrites(e);return new Promise((s,a)=>{let l=o.queued;l?.release();let d=l?.waiters[l.waiters.length-1];d!==void 0&&this.holdOwn(o,d);let c=this.identity?.()??null;for(let u of l?.waiters.slice()??[])Ol(u.identity,c)&&this.drop(o,u,Gl(e));o.queued=this.queue(o,n,r,Op(s,a,r,i,c),l?.waiters??[]),o.wake?.(),this.pump(e,o);})}holdOwn(e,n){let{signal:r}=n,i=n.deadlineAt-Date.now();if(r?.aborted)return this.drop(e,n,yr(r));if(i<=0)return this.drop(e,n,this.timeout("save",n.budget));let o=AbortSignal.timeout(i),s=()=>this.drop(e,n,this.timeout("save",n.budget)),a=()=>{r&&this.drop(e,n,yr(r));};o.addEventListener("abort",s,{once:true}),r?.addEventListener("abort",a,{once:true}),n.detach=()=>{o.removeEventListener("abort",s),r?.removeEventListener("abort",a);};}drop(e,n,r){let i=e.queued?.waiters,o=i?.indexOf(n)??-1;o>=0&&i?.splice(o,1),n.reject(r),e.wake?.();}queue(e,n,r,i,o){let{budget:s}=i,a=[...o,i],l=AbortSignal.timeout(s),d=g=>{if(e.queued===p){this.take(e,p);for(let f of a)f.reject(g);e.wake?.();}},c=()=>d(this.timeout("save",s)),u=()=>{r.signal&&d(yr(r.signal));};l.addEventListener("abort",c,{once:true}),r.signal?.addEventListener("abort",u,{once:true});let p={bytes:n,options:r,budget:s,deadlineAt:i.deadlineAt,identity:i.identity,waiters:a,release:()=>{l.removeEventListener("abort",c),r.signal?.removeEventListener("abort",u);}};return p}async pump(e,n){if(!n.running){n.running=true;try{for(let r=n.queued;r!==void 0;r=n.queued){let i=Date.now(),o=this.holdUntil-i;if(o>0){if(o>=r.deadlineAt-i){this.take(n,r);for(let l of r.waiters)l.reject(this.held(e,o));continue}for(let l of r.waiters.slice(0,-1))o>=l.deadlineAt-i&&this.drop(n,l,this.held(e,o));}let s=Math.max(o,this.spacing(n,r,i));if(s>0){await this.pause(n,s);continue}this.take(n,r);let a;try{a=this.precondition(e,r);}catch(l){for(let d of r.waiters)d.reject(l);continue}n.lastSentAt=i;try{let l=await this.send(e,r,a);for(let d of r.waiters)d.resolve(l);}catch(l){for(let d of r.waiters)d.reject(l);}}}finally{n.running=false;}}}spacing(e,n,r){if(e.lastSentAt===void 0||n.waiters.some(s=>s.teardown))return 0;let i=this.options.minWriteIntervalMs??xp,o=Math.min(...n.waiters.map(s=>s.deadlineAt-s.budget/2));return Math.min(e.lastSentAt+i,o)-r}pause(e,n){return new Promise(r=>{let i=()=>{clearTimeout(o),e.wake===i&&(e.wake=void 0),r();},o=setTimeout(i,Math.min(n,Pp));e.wake=i;})}take(e,n){e.queued===n&&(e.queued=void 0),n.release();}slotWrites(e){let n=this.writes.get(e);return n===void 0&&(n={running:false,queued:void 0,lastSentAt:void 0,wake:void 0},this.writes.set(e,n)),n}noteRateLimit(e){if(!Cl(e))return;let n=e.retryAfterSeconds,r=n===void 0?Tl:Math.min(n*1e3,Tl);this.holdUntil=Math.max(this.holdUntil,Date.now()+r);}held(e,n){let r=Math.ceil(n/1e3);return new M("rate_limited",429,`save ${JSON.stringify(e)} was not sent: the platform refused a save call for the rate, and the wait it asked for ends in ${r}s, after this call's timeoutMs. Keep the state and write once the wait is over.`,r)}async send(e,n,r){let{bytes:i,options:o,budget:s}=n,a=o.contentType??"application/octet-stream",l=Il(o.signal,Math.max(0,n.deadlineAt-Date.now()));try{let d=await ml(this.api,this.entity.type,this.entity.id,e,{size_bytes:i.byteLength,content_type:a,...r,...o.metadata===void 0?{}:{metadata:o.metadata}},{signal:l.signal});if(typeof d.upload_url!="string"||typeof d.session_id!="string")throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let c=Cp(d.upload_headers,e),u,p=this.options.fetch??globalThis.fetch.bind(globalThis);try{u=await p(d.upload_url,{method:"PUT",headers:{"content-type":a,...c},body:i,credentials:"omit",signal:l.signal});}catch(f){throw Bi(l.signal,o.signal)?this.timeout("upload",s):new ie("upload_failed",`${El} for PUT. Underlying error: ${f}`)}if(u.status===429)throw await Ml("upload",u);if(!u.ok){let f=await fr(u);throw new ie("upload_failed",u.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+f:`the save upload answered ${u.status}. `+(u.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+f)}let g=Ui(await _s(this.api,this.entity.type,this.entity.id,e,{session_id:d.session_id},{signal:l.signal}));return this.remember(e,g.etag?{kind:"etag",etag:g.etag}:void 0),g}catch(d){throw Mp(d)?new ie("save_conflict",`save ${JSON.stringify(e)} was not written: the stored save changed since this game last loaded or wrote it, so another device or tab saved in between. Load it again and decide what to write from what is stored, rather than resending this write.`):(this.noteRateLimit(d),this.rethrow(d,o.signal,l.signal,"save",s))}finally{l.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(i){throw new ie("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${i}`)}}async getBytes(e,n={}){Fe(e);let r=this.budget(n.timeoutMs),i=Il(n.signal,r),o=this.seq;try{let s;try{let c=await Oi(this.api,this.entity.type,this.entity.id,e,{signal:i.signal});if(!c.modified)return this.remember(e,{kind:"empty"},o),null;s=c.body;}catch(c){if(Wi(c))return this.remember(e,{kind:"empty"},o),null;throw c}if(typeof s.download_url!="string")throw new ie("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),l;try{l=await a(s.download_url,{credentials:"omit",signal:i.signal});}catch(c){throw Bi(i.signal,n.signal)?this.timeout("download",r):new ie("download_failed",`${El} for GET. Underlying error: ${c}`)}if(l.status===429)throw await Ml("download",l);if(!l.ok){let c=await fr(l);throw new ie("download_failed",`the save download answered ${l.status}. `+(l.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+c)}let d=new Uint8Array(await l.arrayBuffer());return this.remember(e,s.etag?{kind:"etag",etag:s.etag}:void 0,o),d}catch(s){throw this.slots().get(e)===void 0&&this.remember(e,{kind:"failed"}),this.noteRateLimit(s),this.rethrow(s,n.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,n={}){try{let r=await Oi(this.api,this.entity.type,this.entity.id,Fe(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Ui(r.body):null}catch(r){if(Wi(r))return null;throw r}}async list(e={}){let n=await el(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}}),r=n.next_cursor;return {saves:(n.data??[]).map(Ui),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await hs(this.api,this.entity.type,this.entity.id,Fe(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Wi(r))throw r}this.remember(e,{kind:"empty"});}precondition(e,n){if(Ol(n.identity,this.identity?.()??null))throw Gl(e);if(n.waiters.some(i=>i.overwrite))return {};let r=this.slots().get(e);if(r===void 0)return {};if(r.kind==="etag")return {if_match:r.etag};if(r.kind==="empty")return {if_none_match:"*"};throw new ie("load_failed",`save ${JSON.stringify(e)} was not written: the last load of this slot failed, so what this write would replace is unknown, and it could be the player's real progress. Load it again before saving, or pass overwrite: true if replacing whatever is stored is what you mean.`)}remember(e,n,r){let i=this.slots(),o=i.get(e);r!==void 0&&o!==void 0&&o.kind!=="failed"&&o.seq>r||(this.seq+=1,n===void 0?i.delete(e):i.set(e,{...n,seq:this.seq}));}slots(){let e=this.identity?.()??null;return e!==null&&e!==this.versionsOf&&(this.versionsOf!==null&&this.versions.clear(),this.versionsOf=e),this.versions}budget(e){return e??this.options.timeoutMs??Ap}timeout(e,n){return new ie("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,i,o){return e instanceof ie||Cl(e)?e:Bi(r,n)?this.timeout(i,o):e}};function Gp(t){try{return Mi(t)}catch{return t}}function Vi(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"?Gp(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var br=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await Qs(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>Vi(i)):[]}async get(e,n={}){try{let r=await As(this.api,this.entity.type,this.entity.id,e,{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Vi(r.body,r.etag):null}catch(r){if(Ll(r))return null;throw r}}async put(e,n,r={}){let i=await sl(this.api,this.entity.type,this.entity.id,e,{value:Yn(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Vi(i)}async delete(e,n){try{await ys(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!Ll(r))throw r}}};function Ll(t){return t?.reason==="not_found"}function vr(t,e,n={}){let r=new pr(ue,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let i=new sr(t,e,r);return {settings:new br(t,e),inventory:i,saves:new hr(t,e,n.saves??{},n.identity),currencies:new ar(i,n.resolveCurrencyId),mutations:new cr(t,e,r),orders:new ur(t,e),progressions:new mr(t,e,i)}}var Hi={type:"players",id:"me"};var nt=t=>typeof t=="string"?t:"",At=t=>typeof t=="number"?t:0;function _r(t,e){let n=e??{},r=nt(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:nt(n.player_id),gameId:nt(n.game_id),channel:nt(n.channel)||"release",name:nt(n.name),slotIndex:At(n.slot_index),isActive:n.is_active!==false,createdAt:nt(n.created_at),updatedAt:nt(n.updated_at)}}var wr=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=vr(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};async list(e){let r=(await Ys(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>_r(this.scope,i)):[]}async get(e,n){let r=await ks(this.api,e,n===void 0?{}:{signal:n});return _r(this.scope,r)}async create(e){let n=await ms(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return _r(this.scope,n)}async update(e,n,r){let i=await ul(this.api,e,{name:n},r===void 0?{}:{signal:r});return _r(this.scope,i)}async delete(e,n){await gl(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await Us(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:At(r?.total_slots),availableSlots:At(r?.available_slots),activeCharacterCount:At(r?.active_character_count),defaultMaxSlots:At(r?.default_max_slots),purchasedExtraSlots:At(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var $l="[gem: use gem.text.toPlain()]",Dl=new Set,Fl;function Lp(t){try{if(Dl.has(t))return;let e=globalThis.location;if(Fl??=!!e?.port&&Ke(e.hostname??""),!Fl)return;Dl.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${$l}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
|
|
2
|
-
${new Error().stack}`);}catch{}}var ve=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return Lp(this.#n),$l}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function he(t,e){return new ve(t,e)}var rt={toPlain(t){return ve.unwrap(t)},compare(t,e,n){let r=t instanceof ve?ve.unwrap(t):t,i=e instanceof ve?ve.unwrap(e):e;if(typeof Intl>"u"||typeof Intl.Collator!="function")return r<i?-1:r>i?1:0;let o;try{o=new Intl.Collator(n);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(t,e){let n=t instanceof ve?ve.unwrap(t):t,r=e instanceof ve?ve.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var xt=t=>typeof t=="string"?t:"";function Sr(t){let e=t??{},n=typeof e.message=="string"&&e.message.length>0?e.message:void 0,r=typeof e.resolved_at=="string"?e.resolved_at:void 0;return {id:xt(e.transfer_id),status:xt(e.status),sourceEntityId:xt(e.source_entity_id),targetEntityId:xt(e.target_entity_id),...n===void 0?{}:{message:he(n,"transfer.message")},createdAt:xt(e.created_at),expiresAt:xt(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Dp(){return crypto.randomUUID()}var kr=class{constructor(e,n,r){this.api=e;this.self=n;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let n=await Ks(this.api,{source_entity_type:this.self.type,source_entity_id:this.self.id,target_entity_type:e.to.type,target_entity_id:e.to.id,items:(e.items??[]).map(r=>({item_definition_id:r.itemDefinitionId,quantity:r.quantity})),currencies:(e.currencies??[]).map(r=>({currency_id:r.currencyId,amount:r.amount})),...e.message===void 0?{}:{message:e.message},nonce:Dp()},e.signal===void 0?{}:{signal:e.signal});return Sr(n)}async list(e={}){let r=await rl(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Sr):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await Ws(this.api,e,n===void 0?{}:{signal:n});return Sr(r)}async accept(e,n){return this.resolve(()=>ss(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>cl(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>ds(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Sr(await e())}};var Fp=t=>typeof t=="string"?t:"",$p=t=>typeof t=="string"&&t?t:void 0,qp=t=>typeof t=="number"?t:void 0;function ql(t){let e=new Map(t.map(r=>[r.id,r])),n=new Map(t.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??n.get(r)??null}function Np(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new pe("config_malformed",`the config document is ${t===null?"null":typeof t}, expected a JSON object`);let e=t,n=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new pe("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=qp(e.version);if(r===void 0)throw new pe("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,c)=>{let u=Fp(l.id);if(!u)throw new pe("config_malformed",`${d}[${c}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},o=n("items");o.forEach((l,d)=>i(l??{},"items",d));let s=n("currencies");s.forEach((l,d)=>i(l??{},"currencies",d));let a=t;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:o,currencies:s,catalogs:n("catalogs"),loot_tables:n("loot_tables"),affix_pools:n("affix_pools"),progressions:n("progressions"),game_room_templates:n("game_room_templates"),kv:typeof a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:ql(o),currency:ql(s)}}var pe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Nl=10*1024*1024,jl=15e3,Bl=new Set(["dev","test","release"]);function jp(t){if(!Bl.has(t))throw new pe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Bl].join(", ")}. gem-api would reject the assignment read.`);return t}var Rr=t=>typeof t=="number"?t:0,Ki=t=>typeof t=="string"?t:"";function Bp(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:Ki(i.entry_id),weight:Rr(i.weight),dropRate:Rr(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:Ki(e.loot_table_id),name:Ki(e.name),rollCount:Rr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Rr(e.total_weight),entries:n}}var Ar=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=void 0;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded!==void 0)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,n=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===n&&(this.inFlight=null);});return this.inFlight=n,n}refresh(){this.loaded=void 0,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new pe("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let i=this.dropRatesByConfig.get(r);i===void 0&&(i=new Map,this.dropRatesByConfig.set(r,i));let o=i.get(e);if(o!==void 0)return o;let s=(async()=>{let a=await Rs(this.api,e,n===void 0?{}:{signal:n});return Bp(a)})().catch(a=>{throw i?.get(e)===s&&i.delete(e),a});return i.set(e,s),s}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??jl),n;try{let l=await Ss(this.api,jp(this.channel()),{signal:e});if(!l.modified)throw new pe("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof pe)throw l;if(l?.reason==="not_found")return null;throw l}let r=$p(n.config_url);if(r===void 0)return null;let i=this.options.fetch??globalThis.fetch.bind(globalThis),o;try{o=await i(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new pe("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??jl}ms`):new pe("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!o.ok){let l=await o.text().then(d=>ji(d)).catch(()=>"");throw new pe("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await o.text();if(s.length>Nl)throw new pe("config_too_large",`the config document is ${s.length} bytes, over the ${Nl} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new pe("config_malformed",`config document is not JSON: ${String(l)}`)}return Np(a)}};var Ul=400,Ce=t=>typeof t=="string"?t:"",Up=/(?:Z|[+-]\d{2}:?\d{2})$/i;function it(t){let e=Ce(t);if(!Up.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Wp=/^[0-9a-f]{1,64}$/,Vp=/^[0-9a-f]{16}$/,Hp=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Kp=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Ji(t){let e=Ce(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,i,o]=[Number(n[1]),Number(n[2]),Number(n[3])],s=new Date(Date.UTC(r,i-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===i-1&&s.getUTCDate()===o?e:void 0}var Jp=4096,zp=new TextEncoder;function Xp(t){let e=Ce(t.challenge_data),n=Ce(t.challenge_data_hash);return e===""||!Vp.test(n)?{}:zp.encode(e).length>Jp?{}:{data:e,dataHash:n}}function Yp(t){let e=t??{},n=it(e.period_start_at),r=it(e.period_ends_at);if(n===0||r===0)return;let i=Ce(e.slug),o=Ce(e.seed),s=Ji(e.period_local_date),a=Ce(e.boundary),l=Ce(e.reset_time);return {id:Ce(e.progression_definition_id),...i===""?{}:{slug:i},window:Ce(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:Hp.test(a)?a:"",resetTime:Kp.test(l)?l:"",seed:Wp.test(o)?o:"",...Xp(e)}}function Pt(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function xr(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Yp).filter(n=>n!==void 0):[]}var Yt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;Pt(n);let r=await Xs(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return xr(r)}};function Me(t){return typeof t=="string"&&t!==""?t:void 0}var Wl=new Set(["localhost","127.0.0.1","[::1]"]);function ot(t){return Tt(t)}function Tt(t){let e=Me(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&Wl.has(n.hostname)))return e}var Qp=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Zp=/^[a-z][a-z0-9_]{0,31}$/;function eg(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let i=r??{},o=Me(i.family),s=Me(i.avatar_3d_id),a=ot(i.model_url),l=ot(i.icon_url);o===void 0||!Zp.test(o)||n.has(o)||s===void 0||!Qp.test(s)||a===void 0||l===void 0||(n.add(o),e.push({family:o,id:s,modelUrl:a,iconUrl:l}));}return e}function tg(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},i=Me(r.item_id),o=ot(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Pe(t){let e=t??{},n=Me(e.player_id),r=Me(e.display_name),i=Me(e.discriminator),o=Me(e.display_tag),s=Me(e.avatar_icon_id),a=ot(e.avatar_icon_url),l=Me(e.avatar_3d_id),d=ot(e.avatar_3d_model_url),c=ot(e.avatar_3d_icon_url),u=eg(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:he(r,"displayName")},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:he(o,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...c===void 0?{}:{avatar3dIconUrl:c},...u===void 0?{}:{avatars3d:u},badges:tg(e.badges)}}var ng=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function zi(t){if(t===void 0)return;let e=ot(t);if(e===void 0)return;let n=new URL(e);return Wl.has(n.hostname)||ng.has(n.origin)?e:void 0}var Vl=100,Jl=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Xi(t){let{periodsBack:e,period:n,playerId:r}=t;if(Pt(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!Jl.test(n)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(n)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...n===void 0?{}:{period:n},...r===void 0?{}:{player_id:r}}}function zl(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!Jl.test(e))return;let n=Ji(t.period_local_date),r=it(t.period_start_at),i=it(t.period_ends_at),o=r>0&&i>0;return {id:e,...n===void 0?{}:{localDate:n},...o?{startAt:r,endsAt:i}:{},opensAt:it(t.opens_at),closesAt:it(t.closes_at),final:t.final===true}}var Qt=t=>typeof t=="string"?t:"",Et=t=>typeof t=="number"?t:0,Zt=t=>typeof t=="string"?t:void 0,rg=t=>typeof t=="number"?t:void 0,Xl={player:"players",character:"characters"};function ig(t,e){let n=t??{},r=Zt(n.entity_id),i=typeof n.entity_type=="string"&&Object.hasOwn(Xl,n.entity_type)?n.entity_type:void 0,o=Yl(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...Pe(n),rank:Et(n.rank),occurredAt:Et(n.occurred_at),...a===void 0?{}:{isViewer:a},...r===void 0?{}:{entityId:r},...i===void 0?{}:{entityType:i},...o===void 0?{}:{stats:o},...s===void 0?{}:{properties:s}}}function Hl(t,e){let n=t??{},r=Zt(n.bucket_1),i=Zt(n.bucket_2),o=rg(n.update_frequency_seconds),s=zl(n);return {leaderboardType:Qt(n.leaderboard_type),runType:Qt(n.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(n.entries)?n.entries.map(a=>ig(a,e)):[],generatedAt:Et(n.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function Kl(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=Yl(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:Et(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function Yl(t){if(t===null||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t))typeof r=="number"&&(e[n]=r);return e}function og(t,e,n){let r=t??{},i=Zt(r.bucket_1),o=Zt(r.bucket_2),s=zl(r);return {leaderboardType:Qt(r.leaderboard_type),runType:Qt(r.run_type),entityType:e,entityId:n,...i===void 0?{}:{bucket1:i},...o===void 0?{}:{bucket2:o},entries:Array.isArray(r.entries)?r.entries.map(Kl).filter(a=>a!==void 0):[],personalBest:Kl(r.personal_best)??null,totalRuns:Et(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:Et(r.generated_at),...s===void 0?{}:{period:s}}}var en=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Xi(n),i=await Fs(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Hl(i,false)}async friends(e,n={}){let r=Xi(n),i=await Os(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Hl(i,true)}async mine(e,n={}){return this.#n(e,"player","me",n)}async character(e,n,r={}){return this.#n(e,"character",n,r)}async#n(e,n,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>Vl)throw new TypeError(`limit must be an integer between 1 and ${Vl}, got ${String(l)}`)}let o=Xi(i),s=await Ts(this.#e,e,Xl[n],r,{...o,...i.bucket1===void 0?{}:{bucket_1:i.bucket1},...i.bucket2===void 0?{}:{bucket_2:i.bucket2},...i.limit===void 0?{}:{limit:i.limit},...i.signal===void 0?{}:{signal:i.signal}}),a=n==="player"&&r==="me"&&Qt((s??{}).entity_id)||r;return og(s,n,a)}};var Pr=t=>typeof t=="string"?t:"",Yi=t=>typeof t=="number"?t:0;function Ql(t){let e=t??{};return {playerId:Pr(e.player_id),key:Pr(e.key),value:e.value,updatedAt:Yi(e.updated_at)}}function ag(t){let e=t??{};return {...Pe(e),playerId:Pr(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Yi(e.updated_at)}}function sg(t){return t?.reason==="not_found"}var tn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let i=await Gs(this.api,Fe(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:Pr(i.key),entries:Array.isArray(i.entries)?i.entries.map(ag):[],generatedAt:Yi(i.generated_at)}}async of(e,n,r={}){try{return Ql(await Bs(this.api,e,Fe(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(sg(i))return null;throw i}}async set(e,n,r={}){if(Fe(e),n===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(n);}catch(o){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}.`,{cause:o})}let i=await this.selfPlayerId();return Ql(await ll(this.api,i,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await bs(this.api,r,Fe(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var lg="gemChallenge",Zl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ed(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(lg)??void 0}catch{return}}var at=class extends M{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(n))i!==void 0&&Object.assign(this,{[r]:i});}},Tr=t=>typeof t=="string"?t:void 0;function td(t){let e=t??{};return {...Pe(e),playerId:Tr(e.player_id)??""}}function nd(t){let e=t.has_more===true?Tr(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function dg(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(td):[],...nd(e)}}var Qi=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function cg(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function rd(t){let e=t??{},n=Qi(e.opened_at),r=Qi(e.answered_at);return {id:Tr(e.item_id)??"",from:td(e.sender),template:Tr(e.template)??"",params:cg(e.params),createdAt:Qi(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function ug(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(rd):[],...nd(e)}}function mg(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var nn=class{#e;#n;#o;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#o=n.launchedChallengeId;}async list(e={}){let n=await nl(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return dg(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await tl(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return ug(n)}async launchedChallenge(e={}){let n=this.#o;if(n===void 0||!Zl.test(n))return null;try{return rd(await Ds(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(mg(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!Zl.test(e))throw new M("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await il(this.#e,e);}};var pg=0;function _e(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++pg)}-${String(Date.now())}-${t}`}}var gg=12e4,id=8,fg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,yg=/^[a-z0-9][a-z0-9_-]{0,63}$/;function rn(t,e,n={}){return new at(new M("invalid",400,e,void 0,t),n)}function hg(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function bg(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!fg.test(e))return {error:rn("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!yg.test(n))return {error:rn("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(!hg(r))return {error:rn("param_invalid","params must be a plain object of strings and integers")};let i={},o=Object.keys(r);for(let s of o){let a=r[s];if(typeof a=="string"||typeof a=="number"&&Number.isSafeInteger(a)){Object.defineProperty(i,s,{value:a,enumerable:true,writable:true,configurable:true});continue}return {error:rn("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>id?{error:rn("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(id)}`)}:{playerId:e,template:n,params:i}}function vg(t){switch(t.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:t.outcome}};case "rate_limited":{let e=t.retryAfterMs,n=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new at(new M("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new at(new M("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function _g(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function od(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=bg(n);if("error"in r)return Promise.reject(r.error);let i=`challenge-${_e()}`;return new Promise((o,s)=>{let a={},l=c=>{e.delete(i)&&(t.clock.clearTimeout(a.timer),"error"in c?s(c.error):o(c.outcome));};e.set(i,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??gg);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 (${_g(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(vg(n));}}}var Er=t=>typeof t=="string"?t:void 0;function wg(t){let e=t??{},n=Er(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Er(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Ir=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await Zn(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=wg(o);s!==void 0&&i.push(s);}return i}},Zi=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function Sg(t){let e=t??{},n=Er(e.currency_id);if(n===void 0||n==="")return;let r=Zi(e.limit),i=Math.min(Zi(e.earned),r),o=Math.min(Zi(e.remaining),r-i),s=e.period_days,a=typeof s=="number"&&Number.isInteger(s)&&s>=1?s:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Er(e.currency_slug)??"",currencyId:n,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function ad(t){let e=new Set,n=r=>{t?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let i=r();typeof i?.then=="function"&&i.then(void 0,n);}catch(i){n(i);}}}}var Cr=class{#e;#n;#o;constructor(e,n,r){this.#e=e,this.#n=n,this.#o=r;}async get(e={}){let r=(await $s(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=Sg(o);s!==void 0&&i.push(s);}return i}on(e,n){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},on=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Ir(e),this.earnAllowance=new Cr(e,n,r);}};var eo=t=>typeof t=="string"?t:"",sd=t=>typeof t=="number"?t:0;function kg(t){let e=t??{};return {key:eo(e.key),visibility:eo(e.visibility),value:e.value,updatedAt:sd(e.updated_at)}}function Rg(t){let e=t??{};return {...Pe(e),playerId:eo(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(kg):[],generatedAt:sd(e.generated_at)}}function Ag(t){return t?.reason==="not_found"}var an=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return Rg(await qs(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Ag(r))return null;throw r}}};var xg=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]]),sn=class extends M{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:xg.get(this.code))??super.retryable}},ze=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Pg(e),i;try{i=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(o){throw o instanceof M?Eg(o):o}return Tg(i)}};function Pg(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let e;try{e=JSON.stringify(t);}catch(n){throw new se(`the function input could not be serialised to JSON: ${String(n)}. Pass bytes, or a value JSON can carry. This is a bug in the call, not a server failure.`)}if(e===void 0)throw new se(`the function input is ${typeof t}, which JSON cannot carry. Pass bytes \u2014 an empty Uint8Array for no input \u2014 or a JSON value. This is a bug in the call, not a server failure.`);return new TextEncoder().encode(e)}function Tg(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 Eg(t){let{details:e,invocationId:n}=is(t),i=e?.untrusted?.message,o=e?.reason;return new sn(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...t.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}function Mr(t,e){let n=e?.retryAfterSeconds,r=typeof n=="number"&&Number.isFinite(n)&&n>0?n*1e3:0,i=1e4*2**Math.min(Math.max(0,t-1),16);return Math.min(Math.max(r,i),3e5)}var Ig=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],to="gem_";function ld(t){return t.startsWith(to)}function Cg(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function Mg(t){let e=t;return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^=e>>>16,e>>>0}function Or(t,e,n){if(no(t,n),typeof e!="string"||e==="")throw new TypeError("[gem] experiment: playerId must be a non-empty string");let r=typeof n=="number"?n:n.length,i=Mg(Cg(`${t}:${e}`))%r;return typeof n=="number"?i:n[i]}function no(t,e){if(typeof t!="string"||t==="")throw new TypeError("[gem] experiment: key must be a non-empty string");if(typeof e=="number"){if(!Number.isInteger(e)||e<1||e>2048)throw new RangeError(`[gem] experiment '${t}': the count must be an integer from 1 to 2048; got ${String(e)}`);return}if(!Array.isArray(e))throw new TypeError(`[gem] experiment '${t}': pass a count or a list of strings; got ${typeof e}`);let n=e;if(n.length<1||n.length>2048)throw new RangeError(`[gem] experiment '${t}': the list must hold 1 to 2048 strings; got ${n.length}`);if(!n.every(r=>typeof r=="string"))throw new TypeError(`[gem] experiment '${t}': every option must be a string`)}var dd=1e4,cd=50,Og=500,Gg=65536-4*1024,Lg=24*1024;function ud(t){let e={},n={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=i:typeof i=="number"&&Number.isFinite(i)&&(n[r]=i);return {dimensions:e,measures:n}}var md=t=>typeof t=="number"?t:0,Dg=t=>typeof t=="string"?t:"";function Gr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function Fg(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:md(o.index),code:Dg(o.code)}}):[];return {accepted:md(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function ro(){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 $g(t){return t?.retryable===true}var ln=class{#e;#n;#o;#y;#t=[];#h={};#a=0;#s=null;#b=false;#v=false;#m=0;#_=0;#w=0;#r=false;#S=null;#l=null;#c=false;#i=false;#p=false;#k=false;#R=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#o=Math.max(dd,e.options?.flushIntervalMs??dd),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??Og));}track(e,n={}){if(!(!this.#n||this.#r)){if(ld(e)){this.#R||(this.#R=true,this.#f(`[gem] analytics: '${e}' was not recorded \u2014 the gem_ prefix is reserved for the platform's own events, which the SDK emits for you. Name your event something else.`));return}this.#A(e,ud({...this.#h,...n}));}}setContext(e){this.#h={...this.#h,...e};}async experiment(e,n){no(e,n);let r=this.#e.awaitPlayerId===void 0?this.#e.playerId():await this.#e.awaitPlayerId();if(r===null)throw new Error(`[gem] experiment '${e}': no player to select for \u2014 this call was not made by a player.`);return typeof n=="number"?Or(e,r,n):Or(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return Gr();let n=this.#C();if(n===null||n==="")return this.#t.length>0&&!this.#k&&(this.#k=true,this.#f("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),Gr();if(this.#P(),this.#t.length===0)return Gr();let r=e.keepalive===true;if(this.#m>0&&!r)return Gr();this.#u();let i=this.#t.splice(0,this.#E(r)),o=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:ro(),sent_at_ms:s,events:i.map(d=>pd(d,s))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await Hs(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),c=Fg(d,o);return this.#_=0,this.#w=0,this.#I(c),c}catch(d){throw $g(d)?(this.#T(i,o),this.#_+=1,this.#w=this.#e.clock.now()+Mr(this.#_,d)):this.#f(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#m-=1,this.#t.length>0&&this.#d();}}trackPlatform(e,n={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#A(e,ud(n));}hold(){this.#r||this.#l!==null||(this.#i=true,this.#u());}release(){if(!this.#i||this.#r)return;this.#i=false;let e=this.#e.clock.now(),n=this.#t.map(r=>({...r,atMs:e}));this.#t=n,this.#p&&(this.#p=false,this.#l=e,this.#c=false,this.#t.unshift({uid:ro(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=cd?this.#g():this.#t.length>0&&this.#d();}get held(){return this.#i}startSession(){if(!(this.#r||this.#l!==null)){if(this.#i){this.#p=true;return}this.#l=this.#e.clock.now(),this.#c=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#c)return;if(this.#c=true,this.#i){this.#p=false,this.#t=[],this.#a=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#g({keepalive:true});}setPaused(e){this.#r||e===this.#b||(this.#b=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#v||(this.#v=e,e?this.#u():this.#t.length>0&&this.#d());}dispose(){this.#r=true,this.#u(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#A(e,n){let{dimensions:r,measures:i}=n;for(this.#P();this.#t.length>=this.#y;)this.#t.shift(),this.#a+=1;this.#t.push({uid:ro(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=cd?this.#g():this.#d();}#g(e={}){if(e.keepalive!==true&&this.#x()>0){this.#d();return}this.flush(e).catch(()=>{});}#x(){return Math.max(0,this.#w-this.#e.clock.now())}#T(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#y;)this.#t.shift(),this.#a+=1;}#E(e){let n=e?Lg:Gg,r=Math.min(this.#t.length,100),i=128;for(let o=0;o<r;o+=1){let s=this.#t[o];if(s===void 0)break;if(i+=JSON.stringify(pd(s,0)).length+1,i>n)return Math.max(1,o)}return r}#d(){this.#s!==null||this.#b||this.#v||this.#i||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#g();},Math.max(this.#o,this.#x())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#P(){let e=this.#M();e===null||e===""||(this.#S!==null&&this.#S!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#S=e);}#I(e){for(let n of e.rejected)this.#f(`[gem] analytics: an event was refused (${n.code}). `+qg(n.code));}#f(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#C(){try{return this.#e.gameId()}catch{return null}}#M(){try{return this.#e.playerId()}catch{return null}}};function pd(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function qg(t){switch(t){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function be(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function dn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=be(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Ng=2e3,jg=5e3;function fd(t){let e=[],n=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,c=null;s=u=>{d||(d=true,r=null,t.clock.clearTimeout(c),l(u));},c=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??Ng);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !gd(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=c=>{i.delete(d)&&(t.clock.clearTimeout(l),a(c));};i.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??jg);})},accept(s,a){let l=dn(a),d=be(s),c=l.length>0?l:d===void 0?[]:[d];if(c.length!==0){e=c,r?.settle(c);for(let[u,p]of [...i])gd(c,p)||u(c);}}}}function gd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Bg=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),w=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="DedicatedServerError",this.retryable=Bg.has(n),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var yd=["explicit","stale_cleanup","game_room_closed","replaced","migration_failed","host_left","insufficient_players","all_left","expired","migration_rate_exceeded","game_room_gone","failed","idle","reclaimed"],Ug=new Set(yd);function Xe(t){return typeof t=="string"&&Ug.has(t)?t:"unknown"}var Lr="webrtc_dedicated",so=["universal","mobile","web"];var Wg="p2p_unavailable",Vg="capacity_unavailable",Hg=2,hd=3e4,bd=1e3,vd=2e4;async function lo(t){let e=be(t.clusterTargetId),n=t.nextClusterTarget,r=0,i=t.clock??ue,o=t.retry??{},s=o.budgetMs??hd,a=o.maxDelayMs??vd,l=o.initialDelayMs??bd,d=i.now(),c=d+s,u=0;for(;;){u++;try{let p=await po(t.signal,"while allocating",()=>t.client.post(`${Sd(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Kg(p)||s<=0)throw p;if(p.status===503&&p.code===Wg)throw new w("p2p_unavailable",`room ${t.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});if(r=p.code===Vg?r+1:0,n!==void 0&&r>=Hg){let x=n;n=void 0;let P=be(await x());P!==void 0&&(e=P,r=0);}let g=Math.min(a,l*2**(u-1)),f=Math.min(a,(p.retryAfterSeconds??0)*1e3),k=Math.max(g/2,f)+Math.random()*(g/2);if(i.now()+k>c)throw Jg(t,p,u,i.now()-d,s);if(o.onWaiting?.({attempt:u,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:k,status:p.status,message:p.message}),await Dr(i,k,t.signal),t.signal?.aborted)throw ao("while waiting to allocate")}}}function Kg(t){return t instanceof M?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Jg(t,e,n,r,i){let o=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new w("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${o}: ${e.message}`,{cause:e}):new w("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${o}: ${e.message}`,{cause:e})}var zg=12e4,Xg=1e3;async function co(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Xg,i=t.timeoutMs??zg,o=e.now()+i,s=_d(t),a={seen:t.knownToExist===true};for(;;){let l=await wd(t,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new w("timeout",`match ${n} was still ${l.status} after ${i}ms`);await Dr(e,r,t.signal);}}async function uo(t){return (await wd(t,_d(t),{seen:t.knownToExist===true})).outcome}function _d(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Sd(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function wd(t,e,n){let{matchId:r}=t,i=t.clock.now(),o;try{o=await po(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof M&&s.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(n.seen=true,o.status==="ready")return {status:"ready",outcome:Yg(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Xe(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function mo(t){let e=await po(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 po(t,e,n){if(t?.aborted)throw ao(e);try{return await n()}catch(r){throw t?.aborted?ao(e,r):r}}function ao(t,e){return new w("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function Yg(t,e,n){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:n+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function Sd(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Dr(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{t.clearTimeout(o),n?.removeEventListener("abort",i),r();},o=t.setTimeout(i,e);n?.addEventListener("abort",i);})}function kd(t){return typeof t=="string"&&t.trim()!==""}function Fr(t,e){return kd(t)?t.trim():kd(e)?e:null}var $r="0.1.0-beta",Rd="0-beta",It="web",Qg=/^(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 Zg(t){let e=Qg.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Ad(t,e){let n=ef(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:$r};let i=Zg(r);if(i===null)throw new w("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${$r}' for it.`);if(i!==Rd)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Rd}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${$r}' for it.`);return {...t,platform:n,engineVersion:r}}function ef(t,e){if(t===void 0||t===It)return It;if(!so.includes(t))throw new w("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${so.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${It}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${It}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),It}function cn(t){let e=t??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let n=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:xd(e.queued_at),expiresAt:xd(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function xd(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var tf=3,Pd=1e3,qr=class{constructor(e){this.options=e;this.snapshot=e.first;let n=new Promise((o,s)=>{this.resolve=o,this.reject=s;});n.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:n,cancel:()=>(this.requestCancel(),n)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let n=e?Pd:Math.max(Pd,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},n);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,n=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){n=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(n);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof M&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<tf){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof M&&e.code==="matchmaking_unavailable";this.settle({status:n?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let n=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:n});}catch(n){this.busy=false,this.fail(n);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var nf="gemPlayWith",rf=/^[A-Za-z0-9_-]{16,128}$/;function Td(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(nf);}catch{return}return e!==null&&rf.test(e)?e:void 0}function Ed(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var of="join",af="welcome",sf="rejected",Id=25e3,lf=1e3,go=1;function fo(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var df={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 yo(t){let e=typeof t=="string"?t:"unknown";return new w(df[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function un(t){let{channel:e,clock:n}=t;return new Promise((r,i)=>{let o=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Id),a=n.setTimeout(()=>h(new w("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,lf)),l=k=>{let x=k.data;if(typeof x!="string"){u(x);return}let P;try{P=JSON.parse(x);}catch{u(x);return}if(o){u(x);return}if(P.t===af){let b=fo(P.heartbeat_interval);f({...typeof P.player_id=="string"?{playerId:P.player_id}:{},...typeof P.match_id=="string"?{matchId:P.match_id}:{},...b===void 0?{}:{heartbeatIntervalMs:b}});return}if(P.t===sf){h(yo(P.reason));return}u(x);},d=()=>{h(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},c=()=>{h(new w("aborted","the caller aborted during the join exchange"));},u=k=>{o&&t.onMessage?.(k);},p=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",c);},g=()=>{e.removeEventListener("message",l);},f=k=>{o=true,p(),t.onMessage===void 0&&g(),r({welcome:k,detach:g});},h=k=>{o||(o=true,p(),g(),i(k));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){c();return}t.signal?.addEventListener("abort",c);try{e.send(JSON.stringify({t:of,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:go}:{}}));}catch(k){h(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(k)}`,{cause:k}));}})}var st=1,mn=2,ho=4,_o=8,cf=2,uf=1e3,wo="heartbeat timeout",pn="gem-uu",Nr=2,Md="gem_transports";function Ct(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!mf(r)||e.includes(r)||e.push(r);}return e}function mf(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function gn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Md];if(typeof n!="object"||n===null)return null;let r=n;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function jr(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Od=new TextEncoder,Gd=new TextDecoder;function So(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function ko(t){let e=0;return t?.reliable===false&&(e|=st),t?.ordered===false&&(e|=mn),e}function Ro(t){return {reliable:(t&st)===0,ordered:(t&mn)===0}}var Ao={reliable:true,ordered:true};function Ld(t){return JSON.stringify({t:"join",credential:t,wire:Nr,heartbeat:go})}function Dd(t){let e;try{e=JSON.parse(t);}catch{throw new w("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=fo(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"?yo(e.reason):new w("join_refused","the server answered the join out of protocol")}function Br(){return typeof globalThis.WebTransport=="function"&&xo===null}function Ur(){return xo}var xo=null;var Cd="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function pf(t){let e=Qn(t);if(e.byteLength!==32)throw new w("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var bo=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new w("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function vo(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 fn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new w("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new a(t.url):new a(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:pf(t.certHashBase64)}]});}let r=n,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(xo=Cd,i(new w("connection_failed",`${Cd}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new w("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return i(new w("connection_failed","the session ended before the control stream arrived"));let d=l.value,c=d.writable.getWriter();await c.write(vo(ho,Od.encode(Ld(t.credential))));let u=new bo,p=d.readable.getReader(),g;for(;g===void 0;){let f=await Promise.race([p.read(),s]);if(f.done||f.value===void 0)return i(new w("connection_failed","the control stream closed before the join was answered"));for(let h of u.push(f.value)){g=Dd(Gd.decode(h.payload));break}}return {link:gf(r,c,p,u,t.log??(f=>console.warn(f)),$d(g,t.clock)),welcome:g}}catch(a){return i(a)}}function gf(t,e,n,r,i,o){let s,a,l=false,d=f=>{if(!l){l=true,c.stop();try{t.close();}catch{}a?.(f);}},c=To(o,()=>d(wo)),u=(f,h)=>{c.heard(),(f&_o)===0&&s!==void 0&&((f&ho)!==0?s(Gd.decode(h),Ao):s(h,Ro(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let h of r.push(f.value))u(h.flags,h.payload);}}catch{}d("stream closed");})();let p,g;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let h=f.readable.getReader();g=f.writable.getWriter(),p=f,(async()=>{try{for(;;){let k=await h.read();if(k.done||k.value===void 0)break;let x=k.value;x.byteLength!==0&&u((x[0]??0)|st|mn,x.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){p=void 0,g=void 0,i(`[gem] webtransport datagram lane unusable (${jr(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(Fd(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,h){if(l)return;if(typeof f=="string"){e.write(vo(ho,Od.encode(f))).catch(()=>d("write failed"));return}let k=ko(h);if((k&st)!==0&&g!==void 0){let x=So(k,f),P=p?.maxDatagramSize;if(P===void 0||x.byteLength<=P){g.write(x).catch(()=>{});return}}e.write(vo(k,f)).catch(()=>d("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){d("closed");}}}function Po(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new w("connection_failed","this environment has no WebSocket"));n=new i(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),o(g));},d=()=>{r.send(Ld(t.credential));},c=g=>{if(s)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let f;try{f=Dd(g.data);}catch(h){l(h);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",c),r.removeEventListener("close",u),r.removeEventListener("error",p),i({link:ff(r,$d(f,t.clock)),welcome:f});},u=()=>{l(new w("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new w("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",c),r.addEventListener("close",u),r.addEventListener("error",p),r.readyState===1&&d();})}function Fd(t){return typeof t=="string"&&t.length>0?t:void 0}function $d(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function To(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,uf)*cf,i=n.now(),o=null,s=()=>{o=null;let a=n.now()-i;if(a>=r){e();return}o=n.setTimeout(s,r-a);};return o=n.setTimeout(s,r),{heard:()=>{i=n.now();},stop:()=>{o!==null&&(n.clearTimeout(o),o=null);}}}function ff(t,e){let n,r,i=false,o=a=>{if(!i){i=true,s.stop();try{t.close();}catch{}r?.(a);}},s=To(e,()=>o(wo));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,Ao);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&_o)===0&&n?.(l.slice(1),Ro(d));})),t.addEventListener("close",(a=>o(Fd(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){t.send(a);return}t.send(So(ko(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){o("closed");}}}function Eo(t,e,n,r){let i,o,s=false,a=n,l=u=>{if(!s){s=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}o?.(u);}},d=To(r,()=>l(wo)),c=(u,p)=>{if(d.heard(),typeof u=="string"){i?.(u,Ao);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let f=g[0]??0;(f&_o)===0&&i?.(g.slice(1),Ro(f|p));};if(t.addEventListener("message",(u=>c(u.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(p=>c(p.data,st|mn))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,p){if(s)return;if(typeof u=="string"){t.send(u);return}let g=ko(p),f=So(g,u);if((g&st)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}t.send(f);},onMessage(u){i=u;},onClose(u){o=u;},close(){l("closed");}}}function qd(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let i=Io(r);i!==void 0&&(e[n]=i);}return e}function Nd(t){if(Array.isArray(t))return t.map(yf).filter(e=>!!e)}function Io(t){if(Co(t)||Array.isArray(t)&&t.every(Co))return t}function Co(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function yf(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Io(e.fixed),r=Io(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...Mt("description",hf(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Co)?{allowed:e.allowed}:{},...Mt("min",yn(e.min)),...Mt("max",yn(e.max)),...Mt("minItems",yn(e.min_items)),...Mt("maxItems",yn(e.max_items)),...Mt("maxLength",yn(e.max_length))}}function hf(t){return typeof t=="string"&&t.length>0?t:void 0}function yn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Mt(t,e){return e===void 0?{}:{[t]:e}}function $e(t){let e=t??{},n=Q(e.id)??Q(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(bf):[];return {id:n,gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:Oe(e.max_players)??0,memberCount:Oe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...Re("joinCode",Q(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...Re("roomArgs",qd(e.room_args)),...Re("roomArgsTemplate",Nd(e.room_args_template)),gameChannel:Q(e.game_channel)??"release",...Re("region",Q(e.region)),...Re("clusterTargetId",Q(e.cluster_target_id)),selfHosted:e.self_hosted===true,...Re("matchId",Q(e.match_id)),version:Oe(e.version)??0,...Re("templateId",Q(e.template_id)),...Re("templateSlug",Q(e.template_slug)),roomType:Q(e.game_room_type)??"Standard",...Re("transports",Ct(e.transports)??void 0),createdAt:Oe(e.created_at)??0,updatedAt:Oe(e.updated_at)??0,...Re("startedAt",Oe(e.started_at))}}function bf(t){let e=t??{};return {...Pe(e),playerId:Q(e.player_id)??"",isReady:e.is_ready===true,role:Q(e.role)??"member",joinedAt:Oe(e.joined_at)??0,...Re("groupId",Q(e.group_id)),...Re("platform",Q(e.platform))}}function Mo(t){let e=t??{};return {id:Q(e.id)??Q(e.game_room_id)??"",gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:Oe(e.max_players)??0,memberCount:Oe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Q(e.game_channel)??"release",roomType:Q(e.game_room_type)??"Standard",createdAt:Oe(e.created_at)??0}}function Q(t){return typeof t=="string"&&t.length>0?t:void 0}function Oe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Re(t,e){return e===void 0?{}:{[t]:e}}var Wr=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(Mo),...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(Mo)}))}create(e,n,r){return _f(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},...hn(n)},e.signal).then($e)}get(e,n){return this.options.client.get(this.roomV2(e),n).then($e)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...hn(r)},n.signal).then($e)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...hn(r)},n.signal).then($e)}quickJoin(e,n,r=[]){return Oo(this.options,e,n,r).then(i=>i.room)}createTicket(e,n,r=[]){return fs(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...hn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(cn)}heartbeatTicket(e){return Vs(this.generated(),e).then(cn)}cancelTicket(e,n=false){return n?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(cn):cs(this.generated(),e).then(cn)}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 Bd(this.options,e)}close(e,n){return this.options.client.delete(this.roomV1(e),n).then(()=>{})}update(e,n){return this.options.client.patch(this.roomV2(e),{...n.name===void 0?{}:{name:n.name},...n.maxPlayers===void 0?{}:{max_players:n.maxPlayers},...n.isPublic===void 0?{}:{is_public:n.isPublic},...n.settings===void 0?{}:{settings:n.settings},...n.roomArgs===void 0?{}:{room_args:n.roomArgs}},n.signal).then($e)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then($e)}kick(e,n,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(n)}`,{},r).then(()=>this.get(e,r))}transferHost(e,n,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(n)}`,{},r).then($e)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return jd(this.options)}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function jd(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function Bd(t,e){return e===void 0&&t.selfHosted?.()===true}function Oo(t,e,n,r=[],i){let o=Bd(t,e.partyId);return t.client.post(`${jd(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...vf(e.templateSlugs,o),...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...o?{self_hosted:true}:{},...i===void 0?{}:{play_with_ticket:i},...hn(n)},e.signal).then(s=>({room:$e(s),playWith:i===void 0?null:Ed(s)}))}function vf(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function hn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function _f(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 Vr=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===i&&n(i);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};var Hr=class{constructor(e){this.options=e;let n=e.first,r=new Promise(a=>{this.resolve=a;}),i=()=>this.status;this.ticket={id:n.ticketId,get status(){return i()},partySize:n.partySize??0,queuedAt:n.queuedAt??0,expiresAt:n.expiresAt??0,outcome:r};let o=n.queuedAt!==void 0&&n.expiresAt!==void 0?(n.expiresAt-n.queuedAt)*1e3:9e5,s=Math.min(Math.max(o,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},s);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function wf(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var Sf=1e3,kf=3e3,Rf=6e4,Af=2,Ud=new Set(["game_room_closed","game_room_gone"]),xf=12e4,Pf=5e3,Tf=new Set(["invalid_cluster_target","capacity_unavailable"]),Ef=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Kd(t,e){return new Go(e,t)}var Go=class{constructor(e,n={}){this.options=e;this.internals=n;this.autoFollow=e.followMatch!==false,this.apiOptions={client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true},this.api=new Wr(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new Vr;api;apiOptions;playWithAnswer=null;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await n;return this.api.create(r,this.version("create"),o[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,n={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(n),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(n),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),Mf(e);let n=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.postQuickJoin(r,a).catch(l=>this.retryPastStaleMembership(l,r,a)),o=await this.run("quickJoin",async()=>{let a=await n;return i(a).catch(async l=>{let d=await this.afterRefusedClusters(l,a);if(d.length===0||Hd(d,a))throw l;return i(d)})}),{room:s}=o;return this.playWithAnswer=o.playWith,this.enter(s,"joined"),this.askForLocalServer(s),s}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Cf(e?.templateSlugs),this.queueing=true;try{let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let s=await n;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Hd(l,s))throw a;return this.api.createTicket(r,this.version("queueForMatch"),l)})});this.heldQueued?.ticketId===i.id&&(this.heldQueued=null),this.partyWatch?.end({status:"lost"});let o=new qr({clock:this.options.clock,first:i,heartbeat:s=>this.track(this.api.heartbeatTicket(s)),cancel:(s,a)=>this.track(this.api.cancelTicket(s,a)),seat:s=>this.enterMatchedRoom(s),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;let n=this.heldQueued;this.heldQueued=null,n!==null&&this.showPartyTicket(n);}}async enterMatchedRoom(e){let n=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?n:(this.room!==null&&this.room.id!==n.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(n,"joined"),this.room?.id===n.id?this.room:n)}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let i of n)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(i){if(i instanceof M&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>uo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...n===void 0?{}:{signal:n}})));}catch(s){return s instanceof M&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=Xe(n.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(i),i}async kick(e,n){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(i),i}async transferHost(e,n){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(i),i}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new w("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let i=be(n.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(c,u)=>lo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...c===void 0?{}:{clusterTargetId:c},...i===void 0?{nextClusterTarget:()=>this.nextCluster(u)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(o,[s]).catch(async c=>{if(i!==void 0||!Vd(c))throw c;let u=await this.nextCluster([s],true);if(u===void 0)throw c;return a(u,[s,u])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new w("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(i)}chase(e,n,r){return co({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new w("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Ud.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new w("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let i={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!lt()){this.park(e,()=>this.reconnectStep(e));return}let n=this.options.autoReconnect;if(n===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=n.attempts||r<Sf){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(wf(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!lt()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>uo({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,!Ud.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await n.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let n=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):n&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new w("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let n=this.session.matchId;this.session={phase:"suspended",matchId:n,reason:e},this.emitter.emit("matchSuspended",{matchId:n,cause:e}),this.armReconnect(n,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new w("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let n=this.heldMatchId;if(n===null)throw new w("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:n},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let n=this.heldMatchId;if(n!==null)try{await this.api.leaveMatch(n,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}get playWith(){return this.playWithAnswer}on(e,n){let r=this.emitter.on(e,n);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Tf.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let n=new Hr({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===n&&(this.partyWatch=null);}});this.partyWatch=n,this.emitter.emit("partyQueued",n.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(i=>i.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&<())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let n=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(n,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!lt())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of Kr)e.addEventListener(r,this.visibilityListener);let n=globalThis.document;typeof n?.addEventListener=="function"&&n.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let n=this.inFlight;this.inFlight=[],await Promise.allSettled(n);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of Kr)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??Pf}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new w("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let n=this.options.clientVersion,r=Fr(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new w("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return Ad({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return dn(await this.options.resolveClusterTargets());let e=be(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Vd(e)||n.length===0?[]:dn(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!n?o:r(dn(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof M)||e.reason!=="conflict"||!Ef.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(n.signal);}catch{throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.postQuickJoin(n,r)}postQuickJoin(e,n){return Oo(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}assertNotInRoom(e){if(this.room!==null)throw new w("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new w("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new w("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,n){let r=n instanceof M?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof w?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(n,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,l]of i){let d=r.get(a);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",a,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=If(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??xf;return new Promise((i,o)=>{let s=u=>{a(),l(),this.options.clock.clearTimeout(c),e.signal?.removeEventListener("abort",d),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>i(u))),l=this.emitter.on("matchFailed",(u,p)=>s(()=>o(new w("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>s(()=>o(new w("aborted","the caller aborted while awaiting a match"))),c=this.options.clock.setTimeout(()=>s(()=>o(new w("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??kf}pushedInterval(){return this.options.pushedPollIntervalMs??Rf}pushed(){return this.options.clock.now()-this.lastPushAt<Af*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=n=>{if(this.ticketWatch?.abandon(true),n?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function lt(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Kr=["visibilitychange","focus","pageshow","online"];function If(t,e){return t.version!==e.version||t.status!==e.status||t.matchId!==e.matchId||t.hostPlayerId!==e.hostPlayerId||t.name!==e.name||t.maxPlayers!==e.maxPlayers||t.isPublic!==e.isPublic||Wd(t)!==Wd(e)}function Wd(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Vd(t){return t instanceof M&&t.code==="invalid_cluster_target"}var Jr=8;function Cf(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=Jr&&t.every(n=>typeof n=="string"&&n.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Jr} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function Mf(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Jr&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Jr} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(t?.templateSlug!==void 0||t?.templateId!==void 0)throw new w("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function Hd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Of=["p2p","dedicated","unknown"],Lo=["connection_setup_duration_seconds","reconnect_latency_seconds","datachannel_rtt_seconds","p2p_join_to_play_latency_seconds","ice_restart_outcome_total","connection_failures_total","transport_permanent_failures_total","transport_quality_score","host_migration_outcome_total","turn_relay_usage_ratio"];var Ot=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let i=Gf(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 Gf(t,e,n){let r=Math.floor(n/1e3);return t.filter(i=>Lo.includes(i.type)).slice(0,100).map(i=>{let o=Lf(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Lf(t){if(t!==void 0)return Of.includes(t)?t:"unknown"}var bn=class{constructor(e){this.options=e;this.reporter=new Ot({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:zr(i.credential)??"",hostFingerprint:zr(i.host_fingerprint)??"",hostEpoch:Xr(i.host_epoch)??0,expiresAt:(Xr(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,c=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);c.length!==0&&o.push({urls:c,username:zr(d.username)??"",credential:zr(d.credential)??""});}let s=Xr(i.expires_at),a=Xr(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,n,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:n},r);}async leave(e,n=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:n});}async telemetry(e,n){await this.reporter.post(e,n);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function zr(t){return typeof t=="string"&&t.length>0?t:void 0}function Xr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var Df=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),D=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="P2pError",this.retryable=Df.has(n);}reason;retryable};var Jd=10240,zd=2048,Ff=new TextEncoder;function Xd(t){return Ff.encode(t).length}function Ye(t,e){let n=i=>{throw new w("invalid_sdp",`the ${e} ${i}`)},r=Xd(t);r>=Jd&&n(`is ${r} bytes, over the ${Jd} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let i of t.split(/\r\n|\n/)){let o=Xd(i);o>zd&&n(`has a ${o}-byte line, over the ${zd} limit`);}}function Yr(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 Qr=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 $f=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function Gt(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=Zr(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Zr(t){let[e,...n]=t.trim().split(/\s+/);if(e===void 0||n.length===0)return null;let r=`${e.toLowerCase()} ${n.join("").toUpperCase()}`;return $f.test(r)?r:null}function vn(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 Do=5e3,qf=12e4+Do,Nf=1024,jf=6e4,Bf=1e4,Yd=64*1024,Qd=5;function Fo(t){let e=new Map,n=-1/0,r=null,i=(()=>{let a;try{a=new URL(`${t.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=t.subtle??globalThis.crypto?.subtle;if(!a)throw new D("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!i.ok)throw new D("keys_unavailable",i.reason);let a=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(Bf)});}catch{throw new D("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new D("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>Yd)throw new D("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Yd} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof D?p:new D("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let c=Array.isArray(d.keys)?d.keys:[];if(c.length>Qd)throw new D("keys_unavailable",`the JWKS endpoint published ${c.length} keys, over the ${Qd} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=o();for(let p of c){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let f=await u.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,f);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!i.ok)throw new D("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new D("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<n&&(n=-1/0),d-n<jf?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var _n=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>=Nf){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+qf),true}};function ec(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}function Zd(t){try{let e=new TextDecoder().decode(ec(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function $o(t,e,n,r,i){let o=N=>{throw new D("peer_unauthenticated",`the peer's join credential is not usable: ${N}`)},s=t.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,c=Zd(a);c===null&&o("its header does not decode"),c.alg!=="RS256"&&o(`its alg is ${JSON.stringify(c.alg)}, not RS256`),c.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(c.typ)}, not p2p+jwt`);let u=c.kid;(typeof u!="string"||u.length===0)&&o("it names no key");let p=await n.key(u);p===null&&o("it was signed by a key this build cannot resolve");let g=i.subtle??globalThis.crypto?.subtle;g||o("this environment has no WebCrypto");let f=new TextEncoder().encode(`${a}.${l}`),h;try{h=ec(d);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,h,f)||o("its signature does not verify");let x=Zd(l);x===null&&o("its payload does not decode");let P=x,b=N=>typeof P[N]=="string"?P[N]:"",S=N=>typeof P[N]=="number"&&Number.isFinite(P[N])?P[N]: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 I=S("exp")*1e3,T=S("nbf")*1e3;(!Number.isFinite(I)||e.now>I+Do)&&o("it has expired"),Number.isFinite(T)&&e.now<T-Do&&o("it is not valid yet");let V=b("role");V!=="host"&&V!=="client"&&o("it names no usable role");let q=S("host_epoch");q!==e.hostEpoch&&o("it names a different host epoch");let B=Zr(b("fingerprint"));B===null&&o("its fingerprint claim is malformed"),vn(B,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let E=Zr(b("host_fingerprint"));E===null&&o("its host fingerprint claim is malformed"),vn(E,e.hostFingerprint)||o("it was issued against a different host certificate");let O=b("jti");O.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(O,e.now)||o("it has already been used");let F=b("sub");return F.length===0&&o("it names no player"),{playerId:F.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:q,role:V,fingerprint:B,hostFingerprint:E,jti:O,expiresAt:I}}function qo(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 No(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 jo(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Bo(t){if(t.byteLength<1)return null;let e=new DataView(t);switch(e.getUint8(0)){case 1:{if(t.byteLength<3)return null;let n=e.getUint16(1,true);return n>8192||t.byteLength<3+n+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(t,3,n)),protocolVersion:e.getUint32(3+n,true),assignedPeerId:e.getUint32(7+n,true)}}case 2:return t.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return t.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function tc(t){switch(t){case 1:return "the host did not accept this credential";case 2:return "the host speaks a different protocol version \u2014 an engine peer refuses a browser peer here, deliberately";case 3:return "the match is full";case 4:return "the host is rate-limiting joins";case 129:return "the host verified this credential but it names a different player than the one who signalled \u2014 the host has its own line saying which";case 130:return "the host has this player on the kicked list for the current host epoch";case 131:return "the host could not fetch the platform's signing keys, so it cannot verify anyone yet \u2014 the host's console says why";default:return `the host refused with an unrecognised code (${t})`}}function nc(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var wn=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 Uo={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},qe=["reliable","ordered","unreliable"];function Wo(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 Sn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var ic=1,Kf=3e4,oc=2e3,Jf=5e3,ac=6e4,zf=8,Ho=class{constructor(e=zf){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;}},Xf=new Ho,Yf=8,Qf=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Rn=class{constructor(e){this.options=e;this.keys=e.keys??Fo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Qr;links=new Map;replays=new _n;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=ic+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??Kf;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),i=be(this.options.clusterTargetId);if(i!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Vo(a)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new D("timeout",`no usable P2P connection after ${n}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},n),s=()=>this.fail(new D("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",s),this.ready=null;}}async kick(e){if(!this.isHost)throw new D("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);default:return}}async onHello(e){let n=de(e.playerId),r=de(e.hostPlayerId),i=ei(e.hostEpoch);if(!(n===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new wn(n,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,ic),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new D("invalid_sdp","the browser produced an offer with no SDP");Ye(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:Gt(r);if(i===null)throw new D("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??Xf,s=()=>this.closed||e!==this.credentialGeneration,a=Jf;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let c=d.status,u;if(c===409)u=oc;else if(c===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=a,a=Math.min(a*2,ac)),u=Math.min(Math.max(u,oc),ac);}else throw d;if(!await this.waitForCredential(u,s))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=Yf){let c=this.pendingOffers.keys().next().value;c!==void 0&&this.pendingOffers.delete(c);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let i=de(e.sessionId);if(i!==null&&this.answeredSessions.get(n)===i)return;Ye(r,"offer"),this.refuseMedia(r,"offer");let o=Gt(r);if(o===null)throw new D("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(n,i);let s=this.links.get(n);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(n,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let l=await a.connection.createAnswer();await a.connection.setLocalDescription(l);let d=a.connection.localDescription?.sdp??l.sdp;if(!d)throw new D("invalid_sdp","the browser produced an answer with no SDP");Ye(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||n!==this.hostPlayerId)return;Ye(r,"answer"),this.refuseMedia(r,"answer");let o=Gt(r);if(o===null)throw new D("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:vn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new D("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e);}async onIce(e){let n=de(e.fromPlayerId),r=de(e.candidate);if(n===null||r===null)return;let i=this.links.get(n);if(!i)return;let o=de(e.sdpMid),s=ei(e.sdpMLineIndex)??ei(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let n=de(e.playerId);if(n===null)return;let r=de(e.reason)??"left";if(n===this.localPlayerId){this.fail(new D("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(n);i&&this.dropLink(i,r,true);}async onMigration(e){let n=de(e.hostPlayerId),r=ei(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:n,hostEpoch:r,...de(e.reason)===null?{}:{reason:de(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(i.kind==="refused"){this.report_(new D("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new D("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let n=de(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new D("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=de(e.code)??"unknown",r=de(e.message)??"the platform refused a signaling message";this.report_(new D("signaling_failed",`${n}: ${r}`));}openLink(e,n){let i=(this.options.peerConnectionFactory??Wo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of qe){let g=i.createDataChannel(p,Uo[p]);g.binaryType="arraybuffer",o[p]=g;}let s={playerId:e,assignedPeerId:n,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),c=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",u),o.reliable.addEventListener("message",c),s.detachHandshake=()=>{o.reliable.removeEventListener("open",u),o.reliable.removeEventListener("message",c);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}flushCandidates(e){let n=e.pendingCandidates;e.pendingCandidates=[];for(let r of n)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let n=this.credential;if(n===null)throw new D("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=n.expiresAt)throw new D("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(qo({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Bo(n);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new D(nc(r.reason),tc(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=Gt(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 $o(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof D&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",Vo(s)),a&&this.fail(s);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(No({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(jo(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let i of qe)sc(e.channels[i]);sc(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,n);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let n=this.ready;this.ready=null,n.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof D?e:new D("connection_failed",Vo(e),{cause:e}));}count(e){this.counted||!Qf.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(Yr(e))throw new D("media_refused",`the ${n} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(n=>this.options.clock.setTimeout(n,e))}warn(e){let n=this.options.log;n!==null&&(n??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function de(t){return typeof t=="string"&&t.length>0?t:null}function ei(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Vo(t){return t instanceof Error?t.message:String(t)}function sc(t){try{t.close();}catch{}}var Zf=100,ey=50,An=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??Zf)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new D("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new D("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:n,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??ey));}};function H(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Qe(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function Lt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function lc(t){return typeof t=="boolean"?t:void 0}var Se=H(64),xn=Qe(0,2147483647);function Ko(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=Se(n);typeof r=="string"&&e.push(r);}return e}function Y(t,e,n){return {to:t,from:e,read:n,required:true}}function K(t,e,n){return {to:t,from:e,read:n,required:false}}var ry=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=Lt("disconnected","failed","closed")(e.iceState),r=Qe(0,4102444800)(e.lastSeenAt);if(!(n===void 0&&r===void 0))return {...n===void 0?{}:{ice_state:n},...r===void 0?{}:{last_seen_timestamp:r}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[Y("sdp","sdp",H(10240)),Y("signaling_intent","intent",Lt("initial","ice_restart","full_reconnect")),K("sdp_hash","sdpHash",H(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[Y("peer_id","peerId",Se),Y("sdp","sdp",H(10240)),Y("assigned_peer_id","assignedPeerId",Qe(0,4294967295)),K("sdp_hash","sdpHash",H(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[Y("peer_id","peerId",Se),Y("candidate","candidate",H(512)),K("sdp_mid","sdpMid",H(64)),K("sdp_mline_index","sdpMLineIndex",Qe(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[Y("host_epoch","hostEpoch",xn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[Y("host_epoch","hostEpoch",xn),K("evidence","evidence",ry)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[Y("playerId","player_id",Se),Y("hostPlayerId","host_player_id",Se),Y("hostEpoch","host_epoch",xn),K("members","members",Ko)],offer:[Y("fromPlayerId","from_player_id",Se),Y("sdp","sdp",H(10240)),K("sessionId","signaling_session_id",H(128)),K("sdpHash","sdp_hash",H(128)),K("iceUfrag","ice_ufrag",H(64)),K("intent","signaling_intent",Lt("initial","ice_restart","full_reconnect"))],answer:[Y("fromPlayerId","from_player_id",Se),Y("sdp","sdp",H(10240)),K("sessionId","signaling_session_id",H(128)),K("sdpHash","sdp_hash",H(128)),K("iceUfrag","ice_ufrag",H(64)),K("assignedPeerId","assigned_peer_id",Qe(0,4294967295))],ice:[Y("fromPlayerId","from_player_id",Se),Y("candidate","candidate",H(512)),K("sdpMid","sdp_mid",H(64)),K("sdpMLineIndex","sdp_m_line_index",Qe(0,255)),K("sdpMLineIndexAlt","sdp_mline_index",Qe(0,255))],peerJoined:[Y("playerId","player_id",Se)],peerLeft:[Y("playerId","player_id",Se),K("reason","reason",H(64))],migration:[Y("hostPlayerId","new_host_player_id",Se),Y("hostEpoch","host_epoch",xn),K("reason","reason",H(64)),K("kickedPlayerIds","kicked_player_ids",Ko),K("migrationComplete","migration_complete",lc)],matchEnded:[K("reason","reason",H(64))],error:[K("code","code",H(64)),K("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 ct="webrtc_p2p";function cc(t){let e=new bn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,i,o){n.get(r)?.handleSignal(i,o);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new D("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=be(r.clusterTargetId),o=i??be(await t.resolveClusterTarget?.());t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let s=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==ct)throw new D("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${ct}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new An({bridge:t.bridge,matchId:s.matchId,clock:t.clock}),l=new Rn({api:e,clock:t.clock,matchId:s.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:a,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Sn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(s.matchId,l),l.on("matchEnded",()=>n.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(s.matchId),l.close(),d}return l}}}function uc(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,i=t.document??globalThis.document,o=[];if(typeof r.addEventListener=="function"){let a=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",a),o.push(()=>r.removeEventListener?.("pagehide",a));let l=()=>e.setHidden(!lt());for(let d of Kr)r.addEventListener(d,l),o.push(()=>r.removeEventListener?.(d,l));typeof i?.addEventListener=="function"&&(i.addEventListener("resume",l),o.push(()=>i.removeEventListener?.("resume",l))),e.setHidden(!lt());}let s=new Map;return o.push(n.on("matchReady",a=>{let l=a.protocol===ct?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(n.on("matchEnded",a=>{let l=s.get(a.matchId);l!==void 0&&(s.delete(a.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let a of o.splice(0))try{a();}catch{}s.clear();}}var mc=["pointerdown","keydown"];function pc(t,e=globalThis){let n=false,r=false,i=null,o=()=>{if(i!==null){try{e.cancelAnimationFrame?.(i);}catch{}i=null;}},s=()=>{if(!r){r=true,o();for(let g of mc)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(g){g?.isTrusted===true&&a();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(f=>f?.buttons.some(h=>h.pressed)===true)},c=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(i=null,!(n||r)){if(d()){a();return}c()&&(i=e.requestAnimationFrame?.(u)??null);}};function p(){i===null&&!n&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of mc)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),c()&&(i=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return n},stop:s}}async function ti(t,e,n,r){let i=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),i}function Jo(t,e){let n=false;return async r=>{let i=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),i}}function zo(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(i,o){return r.has(i)?false:(r.add(i),n.push({name:i,at:o??e()}),true)},timeline(){let i=[...n].sort((o,s)=>o.at-s.at);return i.map((o,s)=>{let a=i[s-1],l=a===void 0?"":` (+${Math.round(o.at-a.at)}ms)`;return `${o.name}@${Math.round(o.at)}ms${l}`}).join(" \u2192 ")}}}var iy="GemWebSdkHandshake";var oy=()=>Date.now();function gc(t,e,n={}){let r=t[iy];if(r===void 0)return null;let i=n.ttlMs??9500,o=n.now??oy,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,c=false,u=o()-i;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(s[p])===true){c=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:c}}var Xo=new WeakMap,fc=new WeakSet,Yo=new Set,ni=new Set,ri=[],Ft=null,Qo=false,ay=1920;function Zo(t){return Xo.get(t)}function ea(t){return !Qo||fc.has(t)}function ta(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function yc(t=globalThis.window){if(Qo||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;Qo=true;for(let o of Array.from(t.document?.querySelectorAll("canvas")??[]))fc.add(o);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(o,...s){let a=n.call(this,o,...s);if(a&&!Xo.has(this)){let l={kind:o,context:a};Xo.set(this,l),ta(l)&&Yo.add(this);}return a};let r=t.requestAnimationFrame,i=t.cancelAnimationFrame;t.requestAnimationFrame=o=>{let s=r.call(t,a=>{ni.delete(s);try{o(a);}finally{sy();}});return ni.add(s),vc(),s},t.cancelAnimationFrame=o=>{ni.delete(o),i.call(t,o);};}function hc(t,e){return new Promise(n=>{let r={canvas:t,done:o=>{clearTimeout(i),ri=ri.filter(s=>s!==r),n(o);}},i=setTimeout(()=>r.done(null),e);ri.push(r);})}function bc(t){return Ft?.canvas===t?Ft.bitmap:null}function sy(){for(let t of ri){let e;try{e=na(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}ni.size===0&&ly();}function ly(){let t=null;for(let r of Yo)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):Yo.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,ay/Math.max(t.width,t.height)),n=e<1?{resizeWidth:Math.max(1,Math.floor(t.width*e)),resizeHeight:Math.max(1,Math.floor(t.height*e)),resizeQuality:"medium"}:{};vc(),Ft={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function vc(){Ft&&(Ft.bitmap.then(t=>t?.close()),Ft=null);}function na(t){let e=dy();if(!e)return true;e.clearRect(0,0,8,8),e.drawImage(t,0,0,8,8);let n=e.getImageData(0,0,8,8).data;for(let r=0;r<n.length;r+=4){if(n[r]|n[r+1]|n[r+2])return true;let i=n[r+3];if(i!==0&&i!==255)return true}return false}var Pn;function dy(){if(Pn!==void 0)return Pn;if(typeof OffscreenCanvas=="function")Pn=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),Pn=t?.getContext("2d",{willReadFrequently:true})??null;}return Pn??null}var ra=false;async function kc(t,e,n,r){if(ra){e.close(),n("busy",true);return}ra=true;let i=null;try{let o=await my(t,r);if(typeof o=="string"){e.close(),n(o,cy(o));return}i=o;let a=await(r.encodeRef??(l=>hy(l,r)))(i);if(i.close(),i=null,a===null){e.close(),n("failed",!0);return}if(a.size>yy){e.close(),n("too_large",!1);return}e.postMessage(a);}catch(o){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",o);}finally{ra=false,i?.close();}}function cy(t){switch(t){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}var uy=600;async function my(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":_c(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=fy(n);if(!r)return "no_source";try{let i=await py(r);return typeof i=="string"?i:_c(i,t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}async function py(t){let e=gy(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!ta(e))return createImageBitmap(t);let n=await hc(t,uy);if(n)return n;let r=await bc(t);return r&&na(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function gy(t){let e=Zo(t);if(e)return e;if(!ea(t))return "no_source";try{for(let n of ["webgl2","webgl","2d","webgpu"]){let r=t.getContext(n);if(r)return {kind:n,context:r}}}catch{return "unreadable"}return "unreadable"}function fy(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||!Zo(r)&&!ea(r)||i>n&&(e=r,n=i);}return e}async function _c(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let i=Math.min(n/t.width,r/t.height),o=Math.max(1,Math.floor(t.width*i)),s=Math.max(1,Math.floor(t.height*i));try{let a=await createImageBitmap(t,{resizeWidth:o,resizeHeight:s,resizeQuality:"high"});return t.close(),a}catch{return t.close(),"too_large"}}var yy=8*1024*1024,wc="image/webp",Sc=.92;async function hy(t,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(t.width,t.height),s=o.getContext("2d");if(s){s.drawImage(t,0,0);let a=await o.convertToBlob({type:wc,quality:Sc});if(a&&a.size>0)return a}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let i=r.getContext("2d");return !i||(i.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(s=>o(s),wc,Sc);})}async function Rc(t,e){if(!e)return;let n;try{n=await by(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 by(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 Ac=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function xc(t=globalThis){let n=t[Ac];if(n!==void 0)return n;let r=false,i=()=>r,o=[],s=vy(t,i);s!==null&&o.push(s);let a=_y(t,i);a!==null&&o.push(a);let l={get muted(){return r},setMuted(d){let c=!!d;if(c!==r){r=c;for(let u of o)u();}}};return Object.defineProperty(t,Ac,{value:l,configurable:true}),l}function vy(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let i=t.OfflineAudioContext,o=n.connect,s=n.disconnect,a=new Map,l=c=>{let u=c.gain,p=c.context.currentTime;u.cancelScheduledValues(p),e()?u.setValueAtTime(0,p):u.setTargetAtTime(1,p,.01);},d=c=>{let u=c.context;if(i!==void 0&&u instanceof i)return null;let p=a.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,o.call(p,c),a.set(u,p)),p};return n.connect=function(...u){let[p,...g]=u;if(p instanceof r){let f;try{f=d(p);}catch{f=null;}if(f!==null)return o.call(this,f,...g),p}return o.apply(this,u)},n.disconnect=function(...u){let[p,...g]=u;if(p instanceof r){let f=a.get(p.context);if(f!==void 0&&f!==this)try{return s.call(this,f,...g)}catch{}}return s.apply(this,u)},()=>{for(let[c,u]of a){if(c.state==="closed"){a.delete(c);continue}try{l(u);}catch{}}}}function _y(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,i=Object.getOwnPropertyDescriptor(r,"muted"),o=i?.get,s=i?.set;if(o===void 0||s===void 0)return null;let a=r.play,l=new WeakMap,d=new WeakSet,c=new Set,u=p=>{l.has(p)||l.set(p,!!o.call(p)),d.has(p)||(d.add(p),c.add(new WeakRef(p))),s.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!o.call(this):p},set(p){l.set(this,!!p),u(this);}}),r.play=function(){try{u(this);}catch{}return a.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{u(g);}catch{}},true),()=>{for(let p of c){let g=p.deref();if(g===void 0){c.delete(p);continue}try{s.call(g,(l.get(g)??!1)||e());}catch{}}}}var wy=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Sy=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',ky=`${wy}${Sy}`,ia=new WeakSet;function Pc(t=globalThis.document){if(t==null||ia.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(ky),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],ia.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"),ia.add(t),"inline")}catch{return null}}function Tc(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=t.now??(()=>globalThis.performance?.now()??Date.now()),i=false,o=false,s=false,a=null,l=null,d=null,c=[],u=false,p=0,g=null,f=[],h=()=>i&&!o&&!s,k=()=>{l=null,d=null,c=[],p=0,g=null,f=[];},x=S=>{if(a=null,!h()){k();return}if(d!==null&&c.push(S-d),d=S,l===null)l=S;else {let I=S-l;if(I>=e&&c.length>0){if(u){let T=g===null?I:r()-g;t.report(Ay(p,f,I,T));}else t.report(Ry(c,I));l=S,c=[],p=0,f=[];}}P();},P=()=>{let S=n.requestAnimationFrame;typeof S=="function"&&(a=S.call(n,x));},b=()=>{if(h()){a===null&&(k(),P());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),k();};return {setRequested(S){i=S,b();},setPaused(S){o=S,b();},draw(){if(!u){u=true,a!==null&&k();return}if(a===null||l===null)return;let S=r();g!==null&&f.length<1e3&&f.push(S-g),g=S,p+=1;},get running(){return a!==null},dispose(){s=true,b();}}}function Ry(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:Ec(t),counts:"pageFrames"}}function Ay(t,e,n,r){let i=r;return e.length>0&&(i=Ec(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:i,counts:"gameDraws"}}function Ec(t){let e=[...t].sort((r,i)=>r-i),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var ii=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Ic(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Cc(t,e){t!==null&&(t.style.setProperty(ii.top,`${e.top}px`),t.style.setProperty(ii.right,`${e.right}px`),t.style.setProperty(ii.bottom,`${e.bottom}px`),t.style.setProperty(ii.left,`${e.left}px`));}var oi=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height",centerY:"--gem-reserved-tl-center-y",controlHeight:"--gem-reserved-tl-control-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height",centerY:"--gem-reserved-tr-center-y",controlHeight:"--gem-reserved-tr-control-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height",centerY:"--gem-reserved-bl-center-y",controlHeight:"--gem-reserved-bl-control-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height",centerY:"--gem-reserved-br-center-y",controlHeight:"--gem-reserved-br-control-height"}});function Mc(){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 xy(t,e){let n={tl:{width:0,height:0,control:null},tr:{width:0,height:0,control:null},bl:{width:0,height:0,control:null},br:{width:0,height:0,control:null}};for(let r of t){let i=e?r.x+r.width/2<=e.width/2:r.x===0,o=e?r.y+r.height/2<=e.height/2:r.y===0,s=i?r.x+r.width:e?e.width-r.x:r.width,a=o?r.y+r.height:e?e.height-r.y:r.height,l=n[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));let d=r.control;if(d){let c=l.control;l.control=c?{top:Math.min(c.top,d.y),bottom:Math.max(c.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Oc(t,e,n){if(t===null)return;let r=xy(e,n);for(let i of ["tl","tr","bl","br"]){t.style.setProperty(oi[i].width,`${r[i].width}px`),t.style.setProperty(oi[i].height,`${r[i].height}px`);let o=r[i].control;t.style.setProperty(oi[i].centerY,o?`${(o.top+o.bottom)/2}px`:""),t.style.setProperty(oi[i].controlHeight,o?`${o.bottom-o.top}px`:"");}}var Py=3e4,ai=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Gc(t){let e=t.clock??ue,n=t.timeoutMs??Py,r=new Map,i=new Map,o=0,s=a=>{let l=r.get(a);return l?(r.delete(a),i.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(a){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(a);if(l)return l;let d=new Promise((c,u)=>{let p=`ls${++o}`,g=e.setTimeout(()=>{r.delete(p),i.delete(a),u(new ai("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(p,{room:a,resolve:c,reject:u,timer:g}),t.bridge.requestLocalServer(p,a)||(s(p),c());});return i.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new ai(a.reason,a.retryable,a.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var Tn={url:"https://downloads.indiegems.games/sdk/v17.0.0/gem-web-sdk.devtools.min.js",integrity:"sha384-+eG2xP5KChUVT2KirXMEcEfHI7XfRlDeSfvPECXMOCJqPML3LpJ0DD+voIY/QMsu"};var $t=null;function Ty(){return $t!==null||($t=new Promise((t,e)=>{let n=document.createElement("script");n.src=Tn.url,n.integrity=Tn.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){$t=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${Tn.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{$t=null,e(new Error(`gem devtools: could not load ${Tn.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);})),$t}function Lc(t,e){let n=null,r=0;async function i(o){if(n!==null)return true;let s=++r;if(!e())return false;let a=await Ty();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:o,text:rt,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>i("game"),openFrom:i}}var Ey=1e4,Dc={reason:"unavailable",retryable:false};function Fc(t){let e=new Map,n=null,r=null,i=0,o=(d,c)=>{c.timer=t.clock.setTimeout(()=>{e.delete(d),c.reject({reason:"timeout",retryable:true});},t.timeoutMs??Ey);},s=(d,c)=>{let u=a(d);u&&c(u);},a=d=>{let c=e.get(d);return c?(e.delete(d),t.clock.clearTimeout(c.timer),c):null},l=new wt({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((c,u)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){u(Dc);return}let g=`t${++i}`,f={resolve:c,reject:u,reason:d,timer:null,held:p!=="connected"};e.set(g,f),o(g,f),f.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let c={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,u=>u.resolve(c));return}l.accept(c);},onDenied(d){s(d.requestId,c=>c.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[c,u]of e)u.held&&(u.held=false,t.clock.clearTimeout(u.timer),o(c,u),t.bridge.requestToken(c,u.reason));else if(d==="refused"||d==="closed")for(let c of [...e.keys()])s(c,u=>u.reject(Dc));},get identity(){return n},get gameVersion(){return r}}}var Iy=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),aa="embedder_relay_unavailable",Cy="embedder_no_relay",My=new Set([aa]),sa=new Set([Cy]),En=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new oa(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new w("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){n.refuse(new w("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(Oy(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new w("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,n);}release(e,n){this.pending.get(e)===n&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new w("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new w("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function Oy(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new w(Gy(t),r,{platformCode:t})}function Gy(t){return t===void 0||My.has(t)?"signaling_failed":sa.has(t)?"offer_refused":Iy.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var oa=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new w("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return n?.aborted?Promise.reject(new w("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new w("aborted","the caller aborted the signaling exchange"));},a=()=>{n?.removeEventListener("abort",s),this.hub.release(e.matchId,l),this.teardown===a&&(this.teardown=null);},l={settle:d=>{a(),i(d);},refuse:d=>{a(),o(d);}};this.teardown=a,n?.addEventListener("abort",s),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof w?d:new w("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var $c="match_ended:",qc="server_shutdown:",Nc="kicked:",Ly=123;function Dy(t){if(typeof t!="string"||t.length===0||t.length>Ly)return {kind:"other"};if(t.startsWith($c)){let e=Xe(t.slice($c.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(qc)?{kind:"server_shutdown",cause:t.slice(qc.length)}:t.startsWith(Nc)?{kind:"kicked",detail:t.slice(Nc.length)}:{kind:"other"}}function la(t,e,n){let r=Dy(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 da(){return {exchange(){return Promise.reject(new w("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var Fy=3e3,$y=1e4,qy=15e3;async function si(t){let e=t.peerConnection;try{Bc(t,"before the handshake started"),ca(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let s of t.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});t.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await By(e,t),ca(t);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new w("invalid_sdp","the offer carried no SDP");Ye(i,"offer"),jc(i,"offer");let o=await jy(t,i);if(ca(t),typeof o?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return Ye(o.sdp,"answer"),jc(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Uy(n,t),Bc(t,"before the channel opened"),n}catch(n){throw e.close(),Ny(n)}}function Ny(t){return t instanceof w?t:Vc(t)?ut():new w("connection_failed",Hc(t),{cause:t})}function jc(t,e){if(Yr(t))throw new w("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function jy(t,e){let n=t.exchangeTimeoutMs??$y,r=Wc(t,n),i=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(o=>{throw o instanceof w?o:Vc(o)?ut():new w("signaling_failed",Hc(o),{cause:o})});return Wy(i,t,r,()=>r.exhausted?ua("while the offer was in flight"):new w("timeout",`no answer arrived within ${n}ms`))}function By(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let i=()=>{n.clearTimeout(s),t.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{t.iceGatheringState==="complete"&&i();},s=n.setTimeout(i,e.gatherTimeoutMs??Fy);t.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Uy(t,e){if(e.signal?.aborted)return Promise.reject(ut());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new w("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??qy,i=Wc(e,r);return new Promise((o,s)=>{let a=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",c);},l=()=>{a(),o();},d=g=>{a(),s(new w("connection_failed","the data channel failed before it opened",Uc(g)===void 0?void 0:{cause:Uc(g)}));},c=()=>{a(),s(ut());},u=()=>{a(),s(i.exhausted?ua("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(u,i.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",c);})}function Wc(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 Wy(t,e,n,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(ut()):new Promise((s,a)=>{let l=u=>{i.clearTimeout(c),o?.removeEventListener("abort",d),u();},d=()=>l(()=>a(ut())),c=i.setTimeout(()=>l(()=>a(r())),n.ms);o?.addEventListener("abort",d),t.then(u=>l(()=>s(u)),u=>l(()=>a(u)));})}function Bc(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw ua(`already ${e}`)}function ua(t){return new w("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function ca(t){if(t.signal?.aborted)throw ut()}function ut(){return new w("aborted","the caller aborted the connection attempt")}function Vc(t){return t?.name==="AbortError"}function Uc(t){return t?.error}function Hc(t){return t instanceof Error?t.message:String(t)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[Y("sdp","sdp",H(10240)),K("sessionId","session_id",H(64))],error:[K("code","code",H(64)),K("message","message",H(256))],matchEnded:[K("reason","reason",H(64))]}));function eu(t){let{client:e,clock:n,rooms:r}=t,i=t.signaling??da,o=t.log??(b=>console.warn(b)),s=new Ot({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(b,S)=>{let I=a.get(b)??new Set;I.add(S),a.set(b,I);},d=(b,S)=>{let I=a.get(b);I!==void 0&&(I.delete(S),I.size===0&&a.delete(b));},c=async b=>{if(r.isHost&&!pa(r)&&r.currentRoom?.matchId===void 0){let S=be(b.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},...b.retry===void 0?{}:{retry:b.retry},...b.signal===void 0?{}:{signal:b.signal}});}return Qc(r.matchConnectionState==="suspended"?await r.reconnectToMatch(ma(b)):await r.awaitMatch(ma(b)))},u=async b=>Qc(await r.pollMatchStatus(ma(b))),p=async(b,S)=>{let I=false;try{let T=await c(b),V=r.currentRoom?.transports;if(V!==void 0&&!V.includes("webrtc"))throw new w("misconfigured",`the room template offers (${V.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let q=b.peerConnection??Zc();I=!0;let B=await si({peerConnection:q,signaling:S,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...li(b,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),E=null;if(b.presentCredential!==!1)try{E=await un({channel:B,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...li(b,"onMessage","signal"),...b.welcomeTimeoutMs===void 0?{}:{ceilingMs:b.welcomeTimeoutMs}});}catch(O){throw Te(B),Te(q),O}return Zy(r,T,B,q,S,b.reportDisconnect!==!1,b.reportConnected!==!1,E,{remember:l,forget:d},b.onMatchEnded)}catch(T){throw I&&Yc(s,T),Te(S),T}},g=async(b,S,I,T,V,q)=>{if(b==="webtransport"){let U=T?.webtransport;if(U===void 0)throw new w("misconfigured","webtransport is not advertised");let J={credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n};if(typeof U.named_url=="string"&&U.named_url!==""){let oe=Math.max(Math.floor(q/2),1e3);try{return await fn({url:U.named_url,timeoutMs:oe,log:o,...J})}catch(ge){if(Ur()!==null)throw ge;return o(`[gem] webtransport named dial failed (${jr(ge)}); retrying the pinned dial`),fn({url:U.url,certHashBase64:U.cert_sha256_b64,timeoutMs:oe,log:o,...J})}}return fn({url:U.url,certHashBase64:U.cert_sha256_b64,timeoutMs:q,...J})}if(b==="websocket"){let U=T?.websocket;if(U===void 0)throw new w("misconfigured","websocket is not advertised");return Po({url:U.url,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n,timeoutMs:q})}let B=S.peerConnection??Zc(),E,O=await si({peerConnection:B,signaling:V,clock:n,matchId:I.matchId,credentialExpiresAt:I.credentialExpiresAt,extraChannels:[{label:pn,ordered:false,maxRetransmits:0}],onExtraChannel:(U,J)=>{U===pn&&(E=J);},...li(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:Ky}:{}}),F;try{F=await un({channel:O,clock:n,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,wire:Nr,heartbeat:!0,...li(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(U){throw Te(O),Te(B),U}let N=F.welcome.heartbeatIntervalMs;return {link:Eo(O,B,E,N===void 0?void 0:{clock:n,intervalMs:N}),welcome:F.welcome,channel:O,peerConnection:B}},f=(b,S,I,T,V)=>{let q=false,B;T.link.onClose(N=>{!q&&b.reportDisconnect!==false&&la(r,S.matchId,N),B?.(N);}),b.reportDisconnect!==false&&b.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let E={transport:T.link.transport,send:(N,U)=>T.link.send(N,U),onMessage:N=>T.link.onMessage(N),onClose:N=>{B=N;},close:()=>T.link.close()},O=()=>{q||(q=true,Te(T.link),Te(V));},F=N=>{if(!q){try{b.onMatchEnded?.(N);}catch{}O();}};return l(S.matchId,F),{matchId:S.matchId,transport:I,link:E,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(S.matchId,F),O();}}},h=async(b,S)=>{let I=r.currentRoom?.id,T=r.gameId,V=()=>({advert:gn(r.currentRoom?.settings,b),template:r.currentRoom?.transports??null});if(I===void 0||T===null)return V();try{let q=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(I)}`,S);return {advert:gn(q.settings,b),template:Ct(q.transports)??r.currentRoom?.transports??null}}catch{return V()}},k=(b,S)=>{let I=b??Kc;return S.length===0?I:I.filter(T=>S.includes(T))},x=async(b,S,I)=>{try{let T=await c(b),{advert:V,template:q}=await h(T.matchId,b.signal),B=k(q,S),E=B.filter(X=>Xy(X,V)),O=Ur();if(O!==null&&B.includes("webtransport")&&V?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${O} (learned on an earlier dial in this page)`),E.length===0){let X=q===null?`the default order (${Kc.join(", ")})`:`the room template's transports (${q.join(", ")||"none"})`;throw new w("misconfigured",`none of ${X}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let F=b.transportAttemptTimeoutMs??Hy,N=()=>b.deadlineAt===void 0?1/0:b.deadlineAt-n.now(),U=X=>t.signalingReady===void 0||X<=0?Promise.resolve(!0):t.signalingReady(X),J=[],oe=[];for(let X of E){if(N()<zc){o(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}oe.length>0&&T.credentialExpiresAt-n.now()<Xc&&(T=await u(b)),oe.push(X);let Ne=!1,ke=!1,fe={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&b.redial===!0){let te=Math.min(Jc,N());await U(te)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let je=Math.max(Math.min(F,N()),zc);try{return f(b,T,X,await g(X,b,T,V,I,je),I)}catch(te){let z=te instanceof w?te:new w("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(X==="webrtc"&&Yc(s,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Ne){Ne=!0,T=await u(b);continue}if(X==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===aa&&!ke){ke=!0;let le=Math.min(Jc,N());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(le)}ms for the socket before offering again`),await U(le))continue}if(z.reason==="join_rate_limited"){let le=zy(fe,Math.random,N());if(le!==null){if(fe.attempts+=1,fe.waitedMs+=le,o(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(le)}ms before presenting again (retry ${fe.attempts} of ${nu.maxAttempts})`),await Dr(n,le,b.signal),b.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<Xc&&(T=await u(b));continue}}if(Jy.has(z.reason)||z.reason==="credential_expired"||X==="webrtc"&&tu(z)){o(`[gem] ${X} rung failed (${z.reason}): ${jr(z.cause??z)} \u2014 `+(oe.length<E.length?`falling through to ${E[oe.length]}`:"no rungs left")),J.push(z);break}throw o(`[gem] ${X} rung refused the session (${z.reason}): ${z.message}`),z}}}let ge=J[J.length-1];throw ge===void 0?new w("timeout",`the reconnect budget ran out before any transport (${E.join(", ")}) could be tried`):new w(ge.reason,`every transport tried (${oe.join(", ")}) failed; the last said: ${ge.message}`,{cause:J,platformCode:ge.platformCode})}catch(T){throw Te(I),T}};return {listClusterTargets:async(b={})=>mo({client:e,...b}),handleMatchEnded(b,S){let I=a.get(b);if(I!==void 0){a.delete(b);for(let T of I)T(S);}},connect:(async(b={})=>{let S=b.signaling??i();return b.transports===void 0?p(b,S):x(b,b.transports,S)})}}var Kc=["webtransport","webrtc","websocket"],Hy=1e4,Ky=5e3,Jc=3e3,zc=1e3,Xc=1e4,Jy=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function tu(t){return t.platformCode!==void 0&&sa.has(t.platformCode)}var nu={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function zy(t,e=Math.random,n=1/0){let r=nu;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 Xy(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Br():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Yy(e.websocket.url)}function Yy(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return Ke(e)}function ma(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var Qy=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Yc(t,e){e instanceof w&&(!Qy.has(e.reason)&&!tu(e)||t.report([{type:"connection_failures_total",value:1}]));}function Zy(t,e,n,r,i,o,s,a,l,d){let c=false,u=()=>{c||la(t,e.matchId,void 0);};o&&(n.addEventListener("close",u),s&&t.notifyMatchConnected(e.matchId));let p=()=>{c||(c=true,n.removeEventListener("close",u),a?.detach(),Te(n),Te(r),Te(i));},g=f=>{if(!c){try{d?.(f);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function pa(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Qc(t){if(t.status==="failed")throw new w("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new w("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Lr)throw new w("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Lr}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:n}=t;if(e===void 0||n===void 0)throw new w("connection_failed",`match ${t.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...t,joinCredential:e,credentialExpiresAt:n}}function Zc(){let t=globalThis.RTCPeerConnection;if(!t)throw new w("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new t({iceServers:[]})}function Te(t){try{t.close();}catch{}}function li(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var eh=1e4;function ru(t,e){return ga(t,e)}function ga(t,e){if(typeof t.serverToken!="function"||typeof t.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let n=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new wt({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((s,a)=>{let l=e.clock.setTimeout(()=>{r=null,a({reason:"unavailable",retryable:true});},e.timeoutMs??eh);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),o=t.onServerToken(s=>{let a=n(s),l=r;if(l){r=null,l.resolve(a);return}i.accept(a);});return {source:i,dispose(){o(),i.dispose(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var ya={};Gm(ya,{acceptTransfer:()=>th,addEntityProgression:()=>nh,adminAction:()=>rh,cancelInventoryTransfer:()=>ih,claimEntityProgressionRewards:()=>oh,closeGameRoom:()=>ah,createEntityBatchOrder:()=>sh,createEntityOrder:()=>lh,createSession:()=>dh,deleteEntityGameSetting:()=>ch,deleteEntitySave:()=>uh,deleteSession:()=>mh,deleteShowcaseValue:()=>ph,executeEntityRecipe:()=>gh,finalizeSaveUpload:()=>fh,getChannelAssignment:()=>yh,getDropRates:()=>hh,getEntityCurrency:()=>bh,getEntityGameSetting:()=>vh,getEntityInventory:()=>_h,getEntityInventoryItem:()=>wh,getEntityLeaderboard:()=>Sh,getEntityOrder:()=>kh,getEntityProgression:()=>Rh,getEntityRecipeAvailability:()=>Ah,getEntityRecipeUsage:()=>xh,getEntitySave:()=>Ph,getEvent:()=>Th,getGameRoomV2:()=>Eh,getLeaderboard:()=>Ih,getPlayerGameProfile:()=>Ch,getPurchaseCatalog:()=>Mh,getResolvedTemplate:()=>Oh,getRoomArgs:()=>Gh,getShowcaseValue:()=>Lh,getTransferDetails:()=>Dh,ingestAnalyticsEvents:()=>fa,initiateInventoryTransfer:()=>Fh,invokeFunction:()=>$h,kickPlayer:()=>qh,listChallenges:()=>Nh,listEntityGameSettings:()=>jh,listEntityOrders:()=>Bh,listEntityProgressions:()=>Uh,listEntitySaves:()=>Wh,listEvents:()=>Vh,listGameRooms:()=>Hh,listResolvedTemplates:()=>Kh,listTransfers:()=>Jh,maxEntityProgression:()=>zh,putEntityGameSetting:()=>Xh,putRoomArgs:()=>Yh,putShowcaseValue:()=>Qh,rejectTransfer:()=>Zh,reportMatchPlayers:()=>eb,requestSaveUploadUrl:()=>tb,resetEntityProgression:()=>nb,setMatchBackfill:()=>rb,simulateEntityOrder:()=>ib,transferHostV2:()=>ob,updateGameRoomV2:()=>ab});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 th(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function nh(t,e,n,r,i,o){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/add`;return t.client.post(s,i,o?.signal)}async function rh(t,e,n,r){let i=`/v1/voice/sessions/${v(e)}/admin`;return t.client.post(i,n,r?.signal)}async function ih(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function oh(t,e,n,r,i,o){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/claim`;return t.client.post(s,i,o?.signal)}async function ah(t,e,n){let r=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.delete(r,n?.signal)}async function sh(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 lh(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 dh(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function ch(t,e,n,r,i){let o=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(o,i?.signal)}async function uh(t,e,n,r,i){let o=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(o,i?.signal)}async function mh(t,e,n){let r=`/v1/voice/sessions/${v(e)}`;return t.client.delete(r,n?.signal)}async function ph(t,e,n,r){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(i,r?.signal)}async function gh(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 fh(t,e,n,r,i,o){let s=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function yh(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 hh(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function bh(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/currencies/${v(r)}`;return t.client.get(o,i?.signal)}async function vh(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 _h(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${v(e)}/${v(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function wh(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 Sh(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${v(e)}/${v(n)}/${v(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function kh(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 Rh(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 Ah(t,e,n,r,i,o){let s=`/v1/inventory/${v(e)}/${v(n)}/catalogs/${v(r)}/recipes/${v(i)}/availability`;return t.client.get(s,o?.signal)}async function xh(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${v(e)}/${v(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Ph(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 Th(t,e,n){let r=`/v1/events/${v(e)}`;return t.client.get(r,n?.signal)}async function Eh(t,e,n){let r=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Ih(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 Ch(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function Mh(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 Oh(t,e,n){let r=`/v1/game-room-templates/${v(e)}`;return t.client.get(r,n?.signal)}async function Gh(t,e,n){let r=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/room-args`;return t.client.get(r,n?.signal)}async function Lh(t,e,n,r){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(i,r?.signal)}async function Dh(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function fa(t,e,n){let r=`/v1/games/${v(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function Fh(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function $h(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function qh(t,e,n,r){let i=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/kick/${v(n)}`;return t.client.post(i,void 0,r?.signal)}async function Nh(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 jh(t,e,n,r){let i=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(i,r?.signal)}async function Bh(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${v(e)}/${v(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Uh(t,e,n,r){let i=`/v1/inventory/${v(e)}/${v(n)}/progressions`;return t.client.get(i,r?.signal)}async function Wh(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${v(e)}/${v(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Vh(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 Hh(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/${v(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Kh(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function Jh(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 zh(t,e,n,r,i,o){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/max`;return t.client.post(s,i,o?.signal)}async function Xh(t,e,n,r,i,o){let s=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Yh(t,e,n,r){let i=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/room-args`;return t.client.put(i,n,r?.signal)}async function Qh(t,e,n,r,i){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(o,r,i?.signal)}async function Zh(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function eb(t,e,n,r){let i=`/v1/games/${v(t.gameId())}/matches/${v(e)}/players/report`;return t.client.post(i,n,r?.signal)}async function tb(t,e,n,r,i,o){let s=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function nb(t,e,n,r,i,o){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/reset`;return t.client.post(s,i,o?.signal)}async function rb(t,e,n,r){let i=`/v1/games/${v(t.gameId())}/matches/${v(e)}/backfill`;return t.client.put(i,n,r?.signal)}async function ib(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/orders/simulate`;return t.client.post(o,r,i?.signal)}async function ob(t,e,n,r){let i=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}/transfer/${v(n)}`;return t.client.post(i,void 0,r?.signal)}async function ab(t,e,n,r){let i=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.patch(i,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var sb=1e4,lb=50,db=1e3,cb=65536-4*1024,iu=t=>typeof t=="number"?t:0,ub=t=>typeof t=="string"?t:"";function ou(){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 mb(t){return t?.retryable===true}function pb(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:iu(o.index),code:ub(o.code)}}):[];return {accepted:iu(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function au(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 su(t){let e=Math.max(1,Math.floor(t.maxQueue??db)),n={client:t.client,gameId:()=>t.gameId},r=[],i=0,o=null,s=false,a=null,l=0,d=0,c=false,u=false,p=b=>{t.log?.(b);},g=()=>{o!==null&&(t.clock.clearTimeout(o),o=null);},f=()=>Math.max(0,d-t.clock.now()),h=()=>{o!==null||s||a!==null||(o=t.clock.setTimeout(()=>{o=null,x().catch(()=>{});},Math.max(sb,f())));},k=()=>{let b=Math.min(r.length,100),S=128;for(let I=0;I<b;I+=1){let T=r[I];if(T===void 0)break;if(S+=JSON.stringify(au(T,0)).length+1,S>cb)return Math.max(1,I)}return b};async function x(b){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let S=P(b);a=S;try{return await S}finally{a===S&&(a=null),r.length>0&&h();}}async function P(b){g();let S=r.splice(0,k()),I=i;i=0;let T=Math.round(t.clock.now()),V={batch_id:ou(),sent_at_ms:T,events:S.map(q=>au(q,T))};try{let q=await fa(n,V,b===void 0?void 0:{signal:b}),B=pb(q,I);l=0,d=0;for(let E of B.rejected)p(`[gem] analytics: an event was refused (${E.code}). See the analytics_events section of your game config.`);return B}catch(q){if(mb(q)){for(r=[...S,...r],i+=I;r.length>e;)r.shift(),i+=1;l+=1,d=t.clock.now()+Mr(l,q);}else p(`[gem] analytics: ${S.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(q)}`);throw q}}return {track(b,S,I={}){if(s)return;if(typeof b!="string"||b===""){u||(u=true,p(`[gem] analytics: '${S}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(S.startsWith(to)){c||(c=true,p(`[gem] analytics: '${S}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let T={},V={};for(let[q,B]of Object.entries(I))typeof B=="string"?T[q]=B:typeof B=="number"&&Number.isFinite(B)&&(V[q]=B);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:ou(),playerId:b,name:S,atMs:t.clock.now(),dimensions:T,measures:V}),r.length>=lb&&a===null&&f()===0?x().catch(()=>{}):h();},flush:b=>x(b),get pending(){return r.length},dispose(){s=true,g(),r=[],i=0;}}}function lu(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().");Pt(r);let o=await t({player_id:n,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return xr(o)}}}function gb(t){let e={};for(let[n,r]of Object.entries(ya))if(typeof r=="function"){let i=r;e[n]=(...o)=>i(t,...o);}return e}function qt(t,e={}){let n=e.clock??ue,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let i=ga(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=gr({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new We({transport:o,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=gb({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,c=t.endMatch,u=t.log,p=su({client:s,clock:n,gameId:a.gameId,...typeof u=="function"?{log:f=>u.call(t,f)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(c===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 c.call(t);},setBackfill:async(f,h)=>{let k=await l.setMatchBackfill(a.matchId,{open:f.open,...f.seats===void 0?{}:{seats:f.seats}},h===void 0?{}:{signal:h});return {open:k.open,seats:k.seats??null}},reportPlayers:async(f,h)=>(await l.reportMatchPlayers(a.matchId,{players:f.map(x=>({player_id:x.playerId,state:x.state}))},h===void 0?{}:{signal:h})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new ze(l.invokeFunction),challenges:lu(l.listChallenges),...d===void 0?{}:{room:{get:f=>l.getGameRoomV2(d,f),args:async f=>{let h=await l.getGameRoomV2(d,f?.signal===void 0?{}:{signal:f.signal}),k=h.modified?h.body:void 0;if(k?.room_args==null||k.room_args_template==null)throw new M("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:k.room_args,room_args_template:k.room_args_template}}}},dispose:()=>{p.dispose(),i.dispose();}}}function mt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Nt(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function In(t){return typeof t=="string"?t:t.slice().buffer}function di(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 fb=5e3,du=3e4,cu=2e3,yb=1e4,hb=3,uu=1;async function mu(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let i=e.log===void 0?y=>console.info(y):e.log,o=y=>i?.(`[gem host] ${y}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,c=(y,C)=>{l&&(a=a.then(async()=>{if(!d)try{await C();}catch(L){o(`the bundle's ${y} handler threw: ${pt(L)}. Serving continues.`);}}));},u=true,p,g,f,h=y=>{if(!u)return;u=false,c("leave",()=>s.leave?.(r,{cause:y??"left"}));let C=g;C&&queueMicrotask(()=>C(y));},k={send(y,C){if(!u)return;let L=Nt(mt(C));c("message",()=>s.message?.(r,y,typeof y=="string",{reliable:L.reliable,ordered:L.ordered}));},onMessage(y){p=y;},onClose(y){g=y;},close(){h("closed");}},x=(y,C)=>{if(!u)return;let L=Nt(mt(C));queueMicrotask(()=>{u&&p?.(y,L);});},P=new Map,b=y=>{let C=[];for(let L of qe){let Z=y.channels[L];try{Z.binaryType="arraybuffer";}catch{}let we=Nt(L),qn=bt=>{let Ut=di(bt?.data);Ut!==null&&c("message",()=>s.message?.(y.playerId,Ut.data,Ut.isText,{reliable:we.reliable,ordered:we.ordered}));};Z.addEventListener("message",qn),C.push(()=>Z.removeEventListener("message",qn));}P.get(y.playerId)?.forEach(L=>L()),P.set(y.playerId,C);},S=y=>{P.get(y)?.forEach(C=>C()),P.delete(y);},I=new Set,T=new Map,V=(y,C,L)=>({playerNumber:y.assignedPeerId,transport:"webrtc_p2p",...C?{rejoin:true}:{},...L?{superseded:true}:{}}),q=y=>{let C=P.has(y.playerId),L=I.has(y.playerId);I.add(y.playerId),b(y),C&&c("leave",()=>s.leave?.(y.playerId,{cause:"superseded"})),c("join",()=>s.join?.(y.playerId,V(y,L,C)));},B=new Set,E=(y,C,L)=>{if(y===r){x(C,L);return}let Z=n.peer(y);if(Z===null){let we=T.get(y);if(we!==void 0&&e.clock.now()-we<cu)return;B.has(y)||(B.add(y),o(`send to '${y}' dropped: no such connected player`));return}Z.send(In(C),mt(L));},O={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:y=>e.tokens.subscribe(y),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(y=>y.playerId)??[],players(){let y=u?[r]:[];for(let C of n.peers)y.push(C.playerId);return y},profile(y){let C=e.room()?.members.find(L=>L.playerId===y);if(!(!C||C.displayName===void 0))return {displayName:rt.toPlain(C.displayName),...C.displayTag===void 0?{}:{displayTag:rt.toPlain(C.displayTag)},...C.discriminator===void 0?{}:{discriminator:C.discriminator}}},playerNumber(y){return y===r?uu:n.peer(y)?.assignedPeerId},send(y,C,L){E(y,C,L);},broadcast(y,C){let L=C?.except;u&&r!==L&&x(y,C);for(let Z of n.peers)Z.playerId!==L&&Z.send(In(y),mt(C));},async endMatch(){let y=await je();return y.answer!=="ok"&&o(y.cause),y.answer},kick(y,C){if(y===r){h(C??"kicked");return}n.kick(y).catch(L=>{o(`kick of '${y}' failed: ${pt(L)}`);});},log(y){o(y);},warn(y){o(`\u26A0 ${y}`);}},F=()=>{},N=new Promise(y=>{F=y;}),U=[],J=null,oe=async(y,C)=>{l=false;let L=a.then(async()=>{try{await s.shutdown(y);}catch(Z){o(`the bundle's shutdown threw: ${pt(Z)}`);}});a=L,await L,De();for(let Z of U.splice(0))Z();for(let Z of [...P.keys()])S(Z);h(C);},ge=(y,C)=>J||(J=(async()=>{await oe(C,y),n.close(),F();})(),J),X=()=>J||(J=(async()=>{await oe({reason:"signal"},"left"),await n.leave().catch(y=>o(`leaving the match failed: ${pt(y)}`)),F();})(),J),Ne=()=>J||(J=(async()=>{l=false;let y=await je();y.answer==="ok"?(await oe({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(o(`${y.cause}; leaving instead`),await oe({reason:"signal"},"left"),await n.leave().catch(C=>o(`leaving the match failed: ${pt(C)}`))),F();})(),J),ke=null,fe=()=>(ke??=qt(O,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),ke),je=async()=>{try{return await ol({client:fe().client,gameId:()=>O.gameId},O.matchId,{},{signal:AbortSignal.timeout(fb)}),{answer:"ok"}}catch(y){return y instanceof M&&(y.reason==="forbidden"||y.reason==="not_found")?{answer:y.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${y.reason})`}:{answer:"failed",cause:`ending the match failed: ${pt(y)}`}}},te=null,z=false,le=0,xe,Be=null,De=()=>{z=true,te!==null&&(e.clock.clearTimeout(te),te=null),Be?.(),Be=null;},yt=y=>{o(`heartbeats paused: ${y}; they resume when a fresh play token arrives`),Ee();let C=xe,L=false,Z=e.tokens.subscribe(we=>{L||z||we.token===C||Bt(we)||(L=true,Be?.(),Be=null,le=0,xe=void 0,Ee(),o("a fresh play token arrived; heartbeats resume"),te=e.clock.setTimeout(()=>{Ue();},0));});L?Z():Be=Z;},Ee=()=>{let y=ke;ke=null,y?.dispose();},Bt=y=>y.expiresAt*1e3<=e.clock.now(),Ue=async()=>{if(te=null,!z){try{await fe().client.post(`/v1/games/${encodeURIComponent(O.gameId)}/matches/${encodeURIComponent(O.matchId)}/heartbeat`,void 0,AbortSignal.timeout(yb)),le=0,xe=void 0;}catch(y){if(y instanceof M&&(y.reason==="forbidden"||y.reason==="not_found")){o(`the platform no longer holds this match under this host (${y.reason}); heartbeats stop`),De();return}if(bb(y)){if(z)return;le+=1;let C=e.tokens.current(),L=C===void 0?"this host holds no play token":Bt(C)?"this host's play token has expired":C.token===xe?"the platform refused this host's play token again":le>=hb?`the platform refused this host's play token ${le} times in a row`:null;if(xe=C?.token,L!==null){yt(L);return}}else le=0,xe=void 0;o(`heartbeat failed: ${pt(y)}`);}z||(te=e.clock.setTimeout(()=>{Ue();},du));}},vi=()=>{z||te!==null||(te=e.clock.setTimeout(()=>{Ue();},du));};{let y=F;F=()=>{De(),ke?.dispose(),ke=null,y();};}let ht=Promise.resolve().then(()=>s.init(O));a=ht.then(()=>{},()=>{}),c("join",()=>s.join?.(r,{playerNumber:uu,transport:"loopback"})),U.push(n.on("peerJoined",q)),U.push(n.on("peerLeft",(y,C)=>{S(y);let L=e.clock.now();for(let[Z,we]of T)L-we>=cu&&T.delete(Z);T.set(y,L),B.delete(y),c("leave",()=>s.leave?.(y,{cause:C}));})),U.push(n.on("error",y=>{o(`\u26A0 session error: ${y.message}`);})),U.push(n.on("matchEnded",y=>{J||ha(f,y),ge("match ended",{reason:"match_ended",platform_reason:y});})),U.push(n.on("hostChanged",y=>{y!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let y of n.peers)q(y);try{await ht,vi();}catch(y){l=false,De(),d=true;for(let C of U.splice(0))C();for(let C of [...P.keys()])S(C);throw n.leave().catch(()=>{}),F(),y}return {matchId:n.matchId,localLink:k,onMatchEnded(y){f=y;},end:Ne,leave:X,stop:y=>ge(y,{reason:"stopped"}),done:N}}function ha(t,e){try{t?.(e);}catch{}}function bb(t){return t instanceof M&&t.status===401||ne.isAuthError(t)}function pt(t){return t instanceof Error?t.message:String(t)}function ba(t,e){let n=async()=>{throw new w("misconfigured",`this seat is \`${t}\`, not the match's authority: `+(t==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:t,matchId:e,end:n,leave:n,stop:async()=>{}}}function pu(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,i=new Map,o=async a=>{r.isHost&&!pa(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...a.signal===void 0?{}:{signal:a.signal}});let l={...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},s=a=>({...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0?{}:{clusterTargetId:a.clusterTargetId}});return {async serve(a,l={}){let d=await o(l);if(d.protocol!==ct)return ba("dedicated",d.matchId);let c=t.p2p.session?.(d.matchId)??null;if(c===null&&!r.isHost||c!==null&&!c.isHost)return ba("peer",d.matchId);let u=t.identity();if(u===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=c??await t.p2p.connect(s(l)),g=await mu(a,{session:p,clock:t.clock,gameId:u.gameId,channel:u.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:u.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return i.set(d.matchId,g),g.done.then(()=>{i.get(d.matchId)===g&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(a={}){let l=await o(a),d=a.onMatchEnded;if(l.protocol===ct){let g=i.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Sb(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let f=await Sn(),h=async()=>t.p2p.connect({...s(a),certificate:f}),k=await h(),x=Rb(k,h,d,P=>{r.notifyMatchDisconnected(P).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(k.matchId,{redial:x.redial,abandon:x.abandon}),x.onClosed(()=>{e.get(k.matchId)?.abandon===x.abandon&&e.delete(k.matchId);})),x}let c=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),u=await c(),p=kb(u,c,r,n);return n&&(e.set(u.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(u.matchId)?.abandon===p.abandon&&e.delete(u.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var gu="link_closed",vb="host_unreachable",_b=new Set(["failed","closed"]);function wb(t){return _b.has(t)?gu:vb}function Sb(t,e,n){let r=e.localLink;e.onMatchEnded(n);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:t,protocol:"loopback",get state(){return i},send:(s,a)=>r.send(s,a),onMessage:s=>r.onMessage(s),onClose:s=>{o=s,r.onClose(a=>{i="closed",o?.(a);});},close:()=>r.close()}}function kb(t,e,n,r){let i=t.matchId,o=t,s="connected",a,l,d=[],c=false,u=false,p=f=>{if(s!=="closed"){s="closed";for(let h of d.splice(0))h();l?.(f);}},g=f=>{f.link.onMessage((h,k)=>a?.(h,k)),f.link.onClose(h=>{if(f!==o||s==="closed")return;if(c||!r){p(h);return}let k=n.matchSession;if(k.phase==="suspended"&&k.matchId===i){s="suspended";return}p(h);});};return g(t),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return s},send(f,h){s==="connected"&&o.link.send(f,h);},onMessage(f){a=f;},onClose(f){l=f;},close(){if(s!=="closed"){if(c=true,s==="suspended"){p("closed");return}o.close(),p("closed");}},async redial(f){if(s==="closed"||c)return "closed";if(u)return "connected";u=true;let h;try{h=await e(f===void 0?{}:{deadlineAt:f});}finally{u=false;}return c||s==="closed"?(h.close(),"closed"):(o=h,g(h),s="connected",n.notifyMatchConnected(i),"connected")},abandon(f){s!=="closed"&&(s==="connected"&&o.close(),p(f));},onClosed(f){s==="closed"?f():d.push(f);}}}function Rb(t,e,n,r,i,o=false){let s=t.matchId,a=t,l,d,c=[],u=[],p=[],g=false,f=false,h=false,k=false,x="connected",P=E=>{if(g)return;g=true,x="closed";for(let F of c.splice(0))F();for(let F of u.splice(0))F();for(let F of p.splice(0))F();let O=d;O&&queueMicrotask(()=>O(E));},b=E=>{for(let O of c.splice(0))O();for(let O of qe){let F=E.channels[O];try{F.binaryType="arraybuffer";}catch{}let N=Nt(O),U=J=>{let oe=di(J?.data);oe!==null&&l?.(oe.data,N);};F.addEventListener("message",U),c.push(()=>F.removeEventListener("message",U));}},S=()=>a.peer(a.hostPlayerId),I=E=>{if(!(g||a.isHost)&&x!=="suspended"){if(r?.(E),o){x="suspended";return}P(E);}},T=E=>{for(let O of qe){let F=E.channels[O];if(typeof F.addEventListener!="function")continue;let N=()=>{S()===E&&I(gu);};F.addEventListener("close",N),c.push(()=>F.removeEventListener?.("close",N));}},V=E=>{b(E),T(E),!g&&(x="connected",i?.());},q=E=>{for(let O of u.splice(0))O();u.push(E.on("migrating",()=>{k=true;})),u.push(E.on("hostChanged",O=>{if(k=false,O===E.playerId){P("host_migrated_here");return}let F=S();F!==null&&V(F);})),u.push(E.on("peerJoined",O=>{O.playerId===E.hostPlayerId&&V(O);})),u.push(E.on("matchEnded",O=>{g||ha(n,O),P(O);})),u.push(E.on("peerLeft",(O,F)=>{O===E.hostPlayerId&&I(wb(F));}));};q(a);let B=S();return B!==null&&V(B),{matchId:s,protocol:"p2p",get state(){return x},send(E,O){x==="connected"&&S()?.send(In(E),mt(O));},onMessage(E){l=E;},onClose(E){d=E;},close(){f=true,P("closed"),a.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||h)return "connected";if(k)throw new D("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");h=true;let E;try{for(let F of c.splice(0))F();for(let F of u.splice(0))F();a.close(),E=await e();}finally{h=false;}if(g)return f?E.leave().catch(()=>{}):E.close(),"closed";a=E,q(a);let O=S();if(O===null)throw a.close(),new D("connection_failed","this peer rejoined the match but the host never answered with a link");return V(O),"connected"},abandon(E){P(E);},onClosed(E){g?E():p.push(E);}}}function fu(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},s=l=>{n.delete(r)&&(t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>s(void 0),t.timeoutMs??2e3);let a=false;try{a=t.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){n.get(r)?.(i);}}}var Ab=12e4;function gt(t,e){return {outcome:t,reason:e}}function yu(t){let e=false,n=new Map,r=(i,o,s,a)=>{if(!t.bridge.parentSupports(i))return Promise.resolve(gt("unavailable","error"));if(e)return Promise.resolve(gt("declined","busy"));let l=`purchase-${_e()}`;return new Promise(d=>{let c={},u=g=>{n.delete(l)&&(e=false,t.clock.clearTimeout(c.timer),d(g));};e=true,n.set(l,{finish:u,check:s,label:a}),c.timer=t.clock.setTimeout(()=>u(gt("unavailable","error")),t.timeoutMs??Ab);let p=false;try{p=o(l);}catch{}p||u(gt("unavailable","error"));})};return {api:{request(i){return r("purchases",o=>t.bridge.requestPurchase(o,i.kind,i.targetId,i.currencySlug,i.quantity,i.catalogId),o=>o===void 0?null:t.confirm(o),o=>`purchase ${JSON.stringify(o)}`)}},requestAvatar3d(i){return r("avatar3dPurchases",o=>t.bridge.requestAvatar3dPurchase(o,i.itemId,i.currencySlug),()=>t.confirmAvatar3d(i.itemId),()=>`3D avatar ${JSON.stringify(i.itemId)}`)},settle(i){let o=i.outcome==="ok"||i.outcome==="declined"?i.outcome:"unavailable",s=n.get(i.requestId);if(s===void 0){t.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(i.requestId));return}let{finish:a}=s;if(o!=="ok"){a(gt(o,kl(i.reason)));return}let l=i.purchaseId,d;try{d=s.check(l);}catch{d=Promise.resolve("unknown");}if(d===null){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),a(gt("unavailable","error"));return}(async()=>{let c;try{c=await d;}catch{c="unknown";}if(c==="granted"){a(l===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:l});return}c==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(gt("unavailable","error"));})();}}}async function hu(t,e){try{return (await js(t,e)).granted?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}var xb="small_human",bu=/^[a-z][a-z0-9_]{0,31}$/,vu=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Pb=8;function va(t){if(t===null)return [];if(t.avatars3d!==void 0)return t.avatars3d;let{avatar3dId:e,avatar3dModelUrl:n,avatar3dIconUrl:r}=t;return e===void 0||n===void 0||r===void 0?[]:[{family:xb,id:e,modelUrl:n,iconUrl:r}]}function Tb(t,e){return t.length===e.length&&t.every((n,r)=>{let i=e[r];return n.family===i.family&&n.id===i.id&&n.modelUrl===i.modelUrl})}function Eb(t){let e=t??{},n=typeof e.item_id=="string"&&vu.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&bu.test(e.family)?e.family:void 0,i=typeof e.slug=="string"&&e.slug!==""?e.slug:void 0,o=typeof e.display_name=="string"&&e.display_name!==""?e.display_name:void 0,s=typeof e.description=="string"&&e.description!==""?e.description:void 0,a=Tt(e.icon_url),l=Tt(e.model_url),d=[];for(let c of Array.isArray(e.prices)?e.prices:[]){let u=c??{};typeof u.currency_slug=="string"&&u.currency_slug!==""&&typeof u.price=="number"&&Number.isSafeInteger(u.price)&&u.price>0&&d.push({currencySlug:u.currency_slug,price:u.price});}if(!(n===void 0||r===void 0||i===void 0||o===void 0||a===void 0||l===void 0||d.length===0))return {itemId:n,slug:i,family:r,displayName:o,...s===void 0?{}:{description:s},iconUrl:a,modelUrl:l,prices:d}}function Ib(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&bu.test(n)&&!e.includes(n)&&e.push(n),e.length===Pb)break;return e}function _u(t){let e=new Set,n=va(t.player()),r=i=>{t.log?.(`[gem] an avatars3d onChange listener threw: ${i instanceof Error?i.message:String(i)}`);};return t.subscribe(i=>{let o=va(i);if(!Tb(n,o)){n=o;for(let s of [...e])try{s(o);}catch(a){r(a);}}}),{async families(){return Ib(await t.configFamilies())},worn(i){let o=va(t.player());if(i!==void 0)return o.find(l=>l.family===i);let a=t.player()?.avatar3dId;return (a===void 0?void 0:o.find(l=>l.id===a))??o[0]},async offers(){let i=await t.readOffers(),o=[];for(let s of Array.isArray(i?.offers)?i.offers:[]){let a=Eb(s);a!==void 0&&o.push(a);}return o},purchase(i){let o=i?.itemId,s=i?.currencySlug;return typeof o!="string"||!vu.test(o)?Promise.resolve({outcome:"declined",reason:"not_purchasable"}):typeof s!="string"||s===""?Promise.resolve({outcome:"declined",reason:"unknown_currency"}):t.purchase({itemId:o,currencySlug:s})},onChange(i){return e.add(i),()=>{e.delete(i);}}}}async function wu(t,e){try{return (await ws(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}function Su(t){return Ls(t)}var Cb=6e5;function ku(t){let e=null,n=new Map;return {api:{requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${_e()}`;return e=new Promise(i=>{let o={},s=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>{s({outcome:"unavailable"});},t.timeoutMs??Cb);let a=false;try{a=t.bridge.requestSignIn(r);}catch{}a||s({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var Mb=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),Ob=["utm_"];function Ru(t){return Mb.has(t)||Ob.some(e=>t.startsWith(e))}var Au=16,xu=512,Gb=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Lb=/[\p{Cc}\p{Cf}]/u,Db=/\p{Cs}/u,Ge="[gem] gem.share.request:";function Pu(t){let{frame:e,log:n}=t,r=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,o=s=>{n!==null&&(n===void 0?console.warn(s):n(s));};return {get available(){return i()!==null},request(s){let a=i();if(a===null)throw new Error(`${Ge} the arcade does not handle share here \u2014 check gem.share.available first`);if(s!==void 0&&(typeof s!="object"||s===null))throw new TypeError(`${Ge} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!Fb(l))throw new TypeError(`${Ge} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>Au)throw new TypeError(`${Ge} at most ${Au} params; got ${d.length}`);let c=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!Gb.test(u))throw new TypeError(`${Ge} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Ru(u))throw new TypeError(`${Ge} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Ge} param ${g}: values must be strings`);if(p.length>xu)throw new TypeError(`${Ge} param ${g}: a value is at most ${xu} characters`);if(Lb.test(p))throw new TypeError(`${Ge} param ${g}: control and format characters are not allowed`);if(Db.test(p))throw new TypeError(`${Ge} param ${g}: a value must be well-formed text`);c.push({key:u,value:p});}!a.requestShare(c)&&!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 Fb(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Cn=3e4,_a=12e4;function Mn(t,e,n){return t.held?Promise.resolve(n):(t.held=true,e().then(r=>(t.held=false,r)))}function ce(t,e,n){return {outcome:t,reason:e,...n}}function Ze(t){let e=t.outcome==="ok"||t.outcome==="declined"?t.outcome:"unavailable";return typeof t.reason=="string"?{outcome:e,reason:t.reason}:{outcome:e}}function Tu(t){let e=new Map;return {ask(n,r,i,o){let s=`arcade-${_e()}`;return new Promise(a=>{let l={},d=u=>{e.delete(s)&&("timer"in l&&t.clearTimeout(l.timer),a(i(u)));};e.set(s,{expect:n,finish:d}),o!==void 0&&(l.timer=t.setTimeout(()=>d(null),o));let c=false;try{c=r(s);}catch{}c||d(null);})},settle(n){let r=e.get(n.requestId);return r===void 0||r.expect!==n.type?false:(r.finish(n),true)},abandon(){for(let n of [...e.values()])n.finish(null);}}}var $b=12,qb=24,wa=Object.freeze({games:Object.freeze([])});function Nb(t){let e=(n,r)=>he(n,`GameCard.${r}`);return Object.freeze({gameId:t.gameId,...t.slug===void 0?{}:{slug:t.slug},name:e(t.untrusted.name,"name"),tagline:e(t.untrusted.tagline,"tagline"),shortDescription:e(t.untrusted.shortDescription,"shortDescription"),tags:Object.freeze(t.untrusted.tags.map(n=>e(n,"tags"))),iconUrl:t.iconUrl,capsuleLandscapeUrl:t.capsuleLandscapeUrl,capsulePortraitUrl:t.capsulePortraitUrl,...t.previewVideoUrl===void 0?{}:{previewVideoUrl:t.previewVideoUrl},...t.previewPosterUrl===void 0?{}:{previewPosterUrl:t.previewPosterUrl}})}function ci(t){return ce("unavailable","error",t)}function Eu(t){let{bridge:e,asker:n,acting:r}=t,i=a=>e.currentState==="connected"&&e.parentSupports(a),o=new Map,s=(a,l)=>{let d=o.get(a);if(d!==void 0)return d;let c=l().then(u=>(o.delete(a),u));return o.set(a,c),c};return {get available(){return {appLinks:i("appLinks"),openGame:i("openGame")}},appLinks(){return e.parentSupports("appLinks")?s("appLinks",()=>n.ask("gem.appLinksResult",a=>e.requestArcade({type:"gem.requestAppLinks",requestId:a}),a=>{if(a===null)return ci({});let l=a;return {...Ze(a),...l.arcade===void 0?{}:{arcade:{store:l.arcade.store}},...l.game===void 0?{}:{game:{store:l.game.store}}}},Cn)):Promise.resolve(ce("unavailable","unsupported",{}))},openApp(a){return e.parentSupports("appLinks")?a!=="arcade"&&a!=="game"?Promise.resolve(ce("unavailable","invalid_argument",{})):Mn(r,()=>n.ask("gem.openAppResult",l=>e.requestArcade({type:"gem.requestOpenApp",requestId:l,target:a}),l=>l===null?ci({}):Ze(l),_a),ce("declined","busy",{})):Promise.resolve(ce("unavailable","unsupported",{}))},openGame(a){if(!e.parentSupports("openGame"))return Promise.resolve(ce("unavailable","unsupported",{}));let l=typeof a=="string"?a.toLowerCase():"";return vl({gem:j,type:"gem.requestOpenGame",requestId:"-",ref:l})!==null?Promise.resolve(ce("unavailable","invalid_argument",{})):Mn(r,()=>n.ask("gem.openGameResult",c=>e.requestArcade({type:"gem.requestOpenGame",requestId:c,ref:l}),c=>c===null?ci({}):Ze(c),_a),ce("declined","busy",{}))},similarGames(a){if(!e.parentSupports("openGame"))return Promise.resolve(ce("unavailable","unsupported",wa));let l=a?.limit;return l!==void 0&&(typeof l!="number"||!Number.isInteger(l)||l<1||l>qb)?Promise.resolve(ce("unavailable","invalid_argument",wa)):s(`similar:${l??$b}`,()=>n.ask("gem.similarGamesResult",d=>e.requestArcade({type:"gem.requestSimilarGames",requestId:d,...l===void 0?{}:{limit:l}}),d=>{if(d===null)return ci(wa);let c=Ze(d),u=d,p=c.outcome==="ok"?Object.freeze(u.games.map(Nb)):[];return {...c,games:p}},Cn))}}}var jb=64,Iu=Object.freeze({offers:Object.freeze([])});function Bb(t){return Object.freeze({skuId:t.skuId,kind:t.kind,name:t.name,description:t.description,...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl},priceDisplay:t.priceDisplay,...t.grant===void 0?{}:{grant:Object.freeze({currency:t.grant.currency,amount:t.grant.amount})}})}function Cu(t){let{bridge:e,asker:n,acting:r}=t,i=new Set,o=null;function s(a,l,d,c){return e.parentSupports(a)?typeof c!="string"||c.length===0||c.length>jb?Promise.resolve(ce("unavailable","invalid_argument",{})):Mn(r,()=>n.ask(d,u=>e.requestArcade({type:l,requestId:u,skuId:c}),u=>u===null?ce("unavailable","error",{}):Ze(u)),ce("declined","busy",{})):Promise.resolve(ce("unavailable","unsupported",{}))}return {api:{get available(){return e.currentState==="connected"&&e.parentSupports("store")},get showOfferAvailable(){return e.currentState==="connected"&&e.parentSupports("storeOfferSheet")},offers(){return e.parentSupports("store")?(o!==null||(o=n.ask("gem.storeOffersResult",a=>e.requestArcade({type:"gem.requestStoreOffers",requestId:a}),a=>{if(a===null)return ce("unavailable","error",Iu);let l=Ze(a),d=a,c=l.outcome==="ok"?Object.freeze(d.offers.map(Bb)):[];return {...l,offers:c}},Cn).then(a=>(o=null,a))),o):Promise.resolve(ce("unavailable","unsupported",Iu))},purchase(a){return s("store","gem.requestStorePurchase","gem.storePurchaseResult",a)},showOffer(a){return s("storeOfferSheet","gem.requestStoreOfferSheet","gem.storeOfferSheetResult",a)},onSettled(a){return i.add(a),()=>{i.delete(a);}}},settled(a){let l=Object.freeze({skuId:a.skuId});for(let d of [...i])try{d(l);}catch(c){t.onListenerError?.(c);}}}}var Fu="https://gemarcade.com/branding/manifest.json",Ub=1,Mu=256*1024,Wb=256,Vb=64,Hb=256,Ou=8e3,Kb=6e4,Jb=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Gu={GEMS:"gems-mark",ARCADE_TICKETS:"ticket-mark"},Lu=Object.freeze({outcome:"unavailable"}),Du=Object.freeze({outcome:"not_found"});function ft(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function mi(t){return typeof t=="string"&&t!==""&&t.length<=Hb}function zb(t,e){if(!mi(t))return;let n;try{n=new URL(t,e);}catch{return}let r=Tt(n.href);if(r!==void 0)return n.origin===new URL(e).origin?r:zi(r)}function Xb(t,e){let n=t??{},r=zb(n.url,e);if(!(r===void 0||!mi(n.type))&&!(typeof n.bytes!="number"||!(n.bytes>=0))&&!(n.theme!==void 0&&n.theme!=="light"&&n.theme!=="dark"))return Object.freeze({url:r,type:n.type,bytes:n.bytes,...ft(n.width)?{width:n.width}:{},...ft(n.height)?{height:n.height}:{},...ft(n.size)?{size:n.size}:{},...ft(n.density)?{density:n.density}:{},...n.vector===true?{vector:true}:{},...n.theme===void 0?{}:{theme:n.theme}})}function Yb(t,e=Fu){let n;try{n=JSON.parse(t);}catch{return null}let r=n??{};if(r.format!==Ub||!Array.isArray(r.assets))return null;let i=[],o=new Set;for(let s of r.assets.slice(0,Wb)){let a=s??{};if(!mi(a.id)||!Jb.test(a.id)||o.has(a.id)||!mi(a.kind)||!Array.isArray(a.variants))continue;let l=[];for(let d of a.variants.slice(0,Vb)){let c=Xb(d,e);c!==void 0&&l.push(c);}l.length!==0&&(o.add(a.id),i.push(Object.freeze({id:a.id,kind:a.kind,variants:Object.freeze(l)})));}return Object.freeze(i)}function ui(t){let e;for(let n of t)(e===void 0||(n.width??0)>(e.width??0))&&(e=n);return e}function Qb(t,e,n){let r=t.find(l=>l.vector===true),i=t.filter(l=>l.size===void 0);if(e===void 0)return r??ui(i)??ui(t);let o=t.filter(l=>l.size===e);if(o.length>0){let l=c=>c.density??1,d=o.filter(c=>l(c)>=n);return d.length>0?d.reduce((c,u)=>l(u)<l(c)?u:c):o.reduce((c,u)=>l(u)>l(c)?u:c)}if(r!==void 0)return r;let s=i.filter(l=>(l.width??0)>=e*n);return (s.length>0?s.reduce((l,d)=>(d.width??0)<(l.width??0)?d:l):void 0)??ui(i)??ui(t)}function Zb(t,e){let n=e.theme===void 0?[]:t.variants.filter(a=>a.theme===e.theme),r=t.variants.filter(a=>a.theme===void 0),i=[n,r].filter(a=>a.length>0);if(t.kind!=="image")return i[0]?.[0];let s=(e.size===void 0?void 0:i.find(a=>a.some(l=>l.size===e.size)))??i[0];return s&&Qb(s,e.size,e.density)}function ev(t,e){if(e!==void 0){if(e===null||typeof e!="object")throw new TypeError(`[gem] branding.${t}: options must be an object`);if(e.size!==void 0&&!ft(e.size))throw new RangeError(`[gem] branding.${t}: size must be a positive number of CSS px`);if(e.density!==void 0&&!ft(e.density))throw new RangeError(`[gem] branding.${t}: density must be a positive number`);if(e.theme!==void 0&&e.theme!=="light"&&e.theme!=="dark")throw new TypeError(`[gem] branding.${t}: theme must be 'light' or 'dark'`)}}function $u(t){let e=t.manifestUrl??Fu,n=null,r=null,i=-1/0,o=false,s=c=>(i=t.clock.now(),o||(o=true,t.log?.(`[gem] gem.branding could not read the platform's branding (${c}), so every lookup answers 'unavailable' and your bundled fallback shows. If your page sets a Content-Security-Policy, allow ${new URL(e).origin} in connect-src and img-src.`)),null),a=async()=>{if(t.fetch===null)return s("this page has no fetch");let c=t.fetch,u=typeof AbortController=="function"?new AbortController:null,p,g=new Promise(h=>{p=t.clock.setTimeout(()=>{u?.abort(),h(s(`no answer in ${Ou} ms`));},Ou);}),f=(async()=>{let h=await c(e,{credentials:"omit",redirect:"error",...u?{signal:u.signal}:{}});if(!h.ok)return s("the manifest answered an error");if(Number(h.headers.get("content-length"))>Mu)return s("the manifest is too large");let k=await h.text();return k.length>Mu?s("the manifest is too large"):Yb(k,e)??s("the manifest is not format 1 JSON")})().catch(()=>s("the request failed"));try{return await Promise.race([f,g])}finally{t.clock.clearTimeout(p);}},l=()=>n!==null?Promise.resolve(n):r!==null?r:t.clock.now()-i<Kb?Promise.resolve(null):(r=a().then(c=>(r=null,c!==null&&(n=c),c)),r),d=async(c,u,p,g)=>{ev(c,g);let f=await l();if(f===null)return Lu;let h=f.find(P=>P.id===u&&P.kind===p);if(h===void 0)return Du;let k=t.devicePixelRatio(),x=Zb(h,{...g?.size===void 0?{}:{size:g.size},density:g?.density??(ft(k)?k:1),...g?.theme===void 0?{}:{theme:g.theme}});return x===void 0?Du:Object.freeze({outcome:"ok",url:x.url,variant:x,asset:h})};return Object.freeze({get:async(c,u)=>{if(typeof c!="string"||c==="")throw new TypeError("[gem] branding.get: id must be a non-empty string");if(u===null||typeof u!="object"||typeof u.kind!="string")throw new TypeError("[gem] branding.get: options.kind must be a string, such as 'image'");return d("get",c,u.kind,u)},logo:c=>d("logo","gem-logo","image",c),wordmark:c=>d("wordmark","gem-wordmark","image",c),currencyMark:async(c,u)=>{let p=Object.prototype.hasOwnProperty.call(Gu,c)?Gu[c]:void 0;if(p===void 0)throw new TypeError("[gem] branding.currencyMark: currency must be 'GEMS' or 'ARCADE_TICKETS', not "+JSON.stringify(String(c).slice(0,40)));return d("currencyMark",p,"image",u)},trophy:c=>d("trophy","trophy-mark","image",c),list:async()=>{let c=await l();return c===null?Lu:Object.freeze({outcome:"ok",assets:c})}})}var iv="(any-pointer: coarse)";function ov(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 qu(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?c=>matchMedia(c):void 0},i=r.navigator,o,s=new Set,a=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia(iv),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(c,u)=>{s.has(c)||(s.add(c),n!==null&&(n===void 0?console.warn(u):n(u)));};return {get available(){return a()||l()},vibrate(c){let u=a();if(!u&&!l())return false;let p=ov(c);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(u)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 jt=Math.PI/180,Le=Object.freeze({touch:Object.freeze({yaw:1*jt,pitch:.66*jt}),mouse:Object.freeze({yaw:.5*jt,pitch:.5*.77*jt}),stick:Object.freeze({yaw:240*jt,pitch:240*.77*jt}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Sa="[gem.controls]",ka=Object.freeze({yaw:0,pitch:0}),pi=t=>Number.isFinite(t)?t:0,Nu=(t,e)=>({yaw:t+0,pitch:e+0});function ju(t){let e=pi(t),n=(Math.abs(e)-Le.stickDeadzone)/(1-Le.stickDeadzone),r=Le.stickCurve,i=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,i))+0}function av(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Le.touchPitchMin)+Le.touchPitchMin}function Bu(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${Sa} ${e} takes an options object`);let n=t;for(let r of ["sensitivity","gamepadSensitivity"]){let i=n[r];if(i!==void 0&&!(typeof i=="number"&&Number.isFinite(i)&&i>0))throw new TypeError(`${Sa} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(i)}`)}if(n.invertY!==void 0&&typeof n.invertY!="boolean")throw new TypeError(`${Sa} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function sv(t,e){let n=Bu(e,"look()"),r=n.sensitivity,i=n.gamepadSensitivity,o=n.invertY,s=a=>o??a?.invertLookY??false;return {fromPointer(a,l,d,c){let u=pi(a),p=pi(l);if(u===0&&p===0)return ka;let g=t(),f=r??(g===null?void 0:g.lookSensitivity/100)??1,h=d==="touch"||d==="pen",k=h?Le.touch:Le.mouse,x=u*k.yaw*f,P=-p*k.pitch*f;return s(g)&&(P=-P),h&&c!==void 0&&Number.isFinite(c)&&P*c>0&&(P*=av(c)),Nu(x,P)},fromStick(a,l,d){let c=pi(d);if(c<=0)return ka;let u=ju(a),p=ju(l);if(u===0&&p===0)return ka;let g=t(),f=i??(g===null?void 0:g.gamepadLookSensitivity/100)??1,h=u*Le.stick.yaw*c*f,k=-p*Le.stick.pitch*c*f;return s(g)&&(k=-k),Nu(h,k)},set(a){let l=Bu(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(i=l.gamepadSensitivity),"invertY"in l&&(o=l.invertY);}}}function Uu(t){return {look:e=>sv(t.recommended,e),LOOK_BASE:Le}}var Wu=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),Vu=/^[A-Za-z0-9_-]{1,40}$/;function Ra(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function Hu(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function Ku(t,e,n,r){let i=a=>Number.parseFloat(a.toPrecision(12)),o=Math.min(n,Math.max(e,t)),s=i(e+Math.round((o-e)/r)*r);return s>n&&(s=i(s-r)),Math.min(n,Math.max(e,s))}function Ju(t,e){switch(t.kind){case "toggle":return typeof e=="boolean"?e:void 0;case "slider":{if(typeof e!="number"||!Number.isFinite(e))return;let n=t.min??0,r=t.max??100;return Ku(e,n,r,t.step??1)}case "choice":return typeof e=="string"&&(t.options??[]).some(n=>n.id===e)?e:void 0;default:return}}function zu(t,e=()=>{}){if(!Array.isArray(t))return null;let n=[],r=0;for(let i=0;i<t.length;i+=1){let o=t[i],s=`settings[${i}]`;if(n.length===8){e(`${s} and later were left out: at most 8 settings are shown.`);break}if(typeof o!="object"||o===null){e(`${s} was dropped: a setting is an object.`);continue}let a=o,l=a.id;if(typeof l!="string"||!Vu.test(l)){e(`${s} was dropped: its id must be 1 to 40 of A-Z a-z 0-9 _ -.`);continue}let d=`${s} (${JSON.stringify(l)})`;if(n.some(p=>p.id===l)){e(`${d} was dropped: an earlier setting has the same id.`);continue}let c=Hu(a.label);if(c===void 0){e(`${d} was dropped: its label is empty.`);continue}let u;switch(a.kind){case "toggle":{if(typeof a.value!="boolean"){e(`${d} was dropped: a toggle's value is true or false.`);continue}u={id:l,label:c,kind:"toggle",value:a.value},a.quick===true&&(r<2?(u.quick=true,r+=1):e(`${d} is not in the quick row: at most 2 toggles are, the first that ask.`));break}case "slider":{let p=a.min??0,g=a.max??100,f=a.step??1;if(!Ra(p)||!Ra(g)||!Ra(f)||p>=g||f<=0){e(`${d} was dropped: a slider needs finite numbers within \xB11000000 with min below max and a step above 0.`);continue}if(typeof a.value!="number"||!Number.isFinite(a.value)){e(`${d} was dropped: a slider's value is a number.`);continue}u={id:l,label:c,kind:"slider",value:Ku(a.value,p,g,f),min:p,max:g,step:f};break}case "choice":{let p=[];for(let g of Array.isArray(a.options)?a.options:[]){if(p.length===4)break;if(typeof g!="object"||g===null)continue;let f=g,h=Hu(f.label);typeof f.id!="string"||!Vu.test(f.id)||h===void 0||p.some(k=>k.id===f.id)||p.push({id:f.id,label:h});}if(p.length<2){e(`${d} was dropped: a choice needs 2 to 4 options, each with an id of 1 to 40 of A-Z a-z 0-9 _ - and a label.`);continue}if(typeof a.value!="string"||!p.some(g=>g.id===a.value)){e(`${d} was dropped: a choice's value is the id of one of its options.`);continue}u={id:l,label:c,kind:"choice",value:a.value,options:p};break}default:e(`${d} was dropped: its kind must be 'toggle', 'slider' or 'choice'.`);continue}a.icon!==void 0&&(Wu.includes(a.icon)?u.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${Wu.join(", ")}.`)),n.push(u);}return n}var lv=500;function Xu(t){let{clock:e}=t,n=null,r=null,i=-1/0,o=null,s=new Set,a=new Set,l=u=>{a.has(u)||(a.add(u),t.log!==null&&(t.log===void 0?console.warn(u):t.log(u)));},d=()=>{let u=t.frame();return u.currentState==="connected"&&u.parentSupports("gameSettings")},c=()=>{if(n===null||o!==null)return;let u=JSON.stringify(n);if(u===r)return;let p=i+lv-e.now();if(p>0){o=e.setTimeout(()=>{o=null,c();},p);return}t.frame().declareSettings(n)&&(r=u,i=e.now());};return {api:{declare(u){let p=zu(u,g=>l(`[gem] gem.settings.declare: ${g}`));return p===null?(l("[gem] gem.settings.declare did nothing: pass an array of settings, or [] for none."),false):(n=p,c(),d())},onChange(u){if(typeof u!="function")return ()=>{};let p=g=>u(g);return s.add(p),()=>{s.delete(p);}}},forgetSent(){r=null,i=-1/0;},flush:c,onSettingChange(u){let p=n?.findIndex(x=>x.id===u.id)??-1,g=n?.[p];if(n===null||g===void 0)return;let f=Ju(g,u.value);if(f===void 0)return;let h=JSON.stringify(n);n=n.map((x,P)=>P===p?{...x,value:f}:x),r===h&&(r=JSON.stringify(n));let k={id:g.id,value:f};for(let x of [...s])try{x(k);}catch(P){console.error("[gem] a gem.settings.onChange handler threw:",P);}}}}function Yu(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var dv=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Qu(t){if(typeof t!="string"||!dv.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function On(){return {declared:false,grantable:false,heldLimitReached:false}}function Zu(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Qu(n.resets_at),i=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...On(),...i};let o=n.remaining_today,s=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,a=n.next_eligible_at,l=Qu(a),d=n.held_limit_reached===true,c=a!=null,u=o!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!u&&!c&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var cv=18e4,Aa=32,uv=/^[a-z0-9_-]+$/,mv="rewarded_requires_user_gesture";function pv(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var gv=1e3;function fv(){let t=globalThis,e=t.navigator?.getGamepads,n=t.performance?.now;if(typeof e!="function"||typeof n!="function")return;let r=n.call(t.performance),i=e.call(t.navigator);for(let o=0;o<i.length;o+=1){let s=i[o]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=gv)return true}return false}var em=1e4;function yv(t){return t==="interstitial"||t==="rewarded"}function tm(t){return typeof t=="string"&&t!==""&&t.length<=Aa&&uv.test(t)}function hv(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function gi(t){return typeof t=="string"?JSON.stringify(t):typeof t}function nm(t){let e=false,n=new Map,r=new Map,i=new Set,o=d=>{try{t.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let c=t.log;if(c!==null)try{c===void 0?console.warn(`[gem] ${d}`):c(`[gem] ${d}`);}catch{}},l=d=>{let c=t.readAvailability;if(c===void 0)return Promise.resolve(On());let u=r.get(d);if(u!==void 0)return u;let p=new Promise(g=>{let f={},h=b=>f.done===true?false:(f.done=true,t.clock.clearTimeout(f.timer),g(b),true),k=(b,S)=>{!h(On())||i.has(b)||(i.add(b),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${S}. Said once.`));},x=b=>{k(hv(b),`the read failed (${b instanceof Error?b.message:gi(b)})`);},P;try{P=Promise.resolve(c(d,AbortSignal.timeout(em)));}catch(b){P=Promise.reject(b);}f.timer=t.clock.setTimeout(()=>{k("timeout","no answer within 10 s");},em),P.then(b=>{try{h(Zu(b,t.bridge.parentSupports("ads")));}catch(S){x(S);}},x);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return tm(d)?l(d):(o(`gem.ads.rewardedStatus(${gi(d)}) answered not grantable: a placement is 1..${String(Aa)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(On()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let c=d?.placement,u=d?.format;if(!tm(c)||!yv(u))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${gi(c)}, format ${gi(u)}. A placement is 1..${String(Aa)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});if(u==="rewarded"){let g;try{g=(t.userActivation??pv)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??fv)()===!0&&(g=!0);}catch{}if(g===false){let f=`${mv}: gem.ads.requestAd("${c}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return o(f),a(f),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${_e()}`;return new Promise(g=>{let f={},h=x=>{n.delete(p)&&(e=false,t.clock.clearTimeout(f.timer),g(x));};e=true,n.set(p,h),f.timer=t.clock.setTimeout(()=>{h({outcome:"unavailable"});},t.timeoutMs??cv);let k=false;try{k=t.bridge.requestAd(p,c,u);}catch{}k||h({outcome:"no_ad"});})}},settle(d){let c=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",u=n.get(d.requestId);if(u===void 0){t.onDropped?.(`gem.adResult (${c}) for an unknown requestId: `+JSON.stringify(d.requestId));return}u({outcome:c});}}}var rm=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),im=18e4,bv=1e4,vv=/^[a-z0-9_-]{1,32}$/;function xa(t){return typeof t=="string"?JSON.stringify(t):typeof t}var Gn=Object.freeze({shown:false});function om(t){let e=new Map,n,r=false,i=o=>{try{t.onDropped?.(o);}catch{}return Gn};return {api:{signal(o){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(Gn):(r=!0,Promise.resolve(i("moments_unsupported: gem.moments.signal answered shown: false without asking: this arcade does not do platform moments. Keep the call; it costs nothing. Said once.")));let s=o?.kind,a=o?.placement,l=o?.wall;if(!rm.includes(s)||a!==void 0&&(typeof a!="string"||!vv.test(a))||l!==void 0&&typeof l!="boolean")return Promise.resolve(i(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${xa(s)}, placement ${xa(a)}, wall ${xa(l)}. A kind is one of ${rm.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'; a wall, when given, is true or false. Answering shown: false.`));if(!t.bridge.readyCalled())return Promise.resolve(i(`moments_before_ready: gem.moments.signal({ kind: '${s}' }) before gem.frame.ready(): a moment is a break in play, and play has not started. Signal from the press that leaves a break, never on boot. Answering shown: false.`));if(e.size>0)return Promise.resolve(i(`moments_in_flight: gem.moments.signal({ kind: '${s}' }) while another moment is still waiting for its answer. Signal once per break, and await the answer before play resumes. Answering shown: false.`));let d=t.clock.now();if(n!==void 0&&d-n<bv)return Promise.resolve(i(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(d-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let c=`moment-${_e()}`;return new Promise(u=>{let p={},g=(h,k)=>{e.delete(c)&&(t.clock.clearTimeout(p.timer),k&&(n=t.clock.now()),u(h));};e.set(c,h=>g(h,!0)),p.timer=t.clock.setTimeout(()=>{e.has(c)&&(g(Gn,!0),i(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??im)/1e3)} s. Answering shown: false.`));},t.timeoutMs??im);let f=!1;try{f=t.bridge.signalMoment(c,s,a,l===!0?!0:void 0);}catch{}f||g(Gn,!1);})}catch{return Promise.resolve(Gn)}}},settle(o){let s=e.get(o.requestId);if(s===void 0){i(`gem.momentResult (shown: ${String(o.shown)}) for an unknown requestId: `+JSON.stringify(o.requestId));return}s({shown:o.shown===true});}}}var Pa=16384;function am(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:_v(e)}function _v(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 wv=1e4,Sv=5e3;function sm(t){let e=null,n=false,r=[],i=new Map,o=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=Sv){return n?Promise.resolve(e):new Promise(a=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{t.clock.clearTimeout(c),l(),a(e);},c=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=am(s);if(a===null)return t.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(a>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(s)),d=`device-settings-${_e()}`;return new Promise(c=>{let u={},p=f=>{i.delete(d)&&(t.clock.clearTimeout(u.timer),f==="stored"&&(e=l,n=true,o()),c(f));};i.set(d,p),u.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??wv);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,n=true,o();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=i.get(s.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var Ln=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 kv=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Rv(t){return typeof t=="string"&&kv.test(t)}function fi(t){if(t===null||Rv(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 lm(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Ea(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 yi(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(e.length===4)break;if(typeof n!="object"||n===null)continue;let{id:r,label:i}=n;typeof r!="string"||r.length===0||r.length>32||typeof i!="string"||i.trim().length===0||e.some(o=>o.id===r)||e.push({id:r,label:i.trim().slice(0,40)});}return e.length===0?{settings:false}:{settings:false,items:e}}function dm(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Av(t){let e=t.untrusted,n=he(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,i=r?he(r,"gem.player.displayTag"):void 0,o=t.discriminator||t.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=t.avatarIconUrl||t.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=t.avatarIconId,c=t.avatar3dId,u={displayName:n,displayHandle:i??n,badges:(t.badges??[]).map(h=>({itemId:h.itemId,iconUrl:h.iconUrl}))};t.playerId&&(u.playerId=t.playerId),s&&(u.discriminator=s),i&&(u.displayTag=i),a&&(u.avatarIconUrl=u.avatarUrl=a),d&&l.test(d)&&(u.avatarIconId=d),c&&l.test(c)&&(u.avatar3dId=c),t.avatar3dModelUrl&&(u.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(u.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(u.avatars3d=t.avatars3d.filter(h=>l.test(h.id)&&/^[a-z][a-z0-9_]*$/.test(h.family)).filter((h,k,x)=>x.findIndex(P=>P.family==h.family)==k).map(({family:h,id:k,modelUrl:x,iconUrl:P})=>({family:h,id:k,modelUrl:x,iconUrl:P})));let p=t.boost,g=(p?.multipliers??[]).map(h=>({currencyId:h.currencyId,currencySlug:h.currencySlug,multiplier:h.multiplierBp/1e4})),f=g.some(h=>h.multiplier>1);return u.boost=f&&p?.expiresInDays?{active:f,multipliers:g,expiresInDays:p.expiresInDays}:{active:f,multipliers:g},u}var xv=1e4,Pv=["appLinks","openGame","store","storeOfferSheet"],Ta=new WeakMap;function um(t,e){if(Ta.has(t))throw new Error("admitBuildEmbedders: already admitted");Ta.set(t,Object.freeze([...e]));}var Dn=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??ue,this.inbound=new Jt(this.clock),this.outbound=new Jt(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(a=>kt(a,e.origin))||or(e.origin,this.options.selfOrigin)||(Ta.get(this)??[]).some(a=>kt(a,e.origin))))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=ir["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!kt(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let s=_l(tr,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:j,type:"gem.error",code:"version_mismatch",message:`frame supports v${tr.min}..v${tr.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=s,o.onmessage=a=>this.receive(a.data,a.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:j,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:j,type:"gem.ready"});}settled(e=xv){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=o=>{this.clock.clearTimeout(i),n(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:j,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:j,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:j,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:j,type:"gem.exit"}:{gem:j,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:j,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:j,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:j,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:j,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:j,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:lm(e.origin.x),y:lm(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=fi(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:j,type:"gem.portraitBorders"}:{gem:j,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:j,type:"gem.walletDisplay",...Ea(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:j,type:"gem.menu",...yi(e)}):false}declareSettings(e){return this.gated("gameSettings")?this.send({gem:j,type:"gem.settingsDeclare",settings:e}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:j,type:"gem.gemCorner",corner:e}):false}requestShare(e){return this.gated("share")?this.send({gem:j,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:j,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:j,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:j,type:"gem.frameStats",fps:dm(e.fps,1e3),frameTimeP95Ms:dm(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:j,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:j,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:j,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:j,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,i,o,s){return this.send({gem:j,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}requestAvatar3dPurchase(e,n,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:j,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:j,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:j,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r,i){return this.send({gem:j,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r},...i===true?{wall:true}:{}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:j,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,i){return this.send({gem:j,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...i===void 0?{}:{params:i}})}requestArcade(e){return this.gated(rr(e.type))&&this.send({gem:j,...e})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(nr)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(nr)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(nr)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:j,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}gated(e){return this.state==="connected"&&this.parentSupports(e)}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let n=e.type;if(!this.outbound.allow(n))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${n}`),false;let r=ir[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||cm(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=ir[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=rr(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.settingChange":this.options.onSettingChange?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=n[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return cm(n.slice(1)),this.options.onScreenshot(d,l,(c,u)=>this.screenshotDenied(c,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(Av(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.ticketEvent":this.options.onTicketEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.momentResult":this.options.onMomentResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:if(Pv.includes(rr(r))){this.options.onArcadeAnswer?.(a);break}this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:j,type:"gem.screenshot.denied",reason:e,retryable:n});}};function cm(t){for(let e of t)try{e?.close?.();}catch{}}var mm="https://api.gemarcade.com";function Ia(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 Tv=new Set(["localhost","127.0.0.1","[::1]"]);function pm(t){let e=Ia(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!Tv.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 ym="/gem-embedders.json",hi=4096,gm=16,fm=5e3,Fn=Object.freeze({origins:Object.freeze([])});function et(t){return {origins:[],refused:`[gem] ${ym} was ignored: ${t}`}}function Ev(t){if(t.trim()==="")return Fn;let e;try{e=JSON.parse(t);}catch{return et("it is not JSON.")}if(e===null||typeof e!="object"||Array.isArray(e))return et('it must be an object, { "embedders": [...] }.');let n=e.embedders;if(n===void 0)return Fn;if(!Array.isArray(n))return et('"embedders" must be an array of origins.');if(n.length>gm)return et(`"embedders" has more than ${gm} entries.`);let r=n.filter(i=>typeof i!="string"||!St(i)||!i.toLowerCase().startsWith("https://")||Ke(new URL(i).hostname));if(r.length>0){let i=r.slice(0,3).map(o=>typeof o=="string"?JSON.stringify(o.slice(0,100)):String(o)).join(", ");return et(`${r.length===1?"an entry is":"entries are"} not an https origin off this machine (${i}${r.length>3?", \u2026":""}).`)}return {origins:Object.freeze([...new Set(n)])}}async function hm(t){let e=typeof AbortController=="function"?new AbortController:null,n,r=new Promise(o=>{n=t.clock.setTimeout(()=>{e?.abort(),o(et(`it took more than ${fm} ms to read.`));},fm);}),i=(async()=>{let o=await t.fetch(t.selfOrigin+ym,{credentials:"omit",redirect:"error",...e?{signal:e.signal}:{}});if(!o.ok||(o.headers.get("content-type")??"").toLowerCase().includes("text/html"))return Fn;if(Number(o.headers.get("content-length"))>hi)return et(`it is larger than ${hi} bytes.`);let a=await o.text();return a.length>hi?et(`it is larger than ${hi} bytes.`):Ev(a)})().catch(()=>Fn);try{return await Promise.race([i,r])}finally{t.clock.clearTimeout(n);}}function bm(t){if(typeof t!="string"||!St(t))return null;let e=t.slice(0,t.indexOf(":")).toLowerCase();return e==="https"||e==="http"?t:null}function vm(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function Iv(){let t=[["root",null],["hips","root"],["spine","hips"],["chest","spine"],["upper_chest","chest"],["neck","upper_chest"],["head","neck"],["head_socket","head"]];for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("shoulder"),"upper_chest"],[n("upper_arm"),n("shoulder")],[n("lower_arm"),n("upper_arm")],[n("hand"),n("lower_arm")],[n("hand_socket"),n("hand")]);for(let r of ["thumb","index","middle","ring","little"])for(let i=1;i<=3;i++)t.push([n(`${r}_${i}`),n(i===1?"hand":`${r}_${i-1}`)]);}for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("upper_leg"),"hips"],[n("lower_leg"),n("upper_leg")],[n("foot"),n("lower_leg")],[n("toes"),n("foot")]);}return t}var Cv=Object.freeze({small_human:vm([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:vm(Iv())});var Ov=Object.freeze(["https://gemarcade.com","https://developer.gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),Gv=mm,Lv=["top-left","top-right","bottom-left","bottom-right"],_m=8e3,bi=15e3,Dv=9e4,Fv=1/0,$v=8e3,qv=5e3,Nv=5e3;async function jv(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 $n(t){let e=null,n=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){n=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||n?Promise.resolve(e):new Promise(o=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{t.clearTimeout(l),s(),o(d);},l=t.setTimeout(()=>{s(),o(e);},i);r.push(a);})}}}function QT(t={}){let e=t.clock??ue,n=t.log===void 0?m=>console.info(m):t.log,r=t.baseUrl??void 0;if(r!=null){let m=Ia(r);if(m!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${m}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=typeof window>"u"?void 0:window.location?.search,o=ed(i),s=Td(i),a=zo();a.mark("sdk created");let l=()=>Fr(ae.gameVersion,t.clientVersion?.gameVersion),d=new ln({client:()=>vt,clock:e,gameId:()=>ae.identity?.gameId??null,playerId:()=>ae.identity?.playerId??null,awaitPlayerId:async()=>(await zn(bi)).playerId,environment:()=>{let m=l();return {sdk_version:Qa(),...m===null?{}:{game_version:m}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),c=pc(()=>{a.mark("engaged"),d.release(),$.reportEngaged();},typeof window>"u"?{}:window),u=m=>{if(m===false)return null;let A=m?.attempts??Fv,G=m?.budgetMs??Dv;return !(A>0)||!(G>0)?null:{attempts:A,budgetMs:G,maxDelayMs:m?.maxDelayMs??$v}},p=m=>{m.on("created",()=>{a.mark("room created");}),m.on("joined",()=>{a.mark("room joined");}),m.on("matchAllocationStarted",()=>{a.mark("allocation started");}),m.on("matchReady",()=>{a.mark("match ready");}),m.on("matchFailed",()=>{a.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new Ln;let g=t.allowedEmbedders;if(g!=null&&!Array.isArray(g))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let f=Array.from(g??[]),h=f.filter(m=>typeof m!="string"||!St(m));if(h.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${h.length===1?"an entry":"entries"} that ${h.length===1?"is":"are"} not an origin: ${h.map(m=>typeof m=="string"?JSON.stringify(m):String(m)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let k=Object.freeze([...new Set([...Ov,...f])]),x=$n(e),P=new Set,b=$n(e),S=false,I=$n(e),T=ad(n),V=$n(e),q=t.manageAudio===false?null:xc();t.selectableText!==true&&Pc(),t.onScreenshot===void 0&&yc(window);let B=null,E=null,O=null,F=()=>{B===null||B===E||$.reportMuted(B)&&(E=B);},N,U,J=-1/0,oe=null,ge=()=>{if(N===void 0||oe!==null||N===U)return;let m=J+1e3-e.now();if(m>0){oe=e.setTimeout(()=>{oe=null,ge();},m);return}$.showPortraitBorders(N)&&(U=N,J=e.now());},X=null,Ne=null,ke=()=>{if(X===null)return false;let m=JSON.stringify(Ea(X.visible,X.only));return m===Ne?$.parentSupports("walletDisplay"):$.setWalletVisible(X.visible,X)?(Ne=m,true):false},fe=null,je=null,te=()=>{if(fe===null)return false;let m=JSON.stringify(yi(fe.items));return m===je?$.parentSupports("gameMenu"):$.setMenu(fe.items)?(je=m,true):false},z=null,le=null,xe=Xu({frame:()=>$,clock:e,log:t.log}),Be=()=>z===null?false:z===le?$.parentSupports("gemCorner"):$.setGemCorner(z)?(le=z,true):false,De=Tc({report:m=>$.reportFrameStats(m)}),yt=false,Ee=Lc(()=>Ja,()=>yt),Bt=m=>{let A=yt&&!m,G=yt!==m;if(yt=m,A&&Ee.close(),!!G)try{t.onDevToolsPermissionChange?.(m);}catch(ee){n?.(`[gem] onDevToolsPermissionChange threw: ${ee instanceof Error?ee.message:String(ee)}`),queueMicrotask(()=>{throw ee});}},Ue=r??Gv,vi=r!==void 0,ht,y=m=>(n?.(`[gem] token refused: ${m}`),t.onError?.("internal",m),false),C=(m,A)=>{if(m===void 0)return A!==void 0?y("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let G=pm(m);return G!==null?y(`the embedder named an API root that cannot be used: ${G}. Its value is withheld here rather than written to logs.`):ht!==void 0&&ht!==m?y("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(ht=m,vi||(Ue=m),true)},L=window.location?.origin,Z=null,we=-1/0,qn=2e3,bt=new Set,Ut=m=>Z!==false?Promise.resolve(true):new Promise(A=>{let G=e.setTimeout(()=>{bt.delete(ee),A(false);},m),ee=()=>{e.clearTimeout(G),bt.delete(ee),A(true);};bt.add(ee);}),_i=()=>{},wi=null,Nn=Tu(e),$=new Dn({allowedEmbedders:k,...typeof L=="string"&&L!==""?{selfOrigin:L}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","ticketEvents","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","gemCorner","gameSettings","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges","appLinks","openGame","store","storeOfferSheet",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[]],onRefused:m=>{wi=m,t.onRefused?.(m);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:m=>{ae.onBridgeState(m),m!=="connected"&&Nn.abandon(),m!=="connected"&&De.setRequested(false),E=null,Ne=null,je=null,le=null,xe.forgetSent(),U=void 0,m==="refused"&&(console.error("[gem] this game refused the page that framed it"+(wi===null?"":` (${wi})`)+", 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."),_i()),m==="connected"&&(a.mark("bridge connected"),Rm(),F(),ge(),ke(),te(),Be(),xe.flush(),$.unbiddenLaunch&&!c.engaged&&d.hold(),d.startSession(),c.engaged&&$.reportEngaged()),t.onStateChange?.(m);},onPlayer:m=>{x.set(m);for(let A of [...P])A(m);t.onPlayer?.(m);},onPrefs:m=>{let A={reducedMotion:m.reducedMotion,muted:m.muted,locale:m.locale,showFrameStats:m.showFrameStats===true,music:m.music!==false,sounds:m.sounds!==false,recommended:m.recommended===void 0?null:Object.freeze({volume:m.recommended.volume,batterySaver:m.recommended.batterySaver,keyboardLayout:m.recommended.keyboardLayout,gamepadConfirm:m.recommended.gamepadConfirm,vibration:m.recommended.vibration,lookSensitivity:m.recommended.lookSensitivity??100,gamepadLookSensitivity:m.recommended.gamepadLookSensitivity??100,invertLookY:m.recommended.invertLookY??false,touchMovement:m.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:Yu(m.recommended.graphicsQuality,m.recommended.batterySaver),graphicsQualityAuto:m.recommended.graphicsQualityAuto??true,colorHelp:typeof m.recommended.colorHelp=="boolean"?m.recommended.colorHelp:null})};b.set(A),E=A.muted,q?.setMuted(A.muted),De.setRequested(A.showFrameStats&&$.parentSupports("frameStats")),t.onPrefs?.(A),t.onAudioChannels!==void 0&&(O===null||O.music!==A.music||O.sounds!==A.sounds)&&(O=Object.freeze({music:A.music,sounds:A.sounds}),t.onAudioChannels(O));},onCohorts:m=>{let A=Object.freeze(m.cohorts.map(G=>Object.freeze({experimentId:G.experimentId,variantKey:G.variantKey})));I.set(A),t.onCohorts?.(A);},onEarnAllowanceChanged:()=>T.emit(),onViewport:m=>{let A=Object.freeze({insets:Object.freeze({top:m.insets.top,right:m.insets.right,bottom:m.insets.bottom,left:m.insets.left}),reserved:Object.freeze((m.reserved??[]).map(({x:ee,y:za,width:Xa,height:Ya,control:Vt})=>Object.freeze(Vt?{x:ee,y:za,width:Xa,height:Ya,control:Object.freeze({x:Vt.x,y:Vt.y,width:Vt.width,height:Vt.height})}:{x:ee,y:za,width:Xa,height:Ya})))});V.set(A);let G=Ic();Cc(G,A.insets),Oc(G,A.reserved,Mc()),t.onViewport?.(A);},onPause:m=>{S=m.paused,d.setPaused(m.paused),De.setPaused(m.paused),t.onPause?.(m.paused);},onSettingChange:m=>xe.onSettingChange(m),onMenuSelect:m=>{fe===null||m.entry!=="item"||!(yi(fe.items).items??[]).some(G=>G.id===m.id)||fe.items?.find(G=>G.id===m.id)?.onSelect?.();},onWillTerminate:m=>{d.endSession(m.reason),t.onWillTerminate?.({reason:m.reason,graceMs:m.graceMs});},onToken:m=>{let A=m.garden;if(Bt(m.allowDevTools===true),!C(m.apiBaseUrl,A))return;let G=m;ae.onToken(G);let ee=ae.identity;ee&&(Si.set(ee),Oa||(Oa=true,me.reconcileSeats().catch(()=>{}))),Ga.push({token:G.token,expiresAt:G.expiresAt});},onTokenDenied:m=>{Bt(false),ae.onDenied(m);},onScreenshot:(m,A,G)=>{kc(m,A,G,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Rc($,t.onFeedbackContext);},onDevtools:m=>{m==="close"?Ee.close():m==="open"?Ee.openFrom("platform").catch(()=>{}):Ee.isOpen?Ee.close():Ee.openFrom("platform").catch(()=>{});},onRoomEvent:m=>me.handleRoomEvent({event:m.event,roomId:m.roomId,...m.matchId===void 0?{}:{matchId:m.matchId},...m.version===void 0?{}:{version:m.version},...m.reason===void 0?{}:{reason:m.reason},...m.platform===void 0?{}:{platform:m.platform}}),onSeatedEvent:m=>me.handleSeated(m.roomId),onAutoStartFailedEvent:m=>me.handleAutoStartFailed(m.roomId,m.code),onTicketEvent:m=>me.handleTicketEvent({event:m.event,ticketId:m.ticketId,...m.partySize===void 0?{}:{partySize:m.partySize},...m.queuedAt===void 0?{}:{queuedAt:m.queuedAt},...m.expiresAt===void 0?{}:{expiresAt:m.expiresAt},...m.reason===void 0?{}:{reason:m.reason},...m.roomId===void 0?{}:{roomId:m.roomId}}),onSocketState:m=>{let A=Z;if(Z=m.connected,m.connected)for(let ee of [...bt])ee();if(!m.connected||A===true)return;let G=e.now();G-we<qn||(we=G,me.reconcile().catch(()=>{}));},onSignalEvent:m=>{let A=typeof m.data=="object"&&m.data!==null&&!Array.isArray(m.data)?m.data:{};_t.handleSignalEvent(m.matchId,m.event,A),m.event==="matchEnded"&&me.reconcile({matchId:m.matchId,...typeof A.reason=="string"?{reason:A.reason}:{}}).catch(()=>{});},onDedicatedEvent:m=>{m.event==="matchEnded"&&(Wt.handleMatchEnded(m.matchId,m.reason),me.reconcile({matchId:m.matchId,...m.reason===void 0?{}:{reason:m.reason}}).catch(()=>{})),Ma.handleEvent(m);},onClusterTarget:m=>Wn.accept(m.clusterTargetId,m.clusterTargetIds),onLocalServer:m=>Vn.accept(m),onLocalServerDenied:m=>Vn.refuse(m),onPartyResult:m=>Da.settle(m.requestId,m.partyId),onPurchaseResult:m=>Ri.settle(m),onDeviceSettings:m=>{Un.receive(m),t.onDeviceSettings?.(Un.api.current);},onDeviceSettingsResult:m=>Un.settle(m),onAdResult:m=>$a.settle(m),onMomentResult:m=>qa.settle(m),onSignInResult:m=>Na.settle(m),onFriendChallengeResult:m=>Ua.settle(m),onArcadeAnswer:m=>{m.type==="gem.storePurchaseSettled"?Ba.settled(m):xm(m);}}),Ma=new En({bridge:$}),Si=$n(e);_i=()=>{Si.release(),x.release(),I.release();},$.currentState==="refused"&&_i();let Oa=false,ki=new Set,jn,Ga={current:()=>jn,subscribe:m=>(ki.add(m),jn!==void 0&&m(jn),()=>ki.delete(m)),push:m=>{jn=m;for(let A of [...ki])try{A(m);}catch(G){n?.(`[gem] a server-token listener threw: ${G instanceof Error?G.message:String(G)}`);}}},ae=Fc({bridge:$,clock:e,onStateChange:(m,A)=>{if(m==="ready"){if(a.mark("token ready")){let G=a.marks.find(ee=>ee.name==="token ready")?.at;d.trackPlatform("gem_boot_ready",G===void 0?{}:{boot_ms:Math.max(0,Math.round(G))});}}else m==="lost"&&(a.mark("token lost"),d.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(m,A);}}),La=()=>{let m=ae.identity;return !m||ae.source.currentState==="lost"?null:`${m.playerId}\0${m.gameId}\0${m.channel}`},Rm=()=>{a.mark("token requested"),ae.source.get().catch(()=>{});},Da=fu({bridge:$,clock:e}),Bn={},Ri=yu({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m),confirm:async m=>Bn.confirm?.(m)??"unknown",confirmAvatar3d:async m=>Bn.confirmAvatar3d?.(m)??"unknown"}),Un=sm({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),Fa={},$a=nm({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m),readAvailability:(m,A)=>Fa.read?.(m,A)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),qa=om({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),Na=ku({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),ja={held:false},Am=Eu({bridge:$,asker:Nn,acting:ja}),Ba=Cu({bridge:$,asker:Nn,acting:ja,onListenerError:m=>t.onError?.("internal",`gem.store.onSettled listener threw: ${String(m)}`)}),xm=m=>{Nn.settle(m)||t.onError?.("internal",`${m.type} (${m.outcome}) for an unknown requestId: `+JSON.stringify(m.requestId));},Ua=od({bridge:$,clock:e,onDropped:m=>t.onError?.("internal",m)}),Wn=fd({bridge:$,clock:e}),Vn=Gc({bridge:$,clock:e}),Ai=bm(L),Wa=window.fetch,Hn=Ai!==null&&typeof Wa=="function"?"unread":"read",Kn=null,xi=false,Pm=m=>{if(Hn==="read"||m.source!==window.parent)return false;let A=m.origin;return typeof A!="string"||k.some(G=>kt(G,A))||or(A,typeof L=="string"?L:void 0)?false:((Kn===null||!xi)&&(Kn=m),Hn==="unread"&&Ai!==null&&(Hn="reading",hm({fetch:(G,ee)=>Wa.call(window,G,ee),selfOrigin:Ai,clock:e}).then(G=>{"refused"in G&&n?.(G.refused),G.origins.length>0&&um($,G.origins),Hn="read";let ee=Kn;Kn=null,ee!==null&&$.currentState==="waiting"&&Jn(ee);})),true)},Jn=m=>{if(Pm(m))return false;let A=$.handleWindowMessage({data:m.data,origin:m.origin,source:m.source,ports:m.ports});return A&&window.removeEventListener("message",Jn),A};window.addEventListener("message",Jn),xi=true;let tt;try{tt=gc(window,Jn);}finally{xi=false;}let Tm=tt?.capture,Pi=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Pi?.domInteractive!==void 0&&Pi.domInteractive>0&&a.mark("document parsed",Pi.domInteractive),Tm?.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 Ti=t.handshakeWarningMs;Ti!==null&&n&&e.setTimeout(()=>{let m=tt===null?"no capture script ran":`capture: ${tt.delivered} offer(s) delivered, ${tt.stale} stale, ${tt.capture.dropped} evicted${tt.capture.late?", installed late":""}`;if($.currentState==="connected"){n(`[gem] handshake connected. boot: ${a.timeline()} \xB7 ${m}`);return}n(`[gem] no completed handshake after ${Ti??_m}ms (bridge state: ${$.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${a.timeline()} \xB7 `+m);},Ti??_m);let Em=gr({get baseUrl(){return Ue},tokenSource:ae.source,get defaultQuery(){let m=ae.identity;return m?{game_id:m.gameId,channel:m.channel}:{}}}),vt=new We({transport:Em,clock:e}),ye={client:vt,gameId:()=>ae.identity?.gameId??""};Bn.confirm=m=>hu(ye,m),Bn.confirmAvatar3d=m=>wu(ye,m),Fa.read=(m,A)=>dl(ye,"players","me",m,{signal:A});let Im=()=>ae.identity?.channel??"release",Ei=new Ar(ye,Im),Cm=_u({player:()=>x.current,subscribe:m=>(P.add(m),()=>{P.delete(m);}),configFamilies:async()=>(await Ei.load())?.avatar_3d_families,readOffers:()=>Su(ye),purchase:m=>Ri.requestAvatar3d(m),log:t.log}),Va=async m=>(await Ei.load())?.currency(m)?.id??void 0,Ha=vr(ye,Hi,{identity:La,resolveCurrencyId:Va}),zn=async m=>{let A=await Si.wait(m);if(A)return A;throw $.currentState==="refused"?new ne("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new ne("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},Ii=u(t.autoReconnect),me=Kd(s===void 0?{}:{playWithTicket:s},{client:vt,clock:e,gameId:()=>ae.identity?.gameId??null,playerId:()=>ae.identity?.playerId??null,awaitGameId:async()=>(await zn(bi)).gameId,resolveParty:Da.resolve,resolveClusterTargets:Wn.resolveList,refreshClusterTargets:Wn.refresh,ensureLocalServer:Vn.ensure,localHostAvailable:Vn.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>ae.gameVersion,...t.pollRooms===void 0?{}:{poll:t.pollRooms},...t.recoverStaleMembership===void 0?{}:{recoverStaleMembership:t.recoverStaleMembership},...t.retryAutoStart===void 0?{}:{retryAutoStart:t.retryAutoStart},...t.watchSeats===void 0?{}:{watchSeats:t.watchSeats},...t.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:t.seatPollIntervalMs},...Ii===null?{}:{autoReconnect:{...Ii,redial:(m,A)=>Ci.redialMatch(m,A),abandon:(m,A)=>Ci.abandonMatch(m,A)}}});p(me),uc({analytics:d,rooms:me});let _t=cc({client:vt,clock:e,rooms:me,bridge:$,gameId:()=>ae.identity?.gameId??"",baseUrl:()=>Ue,resolveClusterTarget:Wn.resolve,boot:a,...t.log===void 0?{}:{log:t.log}}),Ka=Jo(a,n),Wt=eu({client:vt,clock:e,rooms:me,signaling:()=>Ma.channel(),signalingReady:Ut,log:n??(()=>{})}),Ci=pu({rooms:me,p2p:{connect:m=>Ka(_t.connect(m)),session:m=>_t.session(m)},dedicated:{connect:(m=>ti(a,"welcome",Wt.connect(m),n))},clock:e,identity:()=>ae.identity,apiBaseUrl:()=>Ue,tokens:Ga,room:()=>me.currentRoom,autoReconnect:Ii!==null,...t.log===void 0?{}:{log:t.log}}),Mm=async()=>(await zn(bi)).playerId,Ja={client:vt,boot:a,get identity(){return ae.identity},awaitIdentity:(m=bi)=>zn(m),awaitBridge:m=>$.settled(m),get player(){return x.current},awaitPlayer:(m=qv)=>x.wait(m),me:Ha,characters:new wr(ye,void 0,La,Va),transfers:new kr(ye,Hi,Ha.inventory),gameConfig:Ei,purchases:Ri.api,deviceSettings:Un.api,moments:qa.api,ads:$a.api,account:Na.api,share:Pu({frame:$,log:t.log}),arcade:Am,store:Ba.api,branding:$u({fetch:typeof window.fetch=="function"?(m,A)=>window.fetch.call(window,m,A):null,clock:e,devicePixelRatio:()=>window.devicePixelRatio??1,log:n}),vibration:qu({frame:$,log:t.log}),get avatarPickerAvailable(){return $.currentState==="connected"&&$.parentSupports("avatarPicker")},openAvatarPicker:m=>$.requestAvatarPicker(m?.tab),avatars3d:Cm,settings:xe.api,controls:Uu({recommended:()=>b.current?.recommended??null}),analytics:d,leaderboards:new en(ye),challenges:new Yt(ye),showcase:new tn(ye,Mm),friends:new nn(ye,{challenge:Ua.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new on(ye,T,n),profiles:new an(ye),functions:new ze((m,A)=>zs(ye,m,A)),get prefs(){return b.current},get paused(){return S},get cohorts(){return I.current},get viewport(){return V.current},awaitCohorts:(m=Nv)=>I.wait(m),reportMuted:m=>{B=!!m,F();},showPortraitBorders:m=>{let A=fi(m);A!==void 0&&(N=A,ge());},cueReward:m=>$.cueReward(m),setWalletVisible:(m,A)=>{let G=Array.isArray(A?.only)?[...A.only]:void 0;return X=G===void 0?{visible:m===true}:{visible:m===true,only:G},ke()},setMenu:m=>(fe=Array.isArray(m?.items)?{items:m.items.map(A=>({...A}))}:{},te()),setGemCorner:m=>{if(!Lv.includes(m)){let A=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setGemCorner: ${A} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return z=m,Be()},reportFrame:()=>De.draw(),exit:m=>jv(me,$,m,d),frame:$,devtools:Ee,rooms:me,dedicatedServer:{listClusterTargets:m=>Wt.listClusterTargets(m),connect:(m=>ti(a,"welcome",Wt.connect(m),n)),handleMatchEnded:(m,A)=>Wt.handleMatchEnded(m,A)},p2p:{handleSignalEvent:(m,A,G)=>_t.handleSignalEvent(m,A,G),session:m=>_t.session(m),connect:m=>Ka(_t.connect(m))},match:Ci};return Ja}var wm="the match has not started yet: the runtime hands over the host at `init`, and this was read before that. Read it from `init` or later \u2014 a bundle that needs a value at module scope is reading it one call too early.";function Ca(t,e={}){let n=e.clock??ue,r=()=>{let a=t();if(a===null)throw new Error(wm);return a},i=null,o=()=>{if(i===null)throw new Error(wm);return i};return {server:{get identity(){return o().identity},get client(){return o().client},get api(){return o().api},get match(){return o().match},get analytics(){return o().analytics},get functions(){return o().functions},get challenges(){return o().challenges},get room(){return o().room},dispose(){i?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(a){let d=r().profile?.(a);if(!d)return null;let c=d.displayName;return typeof c!="string"||c===""?null:{displayName:he(c,"profile.displayName"),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:he(d.displayTag,"profile.displayTag")}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(a){return r().playerNumber?.(a)},send(a,l,d){d===void 0?r().send(a,l):r().send(a,l,d);},broadcast(a,l){l===void 0?r().broadcast(a):r().broadcast(a,l);},kick(a,l){l===void 0?r().kick(a):r().kick(a,l);},log(a){r().log(a);},warn(a){r().warn(a);}},attach:()=>{i=qt(r(),{...e,clock:n});}}}function Sm(t,e={}){let{server:n,attach:r}=Ca(()=>t,e);return r(),n}function Bv(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:Xe(e)}}}var Uv=1e4;function Wv(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout(Uv));}catch{return}r.catch(i=>{i instanceof M&&i.status>=400&&i.status<500&&(e=i.status!==429);});}}function km(t,e={}){return ()=>{let n=null,{server:r,attach:i}=Ca(()=>n,e),o=t(r),s={async init(l){n=l,i(),await o.init?.();},async shutdown(l){let d=Bv(l);try{await o.shutdown?.(d);}finally{r.dispose();}}},a=Wv(r);return s.join=(l,d)=>(a(l),o.join?.(l,d)),o.leave&&(s.leave=(l,d)=>o.leave?.(l,d)),o.message&&(s.message=(l,d,c,u)=>o.message?.(l,d,c,u)),s}}
|
|
3
|
-
export{
|
|
1
|
+
var $m=Object.defineProperty;var Fm=(t,e)=>{for(var n in e)$m(t,n,{get:e[n],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:18.1.0]";function es(){let t=globalThis.__gemWebSdkVersion;if(typeof t!="string")return "";let e=t.lastIndexOf(":"),n=t.lastIndexOf("]");return e<0||n<=e+1?"":t.slice(e+1,n)}var qm={initialDelayMs:2e3,maxDelayMs:6e4};function Nm(t,e){return e!==void 0?!e:t==="chain_exhausted"}var wt=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;retry=null;failures=0;notBefore=0;disposed=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new ne(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.pastChainCeiling())throw new ne("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new ne(this.failure??"unavailable","the embedder asked for no new token yet; one is asked for when that wait is over");return this.refresh(this.nextReason())}pastChainCeiling(){return this.grant===null||this.seconds()<this.grant.chainEndsAt?false:(this.enter("lost","chain_exhausted"),true)}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}dispose(){this.disposed=true,this.cancelRetry();}scheduleRetry(e){if(this.cancelRetry(),this.failures+=1,this.notBefore=e===void 0?0:this.options.clock.now()+e,this.disposed)return;let{initialDelayMs:n,maxDelayMs:r}=qm,i=Math.min(r,n*2**(this.failures-1)),o=Math.max(i/2,e??0)+Math.random()*(i/2);this.retry={handle:this.options.clock.setTimeout(()=>this.retryNow(),o)};}retryNow(){this.retry=null,this.notBefore=0,!(this.state==="lost"||this.pastChainCeiling())&&this.refresh(this.nextReason()).catch(()=>{});}cancelRetry(){this.retry!==null&&(this.options.clock.clearTimeout(this.retry.handle),this.retry=null);}refresh(e){if(this.inFlight)return this.inFlight;this.cancelRetry();let n=this.generation;this.enter("pending");let r=this.options.request(e).then(i=>{if(n!==this.generation)throw new ne("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=jm(i),{retryable:s,retryAfterMs:a}=i??{};throw n===this.generation&&(Nm(o,typeof s=="boolean"?s:void 0)?this.enter("lost",o):(this.scheduleRetry(typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0),this.enter("degraded",o))),i instanceof ne?i:new ne(o,String(i))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){(e==="ready"||e==="lost")&&this.cancelRetry(),e==="ready"&&(this.failures=0,this.notBefore=0),this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},ne=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function jm(t){if(t instanceof ne)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var se=class t extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof t)return true;let n=e;return n?.name==="TransportRefusal"&&n.retryable===false}},Zn=["if-match","if-none-match"],ts=4096;function Bm(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let i=n.toLowerCase();if(!Zn.includes(i)||r===void 0)continue;let o=typeof r=="string"?Um(r):r;if(typeof o!="string"||o.length>ts||!Wm(o))throw new se(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${ts} 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 Um(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 Wm(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 Hm(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new se("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new se("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function ns(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=Bm(i.headers),s=Hm(i),a=Object.freeze({...i,headers:o,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await t(a,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let c=await e.tokenSource.get(),u=await t(a,c);if(u.status===401)throw e.tokenSource.close("unavailable"),new ne("unavailable","the server refused a freshly minted token");return u}}}function er(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Vm(e))}function tr(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 Oi(t){return new TextDecoder().decode(tr(t))}function Vm(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var M=class extends Error{constructor(n,r,i,o,s){super(`${n} (${r}): ${i}`);this.reason=n;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},os=new WeakMap;function as(t){return os.get(t)??{}}var Km=new Set([408,429,500,502,503,504]),Jm=6e4,ss=new WeakMap;function ls(t,e){ss.set(t,e);}function rs(t){return t!==null&&(t.reason==="rate_limited"||t.retryAfterSeconds!==void 0)}function zm(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new se(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(t)}. This is a configuration fault, not a server failure.`);return t}var He=class{constructor(e){this.options=e;}options;async get(e,n){return this.send({method:"GET",path:e,signal:n},true)}async getWithEtag(e,n={}){let r=await this.sendRaw({method:"GET",path:e,...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{headers:{"if-none-match":n.ifNoneMatch}}},true),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,...Kt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async post(e,n,r,i={}){return this.send({method:"POST",path:e,body:n,signal:r,...Kt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async postBytes(e,n,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...Kt(i)},i.replaySafe===true,i.retryRateLimited!==false);return {bytes:Xm(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,...Kt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Kt(r)},r.replaySafe===true,r.retryRateLimited!==false)}async send(e,n,r=true){return (await this.sendRaw(e,n,r)).body}async sendRaw(e,n,r=true){let i=n?zm(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw is(e.signal);let s=e.signal===void 0?void 0:ss.get(e.signal);for(let a=0;a<i;a++){if(a>0){let c=this.backoffMs(a,o);if(rs(o)&&s!==void 0&&c>=s())throw o;await this.backoff(c,e.signal);}if(e.signal?.aborted)throw rs(o)&&s!==void 0&&s()<=0?o:is(e.signal);let l;try{l=await this.options.transport.request(e);}catch(c){if(ne.isAuthError(c)||se.isRefusal(c)||e.signal?.aborted||Ym(c))throw c;o=new M("unavailable",0,String(c));continue}if(l.status>=200&&l.status<300||l.status===304)return l;let d=Qm(l);if(!Km.has(l.status)||l.status===429&&!r)throw d;o=d;}throw o??new M("unavailable",0,"no attempt was made")}backoffMs(e,n){let r=n?.retryAfterSeconds,i=r!==void 0?r*1e3:2**(e-1)*250,o=2**(e-1)*250;return Math.min(Math.max(i,o),Jm)}backoff(e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=this.options.clock,o=false,s=false,a,l=()=>{o||(o=true,s&&i.clearTimeout(a),n?.removeEventListener("abort",l),r());};n?.addEventListener("abort",l,{once:true}),a=i.setTimeout(l,e),s=true,o&&i.clearTimeout(a);})}};function Xm(t){if(t instanceof Uint8Array)return t;if(t==null)return new Uint8Array(0);let e=typeof t=="string"?t:JSON.stringify(t);return new TextEncoder().encode(e)}function Kt(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function is(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Ym(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Qm(t){let e=ep(t),n=np(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&os.set(e,r),e}var Zm=new Map([["insufficient_funds","insufficient_funds"]]);function ep(t){let{status:e,body:n}=t,r=tp(n),i=t.retryAfterSeconds??ip(n),o=rp(n),s=o===void 0?void 0:Zm.get(o);if(s!==void 0)return new M(s,e,r,void 0,o);switch(e){case 304:return new M("not_modified",e,r);case 400:case 422:return new M("invalid",e,r,void 0,o);case 403:return new M("forbidden",e,r,void 0,o);case 404:return new M("not_found",e,r,void 0,o);case 402:return new M("insufficient_funds",e,r,void 0,o);case 409:return new M("conflict",e,r,void 0,o);case 412:return new M("precondition_failed",e,r,void 0,o);case 413:return new M("too_large",e,r,void 0,o);case 429:return new M("rate_limited",e,r,i,o);default:return new M("unavailable",e,r,i,o)}}function tp(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 np(t){let n=t?.error?.details;return n===null?void 0:n}function rp(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function ip(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function ds(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function cs(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/add`;return t.client.post(s,i,o?.signal)}async function us(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function ms(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}`;return t.client.delete(r,n?.signal)}async function ps(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/claim`;return t.client.post(s,i,o?.signal)}async function gs(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function fs(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ys(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function hs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function bs(t,e,n,r,i){let o=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(o,i?.signal)}async function vs(t,e,n,r,i){let o=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(o,i?.signal)}async function _s(t,e,n,r){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.delete(i,r?.signal)}async function ws(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ss(t,e,n,r,i,o){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function ks(t,e,n){let r=`/v1/games/${_(t.gameId())}/avatars-3d/${_(e)}/owned`;return t.client.get(r,n?.signal)}async function Rs(t,e,n){let r=`/v1/games/${_(t.gameId())}/config/channels/${_(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function As(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.get(r,n?.signal)}async function xs(t,e,n){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Ps(t,e,n,r,i){let o=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Ts(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Es(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/items/${_(r)}`;return t.client.get(o,i?.signal)}async function Is(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${_(e)}/${_(n)}/${_(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function Cs(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders/${_(r)}`;return t.client.get(o,i?.signal)}async function Ms(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}`;return t.client.get(o,i?.signal)}async function Os(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/catalogs/${_(r)}/recipes/${_(i)}/availability`;return t.client.get(s,o?.signal)}async function Gs(t,e,n,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Gi(t,e,n,r,i){let o=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Ls(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}/friends`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function Ds(t,e,n){let r=`/v1/showcase/friends/${_(e)}`;return t.client.get(r,n?.signal)}async function $s(t,e){let n=`/v1/games/${_(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function Fs(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}`;return t.client.get(r,n?.signal)}async function qs(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function Ns(t,e){let n=`/v1/games/${_(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function nr(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function js(t,e,n){let r=`/v1/profiles/players/${_(e)}`;return t.client.get(r,n?.signal)}async function Bs(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 Us(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return t.client.get(r,n?.signal)}async function Ws(t,e,n,r){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.get(i,r?.signal)}async function Hs(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function Vs(t,e,n){let r=`/v1/inventory/transfers/${_(e)}`;return t.client.get(r,n?.signal)}async function Ks(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function Js(t,e,n){let r=`/v1/games/${_(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true,retryRateLimited:false})}async function zs(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Xs(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/platform-funded-game-inventory-purchases`;return t.client.post(o,r,i?.signal)}async function Ys(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Qs(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 Zs(t,e){return t.client.get("/v1/characters",e?.signal)}async function el(t,e,n,r){let i=`/v1/settings/${_(e)}/${_(n)}`;return t.client.get(i,r?.signal)}async function tl(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function nl(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${_(e)}/${_(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function rl(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 il(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 ol(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 al(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function sl(t,e,n,r){let i=`/v1/games/${_(t.gameId())}/matches/${_(e)}/end`;return t.client.post(i,n,r?.signal)}async function ll(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/max`;return t.client.post(s,i,o?.signal)}async function dl(t,e,n,r,i,o){let s=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function cl(t,e,n,r,i){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.put(o,r,i?.signal)}async function ul(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/rewarded-placements/${_(r)}/availability`;return t.client.get(o,i?.signal)}async function ml(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function pl(t,e,n,r){let i=`/v1/characters/${_(e)}`;return t.client.patch(i,n,r?.signal)}async function gl(t,e,n,r,i,o){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function fl(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/reset`;return t.client.post(s,i,o?.signal)}async function yl(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.delete(r,n?.signal)}var q="gem-web-bridge",ir={min:1,max:1},op=65536,hl=8,rr=5e3,bl=1024;var Jt=Object.create(null),or="__malformed";var $i=Object.create(null),ap=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"]]);function ar(t){let e=$i[t];if(e!==void 0)return e;for(let[n,r]of ap)if(t.startsWith(n))return r}function St(t){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(t);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function sp(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 lp(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function dp(t){return /^[a-z_]+$/.test(t)}function cp(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(t)&&!t.includes("--")}function Li(t,e,n){if(e>hl)return `nesting deeper than ${hl}`;if(++n.nodes>rr)return `more than ${rr} values`;if(n.bytes>n.cap)return `over the ${n.cap} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=t;if(n.seen.has(i))return "a repeated or cyclic object reference";if(n.seen.add(i),Array.isArray(t)){if(t.length>bl)return `an array of ${t.length} entries, over the ${bl} limit`;n.bytes+=2;for(let a of t){let l=Li(a,e+1,n);if(l)return l}return null}let o=Object.getPrototypeOf(t);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";n.bytes+=2;let s=t;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++n.nodes>rr)return `more than ${rr} values`;if(n.bytes+=a.length*3+4,n.bytes>n.cap)return `over the ${n.cap} byte limit`;let l=Li(s[a],e+1,n);if(l)return l}return null}function up(t,e=op){let n={nodes:0,bytes:0,seen:new Set,cap:e},r=Li(t,0,n);return r?`message contains ${r}`:n.bytes>e?`message is over the ${e} byte limit`:null}var mp={origin:[St,"not a well-formed origin"],url:[sp,"not a safe absolute http(s) URL"],bcp47:[lp,"not a well-formed BCP 47 tag"],code:[dp,"not a code of lower-case letters and underscores"],gameRef:[cp,"not a game id or web address"]};function vl(t,e,n){for(let r of e){let i=n===""?r[0]:`${n}.${r[0]}`,o=t[r[0]];if(o==null){if(r[1]<"a")continue;return `${i}: required`}let s=Di(o,r,i);if(s)return s}return null}function Di(t,e,n){let r=e[1].toLowerCase();switch(r){case "u":return typeof t=="boolean"?null:Di(t,typeof t=="string"?[e[0],"s",e[2]]:[e[0],"n",e[3],e[4]],n);case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e[2])return `${n}: exceeds ${e[2]} characters`;if(e[3]){let[i,o]=mp[e[3]];if(!i(t))return `${n}: ${o}`}return null}case "n":case "i":return typeof t!="number"||!(r=="i"?Number.isInteger:Number.isFinite)(t)?`${n}: expected ${r=="i"?"integer":"number"}`:t<e[2]||t>e[3]?`${n}: out of range ${e[2]}..${e[3]}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let i=e[2];return i.includes(t)?null:`${n}: not one of ${i.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:vl(t,e[2],n);case "j":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "a":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e[2])return `${n}: exceeds ${e[2]} items`;let i=e[3],o=`${n}[]`;for(let s of t){if(s==null){if(i[1]<"a")continue;return `${o}: required`}let a=Di(s,i,o);if(a)return a}return null}default:return `${n}: unknown kind ${String(r)}`}}var _l=Object.create(null);function A(t,e,n,r,i){return Jt[t]=n,r&&($i[t]=r),_l[t]=o=>{let s=up(o,i);if(s)return s;if(typeof o!="object"||o===null||Array.isArray(o))return "message: expected object";let a=o;return a.gem!==q?"gem: wrong protocol marker":a.type!==t?`type: expected ${t}`:vl(a,e,"")}}var W=["requestId","s",64],Ve=["outcome","e",["ok","declined","unavailable"]],Ke=["reason","S",64,"code"];A("gem.handshake",[["versions","o",[["min","i",1,1e3],["max","i",1,1e3]]],["capabilities","A",64,["","s",64]],["embedder","s",2048,"origin"],["unbidden","B"]],30);A("gem.handshake.accept",[["v","i",1,1e3],["capabilities","A",64,["","s",64]]],5);A("gem.token",[["token","s",4096],["requestId","S",64],["generation","i",0,2147483647],["apiBaseUrl","S",512,"url"],["playerId","s",64],["gameId","s",64],["channel","e",["dev","test","release"]],["gameVersion","S",64],["expiresAt","i",0,4102444800],["chainEndsAt","i",0,4102444800],["allowDevTools","B"]],30);A("gem.token.denied",[W,["retryable","b"],["retryAfterMs","I",0,36e5],["reason","e",["chain_exhausted","unavailable"]],["correlationId","s",64]],30);A("gem.player",[["untrusted","o",[["displayName","s",64],["displayTag","S",80],["displayHandle","s",80]]],["playerId","S",64],["discriminator","S",8],["avatarIconUrl","S",2048,"url"],["avatarIconId","S",64],["avatar3dId","S",64],["avatar3dModelUrl","S",2048,"url"],["avatar3dIconUrl","S",2048,"url"],["avatars3d","A",8,["","o",[["family","s",32],["id","s",64],["modelUrl","s",256,"url"],["iconUrl","s",256,"url"]]]],["badges","A",2,["","o",[["itemId","s",64],["iconUrl","s",2048,"url"]]]],["displayTag","s",8],["avatarUrl","S",2048,"url"],["boost","O",[["multipliers","a",8,["","o",[["currencyId","s",64],["currencySlug","s",32],["multiplierBp","i",1e4,1e6]]]],["expiresInDays","I",1,7]]]],12);A("gem.pause",[["paused","b"]],120);A("gem.prefs",[["reducedMotion","b"],["muted","b"],["showFrameStats","B"],["music","B"],["sounds","B"],["locale","s",35,"bcp47"],["recommended","O",[["volume","i",0,100],["batterySaver","b"],["keyboardLayout","e",["wasd","arrows"]],["gamepadConfirm","e",["south","east"]],["vibration","b"],["lookSensitivity","I",20,400],["gamepadLookSensitivity","I",20,400],["invertLookY","B"],["touchMovement","S",16,"code"],["graphicsQuality","S",16,"code"],["graphicsQualityAuto","B"],["colorHelp","B"]]]],60);A("gem.cohorts",[["cohorts","a",8,["","o",[["experimentId","s",36],["variantKey","s",32]]]]],12,"cohorts");A("gem.earnAllowanceChanged",[],30,"earnAllowance");A("gem.viewport",[["insets","o",[["top","i",0,4096],["right","i",0,4096],["bottom","i",0,4096],["left","i",0,4096]]],["reserved","A",4,["","o",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384],["control","O",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384]]]]]]],60,"viewport");A("gem.deviceSettings",[["settings","J"]],12,"deviceSettings");A("gem.willTerminate",[["reason","e",["grant_expiring","session_ended","navigating","kill_switch"]],["graceMs","i",0,6e4]],10);A("gem.roomEvent",[["event","e",["updated","match_started","match_ready","match_failed","version_stale"]],["roomId","s",64],["matchId","S",64],["version","I",0,2147483647],["reason","S",64],["platform","E",["universal","mobile"]]],120,"rooms");A("gem.socketState",[["connected","b"],["reason","E",["connecting","dropped","watchdog","terminal"]]],12,"socketState");A("gem.seatedEvent",[["roomId","s",64]],60,"partySeating");A("gem.autoStartFailedEvent",[["roomId","s",64],["code","s",64]],30,"autoStartFailure");A("gem.ticketEvent",[["event","e",["queued","matched","expired","cancelled","failed"]],["ticketId","s",64],["partySize","I",1,64],["queuedAt","I",0,4102444800],["expiresAt","I",0,4102444800],["reason","S",64],["roomId","S",64]],60,"ticketEvents");A("gem.signalEvent",[["event","e",["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]],["matchId","s",64],["data","j"]],1800,"p2p");A("gem.dedicatedEvent",[["event","e",["answer","error","matchEnded"]],["matchId","s",64],["sdp","S",10240],["sessionId","S",64],["code","S",64],["message","S",256],["reason","S",64]],120,"dedicated");A("gem.partyResult",[W,["partyId","S",64]],30,"parties");A("gem.clusterTarget",[["clusterTargetId","s",64],["clusterTargetIds","A",3,["","s",64]]],12,"clusterTarget");A("gem.devtools",[["action","e",["open","close","toggle"]]],30,"devtools");A("gem.screenshot",[["maxWidth","i",1,7680],["maxHeight","i",1,4320]],6,"screenshot");A("gem.screenshot.denied",[["reason","e",["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]],["retryable","b"]],12,"screenshot");A("gem.requestContext",[],12,"feedbackContext");A("gem.gameContext",[["context","j"]],12,"feedbackContext");A("gem.signal",[["signal","e",["join","offer","answer","ice","migrationAck","hostUnreachable"]],["matchId","s",64],["data","j"]],1200,"p2p");A("gem.dedicatedOffer",[["matchId","s",64],["sdp","s",10240],["intent","e",["initial","ice_restart","full_reconnect"]]],60,"dedicated");A("gem.partyRequest",[W],12,"parties");A("gem.ready",[],5);A("gem.engaged",[],5,"engagement");A("gem.progress",[["loaded","i",0,1099511627776],["total","i",0,1099511627776]],600);A("gem.requestToken",[W,["reason","e",["initial","expiring","rejected"]]],12);A("gem.requestLocalServer",[W,["gameRoomId","s",64]],6,"localHost");A("gem.localServer",[W,["serverId","S",128]],30,"localHost");A("gem.localServer.denied",[W,["retryable","b"],["reason","e",["refused","unavailable"]]],30,"localHost");A("gem.exit",[["reason","S",64]],5);A("gem.openExternal",[["url","s",2048,"url"]],6);A("gem.requestFullscreen",[["enabled","b"]],30);A("gem.audioState",[["muted","b"]],120,"audioState");A("gem.rewardCue",[["currencySlug","s",32],["expected","I",1,1e9],["origin","O",[["x","i",0,16384],["y","i",0,16384]]]],60,"rewardCue");A("gem.walletDisplay",[["visible","b"],["currencies","A",8,["","s",64]],["score","B"]],60,"walletDisplay");A("gem.controlsDeclare",[["uses","o",[["lookSensitivity","S",16,"code"],["gamepadLookSensitivity","S",16,"code"],["invertLookY","S",16,"code"],["touchMovement","S",16,"code"]]]],60,"controls");A("gem.menu",[["settings","b"],["items","A",4,["","o",[["id","s",32],["label","s",40]]]]],60,"gameMenu");A("gem.menuSelect",[["entry","e",["settings","item"]],["id","S",32]],60,"gameMenu");A("gem.gemCorner",[["corner","e",["top-left","top-right","bottom-left","bottom-right"]]],12,"gemCorner");A("gem.menuStyle",[["ground","S",7],["accent","S",7]],12,"menuStyle");A("gem.settingsDeclare",[["settings","a",8,["","o",[["id","s",40],["label","s",40],["kind","e",["toggle","slider","choice"]],["value","u",40,-1e6,1e6],["quick","B"],["icon","S",16,"code"],["min","N",-1e6,1e6],["max","N",-1e6,1e6],["step","N",0,1e6],["options","A",4,["","o",[["id","s",40],["label","s",40]]]]]]]],120,"gameSettings");A("gem.settingChange",[["id","s",40],["value","u",40,-1e6,1e6]],120,"gameSettings");A("gem.requestShare",[["params","a",16,["","o",[["key","s",64],["value","s",512]]]]],6,"share");A("gem.requestAvatarPicker",[["tab","E",["2d","3d"]]],6,"avatarPicker");A("gem.vibrate",[["pattern","a",99,["","i",0,1e4]]],600,"vibration");A("gem.frameStats",[["fps","i",0,1e3],["frameTimeP95Ms","i",0,1e5],["counts","E",["pageFrames","gameDraws"]]],120,"frameStats");A("gem.portraitBorders",[["name","S",40]],60,"portraitBorders");A("gem.error",[["code","e",["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]],["message","S",256]],60);A("gem.requestPurchase",[W,["purchaseKind","e",["item","recipe"]],["targetId","s",64],["currencySlug","s",32],["quantity","I",1,10],["catalogId","S",64]],12,"purchases");A("gem.requestAvatar3dPurchase",[W,["itemId","s",64],["currencySlug","s",32]],12,"avatar3dPurchases");A("gem.purchaseResult",[W,Ve,Ke,["purchaseId","S",64]],30,"purchases");A("gem.deviceSettings.put",[W,["settings","j"]],30,"deviceSettings");A("gem.deviceSettings.result",[W,["outcome","e",["stored","too_large","unavailable"]]],30,"deviceSettings");A("gem.requestAd",[W,["placement","s",32],["format","e",["interstitial","rewarded"]]],6,"ads");A("gem.adResult",[W,["outcome","e",["shown","no_ad","unavailable"]]],12,"ads");A("gem.signalMoment",[W,["kind","e",["level_end","run_end","match_end","menu_return","other_break"]],["placement","S",32],["wall","B"]],6,"moments");A("gem.momentResult",[W,["shown","b"]],12,"moments");A("gem.requestSignIn",[W],6,"signIn");A("gem.signInResult",[W,["outcome","e",["signed_in","declined","unavailable"]]],12,"signIn");A("gem.requestFriendChallenge",[W,["playerId","s",64],["template","s",64],["params","J"]],12,"friendChallenges");A("gem.friendChallengeResult",[W,["outcome","e",["accepted","cancelled","refused","unavailable","rate_limited","invalid"]],["code","S",64],["param","S",64],["channel","S",16],["configVersion","I",0,9007199254740991],["retryAfterMs","I",0,864e5],["detail","S",300]],30,"friendChallenges");A("gem.requestAppLinks",[W],12,"appLinks");A("gem.appLinksResult",[W,Ve,Ke,["arcade","O",[["store","e",["app_store","google_play"]]]],["game","O",[["store","e",["app_store","google_play"]]]]],30,"appLinks");A("gem.requestOpenApp",[W,["target","e",["arcade","game"]]],6,"appLinks");A("gem.openAppResult",[W,Ve,Ke],30,"appLinks");var wl=A("gem.requestOpenGame",[W,["ref","s",40,"gameRef"]],6,"openGame");A("gem.openGameResult",[W,Ve,Ke],30,"openGame");A("gem.requestSimilarGames",[W,["limit","I",1,24]],12,"openGame");A("gem.similarGamesResult",[W,Ve,Ke,["games","a",24,["","o",[["gameId","s",36,"gameRef"],["slug","S",40,"gameRef"],["iconUrl","s",1024,"url"],["capsuleLandscapeUrl","s",1024,"url"],["capsulePortraitUrl","s",1024,"url"],["previewVideoUrl","S",1024,"url"],["previewPosterUrl","S",1024,"url"],["untrusted","o",[["name","s",64],["tagline","s",64],["shortDescription","s",320],["tags","a",10,["","s",32]]]]]]]],30,"openGame",524288);A("gem.requestStoreOffers",[W],12,"store");A("gem.storeOffersResult",[W,Ve,Ke,["offers","a",32,["","o",[["skuId","s",64],["kind","e",["gem_pack","boost","pass","bundle"]],["name","s",80],["description","s",400],["imageUrl","S",1024,"url"],["priceDisplay","s",32],["grant","O",[["currency","s",32],["amount","i",1,1e9]]]]]]],30,"store",262144);A("gem.requestStorePurchase",[W,["skuId","s",64]],12,"store");A("gem.storePurchaseResult",[W,Ve,Ke],30,"store");A("gem.storePurchaseSettled",[["skuId","s",64]],30,"store");A("gem.requestStoreOfferSheet",[W,["skuId","s",64]],12,"storeOfferSheet");A("gem.storeOfferSheetResult",[W,Ve,Ke],30,"storeOfferSheet");var sr=Object.freeze(_l);Jt.__malformed=60;Object.freeze(Jt);Object.freeze($i);var ue={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},zt=class{constructor(e=ue){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Jt[e];if(n===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??n,s=Math.max(0,r-i),a=Math.min(n,o+s*n/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function kt(t,e){return t.toLowerCase()===e.toLowerCase()}function Je(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function lr(t,e){if(typeof e!="string"||e==="")return false;let n,r;try{n=new URL(t),r=new URL(e);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||n.username!==""||n.password!==""||n.pathname!=="/"||n.search!==""||n.hash!==""||n.port===""?false:Je(n.hostname)&&Je(r.hostname)}function Sl(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 dr=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let i=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,o=i.find(a=>a.currencyId===e),s;return !o&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(o=i.find(a=>a.currencyId===s))),{currencyId:o?o.currencyId:s??e,total:o?o.total:null,...o?.buckets===void 0?{}:{buckets:o.buckets}}}};function qi(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 kl="inventory",Rt=t=>typeof t=="number"?t:0,Xt=t=>typeof t=="string"?t:"";function Fi(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 Rl(t){let e=t??{};return {itemDefinitionId:Xt(e.item_definition_id),instanceId:Xt(e.instance_id),quantity:Rt(e.quantity),acquiredAt:Rt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function pp(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Fi(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:Xt(a.bucket),balance:Rt(a.balance)}}):void 0;return {currencyId:Xt(i.currency_id),total:Rt(i.total),...o===void 0?{}:{buckets:o}}}),items:Fi(e.items,Rl),progressions:Fi(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:Xt(i.progression_definition_id),currentValue:Rt(i.current_value),completionCount:Rt(i.completion_count),isCompleted:i.is_completed===true,...qi(i)}}),...n===void 0?{}:{etag:n}}}var cr=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${kl}#buckets`:kl;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let o=r.items.data.filter(s=>s.itemDefinitionId===e);if(o.length>0)return o}let i=await Es(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(i)?i.map(Rl):[]}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 Ts(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 pp(n)}};var gp={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,already_owned:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},fp=new Set(Object.keys(gp));function Al(t){return typeof t=="string"&&fp.has(t)?t:"error"}var ze=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var re=t=>typeof t=="string"?t:"",yp=t=>typeof t=="string"?t:re(t&&typeof t=="object"?t.type:void 0),Ee=t=>typeof t=="number"?t:0;function hp(t){let e=t??{};return {prerequisiteType:re(e.prerequisite_type),referenceId:re(e.reference_id),required:Ee(e.required),current:Ee(e.current)}}function Yt(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:re(e.order_id),status:re(e.status),...n===void 0?{}:{etag:n}}}function ur(){return crypto.randomUUID()}var bp="recipe-usage",xl=100;function mr(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:re(e.currency_id),bucket:re(e.bucket),delta:Ee(e.delta),balanceAfter:Ee(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:re(e.item_definition_id),instanceId:re(e.instance_id),delta:Ee(e.delta),quantityAfter:Ee(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:re(e.progression_definition_id),delta:Ee(e.delta),valueAfter:Ee(e.value_after),completed:e.completed===true};default:return {kind:"other",type:re(e.type)}}}function vp(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:re(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Ee(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(mr):[]}}function _p(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(vp):void 0;return {orderId:re(e.order_id),status:re(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(mr):[],consumed:Array.isArray(e.consumed)?e.consumed.map(mr):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(mr):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function wp(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:re(e.target_order_id)||re(e.source_order_id),status:re(e.status),purchaseId:re(e.purchase_id),sourceOrderId:re(e.source_order_id),price:{currencyId:re(n.platform_currency_id),amount:Ee(n.price)}}}function Sp(t){let e=t??{},n=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:re(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...n===void 0?{}:{lastUsedAt:n},...r===void 0?{}:{cooldownExpiresAt:r}}}function Pl(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 pr=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(()=>ys(this.api,this.entity.type,this.entity.id,{operations:e.map(Pl),source:n.source??"play",nonce:ur()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Yt(r)}async createMany(e,n={}){return this.write(()=>fs(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Pl),nonce:ur()})),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 Os(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},s=typeof o.uses_remaining=="number"?o.uses_remaining:void 0,a=typeof o.cooldown_expires_at=="string"?o.cooldown_expires_at:void 0,l=Array.isArray(o.lock_reasons)?o.lock_reasons.map(hp):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>yp(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(bp,[],async()=>{let n=await Gs(this.api,this.entity.type,this.entity.id,{limit:xl})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(Sp),truncated:r.length>=xl}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let u=e,p=await this.write(()=>ws(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:ur()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",..._p(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([Bs(this.api,n.signal===void 0?{}:{signal:n.signal}),nr(this.api,n.signal===void 0?{}:{signal:n.signal})]),o=e.payment.currencySlug.toLowerCase(),s=i.currencies.find(u=>u.currency_id.toLowerCase()===o||u.slug.toLowerCase()===o);if(s===void 0){let u=i.currencies.map(p=>p.slug);throw new ze("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let a=e.kind==="item"?r.items.find(u=>u.item_id===e.targetId):r.recipes.find(u=>u.recipe_id===e.targetId&&u.catalog_id===e.catalogId);if(a===void 0)throw new ze("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=a.platform_prices.find(u=>u.platform_currency_id===s.currency_id);if(l===void 0){let u=g=>i.currencies.find(f=>f.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new ze("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new ze("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let c=await this.write(()=>Xs(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:s.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:ur(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return wp(c)}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(()=>cs(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Yt(i)}async maxProgression(e,n,r){let i=await this.write(()=>ll(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Yt(i)}async claimProgression(e,n){let r=await this.write(()=>ps(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Yt(r)}async resetProgression(e,n){let r=await this.write(()=>fl(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Yt(r)}async write(e){return this.cache.invalidate(),e()}};var Ni=t=>typeof t=="string"?t:"",kp=t=>typeof t=="number"?t:0;function Tl(t){let e=t??{};return {orderId:Ni(e.order_id),status:Ni(e.status),source:Ni(e.source),createdAt:kp(e.created_at)}}var gr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await tl(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(Tl):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await Cs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Tl(r)}};var El=t=>typeof t=="number"?t:0,Rp=t=>typeof t=="string"?t:"";function Ap(t){let e=t??{};return {progressionDefinitionId:Rp(e.progression_definition_id),currentValue:El(e.current_value),completionCount:El(e.completion_count),isCompleted:e.is_completed===true,...qi(e)}}var fr=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 Ms(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Ap(o)}catch{return i??null}}};var yr=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,i){this.rebind();let o=n.length===0,s=o?e:e+"\0"+n.join("\0"),a=this.slots.get(s);if(a){let u=a.filledAt;if(u!==void 0&&(i===void 0||this.clock.now()-u<=i))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,c=r().then(u=>(o&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===c&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=c,c}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 xp(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Pp=new Set(Zn);function Tp(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Pp.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function hr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return ns(async(n,r)=>{let i;try{i=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new se("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let o;try{o=new URL(i.href.replace(/\/+$/,"")+n.path);}catch{throw new se(`${JSON.stringify(typeof n.path=="string"?xp(n.path):"(a non-string path)")} does not form a valid URL against ${i.protocol}//${i.host}. This is a malformed request, not a server failure.`)}if(o.protocol!==i.protocol||o.host!==i.host)throw new se(`${JSON.stringify(o.pathname)} resolves to ${o.protocol}//${o.host}, not ${i.protocol}//${i.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(o.username!==""||o.password!==""){let g=i.username!==""||i.password!=="",f=o.username!==i.username||o.password!==i.password,h=g?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new se(`the ${h} puts credentials in the URL, which cannot be fetched (${n.method} ${o.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,f]of Object.entries(t.defaultQuery??{}))o.searchParams.has(g)||o.searchParams.set(g,f);let s=n.bytes,a=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(s=JSON.stringify(n.body),a="application/json");}catch(g){throw new se(`the body of ${n.method} ${JSON.stringify(o.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(o.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...Tp(n.headers)},body:s,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let c=l.headers.get("etag"),u=ji(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...c===null?{}:{etag:c},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},t)}function ji(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}function Bi(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 br(t){try{let e=Bi(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ie=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},Ep=3e4,Ip=5e3,Il=6e4,Cp=2**31-1,Cl="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",Mp=/^[A-Za-z0-9_]{1,64}$/;function qe(t){let e=t.length===0?"a save key cannot be empty":t.length>64?`it is ${t.length} characters; a save key is at most 64`:t.startsWith("_")||t.startsWith("$")?`it begins with ${JSON.stringify(t[0])}, and \`_\` and \`$\` are reserved prefixes`:"a save key is ASCII letters, digits and underscores only \u2014 no hyphens, spaces or other punctuation, unlike a template slug";if(!Mp.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Ml(t,e){let n=new AbortController,r=Date.now()+e;ls(n.signal,()=>r-Date.now());let i=AbortSignal.timeout(e),o=()=>n.abort(i.reason),s=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(i.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",s,{once:true})),{signal:n.signal,release:()=>{i.removeEventListener("abort",o),t?.removeEventListener("abort",s);}}}function Ui(t,e){return t.aborted&&e?.aborted!==true}var Op=new Set(["x-ms-blob-type"]),Gp=/^[ -~]+$/;function Lp(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,i]of Object.entries(t)){let o=r.toLowerCase();if(!Op.has(o))throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof i!="string"||!Gp.test(i))throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(o in n)throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);n[o]=i;}return n}function Wi(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 Hi(t){return t?.reason==="not_found"}function Dp(t){return t?.code==="save_conflict"}function Ol(t){return t instanceof M&&t.reason==="rate_limited"}async function Gl(t,e){let n=await br(e);return new M("rate_limited",429,`the save ${t} answered 429: too many save calls. ${n}`.trim(),ji(e.headers.get("retry-after")))}function vr(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function $p(t,e,n,r,i){let o=false,s=()=>o?false:(o=true,a.detach?.(),true),a={signal:n.signal,budget:r,deadlineAt:Date.now()+r,teardown:n.teardown===true,overwrite:n.overwrite===true,identity:i,resolve:l=>{s()&&t(l);},reject:l=>{s()&&e(l);},detach:void 0};return a}function Ll(t,e){return t!==null&&e!==null&&e!==t}function Dl(t){return new ie("save_conflict",`save ${JSON.stringify(t)} was not written: the signed-in player changed while it waited for the write before it, and it holds the last player's progress.`)}var _r=class{constructor(e,n,r={},i){this.api=e;this.entity=n;this.options=r;this.identity=i;}api;entity;options;identity;versions=new Map;seq=0;versionsOf=null;writes=new Map;holdUntil=0;async put(e,n,r={}){let i;try{i=JSON.stringify(n);}catch(o){throw new ie("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}. Retrying stores the same unserialisable value.`)}if(i===void 0)throw new ie("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(i),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){if(qe(e),r.signal?.aborted)throw vr(r.signal);let i=this.budget(r.timeoutMs),o=this.slotWrites(e);return new Promise((s,a)=>{let l=o.queued;l?.release();let d=l?.waiters[l.waiters.length-1];d!==void 0&&this.holdOwn(o,d);let c=this.identity?.()??null;for(let u of l?.waiters.slice()??[])Ll(u.identity,c)&&this.drop(o,u,Dl(e));o.queued=this.queue(o,n,r,$p(s,a,r,i,c),l?.waiters??[]),o.wake?.(),this.pump(e,o);})}holdOwn(e,n){let{signal:r}=n,i=n.deadlineAt-Date.now();if(r?.aborted)return this.drop(e,n,vr(r));if(i<=0)return this.drop(e,n,this.timeout("save",n.budget));let o=AbortSignal.timeout(i),s=()=>this.drop(e,n,this.timeout("save",n.budget)),a=()=>{r&&this.drop(e,n,vr(r));};o.addEventListener("abort",s,{once:true}),r?.addEventListener("abort",a,{once:true}),n.detach=()=>{o.removeEventListener("abort",s),r?.removeEventListener("abort",a);};}drop(e,n,r){let i=e.queued?.waiters,o=i?.indexOf(n)??-1;o>=0&&i?.splice(o,1),n.reject(r),e.wake?.();}queue(e,n,r,i,o){let{budget:s}=i,a=[...o,i],l=AbortSignal.timeout(s),d=g=>{if(e.queued===p){this.take(e,p);for(let f of a)f.reject(g);e.wake?.();}},c=()=>d(this.timeout("save",s)),u=()=>{r.signal&&d(vr(r.signal));};l.addEventListener("abort",c,{once:true}),r.signal?.addEventListener("abort",u,{once:true});let p={bytes:n,options:r,budget:s,deadlineAt:i.deadlineAt,identity:i.identity,waiters:a,release:()=>{l.removeEventListener("abort",c),r.signal?.removeEventListener("abort",u);}};return p}async pump(e,n){if(!n.running){n.running=true;try{for(let r=n.queued;r!==void 0;r=n.queued){let i=Date.now(),o=this.holdUntil-i;if(o>0){if(o>=r.deadlineAt-i){this.take(n,r);for(let l of r.waiters)l.reject(this.held(e,o));continue}for(let l of r.waiters.slice(0,-1))o>=l.deadlineAt-i&&this.drop(n,l,this.held(e,o));}let s=Math.max(o,this.spacing(n,r,i));if(s>0){await this.pause(n,s);continue}this.take(n,r);let a;try{a=this.precondition(e,r);}catch(l){for(let d of r.waiters)d.reject(l);continue}n.lastSentAt=i;try{let l=await this.send(e,r,a);for(let d of r.waiters)d.resolve(l);}catch(l){for(let d of r.waiters)d.reject(l);}}}finally{n.running=false;}}}spacing(e,n,r){if(e.lastSentAt===void 0||n.waiters.some(s=>s.teardown))return 0;let i=this.options.minWriteIntervalMs??Ip,o=Math.min(...n.waiters.map(s=>s.deadlineAt-s.budget/2));return Math.min(e.lastSentAt+i,o)-r}pause(e,n){return new Promise(r=>{let i=()=>{clearTimeout(o),e.wake===i&&(e.wake=void 0),r();},o=setTimeout(i,Math.min(n,Cp));e.wake=i;})}take(e,n){e.queued===n&&(e.queued=void 0),n.release();}slotWrites(e){let n=this.writes.get(e);return n===void 0&&(n={running:false,queued:void 0,lastSentAt:void 0,wake:void 0},this.writes.set(e,n)),n}noteRateLimit(e){if(!Ol(e))return;let n=e.retryAfterSeconds,r=n===void 0?Il:Math.min(n*1e3,Il);this.holdUntil=Math.max(this.holdUntil,Date.now()+r);}held(e,n){let r=Math.ceil(n/1e3);return new M("rate_limited",429,`save ${JSON.stringify(e)} was not sent: the platform refused a save call for the rate, and the wait it asked for ends in ${r}s, after this call's timeoutMs. Keep the state and write once the wait is over.`,r)}async send(e,n,r){let{bytes:i,options:o,budget:s}=n,a=o.contentType??"application/octet-stream",l=Ml(o.signal,Math.max(0,n.deadlineAt-Date.now()));try{let d=await gl(this.api,this.entity.type,this.entity.id,e,{size_bytes:i.byteLength,content_type:a,...r,...o.metadata===void 0?{}:{metadata:o.metadata}},{signal:l.signal});if(typeof d.upload_url!="string"||typeof d.session_id!="string")throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let c=Lp(d.upload_headers,e),u,p=this.options.fetch??globalThis.fetch.bind(globalThis);try{u=await p(d.upload_url,{method:"PUT",headers:{"content-type":a,...c},body:i,credentials:"omit",signal:l.signal});}catch(f){throw Ui(l.signal,o.signal)?this.timeout("upload",s):new ie("upload_failed",`${Cl} for PUT. Underlying error: ${f}`)}if(u.status===429)throw await Gl("upload",u);if(!u.ok){let f=await br(u);throw new ie("upload_failed",u.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+f:`the save upload answered ${u.status}. `+(u.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+f)}let g=Wi(await Ss(this.api,this.entity.type,this.entity.id,e,{session_id:d.session_id},{signal:l.signal}));return this.remember(e,g.etag?{kind:"etag",etag:g.etag}:void 0),g}catch(d){throw Dp(d)?new ie("save_conflict",`save ${JSON.stringify(e)} was not written: the stored save changed since this game last loaded or wrote it, so another device or tab saved in between. Load it again and decide what to write from what is stored, rather than resending this write.`):(this.noteRateLimit(d),this.rethrow(d,o.signal,l.signal,"save",s))}finally{l.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(i){throw new ie("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${i}`)}}async getBytes(e,n={}){qe(e);let r=this.budget(n.timeoutMs),i=Ml(n.signal,r),o=this.seq;try{let s;try{let c=await Gi(this.api,this.entity.type,this.entity.id,e,{signal:i.signal});if(!c.modified)return this.remember(e,{kind:"empty"},o),null;s=c.body;}catch(c){if(Hi(c))return this.remember(e,{kind:"empty"},o),null;throw c}if(typeof s.download_url!="string")throw new ie("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),l;try{l=await a(s.download_url,{credentials:"omit",signal:i.signal});}catch(c){throw Ui(i.signal,n.signal)?this.timeout("download",r):new ie("download_failed",`${Cl} for GET. Underlying error: ${c}`)}if(l.status===429)throw await Gl("download",l);if(!l.ok){let c=await br(l);throw new ie("download_failed",`the save download answered ${l.status}. `+(l.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+c)}let d=new Uint8Array(await l.arrayBuffer());return this.remember(e,s.etag?{kind:"etag",etag:s.etag}:void 0,o),d}catch(s){throw this.slots().get(e)===void 0&&this.remember(e,{kind:"failed"}),this.noteRateLimit(s),this.rethrow(s,n.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,n={}){try{let r=await Gi(this.api,this.entity.type,this.entity.id,qe(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Wi(r.body):null}catch(r){if(Hi(r))return null;throw r}}async list(e={}){let n=await nl(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(Wi),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await vs(this.api,this.entity.type,this.entity.id,qe(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Hi(r))throw r}this.remember(e,{kind:"empty"});}precondition(e,n){if(Ll(n.identity,this.identity?.()??null))throw Dl(e);if(n.waiters.some(i=>i.overwrite))return {};let r=this.slots().get(e);if(r===void 0)return {};if(r.kind==="etag")return {if_match:r.etag};if(r.kind==="empty")return {if_none_match:"*"};throw new ie("load_failed",`save ${JSON.stringify(e)} was not written: the last load of this slot failed, so what this write would replace is unknown, and it could be the player's real progress. Load it again before saving, or pass overwrite: true if replacing whatever is stored is what you mean.`)}remember(e,n,r){let i=this.slots(),o=i.get(e);r!==void 0&&o!==void 0&&o.kind!=="failed"&&o.seq>r||(this.seq+=1,n===void 0?i.delete(e):i.set(e,{...n,seq:this.seq}));}slots(){let e=this.identity?.()??null;return e!==null&&e!==this.versionsOf&&(this.versionsOf!==null&&this.versions.clear(),this.versionsOf=e),this.versions}budget(e){return e??this.options.timeoutMs??Ep}timeout(e,n){return new ie("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,i,o){return e instanceof ie||Ol(e)?e:Ui(r,n)?this.timeout(i,o):e}};function Fp(t){try{return Oi(t)}catch{return t}}function Vi(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"?Fp(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var wr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await el(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>Vi(i)):[]}async get(e,n={}){try{let r=await Ps(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?Vi(r.body,r.etag):null}catch(r){if($l(r))return null;throw r}}async put(e,n,r={}){let i=await dl(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 Vi(i)}async delete(e,n){try{await bs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!$l(r))throw r}}};function $l(t){return t?.reason==="not_found"}function Sr(t,e,n={}){let r=new yr(ue,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let i=new cr(t,e,r);return {settings:new wr(t,e),inventory:i,saves:new _r(t,e,n.saves??{},n.identity),currencies:new dr(i,n.resolveCurrencyId),mutations:new pr(t,e,r),orders:new gr(t,e),progressions:new fr(t,e,i)}}var Ki={type:"players",id:"me"};var it=t=>typeof t=="string"?t:"",At=t=>typeof t=="number"?t:0;function kr(t,e){let n=e??{},r=it(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:it(n.player_id),gameId:it(n.game_id),channel:it(n.channel)||"release",name:it(n.name),slotIndex:At(n.slot_index),isActive:n.is_active!==false,createdAt:it(n.created_at),updatedAt:it(n.updated_at)}}var Rr=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=Sr(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 Zs(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>kr(this.scope,i)):[]}async get(e,n){let r=await As(this.api,e,n===void 0?{}:{signal:n});return kr(this.scope,r)}async create(e){let n=await gs(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return kr(this.scope,n)}async update(e,n,r){let i=await pl(this.api,e,{name:n},r===void 0?{}:{signal:r});return kr(this.scope,i)}async delete(e,n){await yl(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await Hs(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:At(r?.total_slots),availableSlots:At(r?.available_slots),activeCharacterCount:At(r?.active_character_count),defaultMaxSlots:At(r?.default_max_slots),purchasedExtraSlots:At(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var Nl="[gem: use gem.text.toPlain()]",Fl=new Set,ql;function qp(t){try{if(Fl.has(t))return;let e=globalThis.location;if(ql??=!!e?.port&&Je(e.hostname??""),!ql)return;Fl.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${Nl}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
|
|
2
|
+
${new Error().stack}`);}catch{}}var ve=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return qp(this.#n),Nl}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function he(t,e){return new ve(t,e)}var ot={toPlain(t){return ve.unwrap(t)},compare(t,e,n){let r=t instanceof ve?ve.unwrap(t):t,i=e instanceof ve?ve.unwrap(e):e;if(typeof Intl>"u"||typeof Intl.Collator!="function")return r<i?-1:r>i?1:0;let o;try{o=new Intl.Collator(n);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(t,e){let n=t instanceof ve?ve.unwrap(t):t,r=e instanceof ve?ve.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var xt=t=>typeof t=="string"?t:"";function Ar(t){let e=t??{},n=typeof e.message=="string"&&e.message.length>0?e.message:void 0,r=typeof e.resolved_at=="string"?e.resolved_at:void 0;return {id:xt(e.transfer_id),status:xt(e.status),sourceEntityId:xt(e.source_entity_id),targetEntityId:xt(e.target_entity_id),...n===void 0?{}:{message:he(n,"transfer.message")},createdAt:xt(e.created_at),expiresAt:xt(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Np(){return crypto.randomUUID()}var xr=class{constructor(e,n,r){this.api=e;this.self=n;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let n=await zs(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:Np()},e.signal===void 0?{}:{signal:e.signal});return Ar(n)}async list(e={}){let r=await ol(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(Ar):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await Vs(this.api,e,n===void 0?{}:{signal:n});return Ar(r)}async accept(e,n){return this.resolve(()=>ds(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>ml(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>us(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Ar(await e())}};var jp=t=>typeof t=="string"?t:"",Bp=t=>typeof t=="string"&&t?t:void 0,Up=t=>typeof t=="number"?t:void 0;function jl(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 Wp(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new pe("config_malformed",`the config document is ${t===null?"null":typeof t}, expected a JSON object`);let e=t,n=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new pe("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Up(e.version);if(r===void 0)throw new pe("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,c)=>{let u=jp(l.id);if(!u)throw new pe("config_malformed",`${d}[${c}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},o=n("items");o.forEach((l,d)=>i(l??{},"items",d));let s=n("currencies");s.forEach((l,d)=>i(l??{},"currencies",d));let a=t;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:o,currencies:s,catalogs:n("catalogs"),loot_tables:n("loot_tables"),affix_pools:n("affix_pools"),progressions:n("progressions"),game_room_templates:n("game_room_templates"),kv:typeof a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:jl(o),currency:jl(s)}}var pe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Bl=10*1024*1024,Ul=15e3,Wl=new Set(["dev","test","release"]);function Hp(t){if(!Wl.has(t))throw new pe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Wl].join(", ")}. gem-api would reject the assignment read.`);return t}var Pr=t=>typeof t=="number"?t:0,Ji=t=>typeof t=="string"?t:"";function Vp(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:Ji(i.entry_id),weight:Pr(i.weight),dropRate:Pr(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:Ji(e.loot_table_id),name:Ji(e.name),rollCount:Pr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Pr(e.total_weight),entries:n}}var Tr=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=void 0;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded!==void 0)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,n=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===n&&(this.inFlight=null);});return this.inFlight=n,n}refresh(){this.loaded=void 0,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new pe("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let i=this.dropRatesByConfig.get(r);i===void 0&&(i=new Map,this.dropRatesByConfig.set(r,i));let o=i.get(e);if(o!==void 0)return o;let s=(async()=>{let a=await xs(this.api,e,n===void 0?{}:{signal:n});return Vp(a)})().catch(a=>{throw i?.get(e)===s&&i.delete(e),a});return i.set(e,s),s}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??Ul),n;try{let l=await Rs(this.api,Hp(this.channel()),{signal:e});if(!l.modified)throw new pe("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof pe)throw l;if(l?.reason==="not_found")return null;throw l}let r=Bp(n.config_url);if(r===void 0)return null;let i=this.options.fetch??globalThis.fetch.bind(globalThis),o;try{o=await i(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new pe("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??Ul}ms`):new pe("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!o.ok){let l=await o.text().then(d=>Bi(d)).catch(()=>"");throw new pe("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await o.text();if(s.length>Bl)throw new pe("config_too_large",`the config document is ${s.length} bytes, over the ${Bl} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new pe("config_malformed",`config document is not JSON: ${String(l)}`)}return Wp(a)}};var Hl=400,Ie=t=>typeof t=="string"?t:"",Kp=/(?:Z|[+-]\d{2}:?\d{2})$/i;function at(t){let e=Ie(t);if(!Kp.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Jp=/^[0-9a-f]{1,64}$/,zp=/^[0-9a-f]{16}$/,Xp=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Yp=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function zi(t){let e=Ie(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,i,o]=[Number(n[1]),Number(n[2]),Number(n[3])],s=new Date(Date.UTC(r,i-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===i-1&&s.getUTCDate()===o?e:void 0}var Qp=4096,Zp=new TextEncoder;function eg(t){let e=Ie(t.challenge_data),n=Ie(t.challenge_data_hash);return e===""||!zp.test(n)?{}:Zp.encode(e).length>Qp?{}:{data:e,dataHash:n}}function tg(t){let e=t??{},n=at(e.period_start_at),r=at(e.period_ends_at);if(n===0||r===0)return;let i=Ie(e.slug),o=Ie(e.seed),s=zi(e.period_local_date),a=Ie(e.boundary),l=Ie(e.reset_time);return {id:Ie(e.progression_definition_id),...i===""?{}:{slug:i},window:Ie(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:Xp.test(a)?a:"",resetTime:Yp.test(l)?l:"",seed:Jp.test(o)?o:"",...eg(e)}}function Pt(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function Er(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(tg).filter(n=>n!==void 0):[]}var Qt=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;Pt(n);let r=await Qs(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return Er(r)}};function Ce(t){return typeof t=="string"&&t!==""?t:void 0}var Vl=new Set(["localhost","127.0.0.1","[::1]"]);function st(t){return Tt(t)}function Tt(t){let e=Ce(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&Vl.has(n.hostname)))return e}var ng=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,rg=/^[a-z][a-z0-9_]{0,31}$/;function ig(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let i=r??{},o=Ce(i.family),s=Ce(i.avatar_3d_id),a=st(i.model_url),l=st(i.icon_url);o===void 0||!rg.test(o)||n.has(o)||s===void 0||!ng.test(s)||a===void 0||l===void 0||(n.add(o),e.push({family:o,id:s,modelUrl:a,iconUrl:l}));}return e}function og(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},i=Ce(r.item_id),o=st(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Pe(t){let e=t??{},n=Ce(e.player_id),r=Ce(e.display_name),i=Ce(e.discriminator),o=Ce(e.display_tag),s=Ce(e.avatar_icon_id),a=st(e.avatar_icon_url),l=Ce(e.avatar_3d_id),d=st(e.avatar_3d_model_url),c=st(e.avatar_3d_icon_url),u=ig(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:he(r,"displayName")},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:he(o,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...c===void 0?{}:{avatar3dIconUrl:c},...u===void 0?{}:{avatars3d:u},badges:og(e.badges)}}var ag=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Xi(t){if(t===void 0)return;let e=st(t);if(e===void 0)return;let n=new URL(e);return Vl.has(n.hostname)||ag.has(n.origin)?e:void 0}var Kl=100,Xl=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Yi(t){let{periodsBack:e,period:n,playerId:r}=t;if(Pt(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!Xl.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 Yl(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!Xl.test(e))return;let n=zi(t.period_local_date),r=at(t.period_start_at),i=at(t.period_ends_at),o=r>0&&i>0;return {id:e,...n===void 0?{}:{localDate:n},...o?{startAt:r,endsAt:i}:{},opensAt:at(t.opens_at),closesAt:at(t.closes_at),final:t.final===true}}var Zt=t=>typeof t=="string"?t:"",Et=t=>typeof t=="number"?t:0,en=t=>typeof t=="string"?t:void 0,sg=t=>typeof t=="number"?t:void 0,Ql={player:"players",character:"characters"};function lg(t,e){let n=t??{},r=en(n.entity_id),i=typeof n.entity_type=="string"&&Object.hasOwn(Ql,n.entity_type)?n.entity_type:void 0,o=Zl(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...Pe(n),rank:Et(n.rank),occurredAt:Et(n.occurred_at),...a===void 0?{}:{isViewer:a},...r===void 0?{}:{entityId:r},...i===void 0?{}:{entityType:i},...o===void 0?{}:{stats:o},...s===void 0?{}:{properties:s}}}function Jl(t,e){let n=t??{},r=en(n.bucket_1),i=en(n.bucket_2),o=sg(n.update_frequency_seconds),s=Yl(n);return {leaderboardType:Zt(n.leaderboard_type),runType:Zt(n.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(n.entries)?n.entries.map(a=>lg(a,e)):[],generatedAt:Et(n.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function zl(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=Zl(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:Et(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function Zl(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 dg(t,e,n){let r=t??{},i=en(r.bucket_1),o=en(r.bucket_2),s=Yl(r);return {leaderboardType:Zt(r.leaderboard_type),runType:Zt(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(zl).filter(a=>a!==void 0):[],personalBest:zl(r.personal_best)??null,totalRuns:Et(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:Et(r.generated_at),...s===void 0?{}:{period:s}}}var tn=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Yi(n),i=await qs(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 Jl(i,false)}async friends(e,n={}){let r=Yi(n),i=await Ls(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 Jl(i,true)}async mine(e,n={}){return this.#n(e,"player","me",n)}async character(e,n,r={}){return this.#n(e,"character",n,r)}async#n(e,n,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>Kl)throw new TypeError(`limit must be an integer between 1 and ${Kl}, got ${String(l)}`)}let o=Yi(i),s=await Is(this.#e,e,Ql[n],r,{...o,...i.bucket1===void 0?{}:{bucket_1:i.bucket1},...i.bucket2===void 0?{}:{bucket_2:i.bucket2},...i.limit===void 0?{}:{limit:i.limit},...i.signal===void 0?{}:{signal:i.signal}}),a=n==="player"&&r==="me"&&Zt((s??{}).entity_id)||r;return dg(s,n,a)}};var Ir=t=>typeof t=="string"?t:"",Qi=t=>typeof t=="number"?t:0;function ed(t){let e=t??{};return {playerId:Ir(e.player_id),key:Ir(e.key),value:e.value,updatedAt:Qi(e.updated_at)}}function cg(t){let e=t??{};return {...Pe(e),playerId:Ir(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Qi(e.updated_at)}}function ug(t){return t?.reason==="not_found"}var nn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let i=await Ds(this.api,qe(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:Ir(i.key),entries:Array.isArray(i.entries)?i.entries.map(cg):[],generatedAt:Qi(i.generated_at)}}async of(e,n,r={}){try{return ed(await Ws(this.api,e,qe(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(ug(i))return null;throw i}}async set(e,n,r={}){if(qe(e),n===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(n);}catch(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 ed(await cl(this.api,i,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await _s(this.api,r,qe(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var mg="gemChallenge",td=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function nd(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(mg)??void 0}catch{return}}var lt=class extends M{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(n))i!==void 0&&Object.assign(this,{[r]:i});}},Cr=t=>typeof t=="string"?t:void 0;function rd(t){let e=t??{};return {...Pe(e),playerId:Cr(e.player_id)??""}}function id(t){let e=t.has_more===true?Cr(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function pg(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(rd):[],...id(e)}}var Zi=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function gg(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 od(t){let e=t??{},n=Zi(e.opened_at),r=Zi(e.answered_at);return {id:Cr(e.item_id)??"",from:rd(e.sender),template:Cr(e.template)??"",params:gg(e.params),createdAt:Zi(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function fg(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(od):[],...id(e)}}function yg(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var rn=class{#e;#n;#o;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#o=n.launchedChallengeId;}async list(e={}){let n=await il(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return pg(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await rl(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return fg(n)}async launchedChallenge(e={}){let n=this.#o;if(n===void 0||!td.test(n))return null;try{return od(await Fs(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(yg(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!td.test(e))throw new M("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await al(this.#e,e);}};var hg=0;function _e(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++hg)}-${String(Date.now())}-${t}`}}var bg=12e4,ad=8,vg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,_g=/^[a-z0-9][a-z0-9_-]{0,63}$/;function on(t,e,n={}){return new lt(new M("invalid",400,e,void 0,t),n)}function wg(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Sg(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!vg.test(e))return {error:on("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!_g.test(n))return {error:on("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(!wg(r))return {error:on("param_invalid","params must be a plain object of strings and integers")};let i={},o=Object.keys(r);for(let s of o){let a=r[s];if(typeof a=="string"||typeof a=="number"&&Number.isSafeInteger(a)){Object.defineProperty(i,s,{value:a,enumerable:true,writable:true,configurable:true});continue}return {error:on("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>ad?{error:on("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(ad)}`)}:{playerId:e,template:n,params:i}}function kg(t){switch(t.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:t.outcome}};case "rate_limited":{let e=t.retryAfterMs,n=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new lt(new M("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new lt(new M("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function Rg(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function sd(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=Sg(n);if("error"in r)return Promise.reject(r.error);let i=`challenge-${_e()}`;return new Promise((o,s)=>{let a={},l=c=>{e.delete(i)&&(t.clock.clearTimeout(a.timer),"error"in c?s(c.error):o(c.outcome));};e.set(i,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??bg);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 (${Rg(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(kg(n));}}}var Mr=t=>typeof t=="string"?t:void 0;function Ag(t){let e=t??{},n=Mr(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Mr(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Or=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await nr(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=Ag(o);s!==void 0&&i.push(s);}return i}},eo=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function xg(t){let e=t??{},n=Mr(e.currency_id);if(n===void 0||n==="")return;let r=eo(e.limit),i=Math.min(eo(e.earned),r),o=Math.min(eo(e.remaining),r-i),s=e.period_days,a=typeof s=="number"&&Number.isInteger(s)&&s>=1?s:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Mr(e.currency_slug)??"",currencyId:n,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function ld(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 Gr=class{#e;#n;#o;constructor(e,n,r){this.#e=e,this.#n=n,this.#o=r;}async get(e={}){let r=(await Ns(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=xg(o);s!==void 0&&i.push(s);}return i}on(e,n){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},an=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Or(e),this.earnAllowance=new Gr(e,n,r);}};var to=t=>typeof t=="string"?t:"",dd=t=>typeof t=="number"?t:0;function Pg(t){let e=t??{};return {key:to(e.key),visibility:to(e.visibility),value:e.value,updatedAt:dd(e.updated_at)}}function Tg(t){let e=t??{};return {...Pe(e),playerId:to(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Pg):[],generatedAt:dd(e.generated_at)}}function Eg(t){return t?.reason==="not_found"}var sn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return Tg(await js(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Eg(r))return null;throw r}}};var Ig=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]]),ln=class extends M{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:Ig.get(this.code))??super.retryable}},Xe=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Cg(e),i;try{i=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(o){throw o instanceof M?Og(o):o}return Mg(i)}};function Cg(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let e;try{e=JSON.stringify(t);}catch(n){throw new se(`the function input could not be serialised to JSON: ${String(n)}. Pass bytes, or a value JSON can carry. This is a bug in the call, not a server failure.`)}if(e===void 0)throw new se(`the function input is ${typeof t}, which JSON cannot carry. Pass bytes \u2014 an empty Uint8Array for no input \u2014 or a JSON value. This is a bug in the call, not a server failure.`);return new TextEncoder().encode(e)}function Mg(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 Og(t){let{details:e,invocationId:n}=as(t),i=e?.untrusted?.message,o=e?.reason;return new ln(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...t.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}function Lr(t,e){let n=e?.retryAfterSeconds,r=typeof n=="number"&&Number.isFinite(n)&&n>0?n*1e3:0,i=1e4*2**Math.min(Math.max(0,t-1),16);return Math.min(Math.max(r,i),3e5)}var Gg=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],no="gem_";function ro(t){return t.startsWith(no)}function Lg(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function Dg(t){let e=t;return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^=e>>>16,e>>>0}function Dr(t,e,n){if(io(t,n),typeof e!="string"||e==="")throw new TypeError("[gem] experiment: playerId must be a non-empty string");let r=typeof n=="number"?n:n.length,i=Dg(Lg(`${t}:${e}`))%r;return typeof n=="number"?i:n[i]}function io(t,e){if(typeof t!="string"||t==="")throw new TypeError("[gem] experiment: key must be a non-empty string");if(typeof e=="number"){if(!Number.isInteger(e)||e<1||e>2048)throw new RangeError(`[gem] experiment '${t}': the count must be an integer from 1 to 2048; got ${String(e)}`);return}if(!Array.isArray(e))throw new TypeError(`[gem] experiment '${t}': pass a count or a list of strings; got ${typeof e}`);let n=e;if(n.length<1||n.length>2048)throw new RangeError(`[gem] experiment '${t}': the list must hold 1 to 2048 strings; got ${n.length}`);if(!n.every(r=>typeof r=="string"))throw new TypeError(`[gem] experiment '${t}': every option must be a string`)}var cd=1e4,ud=50,$g=500,Fg=65536-4*1024,qg=24*1024;function md(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 Ng=6e4;function jg(t){let e=new Map;for(let n of t??[]){let r=new Set;for(let[i,o]of Object.entries(n.dimensions??{})){let s=o?.range;typeof s=="object"&&s!==null&&r.add(i);}r.size>0&&e.set(n.id,r);}return e}function Bg(t,e){if(e===void 0)return t;let n=null,r={};for(let[i,o]of Object.entries(t.measures))e.has(i)?(n??={...t.dimensions})[i]=String(o):r[i]=o;return n===null?t:{dimensions:n,measures:r}}var pd=t=>typeof t=="number"?t:0,Ug=t=>typeof t=="string"?t:"";function $r(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function Wg(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:pd(o.index),code:Ug(o.code)}}):[];return {accepted:pd(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function oo(){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 Hg(t){return t?.retryable===true}var dn=class{#e;#n;#o;#h;#t=[];#b={};#a=0;#s=null;#v=false;#_=false;#m=0;#w=0;#S=0;#r=false;#k=null;#l=null;#c=false;#i=false;#p=false;#R=false;#A=false;#g=void 0;#x=false;#P=0;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#o=Math.max(cd,e.options?.flushIntervalMs??cd),this.#h=Math.max(1,Math.floor(e.options?.maxQueue??$g));}track(e,n={}){if(!this.#n||this.#r)return;if(ro(e)){this.#A||(this.#A=true,this.#y(`[gem] analytics: '${e}' was not recorded \u2014 the gem_ prefix is reserved for the platform's own events, which the SDK emits for you. Name your event something else.`));return}this.#T(e,md({...this.#b,...n}));let r=this.#C();this.#g===void 0&&!this.#x&&r!==null&&r!==""&&(this.#x=true,this.#M());}setContext(e){this.#b={...this.#b,...e};}async experiment(e,n){io(e,n);let r=this.#e.awaitPlayerId===void 0?this.#e.playerId():await this.#e.awaitPlayerId();if(r===null)throw new Error(`[gem] experiment '${e}': no player to select for \u2014 this call was not made by a player.`);return typeof n=="number"?Dr(e,r,n):Dr(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return $r();let n=this.#C();if(n===null||n==="")return this.#t.length>0&&!this.#R&&(this.#R=true,this.#y("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),$r();let r=e.keepalive===true;if(!r&&this.#e.declarations!==void 0&&this.#t.some(d=>!ro(d.name))&&await this.#M(),this.#I(),this.#t.length===0||this.#m>0&&!r)return $r();this.#u();let i=this.#t.splice(0,this.#G(r)),o=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:oo(),sent_at_ms:s,events:i.map(d=>gd(d,s,this.#g?.get(d.name)))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await Js(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),c=Wg(d,o);return this.#w=0,this.#S=0,this.#L(c),c}catch(d){throw Hg(d)?(this.#O(i,o),this.#w+=1,this.#S=this.#e.clock.now()+Lr(this.#w,d)):this.#y(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#m-=1,this.#t.length>0&&this.#d();}}trackPlatform(e,n={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#T(e,md(n));}hold(){this.#r||this.#l!==null||(this.#i=true,this.#u());}release(){if(!this.#i||this.#r)return;this.#i=false;let e=this.#e.clock.now(),n=this.#t.map(r=>({...r,atMs:e}));this.#t=n,this.#p&&(this.#p=false,this.#l=e,this.#c=false,this.#t.unshift({uid:oo(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=ud?this.#f():this.#t.length>0&&this.#d();}get held(){return this.#i}startSession(){if(!(this.#r||this.#l!==null)){if(this.#i){this.#p=true;return}this.#l=this.#e.clock.now(),this.#c=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#c)return;if(this.#c=true,this.#i){this.#p=false,this.#t=[],this.#a=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#f({keepalive:true});}setPaused(e){this.#r||e===this.#v||(this.#v=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#_||(this.#_=e,e?this.#u():this.#t.length>0&&this.#d());}dispose(){this.#r=true,this.#u(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#T(e,n){let{dimensions:r,measures:i}=n;for(this.#I();this.#t.length>=this.#h;)this.#t.shift(),this.#a+=1;this.#t.push({uid:oo(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=ud?this.#f():this.#d();}#f(e={}){if(e.keepalive!==true&&this.#E()>0){this.#d();return}this.flush(e).catch(()=>{});}#E(){return Math.max(0,this.#S-this.#e.clock.now())}#O(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#h;)this.#t.shift(),this.#a+=1;}#G(e){let n=e?qg:Fg,r=Math.min(this.#t.length,100),i=128;for(let o=0;o<r;o+=1){let s=this.#t[o];if(s===void 0)break;if(i+=JSON.stringify(gd(s,0,this.#g?.get(s.name))).length+1,i>n)return Math.max(1,o)}return r}#d(){this.#s!==null||this.#v||this.#_||this.#i||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#f();},Math.max(this.#o,this.#E())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#I(){let e=this.#D();e===null||e===""||(this.#k!==null&&this.#k!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#k=e);}#L(e){for(let n of e.rejected)this.#y(`[gem] analytics: an event was refused (${n.code}). `+Vg(n.code));}#y(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#C(){try{return this.#e.gameId()}catch{return null}}#D(){try{return this.#e.playerId()}catch{return null}}async#M(){let e=this.#e.declarations;if(e!==void 0&&!(this.#e.clock.now()<this.#P))try{this.#g=jg(await e());}catch{this.#P=this.#e.clock.now()+Ng;}}};function gd(t,e,n){let{dimensions:r,measures:i}=Bg(t,n);return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:r,measures:i}}function Vg(t){switch(t){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function be(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function cn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=be(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Kg=2e3,Jg=5e3;function yd(t){let e=[],n=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let s,a=new Promise(l=>{let d=false,c=null;s=u=>{d||(d=true,r=null,t.clock.clearTimeout(c),l(u));},c=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??Kg);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !fd(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=c=>{i.delete(d)&&(t.clock.clearTimeout(l),a(c));};i.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??Jg);})},accept(s,a){let l=cn(a),d=be(s),c=l.length>0?l:d===void 0?[]:[d];if(c.length!==0){e=c,r?.settle(c);for(let[u,p]of [...i])fd(c,p)||u(c);}}}}function fd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var zg=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),w=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="DedicatedServerError",this.retryable=zg.has(n),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var hd=["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"],Xg=new Set(hd);function Ye(t){return typeof t=="string"&&Xg.has(t)?t:"unknown"}var Fr="webrtc_dedicated",co=["universal","mobile","web"];var Yg="p2p_unavailable",Qg="capacity_unavailable",Zg=2,bd=3e4,vd=1e3,_d=2e4;async function uo(t){let e=be(t.clusterTargetId),n=t.nextClusterTarget,r=0,i=t.clock??ue,o=t.retry??{},s=o.budgetMs??bd,a=o.maxDelayMs??_d,l=o.initialDelayMs??vd,d=i.now(),c=d+s,u=0;for(;;){u++;try{let p=await fo(t.signal,"while allocating",()=>t.client.post(`${kd(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!ef(p)||s<=0)throw p;if(p.status===503&&p.code===Yg)throw new w("p2p_unavailable",`room ${t.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});if(r=p.code===Qg?r+1:0,n!==void 0&&r>=Zg){let x=n;n=void 0;let P=be(await x());P!==void 0&&(e=P,r=0);}let g=Math.min(a,l*2**(u-1)),f=Math.min(a,(p.retryAfterSeconds??0)*1e3),k=Math.max(g/2,f)+Math.random()*(g/2);if(i.now()+k>c)throw tf(t,p,u,i.now()-d,s);if(o.onWaiting?.({attempt:u,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:k,status:p.status,message:p.message}),await qr(i,k,t.signal),t.signal?.aborted)throw lo("while waiting to allocate")}}}function ef(t){return t instanceof M?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function tf(t,e,n,r,i){let o=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new w("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${o}: ${e.message}`,{cause:e}):new w("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${o}: ${e.message}`,{cause:e})}var nf=12e4,rf=1e3;async function mo(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??rf,i=t.timeoutMs??nf,o=e.now()+i,s=wd(t),a={seen:t.knownToExist===true};for(;;){let l=await Sd(t,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new w("timeout",`match ${n} was still ${l.status} after ${i}ms`);await qr(e,r,t.signal);}}async function po(t){return (await Sd(t,wd(t),{seen:t.knownToExist===true})).outcome}function wd(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${kd(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Sd(t,e,n){let{matchId:r}=t,i=t.clock.now(),o;try{o=await fo(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof M&&s.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(n.seen=true,o.status==="ready")return {status:"ready",outcome:of(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Ye(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function go(t){let e=await fo(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 fo(t,e,n){if(t?.aborted)throw lo(e);try{return await n()}catch(r){throw t?.aborted?lo(e,r):r}}function lo(t,e){return new w("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function of(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 kd(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function qr(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{t.clearTimeout(o),n?.removeEventListener("abort",i),r();},o=t.setTimeout(i,e);n?.addEventListener("abort",i);})}function Rd(t){return typeof t=="string"&&t.trim()!==""}function Nr(t,e){return Rd(t)?t.trim():Rd(e)?e:null}var jr="0.1.0-beta",Ad="0-beta",It="web",af=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;function sf(t){let e=af.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function xd(t,e){let n=lf(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:jr};let i=sf(r);if(i===null)throw new w("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${jr}' for it.`);if(i!==Ad)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Ad}' 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 '${jr}' for it.`);return {...t,platform:n,engineVersion:r}}function lf(t,e){if(t===void 0||t===It)return It;if(!co.includes(t))throw new w("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${co.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${It}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${It}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),It}function un(t){let e=t??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let n=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:Pd(e.queued_at),expiresAt:Pd(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function Pd(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var df=3,Td=1e3,Br=class{constructor(e){this.options=e;this.snapshot=e.first;let n=new Promise((o,s)=>{this.resolve=o,this.reject=s;});n.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:n,cancel:()=>(this.requestCancel(),n)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let n=e?Td:Math.max(Td,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},n);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,n=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){n=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(n);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof M&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<df){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof M&&e.code==="matchmaking_unavailable";this.settle({status:n?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let n=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:n});}catch(n){this.busy=false,this.fail(n);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var cf="gemPlayWith",uf=/^[A-Za-z0-9_-]{16,128}$/;function Ed(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(cf);}catch{return}return e!==null&&uf.test(e)?e:void 0}function Id(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var mf="join",pf="welcome",gf="rejected",Cd=25e3,ff=1e3,yo=1;function ho(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var yf={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 bo(t){let e=typeof t=="string"?t:"unknown";return new w(yf[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function mn(t){let{channel:e,clock:n}=t;return new Promise((r,i)=>{let o=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Cd),a=n.setTimeout(()=>h(new w("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,ff)),l=k=>{let x=k.data;if(typeof x!="string"){u(x);return}let P;try{P=JSON.parse(x);}catch{u(x);return}if(o){u(x);return}if(P.t===pf){let b=ho(P.heartbeat_interval);f({...typeof P.player_id=="string"?{playerId:P.player_id}:{},...typeof P.match_id=="string"?{matchId:P.match_id}:{},...b===void 0?{}:{heartbeatIntervalMs:b}});return}if(P.t===gf){h(bo(P.reason));return}u(x);},d=()=>{h(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},c=()=>{h(new w("aborted","the caller aborted during the join exchange"));},u=k=>{o&&t.onMessage?.(k);},p=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",c);},g=()=>{e.removeEventListener("message",l);},f=k=>{o=true,p(),t.onMessage===void 0&&g(),r({welcome:k,detach:g});},h=k=>{o||(o=true,p(),g(),i(k));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){c();return}t.signal?.addEventListener("abort",c);try{e.send(JSON.stringify({t:mf,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:yo}:{}}));}catch(k){h(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(k)}`,{cause:k}));}})}var dt=1,pn=2,vo=4,So=8,hf=2,bf=1e3,ko="heartbeat timeout",gn="gem-uu",Ur=2,Od="gem_transports";function Ct(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!vf(r)||e.includes(r)||e.push(r);}return e}function vf(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function fn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Od];if(typeof n!="object"||n===null)return null;let r=n;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function Wr(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Gd=new TextEncoder,Ld=new TextDecoder;function Ro(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function Ao(t){let e=0;return t?.reliable===false&&(e|=dt),t?.ordered===false&&(e|=pn),e}function xo(t){return {reliable:(t&dt)===0,ordered:(t&pn)===0}}var Po={reliable:true,ordered:true};function Dd(t){return JSON.stringify({t:"join",credential:t,wire:Ur,heartbeat:yo})}function $d(t){let e;try{e=JSON.parse(t);}catch{throw new w("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=ho(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"?bo(e.reason):new w("join_refused","the server answered the join out of protocol")}function Hr(){return typeof globalThis.WebTransport=="function"&&To===null}function Vr(){return To}var To=null;var Md="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function _f(t){let e=tr(t);if(e.byteLength!==32)throw new w("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var _o=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new w("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function wo(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 yn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new w("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new a(t.url):new a(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:_f(t.certHashBase64)}]});}let r=n,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(To=Md,i(new w("connection_failed",`${Md}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new w("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return i(new w("connection_failed","the session ended before the control stream arrived"));let d=l.value,c=d.writable.getWriter();await c.write(wo(vo,Gd.encode(Dd(t.credential))));let u=new _o,p=d.readable.getReader(),g;for(;g===void 0;){let f=await Promise.race([p.read(),s]);if(f.done||f.value===void 0)return i(new w("connection_failed","the control stream closed before the join was answered"));for(let h of u.push(f.value)){g=$d(Ld.decode(h.payload));break}}return {link:wf(r,c,p,u,t.log??(f=>console.warn(f)),qd(g,t.clock)),welcome:g}}catch(a){return i(a)}}function wf(t,e,n,r,i,o){let s,a,l=false,d=f=>{if(!l){l=true,c.stop();try{t.close();}catch{}a?.(f);}},c=Io(o,()=>d(ko)),u=(f,h)=>{c.heard(),(f&So)===0&&s!==void 0&&((f&vo)!==0?s(Ld.decode(h),Po):s(h,xo(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let h of r.push(f.value))u(h.flags,h.payload);}}catch{}d("stream closed");})();let p,g;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let h=f.readable.getReader();g=f.writable.getWriter(),p=f,(async()=>{try{for(;;){let k=await h.read();if(k.done||k.value===void 0)break;let x=k.value;x.byteLength!==0&&u((x[0]??0)|dt|pn,x.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){p=void 0,g=void 0,i(`[gem] webtransport datagram lane unusable (${Wr(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(Fd(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,h){if(l)return;if(typeof f=="string"){e.write(wo(vo,Gd.encode(f))).catch(()=>d("write failed"));return}let k=Ao(h);if((k&dt)!==0&&g!==void 0){let x=Ro(k,f),P=p?.maxDatagramSize;if(P===void 0||x.byteLength<=P){g.write(x).catch(()=>{});return}}e.write(wo(k,f)).catch(()=>d("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){d("closed");}}}function Eo(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new w("connection_failed","this environment has no WebSocket"));n=new i(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),o(g));},d=()=>{r.send(Dd(t.credential));},c=g=>{if(s)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let f;try{f=$d(g.data);}catch(h){l(h);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",c),r.removeEventListener("close",u),r.removeEventListener("error",p),i({link:Sf(r,qd(f,t.clock)),welcome:f});},u=()=>{l(new w("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new w("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",c),r.addEventListener("close",u),r.addEventListener("error",p),r.readyState===1&&d();})}function Fd(t){return typeof t=="string"&&t.length>0?t:void 0}function qd(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function Io(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,bf)*hf,i=n.now(),o=null,s=()=>{o=null;let a=n.now()-i;if(a>=r){e();return}o=n.setTimeout(s,r-a);};return o=n.setTimeout(s,r),{heard:()=>{i=n.now();},stop:()=>{o!==null&&(n.clearTimeout(o),o=null);}}}function Sf(t,e){let n,r,i=false,o=a=>{if(!i){i=true,s.stop();try{t.close();}catch{}r?.(a);}},s=Io(e,()=>o(ko));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,Po);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&So)===0&&n?.(l.slice(1),xo(d));})),t.addEventListener("close",(a=>o(Fd(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){t.send(a);return}t.send(Ro(Ao(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){o("closed");}}}function Co(t,e,n,r){let i,o,s=false,a=n,l=u=>{if(!s){s=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}o?.(u);}},d=Io(r,()=>l(ko)),c=(u,p)=>{if(d.heard(),typeof u=="string"){i?.(u,Po);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let f=g[0]??0;(f&So)===0&&i?.(g.slice(1),xo(f|p));};if(t.addEventListener("message",(u=>c(u.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(p=>c(p.data,dt|pn))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,p){if(s)return;if(typeof u=="string"){t.send(u);return}let g=Ao(p),f=Ro(g,u);if((g&dt)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}t.send(f);},onMessage(u){i=u;},onClose(u){o=u;},close(){l("closed");}}}function Nd(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let i=Mo(r);i!==void 0&&(e[n]=i);}return e}function jd(t){if(Array.isArray(t))return t.map(kf).filter(e=>!!e)}function Mo(t){if(Oo(t)||Array.isArray(t)&&t.every(Oo))return t}function Oo(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function kf(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Mo(e.fixed),r=Mo(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...Mt("description",Rf(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Oo)?{allowed:e.allowed}:{},...Mt("min",hn(e.min)),...Mt("max",hn(e.max)),...Mt("minItems",hn(e.min_items)),...Mt("maxItems",hn(e.max_items)),...Mt("maxLength",hn(e.max_length))}}function Rf(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 Mt(t,e){return e===void 0?{}:{[t]:e}}function Ne(t){let e=t??{},n=Q(e.id)??Q(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(Af):[];return {id:n,gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:Me(e.max_players)??0,memberCount:Me(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...Re("joinCode",Q(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...Re("roomArgs",Nd(e.room_args)),...Re("roomArgsTemplate",jd(e.room_args_template)),gameChannel:Q(e.game_channel)??"release",...Re("region",Q(e.region)),...Re("clusterTargetId",Q(e.cluster_target_id)),selfHosted:e.self_hosted===true,...Re("matchId",Q(e.match_id)),version:Me(e.version)??0,...Re("templateId",Q(e.template_id)),...Re("templateSlug",Q(e.template_slug)),roomType:Q(e.game_room_type)??"Standard",...Re("transports",Ct(e.transports)??void 0),createdAt:Me(e.created_at)??0,updatedAt:Me(e.updated_at)??0,...Re("startedAt",Me(e.started_at))}}function Af(t){let e=t??{};return {...Pe(e),playerId:Q(e.player_id)??"",isReady:e.is_ready===true,role:Q(e.role)??"member",joinedAt:Me(e.joined_at)??0,...Re("groupId",Q(e.group_id)),...Re("platform",Q(e.platform))}}function Go(t){let e=t??{};return {id:Q(e.id)??Q(e.game_room_id)??"",gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:Me(e.max_players)??0,memberCount:Me(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Q(e.game_channel)??"release",roomType:Q(e.game_room_type)??"Standard",createdAt:Me(e.created_at)??0}}function Q(t){return typeof t=="string"&&t.length>0?t:void 0}function Me(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Re(t,e){return e===void 0?{}:{[t]:e}}var Kr=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(Go),...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(Go)}))}create(e,n,r){return Pf(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},...bn(n)},e.signal).then(Ne)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Ne)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...bn(r)},n.signal).then(Ne)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...bn(r)},n.signal).then(Ne)}quickJoin(e,n,r=[]){return Lo(this.options,e,n,r).then(i=>i.room)}createTicket(e,n,r=[]){return hs(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...bn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(un)}heartbeatTicket(e){return Ks(this.generated(),e).then(un)}cancelTicket(e,n=false){return n?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(un):ms(this.generated(),e).then(un)}leave(e,n,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return Ud(this.options,e)}close(e,n){return this.options.client.delete(this.roomV1(e),n).then(()=>{})}update(e,n){return this.options.client.patch(this.roomV2(e),{...n.name===void 0?{}:{name:n.name},...n.maxPlayers===void 0?{}:{max_players:n.maxPlayers},...n.isPublic===void 0?{}:{is_public:n.isPublic},...n.settings===void 0?{}:{settings:n.settings},...n.roomArgs===void 0?{}:{room_args:n.roomArgs}},n.signal).then(Ne)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Ne)}kick(e,n,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(n)}`,{},r).then(()=>this.get(e,r))}transferHost(e,n,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(n)}`,{},r).then(Ne)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return Bd(this.options)}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Bd(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function Ud(t,e){return e===void 0&&t.selfHosted?.()===true}function Lo(t,e,n,r=[],i){let o=Ud(t,e.partyId);return t.client.post(`${Bd(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...xf(e.templateSlugs,o),...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...o?{self_hosted:true}:{},...i===void 0?{}:{play_with_ticket:i},...bn(n)},e.signal).then(s=>({room:Ne(s),playWith:i===void 0?null:Id(s)}))}function xf(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function bn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function Pf(t){t!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${t}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var Jr=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===i&&n(i);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...i)=>{r(),n(...i);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};var zr=class{constructor(e){this.options=e;let n=e.first,r=new Promise(a=>{this.resolve=a;}),i=()=>this.status;this.ticket={id:n.ticketId,get status(){return i()},partySize:n.partySize??0,queuedAt:n.queuedAt??0,expiresAt:n.expiresAt??0,outcome:r};let o=n.queuedAt!==void 0&&n.expiresAt!==void 0?(n.expiresAt-n.queuedAt)*1e3:9e5,s=Math.min(Math.max(o,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},s);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function Tf(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var Ef=1e3,If=3e3,Cf=6e4,Mf=2,Wd=new Set(["game_room_closed","game_room_gone"]),Of=12e4,Gf=5e3,Lf=new Set(["invalid_cluster_target","capacity_unavailable"]),Df=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Jd(t,e){return new Do(e,t)}var Do=class{constructor(e,n={}){this.options=e;this.internals=n;this.autoFollow=e.followMatch!==false,this.apiOptions={client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true},this.api=new Kr(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new Jr;api;apiOptions;playWithAnswer=null;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await n;return this.api.create(r,this.version("create"),o[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,n={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(n),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(n),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),qf(e);let n=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.postQuickJoin(r,a).catch(l=>this.retryPastStaleMembership(l,r,a)),o=await this.run("quickJoin",async()=>{let a=await n;return i(a).catch(async l=>{let d=await this.afterRefusedClusters(l,a);if(d.length===0||Kd(d,a))throw l;return i(d)})}),{room:s}=o;return this.playWithAnswer=o.playWith,this.enter(s,"joined"),this.askForLocalServer(s),s}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Ff(e?.templateSlugs),this.queueing=true;try{let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let s=await n;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Kd(l,s))throw a;return this.api.createTicket(r,this.version("queueForMatch"),l)})});this.heldQueued?.ticketId===i.id&&(this.heldQueued=null),this.partyWatch?.end({status:"lost"});let o=new Br({clock:this.options.clock,first:i,heartbeat:s=>this.track(this.api.heartbeatTicket(s)),cancel:(s,a)=>this.track(this.api.cancelTicket(s,a)),seat:s=>this.enterMatchedRoom(s),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;let n=this.heldQueued;this.heldQueued=null,n!==null&&this.showPartyTicket(n);}}async enterMatchedRoom(e){let n=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?n:(this.room!==null&&this.room.id!==n.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(n,"joined"),this.room?.id===n.id?this.room:n)}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let i of n)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(i){if(i instanceof M&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>po({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...n===void 0?{}:{signal:n}})));}catch(s){return s instanceof M&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=Ye(n.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(i),i}async kick(e,n){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(i),i}async transferHost(e,n){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(i),i}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new w("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let i=be(n.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(c,u)=>uo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...c===void 0?{}:{clusterTargetId:c},...i===void 0?{nextClusterTarget:()=>this.nextCluster(u)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(o,[s]).catch(async c=>{if(i!==void 0||!Vd(c))throw c;let u=await this.nextCluster([s],true);if(u===void 0)throw c;return a(u,[s,u])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new w("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(i)}chase(e,n,r){return mo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new w("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Wd.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new w("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let i={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!ct()){this.park(e,()=>this.reconnectStep(e));return}let n=this.options.autoReconnect;if(n===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=n.attempts||r<Ef){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(Tf(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!ct()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>po({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,!Wd.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await n.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let n=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):n&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new w("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let n=this.session.matchId;this.session={phase:"suspended",matchId:n,reason:e},this.emitter.emit("matchSuspended",{matchId:n,cause:e}),this.armReconnect(n,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new w("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let n=this.heldMatchId;if(n===null)throw new w("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:n},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let n=this.heldMatchId;if(n!==null)try{await this.api.leaveMatch(n,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}get playWith(){return this.playWithAnswer}on(e,n){let r=this.emitter.on(e,n);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Lf.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let n=new zr({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===n&&(this.partyWatch=null);}});this.partyWatch=n,this.emitter.emit("partyQueued",n.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(i=>i.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&ct())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let n=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(n,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!ct())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of Xr)e.addEventListener(r,this.visibilityListener);let n=globalThis.document;typeof n?.addEventListener=="function"&&n.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let n=this.inFlight;this.inFlight=[],await Promise.allSettled(n);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of Xr)e.removeEventListener?.(r,this.visibilityListener);globalThis.document?.removeEventListener?.("resume",this.visibilityListener),this.visibilityListener=null;}}get watchingSeats(){return this.options.watchSeats!==false&&this.emitter.hasListeners("seated")}get seatPollMs(){return this.options.seatPollIntervalMs??Gf}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new w("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let n=this.options.clientVersion,r=Nr(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new w("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return xd({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return cn(await this.options.resolveClusterTargets());let e=be(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Vd(e)||n.length===0?[]:cn(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!n?o:r(cn(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof M)||e.reason!=="conflict"||!Df.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(n.signal);}catch{throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new M(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.postQuickJoin(n,r)}postQuickJoin(e,n){return Lo(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}assertNotInRoom(e){if(this.room!==null)throw new w("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new w("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new w("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,n){let r=n instanceof M?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof w?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(n,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,l]of i){let d=r.get(a);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",a,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=$f(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??Of;return new Promise((i,o)=>{let s=u=>{a(),l(),this.options.clock.clearTimeout(c),e.signal?.removeEventListener("abort",d),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>i(u))),l=this.emitter.on("matchFailed",(u,p)=>s(()=>o(new w("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>s(()=>o(new w("aborted","the caller aborted while awaiting a match"))),c=this.options.clock.setTimeout(()=>s(()=>o(new w("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??If}pushedInterval(){return this.options.pushedPollIntervalMs??Cf}pushed(){return this.options.clock.now()-this.lastPushAt<Mf*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=n=>{if(this.ticketWatch?.abandon(true),n?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function ct(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Xr=["visibilitychange","focus","pageshow","online"];function $f(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||Hd(t)!==Hd(e)}function Hd(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Vd(t){return t instanceof M&&t.code==="invalid_cluster_target"}var Yr=8;function Ff(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=Yr&&t.every(n=>typeof n=="string"&&n.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Yr} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function qf(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Yr&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Yr} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(t?.templateSlug!==void 0||t?.templateId!==void 0)throw new w("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function Kd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Nf=["p2p","dedicated","unknown"],$o=["connection_setup_duration_seconds","reconnect_latency_seconds","datachannel_rtt_seconds","p2p_join_to_play_latency_seconds","ice_restart_outcome_total","connection_failures_total","transport_permanent_failures_total","transport_quality_score","host_migration_outcome_total","turn_relay_usage_ratio"];var Ot=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let i=jf(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 jf(t,e,n){let r=Math.floor(n/1e3);return t.filter(i=>$o.includes(i.type)).slice(0,100).map(i=>{let o=Bf(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Bf(t){if(t!==void 0)return Nf.includes(t)?t:"unknown"}var vn=class{constructor(e){this.options=e;this.reporter=new Ot({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:Qr(i.credential)??"",hostFingerprint:Qr(i.host_fingerprint)??"",hostEpoch:Zr(i.host_epoch)??0,expiresAt:(Zr(i.expires_at)??0)*1e3}}async turnLease(e,n,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,c=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);c.length!==0&&o.push({urls:c,username:Qr(d.username)??"",credential:Qr(d.credential)??""});}let s=Zr(i.expires_at),a=Zr(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??0)*1e3}}async kick(e,n,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:n},r);}async leave(e,n=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:n});}async telemetry(e,n){await this.reporter.post(e,n);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function Qr(t){return typeof t=="string"&&t.length>0?t:void 0}function Zr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var Uf=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),D=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="P2pError",this.retryable=Uf.has(n);}reason;retryable};var zd=10240,Xd=2048,Wf=new TextEncoder;function Yd(t){return Wf.encode(t).length}function Qe(t,e){let n=i=>{throw new w("invalid_sdp",`the ${e} ${i}`)},r=Yd(t);r>=zd&&n(`is ${r} bytes, over the ${zd} 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=Yd(i);o>Xd&&n(`has a ${o}-byte line, over the ${Xd} limit`);}}function ei(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 ti=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 Hf=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function Gt(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=ni(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function ni(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 Hf.test(r)?r:null}function _n(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 Fo=5e3,Vf=12e4+Fo,Kf=1024,Jf=6e4,zf=1e4,Qd=64*1024,Zd=5;function qo(t){let e=new Map,n=-1/0,r=null,i=(()=>{let a;try{a=new URL(`${t.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=t.subtle??globalThis.crypto?.subtle;if(!a)throw new D("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!i.ok)throw new D("keys_unavailable",i.reason);let a=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(zf)});}catch{throw new D("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new D("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>Qd)throw new D("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Qd} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof D?p:new D("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let c=Array.isArray(d.keys)?d.keys:[];if(c.length>Zd)throw new D("keys_unavailable",`the JWKS endpoint published ${c.length} keys, over the ${Zd} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=o();for(let p of c){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let f=await u.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,f);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!i.ok)throw new D("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new D("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<n&&(n=-1/0),d-n<Jf?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var wn=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>=Kf){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+Vf),true}};function tc(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 ec(t){try{let e=new TextDecoder().decode(tc(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function No(t,e,n,r,i){let o=j=>{throw new D("peer_unauthenticated",`the peer's join credential is not usable: ${j}`)},s=t.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,c=ec(a);c===null&&o("its header does not decode"),c.alg!=="RS256"&&o(`its alg is ${JSON.stringify(c.alg)}, not RS256`),c.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(c.typ)}, not p2p+jwt`);let u=c.kid;(typeof u!="string"||u.length===0)&&o("it names no key");let p=await n.key(u);p===null&&o("it was signed by a key this build cannot resolve");let g=i.subtle??globalThis.crypto?.subtle;g||o("this environment has no WebCrypto");let f=new TextEncoder().encode(`${a}.${l}`),h;try{h=tc(d);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,h,f)||o("its signature does not verify");let x=ec(l);x===null&&o("its payload does not decode");let P=x,b=j=>typeof P[j]=="string"?P[j]:"",S=j=>typeof P[j]=="number"&&Number.isFinite(P[j])?P[j]: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 I=S("exp")*1e3,T=S("nbf")*1e3;(!Number.isFinite(I)||e.now>I+Fo)&&o("it has expired"),Number.isFinite(T)&&e.now<T-Fo&&o("it is not valid yet");let H=b("role");H!=="host"&&H!=="client"&&o("it names no usable role");let N=S("host_epoch");N!==e.hostEpoch&&o("it names a different host epoch");let B=ni(b("fingerprint"));B===null&&o("its fingerprint claim is malformed"),_n(B,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let E=ni(b("host_fingerprint"));E===null&&o("its host fingerprint claim is malformed"),_n(E,e.hostFingerprint)||o("it was issued against a different host certificate");let O=b("jti");O.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(O,e.now)||o("it has already been used");let $=b("sub");return $.length===0&&o("it names no player"),{playerId:$.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:N,role:H,fingerprint:B,hostFingerprint:E,jti:O,expiresAt:I}}function jo(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 Bo(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 Uo(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Wo(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 nc(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 rc(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Sn=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 Ho={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},je=["reliable","ordered","unreliable"];function Vo(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 kn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var oc=1,ey=3e4,ac=2e3,ty=5e3,sc=6e4,ny=8,Jo=class{constructor(e=ny){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;}},ry=new Jo,iy=8,oy=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),An=class{constructor(e){this.options=e;this.keys=e.keys??qo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new ti;links=new Map;replays=new wn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=oc+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??ey;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),i=be(this.options.clusterTargetId);if(i!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Ko(a)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new D("timeout",`no usable P2P connection after ${n}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},n),s=()=>this.fail(new D("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",s),this.ready=null;}}async kick(e){if(!this.isHost)throw new D("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);default:return}}async onHello(e){let n=de(e.playerId),r=de(e.hostPlayerId),i=ri(e.hostEpoch);if(!(n===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Sn(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,oc),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new D("invalid_sdp","the browser produced an offer with no SDP");Qe(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:Gt(r);if(i===null)throw new D("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??ry,s=()=>this.closed||e!==this.credentialGeneration,a=ty;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let c=d.status,u;if(c===409)u=ac;else if(c===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=a,a=Math.min(a*2,sc)),u=Math.min(Math.max(u,ac),sc);}else throw d;if(!await this.waitForCredential(u,s))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=iy){let c=this.pendingOffers.keys().next().value;c!==void 0&&this.pendingOffers.delete(c);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let i=de(e.sessionId);if(i!==null&&this.answeredSessions.get(n)===i)return;Qe(r,"offer"),this.refuseMedia(r,"offer");let o=Gt(r);if(o===null)throw new D("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(n,i);let s=this.links.get(n);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(n,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let l=await a.connection.createAnswer();await a.connection.setLocalDescription(l);let d=a.connection.localDescription?.sdp??l.sdp;if(!d)throw new D("invalid_sdp","the browser produced an answer with no SDP");Qe(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||n!==this.hostPlayerId)return;Qe(r,"answer"),this.refuseMedia(r,"answer");let o=Gt(r);if(o===null)throw new D("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:_n(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new D("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e);}async onIce(e){let n=de(e.fromPlayerId),r=de(e.candidate);if(n===null||r===null)return;let i=this.links.get(n);if(!i)return;let o=de(e.sdpMid),s=ri(e.sdpMLineIndex)??ri(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let n=de(e.playerId);if(n===null)return;let r=de(e.reason)??"left";if(n===this.localPlayerId){this.fail(new D("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(n);i&&this.dropLink(i,r,true);}async onMigration(e){let n=de(e.hostPlayerId),r=ri(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:n,hostEpoch:r,...de(e.reason)===null?{}:{reason:de(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(i.kind==="refused"){this.report_(new D("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new D("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let n=de(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new D("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=de(e.code)??"unknown",r=de(e.message)??"the platform refused a signaling message";this.report_(new D("signaling_failed",`${n}: ${r}`));}openLink(e,n){let i=(this.options.peerConnectionFactory??Vo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of je){let g=i.createDataChannel(p,Ho[p]);g.binaryType="arraybuffer",o[p]=g;}let s={playerId:e,assignedPeerId:n,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),c=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",u),o.reliable.addEventListener("message",c),s.detachHandshake=()=>{o.reliable.removeEventListener("open",u),o.reliable.removeEventListener("message",c);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}flushCandidates(e){let n=e.pendingCandidates;e.pendingCandidates=[];for(let r of n)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let n=this.credential;if(n===null)throw new D("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=n.expiresAt)throw new D("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(jo({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Wo(n);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new D(rc(r.reason),nc(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=Gt(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 No(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof D&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",Ko(s)),a&&this.fail(s);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Bo({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(Uo(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 je)lc(e.channels[i]);lc(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,n);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let n=this.ready;this.ready=null,n.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof D?e:new D("connection_failed",Ko(e),{cause:e}));}count(e){this.counted||!oy.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(ei(e))throw new D("media_refused",`the ${n} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(n=>this.options.clock.setTimeout(n,e))}warn(e){let n=this.options.log;n!==null&&(n??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function de(t){return typeof t=="string"&&t.length>0?t:null}function ri(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Ko(t){return t instanceof Error?t.message:String(t)}function lc(t){try{t.close();}catch{}}var ay=100,sy=50,xn=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??ay)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new D("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new D("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:n,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??sy));}};function V(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Ze(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function Lt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function dc(t){return typeof t=="boolean"?t:void 0}var we=V(64),Pn=Ze(0,2147483647);function zo(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=we(n);typeof r=="string"&&e.push(r);}return e}function Y(t,e,n){return {to:t,from:e,read:n,required:true}}function K(t,e,n){return {to:t,from:e,read:n,required:false}}var cy=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=Lt("disconnected","failed","closed")(e.iceState),r=Ze(0,4102444800)(e.lastSeenAt);if(!(n===void 0&&r===void 0))return {...n===void 0?{}:{ice_state:n},...r===void 0?{}:{last_seen_timestamp:r}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[Y("sdp","sdp",V(10240)),Y("signaling_intent","intent",Lt("initial","ice_restart","full_reconnect")),K("sdp_hash","sdpHash",V(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[Y("peer_id","peerId",we),Y("sdp","sdp",V(10240)),Y("assigned_peer_id","assignedPeerId",Ze(0,4294967295)),K("sdp_hash","sdpHash",V(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[Y("peer_id","peerId",we),Y("candidate","candidate",V(512)),K("sdp_mid","sdpMid",V(64)),K("sdp_mline_index","sdpMLineIndex",Ze(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[Y("host_epoch","hostEpoch",Pn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[Y("host_epoch","hostEpoch",Pn),K("evidence","evidence",cy)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[Y("playerId","player_id",we),Y("hostPlayerId","host_player_id",we),Y("hostEpoch","host_epoch",Pn),K("members","members",zo)],offer:[Y("fromPlayerId","from_player_id",we),Y("sdp","sdp",V(10240)),K("sessionId","signaling_session_id",V(128)),K("sdpHash","sdp_hash",V(128)),K("iceUfrag","ice_ufrag",V(64)),K("intent","signaling_intent",Lt("initial","ice_restart","full_reconnect"))],answer:[Y("fromPlayerId","from_player_id",we),Y("sdp","sdp",V(10240)),K("sessionId","signaling_session_id",V(128)),K("sdpHash","sdp_hash",V(128)),K("iceUfrag","ice_ufrag",V(64)),K("assignedPeerId","assigned_peer_id",Ze(0,4294967295))],ice:[Y("fromPlayerId","from_player_id",we),Y("candidate","candidate",V(512)),K("sdpMid","sdp_mid",V(64)),K("sdpMLineIndex","sdp_m_line_index",Ze(0,255)),K("sdpMLineIndexAlt","sdp_mline_index",Ze(0,255))],peerJoined:[Y("playerId","player_id",we)],peerLeft:[Y("playerId","player_id",we),K("reason","reason",V(64))],migration:[Y("hostPlayerId","new_host_player_id",we),Y("hostEpoch","host_epoch",Pn),K("reason","reason",V(64)),K("kickedPlayerIds","kicked_player_ids",zo),K("migrationComplete","migration_complete",dc)],matchEnded:[K("reason","reason",V(64))],error:[K("code","code",V(64)),K("message","message",V(256))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var mt="webrtc_p2p";function uc(t){let e=new vn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,i,o){n.get(r)?.handleSignal(i,o);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new D("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=be(r.clusterTargetId),o=i??be(await t.resolveClusterTarget?.());t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let s=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==mt)throw new D("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${mt}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new xn({bridge:t.bridge,matchId:s.matchId,clock:t.clock}),l=new An({api:e,clock:t.clock,matchId:s.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:a,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await kn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(s.matchId,l),l.on("matchEnded",()=>n.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(s.matchId),l.close(),d}return l}}}function mc(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,i=t.document??globalThis.document,o=[];if(typeof r.addEventListener=="function"){let a=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",a),o.push(()=>r.removeEventListener?.("pagehide",a));let l=()=>e.setHidden(!ct());for(let d of Xr)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(!ct());}let s=new Map;return o.push(n.on("matchReady",a=>{let l=a.protocol===mt?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(n.on("matchEnded",a=>{let l=s.get(a.matchId);l!==void 0&&(s.delete(a.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let a of o.splice(0))try{a();}catch{}s.clear();}}var pc=["pointerdown","keydown"];function gc(t,e=globalThis){let n=false,r=false,i=null,o=()=>{if(i!==null){try{e.cancelAnimationFrame?.(i);}catch{}i=null;}},s=()=>{if(!r){r=true,o();for(let g of pc)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(g){g?.isTrusted===true&&a();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(f=>f?.buttons.some(h=>h.pressed)===true)},c=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(i=null,!(n||r)){if(d()){a();return}c()&&(i=e.requestAnimationFrame?.(u)??null);}};function p(){i===null&&!n&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of pc)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),c()&&(i=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return n},stop:s}}async function ii(t,e,n,r){let i=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),i}function Xo(t,e){let n=false;return async r=>{let i=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),i}}function Yo(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(i,o){return r.has(i)?false:(r.add(i),n.push({name:i,at:o??e()}),true)},timeline(){let i=[...n].sort((o,s)=>o.at-s.at);return i.map((o,s)=>{let a=i[s-1],l=a===void 0?"":` (+${Math.round(o.at-a.at)}ms)`;return `${o.name}@${Math.round(o.at)}ms${l}`}).join(" \u2192 ")}}}var uy="GemWebSdkHandshake";var my=()=>Date.now();function fc(t,e,n={}){let r=t[uy];if(r===void 0)return null;let i=n.ttlMs??9500,o=n.now??my,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,c=false,u=o()-i;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(s[p])===true){c=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:c}}var Qo=new WeakMap,yc=new WeakSet,Zo=new Set,oi=new Set,ai=[],$t=null,ea=false,py=1920;function ta(t){return Qo.get(t)}function na(t){return !ea||yc.has(t)}function ra(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function hc(t=globalThis.window){if(ea||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;ea=true;for(let o of Array.from(t.document?.querySelectorAll("canvas")??[]))yc.add(o);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(o,...s){let a=n.call(this,o,...s);if(a&&!Qo.has(this)){let l={kind:o,context:a};Qo.set(this,l),ra(l)&&Zo.add(this);}return a};let r=t.requestAnimationFrame,i=t.cancelAnimationFrame;t.requestAnimationFrame=o=>{let s=r.call(t,a=>{oi.delete(s);try{o(a);}finally{gy();}});return oi.add(s),_c(),s},t.cancelAnimationFrame=o=>{oi.delete(o),i.call(t,o);};}function bc(t,e){return new Promise(n=>{let r={canvas:t,done:o=>{clearTimeout(i),ai=ai.filter(s=>s!==r),n(o);}},i=setTimeout(()=>r.done(null),e);ai.push(r);})}function vc(t){return $t?.canvas===t?$t.bitmap:null}function gy(){for(let t of ai){let e;try{e=ia(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}oi.size===0&&fy();}function fy(){let t=null;for(let r of Zo)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):Zo.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,py/Math.max(t.width,t.height)),n=e<1?{resizeWidth:Math.max(1,Math.floor(t.width*e)),resizeHeight:Math.max(1,Math.floor(t.height*e)),resizeQuality:"medium"}:{};_c(),$t={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function _c(){$t&&($t.bitmap.then(t=>t?.close()),$t=null);}function ia(t){let e=yy();if(!e)return true;e.clearRect(0,0,8,8),e.drawImage(t,0,0,8,8);let n=e.getImageData(0,0,8,8).data;for(let r=0;r<n.length;r+=4){if(n[r]|n[r+1]|n[r+2])return true;let i=n[r+3];if(i!==0&&i!==255)return true}return false}var Tn;function yy(){if(Tn!==void 0)return Tn;if(typeof OffscreenCanvas=="function")Tn=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),Tn=t?.getContext("2d",{willReadFrequently:true})??null;}return Tn??null}var oa=false;async function Rc(t,e,n,r){if(oa){e.close(),n("busy",true);return}oa=true;let i=null;try{let o=await vy(t,r);if(typeof o=="string"){e.close(),n(o,hy(o));return}i=o;let a=await(r.encodeRef??(l=>Ry(l,r)))(i);if(i.close(),i=null,a===null){e.close(),n("failed",!0);return}if(a.size>ky){e.close(),n("too_large",!1);return}e.postMessage(a);}catch(o){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",o);}finally{oa=false,i?.close();}}function hy(t){switch(t){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}var by=600;async function vy(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":wc(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Sy(n);if(!r)return "no_source";try{let i=await _y(r);return typeof i=="string"?i:wc(i,t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}async function _y(t){let e=wy(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!ra(e))return createImageBitmap(t);let n=await bc(t,by);if(n)return n;let r=await vc(t);return r&&ia(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function wy(t){let e=ta(t);if(e)return e;if(!na(t))return "no_source";try{for(let n of ["webgl2","webgl","2d","webgpu"]){let r=t.getContext(n);if(r)return {kind:n,context:r}}}catch{return "unreadable"}return "unreadable"}function Sy(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let i=r.width*r.height;i<=0||r.clientWidth<=0||r.clientHeight<=0||!ta(r)&&!na(r)||i>n&&(e=r,n=i);}return e}async function wc(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let i=Math.min(n/t.width,r/t.height),o=Math.max(1,Math.floor(t.width*i)),s=Math.max(1,Math.floor(t.height*i));try{let a=await createImageBitmap(t,{resizeWidth:o,resizeHeight:s,resizeQuality:"high"});return t.close(),a}catch{return t.close(),"too_large"}}var ky=8*1024*1024,Sc="image/webp",kc=.92;async function Ry(t,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(t.width,t.height),s=o.getContext("2d");if(s){s.drawImage(t,0,0);let a=await o.convertToBlob({type:Sc,quality:kc});if(a&&a.size>0)return a}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let i=r.getContext("2d");return !i||(i.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(s=>o(s),Sc,kc);})}async function Ac(t,e){if(!e)return;let n;try{n=await Ay(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 Ay(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 xc=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function Pc(t=globalThis){let n=t[xc];if(n!==void 0)return n;let r=false,i=()=>r,o=[],s=xy(t,i);s!==null&&o.push(s);let a=Py(t,i);a!==null&&o.push(a);let l={get muted(){return r},setMuted(d){let c=!!d;if(c!==r){r=c;for(let u of o)u();}}};return Object.defineProperty(t,xc,{value:l,configurable:true}),l}function xy(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let i=t.OfflineAudioContext,o=n.connect,s=n.disconnect,a=new Map,l=c=>{let u=c.gain,p=c.context.currentTime;u.cancelScheduledValues(p),e()?u.setValueAtTime(0,p):u.setTargetAtTime(1,p,.01);},d=c=>{let u=c.context;if(i!==void 0&&u instanceof i)return null;let p=a.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,o.call(p,c),a.set(u,p)),p};return n.connect=function(...u){let[p,...g]=u;if(p instanceof r){let f;try{f=d(p);}catch{f=null;}if(f!==null)return o.call(this,f,...g),p}return o.apply(this,u)},n.disconnect=function(...u){let[p,...g]=u;if(p instanceof r){let f=a.get(p.context);if(f!==void 0&&f!==this)try{return s.call(this,f,...g)}catch{}}return s.apply(this,u)},()=>{for(let[c,u]of a){if(c.state==="closed"){a.delete(c);continue}try{l(u);}catch{}}}}function Py(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,i=Object.getOwnPropertyDescriptor(r,"muted"),o=i?.get,s=i?.set;if(o===void 0||s===void 0)return null;let a=r.play,l=new WeakMap,d=new WeakSet,c=new Set,u=p=>{l.has(p)||l.set(p,!!o.call(p)),d.has(p)||(d.add(p),c.add(new WeakRef(p))),s.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!o.call(this):p},set(p){l.set(this,!!p),u(this);}}),r.play=function(){try{u(this);}catch{}return a.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{u(g);}catch{}},true),()=>{for(let p of c){let g=p.deref();if(g===void 0){c.delete(p);continue}try{s.call(g,(l.get(g)??!1)||e());}catch{}}}}var Ty=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Ey=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Iy=`${Ty}${Ey}`,aa=new WeakSet;function Tc(t=globalThis.document){if(t==null||aa.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(Iy),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],aa.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"),aa.add(t),"inline")}catch{return null}}function Ec(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=t.now??(()=>globalThis.performance?.now()??Date.now()),i=false,o=false,s=false,a=null,l=null,d=null,c=[],u=false,p=0,g=null,f=[],h=()=>i&&!o&&!s,k=()=>{l=null,d=null,c=[],p=0,g=null,f=[];},x=S=>{if(a=null,!h()){k();return}if(d!==null&&c.push(S-d),d=S,l===null)l=S;else {let I=S-l;if(I>=e&&c.length>0){if(u){let T=g===null?I:r()-g;t.report(My(p,f,I,T));}else t.report(Cy(c,I));l=S,c=[],p=0,f=[];}}P();},P=()=>{let S=n.requestAnimationFrame;typeof S=="function"&&(a=S.call(n,x));},b=()=>{if(h()){a===null&&(k(),P());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),k();};return {setRequested(S){i=S,b();},setPaused(S){o=S,b();},draw(){if(!u){u=true,a!==null&&k();return}if(a===null||l===null)return;let S=r();g!==null&&f.length<1e3&&f.push(S-g),g=S,p+=1;},get running(){return a!==null},dispose(){s=true,b();}}}function Cy(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:Ic(t),counts:"pageFrames"}}function My(t,e,n,r){let i=r;return e.length>0&&(i=Ic(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:i,counts:"gameDraws"}}function Ic(t){let e=[...t].sort((r,i)=>r-i),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var si=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Cc(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Mc(t,e){t!==null&&(t.style.setProperty(si.top,`${e.top}px`),t.style.setProperty(si.right,`${e.right}px`),t.style.setProperty(si.bottom,`${e.bottom}px`),t.style.setProperty(si.left,`${e.left}px`));}var li=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height",centerY:"--gem-reserved-tl-center-y",controlHeight:"--gem-reserved-tl-control-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height",centerY:"--gem-reserved-tr-center-y",controlHeight:"--gem-reserved-tr-control-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height",centerY:"--gem-reserved-bl-center-y",controlHeight:"--gem-reserved-bl-control-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height",centerY:"--gem-reserved-br-center-y",controlHeight:"--gem-reserved-br-control-height"}});function Oc(){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 Oy(t,e){let n={tl:{width:0,height:0,control:null},tr:{width:0,height:0,control:null},bl:{width:0,height:0,control:null},br:{width:0,height:0,control:null}};for(let r of t){let i=e?r.x+r.width/2<=e.width/2:r.x===0,o=e?r.y+r.height/2<=e.height/2:r.y===0,s=i?r.x+r.width:e?e.width-r.x:r.width,a=o?r.y+r.height:e?e.height-r.y:r.height,l=n[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));let d=r.control;if(d){let c=l.control;l.control=c?{top:Math.min(c.top,d.y),bottom:Math.max(c.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Gc(t,e,n){if(t===null)return;let r=Oy(e,n);for(let i of ["tl","tr","bl","br"]){t.style.setProperty(li[i].width,`${r[i].width}px`),t.style.setProperty(li[i].height,`${r[i].height}px`);let o=r[i].control;t.style.setProperty(li[i].centerY,o?`${(o.top+o.bottom)/2}px`:""),t.style.setProperty(li[i].controlHeight,o?`${o.bottom-o.top}px`:"");}}var Gy=3e4,di=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Lc(t){let e=t.clock??ue,n=t.timeoutMs??Gy,r=new Map,i=new Map,o=0,s=a=>{let l=r.get(a);return l?(r.delete(a),i.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(a){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(a);if(l)return l;let d=new Promise((c,u)=>{let p=`ls${++o}`,g=e.setTimeout(()=>{r.delete(p),i.delete(a),u(new di("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(p,{room:a,resolve:c,reject:u,timer:g}),t.bridge.requestLocalServer(p,a)||(s(p),c());});return i.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new di(a.reason,a.retryable,a.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var En={url:"https://downloads.indiegems.games/sdk/v18.1.0/gem-web-sdk.devtools.min.js",integrity:"sha384-G0ezyRUBqI3do9Q+rEg/7+BCL6g0HItZ/xGznlRyPrLdgJumzHNpBj9AfrKUiRoM"};var Ft=null;function Ly(){return Ft!==null||(Ft=new Promise((t,e)=>{let n=document.createElement("script");n.src=En.url,n.integrity=En.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Ft=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${En.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Ft=null,e(new Error(`gem devtools: could not load ${En.url}. Either the network refused it or its Subresource Integrity check failed, or the CDN did not answer the CORS preflight this request needs \u2014 SRI is only checkable on bytes the page may read. A locally rebuilt SDK is the commonest cause: it produces panel bytes that do not match the hash compiled into this build.`));},document.head.append(n);})),Ft}function Dc(t,e){let n=null,r=0;async function i(o){if(n!==null)return true;let s=++r;if(!e())return false;let a=await Ly();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:o,text:ot,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 Dy=1e4,$c={reason:"unavailable",retryable:false};function Fc(t){let e=new Map,n=null,r=null,i=0,o=(d,c)=>{c.timer=t.clock.setTimeout(()=>{e.delete(d),c.reject({reason:"timeout",retryable:true});},t.timeoutMs??Dy);},s=(d,c)=>{let u=a(d);u&&c(u);},a=d=>{let c=e.get(d);return c?(e.delete(d),t.clock.clearTimeout(c.timer),c):null},l=new wt({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((c,u)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){u($c);return}let g=`t${++i}`,f={resolve:c,reject:u,reason:d,timer:null,held:p!=="connected"};e.set(g,f),o(g,f),f.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let c={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,u=>u.resolve(c));return}l.accept(c);},onDenied(d){s(d.requestId,c=>c.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[c,u]of e)u.held&&(u.held=false,t.clock.clearTimeout(u.timer),o(c,u),t.bridge.requestToken(c,u.reason));else if(d==="refused"||d==="closed")for(let c of [...e.keys()])s(c,u=>u.reject($c));},get identity(){return n},get gameVersion(){return r}}}var $y=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),la="embedder_relay_unavailable",Fy="embedder_no_relay",qy=new Set([la]),da=new Set([Fy]),In=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new sa(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new w("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){n.refuse(new w("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(Ny(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new w("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,n);}release(e,n){this.pending.get(e)===n&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new w("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new w("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function Ny(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new w(jy(t),r,{platformCode:t})}function jy(t){return t===void 0||qy.has(t)?"signaling_failed":da.has(t)?"offer_refused":$y.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var sa=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new w("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return n?.aborted?Promise.reject(new w("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new w("aborted","the caller aborted the signaling exchange"));},a=()=>{n?.removeEventListener("abort",s),this.hub.release(e.matchId,l),this.teardown===a&&(this.teardown=null);},l={settle:d=>{a(),i(d);},refuse:d=>{a(),o(d);}};this.teardown=a,n?.addEventListener("abort",s),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof w?d:new w("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var qc="match_ended:",Nc="server_shutdown:",jc="kicked:",By=123;function Uy(t){if(typeof t!="string"||t.length===0||t.length>By)return {kind:"other"};if(t.startsWith(qc)){let e=Ye(t.slice(qc.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Nc)?{kind:"server_shutdown",cause:t.slice(Nc.length)}:t.startsWith(jc)?{kind:"kicked",detail:t.slice(jc.length)}:{kind:"other"}}function ca(t,e,n){let r=Uy(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 ua(){return {exchange(){return Promise.reject(new w("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var Wy=3e3,Hy=1e4,Vy=15e3;async function ci(t){let e=t.peerConnection;try{Uc(t,"before the handshake started"),ma(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let s of t.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});t.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await zy(e,t),ma(t);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new w("invalid_sdp","the offer carried no SDP");Qe(i,"offer"),Bc(i,"offer");let o=await Jy(t,i);if(ma(t),typeof o?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return Qe(o.sdp,"answer"),Bc(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Xy(n,t),Uc(t,"before the channel opened"),n}catch(n){throw e.close(),Ky(n)}}function Ky(t){return t instanceof w?t:Vc(t)?pt():new w("connection_failed",Kc(t),{cause:t})}function Bc(t,e){if(ei(t))throw new w("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function Jy(t,e){let n=t.exchangeTimeoutMs??Hy,r=Hc(t,n),i=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(o=>{throw o instanceof w?o:Vc(o)?pt():new w("signaling_failed",Kc(o),{cause:o})});return Yy(i,t,r,()=>r.exhausted?pa("while the offer was in flight"):new w("timeout",`no answer arrived within ${n}ms`))}function zy(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let i=()=>{n.clearTimeout(s),t.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{t.iceGatheringState==="complete"&&i();},s=n.setTimeout(i,e.gatherTimeoutMs??Wy);t.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Xy(t,e){if(e.signal?.aborted)return Promise.reject(pt());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new w("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??Vy,i=Hc(e,r);return new Promise((o,s)=>{let a=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",c);},l=()=>{a(),o();},d=g=>{a(),s(new w("connection_failed","the data channel failed before it opened",Wc(g)===void 0?void 0:{cause:Wc(g)}));},c=()=>{a(),s(pt());},u=()=>{a(),s(i.exhausted?pa("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(u,i.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",c);})}function Hc(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 Yy(t,e,n,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(pt()):new Promise((s,a)=>{let l=u=>{i.clearTimeout(c),o?.removeEventListener("abort",d),u();},d=()=>l(()=>a(pt())),c=i.setTimeout(()=>l(()=>a(r())),n.ms);o?.addEventListener("abort",d),t.then(u=>l(()=>s(u)),u=>l(()=>a(u)));})}function Uc(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw pa(`already ${e}`)}function pa(t){return new w("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function ma(t){if(t.signal?.aborted)throw pt()}function pt(){return new w("aborted","the caller aborted the connection attempt")}function Vc(t){return t?.name==="AbortError"}function Wc(t){return t?.error}function Kc(t){return t instanceof Error?t.message:String(t)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[Y("sdp","sdp",V(10240)),K("sessionId","session_id",V(64))],error:[K("code","code",V(64)),K("message","message",V(256))],matchEnded:[K("reason","reason",V(64))]}));function tu(t){let{client:e,clock:n,rooms:r}=t,i=t.signaling??ua,o=t.log??(b=>console.warn(b)),s=new Ot({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(b,S)=>{let I=a.get(b)??new Set;I.add(S),a.set(b,I);},d=(b,S)=>{let I=a.get(b);I!==void 0&&(I.delete(S),I.size===0&&a.delete(b));},c=async b=>{if(r.isHost&&!fa(r)&&r.currentRoom?.matchId===void 0){let S=be(b.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},...b.retry===void 0?{}:{retry:b.retry},...b.signal===void 0?{}:{signal:b.signal}});}return Zc(r.matchConnectionState==="suspended"?await r.reconnectToMatch(ga(b)):await r.awaitMatch(ga(b)))},u=async b=>Zc(await r.pollMatchStatus(ga(b))),p=async(b,S)=>{let I=false;try{let T=await c(b),H=r.currentRoom?.transports;if(H!==void 0&&!H.includes("webrtc"))throw new w("misconfigured",`the room template offers (${H.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 N=b.peerConnection??eu();I=!0;let B=await ci({peerConnection:N,signaling:S,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...ui(b,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),E=null;if(b.presentCredential!==!1)try{E=await mn({channel:B,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...ui(b,"onMessage","signal"),...b.welcomeTimeoutMs===void 0?{}:{ceilingMs:b.welcomeTimeoutMs}});}catch(O){throw Te(B),Te(N),O}return ah(r,T,B,N,S,b.reportDisconnect!==!1,b.reportConnected!==!1,E,{remember:l,forget:d},b.onMatchEnded)}catch(T){throw I&&Qc(s,T),Te(S),T}},g=async(b,S,I,T,H,N)=>{if(b==="webtransport"){let U=T?.webtransport;if(U===void 0)throw new w("misconfigured","webtransport is not advertised");let J={credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n};if(typeof U.named_url=="string"&&U.named_url!==""){let oe=Math.max(Math.floor(N/2),1e3);try{return await yn({url:U.named_url,timeoutMs:oe,log:o,...J})}catch(ge){if(Vr()!==null)throw ge;return o(`[gem] webtransport named dial failed (${Wr(ge)}); retrying the pinned dial`),yn({url:U.url,certHashBase64:U.cert_sha256_b64,timeoutMs:oe,log:o,...J})}}return yn({url:U.url,certHashBase64:U.cert_sha256_b64,timeoutMs:N,...J})}if(b==="websocket"){let U=T?.websocket;if(U===void 0)throw new w("misconfigured","websocket is not advertised");return Eo({url:U.url,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n,timeoutMs:N})}let B=S.peerConnection??eu(),E,O=await ci({peerConnection:B,signaling:H,clock:n,matchId:I.matchId,credentialExpiresAt:I.credentialExpiresAt,extraChannels:[{label:gn,ordered:false,maxRetransmits:0}],onExtraChannel:(U,J)=>{U===gn&&(E=J);},...ui(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:eh}:{}}),$;try{$=await mn({channel:O,clock:n,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,wire:Ur,heartbeat:!0,...ui(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(U){throw Te(O),Te(B),U}let j=$.welcome.heartbeatIntervalMs;return {link:Co(O,B,E,j===void 0?void 0:{clock:n,intervalMs:j}),welcome:$.welcome,channel:O,peerConnection:B}},f=(b,S,I,T,H)=>{let N=false,B;T.link.onClose(j=>{!N&&b.reportDisconnect!==false&&ca(r,S.matchId,j),B?.(j);}),b.reportDisconnect!==false&&b.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let E={transport:T.link.transport,send:(j,U)=>T.link.send(j,U),onMessage:j=>T.link.onMessage(j),onClose:j=>{B=j;},close:()=>T.link.close()},O=()=>{N||(N=true,Te(T.link),Te(H));},$=j=>{if(!N){try{b.onMatchEnded?.(j);}catch{}O();}};return l(S.matchId,$),{matchId:S.matchId,transport:I,link:E,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(S.matchId,$),O();}}},h=async(b,S)=>{let I=r.currentRoom?.id,T=r.gameId,H=()=>({advert:fn(r.currentRoom?.settings,b),template:r.currentRoom?.transports??null});if(I===void 0||T===null)return H();try{let N=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(I)}`,S);return {advert:fn(N.settings,b),template:Ct(N.transports)??r.currentRoom?.transports??null}}catch{return H()}},k=(b,S)=>{let I=b??Jc;return S.length===0?I:I.filter(T=>S.includes(T))},x=async(b,S,I)=>{try{let T=await c(b),{advert:H,template:N}=await h(T.matchId,b.signal),B=k(N,S),E=B.filter(X=>rh(X,H)),O=Vr();if(O!==null&&B.includes("webtransport")&&H?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${O} (learned on an earlier dial in this page)`),E.length===0){let X=N===null?`the default order (${Jc.join(", ")})`:`the room template's transports (${N.join(", ")||"none"})`;throw new w("misconfigured",`none of ${X}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let $=b.transportAttemptTimeoutMs??Zy,j=()=>b.deadlineAt===void 0?1/0:b.deadlineAt-n.now(),U=X=>t.signalingReady===void 0||X<=0?Promise.resolve(!0):t.signalingReady(X),J=[],oe=[];for(let X of E){if(j()<Xc){o(`[gem] ${X} rung not tried: the reconnect budget is spent`);break}oe.length>0&&T.credentialExpiresAt-n.now()<Yc&&(T=await u(b)),oe.push(X);let Be=!1,Se=!1,fe={attempts:0,waitedMs:0};for(;;){if(X==="webrtc"&&b.redial===!0){let te=Math.min(zc,j());await U(te)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let Ue=Math.max(Math.min($,j()),Xc);try{return f(b,T,X,await g(X,b,T,H,I,Ue),I)}catch(te){let z=te instanceof w?te:new w("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(X==="webrtc"&&Qc(s,z),(z.reason==="credential_expired"||z.reason==="credential_reused")&&!Be){Be=!0,T=await u(b);continue}if(X==="webrtc"&&z.reason==="signaling_failed"&&z.platformCode===la&&!Se){Se=!0;let le=Math.min(zc,j());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 U(le))continue}if(z.reason==="join_rate_limited"){let le=nh(fe,Math.random,j());if(le!==null){if(fe.attempts+=1,fe.waitedMs+=le,o(`[gem] ${X} rung: the server is rate-limiting this player's joins; waiting ${Math.round(le)}ms before presenting again (retry ${fe.attempts} of ${ru.maxAttempts})`),await qr(n,le,b.signal),b.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<Yc&&(T=await u(b));continue}}if(th.has(z.reason)||z.reason==="credential_expired"||X==="webrtc"&&nu(z)){o(`[gem] ${X} rung failed (${z.reason}): ${Wr(z.cause??z)} \u2014 `+(oe.length<E.length?`falling through to ${E[oe.length]}`:"no rungs left")),J.push(z);break}throw o(`[gem] ${X} rung refused the session (${z.reason}): ${z.message}`),z}}}let ge=J[J.length-1];throw ge===void 0?new w("timeout",`the reconnect budget ran out before any transport (${E.join(", ")}) could be tried`):new w(ge.reason,`every transport tried (${oe.join(", ")}) failed; the last said: ${ge.message}`,{cause:J,platformCode:ge.platformCode})}catch(T){throw Te(I),T}};return {listClusterTargets:async(b={})=>go({client:e,...b}),handleMatchEnded(b,S){let I=a.get(b);if(I!==void 0){a.delete(b);for(let T of I)T(S);}},connect:(async(b={})=>{let S=b.signaling??i();return b.transports===void 0?p(b,S):x(b,b.transports,S)})}}var Jc=["webtransport","webrtc","websocket"],Zy=1e4,eh=5e3,zc=3e3,Xc=1e3,Yc=1e4,th=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function nu(t){return t.platformCode!==void 0&&da.has(t.platformCode)}var ru={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function nh(t,e=Math.random,n=1/0){let r=ru;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 rh(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Hr():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||ih(e.websocket.url)}function ih(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return Je(e)}function ga(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var oh=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Qc(t,e){e instanceof w&&(!oh.has(e.reason)&&!nu(e)||t.report([{type:"connection_failures_total",value:1}]));}function ah(t,e,n,r,i,o,s,a,l,d){let c=false,u=()=>{c||ca(t,e.matchId,void 0);};o&&(n.addEventListener("close",u),s&&t.notifyMatchConnected(e.matchId));let p=()=>{c||(c=true,n.removeEventListener("close",u),a?.detach(),Te(n),Te(r),Te(i));},g=f=>{if(!c){try{d?.(f);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function fa(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Zc(t){if(t.status==="failed")throw new w("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new w("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Fr)throw new w("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Fr}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:n}=t;if(e===void 0||n===void 0)throw new w("connection_failed",`match ${t.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...t,joinCredential:e,credentialExpiresAt:n}}function eu(){let t=globalThis.RTCPeerConnection;if(!t)throw new w("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new t({iceServers:[]})}function Te(t){try{t.close();}catch{}}function ui(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var sh=1e4;function iu(t,e){return ya(t,e)}function ya(t,e){if(typeof t.serverToken!="function"||typeof t.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let n=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new wt({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((s,a)=>{let l=e.clock.setTimeout(()=>{r=null,a({reason:"unavailable",retryable:true});},e.timeoutMs??sh);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),o=t.onServerToken(s=>{let a=n(s),l=r;if(l){r=null,l.resolve(a);return}i.accept(a);});return {source:i,dispose(){o(),i.dispose(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var ba={};Fm(ba,{acceptTransfer:()=>lh,addEntityProgression:()=>dh,adminAction:()=>ch,cancelInventoryTransfer:()=>uh,claimEntityProgressionRewards:()=>mh,closeGameRoom:()=>ph,createEntityBatchOrder:()=>gh,createEntityOrder:()=>fh,createSession:()=>yh,deleteEntityGameSetting:()=>hh,deleteEntitySave:()=>bh,deleteSession:()=>vh,deleteShowcaseValue:()=>_h,executeEntityRecipe:()=>wh,finalizeSaveUpload:()=>Sh,getChannelAssignment:()=>kh,getDropRates:()=>Rh,getEntityCurrency:()=>Ah,getEntityGameSetting:()=>xh,getEntityInventory:()=>Ph,getEntityInventoryItem:()=>Th,getEntityLeaderboard:()=>Eh,getEntityOrder:()=>Ih,getEntityProgression:()=>Ch,getEntityRecipeAvailability:()=>Mh,getEntityRecipeUsage:()=>Oh,getEntitySave:()=>Gh,getEvent:()=>Lh,getGameRoomV2:()=>Dh,getLeaderboard:()=>$h,getPlayerGameProfile:()=>Fh,getPurchaseCatalog:()=>qh,getResolvedTemplate:()=>Nh,getRoomArgs:()=>jh,getShowcaseValue:()=>Bh,getTransferDetails:()=>Uh,ingestAnalyticsEvents:()=>ha,initiateInventoryTransfer:()=>Wh,invokeFunction:()=>Hh,kickPlayer:()=>Vh,listChallenges:()=>Kh,listEntityGameSettings:()=>Jh,listEntityOrders:()=>zh,listEntityProgressions:()=>Xh,listEntitySaves:()=>Yh,listEvents:()=>Qh,listGameRooms:()=>Zh,listResolvedTemplates:()=>eb,listTransfers:()=>tb,maxEntityProgression:()=>nb,putEntityGameSetting:()=>rb,putRoomArgs:()=>ib,putShowcaseValue:()=>ob,rejectTransfer:()=>ab,reportMatchPlayers:()=>sb,requestSaveUploadUrl:()=>lb,resetEntityProgression:()=>db,setMatchBackfill:()=>cb,simulateEntityOrder:()=>ub,transferHostV2:()=>mb,updateGameRoomV2:()=>pb});function v(t){let e=String(t);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function lh(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function dh(t,e,n,r,i,o){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/add`;return t.client.post(s,i,o?.signal)}async function ch(t,e,n,r){let i=`/v1/voice/sessions/${v(e)}/admin`;return t.client.post(i,n,r?.signal)}async function uh(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function mh(t,e,n,r,i,o){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/claim`;return t.client.post(s,i,o?.signal)}async function ph(t,e,n){let r=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.delete(r,n?.signal)}async function gh(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 fh(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 yh(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function hh(t,e,n,r,i){let o=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(o,i?.signal)}async function bh(t,e,n,r,i){let o=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(o,i?.signal)}async function vh(t,e,n){let r=`/v1/voice/sessions/${v(e)}`;return t.client.delete(r,n?.signal)}async function _h(t,e,n,r){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(i,r?.signal)}async function wh(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 Sh(t,e,n,r,i,o){let s=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function kh(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 Rh(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Ah(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/currencies/${v(r)}`;return t.client.get(o,i?.signal)}async function xh(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 Ph(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${v(e)}/${v(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Th(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 Eh(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${v(e)}/${v(n)}/${v(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function Ih(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 Ch(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 Mh(t,e,n,r,i,o){let s=`/v1/inventory/${v(e)}/${v(n)}/catalogs/${v(r)}/recipes/${v(i)}/availability`;return t.client.get(s,o?.signal)}async function Oh(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${v(e)}/${v(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Gh(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 Lh(t,e,n){let r=`/v1/events/${v(e)}`;return t.client.get(r,n?.signal)}async function Dh(t,e,n){let r=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function $h(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 Fh(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function qh(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 Nh(t,e,n){let r=`/v1/game-room-templates/${v(e)}`;return t.client.get(r,n?.signal)}async function jh(t,e,n){let r=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/room-args`;return t.client.get(r,n?.signal)}async function Bh(t,e,n,r){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(i,r?.signal)}async function Uh(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,{replaySafe:true,retryRateLimited:false})}async function Wh(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Hh(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Vh(t,e,n,r){let i=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/kick/${v(n)}`;return t.client.post(i,void 0,r?.signal)}async function Kh(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 Jh(t,e,n,r){let i=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(i,r?.signal)}async function zh(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${v(e)}/${v(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Xh(t,e,n,r){let i=`/v1/inventory/${v(e)}/${v(n)}/progressions`;return t.client.get(i,r?.signal)}async function Yh(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${v(e)}/${v(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Qh(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 Zh(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/${v(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function eb(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function tb(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 nb(t,e,n,r,i,o){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/max`;return t.client.post(s,i,o?.signal)}async function rb(t,e,n,r,i,o){let s=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ib(t,e,n,r){let i=`/v1/games/${v(t.gameId())}/game-rooms/${v(e)}/room-args`;return t.client.put(i,n,r?.signal)}async function ob(t,e,n,r,i){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(o,r,i?.signal)}async function ab(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function sb(t,e,n,r){let i=`/v1/games/${v(t.gameId())}/matches/${v(e)}/players/report`;return t.client.post(i,n,r?.signal)}async function lb(t,e,n,r,i,o){let s=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function db(t,e,n,r,i,o){let s=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/reset`;return t.client.post(s,i,o?.signal)}async function cb(t,e,n,r){let i=`/v1/games/${v(t.gameId())}/matches/${v(e)}/backfill`;return t.client.put(i,n,r?.signal)}async function ub(t,e,n,r,i){let o=`/v1/inventory/${v(e)}/${v(n)}/orders/simulate`;return t.client.post(o,r,i?.signal)}async function mb(t,e,n,r){let i=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}/transfer/${v(n)}`;return t.client.post(i,void 0,r?.signal)}async function pb(t,e,n,r){let i=`/v2/games/${v(t.gameId())}/game-rooms/${v(e)}`;return t.client.patch(i,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var gb=1e4,fb=50,yb=1e3,hb=65536-4*1024,ou=t=>typeof t=="number"?t:0,bb=t=>typeof t=="string"?t:"";function au(){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 vb(t){return t?.retryable===true}function _b(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:ou(o.index),code:bb(o.code)}}):[];return {accepted:ou(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function su(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 lu(t){let e=Math.max(1,Math.floor(t.maxQueue??yb)),n={client:t.client,gameId:()=>t.gameId},r=[],i=0,o=null,s=false,a=null,l=0,d=0,c=false,u=false,p=b=>{t.log?.(b);},g=()=>{o!==null&&(t.clock.clearTimeout(o),o=null);},f=()=>Math.max(0,d-t.clock.now()),h=()=>{o!==null||s||a!==null||(o=t.clock.setTimeout(()=>{o=null,x().catch(()=>{});},Math.max(gb,f())));},k=()=>{let b=Math.min(r.length,100),S=128;for(let I=0;I<b;I+=1){let T=r[I];if(T===void 0)break;if(S+=JSON.stringify(su(T,0)).length+1,S>hb)return Math.max(1,I)}return b};async function x(b){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let S=P(b);a=S;try{return await S}finally{a===S&&(a=null),r.length>0&&h();}}async function P(b){g();let S=r.splice(0,k()),I=i;i=0;let T=Math.round(t.clock.now()),H={batch_id:au(),sent_at_ms:T,events:S.map(N=>su(N,T))};try{let N=await ha(n,H,b===void 0?void 0:{signal:b}),B=_b(N,I);l=0,d=0;for(let E of B.rejected)p(`[gem] analytics: an event was refused (${E.code}). See the analytics_events section of your game config.`);return B}catch(N){if(vb(N)){for(r=[...S,...r],i+=I;r.length>e;)r.shift(),i+=1;l+=1,d=t.clock.now()+Lr(l,N);}else p(`[gem] analytics: ${S.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(N)}`);throw N}}return {track(b,S,I={}){if(s)return;if(typeof b!="string"||b===""){u||(u=true,p(`[gem] analytics: '${S}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(S.startsWith(no)){c||(c=true,p(`[gem] analytics: '${S}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let T={},H={};for(let[N,B]of Object.entries(I))typeof B=="string"?T[N]=B:typeof B=="number"&&Number.isFinite(B)&&(H[N]=B);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:au(),playerId:b,name:S,atMs:t.clock.now(),dimensions:T,measures:H}),r.length>=fb&&a===null&&f()===0?x().catch(()=>{}):h();},flush:b=>x(b),get pending(){return r.length},dispose(){s=true,g(),r=[],i=0;}}}function du(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().");Pt(r);let o=await t({player_id:n,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return Er(o)}}}function wb(t){let e={};for(let[n,r]of Object.entries(ba))if(typeof r=="function"){let i=r;e[n]=(...o)=>i(t,...o);}return e}function qt(t,e={}){let n=e.clock??ue,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let i=ya(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=hr({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new He({transport:o,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=wb({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,c=t.endMatch,u=t.log,p=lu({client:s,clock:n,gameId:a.gameId,...typeof u=="function"?{log:f=>u.call(t,f)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(c===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 c.call(t);},setBackfill:async(f,h)=>{let k=await l.setMatchBackfill(a.matchId,{open:f.open,...f.seats===void 0?{}:{seats:f.seats}},h===void 0?{}:{signal:h});return {open:k.open,seats:k.seats??null}},reportPlayers:async(f,h)=>(await l.reportMatchPlayers(a.matchId,{players:f.map(x=>({player_id:x.playerId,state:x.state}))},h===void 0?{}:{signal:h})).players.map(x=>({playerId:x.player_id,outcome:x.outcome}))},analytics:p,functions:new Xe(l.invokeFunction),challenges:du(l.listChallenges),...d===void 0?{}:{room:{get:f=>l.getGameRoomV2(d,f),args:async f=>{let h=await l.getGameRoomV2(d,f?.signal===void 0?{}:{signal:f.signal}),k=h.modified?h.body:void 0;if(k?.room_args==null||k.room_args_template==null)throw new M("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:k.room_args,room_args_template:k.room_args_template}}}},dispose:()=>{p.dispose(),i.dispose();}}}function gt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Nt(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function Cn(t){return typeof t=="string"?t:t.slice().buffer}function mi(t){if(typeof t=="string")return {data:t,isText:true};if(t instanceof ArrayBuffer)return {data:new Uint8Array(t),isText:false};if(ArrayBuffer.isView(t)){let e=t;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var Sb=5e3,cu=3e4,uu=2e3,kb=1e4,Rb=3,mu=1;async function pu(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let i=e.log===void 0?y=>console.info(y):e.log,o=y=>i?.(`[gem host] ${y}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,c=(y,C)=>{l&&(a=a.then(async()=>{if(!d)try{await C();}catch(F){o(`the bundle's ${y} handler threw: ${ft(F)}. Serving continues.`);}}));},u=true,p,g,f,h=y=>{if(!u)return;u=false,c("leave",()=>s.leave?.(r,{cause:y??"left"}));let C=g;C&&queueMicrotask(()=>C(y));},k={send(y,C){if(!u)return;let F=Nt(gt(C));c("message",()=>s.message?.(r,y,typeof y=="string",{reliable:F.reliable,ordered:F.ordered}));},onMessage(y){p=y;},onClose(y){g=y;},close(){h("closed");}},x=(y,C)=>{if(!u)return;let F=Nt(gt(C));queueMicrotask(()=>{u&&p?.(y,F);});},P=new Map,b=y=>{let C=[];for(let F of je){let Z=y.channels[F];try{Z.binaryType="arraybuffer";}catch{}let ke=Nt(F),Fe=Wt=>{let bt=mi(Wt?.data);bt!==null&&c("message",()=>s.message?.(y.playerId,bt.data,bt.isText,{reliable:ke.reliable,ordered:ke.ordered}));};Z.addEventListener("message",Fe),C.push(()=>Z.removeEventListener("message",Fe));}P.get(y.playerId)?.forEach(F=>F()),P.set(y.playerId,C);},S=y=>{P.get(y)?.forEach(C=>C()),P.delete(y);},I=new Set,T=new Map,H=(y,C,F)=>({playerNumber:y.assignedPeerId,transport:"webrtc_p2p",...C?{rejoin:true}:{},...F?{superseded:true}:{}}),N=y=>{let C=P.has(y.playerId),F=I.has(y.playerId);I.add(y.playerId),b(y),C&&c("leave",()=>s.leave?.(y.playerId,{cause:"superseded"})),c("join",()=>s.join?.(y.playerId,H(y,F,C)));},B=new Set,E=(y,C,F)=>{if(y===r){x(C,F);return}let Z=n.peer(y);if(Z===null){let ke=T.get(y);if(ke!==void 0&&e.clock.now()-ke<uu)return;B.has(y)||(B.add(y),o(`send to '${y}' dropped: no such connected player`));return}Z.send(Cn(C),gt(F));},O={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:y=>e.tokens.subscribe(y),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(y=>y.playerId)??[],players(){let y=u?[r]:[];for(let C of n.peers)y.push(C.playerId);return y},profile(y){let C=e.room()?.members.find(F=>F.playerId===y);if(!(!C||C.displayName===void 0))return {displayName:ot.toPlain(C.displayName),...C.displayTag===void 0?{}:{displayTag:ot.toPlain(C.displayTag)},...C.discriminator===void 0?{}:{discriminator:C.discriminator}}},playerNumber(y){return y===r?mu:n.peer(y)?.assignedPeerId},send(y,C,F){E(y,C,F);},broadcast(y,C){let F=C?.except;u&&r!==F&&x(y,C);for(let Z of n.peers)Z.playerId!==F&&Z.send(Cn(y),gt(C));},async endMatch(){let y=await Ue();return y.answer!=="ok"&&o(y.cause),y.answer},kick(y,C){if(y===r){h(C??"kicked");return}n.kick(y).catch(F=>{o(`kick of '${y}' failed: ${ft(F)}`);});},log(y){o(y);},warn(y){o(`\u26A0 ${y}`);}},$=()=>{},j=new Promise(y=>{$=y;}),U=[],J=null,oe=async(y,C)=>{l=false;let F=a.then(async()=>{try{await s.shutdown(y);}catch(Z){o(`the bundle's shutdown threw: ${ft(Z)}`);}});a=F,await F,De();for(let Z of U.splice(0))Z();for(let Z of [...P.keys()])S(Z);h(C);},ge=(y,C)=>J||(J=(async()=>{await oe(C,y),n.close(),$();})(),J),X=()=>J||(J=(async()=>{await oe({reason:"signal"},"left"),await n.leave().catch(y=>o(`leaving the match failed: ${ft(y)}`)),$();})(),J),Be=()=>J||(J=(async()=>{l=false;let y=await Ue();y.answer==="ok"?(await oe({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(o(`${y.cause}; leaving instead`),await oe({reason:"signal"},"left"),await n.leave().catch(C=>o(`leaving the match failed: ${ft(C)}`))),$();})(),J),Se=null,fe=()=>(Se??=qt(O,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Se),Ue=async()=>{try{return await sl({client:fe().client,gameId:()=>O.gameId},O.matchId,{},{signal:AbortSignal.timeout(Sb)}),{answer:"ok"}}catch(y){return y instanceof M&&(y.reason==="forbidden"||y.reason==="not_found")?{answer:y.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${y.reason})`}:{answer:"failed",cause:`ending the match failed: ${ft(y)}`}}},te=null,z=false,le=0,xe,Le=null,De=()=>{z=true,te!==null&&(e.clock.clearTimeout(te),te=null),Le?.(),Le=null;},Nn=y=>{o(`heartbeats paused: ${y}; they resume when a fresh play token arrives`),Bt();let C=xe,F=false,Z=e.tokens.subscribe(ke=>{F||z||ke.token===C||nt(ke)||(F=true,Le?.(),Le=null,le=0,xe=void 0,Bt(),o("a fresh play token arrived; heartbeats resume"),te=e.clock.setTimeout(()=>{We();},0));});F?Z():Le=Z;},Bt=()=>{let y=Se;Se=null,y?.dispose();},nt=y=>y.expiresAt*1e3<=e.clock.now(),We=async()=>{if(te=null,!z){try{await fe().client.post(`/v1/games/${encodeURIComponent(O.gameId)}/matches/${encodeURIComponent(O.matchId)}/heartbeat`,void 0,AbortSignal.timeout(kb)),le=0,xe=void 0;}catch(y){if(y instanceof M&&(y.reason==="forbidden"||y.reason==="not_found")){o(`the platform no longer holds this match under this host (${y.reason}); heartbeats stop`),De();return}if(Ab(y)){if(z)return;le+=1;let C=e.tokens.current(),F=C===void 0?"this host holds no play token":nt(C)?"this host's play token has expired":C.token===xe?"the platform refused this host's play token again":le>=Rb?`the platform refused this host's play token ${le} times in a row`:null;if(xe=C?.token,F!==null){Nn(F);return}}else le=0,xe=void 0;o(`heartbeat failed: ${ft(y)}`);}z||(te=e.clock.setTimeout(()=>{We();},cu));}},$e=()=>{z||te!==null||(te=e.clock.setTimeout(()=>{We();},cu));};{let y=$;$=()=>{De(),Se?.dispose(),Se=null,y();};}let Ut=Promise.resolve().then(()=>s.init(O));a=Ut.then(()=>{},()=>{}),c("join",()=>s.join?.(r,{playerNumber:mu,transport:"loopback"})),U.push(n.on("peerJoined",N)),U.push(n.on("peerLeft",(y,C)=>{S(y);let F=e.clock.now();for(let[Z,ke]of T)F-ke>=uu&&T.delete(Z);T.set(y,F),B.delete(y),c("leave",()=>s.leave?.(y,{cause:C}));})),U.push(n.on("error",y=>{o(`\u26A0 session error: ${y.message}`);})),U.push(n.on("matchEnded",y=>{J||va(f,y),ge("match ended",{reason:"match_ended",platform_reason:y});})),U.push(n.on("hostChanged",y=>{y!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let y of n.peers)N(y);try{await Ut,$e();}catch(y){l=false,De(),d=true;for(let C of U.splice(0))C();for(let C of [...P.keys()])S(C);throw n.leave().catch(()=>{}),$(),y}return {matchId:n.matchId,localLink:k,onMatchEnded(y){f=y;},end:Be,leave:X,stop:y=>ge(y,{reason:"stopped"}),done:j}}function va(t,e){try{t?.(e);}catch{}}function Ab(t){return t instanceof M&&t.status===401||ne.isAuthError(t)}function ft(t){return t instanceof Error?t.message:String(t)}function _a(t,e){let n=async()=>{throw new w("misconfigured",`this seat is \`${t}\`, not the match's authority: `+(t==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:t,matchId:e,end:n,leave:n,stop:async()=>{}}}function gu(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,i=new Map,o=async a=>{r.isHost&&!fa(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...a.signal===void 0?{}:{signal:a.signal}});let l={...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},s=a=>({...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0?{}:{clusterTargetId:a.clusterTargetId}});return {async serve(a,l={}){let d=await o(l);if(d.protocol!==mt)return _a("dedicated",d.matchId);let c=t.p2p.session?.(d.matchId)??null;if(c===null&&!r.isHost||c!==null&&!c.isHost)return _a("peer",d.matchId);let u=t.identity();if(u===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=c??await t.p2p.connect(s(l)),g=await pu(a,{session:p,clock:t.clock,gameId:u.gameId,channel:u.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:u.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return i.set(d.matchId,g),g.done.then(()=>{i.get(d.matchId)===g&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(a={}){let l=await o(a),d=a.onMatchEnded;if(l.protocol===mt){let g=i.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),Eb(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let f=await kn(),h=async()=>t.p2p.connect({...s(a),certificate:f}),k=await h(),x=Cb(k,h,d,P=>{r.notifyMatchDisconnected(P).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(k.matchId,{redial:x.redial,abandon:x.abandon}),x.onClosed(()=>{e.get(k.matchId)?.abandon===x.abandon&&e.delete(k.matchId);})),x}let c=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),u=await c(),p=Ib(u,c,r,n);return n&&(e.set(u.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(u.matchId)?.abandon===p.abandon&&e.delete(u.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var fu="link_closed",xb="host_unreachable",Pb=new Set(["failed","closed"]);function Tb(t){return Pb.has(t)?fu:xb}function Eb(t,e,n){let r=e.localLink;e.onMatchEnded(n);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:t,protocol:"loopback",get state(){return i},send:(s,a)=>r.send(s,a),onMessage:s=>r.onMessage(s),onClose:s=>{o=s,r.onClose(a=>{i="closed",o?.(a);});},close:()=>r.close()}}function Ib(t,e,n,r){let i=t.matchId,o=t,s="connected",a,l,d=[],c=false,u=false,p=f=>{if(s!=="closed"){s="closed";for(let h of d.splice(0))h();l?.(f);}},g=f=>{f.link.onMessage((h,k)=>a?.(h,k)),f.link.onClose(h=>{if(f!==o||s==="closed")return;if(c||!r){p(h);return}let k=n.matchSession;if(k.phase==="suspended"&&k.matchId===i){s="suspended";return}p(h);});};return g(t),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return s},send(f,h){s==="connected"&&o.link.send(f,h);},onMessage(f){a=f;},onClose(f){l=f;},close(){if(s!=="closed"){if(c=true,s==="suspended"){p("closed");return}o.close(),p("closed");}},async redial(f){if(s==="closed"||c)return "closed";if(u)return "connected";u=true;let h;try{h=await e(f===void 0?{}:{deadlineAt:f});}finally{u=false;}return c||s==="closed"?(h.close(),"closed"):(o=h,g(h),s="connected",n.notifyMatchConnected(i),"connected")},abandon(f){s!=="closed"&&(s==="connected"&&o.close(),p(f));},onClosed(f){s==="closed"?f():d.push(f);}}}function Cb(t,e,n,r,i,o=false){let s=t.matchId,a=t,l,d,c=[],u=[],p=[],g=false,f=false,h=false,k=false,x="connected",P=E=>{if(g)return;g=true,x="closed";for(let $ of c.splice(0))$();for(let $ of u.splice(0))$();for(let $ of p.splice(0))$();let O=d;O&&queueMicrotask(()=>O(E));},b=E=>{for(let O of c.splice(0))O();for(let O of je){let $=E.channels[O];try{$.binaryType="arraybuffer";}catch{}let j=Nt(O),U=J=>{let oe=mi(J?.data);oe!==null&&l?.(oe.data,j);};$.addEventListener("message",U),c.push(()=>$.removeEventListener("message",U));}},S=()=>a.peer(a.hostPlayerId),I=E=>{if(!(g||a.isHost)&&x!=="suspended"){if(r?.(E),o){x="suspended";return}P(E);}},T=E=>{for(let O of je){let $=E.channels[O];if(typeof $.addEventListener!="function")continue;let j=()=>{S()===E&&I(fu);};$.addEventListener("close",j),c.push(()=>$.removeEventListener?.("close",j));}},H=E=>{b(E),T(E),!g&&(x="connected",i?.());},N=E=>{for(let O of u.splice(0))O();u.push(E.on("migrating",()=>{k=true;})),u.push(E.on("hostChanged",O=>{if(k=false,O===E.playerId){P("host_migrated_here");return}let $=S();$!==null&&H($);})),u.push(E.on("peerJoined",O=>{O.playerId===E.hostPlayerId&&H(O);})),u.push(E.on("matchEnded",O=>{g||va(n,O),P(O);})),u.push(E.on("peerLeft",(O,$)=>{O===E.hostPlayerId&&I(Tb($));}));};N(a);let B=S();return B!==null&&H(B),{matchId:s,protocol:"p2p",get state(){return x},send(E,O){x==="connected"&&S()?.send(Cn(E),gt(O));},onMessage(E){l=E;},onClose(E){d=E;},close(){f=true,P("closed"),a.leave().catch(()=>{});},async redial(){if(x==="closed")return "closed";if(x==="connected"||h)return "connected";if(k)throw new D("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");h=true;let E;try{for(let $ of c.splice(0))$();for(let $ of u.splice(0))$();a.close(),E=await e();}finally{h=false;}if(g)return f?E.leave().catch(()=>{}):E.close(),"closed";a=E,N(a);let O=S();if(O===null)throw a.close(),new D("connection_failed","this peer rejoined the match but the host never answered with a link");return H(O),"connected"},abandon(E){P(E);},onClosed(E){g?E():p.push(E);}}}function yu(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},s=l=>{n.delete(r)&&(t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>s(void 0),t.timeoutMs??2e3);let a=false;try{a=t.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){n.get(r)?.(i);}}}var Mb=12e4;function yt(t,e){return {outcome:t,reason:e}}function hu(t){let e=false,n=new Map,r=(i,o,s,a)=>{if(!t.bridge.parentSupports(i))return Promise.resolve(yt("unavailable","error"));if(e)return Promise.resolve(yt("declined","busy"));let l=`purchase-${_e()}`;return new Promise(d=>{let c={},u=g=>{n.delete(l)&&(e=false,t.clock.clearTimeout(c.timer),d(g));};e=true,n.set(l,{finish:u,check:s,label:a}),c.timer=t.clock.setTimeout(()=>u(yt("unavailable","error")),t.timeoutMs??Mb);let p=false;try{p=o(l);}catch{}p||u(yt("unavailable","error"));})};return {api:{request(i){return r("purchases",o=>t.bridge.requestPurchase(o,i.kind,i.targetId,i.currencySlug,i.quantity,i.catalogId),o=>o===void 0?null:t.confirm(o),o=>`purchase ${JSON.stringify(o)}`)}},requestAvatar3d(i){return r("avatar3dPurchases",o=>t.bridge.requestAvatar3dPurchase(o,i.itemId,i.currencySlug),()=>t.confirmAvatar3d(i.itemId),()=>`3D avatar ${JSON.stringify(i.itemId)}`)},settle(i){let o=i.outcome==="ok"||i.outcome==="declined"?i.outcome:"unavailable",s=n.get(i.requestId);if(s===void 0){t.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(i.requestId));return}let{finish:a}=s;if(o!=="ok"){a(yt(o,Al(i.reason)));return}let l=i.purchaseId,d;try{d=s.check(l);}catch{d=Promise.resolve("unknown");}if(d===null){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),a(yt("unavailable","error"));return}(async()=>{let c;try{c=await d;}catch{c="unknown";}if(c==="granted"){a(l===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:l});return}c==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(yt("unavailable","error"));})();}}}async function bu(t,e){try{return (await Us(t,e)).granted?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}var Ob="small_human",vu=/^[a-z][a-z0-9_]{0,31}$/,_u=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Gb=8;function wa(t){if(t===null)return [];if(t.avatars3d!==void 0)return t.avatars3d;let{avatar3dId:e,avatar3dModelUrl:n,avatar3dIconUrl:r}=t;return e===void 0||n===void 0||r===void 0?[]:[{family:Ob,id:e,modelUrl:n,iconUrl:r}]}function Lb(t,e){return t.length===e.length&&t.every((n,r)=>{let i=e[r];return n.family===i.family&&n.id===i.id&&n.modelUrl===i.modelUrl})}function Db(t){let e=t??{},n=typeof e.item_id=="string"&&_u.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&vu.test(e.family)?e.family:void 0,i=typeof e.slug=="string"&&e.slug!==""?e.slug:void 0,o=typeof e.display_name=="string"&&e.display_name!==""?e.display_name:void 0,s=typeof e.description=="string"&&e.description!==""?e.description:void 0,a=Tt(e.icon_url),l=Tt(e.model_url),d=[];for(let c of Array.isArray(e.prices)?e.prices:[]){let u=c??{};typeof u.currency_slug=="string"&&u.currency_slug!==""&&typeof u.price=="number"&&Number.isSafeInteger(u.price)&&u.price>0&&d.push({currencySlug:u.currency_slug,price:u.price});}if(!(n===void 0||r===void 0||i===void 0||o===void 0||a===void 0||l===void 0||d.length===0))return {itemId:n,slug:i,family:r,displayName:o,...s===void 0?{}:{description:s},iconUrl:a,modelUrl:l,prices:d}}function $b(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&vu.test(n)&&!e.includes(n)&&e.push(n),e.length===Gb)break;return e}function wu(t){let e=new Set,n=wa(t.player()),r=i=>{t.log?.(`[gem] an avatars3d onChange listener threw: ${i instanceof Error?i.message:String(i)}`);};return t.subscribe(i=>{let o=wa(i);if(!Lb(n,o)){n=o;for(let s of [...e])try{s(o);}catch(a){r(a);}}}),{async families(){return $b(await t.configFamilies())},worn(i){let o=wa(t.player());if(i!==void 0)return o.find(l=>l.family===i);let a=t.player()?.avatar3dId;return (a===void 0?void 0:o.find(l=>l.id===a))??o[0]},async offers(){let i=await t.readOffers(),o=[];for(let s of Array.isArray(i?.offers)?i.offers:[]){let a=Db(s);a!==void 0&&o.push(a);}return o},purchase(i){let o=i?.itemId,s=i?.currencySlug;return typeof o!="string"||!_u.test(o)?Promise.resolve({outcome:"declined",reason:"not_purchasable"}):typeof s!="string"||s===""?Promise.resolve({outcome:"declined",reason:"unknown_currency"}):t.purchase({itemId:o,currencySlug:s})},onChange(i){return e.add(i),()=>{e.delete(i);}}}}async function Su(t,e){try{return (await ks(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}function ku(t){return $s(t)}var Fb=6e5;function Ru(t){let e=null,n=new Map;return {api:{requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${_e()}`;return e=new Promise(i=>{let o={},s=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>{s({outcome:"unavailable"});},t.timeoutMs??Fb);let a=false;try{a=t.bridge.requestSignIn(r);}catch{}a||s({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var qb=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),Nb=["utm_"];function Au(t){return qb.has(t)||Nb.some(e=>t.startsWith(e))}var xu=16,Pu=512,jb=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Bb=/[\p{Cc}\p{Cf}]/u,Ub=/\p{Cs}/u,Oe="[gem] gem.share.request:";function Tu(t){let{frame:e,log:n}=t,r=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,o=s=>{n!==null&&(n===void 0?console.warn(s):n(s));};return {get available(){return i()!==null},request(s){let a=i();if(a===null)throw new Error(`${Oe} the arcade does not handle share here \u2014 check gem.share.available first`);if(s!==void 0&&(typeof s!="object"||s===null))throw new TypeError(`${Oe} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!Wb(l))throw new TypeError(`${Oe} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>xu)throw new TypeError(`${Oe} at most ${xu} params; got ${d.length}`);let c=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!jb.test(u))throw new TypeError(`${Oe} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Au(u))throw new TypeError(`${Oe} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Oe} param ${g}: values must be strings`);if(p.length>Pu)throw new TypeError(`${Oe} param ${g}: a value is at most ${Pu} characters`);if(Bb.test(p))throw new TypeError(`${Oe} param ${g}: control and format characters are not allowed`);if(Ub.test(p))throw new TypeError(`${Oe} param ${g}: a value must be well-formed text`);c.push({key:u,value:p});}!a.requestShare(c)&&!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 Wb(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Mn=3e4,Sa=12e4;function On(t,e,n){return t.held?Promise.resolve(n):(t.held=true,e().then(r=>(t.held=false,r)))}function ce(t,e,n){return {outcome:t,reason:e,...n}}function et(t){let e=t.outcome==="ok"||t.outcome==="declined"?t.outcome:"unavailable";return typeof t.reason=="string"?{outcome:e,reason:t.reason}:{outcome:e}}function Eu(t){let e=new Map;return {ask(n,r,i,o){let s=`arcade-${_e()}`;return new Promise(a=>{let l={},d=u=>{e.delete(s)&&("timer"in l&&t.clearTimeout(l.timer),a(i(u)));};e.set(s,{expect:n,finish:d}),o!==void 0&&(l.timer=t.setTimeout(()=>d(null),o));let c=false;try{c=r(s);}catch{}c||d(null);})},settle(n){let r=e.get(n.requestId);return r===void 0||r.expect!==n.type?false:(r.finish(n),true)},abandon(){for(let n of [...e.values()])n.finish(null);}}}var Hb=12,Vb=24,ka=Object.freeze({games:Object.freeze([])});function Kb(t){let e=(n,r)=>he(n,`GameCard.${r}`);return Object.freeze({gameId:t.gameId,...t.slug===void 0?{}:{slug:t.slug},name:e(t.untrusted.name,"name"),tagline:e(t.untrusted.tagline,"tagline"),shortDescription:e(t.untrusted.shortDescription,"shortDescription"),tags:Object.freeze(t.untrusted.tags.map(n=>e(n,"tags"))),iconUrl:t.iconUrl,capsuleLandscapeUrl:t.capsuleLandscapeUrl,capsulePortraitUrl:t.capsulePortraitUrl,...t.previewVideoUrl===void 0?{}:{previewVideoUrl:t.previewVideoUrl},...t.previewPosterUrl===void 0?{}:{previewPosterUrl:t.previewPosterUrl}})}function pi(t){return ce("unavailable","error",t)}function Iu(t){let{bridge:e,asker:n,acting:r}=t,i=a=>e.currentState==="connected"&&e.parentSupports(a),o=new Map,s=(a,l)=>{let d=o.get(a);if(d!==void 0)return d;let c=l().then(u=>(o.delete(a),u));return o.set(a,c),c};return {get available(){return {appLinks:i("appLinks"),openGame:i("openGame")}},appLinks(){return e.parentSupports("appLinks")?s("appLinks",()=>n.ask("gem.appLinksResult",a=>e.requestArcade({type:"gem.requestAppLinks",requestId:a}),a=>{if(a===null)return pi({});let l=a;return {...et(a),...l.arcade===void 0?{}:{arcade:{store:l.arcade.store}},...l.game===void 0?{}:{game:{store:l.game.store}}}},Mn)):Promise.resolve(ce("unavailable","unsupported",{}))},openApp(a){return e.parentSupports("appLinks")?a!=="arcade"&&a!=="game"?Promise.resolve(ce("unavailable","invalid_argument",{})):On(r,()=>n.ask("gem.openAppResult",l=>e.requestArcade({type:"gem.requestOpenApp",requestId:l,target:a}),l=>l===null?pi({}):et(l),Sa),ce("declined","busy",{})):Promise.resolve(ce("unavailable","unsupported",{}))},openGame(a){if(!e.parentSupports("openGame"))return Promise.resolve(ce("unavailable","unsupported",{}));let l=typeof a=="string"?a.toLowerCase():"";return wl({gem:q,type:"gem.requestOpenGame",requestId:"-",ref:l})!==null?Promise.resolve(ce("unavailable","invalid_argument",{})):On(r,()=>n.ask("gem.openGameResult",c=>e.requestArcade({type:"gem.requestOpenGame",requestId:c,ref:l}),c=>c===null?pi({}):et(c),Sa),ce("declined","busy",{}))},similarGames(a){if(!e.parentSupports("openGame"))return Promise.resolve(ce("unavailable","unsupported",ka));let l=a?.limit;return l!==void 0&&(typeof l!="number"||!Number.isInteger(l)||l<1||l>Vb)?Promise.resolve(ce("unavailable","invalid_argument",ka)):s(`similar:${l??Hb}`,()=>n.ask("gem.similarGamesResult",d=>e.requestArcade({type:"gem.requestSimilarGames",requestId:d,...l===void 0?{}:{limit:l}}),d=>{if(d===null)return pi(ka);let c=et(d),u=d,p=c.outcome==="ok"?Object.freeze(u.games.map(Kb)):[];return {...c,games:p}},Mn))}}}var Jb=64,Cu=Object.freeze({offers:Object.freeze([])});function zb(t){return Object.freeze({skuId:t.skuId,kind:t.kind,name:t.name,description:t.description,...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl},priceDisplay:t.priceDisplay,...t.grant===void 0?{}:{grant:Object.freeze({currency:t.grant.currency,amount:t.grant.amount})}})}function Mu(t){let{bridge:e,asker:n,acting:r}=t,i=new Set,o=null;function s(a,l,d,c){return e.parentSupports(a)?typeof c!="string"||c.length===0||c.length>Jb?Promise.resolve(ce("unavailable","invalid_argument",{})):On(r,()=>n.ask(d,u=>e.requestArcade({type:l,requestId:u,skuId:c}),u=>u===null?ce("unavailable","error",{}):et(u)),ce("declined","busy",{})):Promise.resolve(ce("unavailable","unsupported",{}))}return {api:{get available(){return e.currentState==="connected"&&e.parentSupports("store")},get showOfferAvailable(){return e.currentState==="connected"&&e.parentSupports("storeOfferSheet")},offers(){return e.parentSupports("store")?(o!==null||(o=n.ask("gem.storeOffersResult",a=>e.requestArcade({type:"gem.requestStoreOffers",requestId:a}),a=>{if(a===null)return ce("unavailable","error",Cu);let l=et(a),d=a,c=l.outcome==="ok"?Object.freeze(d.offers.map(zb)):[];return {...l,offers:c}},Mn).then(a=>(o=null,a))),o):Promise.resolve(ce("unavailable","unsupported",Cu))},purchase(a){return s("store","gem.requestStorePurchase","gem.storePurchaseResult",a)},showOffer(a){return s("storeOfferSheet","gem.requestStoreOfferSheet","gem.storeOfferSheetResult",a)},onSettled(a){return i.add(a),()=>{i.delete(a);}}},settled(a){let l=Object.freeze({skuId:a.skuId});for(let d of [...i])try{d(l);}catch(c){t.onListenerError?.(c);}}}}var Fu="https://gemarcade.com/branding/manifest.json",Xb=1,Ou=256*1024,Yb=256,Qb=64,Zb=256,Gu=8e3,ev=6e4,tv=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Lu={GEMS:"gems-mark",ARCADE_TICKETS:"ticket-mark"},Du=Object.freeze({outcome:"unavailable"}),$u=Object.freeze({outcome:"not_found"});function ht(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function fi(t){return typeof t=="string"&&t!==""&&t.length<=Zb}function nv(t,e){if(!fi(t))return;let n;try{n=new URL(t,e);}catch{return}let r=Tt(n.href);if(r!==void 0)return n.origin===new URL(e).origin?r:Xi(r)}function rv(t,e){let n=t??{},r=nv(n.url,e);if(!(r===void 0||!fi(n.type))&&!(typeof n.bytes!="number"||!(n.bytes>=0))&&!(n.theme!==void 0&&n.theme!=="light"&&n.theme!=="dark"))return Object.freeze({url:r,type:n.type,bytes:n.bytes,...ht(n.width)?{width:n.width}:{},...ht(n.height)?{height:n.height}:{},...ht(n.size)?{size:n.size}:{},...ht(n.density)?{density:n.density}:{},...n.vector===true?{vector:true}:{},...n.theme===void 0?{}:{theme:n.theme}})}function iv(t,e=Fu){let n;try{n=JSON.parse(t);}catch{return null}let r=n??{};if(r.format!==Xb||!Array.isArray(r.assets))return null;let i=[],o=new Set;for(let s of r.assets.slice(0,Yb)){let a=s??{};if(!fi(a.id)||!tv.test(a.id)||o.has(a.id)||!fi(a.kind)||!Array.isArray(a.variants))continue;let l=[];for(let d of a.variants.slice(0,Qb)){let c=rv(d,e);c!==void 0&&l.push(c);}l.length!==0&&(o.add(a.id),i.push(Object.freeze({id:a.id,kind:a.kind,variants:Object.freeze(l)})));}return Object.freeze(i)}function gi(t){let e;for(let n of t)(e===void 0||(n.width??0)>(e.width??0))&&(e=n);return e}function ov(t,e,n){let r=t.find(l=>l.vector===true),i=t.filter(l=>l.size===void 0);if(e===void 0)return r??gi(i)??gi(t);let o=t.filter(l=>l.size===e);if(o.length>0){let l=c=>c.density??1,d=o.filter(c=>l(c)>=n);return d.length>0?d.reduce((c,u)=>l(u)<l(c)?u:c):o.reduce((c,u)=>l(u)>l(c)?u:c)}if(r!==void 0)return r;let s=i.filter(l=>(l.width??0)>=e*n);return (s.length>0?s.reduce((l,d)=>(d.width??0)<(l.width??0)?d:l):void 0)??gi(i)??gi(t)}function av(t,e){let n=e.theme===void 0?[]:t.variants.filter(a=>a.theme===e.theme),r=t.variants.filter(a=>a.theme===void 0),i=[n,r].filter(a=>a.length>0);if(t.kind!=="image")return i[0]?.[0];let s=(e.size===void 0?void 0:i.find(a=>a.some(l=>l.size===e.size)))??i[0];return s&&ov(s,e.size,e.density)}function sv(t,e){if(e!==void 0){if(e===null||typeof e!="object")throw new TypeError(`[gem] branding.${t}: options must be an object`);if(e.size!==void 0&&!ht(e.size))throw new RangeError(`[gem] branding.${t}: size must be a positive number of CSS px`);if(e.density!==void 0&&!ht(e.density))throw new RangeError(`[gem] branding.${t}: density must be a positive number`);if(e.theme!==void 0&&e.theme!=="light"&&e.theme!=="dark")throw new TypeError(`[gem] branding.${t}: theme must be 'light' or 'dark'`)}}function qu(t){let e=t.manifestUrl??Fu,n=null,r=null,i=-1/0,o=false,s=c=>(i=t.clock.now(),o||(o=true,t.log?.(`[gem] gem.branding could not read the platform's branding (${c}), so every lookup answers 'unavailable' and your bundled fallback shows. If your page sets a Content-Security-Policy, allow ${new URL(e).origin} in connect-src and img-src.`)),null),a=async()=>{if(t.fetch===null)return s("this page has no fetch");let c=t.fetch,u=typeof AbortController=="function"?new AbortController:null,p,g=new Promise(h=>{p=t.clock.setTimeout(()=>{u?.abort(),h(s(`no answer in ${Gu} ms`));},Gu);}),f=(async()=>{let h=await c(e,{credentials:"omit",redirect:"error",...u?{signal:u.signal}:{}});if(!h.ok)return s("the manifest answered an error");if(Number(h.headers.get("content-length"))>Ou)return s("the manifest is too large");let k=await h.text();return k.length>Ou?s("the manifest is too large"):iv(k,e)??s("the manifest is not format 1 JSON")})().catch(()=>s("the request failed"));try{return await Promise.race([f,g])}finally{t.clock.clearTimeout(p);}},l=()=>n!==null?Promise.resolve(n):r!==null?r:t.clock.now()-i<ev?Promise.resolve(null):(r=a().then(c=>(r=null,c!==null&&(n=c),c)),r),d=async(c,u,p,g)=>{sv(c,g);let f=await l();if(f===null)return Du;let h=f.find(P=>P.id===u&&P.kind===p);if(h===void 0)return $u;let k=t.devicePixelRatio(),x=av(h,{...g?.size===void 0?{}:{size:g.size},density:g?.density??(ht(k)?k:1),...g?.theme===void 0?{}:{theme:g.theme}});return x===void 0?$u:Object.freeze({outcome:"ok",url:x.url,variant:x,asset:h})};return Object.freeze({get:async(c,u)=>{if(typeof c!="string"||c==="")throw new TypeError("[gem] branding.get: id must be a non-empty string");if(u===null||typeof u!="object"||typeof u.kind!="string")throw new TypeError("[gem] branding.get: options.kind must be a string, such as 'image'");return d("get",c,u.kind,u)},logo:c=>d("logo","gem-logo","image",c),wordmark:c=>d("wordmark","gem-wordmark","image",c),currencyMark:async(c,u)=>{let p=Object.prototype.hasOwnProperty.call(Lu,c)?Lu[c]:void 0;if(p===void 0)throw new TypeError("[gem] branding.currencyMark: currency must be 'GEMS' or 'ARCADE_TICKETS', not "+JSON.stringify(String(c).slice(0,40)));return d("currencyMark",p,"image",u)},trophy:c=>d("trophy","trophy-mark","image",c),list:async()=>{let c=await l();return c===null?Du:Object.freeze({outcome:"ok",assets:c})}})}var uv="(any-pointer: coarse)";function mv(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 Nu(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?c=>matchMedia(c):void 0},i=r.navigator,o,s=new Set,a=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia(uv),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(c,u)=>{s.has(c)||(s.add(c),n!==null&&(n===void 0?console.warn(u):n(u)));};return {get available(){return a()||l()},vibrate(c){let u=a();if(!u&&!l())return false;let p=mv(c);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(u)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 jt=Math.PI/180,Ge=Object.freeze({touch:Object.freeze({yaw:1*jt,pitch:.66*jt}),mouse:Object.freeze({yaw:.5*jt,pitch:.5*.77*jt}),stick:Object.freeze({yaw:240*jt,pitch:240*.77*jt}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Ra="[gem.controls]",Aa=Object.freeze({yaw:0,pitch:0}),yi=t=>Number.isFinite(t)?t:0,ju=(t,e)=>({yaw:t+0,pitch:e+0});function Bu(t){let e=yi(t),n=(Math.abs(e)-Ge.stickDeadzone)/(1-Ge.stickDeadzone),r=Ge.stickCurve,i=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,i))+0}function pv(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Ge.touchPitchMin)+Ge.touchPitchMin}function Uu(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${Ra} ${e} takes an options object`);let n=t;for(let r of ["sensitivity","gamepadSensitivity"]){let i=n[r];if(i!==void 0&&!(typeof i=="number"&&Number.isFinite(i)&&i>0))throw new TypeError(`${Ra} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(i)}`)}if(n.invertY!==void 0&&typeof n.invertY!="boolean")throw new TypeError(`${Ra} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function gv(t,e){let n=Uu(e,"look()"),r=n.sensitivity,i=n.gamepadSensitivity,o=n.invertY,s=a=>o??a?.invertLookY??false;return {fromPointer(a,l,d,c){let u=yi(a),p=yi(l);if(u===0&&p===0)return Aa;let g=t(),f=r??(g===null?void 0:g.lookSensitivity/100)??1,h=d==="touch"||d==="pen",k=h?Ge.touch:Ge.mouse,x=u*k.yaw*f,P=-p*k.pitch*f;return s(g)&&(P=-P),h&&c!==void 0&&Number.isFinite(c)&&P*c>0&&(P*=pv(c)),ju(x,P)},fromStick(a,l,d){let c=yi(d);if(c<=0)return Aa;let u=Bu(a),p=Bu(l);if(u===0&&p===0)return Aa;let g=t(),f=i??(g===null?void 0:g.gamepadLookSensitivity/100)??1,h=u*Ge.stick.yaw*c*f,k=-p*Ge.stick.pitch*c*f;return s(g)&&(k=-k),ju(h,k)},set(a){let l=Uu(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(i=l.gamepadSensitivity),"invertY"in l&&(o=l.invertY);}}}function Wu(t){return {look:e=>gv(t.recommended,e),LOOK_BASE:Ge}}var Hu=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),Vu=/^[A-Za-z0-9_-]{1,40}$/;function xa(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function Ku(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function Ju(t,e,n,r){let i=a=>Number.parseFloat(a.toPrecision(12)),o=Math.min(n,Math.max(e,t)),s=i(e+Math.round((o-e)/r)*r);return s>n&&(s=i(s-r)),Math.min(n,Math.max(e,s))}function zu(t,e){switch(t.kind){case "toggle":return typeof e=="boolean"?e:void 0;case "slider":{if(typeof e!="number"||!Number.isFinite(e))return;let n=t.min??0,r=t.max??100;return Ju(e,n,r,t.step??1)}case "choice":return typeof e=="string"&&(t.options??[]).some(n=>n.id===e)?e:void 0;default:return}}function Xu(t,e=()=>{}){if(!Array.isArray(t))return null;let n=[],r=0;for(let i=0;i<t.length;i+=1){let o=t[i],s=`settings[${i}]`;if(n.length===8){e(`${s} and later were left out: at most 8 settings are shown.`);break}if(typeof o!="object"||o===null){e(`${s} was dropped: a setting is an object.`);continue}let a=o,l=a.id;if(typeof l!="string"||!Vu.test(l)){e(`${s} was dropped: its id must be 1 to 40 of A-Z a-z 0-9 _ -.`);continue}let d=`${s} (${JSON.stringify(l)})`;if(n.some(p=>p.id===l)){e(`${d} was dropped: an earlier setting has the same id.`);continue}let c=Ku(a.label);if(c===void 0){e(`${d} was dropped: its label is empty.`);continue}let u;switch(a.kind){case "toggle":{if(typeof a.value!="boolean"){e(`${d} was dropped: a toggle's value is true or false.`);continue}u={id:l,label:c,kind:"toggle",value:a.value},a.quick===true&&(r<2?(u.quick=true,r+=1):e(`${d} is not in the quick row: at most 2 toggles are, the first that ask.`));break}case "slider":{let p=a.min??0,g=a.max??100,f=a.step??1;if(!xa(p)||!xa(g)||!xa(f)||p>=g||f<=0){e(`${d} was dropped: a slider needs finite numbers within \xB11000000 with min below max and a step above 0.`);continue}if(typeof a.value!="number"||!Number.isFinite(a.value)){e(`${d} was dropped: a slider's value is a number.`);continue}u={id:l,label:c,kind:"slider",value:Ju(a.value,p,g,f),min:p,max:g,step:f};break}case "choice":{let p=[];for(let g of Array.isArray(a.options)?a.options:[]){if(p.length===4)break;if(typeof g!="object"||g===null)continue;let f=g,h=Ku(f.label);typeof f.id!="string"||!Vu.test(f.id)||h===void 0||p.some(k=>k.id===f.id)||p.push({id:f.id,label:h});}if(p.length<2){e(`${d} was dropped: a choice needs 2 to 4 options, each with an id of 1 to 40 of A-Z a-z 0-9 _ - and a label.`);continue}if(typeof a.value!="string"||!p.some(g=>g.id===a.value)){e(`${d} was dropped: a choice's value is the id of one of its options.`);continue}u={id:l,label:c,kind:"choice",value:a.value,options:p};break}default:e(`${d} was dropped: its kind must be 'toggle', 'slider' or 'choice'.`);continue}a.icon!==void 0&&(Hu.includes(a.icon)?u.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${Hu.join(", ")}.`)),n.push(u);}return n}var fv=500;function Yu(t){let{clock:e}=t,n=null,r=null,i=-1/0,o=null,s=new Set,a=new Set,l=u=>{a.has(u)||(a.add(u),t.log!==null&&(t.log===void 0?console.warn(u):t.log(u)));},d=()=>{let u=t.frame();return u.currentState==="connected"&&u.parentSupports("gameSettings")},c=()=>{if(n===null||o!==null)return;let u=JSON.stringify(n);if(u===r)return;let p=i+fv-e.now();if(p>0){o=e.setTimeout(()=>{o=null,c();},p);return}t.frame().declareSettings(n)&&(r=u,i=e.now());};return {api:{declare(u){let p=Xu(u,g=>l(`[gem] gem.settings.declare: ${g}`));return p===null?(l("[gem] gem.settings.declare did nothing: pass an array of settings, or [] for none."),false):(n=p,c(),d())},onChange(u){if(typeof u!="function")return ()=>{};let p=g=>u(g);return s.add(p),()=>{s.delete(p);}}},forgetSent(){r=null,i=-1/0;},flush:c,onSettingChange(u){let p=n?.findIndex(x=>x.id===u.id)??-1,g=n?.[p];if(n===null||g===void 0)return;let f=zu(g,u.value);if(f===void 0)return;let h=JSON.stringify(n);n=n.map((x,P)=>P===p?{...x,value:f}:x),r===h&&(r=JSON.stringify(n));let k={id:g.id,value:f};for(let x of [...s])try{x(k);}catch(P){console.error("[gem] a gem.settings.onChange handler threw:",P);}}}}function Qu(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var yv=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Zu(t){if(typeof t!="string"||!yv.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function Gn(){return {declared:false,grantable:false,heldLimitReached:false}}function em(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Zu(n.resets_at),i=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...Gn(),...i};let o=n.remaining_today,s=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,a=n.next_eligible_at,l=Zu(a),d=n.held_limit_reached===true,c=a!=null,u=o!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!u&&!c&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var hv=18e4,Pa=32,bv=/^[a-z0-9_-]+$/,vv="rewarded_requires_user_gesture";function _v(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var wv=1e3;function Sv(){let t=globalThis,e=t.navigator?.getGamepads,n=t.performance?.now;if(typeof e!="function"||typeof n!="function")return;let r=n.call(t.performance),i=e.call(t.navigator);for(let o=0;o<i.length;o+=1){let s=i[o]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=wv)return true}return false}var tm=1e4;function kv(t){return t==="interstitial"||t==="rewarded"}function nm(t){return typeof t=="string"&&t!==""&&t.length<=Pa&&bv.test(t)}function Rv(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function hi(t){return typeof t=="string"?JSON.stringify(t):typeof t}function rm(t){let e=false,n=new Map,r=new Map,i=new Set,o=d=>{try{t.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let c=t.log;if(c!==null)try{c===void 0?console.warn(`[gem] ${d}`):c(`[gem] ${d}`);}catch{}},l=d=>{let c=t.readAvailability;if(c===void 0)return Promise.resolve(Gn());let u=r.get(d);if(u!==void 0)return u;let p=new Promise(g=>{let f={},h=b=>f.done===true?false:(f.done=true,t.clock.clearTimeout(f.timer),g(b),true),k=(b,S)=>{!h(Gn())||i.has(b)||(i.add(b),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${S}. Said once.`));},x=b=>{k(Rv(b),`the read failed (${b instanceof Error?b.message:hi(b)})`);},P;try{P=Promise.resolve(c(d,AbortSignal.timeout(tm)));}catch(b){P=Promise.reject(b);}f.timer=t.clock.setTimeout(()=>{k("timeout","no answer within 10 s");},tm),P.then(b=>{try{h(em(b,t.bridge.parentSupports("ads")));}catch(S){x(S);}},x);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return nm(d)?l(d):(o(`gem.ads.rewardedStatus(${hi(d)}) answered not grantable: a placement is 1..${String(Pa)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(Gn()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let c=d?.placement,u=d?.format;if(!nm(c)||!kv(u))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${hi(c)}, format ${hi(u)}. A placement is 1..${String(Pa)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});if(u==="rewarded"){let g;try{g=(t.userActivation??_v)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??Sv)()===!0&&(g=!0);}catch{}if(g===false){let f=`${vv}: gem.ads.requestAd("${c}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return o(f),a(f),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${_e()}`;return new Promise(g=>{let f={},h=x=>{n.delete(p)&&(e=false,t.clock.clearTimeout(f.timer),g(x));};e=true,n.set(p,h),f.timer=t.clock.setTimeout(()=>{h({outcome:"unavailable"});},t.timeoutMs??hv);let k=false;try{k=t.bridge.requestAd(p,c,u);}catch{}k||h({outcome:"no_ad"});})}},settle(d){let c=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",u=n.get(d.requestId);if(u===void 0){t.onDropped?.(`gem.adResult (${c}) for an unknown requestId: `+JSON.stringify(d.requestId));return}u({outcome:c});}}}var im=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),om=18e4,Av=1e4,xv=/^[a-z0-9_-]{1,32}$/;function Ta(t){return typeof t=="string"?JSON.stringify(t):typeof t}var Ln=Object.freeze({shown:false});function am(t){let e=new Map,n,r=false,i=o=>{try{t.onDropped?.(o);}catch{}return Ln};return {api:{signal(o){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(Ln):(r=!0,Promise.resolve(i("moments_unsupported: gem.moments.signal answered shown: false without asking: this arcade does not do platform moments. Keep the call; it costs nothing. Said once.")));let s=o?.kind,a=o?.placement,l=o?.wall;if(!im.includes(s)||a!==void 0&&(typeof a!="string"||!xv.test(a))||l!==void 0&&typeof l!="boolean")return Promise.resolve(i(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${Ta(s)}, placement ${Ta(a)}, wall ${Ta(l)}. A kind is one of ${im.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'; a wall, when given, is true or false. Answering shown: false.`));if(!t.bridge.readyCalled())return Promise.resolve(i(`moments_before_ready: gem.moments.signal({ kind: '${s}' }) before gem.frame.ready(): a moment is a break in play, and play has not started. Signal from the press that leaves a break, never on boot. Answering shown: false.`));if(e.size>0)return Promise.resolve(i(`moments_in_flight: gem.moments.signal({ kind: '${s}' }) while another moment is still waiting for its answer. Signal once per break, and await the answer before play resumes. Answering shown: false.`));let d=t.clock.now();if(n!==void 0&&d-n<Av)return Promise.resolve(i(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(d-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let c=`moment-${_e()}`;return new Promise(u=>{let p={},g=(h,k)=>{e.delete(c)&&(t.clock.clearTimeout(p.timer),k&&(n=t.clock.now()),u(h));};e.set(c,h=>g(h,!0)),p.timer=t.clock.setTimeout(()=>{e.has(c)&&(g(Ln,!0),i(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??om)/1e3)} s. Answering shown: false.`));},t.timeoutMs??om);let f=!1;try{f=t.bridge.signalMoment(c,s,a,l===!0?!0:void 0);}catch{}f||g(Ln,!1);})}catch{return Promise.resolve(Ln)}}},settle(o){let s=e.get(o.requestId);if(s===void 0){i(`gem.momentResult (shown: ${String(o.shown)}) for an unknown requestId: `+JSON.stringify(o.requestId));return}s({shown:o.shown===true});}}}var Ea=16384;function sm(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:Pv(e)}function Pv(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=t.charCodeAt(n+1);i>=56320&&i<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var Tv=1e4,Ev=5e3;function lm(t){let e=null,n=false,r=[],i=new Map,o=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=Ev){return n?Promise.resolve(e):new Promise(a=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{t.clock.clearTimeout(c),l(),a(e);},c=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=sm(s);if(a===null)return t.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(a>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(s)),d=`device-settings-${_e()}`;return new Promise(c=>{let u={},p=f=>{i.delete(d)&&(t.clock.clearTimeout(u.timer),f==="stored"&&(e=l,n=true,o()),c(f));};i.set(d,p),u.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??Tv);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,n=true,o();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=i.get(s.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var Dn=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 Iv=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Cv(t){return typeof t=="string"&&Iv.test(t)}function bi(t){if(t===null||Cv(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 dm(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Ca(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 vi(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(e.length===4)break;if(typeof n!="object"||n===null)continue;let{id:r,label:i}=n;typeof r!="string"||r.length===0||r.length>32||typeof i!="string"||i.trim().length===0||e.some(o=>o.id===r)||e.push({id:r,label:i.trim().slice(0,40)});}return e.length===0?{settings:false}:{settings:false,items:e}}function cm(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Mv(t){let e=t.untrusted,n=he(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,i=r?he(r,"gem.player.displayTag"):void 0,o=t.discriminator||t.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=t.avatarIconUrl||t.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=t.avatarIconId,c=t.avatar3dId,u={displayName:n,displayHandle:i??n,badges:(t.badges??[]).map(h=>({itemId:h.itemId,iconUrl:h.iconUrl}))};t.playerId&&(u.playerId=t.playerId),s&&(u.discriminator=s),i&&(u.displayTag=i),a&&(u.avatarIconUrl=u.avatarUrl=a),d&&l.test(d)&&(u.avatarIconId=d),c&&l.test(c)&&(u.avatar3dId=c),t.avatar3dModelUrl&&(u.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(u.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(u.avatars3d=t.avatars3d.filter(h=>l.test(h.id)&&/^[a-z][a-z0-9_]*$/.test(h.family)).filter((h,k,x)=>x.findIndex(P=>P.family==h.family)==k).map(({family:h,id:k,modelUrl:x,iconUrl:P})=>({family:h,id:k,modelUrl:x,iconUrl:P})));let p=t.boost,g=(p?.multipliers??[]).map(h=>({currencyId:h.currencyId,currencySlug:h.currencySlug,multiplier:h.multiplierBp/1e4})),f=g.some(h=>h.multiplier>1);return u.boost=f&&p?.expiresInDays?{active:f,multipliers:g,expiresInDays:p.expiresInDays}:{active:f,multipliers:g},u}var Ov=1e4,Gv=["appLinks","openGame","store","storeOfferSheet"],Ia=new WeakMap;function mm(t,e){if(Ia.has(t))throw new Error("admitBuildEmbedders: already admitted");Ia.set(t,Object.freeze([...e]));}var $n=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??ue,this.inbound=new zt(this.clock),this.outbound=new zt(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(a=>kt(a,e.origin))||lr(e.origin,this.options.selfOrigin)||(Ia.get(this)??[]).some(a=>kt(a,e.origin))))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=sr["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!kt(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let s=Sl(ir,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:q,type:"gem.error",code:"version_mismatch",message:`frame supports v${ir.min}..v${ir.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=s,o.onmessage=a=>this.receive(a.data,a.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:q,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:q,type:"gem.ready"});}settled(e=Ov){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:q,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:q,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:q,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:q,type:"gem.exit"}:{gem:q,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:q,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:q,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:q,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:q,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:q,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:dm(e.origin.x),y:dm(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=bi(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:q,type:"gem.portraitBorders"}:{gem:q,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:q,type:"gem.walletDisplay",...Ca(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:q,type:"gem.menu",...vi(e)}):false}declareSettings(e){return this.gated("gameSettings")?this.send({gem:q,type:"gem.settingsDeclare",settings:e}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:q,type:"gem.gemCorner",corner:e}):false}setMenuStyle(e){return this.gated("menuStyle")?this.send(e===null?{gem:q,type:"gem.menuStyle"}:{gem:q,type:"gem.menuStyle",ground:e.ground,accent:e.accent}):false}requestShare(e){return this.gated("share")?this.send({gem:q,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:q,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:q,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:q,type:"gem.frameStats",fps:cm(e.fps,1e3),frameTimeP95Ms:cm(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:q,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:q,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:q,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:q,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,i,o,s){return this.send({gem:q,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}requestAvatar3dPurchase(e,n,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:q,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:q,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:q,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r,i){return this.send({gem:q,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r},...i===true?{wall:true}:{}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:q,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,i){return this.send({gem:q,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...i===void 0?{}:{params:i}})}requestArcade(e){return this.gated(ar(e.type))&&this.send({gem:q,...e})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(or)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(or)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(or)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:q,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}gated(e){return this.state==="connected"&&this.parentSupports(e)}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let n=e.type;if(!this.outbound.allow(n))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${n}`),false;let r=sr[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||um(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=sr[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=ar(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.settingChange":this.options.onSettingChange?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=n[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return um(n.slice(1)),this.options.onScreenshot(d,l,(c,u)=>this.screenshotDenied(c,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(Mv(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.ticketEvent":this.options.onTicketEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.momentResult":this.options.onMomentResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:if(Gv.includes(ar(r))){this.options.onArcadeAnswer?.(a);break}this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:q,type:"gem.screenshot.denied",reason:e,retryable:n});}};function um(t){for(let e of t)try{e?.close?.();}catch{}}var pm="https://api.gemarcade.com";function Ma(t){let e;try{e=new URL(t);}catch{return "it is not a valid URL"}return e.protocol!=="https:"&&e.protocol!=="http:"?`its scheme is ${e.protocol.replace(":","")}, and only http and https can be used`:e.username!==""||e.password!==""?"it carries credentials in the URL, which `fetch` will not send":e.href.includes("#")?"it carries a fragment. The transport joins the base and the path by concatenation, so the fragment would swallow the path and every request would go to the API root":e.href.includes("?")?"it carries a query string. The transport joins the base and the path by concatenation, so the query would swallow the path and every request would go to the API root":null}var Lv=new Set(["localhost","127.0.0.1","[::1]"]);function gm(t){let e=Ma(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!Lv.has(n.hostname)?"it is a plaintext http address that is not loopback. An embedder may name an https root, or http on localhost for a rig running the whole stack on one machine \u2014 the play token travels on every request to it":null}var hm="/gem-embedders.json",_i=4096,fm=16,ym=5e3,Fn=Object.freeze({origins:Object.freeze([])});function tt(t){return {origins:[],refused:`[gem] ${hm} was ignored: ${t}`}}function Dv(t){if(t.trim()==="")return Fn;let e;try{e=JSON.parse(t);}catch{return tt("it is not JSON.")}if(e===null||typeof e!="object"||Array.isArray(e))return tt('it must be an object, { "embedders": [...] }.');let n=e.embedders;if(n===void 0)return Fn;if(!Array.isArray(n))return tt('"embedders" must be an array of origins.');if(n.length>fm)return tt(`"embedders" has more than ${fm} entries.`);let r=n.filter(i=>typeof i!="string"||!St(i)||!i.toLowerCase().startsWith("https://")||Je(new URL(i).hostname));if(r.length>0){let i=r.slice(0,3).map(o=>typeof o=="string"?JSON.stringify(o.slice(0,100)):String(o)).join(", ");return tt(`${r.length===1?"an entry is":"entries are"} not an https origin off this machine (${i}${r.length>3?", \u2026":""}).`)}return {origins:Object.freeze([...new Set(n)])}}async function bm(t){let e=typeof AbortController=="function"?new AbortController:null,n,r=new Promise(o=>{n=t.clock.setTimeout(()=>{e?.abort(),o(tt(`it took more than ${ym} ms to read.`));},ym);}),i=(async()=>{let o=await t.fetch(t.selfOrigin+hm,{credentials:"omit",redirect:"error",...e?{signal:e.signal}:{}});if(!o.ok||(o.headers.get("content-type")??"").toLowerCase().includes("text/html"))return Fn;if(Number(o.headers.get("content-length"))>_i)return tt(`it is larger than ${_i} bytes.`);let a=await o.text();return a.length>_i?tt(`it is larger than ${_i} bytes.`):Dv(a)})().catch(()=>Fn);try{return await Promise.race([i,r])}finally{t.clock.clearTimeout(n);}}function vm(t){if(typeof t!="string"||!St(t))return null;let e=t.slice(0,t.indexOf(":")).toLowerCase();return e==="https"||e==="http"?t:null}function _m(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function $v(){let t=[["root",null],["hips","root"],["spine","hips"],["chest","spine"],["upper_chest","chest"],["neck","upper_chest"],["head","neck"],["head_socket","head"]];for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("shoulder"),"upper_chest"],[n("upper_arm"),n("shoulder")],[n("lower_arm"),n("upper_arm")],[n("hand"),n("lower_arm")],[n("hand_socket"),n("hand")]);for(let r of ["thumb","index","middle","ring","little"])for(let i=1;i<=3;i++)t.push([n(`${r}_${i}`),n(i===1?"hand":`${r}_${i-1}`)]);}for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("upper_leg"),"hips"],[n("lower_leg"),n("upper_leg")],[n("foot"),n("lower_leg")],[n("toes"),n("foot")]);}return t}var Fv=Object.freeze({small_human:_m([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:_m($v())});var Nv=Object.freeze(["https://gemarcade.com","https://developer.gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),jv=pm,Bv=["top-left","top-right","bottom-left","bottom-right"];function wm(t){let e=[1,3,5].map(n=>{let r=parseInt(t.slice(n,n+2),16)/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function Uv(t){if(t===null)return null;let{ground:e,accent:n}=Object(t);for(let[s,a]of [["ground",e],["accent",n]]){if(typeof a=="string"&&/^#[0-9a-fA-F]{6}$/.test(a))continue;let l=typeof a=="string"?JSON.stringify(a.slice(0,48)):`a value of type ${typeof a}`;console.warn(`[gem] setMenuStyle: ${s} is ${l}, which is not #rrggbb, so nothing was sent.`);return}let r={ground:e.toLowerCase(),accent:n.toLowerCase()},i=[wm(r.ground),wm(r.accent)],o=(Math.max(...i)+.05)/(Math.min(...i)+.05);if(o>=3)return r;console.warn(`[gem] setMenuStyle: accent ${r.accent} reaches ${Math.floor(o*100)/100}:1 against ground ${r.ground}, under the 3:1 it needs, so nothing was sent.`);}var Sm=8e3,wi=15e3,Wv=9e4,Hv=1/0,Vv=8e3,Kv=5e3,Jv=5e3;async function zv(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 qn(t){let e=null,n=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){n=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||n?Promise.resolve(e):new Promise(o=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{t.clearTimeout(l),s(),o(d);},l=t.setTimeout(()=>{s(),o(e);},i);r.push(a);})}}}function sE(t={}){let e=t.clock??ue,n=t.log===void 0?m=>console.info(m):t.log,r=t.baseUrl??void 0;if(r!=null){let m=Ma(r);if(m!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${m}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=typeof window>"u"?void 0:window.location?.search,o=nd(i),s=Ed(i),a=Yo();a.mark("sdk created");let l=()=>Nr(ae.gameVersion,t.clientVersion?.gameVersion),d=new dn({client:()=>vt,clock:e,gameId:()=>ae.identity?.gameId??null,playerId:()=>ae.identity?.playerId??null,awaitPlayerId:async()=>(await Qn(wi)).playerId,declarations:async()=>(await Yn.load())?.analytics_events,environment:()=>{let m=l();return {sdk_version:es(),...m===null?{}:{game_version:m}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),c=gc(()=>{a.mark("engaged"),d.release(),L.reportEngaged();},typeof window>"u"?{}:window),u=m=>{if(m===false)return null;let R=m?.attempts??Hv,G=m?.budgetMs??Wv;return !(R>0)||!(G>0)?null:{attempts:R,budgetMs:G,maxDelayMs:m?.maxDelayMs??Vv}},p=m=>{m.on("created",()=>{a.mark("room created");}),m.on("joined",()=>{a.mark("room joined");}),m.on("matchAllocationStarted",()=>{a.mark("allocation started");}),m.on("matchReady",()=>{a.mark("match ready");}),m.on("matchFailed",()=>{a.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new Dn;let g=t.allowedEmbedders;if(g!=null&&!Array.isArray(g))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let f=Array.from(g??[]),h=f.filter(m=>typeof m!="string"||!St(m));if(h.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${h.length===1?"an entry":"entries"} that ${h.length===1?"is":"are"} not an origin: ${h.map(m=>typeof m=="string"?JSON.stringify(m):String(m)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let k=Object.freeze([...new Set([...Nv,...f])]),x=qn(e),P=new Set,b=qn(e),S=false,I=qn(e),T=ld(n),H=qn(e),N=t.manageAudio===false?null:Pc();t.selectableText!==true&&Tc(),t.onScreenshot===void 0&&hc(window);let B=null,E=null,O=null,$=()=>{B===null||B===E||L.reportMuted(B)&&(E=B);},j,U,J=-1/0,oe=null,ge=()=>{if(j===void 0||oe!==null||j===U)return;let m=J+1e3-e.now();if(m>0){oe=e.setTimeout(()=>{oe=null,ge();},m);return}L.showPortraitBorders(j)&&(U=j,J=e.now());},X=null,Be=null,Se=()=>{if(X===null)return false;let m=JSON.stringify(Ca(X.visible,X.only));return m===Be?L.parentSupports("walletDisplay"):L.setWalletVisible(X.visible,X)?(Be=m,true):false},fe=null,Ue=null,te=()=>{if(fe===null)return false;let m=JSON.stringify(vi(fe.items));return m===Ue?L.parentSupports("gameMenu"):L.setMenu(fe.items)?(Ue=m,true):false},z=null,le=null,xe,Le=null,De=Yu({frame:()=>L,clock:e,log:t.log}),Nn=()=>z===null?false:z===le?L.parentSupports("gemCorner"):L.setGemCorner(z)?(le=z,true):false,Bt=()=>{if(xe===void 0)return false;let m=JSON.stringify(xe);return m===Le?L.parentSupports("menuStyle"):L.setMenuStyle(xe)?(Le=m,true):false},nt=Ec({report:m=>L.reportFrameStats(m)}),We=false,$e=Dc(()=>Xa,()=>We),Ut=m=>{let R=We&&!m,G=We!==m;if(We=m,R&&$e.close(),!!G)try{t.onDevToolsPermissionChange?.(m);}catch(ee){n?.(`[gem] onDevToolsPermissionChange threw: ${ee instanceof Error?ee.message:String(ee)}`),queueMicrotask(()=>{throw ee});}},y=r??jv,C=r!==void 0,F,Z=m=>(n?.(`[gem] token refused: ${m}`),t.onError?.("internal",m),false),ke=(m,R)=>{if(m===void 0)return R!==void 0?Z("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let G=gm(m);return G!==null?Z(`the embedder named an API root that cannot be used: ${G}. Its value is withheld here rather than written to logs.`):F!==void 0&&F!==m?Z("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(F=m,C||(y=m),true)},Fe=window.location?.origin,Wt=null,bt=-1/0,xm=2e3,jn=new Set,Pm=m=>Wt!==false?Promise.resolve(true):new Promise(R=>{let G=e.setTimeout(()=>{jn.delete(ee),R(false);},m),ee=()=>{e.clearTimeout(G),jn.delete(ee),R(true);};jn.add(ee);}),Si=()=>{},ki=null,Bn=Eu(e),L=new $n({allowedEmbedders:k,...typeof Fe=="string"&&Fe!==""?{selfOrigin:Fe}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","ticketEvents","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","gemCorner","menuStyle","gameSettings","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges","appLinks","openGame","store","storeOfferSheet",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[]],onRefused:m=>{ki=m,t.onRefused?.(m);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:m=>{ae.onBridgeState(m),m!=="connected"&&Bn.abandon(),m!=="connected"&&nt.setRequested(false),E=null,Be=null,Ue=null,le=null,Le=null,De.forgetSent(),U=void 0,m==="refused"&&(console.error("[gem] this game refused the page that framed it"+(ki===null?"":` (${ki})`)+", 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."),Si()),m==="connected"&&(a.mark("bridge connected"),Tm(),$(),ge(),Se(),te(),Nn(),Bt(),De.flush(),L.unbiddenLaunch&&!c.engaged&&d.hold(),d.startSession(),c.engaged&&L.reportEngaged()),t.onStateChange?.(m);},onPlayer:m=>{x.set(m);for(let R of [...P])R(m);t.onPlayer?.(m);},onPrefs:m=>{let R={reducedMotion:m.reducedMotion,muted:m.muted,locale:m.locale,showFrameStats:m.showFrameStats===true,music:m.music!==false,sounds:m.sounds!==false,recommended:m.recommended===void 0?null:Object.freeze({volume:m.recommended.volume,batterySaver:m.recommended.batterySaver,keyboardLayout:m.recommended.keyboardLayout,gamepadConfirm:m.recommended.gamepadConfirm,vibration:m.recommended.vibration,lookSensitivity:m.recommended.lookSensitivity??100,gamepadLookSensitivity:m.recommended.gamepadLookSensitivity??100,invertLookY:m.recommended.invertLookY??false,touchMovement:m.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:Qu(m.recommended.graphicsQuality,m.recommended.batterySaver),graphicsQualityAuto:m.recommended.graphicsQualityAuto??true,colorHelp:typeof m.recommended.colorHelp=="boolean"?m.recommended.colorHelp:null})};b.set(R),E=R.muted,N?.setMuted(R.muted),nt.setRequested(R.showFrameStats&&L.parentSupports("frameStats")),t.onPrefs?.(R),t.onAudioChannels!==void 0&&(O===null||O.music!==R.music||O.sounds!==R.sounds)&&(O=Object.freeze({music:R.music,sounds:R.sounds}),t.onAudioChannels(O));},onCohorts:m=>{let R=Object.freeze(m.cohorts.map(G=>Object.freeze({experimentId:G.experimentId,variantKey:G.variantKey})));I.set(R),t.onCohorts?.(R);},onEarnAllowanceChanged:()=>T.emit(),onViewport:m=>{let R=Object.freeze({insets:Object.freeze({top:m.insets.top,right:m.insets.right,bottom:m.insets.bottom,left:m.insets.left}),reserved:Object.freeze((m.reserved??[]).map(({x:ee,y:Ya,width:Qa,height:Za,control:Vt})=>Object.freeze(Vt?{x:ee,y:Ya,width:Qa,height:Za,control:Object.freeze({x:Vt.x,y:Vt.y,width:Vt.width,height:Vt.height})}:{x:ee,y:Ya,width:Qa,height:Za})))});H.set(R);let G=Cc();Mc(G,R.insets),Gc(G,R.reserved,Oc()),t.onViewport?.(R);},onPause:m=>{S=m.paused,d.setPaused(m.paused),nt.setPaused(m.paused),t.onPause?.(m.paused);},onSettingChange:m=>De.onSettingChange(m),onMenuSelect:m=>{fe===null||m.entry!=="item"||!(vi(fe.items).items??[]).some(G=>G.id===m.id)||fe.items?.find(G=>G.id===m.id)?.onSelect?.();},onWillTerminate:m=>{d.endSession(m.reason),t.onWillTerminate?.({reason:m.reason,graceMs:m.graceMs});},onToken:m=>{let R=m.garden;if(Ut(m.allowDevTools===true),!ke(m.apiBaseUrl,R))return;let G=m;ae.onToken(G);let ee=ae.identity;ee&&(Ri.set(ee),La||(La=true,me.reconcileSeats().catch(()=>{}))),Da.push({token:G.token,expiresAt:G.expiresAt});},onTokenDenied:m=>{Ut(false),ae.onDenied(m);},onScreenshot:(m,R,G)=>{Rc(m,R,G,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Ac(L,t.onFeedbackContext);},onDevtools:m=>{m==="close"?$e.close():m==="open"?$e.openFrom("platform").catch(()=>{}):$e.isOpen?$e.close():$e.openFrom("platform").catch(()=>{});},onRoomEvent:m=>me.handleRoomEvent({event:m.event,roomId:m.roomId,...m.matchId===void 0?{}:{matchId:m.matchId},...m.version===void 0?{}:{version:m.version},...m.reason===void 0?{}:{reason:m.reason},...m.platform===void 0?{}:{platform:m.platform}}),onSeatedEvent:m=>me.handleSeated(m.roomId),onAutoStartFailedEvent:m=>me.handleAutoStartFailed(m.roomId,m.code),onTicketEvent:m=>me.handleTicketEvent({event:m.event,ticketId:m.ticketId,...m.partySize===void 0?{}:{partySize:m.partySize},...m.queuedAt===void 0?{}:{queuedAt:m.queuedAt},...m.expiresAt===void 0?{}:{expiresAt:m.expiresAt},...m.reason===void 0?{}:{reason:m.reason},...m.roomId===void 0?{}:{roomId:m.roomId}}),onSocketState:m=>{let R=Wt;if(Wt=m.connected,m.connected)for(let ee of [...jn])ee();if(!m.connected||R===true)return;let G=e.now();G-bt<xm||(bt=G,me.reconcile().catch(()=>{}));},onSignalEvent:m=>{let R=typeof m.data=="object"&&m.data!==null&&!Array.isArray(m.data)?m.data:{};_t.handleSignalEvent(m.matchId,m.event,R),m.event==="matchEnded"&&me.reconcile({matchId:m.matchId,...typeof R.reason=="string"?{reason:R.reason}:{}}).catch(()=>{});},onDedicatedEvent:m=>{m.event==="matchEnded"&&(Ht.handleMatchEnded(m.matchId,m.reason),me.reconcile({matchId:m.matchId,...m.reason===void 0?{}:{reason:m.reason}}).catch(()=>{})),Ga.handleEvent(m);},onClusterTarget:m=>Vn.accept(m.clusterTargetId,m.clusterTargetIds),onLocalServer:m=>Kn.accept(m),onLocalServerDenied:m=>Kn.refuse(m),onPartyResult:m=>Fa.settle(m.requestId,m.partyId),onPurchaseResult:m=>xi.settle(m),onDeviceSettings:m=>{Hn.receive(m),t.onDeviceSettings?.(Hn.api.current);},onDeviceSettingsResult:m=>Hn.settle(m),onAdResult:m=>Na.settle(m),onMomentResult:m=>ja.settle(m),onSignInResult:m=>Ba.settle(m),onFriendChallengeResult:m=>Ha.settle(m),onArcadeAnswer:m=>{m.type==="gem.storePurchaseSettled"?Wa.settled(m):Im(m);}}),Ga=new In({bridge:L}),Ri=qn(e);Si=()=>{Ri.release(),x.release(),I.release();},L.currentState==="refused"&&Si();let La=false,Ai=new Set,Un,Da={current:()=>Un,subscribe:m=>(Ai.add(m),Un!==void 0&&m(Un),()=>Ai.delete(m)),push:m=>{Un=m;for(let R of [...Ai])try{R(m);}catch(G){n?.(`[gem] a server-token listener threw: ${G instanceof Error?G.message:String(G)}`);}}},ae=Fc({bridge:L,clock:e,onStateChange:(m,R)=>{if(m==="ready"){if(a.mark("token ready")){let G=a.marks.find(ee=>ee.name==="token ready")?.at;d.trackPlatform("gem_boot_ready",G===void 0?{}:{boot_ms:Math.max(0,Math.round(G))});}}else m==="lost"&&(a.mark("token lost"),d.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(m,R);}}),$a=()=>{let m=ae.identity;return !m||ae.source.currentState==="lost"?null:`${m.playerId}\0${m.gameId}\0${m.channel}`},Tm=()=>{a.mark("token requested"),ae.source.get().catch(()=>{});},Fa=yu({bridge:L,clock:e}),Wn={},xi=hu({bridge:L,clock:e,onDropped:m=>t.onError?.("internal",m),confirm:async m=>Wn.confirm?.(m)??"unknown",confirmAvatar3d:async m=>Wn.confirmAvatar3d?.(m)??"unknown"}),Hn=lm({bridge:L,clock:e,onDropped:m=>t.onError?.("internal",m)}),qa={},Na=rm({bridge:L,clock:e,onDropped:m=>t.onError?.("internal",m),readAvailability:(m,R)=>qa.read?.(m,R)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),ja=am({bridge:L,clock:e,onDropped:m=>t.onError?.("internal",m)}),Ba=Ru({bridge:L,clock:e,onDropped:m=>t.onError?.("internal",m)}),Ua={held:false},Em=Iu({bridge:L,asker:Bn,acting:Ua}),Wa=Mu({bridge:L,asker:Bn,acting:Ua,onListenerError:m=>t.onError?.("internal",`gem.store.onSettled listener threw: ${String(m)}`)}),Im=m=>{Bn.settle(m)||t.onError?.("internal",`${m.type} (${m.outcome}) for an unknown requestId: `+JSON.stringify(m.requestId));},Ha=sd({bridge:L,clock:e,onDropped:m=>t.onError?.("internal",m)}),Vn=yd({bridge:L,clock:e}),Kn=Lc({bridge:L,clock:e}),Pi=vm(Fe),Va=window.fetch,Jn=Pi!==null&&typeof Va=="function"?"unread":"read",zn=null,Ti=false,Cm=m=>{if(Jn==="read"||m.source!==window.parent)return false;let R=m.origin;return typeof R!="string"||k.some(G=>kt(G,R))||lr(R,typeof Fe=="string"?Fe:void 0)?false:((zn===null||!Ti)&&(zn=m),Jn==="unread"&&Pi!==null&&(Jn="reading",bm({fetch:(G,ee)=>Va.call(window,G,ee),selfOrigin:Pi,clock:e}).then(G=>{"refused"in G&&n?.(G.refused),G.origins.length>0&&mm(L,G.origins),Jn="read";let ee=zn;zn=null,ee!==null&&L.currentState==="waiting"&&Xn(ee);})),true)},Xn=m=>{if(Cm(m))return false;let R=L.handleWindowMessage({data:m.data,origin:m.origin,source:m.source,ports:m.ports});return R&&window.removeEventListener("message",Xn),R};window.addEventListener("message",Xn),Ti=true;let rt;try{rt=fc(window,Xn);}finally{Ti=false;}let Mm=rt?.capture,Ei=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Ei?.domInteractive!==void 0&&Ei.domInteractive>0&&a.mark("document parsed",Ei.domInteractive),Mm?.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 Ii=t.handshakeWarningMs;Ii!==null&&n&&e.setTimeout(()=>{let m=rt===null?"no capture script ran":`capture: ${rt.delivered} offer(s) delivered, ${rt.stale} stale, ${rt.capture.dropped} evicted${rt.capture.late?", installed late":""}`;if(L.currentState==="connected"){n(`[gem] handshake connected. boot: ${a.timeline()} \xB7 ${m}`);return}n(`[gem] no completed handshake after ${Ii??Sm}ms (bridge state: ${L.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${a.timeline()} \xB7 `+m);},Ii??Sm);let Om=hr({get baseUrl(){return y},tokenSource:ae.source,get defaultQuery(){let m=ae.identity;return m?{game_id:m.gameId,channel:m.channel}:{}}}),vt=new He({transport:Om,clock:e}),ye={client:vt,gameId:()=>ae.identity?.gameId??""};Wn.confirm=m=>bu(ye,m),Wn.confirmAvatar3d=m=>Su(ye,m),qa.read=(m,R)=>ul(ye,"players","me",m,{signal:R});let Gm=()=>ae.identity?.channel??"release",Yn=new Tr(ye,Gm),Lm=wu({player:()=>x.current,subscribe:m=>(P.add(m),()=>{P.delete(m);}),configFamilies:async()=>(await Yn.load())?.avatar_3d_families,readOffers:()=>ku(ye),purchase:m=>xi.requestAvatar3d(m),log:t.log}),Ka=async m=>(await Yn.load())?.currency(m)?.id??void 0,Ja=Sr(ye,Ki,{identity:$a,resolveCurrencyId:Ka}),Qn=async m=>{let R=await Ri.wait(m);if(R)return R;throw L.currentState==="refused"?new ne("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new ne("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},Ci=u(t.autoReconnect),me=Jd(s===void 0?{}:{playWithTicket:s},{client:vt,clock:e,gameId:()=>ae.identity?.gameId??null,playerId:()=>ae.identity?.playerId??null,awaitGameId:async()=>(await Qn(wi)).gameId,resolveParty:Fa.resolve,resolveClusterTargets:Vn.resolveList,refreshClusterTargets:Vn.refresh,ensureLocalServer:Kn.ensure,localHostAvailable:Kn.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>ae.gameVersion,...t.pollRooms===void 0?{}:{poll:t.pollRooms},...t.recoverStaleMembership===void 0?{}:{recoverStaleMembership:t.recoverStaleMembership},...t.retryAutoStart===void 0?{}:{retryAutoStart:t.retryAutoStart},...t.watchSeats===void 0?{}:{watchSeats:t.watchSeats},...t.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:t.seatPollIntervalMs},...Ci===null?{}:{autoReconnect:{...Ci,redial:(m,R)=>Mi.redialMatch(m,R),abandon:(m,R)=>Mi.abandonMatch(m,R)}}});p(me),mc({analytics:d,rooms:me});let _t=uc({client:vt,clock:e,rooms:me,bridge:L,gameId:()=>ae.identity?.gameId??"",baseUrl:()=>y,resolveClusterTarget:Vn.resolve,boot:a,...t.log===void 0?{}:{log:t.log}}),za=Xo(a,n),Ht=tu({client:vt,clock:e,rooms:me,signaling:()=>Ga.channel(),signalingReady:Pm,log:n??(()=>{})}),Mi=gu({rooms:me,p2p:{connect:m=>za(_t.connect(m)),session:m=>_t.session(m)},dedicated:{connect:(m=>ii(a,"welcome",Ht.connect(m),n))},clock:e,identity:()=>ae.identity,apiBaseUrl:()=>y,tokens:Da,room:()=>me.currentRoom,autoReconnect:Ci!==null,...t.log===void 0?{}:{log:t.log}}),Dm=async()=>(await Qn(wi)).playerId,Xa={client:vt,boot:a,get identity(){return ae.identity},awaitIdentity:(m=wi)=>Qn(m),awaitBridge:m=>L.settled(m),get player(){return x.current},awaitPlayer:(m=Kv)=>x.wait(m),me:Ja,characters:new Rr(ye,void 0,$a,Ka),transfers:new xr(ye,Ki,Ja.inventory),gameConfig:Yn,purchases:xi.api,deviceSettings:Hn.api,moments:ja.api,ads:Na.api,account:Ba.api,share:Tu({frame:L,log:t.log}),arcade:Em,store:Wa.api,branding:qu({fetch:typeof window.fetch=="function"?(m,R)=>window.fetch.call(window,m,R):null,clock:e,devicePixelRatio:()=>window.devicePixelRatio??1,log:n}),vibration:Nu({frame:L,log:t.log}),get avatarPickerAvailable(){return L.currentState==="connected"&&L.parentSupports("avatarPicker")},openAvatarPicker:m=>L.requestAvatarPicker(m?.tab),avatars3d:Lm,settings:De.api,controls:Wu({recommended:()=>b.current?.recommended??null}),analytics:d,leaderboards:new tn(ye),challenges:new Qt(ye),showcase:new nn(ye,Dm),friends:new rn(ye,{challenge:Ha.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new an(ye,T,n),profiles:new sn(ye),functions:new Xe((m,R)=>Ys(ye,m,R)),get prefs(){return b.current},get paused(){return S},get cohorts(){return I.current},get viewport(){return H.current},awaitCohorts:(m=Jv)=>I.wait(m),reportMuted:m=>{B=!!m,$();},showPortraitBorders:m=>{let R=bi(m);R!==void 0&&(j=R,ge());},cueReward:m=>L.cueReward(m),setWalletVisible:(m,R)=>{let G=Array.isArray(R?.only)?[...R.only]:void 0;return X=G===void 0?{visible:m===true}:{visible:m===true,only:G},Se()},setMenu:m=>(fe=Array.isArray(m?.items)?{items:m.items.map(R=>({...R}))}:{},te()),setGemCorner:m=>{if(!Bv.includes(m)){let R=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setGemCorner: ${R} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return z=m,Nn()},setMenuStyle:m=>{let R=Uv(m);return R===void 0?false:(xe=R,Bt())},reportFrame:()=>nt.draw(),exit:m=>zv(me,L,m,d),frame:L,devtools:$e,rooms:me,dedicatedServer:{listClusterTargets:m=>Ht.listClusterTargets(m),connect:(m=>ii(a,"welcome",Ht.connect(m),n)),handleMatchEnded:(m,R)=>Ht.handleMatchEnded(m,R)},p2p:{handleSignalEvent:(m,R,G)=>_t.handleSignalEvent(m,R,G),session:m=>_t.session(m),connect:m=>za(_t.connect(m))},match:Mi};return Xa}var km="the match has not started yet: the runtime hands over the host at `init`, and this was read before that. Read it from `init` or later \u2014 a bundle that needs a value at module scope is reading it one call too early.";function Oa(t,e={}){let n=e.clock??ue,r=()=>{let a=t();if(a===null)throw new Error(km);return a},i=null,o=()=>{if(i===null)throw new Error(km);return i};return {server:{get identity(){return o().identity},get client(){return o().client},get api(){return o().api},get match(){return o().match},get analytics(){return o().analytics},get functions(){return o().functions},get challenges(){return o().challenges},get room(){return o().room},dispose(){i?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(a){let d=r().profile?.(a);if(!d)return null;let c=d.displayName;return typeof c!="string"||c===""?null:{displayName:he(c,"profile.displayName"),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:he(d.displayTag,"profile.displayTag")}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(a){return r().playerNumber?.(a)},send(a,l,d){d===void 0?r().send(a,l):r().send(a,l,d);},broadcast(a,l){l===void 0?r().broadcast(a):r().broadcast(a,l);},kick(a,l){l===void 0?r().kick(a):r().kick(a,l);},log(a){r().log(a);},warn(a){r().warn(a);}},attach:()=>{i=qt(r(),{...e,clock:n});}}}function Rm(t,e={}){let{server:n,attach:r}=Oa(()=>t,e);return r(),n}function Xv(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:Ye(e)}}}var Yv=1e4;function Qv(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout(Yv));}catch{return}r.catch(i=>{i instanceof M&&i.status>=400&&i.status<500&&(e=i.status!==429);});}}function Am(t,e={}){return ()=>{let n=null,{server:r,attach:i}=Oa(()=>n,e),o=t(r),s={async init(l){n=l,i(),await o.init?.();},async shutdown(l){let d=Xv(l);try{await o.shutdown?.(d);}finally{r.dispose();}}},a=Qv(r);return s.join=(l,d)=>(a(l),o.join?.(l,d)),o.leave&&(s.leave=(l,d)=>o.leave?.(l,d)),o.message&&(s.message=(l,d,c,u)=>o.message?.(l,d,c,u)),s}}
|
|
3
|
+
export{Nv as ARCADE_EMBEDDERS,Fv as AVATAR_RIGS,dn as AnalyticsApi,ne as AuthError,Zn as CONDITIONAL_HEADERS,Qt as ChallengesApi,Ea as DEVICE_SETTINGS_MAX_BYTES,w as DedicatedServerError,lt as FriendChallengeError,rn as FriendsApi,Xe as FunctionsApi,M as GemApiError,He as GemClient,pe as GemConfigError,$n as GemFrame,ln as GemFunctionError,ie as GemSaveError,Dn as GemUnframedError,tn as LeaderboardsApi,Hl as MAX_PERIODS_BACK,Gg as PLATFORM_EVENTS,an as PlatformApi,Or as PlatformCurrenciesApi,Gr as PlatformEarnAllowanceApi,ve as PlayerText,sn as ProfilesApi,ze as PurchaseRefusal,nn as ShowcaseApi,se as TransportRefusal,gn as UNRELIABLE_CHANNEL_LABEL,he as asPlayerText,Yo as createBootTimeline,sE as createGem,qt as createGemServer,iu as createHostTokenSource,Rm as createMatchServer,Am as defineServer,Dr as experimentSelection,zv as leaveAndExit,Pe as mapIdentity,ii as markOnResolve,Xi as platformIconUrl,mn as presentJoinCredential,Ct as readTemplateTransports,fn as readTransportAdvert,Xo as reportOnResolve,ue as systemClock,ot as text,er as toBase64,Hr as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.sdk.js.map
|
|
4
4
|
//# sourceMappingURL=gem-web-sdk.sdk.js.map
|