@caisual/kit 0.15.0 → 0.20.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/LICENSE +21 -0
- package/README.md +51 -0
- package/dist/kit.js +4 -2
- package/dist/kit.js.map +4 -4
- package/dist/node.js +48 -18
- package/dist/overlay.js +296 -157
- package/dist/overlay.js.map +4 -4
- package/dist/runtime.js +55 -22
- package/dist/types/contracts/index.d.ts +3 -0
- package/dist/types/contracts/manifest.d.ts +3 -1
- package/dist/types/contracts/overlay.d.ts +11 -0
- package/dist/types/contracts/pubblicazione-limiti.d.ts +3 -0
- package/dist/types/contracts/replay.d.ts +83 -0
- package/dist/types/contracts/room-limits.d.ts +3 -2
- package/dist/types/contracts/server-js.d.ts +10 -2
- package/dist/types/contracts/server-wasm.d.ts +19 -0
- package/dist/types/handshake.d.ts +1 -0
- package/dist/types/index.d.ts +10 -1
- package/dist/types/overlay/host-bridge.d.ts +2 -0
- package/dist/types/overlay/i18n.d.ts +139 -130
- package/dist/types/overlay/locale.d.ts +4 -0
- package/dist/types/overlay/styles.d.ts +1 -1
- package/dist/types/overlay/ui-model.d.ts +4 -0
- package/dist/types/overlay/ui.d.ts +1 -0
- package/dist/types/protocollo.d.ts +4 -1
- package/dist/types/replay/index.d.ts +65 -0
- package/dist/types/runtime/index.d.ts +1 -0
- package/dist/types/session/index.d.ts +4 -3
- package/dist/types/stanza/nucleo.d.ts +2 -0
- package/dist/types/stanza/tipi.d.ts +2 -0
- package/dist/types/stanza-client/index.d.ts +9 -1
- package/package.json +13 -1
package/dist/kit.js
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
// Caisual game kit v0.
|
|
2
|
-
var ft=["www","api","app","play","live","multi","cdn","assets","static","mail","mx","ns1","ns2","autodiscover","_dmarc","admin","login","account","auth","pay","secure","support","help","blog","status","dev","staging","test","caisual","shipz"],ht=new Set(ft),gt=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,vt=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function de(n){return n.length>=3&&n.length<=32&>.test(n)||vt.test(n)}function Oe(n){return ht.has(n)}function q(n){if(typeof n!="string"||n.length>128)return null;try{return Intl.getCanonicalLocales(n)[0]??null}catch{return null}}function we(n){return n.languages?.length?[...n.languages]:[n.language??"en"]}function yt(n,e="en"){let t=[],i=q(n);for(;i;){t.push(i);let r=i.split("-");r.pop(),r.at(-1)?.length===1&&r.pop(),i=r.join("-")}return t.push(q(e)??e),[...new Set(t)]}function Ee(n,e=[]){let t=e.map(q).filter(r=>r!==null),i=n.map(q).filter(r=>r!==null);if(!t.length)return i[0]??"en";for(let r of i)for(let o of yt(r,r))if(t.includes(o))return o;return t[0]}function Ve(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string")}function je(n,e){let t=e===null?void 0:n.modes.find(i=>i.id===e);if(e!==null&&t===void 0)throw new Error("The selected game mode does not exist.");return{players:{...t?.players??n.players},lobby:t?.lobby??n.lobby}}function pe(n,e){return e!==null&&n.modes.some(t=>t.id===e&&t.execution==="local")}var T=24;var bt=3e3,_e=32,wt=new Set(["overlay","manifest","id","name","description","cover","card","icon","screenshots","tags","languages","language","platform","orientation","input","visibility","network","isolated","requires","players","lobby","persistent","spectators","boards","roles","teams","voice","modes"]),St=new Set(["keyboard","mouse","touch","gamepad"]),Rt=new Set(["desktop","mobile","both"]),xt=new Set(["landscape","portrait"]),kt=new Set(["public","unlisted"]),Ct=new Set(["none","room","team","proximity"]),Pt=new Set(["light","medium","heavy"]),At=/^[a-z0-9-]+$/,De=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Tt=/^[a-z0-9][a-z0-9-]{0,31}$/,Mt=/^[a-z0-9][a-z0-9_-]{0,31}$/;function J(n){return typeof n!="object"||n===null||Array.isArray(n)?null:n}function Le(n){if(n===""||n.startsWith("/")||n.includes("\\")||n.includes("\0")||n.includes("?")||n.includes("#"))return!1;let e=n.split("/");if(e.some(t=>t===""||t==="."||t===".."))return!1;try{return!e.map(i=>decodeURIComponent(i)).some(i=>i===""||i==="."||i===".."||i.includes("/"))}catch{return!1}}function It(n){return n.length===0||n.length>253||n.includes("://")||/[/:?#@]/.test(n)?!1:n.split(".").every(t=>t.length>=1&&t.length<=63&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(t))}function _(n,e,t){return typeof n=="number"&&Number.isInteger(n)&&n>=e&&n<=t}function Se(n,e,t,i){let r=n[e];return r===void 0?t:typeof r!="string"?(i.push(`${e}: must be a string.`),t):r}function me(n,e,t,i,r){if(n[e]===void 0)return;let o=(g,d)=>{if(typeof g!="string"||g.trim().length===0||g.trim().length>t||/[\r\n\u0000-\u001f]/.test(g)){r.push(`${d}: must contain 1-${t} characters on one line.`);return}return g.trim()},s=n[e],a=i?`${i}.${e}`:e;if(typeof s=="string")return o(s,a);let u=J(s);if(!u||Object.keys(u).length===0){r.push(`${a}: must be a string or a non-empty language-to-text object.`);return}let m={};for(let[g,d]of Object.entries(u)){let c=q(g);if(!c){r.push(`${a}.${g}: must be a BCP 47 language tag.`);continue}Object.hasOwn(m,c)&&r.push(`${a}.${g}: duplicate language.`);let y=o(d,`${a}.${g}`);y!==void 0&&(m[c]=y)}return m}function Re(n){let e=[],t=J(n);if(t===null)return{ok:!1,errori:["manifest: must be a JSON object."]};for(let h of Object.keys(t))wt.has(h)||e.push(`${h}: unknown field.`);t.manifest===void 0?e.push("manifest: is required and must be 1."):t.manifest!==1&&e.push("manifest: must be exactly 1.");let i=Se(t,"id","",e);t.id===void 0?e.push("id: is required."):typeof t.id=="string"&&(de(i)?Oe(i)&&e.push("id: this slug is reserved."):e.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens; historical UUID v4 slugs may be 36 characters."));let r=Se(t,"name","",e);t.name===void 0?e.push("name: is required."):typeof t.name=="string"&&(r.trim()===""||r.length>60)&&e.push("name: must contain 1-60 characters.");let o=t.description===""?"":me(t,"description",500,"",e)??"",s={cover:"",card:"",icon:""},a=new Set;for(let h of["cover","card","icon"]){let p=t[h];if(p==null)e.push(`${h}: is required.`);else if(typeof p!="string"||!Le(p))e.push(`${h}: must be a relative file path inside client/ without query, fragment, or parent segments.`);else{/\.(png|jpe?g|webp)$/i.test(p)||e.push(`${h}: must be a PNG, JPEG or WebP file.`);let z=decodeURIComponent(p);a.has(z)&&e.push(`${h}: each image must use a different file; cover, card and icon cannot share a path.`),a.add(z),s[h]=p}}let{cover:u,card:m,icon:g}=s,d=[];if(t.screenshots!==void 0)if(!Array.isArray(t.screenshots))e.push("screenshots: must be an array of relative file paths.");else{t.screenshots.length>8&&e.push("screenshots: must contain at most 8 paths.");for(let[h,p]of t.screenshots.entries())typeof p!="string"||!Le(p)?e.push(`screenshots[${h}]: must be a relative file path without query, fragment, or parent segments.`):d.push(p)}let c=[];if(t.tags!==void 0)if(!Array.isArray(t.tags))e.push("tags: must be an array.");else{t.tags.length>10&&e.push("tags: must contain at most 10 tags.");for(let[h,p]of t.tags.entries())typeof p!="string"||p.length>24||!At.test(p)?e.push(`tags[${h}]: must be 1-24 lowercase letters, digits, or hyphens.`):c.push(p)}let y=Se(t,"language","en",e);/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(y)||e.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");let k=[];if(!Array.isArray(t.languages)||t.languages.length===0)e.push("languages: must be a non-empty array of BCP 47 language tags.");else for(let[h,p]of t.languages.entries()){let z=q(p);z?k.includes(z)?e.push(`languages[${h}]: duplicate language ${z}.`):k.push(z):e.push(`languages[${h}]: must be a BCP 47 language tag.`)}k.includes("en")||e.push("languages: English is always required alongside the game's own languages.");let C=k[0]??y;if(typeof o=="object")for(let h of Object.keys(o))k.includes(h)||e.push(`description.${h}: language must be declared in languages.`);t.language!==void 0&&t.languages!==void 0&&y.toLowerCase()!==C.toLowerCase()&&e.push("language: must match the first entry in languages when both are present.");let D="both";t.platform===void 0?e.push("platform: is required."):typeof t.platform!="string"||!Rt.has(t.platform)?e.push("platform: must be desktop, mobile, or both."):D=t.platform;let E="landscape";t.orientation!==void 0&&(typeof t.orientation!="string"||!xt.has(t.orientation)?e.push("orientation: must be landscape or portrait."):E=t.orientation);let $=[];if(t.input!==void 0)if(!Array.isArray(t.input))e.push("input: must be an array.");else for(let[h,p]of t.input.entries())typeof p!="string"||!St.has(p)?e.push(`input[${h}]: must be keyboard, mouse, touch, or gamepad.`):$.includes(p)?e.push(`input[${h}]: duplicate value ${p}.`):$.push(p);let V="public";t.visibility!==void 0&&(typeof t.visibility!="string"||!kt.has(t.visibility)?e.push("visibility: must be public or unlisted."):V=t.visibility);let B=[];if(t.network!==void 0)if(!Array.isArray(t.network))e.push("network: must be an array of host names.");else for(let[h,p]of t.network.entries())typeof p!="string"||!It(p)?e.push(`network[${h}]: must be a host name without scheme, port, path, query, or fragment.`):B.includes(p)?e.push(`network[${h}]: duplicate host ${p}.`):B.push(p);let U=!1;t.isolated!==void 0&&(typeof t.isolated!="boolean"?e.push("isolated: must be a boolean."):U=t.isolated);let G={webgl2:!1,webgpu:!1,wasm:!1,threads:!1,memoryMb:null,performance:"light"};if(t.requires!==void 0){let h=J(t.requires);if(h===null)e.push("requires: must be an object.");else{for(let p of Object.keys(h))["webgl2","webgpu","wasm","threads","memoryMb","performance"].includes(p)||e.push(`requires.${p}: unknown field.`);for(let p of["webgl2","webgpu","wasm","threads"])h[p]!==void 0&&(typeof h[p]!="boolean"?e.push(`requires.${p}: must be a boolean.`):G[p]=h[p]);h.memoryMb!==void 0&&(h.memoryMb!==null&&(!_(h.memoryMb,512,32768)||h.memoryMb%256!==0)?e.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null."):G.memoryMb=h.memoryMb),h.performance!==void 0&&(typeof h.performance!="string"||!Pt.has(h.performance)?e.push("requires.performance: must be light, medium, or heavy."):G.performance=h.performance),G.threads&&!U&&e.push("requires.threads: needs isolated: true.")}}let I={min:1,max:1};if(t.players!==void 0){let h=J(t.players);if(h===null)e.push("players: must be an object with min and max.");else{for(let p of Object.keys(h))p!=="min"&&p!=="max"&&e.push(`players.${p}: unknown field.`);_(h.min,1,T)||e.push(`players.min: must be an integer from 1 to ${T}.`),_(h.max,1,T)||e.push(`players.max: must be an integer from 1 to ${T} in manifest version 1.`),_(h.min,1,T)&&_(h.max,1,T)&&(h.min>h.max?e.push("players.max: must be greater than or equal to players.min."):I={min:h.min,max:h.max})}}let F=!1;t.lobby!==void 0&&(typeof t.lobby!="boolean"?e.push("lobby: must be a boolean."):F=t.lobby);let P=!1;t.persistent!==void 0&&(typeof t.persistent!="boolean"?e.push("persistent: must be a boolean."):P=t.persistent);let te={delayMs:bt};if(t.spectators===!1||t.spectators===null)te=null;else if(t.spectators!==void 0&&t.spectators!==!0){let h=J(t.spectators);if(h===null)e.push("spectators: must be a boolean or an object with delayMs.");else{for(let p of Object.keys(h))p!=="delayMs"&&e.push(`spectators.${p}: unknown field.`);_(h.delayMs,0,3e4)?te={delayMs:h.delayMs}:e.push("spectators.delayMs: must be an integer from 0 to 30000.")}}let M=null;if(t.overlay!==void 0&&t.overlay!==null){let h=J(t.overlay);if(h===null)e.push("overlay: must be an object or null.");else{for(let p of Object.keys(h))["version","accent"].includes(p)||e.push(`overlay.${p}: unknown field.`);h.version!==1&&e.push("overlay.version: must be exactly 1."),h.accent!==void 0&&(typeof h.accent!="string"||!/^#[0-9a-fA-F]{6}$/.test(h.accent))&&e.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699."),M={version:1,...typeof h.accent=="string"?{accent:h.accent}:{}}}}let X={};if(t.boards!==void 0){let h=J(t.boards);if(h===null)e.push("boards: must be an object of board ids.");else{Object.keys(h).length>_e&&e.push(`boards: at most ${_e} boards.`);for(let[p,z]of Object.entries(h)){let b=!0;Mt.test(p)||(e.push(`boards.${p}: invalid board id.`),b=!1);let S=J(z);if(S===null){e.push(`boards.${p}.source: must be "client" or "server".`);continue}for(let O of Object.keys(S))["source","label","periods","day"].includes(O)||e.push(`boards.${p}.${O}: unknown field.`);S.source!=="client"&&S.source!=="server"&&(e.push(`boards.${p}.source: must be "client" or "server".`),b=!1),S.day!==void 0&&S.day!=="submit"&&S.day!=="start"&&e.push(`boards.${p}.day: must be "submit" or "start".`),S.day==="start"&&S.source!=="server"&&e.push(`boards.${p}.day: start requires source "server".`);let A=me(S,"label",48,`boards.${p}`,e),L=["all-time"];S.periods!==void 0&&(!Array.isArray(S.periods)||S.periods.length<1||S.periods.length>2||S.periods.some(O=>O!=="daily"&&O!=="all-time")||new Set(S.periods).size!==S.periods.length?e.push(`boards.${p}.periods: must contain daily, all-time, or both without duplicates.`):L=[...S.periods]),b&&Object.defineProperty(X,p,{value:{source:S.source,periods:L,...S.day===void 0?{}:{day:S.day},...A===void 0?{}:{label:A}},enumerable:!0,configurable:!0,writable:!0})}}}let H=[];if(t.roles!==void 0)if(!Array.isArray(t.roles))e.push("roles: must be an array.");else{let h=new Set;for(let[p,z]of t.roles.entries()){let b=J(z);if(b===null){e.push(`roles[${p}]: must be an object.`);continue}for(let v of Object.keys(b))["id","min","max","label"].includes(v)||e.push(`roles[${p}].${v}: unknown field.`);let S=b.id,A=b.min,L=b.max,O=!0;typeof S!="string"||S.length>32||!De.test(S)?(e.push(`roles[${p}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`),O=!1):h.has(S)?(e.push(`roles[${p}].id: duplicate role ${S}.`),O=!1):h.add(S),_(A,0,T)||(e.push(`roles[${p}].min: must be an integer from 0 to ${T}.`),O=!1),L!==void 0&&!_(L,0,T)&&(e.push(`roles[${p}].max: must be an integer from 0 to ${T} when present.`),O=!1),typeof A=="number"&&typeof L=="number"&&A>L&&(e.push(`roles[${p}].max: must be greater than or equal to min.`),O=!1);let l=me(b,"label",32,`roles[${p}]`,e);O&&H.push({id:S,min:A,...L===void 0?{}:{max:L},...l===void 0?{}:{label:l}})}}let ie=null;if(t.teams!==void 0&&t.teams!==null){let h=J(t.teams);if(h===null)e.push("teams: must be null or an object with min and max.");else{for(let p of Object.keys(h))p!=="min"&&p!=="max"&&e.push(`teams.${p}: unknown field.`);_(h.min,2,T)||e.push(`teams.min: must be an integer from 2 to ${T}.`),_(h.max,2,T)||e.push(`teams.max: must be an integer from 2 to ${T}.`),_(h.min,2,T)&&_(h.max,2,T)&&(h.min>h.max?e.push("teams.max: must be greater than or equal to teams.min."):ie={min:h.min,max:h.max})}}let K="none";t.voice!==void 0&&(typeof t.voice!="string"||!Ct.has(t.voice)?e.push("voice: must be none, room, team, or proximity."):K=t.voice);let W=[];if(t.modes!==void 0)if(!Array.isArray(t.modes))e.push("modes: must be an array.");else{let h=new Set;for(let[p,z]of t.modes.entries()){let b=J(z);if(b===null){e.push(`modes[${p}]: must be an object.`);continue}for(let v of Object.keys(b))["id","players","lobby","matchmaking","execution","label","instructions"].includes(v)||e.push(`modes[${p}].${v}: unknown field.`);if(typeof b.id!="string"||b.id.length>32||!De.test(b.id)){e.push(`modes[${p}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);continue}if(h.has(b.id)){e.push(`modes[${p}].id: duplicate mode ${b.id}.`);continue}h.add(b.id);let S={id:b.id};for(let[v,w]of[["label",48],["instructions",160]]){let R=me(b,v,w,`modes[${p}]`,e);R!==void 0&&(S[v]=R)}if(b.execution!==void 0&&(b.execution!=="local"&&b.execution!=="room"?e.push(`modes[${p}].execution: must be local or room.`):S.execution=b.execution),M!==null&&S.execution===void 0&&e.push(`modes[${p}].execution: is required with the standard overlay.`),b.players!==void 0){let v=`modes[${p}].players`,w=J(b.players);if(w===null)e.push(`${v}: must be an object with min and max.`);else{for(let R of Object.keys(w))R!=="min"&&R!=="max"&&e.push(`${v}.${R}: unknown field.`);_(w.min,1,T)||e.push(`${v}.min: must be an integer from 1 to ${T}.`),_(w.max,1,T)||e.push(`${v}.max: must be an integer from 1 to ${T}.`),_(w.min,1,T)&&_(w.max,1,T)&&(w.min>w.max?e.push(`${v}.max: must be greater than or equal to min.`):S.players={min:w.min,max:w.max})}}if(b.lobby!==void 0&&(typeof b.lobby!="boolean"?e.push(`modes[${p}].lobby: must be a boolean.`):S.lobby=b.lobby),S.execution==="local"){let v=S.players??I;(v.min!==1||v.max!==1)&&e.push(`modes[${p}].players: local execution requires min and max to be 1.`),(S.lobby??F)&&e.push(`modes[${p}].lobby: local execution requires false.`),b.matchmaking!==void 0&&e.push(`modes[${p}].matchmaking: local execution cannot use matchmaking.`)}if(b.matchmaking===void 0){W.push(S);continue}let A=J(b.matchmaking);if(A===null){e.push(`modes[${p}].matchmaking: must be an object.`);continue}for(let v of Object.keys(A))["key","timeoutMs","defaults"].includes(v)||e.push(`modes[${p}].matchmaking.${v}: unknown field.`);let L=!0,O=[];if(!Array.isArray(A.key)||A.key.length<1||A.key.length>8)e.push(`modes[${p}].matchmaking.key: must contain from 1 to 8 fields.`),L=!1;else for(let[v,w]of A.key.entries())typeof w!="string"||!Tt.test(w)?(e.push(`modes[${p}].matchmaking.key[${v}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`),L=!1):O.includes(w)?(e.push(`modes[${p}].matchmaking.key[${v}]: duplicate field ${w}.`),L=!1):O.push(w);_(A.timeoutMs,1e3,3e5)||(e.push(`modes[${p}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`),L=!1);let l;if(A.defaults!==void 0){let v=J(A.defaults);if(v===null||Object.keys(v).length!==O.length||O.some(w=>!Object.hasOwn(v,w)))e.push(`modes[${p}].matchmaking.defaults: must contain exactly the declared key fields.`);else{l={};for(let[w,R]of Object.entries(v))!(typeof R=="string"&&R.length>=1&&R.length<=64&&/^[A-Za-z0-9_.:-]+$/.test(R))&&!Number.isSafeInteger(R)?e.push(`modes[${p}].matchmaking.defaults.${w}: must be a string of 1-64 characters or a safe integer.`):Object.defineProperty(l,w,{value:R,enumerable:!0})}}L&&W.push({...S,matchmaking:{...l===void 0?{}:{defaults:l},key:O,timeoutMs:A.timeoutMs}})}}return M!==null&&W.length===0&&e.push("modes: at least one explicit mode is required with the standard overlay."),e.length>0?{ok:!1,errori:e}:{ok:!0,manifest:{manifest:1,overlay:M,id:i,name:r,description:o,cover:u,card:m,icon:g,screenshots:d,tags:c,languages:k,language:C,platform:D,orientation:E,input:$,visibility:V,network:B,isolated:U,requires:G,players:I,lobby:F,persistent:P,spectators:te,boards:X,roles:H,teams:ie,voice:K,modes:W}}}function zt(n){return n.gpu!=="hardware"||n.memoryMb!==null&&n.memoryMb<=2048?"low":n.mobile||n.memoryMb!==null&&n.memoryMb<=4096||n.cores!==null&&n.cores<=4?"mid":"high"}function Ne(n){try{n?.getExtension("WEBGL_lose_context")?.loseContext()}catch{}}function Ot(n){let e;try{e=n.navigator}catch{e=void 0}let t=null;try{let s=e?.deviceMemory,a=typeof s=="number"?s*1024:NaN;Number.isFinite(a)&&(t=a)}catch{t=null}let i=null;try{let s=e?.hardwareConcurrency;typeof s=="number"&&Number.isFinite(s)&&(i=s)}catch{i=null}let r=!1;try{r=typeof e?.userAgentData?.mobile=="boolean"?e.userAgentData.mobile:/Android|iPhone|iPad|iPod|Mobile/i.test(e?.userAgent??"")}catch{r=!1}let o=!1;try{o=n.crossOriginIsolated===!0}catch{o=!1}return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:o,gpu:"none",memoryMb:t,cores:i,mobile:r}}async function $e(n,e=1500){let t=n??globalThis,i=Ot(t),r=Promise.resolve().then(()=>{try{let m=t.document?.createElement("canvas");if(m===void 0)return;let g=m.getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(g!==null){i.webgl2=!0,i.gpu="hardware",Ne(g);return}let d=m.getContext("webgl2");d!==null&&(i.webgl2=!0,i.gpu="software",Ne(d))}catch{i.webgl2=!1,i.gpu="none"}}),o=Promise.resolve().then(async()=>{let m;try{let g=t.navigator?.gpu;if(g===void 0)return;let d=await g.requestAdapter();if(d===null)return;m=await d.requestDevice(),i.webgpu=!0}catch{i.webgpu=!1}finally{try{m?.destroy?.()}catch{}}}),s=Promise.resolve().then(()=>{try{i.wasm=t.WebAssembly?.validate(new Uint8Array([0,97,115,109,1,0,0,0]))===!0}catch{i.wasm=!1}}),a=Promise.resolve().then(()=>{try{if(t.WebAssembly===void 0)return;new t.WebAssembly.Memory({initial:1,maximum:1,shared:!0}),i.threads=!0}catch{i.threads=!1}}),u;return await Promise.race([Promise.all([r,o,s,a]),new Promise(m=>{u=setTimeout(m,Math.max(0,e))})]),u!==void 0&&clearTimeout(u),{...i,tier:zt(i)}}function xe(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}function _t(n,e=null,t=null,i=null){let r=Re(n);if(!r.ok)throw new Error("The overlay manifest is invalid.");return{manifest:r.manifest,coverUrl:e,iconUrl:i,invite:t}}function N(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function Dt(n){let e=N(n),t=N(e?.configuration);return e?.v===1&&typeof e.epoch=="string"&&e.epoch.length>0&&e.epoch.length<=128&&t!==null&&(t.coverUrl===null||typeof t.coverUrl=="string")&&(t.iconUrl===null||typeof t.iconUrl=="string")&&(t.invite===null||typeof t.invite=="string"&&/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(t.invite))&&Re(t.manifest).ok}function Ge(n){return Dt(n)?{v:1,epoch:n.epoch,configuration:_t(n.configuration.manifest,n.configuration.coverUrl,n.configuration.invite,n.configuration.iconUrl)}:null}function Lt(n){let e=N(n);return e!==null&&Object.keys(e).length===4&&["top","right","bottom","left"].every(t=>typeof e[t]=="number"&&Number.isFinite(e[t])&&Number(e[t])>=0&&Number(e[t])<=1e5)}function ke(n){let e=N(n);return e!==null&&Object.keys(e).every(t=>["inputBlocked","reservedRects","safeArea","shortcutEnabled"].includes(t))&&(e.safeArea===void 0||Lt(e.safeArea))&&(e.shortcutEnabled===void 0||typeof e.shortcutEnabled=="boolean")&&typeof e.inputBlocked=="boolean"&&Array.isArray(e.reservedRects)&&e.reservedRects.length<=8&&e.reservedRects.every(t=>{let i=N(t);return i!==null&&Object.keys(i).length===4&&["x","y","width","height"].every(r=>typeof i[r]=="number"&&Number.isFinite(i[r])&&i[r]>=0&&i[r]<=1e5)})}function qe(n){let e=N(n),t=N(e?.args);if(e?.type!=="caisual:overlay"||e.v!==1||typeof e.epoch!="string"||e.epoch.length<1||e.epoch.length>128||typeof e.requestId!="string"||!(/^[1-9][0-9]{0,15}$/.test(e.requestId)&&Number.isSafeInteger(Number(e.requestId)))||t===null||Object.keys(e).some(o=>!["type","v","epoch","requestId","sessionId","op","args"].includes(o))||!(e.sessionId===void 0||e.sessionId===null||typeof e.sessionId=="string"&&/^[1-9][0-9]{0,15}$/.test(e.sessionId)))return!1;let i=(...o)=>Object.keys(t).every(s=>o.includes(s)),r=o=>typeof t[o]=="string"&&t[o].length>=1&&t[o].length<=64;switch(e.op){case"local.start":return i("mode")&&r("mode");case"room.create":return i("mode")&&(t.mode===null||r("mode"));case"room.join":return i("code")&&(t.code===void 0||r("code"));case"room.watch":return i("code")&&r("code");case"room.match":{let o=N(t.key);return i("mode","key")&&r("mode")&&(t.key===void 0||o!==null&&Object.keys(o).length<=8&&Object.values(o).every(s=>typeof s=="string"&&s.length>=1&&s.length<=64||typeof s=="number"&&Number.isSafeInteger(s)))}case"room.ready":return i("ready")&&typeof t.ready=="boolean";case"room.role":case"room.requestRole":return i("role")&&r("role");case"room.team":return i("team")&&Number.isInteger(t.team)&&t.team>=1&&t.team<=24;case"room.restart":case"room.start":case"session.cancel":case"session.leave":case"session.disconnect":case"session.resume":return i();case"voice.join":case"voice.leave":return i()&&typeof e.sessionId=="string";case"voice.mute":return i("muted")&&typeof t.muted=="boolean"&&typeof e.sessionId=="string";case"voice.setVolume":return i("playerId","volume")&&typeof e.sessionId=="string"&&typeof t.playerId=="string"&&t.playerId.length>0&&t.playerId.length<=128&&typeof t.volume=="number"&&Number.isFinite(t.volume)&&t.volume>=0&&t.volume<=1;case"overlay.view":return ke(t);default:return!1}}function le(n){if(typeof n!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(n))return!1;let e=Date.parse(`${n}T00:00:00Z`);return Number.isFinite(e)&&new Date(e).toISOString().slice(0,10)===n}function Je(n,e){let t=a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,i=t(n);if(!i||!Array.isArray(i.standings))return null;let r=new Set(e),o=new Set,s=[];for(let a of i.standings){let u=t(a);!u||typeof u.playerId!="string"||!r.has(u.playerId)||o.has(u.playerId)||(o.add(u.playerId),s.push({playerId:u.playerId,...typeof u.score=="number"&&Number.isFinite(u.score)?{score:u.score}:{},...typeof u.rank=="number"&&Number.isSafeInteger(u.rank)&&u.rank>0?{rank:u.rank}:{}}))}return s.length?{standings:s,...Array.isArray(i.winners)?{winners:[...new Set(i.winners.filter(a=>typeof a=="string"&&o.has(a)))]}:{},...typeof i.draw=="boolean"?{draw:i.draw}:{},...typeof i.unit=="string"?{unit:i.unit}:{}}:null}var jt=["en","it","es","fr","de","pt"],Nt={gameUpdated:["This game was updated","Questo gioco \xE8 stato aggiornato","Este juego se ha actualizado","Ce jeu a \xE9t\xE9 mis \xE0 jour","Dieses Spiel wurde aktualisiert","Este jogo foi atualizado"],reloadGame:["Reload game","Ricarica il gioco","Recargar el juego","Recharger le jeu","Spiel neu laden","Recarregar o jogo"],gameLanguages:["Game languages","Lingue del gioco","Idiomas del juego","Langues du jeu","Spielsprachen","Idiomas do jogo"],loading:["Loading game...","Caricamento...","Cargando...","Chargement...","Spiel wird geladen...","Carregando..."],loadingSlow:["This game is taking longer than expected. You can wait a little longer or try again.","Il gioco ci sta mettendo pi\xF9 del previsto. Puoi aspettare ancora un po\u2019 o riprovare.","El juego est\xE1 tardando m\xE1s de lo esperado. Puedes esperar un poco m\xE1s o volver a intentarlo.","Le jeu met plus de temps que pr\xE9vu. Vous pouvez patienter encore un peu ou r\xE9essayer.","Das Spiel braucht l\xE4nger als erwartet. Du kannst noch etwas warten oder es erneut versuchen.","O jogo est\xE1 demorando mais do que o esperado. Voc\xEA pode esperar mais um pouco ou tentar novamente."],home:["Play","Gioca","Jugar","Jouer","Spielen","Jogar"],homeMenu:["Menu","Menu","Men\xFA","Menu","Men\xFC","Menu"],mode:["Mode","Modalit\xE0","Modo","Mode","Modus","Modo"],play:["Play","Gioca","Jugar","Jouer","Spielen","Jogar"],friendsPlay:["Play with friends","Gioca con amici","Jugar con amigos","Jouer entre amis","Mit Freunden spielen","Jogar com amigos"],find:["Find players","Trova giocatori","Buscar jugadores","Trouver des joueurs","Spieler finden","Buscar jogadores"],join:["Join with code","Entra con codice","Entrar con c\xF3digo","Rejoindre avec un code","Mit Code beitreten","Entrar com c\xF3digo"],joinInvite:["Join this room","Entra in questa stanza","Entrar en est\xE1 sala","Rejoindre cette salle","Diesem Raum beitreten","Entrar nest\xE1 sala"],watch:["Watch a room","Guarda una stanza","Observar una sala","Regarder une salle","Raum ansehen","Assistir a uma sala"],resume:["Resume","Riprendi","Continuar","Reprendre","Fortsetzen","Continuar"],room:["Room","Stanza","Sala","Salle","Raum","Sala"],code:["Room code","Codice stanza","C\xF3digo de sala","Code de salle","Raumcode","C\xF3digo da sala"],copy:["Copy invite","Copia invito","Copiar invitaci\xF3n","Copier le lien","Einladung kopieren","Copiar convite"],copied:["Invite copied","Invito copiato","Invitacion copiada","Lien copi\xE9","Einladung kopiert","Convite copiado"],copyFailed:["Copy this link:","Copia questo link:","Copia este enlace:","Copiez ce lien :","Diesen Link kopieren:","Copie este link:"],joining:["Joining room...","Ingresso nella stanza...","Entrando en la sala...","Connexion \xE0 la salle...","Raum wird betreten...","Entrando na sala..."],matching:["Finding your people...","Ricerca giocatori...","Buscando jugadores...","Recherche de joueurs...","Spieler werden gesucht...","Buscando jogadores..."],queue:["{n} / {max} players","{n} / {max} giocatori","{n} / {max} jugadores","{n} / {max} joueurs","{n} / {max} Spieler","{n} / {max} jogadores"],cancel:["Cancel","Annulla","Cancelar","Annuler","Abbrechen","Cancelar"],close:["Close","Chiudi","Cerrar","Fermer","Schlie\xDFen","Fechar"],back:["Back","Indietro","Volver","Retour","Zur\xFCck","Voltar"],ready:["Ready","Pronto","Listo","Pr\xEAt","Bereit","Pronto"],unready:["Not ready","Non pronto","No listo","Pas pr\xEAt","Nicht bereit","N\xE3o pronto"],start:["Start","Inizia","Empezar","Commencer","Starten","Come\xE7ar"],role:["Role","Ruolo","Rol","R\xF4le","Rolle","Fun\xE7\xE3o"],team:["Team","Squadra","Equipo","\xC9quipe","Team","Equipe"],host:["Host","Host","Anfitrion","H\xF4te","Host","Anfitri\xE3o"],you:["You","Tu","T\xFA","Vous","Du","Voc\xEA"],away:["Away","Assente","Ausente","Absent","Abwesend","Ausente"],needPlayers:["Waiting for more players","In attesa di giocatori","Esperando m\xE1s jugadores","En attente de joueurs","Weitere Spieler fehlen","Esperando mais jogadores"],needReady:["Everyone needs to be ready","Tutti devono essere pronti","Todos deben estar listos","Tout le monde doit \xEAtre pr\xEAt","Alle m\xFCssen bereit sein","Todos precisam estar prontos"],needRoles:["Fill the required roles","Completa i ruoli richiesti","Completa los roles","Compl\xE9tez les r\xF4les","Ben\xF6tigte Rollen besetzen","Complete as fun\xE7\xF5es"],needTeams:["Choose the required teams","Scegli le squadre richieste","Elige los equipos","Choisissez les \xE9quipes","Teams auswahlen","Escolha as equipes"],waitHost:["Waiting for the host","In attesa dell'host","Esperando al anfitrion","En attente de l\u2019h\xF4te","Warten auf den Host","Esperando o anfitri\xE3o"],starting:["Starting in","Si inizia tra","Empieza en","D\xE9but dans","Start in","Come\xE7a em"],playing:["Playing","In partita","Jugando","En jeu","Im Spiel","Jogando"],ended:["Game finished","Partita conclusa","Partida terminada","Partie termin\xE9e","Spiel beendet","Partida encerrada"],rematchReady:["{n}/{max} ready","{n}/{max} pronti","{n}/{max} listos","{n}/{max} pr\xEAts","{n}/{max} bereit","{n}/{max} prontos"],rematchStart:["Start rematch","Avvia rivincita","Iniciar revancha","Lancer la revanche","Revanche starten","Iniciar revanche"],won:["You won","Hai vinto","Has ganado","Vous avez gagn\xE9","Du hast gewonnen","Voc\xEA venceu"],lost:["You lost","Hai perso","Has perdido","Vous avez perdu","Du hast verloren","Voc\xEA perdeu"],draw:["Draw","Pareggio","Empate","\xC9galit\xE9","Unentschieden","Empate"],standings:["Standings","Piazzamenti","Posiciones","R\xE9sultats","Platzierungen","Coloca\xE7\xF5es"],points:["points","punti","puntos","points","Punkte","pontos"],time:["time","tempo","tiempo","temps","Zeit","tempo"],distance:["distance","distanza","distancia","distance","Distanz","dist\xE2ncia"],again:["Play again","Gioca ancora","Jugar de nuevo","Rejouer","Erneut spielen","Jogar novamente"],newRoom:["New room. Share the new invite.","Nuova stanza. Condividi il nuovo invito.","Nueva sala. Comparte la invitaci\xF3n.","Nouvelle salle. Partagez le lien.","Neuer Raum. Neue Einladung teilen.","Nova sala. Compartilhe o convite."],watching:["Watching","In osservazione","Observando","Spectateur","Zuschauen","Assistindo"],delay:["{n}s delay","Ritardo {n}s","Retraso de {n}s","Retard de {n}s","{n}s Verz\xF6gerung","Atraso de {n}s"],exit:["Exit","Esci","Salir","Quitter","Verlassen","Sair"],leaveNow:["Leave for now","Esci per ora","Salir por ahora","Quitter pour le moment","Vor\xFCbergehend verlassen","Sair por enquanto"],leaveRoom:["Leave room","Lascia la stanza","Abandonar sala","Abandonner la salle","Raum verlassen","Deixar a sala"],leaveHint:["Your room stays available for Resume.","La stanza resta disponibile con Riprendi.","Podr\xE1s volver a est\xE1 sala.","Vous pourrez reprendre cette salle.","Du kannst den Raum fortsetzen.","Voc\xEA pode voltar a est\xE1 sala."],temporaryHint:["The game continues. Rejoining may only be possible briefly.","La partita continua. Il rientro pu\xF2 essere disponibile solo per poco.","La partida continua. Volver puede ser posible solo por poco tiempo.","La partie continue. Le retour peut \xEAtre limit\xE9.","Das Spiel l\xE4uft weiter. R\xFCckkehr nur kurz m\xF6glich.","A partida continua. O retorno pode ser limitado."],abandonHint:["Leave room gives up your place.","Lascia la stanza libera il tuo posto.","Abandonar libera tu plaza.","Abandonner lib\xE8re votre place.","Raum verlassen gibt deinen Platz frei.","Deixar a sala libera sua vaga."],reconnecting:["Reconnecting...","Riconnessione...","Reconectando...","Reconnexion...","Verbindung wird erneuert...","Reconectando..."],replaced:["Opened in another tab","Aperta in un\u2019altra scheda","Abierta en otra pest\xE1na","Ouverte dans un autre onglet","In anderem Tab ge\xF6ffnet","Aberta em outra aba"],error:["Something went wrong. Try again.","Qualcosa non va. Riprova.","Algo sali\xF3 mal. Reintenta.","Une erreur est survenue. R\xE9essayez.","Etwas ist schiefgelaufen. Erneut versuchen.","Algo deu errado. Tente novamente."],noRoom:["This room is no longer available.","Questa stanza non \xE8 pi\xF9 disponibile.","Esta sala ya no est\xE1 disponible.","Cette salle n'est plus disponible.","Dieser Raum ist nicht mehr verf\xFCgbar.","Esta sala n\xE3o est\xE1 mais disponivel."],full:["This room is full.","La stanza \xE8 piena.","La sala est\xE1 llena.","Cette salle est pleine.","Dieser Raum ist voll.","Esta sala est\xE1 cheia."],noMatch:["No match this time. Try again.","Nessun gruppo trovato. Riprova.","No hay grupo. Reintenta.","Aucun groupe trouv\xE9. R\xE9essayez.","Keine Gruppe gefunden. Erneut versuchen.","Nenhum grupo encontrado. Tente novamente."],invalidCode:["Enter a six-character room code.","Inserisci un codice di sei caratteri.","Escribe un c\xF3digo de seis caracteres.","Entrez un code de six caracteres.","Sechsstelligen Raumcode eingeben.","Digite um c\xF3digo de seis caracteres."],refused:["The room did not accept that change.","La stanza ha rifiutato la modifica.","La sala rechaz\xF3 el cambio.","La salle a refus\xE9 ce changement.","Der Raum hat die \xC4nderung abgelehnt.","A sala recusou a altera\xE7\xE3o."],unavailable:["Unavailable right now","Non disponibile ora","No disponible ahora","Indisponible pour le moment","Derzeit nicht verf\xFCgbar","Indisponivel agora"],offline:["Connection unavailable. Try again.","Connessione non disponibile. Riprova.","Sin conexi\xF3n. Reintenta.","Connexion indisponible. R\xE9essayez.","Keine Verbindung. Erneut versuchen.","Sem conex\xE3o. Tente novamente."],saveFailed:["Keep the room code. Resume could not be saved.","Conserva il codice. Riprendi non \xE8 stato salvato.","Guarda el c\xF3digo. No se pudo guardar el regreso.","Gardez le code. La reprise ne peut pas \xEAtre enregistr\xE9e.","Raumcode aufbewahren. Fortsetzen nicht gespeichert.","Guarde o c\xF3digo. O retorno n\xE3o foi salvo."],boards:["Leaderboard","Classifica","Clasificaci\xF3n","Classement","Bestenliste","Classifica\xE7\xE3o"],board:["Board","Classifica","Tabla","Classement","Bestenliste","Tabela"],daily:["Daily","Giornaliera","Diaria","Du jour","T\xE4glich","Di\xE1ria"],allTime:["All time","Di sempre","Hist\xF3rica","Tous les temps","Gesamt","Geral"],accounts:["Accounts","Account","Cuentas","Comptes","Konten","Contas"],guests:["Guests","Ospiti","Invitados","Invit\xE9s","G\xE4ste","Visitantes"],category:["Category","Categoria","Categoria","Cat\xE9gorie","Kategorie","Categoria"],period:["Period","Periodo","Per\xEDodo","P\xE9riode","Zeitraum","Per\xEDodo"],rank:["Rank","Posizione","Puesto","Rang","Platz","Posicao"],score:["Score","Punteggio","Puntos","Score","Punkte","Pontos"],verified:["Verified","Verificato","Verificado","V\xE9rifi\xE9","Verifiziert","Verificado"],own:["Your best","Il tuo record","Tu record","Votre record","Dein Rekord","Seu recorde"],empty:["No scores yet","Nessun punteggio","A\xFAn no hay puntos","Aucun score","Noch keine Punkte","Ainda sem pontos"],saving:["Saving score...","Salvataggio punteggio...","Guardando puntos...","Enregistrement du score...","Punkte werden gespeichert...","Salvando pontos..."],saved:["Your best is on the board","Il tuo record \xE8 in classifica","Tu record est\xE1 en la tabla","Votre record est au classement","Dein Rekord ist eingetragen","Seu recorde est\xE1 na tabela"],bestAlready:["Your best is already on the board","Il tuo record era gi\xE0 in classifica","Tu record ya estaba en la tabla","Votre record est d\xE9j\xE0 au classement","Dein Rekord ist bereits eingetragen","Seu recorde j\xE1 est\xE1 na tabela"],refresh:["Refresh","Aggiorna","Actualizar","Actualiser","Aktualisieren","Atualizar"],refreshHint:["Score not visible yet. Refresh to check.","Punteggio non ancora visibile. Aggiorna per controllare.","Puntos a\xFAn no visibles. Actualiza.","Score pas encore visible. Actualisez.","Punkte noch nicht sichtbar. Aktualisieren.","Pontos ainda n\xE3o visiveis. Atualize."],friends:["Friends & party","Amici e gruppo","Amigos y grupo","Amis et groupe","Freunde & Gruppe","Amigos e grupo"],localCrew:["Friends and party are unavailable in local preview.","Amici e gruppo non disponibili in anteprima locale.","Amigos y grupo no disponibles en la vista local.","Amis et groupe indisponibles en aper\xE7u local.","Freunde und Gruppe in lokaler Vorschau nicht verf\xFCgbar.","Amigos e grupo indispon\xEDveis na pr\xE9via local."],loginCrew:["Sign in on Caisual to use friends and party.","Accedi a Caisual per amici e gruppo.","Inicia sesion para amigos y grupo.","Connectez-vous pour utiliser amis et groupe.","F\xFCr Freunde und Gruppe bei Caisual anmelden.","Entre no Caisual para amigos e grupo."],online:["Online","Online","En linea","En ligne","Online","Online"],noFriends:["No friends online","Nessun amico online","Sin amigos en linea","Aucun ami en ligne","Keine Freunde online","Nenhum amigo online"],createParty:["Create party","Crea gruppo","Crear grupo","Cr\xE9er un groupe","Gruppe erstellen","Criar grupo"],inviteParty:["Invite to party","Invita nel gruppo","Invitar al grupo","Inviter au groupe","In Gruppe einladen","Convidar para o grupo"],leaveParty:["Leave party","Lascia gruppo","Salir del grupo","Quitter le groupe","Gruppe verlassen","Sair do grupo"],accept:["Accept","Accetta","Aceptar","Accepter","Annehmen","Aceitar"],decline:["Decline","Rifiuta","Rechazar","Refuser","Ablehnen","Recusar"],follow:["Join them","Raggiungi","Unirse","Rejoindre","Beitreten","Juntar-se"],voice:["Voice","Voce","Voz","Voix","Sprache","Voz"],voiceJoin:["Join voice","Entra in voce","Unirse a voz","Activer la voix","Sprachchat beitreten","Entrar na voz"],voiceLeave:["Leave voice","Esci dalla voce","Salir de voz","Quitter la voix","Sprachchat verlassen","Sair da voz"],voiceMute:["Mute","Disattiva microfono","Silenciar","Couper le micro","Stummschalten","Silenciar"],voiceUnmute:["Unmute","Attiva microfono","Activar micr\xF3fono","Activer le micro","Mikrofon aktivieren","Ativar microfone"],voiceOff:["Voice off","Voce disattivata","Voz desactivada","Voix d\xE9sactiv\xE9e","Sprachchat aus","Voz desativada"],voiceJoining:["Joining voice...","Connessione voce...","Conectando voz...","Connexion vocale...","Sprachchat verbindet...","Conectando voz..."],voiceOn:["Voice connected","Voce connessa","Voz conectada","Voix connect\xE9e","Sprachchat verbunden","Voz conectada"],voiceMuted:["Muted","Microfono disattivato","Silenciado","Micro coup\xE9","Stumm","Silenciado"],voiceMic:["Mic on","Microfono attivo","Micr\xF3fono activo","Micro actif","Mikrofon an","Microfone ativo"],voiceListening:["Listening only","Solo ascolto","Solo escucha","\xC9coute seule","Nur zuh\xF6ren","Somente ouvindo"],voiceSpeaking:["Speaking","Sta parlando","Hablando","Parle","Spricht","Falando"],voicePeers:["Voice participants","Partecipanti in voce","Participantes de voz","Participants vocaux","Sprachteilnehmer","Participantes de voz"],voiceEmpty:["No one else in voice yet.","Nessun altro in voce per ora.","A\xFAn no hay nadie m\xE1s en voz.","Personne d\u2019autre en voix pour le moment.","Noch niemand im Sprachchat.","Ningu\xE9m mais na voz ainda."],voiceVolume:["Volume for {name}","Volume di {name}","Volumen de {name}","Volume de {name}","Lautst\xE4rke f\xFCr {name}","Volume de {name}"],voiceUnavailable:["Join a room with voice to use these controls.","Entra in una stanza con voce per usare questi controlli.","Entra en una sala con voz para usar estos controles.","Rejoignez une salle vocale pour utiliser ces commandes.","Diese Steuerung braucht einen Raum mit Sprachchat.","Entre em uma sala com voz para usar estes controles."],voiceWatch:["Voice is unavailable while watching.","La voce non e' disponibile in osservazione.","La voz no est\xE1 disponible al observar.","La voix est indisponible en observation.","Beim Zuschauen ist kein Sprachchat verf\xFCgbar.","A voz n\xE3o est\xE1 dispon\xEDvel ao assistir."],voiceDenied:["Microphone permission denied. Allow it in your browser, then try again.","Permesso microfono negato. Consenti l'accesso nel browser e riprova.","Permiso de micr\xF3fono denegado. Act\xEDvalo en el navegador e int\xE9ntalo de nuevo.","Acc\xE8s au micro refus\xE9. Autorisez-le dans le navigateur, puis r\xE9essayez.","Mikrofonzugriff verweigert. Im Browser erlauben und erneut versuchen.","Permiss\xE3o do microfone negada. Permita no navegador e tente novamente."],voiceUnsupported:["Voice is not supported in this browser.","Questo browser non supporta la voce.","Este navegador no admite voz.","Ce navigateur ne prend pas en charge la voix.","Dieser Browser unterst\xFCtzt keinen Sprachchat.","Este navegador n\xE3o oferece suporte a voz."],voiceFailed:["Voice could not connect. Try again.","Connessione voce non riuscita. Riprova.","No se pudo conectar la voz. Int\xE9ntalo de nuevo.","Connexion vocale impossible. R\xE9essayez.","Sprachverbindung fehlgeschlagen. Erneut versuchen.","N\xE3o foi poss\xEDvel conectar a voz. Tente novamente."],voicePeerGone:["This participant has left voice.","Questo partecipante e' uscito dalla voce.","Este participante sali\xF3 de voz.","Ce participant a quitt\xE9 la voix.","Diese Person hat den Sprachchat verlassen.","Este participante saiu da voz."],shortcut:["Shift+Tab shortcut","Scorciatoia Shift+Tab","Atajo Shift+Tab","Raccourci Maj+Tab","Umschalt+Tab-Kurzbefehl","Atalho Shift+Tab"],menu:["Caisual menu","Menu Caisual","Menu Caisual","Menu Caisual","Caisual-Menu","Menu Caisual"],retry:["Retry","Riprova","Reintentar","R\xE9essayer","Erneut versuchen","Tentar novamente"]},se=n=>Object.fromEntries(Object.entries(Nt).map(([e,t])=>[e,t[n]])),sn={en:se(0),it:se(1),es:se(2),fr:se(3),de:se(4),pt:se(5)};function Be(n){let e=q(n);return e&&jt.includes(e.split("-")[0])?e:"en"}function Ue(n,e,t="/"){let i,r=t.match(/^\/rt\/[^/]+\/[1-9][0-9]*\//)?.[0]??"/";return()=>i??(i=(async()=>{let o={};try{let s=await n(`${r}__caisual/text/${encodeURIComponent(e)}.json`);if(s.ok){let a=await s.json();Ve(a)&&(o=a)}}catch{}return(s,a={})=>Object.hasOwn(o,s)?o[s].replace(/\{([^{}]+)\}/g,(m,g)=>Object.hasOwn(a,g)?String(a[g]):m):s})())}function f(n,e,t={}){return Object.assign(new Error(e),{name:"CaisualError",code:n,...t})}function j(){return f("offline","Caisual services are unavailable.")}function ce(n){return typeof n=="object"&&n!==null&&"code"in n?n.code:null}var Fe="caisual-session-v1";function He(n){let e=N(n);return!e||typeof e.code!="string"||!/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(e.code)||!(e.mode===void 0||e.mode===null||typeof e.mode=="string")?null:{version:1,code:e.code,mode:typeof e.mode=="string"?e.mode:null,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}}function Ke(n,e){let t=null,i=!1,r=Promise.resolve(),o=async()=>{let a={version:1,imported:!0,resume:t};return r=r.catch(()=>{}).then(async()=>{try{await n.set(Fe,a),i=!1}catch(u){throw i=!0,u}finally{e()}}),r},s=(async()=>{try{let a=await n.get(Fe),u=N(a);if(u?.version===1&&u.imported===!0)t=He(u.resume);else{let m=await n.get("resume");t=He(m),(a!==null||m!==null)&&await o()}}catch{i=!0}e()})();return{loaded:s,get value(){return t===null?null:{...t}},get error(){return i},async set(a){await s,t=a,e(),await o()}}}function Z(n,e){for(let t of n)try{t(e)}catch{}}function We(n,e=null,t=n.connected){let i=e?.manifest.overlay?.version===1,r=e?.manifest,o={kind:"idle"},s=!1,a=0,u=0,m=null,g=null,d=null,c=null,y=[],k=!1,C="",D={inputBlocked:i,reservedRects:[],safeArea:{top:0,right:0,bottom:0,left:0}},E=new Set,$=new Set,V=new Set,B=new Set,U=new Set,G=new Set,I=null,F=()=>({local:!0,rooms:t,overlay:i,requestRole:o.kind==="room"&&o.room.metadata.configuration?.requestRole===!0});function P(){if(o.kind!=="room"||!r||r.voice==="none")return null;let l=o.room,v=l.voice;return!v||v.mode==="none"||l.players.find(w=>w.id===l.you)?.role==="spectator"?null:{mode:v.mode,state:v.state,mic:v.mic,muted:v.muted,speaking:v.speaking,peers:v.peers.map(({id:w,mic:R,muted:x,speaking:re,volume:ne})=>({id:w,mic:R,muted:x,speaking:re,volume:ne}))}}function te(){let l=o.kind==="room"||o.kind==="watch"?o.room:null,v=l?.metadata.configuration,w=l?Je(l.result,l.players.map(x=>x.id)):null,R=r&&l&&(l.mode===null||r.modes.some(x=>x.id===l.mode))?je(r,l.mode):{players:{min:1,max:1},lobby:!1};return{kind:m??(o.kind==="idle"?s?"home":"boot":o.kind),id:o.kind==="idle"?null:o.id,mode:m?g:o.kind==="local"?o.mode:l?.mode??null,localStatus:o.kind==="local"?o.status:null,ready:s,capabilities:F(),room:l?{...l.metadata.rematch?.keepSetup||l.metadata.rematch?.autoStart?{rematch:l.metadata.rematch}:{},code:l.code,mode:l.mode,status:l.status,host:l.host,you:o.kind==="room"?o.room.you:null,players:l.players.map(x=>({id:x.id,name:x.name,guest:x.guest,role:x.role,team:x.team,ready:x.ready,connected:x.connected})),...w?{result:w}:{},countdownAt:l.countdownAt,connection:l.connection,closedCode:l.metadata.closedCode,limits:{...v?.players??R.players},lobby:v?.lobby??R.lobby,persistent:v?.persistent??r?.persistent??!1,delayMs:o.kind==="watch"?o.room.delayMs:null,requestRole:v?.requestRole??!1}:null,voice:m?null:P(),waiting:d?{...d}:null,resume:I?.value??null,resumeError:I?.error??!1}}function M(){if(k)return;let l=te(),v=JSON.stringify(l);v!==C&&(C=v,Z(V,l))}function X(){Z(E,{...o}),M()}function H(){if(o.kind!=="room")throw f("no_room","There is no active player room.");return o.room}function ie(){let l=H();if(l.players.find(v=>v.id===l.you)?.role==="spectator")throw f("spectator","Spectators cannot use voice controls.");if(!r||r.voice==="none"||l.voice.mode==="none")throw f("voice_disabled","Voice is disabled for this room.");return l.voice}function K(){a++,c?.abort(),c=null,m=null,d=null,M()}function W(l){y.splice(0).forEach(v=>v()),(o.kind==="room"||o.kind==="watch")&&(l?o.room.disconnect():o.room.leave()),o={kind:"idle"},X()}async function h(l){I?.value?.code===l&&await I.set(null).catch(()=>{})}async function p(l,v,w){if(w!==a||k)throw l.leave(),f("cancelled","The operation was cancelled.");W(!1),o=v?{kind:"watch",room:l,id:String(++u)}:{kind:"room",room:l,id:String(++u)};let R=l;if(y=[R.onPlayers(M),R.onMetadata(()=>{R.connection==="disconnected"&&(o.kind==="room"||o.kind==="watch")&&o.room===R?(y.splice(0).forEach(x=>x()),!v&&R.metadata.closedCode===1e3&&h(R.code),o={kind:"idle"},X()):M()}),R.onStatus(()=>{M(),!v&&R.connection==="ended"&&h(R.code)})],!v){let x=l,re=o.id;x.voice&&y.push(x.voice.onState(M),x.voice.onPeers(M)),y.push(x.onError(ne=>Z(U,{sessionId:re,error:{...ne}}))),y.push(x.onScoreQueued(ne=>Z(G,{...ne})));for(let ne of x.queuedScores)Z(G,{...ne})}return m=null,d=null,X(),!v&&I&&R.connection!=="ended"&&await I.set({version:1,code:R.code,mode:R.mode,updatedAt:n.time.now()}).catch(()=>{}),l}async function z(l,v,w,R=!1){K();let x=a;c=new AbortController,m=l,g=v,M();try{let re=await w(c.signal,x);if(await p(re,R,x),x!==a||k)throw f("cancelled","The operation was cancelled.");return re}finally{x===a&&(m=null,d=null,c=null,M())}}let b=n.room,S=b.onError(l=>{!i||k||(l.code==="version_mismatch"?b.reload():l.code==="version_outdated"&&Z(U,{sessionId:o.kind==="idle"?null:o.id,error:l}))}),A=i?{invited:b.invited,reload:()=>b.reload(),onError:l=>b.onError(l),create(l){return r&&pe(r,l.mode)?Promise.reject(f("invalid_request","Local modes cannot create rooms.")):z("attaching",l.mode,()=>b.create(l))},join(l){return z("attaching",null,()=>b.join(l))},watch(l){return z("attaching",null,()=>b.watch(l),!0)},match(l){return r&&pe(r,l.mode)?Promise.reject(f("invalid_request","Local modes cannot use matchmaking.")):z("matching",l.mode,(v,w)=>{let R=()=>{a===w&&K()};return l.signal?.addEventListener("abort",R,{once:!0}),l.signal?.aborted&&R(),b.match({...l,signal:v,onWaiting(x){w===a&&(d={...x},M(),l.onWaiting?.(x))}}).finally(()=>l.signal?.removeEventListener("abort",R))})}}:b;return i&&(I=Ke(n.save,M)),{session:{get current(){return{...o}},get capabilities(){return F()},onChange(l){return E.add(l),Z(new Set([l]),{...o}),()=>{E.delete(l)}},ready(){k||s||(s=!0,M())},finish(){if(o.kind==="room"||o.kind==="watch")throw f("not_local","Only a local session can be finished by the client.");o.kind==="local"&&(o={...o,status:"ended"},X())}},overlay:{open(l){if(!["home","room","invite","friends","voice","boards"].includes(l))throw f("invalid_request","Unknown overlay panel.");i&&Z(B,l)},onChange(l){return $.add(l),Z(new Set([l]),structuredClone(D)),()=>{$.delete(l)}}},rooms:A,snapshot:te,serverTime:()=>o.kind==="room"||o.kind==="watch"?o.room.serverTime():n.time.now(),onState(l){return V.add(l),l(te()),()=>{V.delete(l)}},onOpen(l){return B.add(l),()=>{B.delete(l)}},onError(l){return U.add(l),()=>{U.delete(l)}},onScore(l){return G.add(l),()=>{G.delete(l)}},async execute(l){if(!i)throw f("overlay_disabled","This game uses its own room flow.");if(l.op==="overlay.view"){if(!ke(l.args))throw f("invalid_request","The overlay geometry is invalid.");if(D={...structuredClone(l.args),safeArea:{top:0,right:0,bottom:0,left:0,...l.args.safeArea}},typeof document<"u")for(let[v,w]of Object.entries(D.safeArea))document.documentElement.style.setProperty(`--caisual-safe-${v}`,`${w}px`);Z($,structuredClone(D));return}if(l.sessionId!==void 0&&l.sessionId!==(o.kind==="idle"?null:o.id))throw f("session_replaced","The active session changed.");if(l.op.startsWith("voice.")&&l.sessionId!==(o.kind==="idle"?null:o.id))throw f("session_replaced","The active session changed.");if(!s)throw f("game_not_ready","The game is still loading.");switch(l.op){case"local.start":{if(!r||!pe(r,l.args.mode))throw f("invalid_mode","This is not a local mode.");K();let v=a;if(o.kind==="room"&&await h(o.room.code),v!==a||k)throw f("cancelled","The operation was cancelled.");W(!1),o={kind:"local",id:String(++u),mode:l.args.mode,status:"playing"},X();return}case"room.create":await A.create(l.args);return;case"room.join":await A.join(l.args.code);return;case"room.watch":await A.watch(l.args.code);return;case"room.match":{let v=r?.modes.find(R=>R.id===l.args.mode),w=l.args.key??v?.matchmaking?.defaults;if(!w)throw f("invalid_request","Matchmaking needs a complete key.");await A.match({mode:l.args.mode,key:w});return}case"voice.join":{let v=H();if(await ie().join(),o.kind!=="room"||o.room!==v)throw f("session_replaced","The active session changed.");M();return}case"voice.mute":ie().mute(l.args.muted),M();return;case"voice.leave":ie().leave(),M();return;case"voice.setVolume":{let v=ie();if(!v.peers.some(w=>w.id===l.args.playerId))throw f("voice_peer_missing","This voice participant is no longer available.");v.setVolume(l.args.playerId,l.args.volume),M();return}case"room.ready":H().ready(l.args.ready);return;case"room.role":H().setRole(l.args.role);return;case"room.requestRole":await H().requestRole(l.args.role);return;case"room.team":H().setTeam(l.args.team);return;case"room.start":H().start();return;case"room.restart":H().restart();return;case"session.cancel":K();return;case"session.resume":{await z("attaching",null,async v=>{if(await I?.loaded,v.aborted)throw f("cancelled","The operation was cancelled.");if(!I?.value)throw f("no_resume","There is no saved room.");return b.join(I.value.code)});return}case"session.disconnect":{K();let v=a;if(o.kind==="room"&&o.room.connection!=="ended"&&I&&await I.set({version:1,code:o.room.code,mode:o.room.mode,updatedAt:n.time.now()}),v!==a||k)throw f("cancelled","The operation was cancelled.");W(!0);return}case"session.leave":{K();let v=a;if(o.kind==="room"&&await h(o.room.code),v!==a||k)throw f("cancelled","The operation was cancelled.");W(!1);return}}},dispose(){S(),K(),W(!0),k=!0,E.clear(),$.clear(),V.clear(),B.clear(),G.clear(),U.clear()}}}function Ze(n,e,t){let i=!0,r=!1,o=e.onChange(a=>{i=a.shortcutEnabled!==!1,r=a.inputBlocked}),s=a=>{let u=a.target;!i||r||a.repeat||a.key!=="Tab"||!a.shiftKey||a.ctrlKey||a.altKey||a.metaKey||u?.closest?.('input,textarea,select,[contenteditable="true"]')||(a.preventDefault(),a.stopImmediatePropagation(),t())};return n.addEventListener("keydown",s,!0),()=>{o(),n.removeEventListener("keydown",s,!0)}}function Qe(n,e,t){let i=!1,r=0,o=0,s=0,a=new Map,u=d=>{if(!i)try{n.postMessage(d)}catch{}},m=[...e.configuration.manifest.overlay&&typeof window<"u"?[Ze(window,t.overlay,()=>u({type:"caisual:overlay-shortcut",v:1,epoch:e.epoch}))]:[],t.onState(d=>u({type:"caisual:overlay-state",v:1,epoch:e.epoch,seq:++r,serverTime:t.serverTime(),state:d})),t.onOpen(d=>u({type:"caisual:overlay-open",v:1,epoch:e.epoch,panel:d})),t.onError(({sessionId:d,error:c})=>u({type:"caisual:overlay-error",v:1,epoch:e.epoch,sessionId:d,error:c})),t.onScore(d=>u({type:"caisual:overlay-score",v:1,epoch:e.epoch,score:d}))],g=d=>{let c=N(d.data);if(c?.type!=="caisual:overlay"||c.epoch!==e.epoch||i)return;let y={type:"caisual:overlay-response",v:1,epoch:e.epoch,requestId:typeof c.requestId=="string"?c.requestId:""};if(!qe(c)){u({...y,ok:!1,error:{code:"invalid_request",message:"The overlay request is invalid."}});return}let k=JSON.stringify([c.op,c.args,c.sessionId]),C=a.get(c.requestId);if(C){C.fingerprint!==k?u({...y,ok:!1,error:{code:"duplicate_request",message:"The request id was already used."}}):C.response.then(u);return}if(Number(c.requestId)<=o||s>=32){u({...y,ok:!1,error:{code:"stale_request",message:"The request is stale or too many requests are pending."}});return}o=Number(c.requestId),s++;let D=Promise.resolve().then(()=>t.execute(c)).then(()=>({...y,ok:!0}),E=>({...y,ok:!1,error:{code:typeof N(E)?.code=="string"?N(E).code:"internal_error",message:E instanceof Error?E.message:"The operation could not be completed."}}));a.set(c.requestId,{fingerprint:k,response:D}),D.then(E=>{if(s--,u(E),a.size>64)for(let $ of a.keys())Number($)<o-64&&a.delete($)})};return n.addEventListener("message",g),n.start(),()=>{i=!0,n.removeEventListener("message",g),m.forEach(d=>d()),t.dispose(),a.clear()}}async function $t(n){let e={};try{e=await n.json()}catch{}return f(typeof e.error?.code=="string"?e.error.code:n.status===401?"invalid_ticket":"internal_error",typeof e.error?.message=="string"?e.error.message:`The request failed with status ${n.status}.`,{currentVersion:e.error?.currentVersion,roomVersion:e.error?.roomVersion})}function fe(n,e,t,i){async function r(o,s,a,u){let m=new Headers({Authorization:`Bearer ${a}`}),g;if(u!==void 0){m.set("Content-Type","application/json");try{g=JSON.stringify(u)}catch{throw f("invalid_request","The value must be valid JSON.")}}try{return await t(new URL(e+o,n),{method:s,headers:m,body:g,credentials:"omit"})}catch{throw j()}}return async function(s,a,u,m=!1){let g;try{g=m?await i.rinnova():await i.ottieni()}catch{throw j()}let d=await r(s,a,g,u);if(d.status===401){try{g=await i.rinnova()}catch{throw j()}d=await r(s,a,g,u)}if(!d.ok)throw await $t(d);try{return await d.json()}catch{throw f("internal_error","The service returned an invalid response.")}}}function Ye(n,e,t){let i=fe(n,"/api/kit",e,t);return{me:()=>i("/me","GET"),saveSet:(r,o)=>i(`/saves/${encodeURIComponent(r)}`,"PUT",{value:o}),async saveGet(r){try{return(await i(`/saves/${encodeURIComponent(r)}`,"GET")).value}catch(o){if(ce(o)==="not_found")return null;throw o}},async saveRemove(r){await i(`/saves/${encodeURIComponent(r)}`,"DELETE")},async saveList(){return(await i("/saves","GET")).saves},async boardSubmit(r,o,s){let a=await i("/scores","POST",{board:r,score:o,daily:s});return{accepted:!0,best:a.best,rank:a.rank,day:a.day,verified:a.verified}},async boardTop(r,o){if(o.day!==void 0&&(!le(o.day)||o.daily===!1))throw f("invalid_request","day must be a real UTC date and cannot be combined with daily: false.");let s=new URLSearchParams;o.day!==void 0&&s.set("day",o.day),o.daily&&s.set("daily","1"),o.limit!==void 0&&s.set("limit",String(o.limit)),o.guests&&s.set("guests","1");let a=s.size===0?"":`?${s.toString()}`,{day:u,entries:m,me:g}=await i(`/scores/${encodeURIComponent(r)}${a}`,"GET");return{day:u,entries:m,me:g}}}}function ae(n){return(Math.floor(n/864e5)+1)*864e5}function he(n,e,t){let i=new Set,r={...n},o,s=!1;function a(){!i.size||o!==void 0||s||(o=setTimeout(u,Math.max(0,Math.min(2147483647,r.expiresAt-e()))),o.unref?.())}async function u(){o=void 0,s=!0;try{let m=await t(),g=m.day!==r.day;if(r={...m},g)for(let d of[...i])try{d({...m})}catch{}}catch{}finally{s=!1,r.expiresAt<=e()&&(r.expiresAt=e()+3e4),a()}}return{...n,random:Xe(n.seed),rng:()=>Xe(n.seed),onChange(m){return i.add(m),a(),()=>{i.delete(m),!i.size&&o!==void 0&&(clearTimeout(o),o=void 0)}}}}function Ce(n){return new Date(n).toISOString().slice(0,10)}async function Pe(n,e,t){let i=new TextEncoder().encode(`caisual:${n}:${e}`),r=new Uint8Array(await t.digest("SHA-256",i));return(r[0]??0)*16777216+((r[1]??0)<<16)+((r[2]??0)<<8)+(r[3]??0)>>>0}function Xe(n){let e=n>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}function ge(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function et(n,e){return ge(n)?.type===e}function Gt(n){if(typeof n!="string")return null;try{let e=new URL(n);return e.origin===n&&(e.protocol==="https:"||e.protocol==="http:")?n:null}catch{return null}}function tt(n,e,t=3e3){return new Promise(i=>{let r=!1,o=globalThis.crypto.randomUUID(),s=g=>{r||(r=!0,n.removeEventListener("message",u),n.clearTimeout(m),i(g))},a=()=>{n.parent.postMessage({type:"caisual:ready",instance:o,overlayVersion:1},e)},u=g=>{if(g.origin!==e||g.source!==n.parent)return;if(et(g.data,"caisual:ready?")){a();return}if(!et(g.data,"caisual:hello"))return;let d=ge(g.data),c=g.ports[0];if(typeof d?.ticket!="string"||!xe(d.n)||c===void 0)return;c.start();let y=Ge(d.overlay),k=C=>Array.isArray(C)?C.map(q).filter(D=>D!==null):void 0;s({...y?{overlay:y}:{},...q(d.language)?{language:q(d.language)}:{},uiLanguage:q(d.uiLanguage)??void 0,languagePreferences:k(d.languagePreferences),gameLanguages:k(d.gameLanguages),ticket:d.ticket,n:d.n,live:Gt(d.live),invite:typeof d.invite=="string"?d.invite:null,porta:c})};n.addEventListener("message",u);let m=n.setTimeout(()=>s(null),t);a()})}function qt(n){let e=n.split(".")[1];if(e===void 0)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=");try{let i=ge(JSON.parse(globalThis.atob(t)));return typeof i?.exp=="number"&&Number.isFinite(i.exp)?i.exp*1e3:null}catch{return null}}function Jt(n,e,t,i){return new Promise((r,o)=>{let s=!1,a=g=>{s||(s=!0,n.removeEventListener("message",u),e.clearTimeout(m),g===null?o(new Error("Ticket refresh timed out.")):r(g))},u=g=>{let d=ge(g.data),c=d?.aud===void 0?"portal":d.aud;d?.type==="caisual:ticket"&&c===i&&typeof d.ticket=="string"&&a(d.ticket)};n.addEventListener("message",u);let m=e.setTimeout(()=>a(null),t);try{n.postMessage(i==="live"?{type:"caisual:ticket",aud:"live"}:{type:"caisual:ticket"})}catch{a(null)}})}function Ae(n,e,t,i,r=3e3,o="portal"){let s=n,a=null,u=()=>{if(a!==null)return a;let g=Jt(e,t,r,o).then(d=>(s=d,d)).finally(()=>{a===g&&(a=null)});return a=g,g};return{async ottieni(){if(s===null)return u();let m=qt(s);return m!==null&&m-i()<3e4?u():s},rinnova:u}}var Te=.02,it=300,Bt=200,nt=3e3,Ut=1e4,Ft=[1e3,2e3,4e3];function ot(n){return Number.isNaN(n)?1:Math.min(1,Math.max(0,n))}function Ht(n){let e=globalThis,t=e.AudioContext??e.webkitAudioContext;return typeof RTCPeerConnection>"u"||typeof MediaStream>"u"||t===void 0||typeof navigator>"u"||navigator.mediaDevices?.getUserMedia===void 0||typeof document>"u"?null:{...n,creaPeerConnection:i=>new RTCPeerConnection(i),getUserMedia:i=>navigator.mediaDevices.getUserMedia(i),creaAudioContext:()=>new t,creaAudioElement:()=>document.createElement("audio"),creaMediaStream:i=>new MediaStream(i)}}var ve=class{constructor(e,t,i){this.contesto=e;this.modeCorrente="none";this.stateCorrente="off";this.mutedCorrente=!1;this.speakingCorrente=!1;this.roster=[];this.gains=new Map;this.volumi=new Map;this.speakingPeers=new Map;this.ultimoAudio=new Map;this.zeroDa=new Map;this.timerZero=new Map;this.ascoltatoriPeers=new Set;this.ascoltatoriState=new Set;this.richieste=new Map;this.riproduzioni=new Map;this.sfuAttive=new Map;this.midGiocatori=new Map;this.negati=new Set;this.mesh=new Map;this.stream=null;this.tracciaMic=null;this.audioContext=null;this.analyser=null;this.peerSfu=null;this.sessioneSfu=null;this.connessioneSfuAttesa=!1;this.trasporto=null;this.intervalloAudio=null;this.timerConnessione=null;this.cancellaAttesaConnessione=null;this.timerRiconnessione=null;this.ultimoAudioMic=Number.NEGATIVE_INFINITY;this.sequenzaRichieste=0;this.generazione=0;this.tentativoRiconnessione=0;this.desiderata=!1;this.micDesiderato=!0;this.promessaIngresso=null;this.negoziazione=Promise.resolve();this.dipendenze=i??Ht(t)}get mode(){return this.modeCorrente}get state(){return this.stateCorrente}get mic(){return this.stateCorrente==="on"&&this.tracciaMic!==null}get muted(){return this.mutedCorrente}get speaking(){return this.speakingCorrente}get peers(){return this.copiaPeers()}async join(e={}){if(this.stateCorrente==="on")return;if(this.stateCorrente==="joining"){this.promessaIngresso!==null&&await this.promessaIngresso;return}if(this.stateCorrente==="reconnecting"&&this.desiderata)return;let t=this.scegliMic(e);this.verificaIngresso(t),this.micDesiderato=t,this.desiderata=!0,this.tentativoRiconnessione=0,this.aggiornaState("joining");let i=++this.generazione,r=this.completaIngresso(i);this.promessaIngresso=r;try{await r}finally{this.promessaIngresso===r&&(this.promessaIngresso=null)}}async completaIngresso(e){try{await this.entra(e)}catch(t){if(e!==this.generazione)return;throw this.desiderata=!1,this.chiudiRisorse(),this.aggiornaState("off"),this.mappaErrore(t)}}leave(){let e=this.desiderata||this.stateCorrente!=="off";this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),e&&this.contesto.connessa()&&this.richiedi({t:"voice",op:"stop"}).catch(()=>{}),this.rifiutaRichieste(f("offline","Voice has stopped.")),this.chiudiRisorse(),this.aggiornaState("off")}mute(e=!0){if(this.stateCorrente!=="on"||this.tracciaMic===null)throw f("not_publishing","Join voice before changing mute.");this.mutedCorrente=e,this.tracciaMic.enabled=!e,e&&(this.speakingCorrente=!1),this.notificaPeers(),this.richiedi({t:"voice",op:"mute",muted:e}).catch(()=>{})}setVolume(e,t){let i=ot(t);this.volumi.set(e,i),this.aggiornaGuadagno(e),this.notificaPeers()}onPeers(e){return this.ascoltatoriPeers.add(e),()=>{this.ascoltatoriPeers.delete(e)}}onState(e){return this.ascoltatoriState.add(e),()=>{this.ascoltatoriState.delete(e)}}ricevi(e){if("r"in e){let t=this.richieste.get(e.r);t!==void 0&&(this.richieste.delete(e.r),"error"in e?t.reject(f(e.error.code,e.error.message)):t.resolve(e));return}if(e.op==="roster"){this.negati.clear(),this.modeCorrente=e.mode;let t=new Set(e.peers.map(i=>i.id));this.roster=[...e.peers.map(i=>({...i,mic:!0})),...e.listeners.flatMap(i=>t.has(i)?[]:[{id:i,mic:!1,muted:!0}])];for(let i of this.roster)i.muted&&this.speakingPeers.set(i.id,!1);this.pulisciPeerAssenti(),this.contesto.rosterPronto(),this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="gain"){this.negati.clear();for(let[t,i]of Object.entries(e.gains))this.gains.set(t,ot(i)),this.aggiornaZero(t),this.aggiornaGuadagno(t);this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="closed"){for(let t of e.mids){let i=this.midGiocatori.get(t);if(i===void 0)continue;let r=this.sfuAttive.get(i);r?.mid===t&&!this.riproduzioni.has(i)&&r.receiver?.track.stop(),r?.mid===t&&this.sfuAttive.delete(i),this.midGiocatori.delete(t),this.scollegaTraccia(i),this.negati.add(i)}this.notificaPeers();return}e.op==="signal"&&this.riceviSegnale(e.from,e.data)}giocatoriCambiati(){this.negati.clear();let e=new Set(this.contesto.giocatori().map(t=>t.id));for(let t of this.gains.keys()){if(e.has(t))continue;this.gains.delete(t),this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t),this.aggiornaGuadagno(t)}this.notificaPeers(),this.accodaRiconciliazione()}socketDisconnesso(){this.sequenzaRichieste=0,this.rifiutaRichieste(f("offline","The room is reconnecting.")),this.desiderata&&(this.generazione++,this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"))}socketRiconnesso(){this.sequenzaRichieste=0,this.desiderata&&this.stateCorrente==="reconnecting"&&this.programmaRiconnessione()}termina(){this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),this.rifiutaRichieste(f("offline","The room connection ended.")),this.chiudiRisorse(),this.aggiornaState("off")}scegliMic(e){return e.mic!==void 0?e.mic:this.contesto.giocatori().find(i=>i.id===this.contesto.you())?.role!=="spectator"}verificaIngresso(e=this.micDesiderato){if(!this.contesto.connessa())throw f("offline","The room is not connected.");if(this.modeCorrente==="none")throw f("voice_disabled","Voice is disabled for this room.");if(this.contesto.giocatori().find(i=>i.id===this.contesto.you())?.role==="spectator"&&e)throw f("spectator","Spectators cannot publish voice.");if(this.dipendenze===null)throw f("unsupported","Voice is not supported in this browser.")}async entra(e){this.verificaIngresso();let t=this.richiediDipendenze(),i=t.creaAudioContext();if(this.audioContext=i,this.micDesiderato){let o;try{o=await t.getUserMedia({audio:!0})}catch(a){throw this.permessoNegato(a)?f("permission_denied","Microphone permission was denied."):f("voice_error","The microphone could not be opened.")}try{this.controllaGenerazione(e)}catch(a){for(let u of o.getTracks())u.stop();throw a}let s=o.getAudioTracks()[0];if(s===void 0)throw f("voice_error","The microphone has no audio track.");this.stream=o,this.tracciaMic=s,s.enabled=!this.mutedCorrente,this.preparaAnalizzatore(o)}try{await i.resume()}catch{}this.controllaGenerazione(e);let r=await this.richiedi({t:"voice",op:"ice"});if(this.controllaGenerazione(e),r.op!=="ice")throw f("voice_error","The voice service returned an invalid response.");if(this.modeCorrente=r.mode,r.mode==="none")throw f("voice_disabled","Voice is disabled for this room.");this.trasporto=r.transport,r.transport==="sfu"?await this.entraSfu(r.iceServers,e):await this.richiedi({t:"voice",op:"publish",mic:this.micDesiderato}),this.micDesiderato&&this.mutedCorrente&&await this.richiedi({t:"voice",op:"mute",muted:!0}),this.controllaGenerazione(e),this.tentativoRiconnessione=0,this.aggiornaState("on"),this.avviaMisuraAudio();for(let o of this.gains.keys())this.aggiornaZero(o);this.accodaRiconciliazione()}async entraSfu(e,t){let i=this.richiediDipendenze().creaPeerConnection({iceServers:e,bundlePolicy:"max-bundle"});this.peerSfu=i,i.ontrack=o=>{let s=o.transceiver.mid,a=s===null?void 0:this.midGiocatori.get(s);a!==void 0&&this.collegaTraccia(a,o.track,o.receiver)},this.osservaCaduta(i);let r;if(this.micDesiderato){let o=i.addTransceiver(this.richiediMic(),{direction:"sendonly"}),s=await i.createOffer();await i.setLocalDescription(s),this.controllaGenerazione(t);let a=o.mid,u=i.localDescription?.sdp;if(a===null||u===void 0)throw f("voice_error","The voice connection could not create an offer.");r=await this.richiedi({t:"voice",op:"session",sdp:u,mid:a})}else r=await this.richiedi({t:"voice",op:"session"});if(r.op!=="session")throw f("voice_error","The voice service returned an invalid response.");if(this.sessioneSfu=r.session,this.micDesiderato){if(r.sdp===null)throw f("voice_error","The voice service returned an invalid response.");await i.setRemoteDescription({type:"answer",sdp:r.sdp}),await this.attendiConnessione(i,t),this.connessioneSfuAttesa=!0;return}if(r.sdp!==null)throw f("voice_error","The voice service returned an invalid response.");this.publisherDesiderati().length>0&&await this.riconciliaSfu()}attendiConnessione(e,t){if(e.connectionState==="connected")return Promise.resolve();let i=this.richiediDipendenze();return new Promise((r,o)=>{let s=()=>{e.removeEventListener("connectionstatechange",a),this.timerConnessione!==null&&i.clearTimeout(this.timerConnessione),this.timerConnessione=null,this.cancellaAttesaConnessione=null},a=()=>{t!==this.generazione?(s(),o(f("offline","Voice was stopped."))):e.connectionState==="connected"?(s(),r()):(e.connectionState==="failed"||e.connectionState==="closed")&&(s(),o(f("voice_error","The voice connection failed.")))};e.addEventListener("connectionstatechange",a),this.cancellaAttesaConnessione=()=>{s(),o(f("offline","Voice was stopped."))},this.timerConnessione=i.setTimeout(()=>{s(),o(f("voice_error","The voice connection timed out."))},Ut)})}accodaRiconciliazione(){this.stateCorrente==="on"&&(this.negoziazione=this.negoziazione.then(async()=>{this.stateCorrente==="on"&&(this.trasporto==="sfu"?await this.riconciliaSfu():this.trasporto==="mesh"&&this.riconciliaMesh())}).catch(()=>this.avviaRiconnessione()))}async riconciliaSfu(){let e=this.sessioneSfu,t=this.peerSfu;if(e===null||t===null)return;let i=new Map(this.publisherDesiderati().map(m=>[m.id,m])),r=[];for(let[m,g]of this.sfuAttive){let d=i.get(m);d!==void 0&&d.session===g.session&&d.track===g.track||(r.push(g),this.riproduzioni.has(m)||g.receiver?.track.stop(),this.sfuAttive.delete(m),this.midGiocatori.delete(g.mid),this.scollegaTraccia(m))}r.length>0&&await this.richiedi({t:"voice",op:"close",session:e,mids:r.map(m=>m.mid)});let o=[...i.values()].filter(m=>!this.sfuAttive.has(m.id));if(o.length===0)return;let s;try{s=await this.richiedi({t:"voice",op:"subscribe",session:e,tracks:o.map(m=>({session:m.session,track:m.track}))})}catch(m){if(ce(m)!=="not_allowed")throw m;for(let g of o)this.negati.add(g.id);return}if(s.op!=="subscribe")throw f("voice_error","The voice service returned an invalid response.");for(let m of s.tracks){let g=o.find(d=>d.session===m.session&&d.track===m.track);m.error==="not_allowed"&&g!==void 0&&this.negati.add(g.id),!(m?.mid===null||m?.mid===void 0||m.error!==null||g===void 0)&&(this.midGiocatori.set(m.mid,g.id),this.sfuAttive.set(g.id,{session:g.session,track:g.track,mid:m.mid,receiver:null}))}await t.setRemoteDescription({type:"offer",sdp:s.sdp});let a=await t.createAnswer();await t.setLocalDescription(a);let u=t.localDescription?.sdp;if(u===void 0)throw f("voice_error","The voice answer is missing.");await this.richiedi({t:"voice",op:"answer",session:e,sdp:u}),this.connessioneSfuAttesa||(await this.attendiConnessione(t,this.generazione),this.connessioneSfuAttesa=!0)}riconciliaMesh(){let e=new Map(this.peerDesiderati().map(t=>[t.id,t]));for(let[t,i]of this.mesh)e.has(t)||(i.pc.close(),this.mesh.delete(t),this.scollegaTraccia(t));for(let t of e.values())this.mesh.has(t.id)||this.creaMesh(t)}creaMesh(e){let t=e.id,i=this.richiediDipendenze().creaPeerConnection(),r={pc:i,makingOffer:!1,ignoreOffer:!1,settingRemoteAnswer:!1,polite:this.contesto.you()>t,receiver:null};this.mesh.set(t,r),i.onicecandidate=o=>{o.candidate!==null&&this.inviaSegnale(t,{kind:"candidate",candidate:o.candidate.toJSON()})},r.polite||(i.onnegotiationneeded=()=>{this.offriMesh(t,r)}),i.ontrack=o=>{r.receiver=o.receiver,this.collegaTraccia(t,o.track,o.receiver)},this.osservaCaduta(i),this.micDesiderato?i.addTransceiver(this.richiediMic(),{direction:e.mic?"sendrecv":"sendonly"}):i.addTransceiver("audio",{direction:"recvonly"})}async offriMesh(e,t){try{t.makingOffer=!0;let i=await t.pc.createOffer();await t.pc.setLocalDescription(i);let r=t.pc.localDescription?.sdp;r!==void 0&&await this.inviaSegnale(e,{kind:"offer",sdp:r})}finally{t.makingOffer=!1}}async riceviSegnale(e,t){if(this.trasporto!=="mesh"||this.stateCorrente!=="on")return;let i=this.peerDesiderati().find(s=>s.id===e);if(i===void 0)return;this.mesh.has(e)||this.creaMesh(i);let r=this.mesh.get(e);if(r===void 0||typeof t!="object"||t===null||Array.isArray(t))return;let o=t;try{if(o.kind==="candidate"){r.ignoreOffer||await r.pc.addIceCandidate(o.candidate);return}if(o.kind!=="offer"&&o.kind!=="answer"||typeof o.sdp!="string")return;let s=!r.makingOffer&&(r.pc.signalingState==="stable"||r.settingRemoteAnswer),a=o.kind==="offer"&&!s;if(r.ignoreOffer=!r.polite&&a,r.ignoreOffer)return;if(r.settingRemoteAnswer=o.kind==="answer",await r.pc.setRemoteDescription({type:o.kind,sdp:o.sdp}),r.settingRemoteAnswer=!1,o.kind==="offer"){let u=await r.pc.createAnswer();await r.pc.setLocalDescription(u);let m=r.pc.localDescription?.sdp;m!==void 0&&await this.inviaSegnale(e,{kind:"answer",sdp:m})}}catch{this.avviaRiconnessione()}}async inviaSegnale(e,t){try{await this.richiedi({t:"voice",op:"signal",to:e,data:t})}catch(i){if(ce(i)!=="not_allowed")throw i;this.mesh.get(e)?.pc.close(),this.mesh.delete(e),this.scollegaTraccia(e),this.negati.add(e)}}peerDesiderati(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.filter(r=>{if(r.id===e||this.negati.has(r.id)||!this.micDesiderato&&!r.mic)return!1;if(this.modeCorrente==="team"){let o=t.find(s=>s.id===r.id);if(i?.role!=="spectator"&&o?.team!==i?.team)return!1}return!0})}publisherDesiderati(){return this.peerDesiderati().filter(e=>{if(!e.mic)return!1;let t=this.zeroDa.get(e.id);return t===void 0||this.richiediDipendenze().ora()-t<nt})}aggiornaZero(e){let t=this.dipendenze;if(t===null)return;let i=this.timerZero.get(e);if(i!==void 0&&t.clearTimeout(i),this.timerZero.delete(e),(this.gains.get(e)??1)>0){this.zeroDa.delete(e);return}this.zeroDa.has(e)||this.zeroDa.set(e,t.ora());let r=t.ora()-(this.zeroDa.get(e)??t.ora()),o=t.setTimeout(()=>{this.timerZero.delete(e),this.accodaRiconciliazione()},Math.max(0,nt-r));this.timerZero.set(e,o)}collegaTraccia(e,t,i){this.scollegaTraccia(e);let r=this.richiediDipendenze(),o=r.creaMediaStream([t]),s=this.richiediAudioContext().createMediaStreamSource(o),a=this.richiediAudioContext().createGain();s.connect(a),a.connect(this.richiediAudioContext().destination);let u=null;try{u=this.richiediAudioContext().createAnalyser(),u.fftSize=256,s.connect(u)}catch{u=null}let m=r.creaAudioElement();m.srcObject=o,m.muted=!0,m.playsInline=!0,m.play().catch(()=>{}),this.riproduzioni.set(e,{source:s,gain:a,analyser:u,audio:m,track:t,receiver:i});let g=this.sfuAttive.get(e);g!==void 0&&(g.receiver=i),this.aggiornaGuadagno(e)}scollegaTraccia(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.source.disconnect(),t.gain.disconnect(),t.analyser?.disconnect(),t.track.stop(),t.audio.pause(),t.audio.srcObject=null,this.riproduzioni.delete(e),this.speakingPeers.delete(e),this.ultimoAudio.delete(e))}aggiornaGuadagno(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.gain.gain.value=(this.volumi.get(e)??1)*(this.gains.get(e)??1))}preparaAnalizzatore(e){let t=this.richiediAudioContext(),i=t.createAnalyser();i.fftSize=256,t.createMediaStreamSource(e).connect(i),this.analyser=i}avviaMisuraAudio(){let e=this.richiediDipendenze();this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.intervalloAudio=e.setInterval(()=>this.misuraAudio(),Bt)}misuraAudio(){let e=this.dipendenze;if(e===null)return;let t=!1;this.analyser!==null&&(t=this.livelloAnalizzatore(this.analyser)>Te),t&&(this.ultimoAudioMic=e.ora());let i=!this.mutedCorrente&&e.ora()-this.ultimoAudioMic<=it;i!==this.speakingCorrente&&(this.speakingCorrente=i,this.notificaPeers());let r=!1;for(let o of this.copiaPeers()){let s=this.riproduzioni.get(o.id);this.livelloAnalizzatore(s?.analyser??null)>Te?this.ultimoAudio.set(o.id,e.ora()):(s?.analyser===null||s?.analyser===void 0)&&(s?.receiver?.getSynchronizationSources?.()??[]).some(m=>(m.audioLevel??0)>Te)&&this.ultimoAudio.set(o.id,e.ora());let a=!o.muted&&e.ora()-(this.ultimoAudio.get(o.id)??0)<=it;(this.speakingPeers.get(o.id)??!1)!==a&&(this.speakingPeers.set(o.id,a),r=!0)}r&&this.notificaPeers()}livelloAnalizzatore(e){let t=e;if(t?.getFloatTimeDomainData===void 0)return 0;let i=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(i),Math.sqrt(i.reduce((r,o)=>r+o*o,0)/Math.max(1,i.length))}copiaPeers(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.flatMap(r=>{if(r.id===e)return[];if(this.modeCorrente==="team"){let o=t.find(s=>s.id===r.id);if(i?.role!=="spectator"&&o?.team!==i?.team)return[]}return[{id:r.id,mic:r.mic,muted:r.muted,speaking:r.mic&&!r.muted&&(this.speakingPeers.get(r.id)??!1),volume:this.volumi.get(r.id)??1,gain:this.gains.get(r.id)??1}]})}pulisciPeerAssenti(){let e=new Set(this.roster.map(t=>t.id));for(let t of this.speakingPeers.keys())e.has(t)||this.speakingPeers.delete(t);for(let t of this.zeroDa.keys()){if(e.has(t))continue;this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t)}}osservaCaduta(e){e.addEventListener("connectionstatechange",()=>{this.stateCorrente==="on"&&(e.connectionState==="failed"||e.connectionState==="disconnected")&&this.avviaRiconnessione()})}avviaRiconnessione(){!this.desiderata||this.stateCorrente==="reconnecting"||(this.generazione++,this.rifiutaRichieste(f("voice_error","The voice connection was restarted.")),this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"),this.programmaRiconnessione())}programmaRiconnessione(){if(!this.desiderata||!this.contesto.connessa()||this.timerRiconnessione!==null||this.stateCorrente!=="reconnecting")return;let e=Ft[this.tentativoRiconnessione];if(e===void 0){this.desiderata=!1,this.aggiornaState("off");return}this.tentativoRiconnessione++,this.timerRiconnessione=this.richiediDipendenze().setTimeout(()=>{this.timerRiconnessione=null;let t=++this.generazione;this.entra(t).catch(()=>{t!==this.generazione||!this.desiderata||(this.chiudiRisorse(),this.aggiornaState("reconnecting"),this.programmaRiconnessione())})},e)}fermaRiconnessione(){this.timerRiconnessione===null||this.dipendenze===null||(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}chiudiRisorse(){let e=this.dipendenze;if(this.cancellaAttesaConnessione?.(),this.cancellaAttesaConnessione=null,e!==null){this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.timerConnessione!==null&&e.clearTimeout(this.timerConnessione);for(let t of this.timerZero.values())e.clearTimeout(t)}this.intervalloAudio=null,this.timerConnessione=null,this.timerZero.clear();for(let t of[...this.riproduzioni.keys()])this.scollegaTraccia(t);this.peerSfu?.close(),this.peerSfu=null;for(let t of this.mesh.values())t.pc.close();this.mesh.clear(),this.sfuAttive.clear(),this.midGiocatori.clear(),this.negati.clear();for(let t of this.stream?.getTracks()??[])t.stop();this.stream=null,this.tracciaMic=null,this.analyser=null,this.audioContext?.close().catch(()=>{}),this.audioContext=null,this.sessioneSfu=null,this.connessioneSfuAttesa=!1,this.trasporto=null,this.speakingCorrente=!1,this.ultimoAudioMic=Number.NEGATIVE_INFINITY,this.speakingPeers.clear(),this.ultimoAudio.clear(),this.negoziazione=Promise.resolve()}richiedi(e){if(!this.contesto.connessa())return Promise.reject(f("offline","The room is reconnecting."));let t=++this.sequenzaRichieste;return new Promise((i,r)=>{this.richieste.set(t,{resolve:i,reject:r});try{this.contesto.invia({...e,r:t})}catch(o){this.richieste.delete(t),r(o)}})}rifiutaRichieste(e){for(let t of this.richieste.values())t.reject(e);this.richieste.clear()}aggiornaState(e){if(e!==this.stateCorrente){this.stateCorrente=e;for(let t of this.ascoltatoriState)try{t(e)}catch{}}}notificaPeers(){let e=this.copiaPeers();for(let t of this.ascoltatoriPeers)try{t(e)}catch{}}controllaGenerazione(e){if(e!==this.generazione||!this.desiderata)throw f("offline","Voice was stopped.")}richiediDipendenze(){if(this.dipendenze===null)throw f("unsupported","Voice is not supported.");return this.dipendenze}richiediMic(){if(this.tracciaMic===null)throw f("voice_error","The microphone is not ready.");return this.tracciaMic}richiediAudioContext(){if(this.audioContext===null)throw f("voice_error","Audio is not ready.");return this.audioContext}permessoNegato(e){return typeof e=="object"&&e!==null&&"name"in e&&(e.name==="NotAllowedError"||e.name==="SecurityError")}mappaErrore(e){if(typeof e=="object"&&e!==null&&"code"in e){let t=e.code;return t==="voice_disabled"||t==="permission_denied"||t==="unsupported"||t==="spectator"||t==="offline"||t==="voice_error"?e:f("voice_error","Voice could not be started.")}return f("voice_error","Voice could not be started.")}};var ee=1,rt=[1e3,2e3,4e3,8e3],Kt=6e4,Wt=5e3,Zt=2e4,Qt=500,Yt=2e3,Xt=new Set([4003,4004,4005,4006,4008,4009]);function Y(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function st(n){let e=Y(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.join=="string"&&typeof e.url=="string"}function ei(n){let e=Y(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.watch=="string"&&typeof e.url=="string"}function ti(n){let e=Y(n),t=Y(e?.players);return e!==null&&typeof e.url=="string"&&Number.isInteger(e.timeoutMs)&&e.timeoutMs>=1e3&&e.timeoutMs<=3e5&&t!==null&&Number.isInteger(t.min)&&Number.isInteger(t.max)&&t.min>=1&&t.max>=t.min}function Q(n){return JSON.parse(JSON.stringify(n))}function ii(n,e){let t=Q(n);for(let i of e){if(i.path.length===0){if(i.op!=="set")return{ok:!1};t=Q(i.value);continue}let r=t,o=i.path;for(let a=0;a<o.length-1;a++){let u=o[a];if(Array.isArray(r)){if(typeof u!="number"||u>=r.length)return{ok:!1};r=r[u]}else{let m=Y(r);if(m===null||typeof u!="string"||!Object.hasOwn(m,u))return{ok:!1};r=m[u]}}let s=o.at(-1);if(Array.isArray(r)){if(i.op!=="set"||typeof s!="number"||s>=r.length)return{ok:!1};r[s]=Q(i.value)}else{let a=Y(r);if(a===null||typeof s!="string")return{ok:!1};if(i.op==="del"){if(!Object.hasOwn(a,s))return{ok:!1};delete a[s]}else Object.defineProperty(a,s,{configurable:!0,enumerable:!0,value:Q(i.value),writable:!0})}}return{ok:!0,state:t}}function ni(n){let e=fe(n.liveOrigin,"",n.fetcher,n.biglietto),t=async(s,a,u,m)=>{try{return await e(s,a,{...Y(u),n:n.n},m)}catch(g){if(g instanceof Error&&"code"in g&&["version_outdated","version_mismatch"].includes(String(g.code))){let d=Y(u),c=typeof d?.code=="string"?d.code.toUpperCase().replace(/[\s-]/g,""):void 0,y=typeof d?.roomId=="string"?d.roomId:void 0;n.onVersionError?.(g,g.code==="version_mismatch"?{code:c,roomId:y,watch:s==="/rooms/watch"}:void 0)}throw g}};async function i(s,a,u=!1){let m=await t(s,"POST",a,u);if(!st(m))throw f("internal_error","The room service returned an invalid response.");return m}async function r(s){let a=await t("/match","POST",{mode:s.mode,key:s.key});if(!ti(a))throw f("internal_error","The matchmaking service returned an invalid response.");return a}async function o(s,a=!1){let u=await t("/rooms/watch","POST",s,a);if(!ei(u))throw f("internal_error","The room service returned an invalid response.");return u}return{create:s=>i("/rooms",{mode:s}),joinCode:s=>i("/rooms/join",{code:s}),joinRoom:s=>i("/rooms/join",{roomId:s},!0),watchCode:s=>o({code:s}),watchRoom:s=>o({roomId:s},!0),match:r,flush:s=>t(`/rooms/${encodeURIComponent(s)}/flush`,"POST")}}var ye=class{constructor(e,t,i,r,o,s,a=!1){this.roomId=e;this.codice=t;this.dipendenze=r;this.api=o;this.segnalaStanza=s;this.spettatore=a;this.meta={host:null,mode:null,countdownAt:null,configuration:null,connection:"connecting",closedCode:null};this.metaListeners=new Set;this.connectionListeners=new Set;this.scoreListeners=new Set;this.scores=[];this.errorListeners=new Set;this.roleId=0;this.roleRequests=new Map;this.statoPubblico=null;this.statoSincronizzato=null;this.tickCorrente=0;this.tickRateCorrente=0;this.latenzaCorrente=null;this.ultimoInput=null;this.inputInviato=null;this.timerInput=null;this.ultimoInvioGioco=-1/0;this.inviiGioco=[];this.seedCorrente=0;this.statusCorrente="lobby";this.giocatoriCorrenti=[];this.youCorrente="";this.hostCorrente=null;this.resultCorrente=null;this.delaySpettatore=0;this.socket=null;this.seq=0;this.scartoOrario=0;this.timerPing=null;this.intervalloPing=null;this.timerRiconnessione=null;this.timerFlush=null;this.flushInCorso=!1;this.flushRichiesto=!1;this.ritardoIndice=0;this.tempoRiconnessione=0;this.resyncRichiesto=!1;this.terminata=!1;this.lasciata=!1;this.prontaRisolta=!1;this.welcomeRicevuto=!1;this.rosterRicevuto=!1;this.timerRoster=null;this.risolviPronta=()=>{};this.rifiutaPronta=()=>{};this.ascoltatoriStato=new Set;this.ascoltatoriGiocatori=new Set;this.ascoltatoriStatus=new Set;this.ascoltatoriMessaggi=new Set;this.promessaPronta=new Promise((u,m)=>{this.risolviPronta=u,this.rifiutaPronta=m}),this.voice=new ve({invia:u=>this.invia(u),connessa:()=>this.socket?.readyState===ee&&this.welcomeRicevuto&&!this.terminata&&!this.lasciata,you:()=>this.youCorrente,giocatori:()=>this.copiaGiocatori(),rosterPronto:()=>{this.rosterRicevuto=!0,this.risolviProntaSePossibile()}},r,r.voce),a&&(this.rosterRicevuto=!0),this.apri(i)}get mode(){return this.meta.mode}get countdownAt(){return this.meta.countdownAt}get connection(){return this.meta.connection}get metadata(){return structuredClone(this.meta)}get queuedScores(){return structuredClone(this.scores)}onMetadata(e){return this.metaListeners.add(e),()=>this.metaListeners.delete(e)}onConnection(e){return this.connectionListeners.add(e),()=>this.connectionListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onScoreQueued(e){return this.scoreListeners.add(e),()=>this.scoreListeners.delete(e)}metadataChanged(e){let t=this.meta.connection;this.meta={...this.meta,...e},this.notifica(this.metaListeners,this.metadata),t!==this.meta.connection&&this.notifica(this.connectionListeners,this.meta.connection)}initialMetadata(e){this.metadataChanged({host:e.host,mode:e.mode,countdownAt:e.countdownAt??null,rematch:e.rematch??null,configuration:e.configuration??null,connection:"connected",closedCode:null})}requestRole(e){if(typeof e!="string"||e.length<1||e.length>32)return Promise.reject(f("invalid_role","The role is not valid."));if(this.connection!=="connected"||this.status!=="playing"||!this.meta.configuration?.requestRole)return Promise.reject(f("role_change_unavailable","Roles cannot be requested right now."));if(this.roleRequests.size>=8)return Promise.reject(f("rate_limited","Too many role requests."));let t=++this.roleId;return new Promise((i,r)=>{let o=this.dipendenze.setTimeout(()=>{this.roleRequests.delete(t),r(f("timeout","The role request timed out."))},5e3);this.roleRequests.set(t,{resolve:i,reject:r,timer:o});try{this.invia({t:"request-role",r:t,role:e})}catch(s){this.dipendenze.clearTimeout(o),this.roleRequests.delete(t),r(s)}})}clearRoleRequests(){for(let e of this.roleRequests.values())this.dipendenze.clearTimeout(e.timer),e.reject(f("offline","The room connection ended."));this.roleRequests.clear()}disconnect(){if(this.lasciata)return;this.lasciata=!0;let e=this.socket;this.socket=null,this.voice.termina(),this.fermaInput(),this.fermaPing(),this.fermaRiconnessione(),this.clearRoleRequests(),this.timerRoster!==null&&this.dipendenze.clearTimeout(this.timerRoster),e?.close(1e3),this.segnalaStanza(null),this.metadataChanged({connection:"disconnected",closedCode:null}),this.prontaRisolta||(this.prontaRisolta=!0,this.rifiutaPronta(f("cancelled","The room was disconnected.")))}get state(){return this.statoPubblico}get tick(){return this.tickCorrente}get tickRate(){return this.tickRateCorrente}get latency(){return this.latenzaCorrente}get seed(){return this.seedCorrente}get status(){return this.statusCorrente}get players(){return this.copiaGiocatori()}get you(){return this.youCorrente}get host(){return this.hostCorrente}get code(){return this.codice}get result(){return this.resultCorrente}get delayMs(){return this.delaySpettatore}pronta(){return this.promessaPronta}invite(){return{code:this.codice,url:new URL(`/r/${this.codice}`,this.dipendenze.appOrigin).href}}onState(e){return this.ascoltatoriStato.add(e),()=>{this.ascoltatoriStato.delete(e)}}onPlayers(e){return this.ascoltatoriGiocatori.add(e),()=>{this.ascoltatoriGiocatori.delete(e)}}onStatus(e){return this.ascoltatoriStatus.add(e),()=>{this.ascoltatoriStatus.delete(e)}}onMessage(e){return this.ascoltatoriMessaggi.add(e),()=>{this.ascoltatoriMessaggi.delete(e)}}send(e){if(this.statusCorrente==="finished")return;let t=this.seq+1;this.invia({t:"msg",seq:t,m:e}),this.seq=t,this.ultimoInvioGioco=this.dipendenze.ora(),this.inviiGioco=[...this.inviiGioco.slice(-19),this.ultimoInvioGioco]}input(e){if(!(this.terminata||this.lasciata||this.statusCorrente==="finished")){try{let t=JSON.stringify(e);if(t===void 0)throw new TypeError;this.ultimoInput=t}catch{throw f("invalid_request","Room input must be valid JSON.")}this.programmaInput()}}pulisciInput(){this.fermaInput(),this.ultimoInput=this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[]}fermaInput(){this.timerInput!==null&&this.dipendenze.clearTimeout(this.timerInput),this.timerInput=null}programmaInput(){if(this.timerInput!==null||this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==ee||this.terminata||this.lasciata)return;let e=this.dipendenze.ora(),i=1e3/(this.tickRateCorrente>0?Math.min(20,this.tickRateCorrente):20);this.inviiGioco=this.inviiGioco.filter(s=>e-s<1e3);let r=this.inviiGioco.length>=20?this.inviiGioco[0]+1e3:e,o=Number.isFinite(this.ultimoInvioGioco)?this.ultimoInvioGioco+i:e+i;this.timerInput=this.dipendenze.setTimeout(()=>{if(this.timerInput=null,this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==ee||this.terminata||this.lasciata)return;let s=this.dipendenze.ora();if(s<this.ultimoInvioGioco+i||this.inviiGioco.filter(u=>s-u<1e3).length>=20){this.programmaInput();return}let a=this.ultimoInput;try{this.send(JSON.parse(a)),this.inputInviato=a}catch{}},Math.max(0,Math.ceil(Math.max(o,r)-e)))}aggiornaTickRate(e){e===void 0||!Number.isInteger(e)||e<0||e>60||e===this.tickRateCorrente||(this.tickRateCorrente=e,this.fermaInput(),this.programmaInput())}ready(e){this.invia({t:"ready",ready:e})}setRole(e){this.invia({t:"role",role:e})}setTeam(e){this.invia({t:"team",team:e})}start(){this.invia({t:"start"})}restart(){if(this.statusCorrente!=="finished")throw f("rematch_unavailable","This room is not waiting for a rematch.");this.invia({t:"restart"})}leave(){if(!this.lasciata){if(this.spettatore||this.voice.leave(),this.lasciata=!0,this.segnalaStanza(null),this.socket?.readyState===ee){let e=this.socket;this.invia({t:"leave"}),this.spettatore&&e.close(1e3)}this.termina(1e3)}}serverTime(){return this.dipendenze.ora()+this.scartoOrario}copiaGiocatori(){return this.giocatoriCorrenti.map(e=>({...e}))}notifica(e,...t){for(let i of e)try{i(...t)}catch{}}invia(e){if(this.socket?.readyState!==ee)throw f("offline","The room is reconnecting.");let t;try{t=JSON.stringify(e)}catch{throw f("invalid_request","Room messages must be valid JSON.")}this.socket.send(t)}apri(e){let t;try{t=this.dipendenze.apriSocket(e)}catch{this.programmaRiconnessione();return}this.socket=t,t.addEventListener("open",()=>{this.socket===t&&this.avviaPing()}),t.addEventListener("message",i=>{this.socket===t&&typeof i.data=="string"&&this.ricevi(i.data)}),t.addEventListener("close",i=>{this.socket===t&&this.chiuso(i.code,i.reason)})}avviaPing(){if(this.socket?.readyState!==ee||this.terminata||this.lasciata)return;let e=this.statusCorrente==="playing"?Wt:Zt;this.timerPing!==null&&this.intervalloPing===e||(this.timerPing!==null&&this.dipendenze.clearInterval(this.timerPing),this.intervalloPing=e,this.timerPing=this.dipendenze.setInterval(()=>{if(this.socket?.readyState===ee)try{this.invia({t:"ping",c:this.dipendenze.ora()})}catch{}},e))}fermaPing(){this.timerPing!==null&&(this.dipendenze.clearInterval(this.timerPing),this.timerPing=null,this.intervalloPing=null)}ricevi(e){let t;try{let i=JSON.parse(e),r=Y(i);if(r===null||typeof r.t!="string")return;t=r}catch{return}try{if(t.t==="watching")this.riceviWatching(t);else if(t.t==="welcome")this.riceviWelcome(t);else if(t.t==="players")this.riceviGiocatori(t.players,t.host);else if(t.t==="status")this.riceviStatus(t);else if(t.t==="state")this.riceviDiff(t);else if(t.t==="snapshot")this.riceviSnapshot(t);else if(t.t==="msg")this.notifica(this.ascoltatoriMessaggi,Q(t.m));else if(t.t==="pong")this.riceviPong(t);else if(t.t==="error")this.notifica(this.errorListeners,{code:t.code,message:t.message});else if(t.t==="flush")this.richiediFlush();else if(t.t==="score-queued"&&!this.spettatore)this.scores.push(structuredClone(t.score)),this.scores=this.scores.slice(-32),this.notifica(this.scoreListeners,structuredClone(t.score));else if(t.t==="role-result"){let i=this.roleRequests.get(t.r);i&&(this.dipendenze.clearTimeout(i.timer),this.roleRequests.delete(t.r),t.ok?i.resolve():i.reject(f(t.code??"role_change_refused","The role change was not accepted.")))}else t.t==="voice"&&this.voice.ricevi(t)}catch{(t.t==="state"||t.t==="snapshot")&&this.chiediResync()}}riceviWatching(e){let t=e.room;!this.spettatore||t.id!==this.roomId||(this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.hostCorrente=t.host,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=Q(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.delaySpettatore=e.delayMs,this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviWelcome(e){let t=e.room;t.id===this.roomId&&(this.youCorrente=e.you,this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.hostCorrente=t.host,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=Q(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,!this.rosterRicevuto&&this.timerRoster===null&&(this.timerRoster=this.dipendenze.setTimeout(()=>{this.timerRoster=null,this.rosterRicevuto=!0,this.risolviProntaSePossibile()},Yt)),this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati(),this.voice.socketRiconnesso(),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviGiocatori(e,t){this.giocatoriCorrenti=e.map(i=>({...i})),t!==void 0?this.hostCorrente=t:this.giocatoriCorrenti.some(i=>i.id===this.hostCorrente&&i.connected)||(this.hostCorrente=this.giocatoriCorrenti.find(i=>i.connected)?.id??null),this.metadataChanged({host:this.hostCorrente}),this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati()}riceviStatus(e){this.statusCorrente=e.status,e.host!==void 0&&(this.hostCorrente=e.host),this.resultCorrente=Q(e.result),e.status==="finished"&&(this.pulisciInput(),this.clearRoleRequests()),e.status==="ended"?(this.terminata=!0,this.clearRoleRequests(),this.segnalaStanza(null),this.spettatore||this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),this.fermaInput(),this.ultimoInput=null):this.avviaPing(),this.metadataChanged({rematch:e.rematch??null,host:this.hostCorrente,countdownAt:e.countdownAt??(e.status==="countdown"?e.at:null),...e.status==="ended"?{connection:"ended",closedCode:4004}:{}}),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,e.at)}riceviDiff(e){if(this.aggiornaTickRate(e.tickRate),e.base!==this.tickCorrente){this.chiediResync();return}let t=ii(this.statoSincronizzato,e.patch);if(!t.ok){this.chiediResync();return}this.resyncRichiesto=!1,this.aggiornaStato(t.state,e.tick,e.serverTime)}riceviSnapshot(e){e.tick<this.tickCorrente||(this.aggiornaTickRate(e.tickRate),this.resyncRichiesto=!1,this.aggiornaStato(e.state,e.tick,e.serverTime))}aggiornaStato(e,t,i){this.statoSincronizzato=Q(e),this.statoPubblico=Q(e),this.tickCorrente=t,this.notifica(this.ascoltatoriStato,this.statoPubblico,t,i)}chiediResync(){if(!(this.resyncRichiesto||this.socket?.readyState!==ee)){this.resyncRichiesto=!0;try{this.invia({t:"resync"})}catch{this.resyncRichiesto=!1}}}riceviPong(e){let t=this.dipendenze.ora();if(!Number.isFinite(e.c)||!Number.isFinite(e.s)||e.c>t)return;let i=t-e.c;this.latenzaCorrente=this.latenzaCorrente===null?i:this.latenzaCorrente*.8+i*.2,this.scartoOrario=e.s-(e.c+t)/2}chiuso(e,t){if(this.socket=null,this.welcomeRicevuto=!1,this.latenzaCorrente=null,this.fermaInput(),this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[],this.fermaPing(),!(this.lasciata||this.terminata)){if(Xt.has(e)){let i=e===4009&&t==="message_too_large"?"message_too_large":void 0;i&&this.notifica(this.errorListeners,{code:i,message:"The room message is too large."}),this.termina(e,i);return}this.clearRoleRequests(),this.spettatore||this.voice.socketDisconnesso(),this.programmaRiconnessione()}}programmaRiconnessione(){if(this.terminata||this.lasciata||this.timerRiconnessione!==null)return;this.metadataChanged({connection:"reconnecting"});let e=Math.min(this.ritardoIndice,rt.length-1),t=rt[e];if(this.tempoRiconnessione+t>Kt){this.termina("timeout");return}this.ritardoIndice++,this.tempoRiconnessione+=t,this.timerRiconnessione=this.dipendenze.setTimeout(()=>{this.timerRiconnessione=null,this.riconnetti()},t)}async riconnetti(){if(!(this.terminata||this.lasciata))try{let e=this.spettatore?await this.api.watchRoom(this.roomId):await this.api.joinRoom(this.roomId);if(this.terminata||this.lasciata)return;let t=this.codice!==e.code;this.codice=e.code,t&&this.prontaRisolta&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.apri(e.url)}catch(e){e instanceof Error&&"code"in e&&["version_mismatch","version_outdated","room_not_found"].includes(String(e.code))?(this.notifica(this.errorListeners,{code:String(e.code),message:e.message}),this.termina(4004,String(e.code))):this.programmaRiconnessione()}}fermaRiconnessione(){this.timerRiconnessione!==null&&(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}termina(e,t){this.clearRoleRequests(),this.metadataChanged({connection:e===1e3?"disconnected":e===4006?"replaced":"closed",closedCode:typeof e=="number"?e:null});let i={closed:e},r=this.statusCorrente!=="ended"||JSON.stringify(this.resultCorrente)!==JSON.stringify(i);if(this.terminata=!0,this.fermaInput(),this.ultimoInput=null,this.segnalaStanza(null),this.statusCorrente="ended",this.resultCorrente=i,this.spettatore||this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),r&&this.notifica(this.ascoltatoriStatus,"ended",i,this.serverTime()),!this.prontaRisolta){this.prontaRisolta=!0;let s=t??(typeof e=="number"?{4003:"kicked",4004:"room_ended",4005:"version_closed",4006:"replaced",4008:"rate_limited",4009:"invalid_request"}[e]??"offline":"offline");this.rifiutaPronta(f(s,"The room connection ended."))}}risolviProntaSePossibile(){this.prontaRisolta||!this.welcomeRicevuto||!this.rosterRicevuto||(this.timerRoster!==null&&(this.dipendenze.clearTimeout(this.timerRoster),this.timerRoster=null),this.prontaRisolta=!0,!this.spettatore&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.risolviPronta())}richiediFlush(){this.flushRichiesto=!0,!(this.flushInCorso||this.timerFlush!==null)&&(this.timerFlush=this.dipendenze.setTimeout(()=>{this.timerFlush=null,this.eseguiFlush()},Qt))}async eseguiFlush(){if(!(this.flushInCorso||!this.flushRichiesto)){this.flushInCorso=!0,this.flushRichiesto=!1;try{await this.api.flush(this.roomId)}catch{}finally{this.flushInCorso=!1,this.flushRichiesto&&this.richiediFlush()}}}};function be(n=null){return{invited:n,reload(){typeof window<"u"&&window.location.reload()},onError(){return()=>{}},async create(){throw j()},async join(){throw j()},async watch(){throw j()},async match(){throw j()}}}function at(n,e){let t,i=new Set,r=ni({...n,onVersionError(d,c){t=c;for(let y of i)try{y(d)}catch{}}}),o=!1,s=null,a=d=>{let c=d?.code??null;o&&c===s||(o=!0,s=c,n.segnalaStanza?.(d))},u=async d=>{let c=new ye(d.roomId,d.code,d.url,n,r,a);return await c.pronta(),c},m=async d=>{let c=new ye(d.roomId,d.code,d.url,n,r,()=>{},!0);return await c.pronta(),{get mode(){return c.mode},get countdownAt(){return c.countdownAt},get connection(){return c.connection},get metadata(){return c.metadata},onMetadata:y=>c.onMetadata(y),onConnection:y=>c.onConnection(y),disconnect:()=>c.disconnect(),get state(){return c.state},get tick(){return c.tick},get tickRate(){return c.tickRate},get latency(){return c.latency},get seed(){return c.seed},get status(){return c.status},get players(){return c.players},get host(){return c.host},get code(){return c.code},get result(){return c.result},get delayMs(){return c.delayMs},onState:y=>c.onState(y),onPlayers:y=>c.onPlayers(y),onStatus:y=>c.onStatus(y),onMessage:y=>c.onMessage(y),leave:()=>{c.leave()},serverTime:()=>c.serverTime()}},g=(d,c)=>new Promise((y,k)=>{let C,D=!1,E=()=>{C.removeEventListener("message",I),C.removeEventListener("close",U),C.removeEventListener("error",G),c.signal?.removeEventListener("abort",B)},$=()=>{try{C.close(1e3)}catch{}},V=(F,P)=>{D||(D=!0,E(),P&&$(),k(F))};function B(){V(f("cancelled","The matchmaking search was cancelled."),!0)}function U(){V(j(),!1)}function G(){V(j(),!0)}function I(F){let P=null;try{P=typeof F.data=="string"?Y(JSON.parse(F.data)):null}catch{}if(P===null||typeof P.t!="string"){V(f("internal_error","The matchmaking service sent an invalid message."),!0);return}if(P.t==="waiting"){if(!Number.isInteger(P.players)||!Number.isInteger(P.min)||!Number.isInteger(P.max)){V(f("internal_error","The matchmaking service sent an invalid message."),!0);return}try{c.onWaiting?.({players:P.players,min:P.min,max:P.max})}catch{}return}if(P.t==="matched"){if(!st(P)){V(f("internal_error","The matchmaking service sent an invalid message."),!0);return}D=!0,E(),$(),y(P);return}if(P.t==="no_match"){V(f("no_match","No match was found before the timeout."),!0);return}if(P.t==="error"){V(f(typeof P.code=="string"?P.code:"internal_error",typeof P.message=="string"?P.message:"The matchmaking service could not complete the search."),!0);return}P.t!=="pong"&&V(f("internal_error","The matchmaking service sent an invalid message."),!0)}try{C=n.apriSocket(d)}catch{k(j());return}C.addEventListener("message",I),C.addEventListener("close",U),C.addEventListener("error",G),c.signal?.addEventListener("abort",B,{once:!0}),c.signal?.aborted===!0&&B()});return{invited:e,reload(){n.reload?.(t)},onError(d){return i.add(d),()=>{i.delete(d)}},async create(d){return u(await r.create(d.mode))},async join(d){let c=d??e;if(c==null||c.length===0)throw f("invalid_request","A room invitation code is required.");return u(await r.joinCode(c))},async watch(d){if(typeof d!="string"||d.length===0)throw f("invalid_request","A room invitation code is required.");return m(await r.watchCode(d))},async match(d){let c=()=>d.signal?.aborted===!0;if(c())throw f("cancelled","The matchmaking search was cancelled.");let y=await r.match(d);if(c())throw f("cancelled","The matchmaking search was cancelled.");return u(await g(y.url,d))}}}var oe="caisual:save:",oi=/^[a-z0-9][a-z0-9_-]{0,31}$/;function Me(n){if(!oi.test(n))throw f("invalid_request","Save keys must use lowercase letters, numbers, underscores, or hyphens.")}function lt(n){if(n===null)return null;try{return JSON.parse(n)}catch{return null}}function ct(n){let e=[];for(let t=0;t<n.length;t++){let i=n.key(t);i?.startsWith(oe)&&e.push(i.slice(oe.length))}return e}function ri(n,e){let t=()=>{if(n===null)throw j();return n};return{async set(i,r){Me(i);let o=t(),s=JSON.stringify({value:r}),a=new TextEncoder().encode(s).byteLength;if(a>262144)throw f("payload_too_large","The save is larger than 262144 bytes.");if(o.getItem(oe+i)===null&&ct(o).length>=32)throw f("save_limit","A game can store at most 32 save keys.");let u={value:r,bytes:a,updatedAt:e()};return o.setItem(oe+i,JSON.stringify(u)),{key:i,bytes:a,updatedAt:u.updatedAt}},async get(i){return Me(i),lt(t().getItem(oe+i))?.value??null},async remove(i){Me(i),t().removeItem(oe+i)},async list(){let i=t();return ct(i).flatMap(r=>{let o=lt(i.getItem(oe+r));return o===null?[]:[{key:r,bytes:o.bytes,updatedAt:o.updatedAt}]}).sort((r,o)=>r.key.localeCompare(o.key))}}}async function Ie(n,e=null){let t=n.ora(),i=Ce(t),r=await Pe(n.hostname,i,n.subtle);return{connected:!1,player:{id:"local",name:"Guest",guest:!0},daily:he({day:i,seed:r,expiresAt:ae(t)},n.ora,async()=>{let o=n.ora(),s=Ce(o);return{day:s,seed:await Pe(n.hostname,s,n.subtle),expiresAt:ae(o)}}),time:{now:n.ora},save:ri(n.archivio,n.ora),board:{async submit(){return{accepted:!1,reason:"offline",verified:!1}},async top(o,s={}){if(s.day!==void 0&&(!le(s.day)||s.daily===!1))throw f("invalid_request","day must be a real UTC date and cannot be combined with daily: false.");return{day:s.day??(s.daily?i:null),entries:[],me:null}}},room:be(e)}}function si(n){let e=n?.querySelector('meta[name="caisual-app"]')?.getAttribute("content");if(e==null)return null;try{let t=new URL(e);return t.origin===e&&(t.protocol==="https:"||t.protocol==="http:")?e:null}catch{return null}}function ai(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function li(){return{finestra:typeof window>"u"?null:window,documento:typeof document>"u"?null:document,fetcher:(n,e)=>globalThis.fetch(n,e),archivio:ai(),language:typeof navigator>"u"?"en":navigator.language,pathname:typeof location>"u"?"/":location.pathname,hostname:typeof location>"u"?"":location.hostname,subtle:globalThis.crypto.subtle,ora:Date.now,sonda:()=>$e()}}async function ci(n){let e=si(n.documento),t=n.finestra===null||n.finestra.parent===n.finestra;if(e===null||t)return ut(n);let i=await tt(n.finestra,e,n.timeoutHandshake);if(i===null)return ut(n);let r=Ae(i.ticket,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"portal"),o=Ye(e,n.fetcher,r),s=n.ora(),a;try{a=await o.me()}catch{let c=await Ie(n,i.invite);return ze(c,i,n)}let u=n.ora(),m=a.serverTime-(s+u)/2,g=i.live===null?be(i.invite):at({appOrigin:e,n:i.n,reload:c=>i.porta.postMessage({type:"caisual:reload",target:c}),liveOrigin:i.live,fetcher:n.fetcher,biglietto:Ae(null,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"live"),apriSocket(c){if(n.apriSocket!==void 0)return n.apriSocket(c);if(typeof WebSocket>"u")throw j();return new WebSocket(c)},ora:n.ora,setTimeout:(c,y)=>globalThis.setTimeout(c,y),clearTimeout:c=>globalThis.clearTimeout(c),setInterval:(c,y)=>globalThis.setInterval(c,y),clearInterval:c=>globalThis.clearInterval(c),voce:n.voce,segnalaStanza(c){try{i.porta.postMessage({type:"caisual:room",room:c})}catch{}}},i.invite),d={connected:!0,player:a.player,daily:he({day:a.day,seed:a.seed,expiresAt:a.expiresAt??ae(a.serverTime)},()=>n.ora()+m,async()=>{let c=await o.me();return{day:c.day,seed:c.seed,expiresAt:c.expiresAt??ae(c.serverTime)}}),time:{now:()=>n.ora()+m},save:{set:(c,y)=>o.saveSet(c,y),get:c=>o.saveGet(c),remove:c=>o.saveRemove(c),list:()=>o.saveList()},board:{async submit(c,y,k={}){try{return await o.boardSubmit(c,y,k.daily===!0)}catch(C){if(typeof C=="object"&&C!==null&&"code"in C&&C.code==="offline")return{accepted:!1,reason:"offline",verified:!1};throw C}},top:(c,y={})=>o.boardTop(c,y)},room:g};return ze(d,i,n)}function ze(n,e,t){let i=We(n,e?.overlay?.configuration??null,n.connected&&e?.live!=null);if(e?.overlay){let a=Qe(e.porta,e.overlay,i);i.session.capabilities.overlay&&typeof window<"u"&&t?.finestra===window&&window.addEventListener("pagehide",a,{once:!0})}let r=e?.languagePreferences?.length?e.languagePreferences:[e?.language??t?.language??"en"],o=Ee(r,e?.gameLanguages??(e?.overlay?we(e.overlay.configuration.manifest):void 0)),s=Be(e?.uiLanguage??e?.language??t?.language);return{...n,player:{...n.player,language:o,uiLanguage:s},text:Ue(t?.fetcher??globalThis.fetch,o,t?.pathname),room:i.rooms,session:i.session,overlay:i.overlay}}async function ut(n){return ze(await Ie(n),void 0,n)}function dt(){return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:!1,gpu:"none",memoryMb:null,cores:null,mobile:!1,tier:"low"}}async function ui(n){let e;try{return await Promise.race([Promise.resolve().then(n).catch(()=>dt()),new Promise(t=>{e=globalThis.setTimeout(()=>t(dt()),1500)})])}finally{e!==void 0&&globalThis.clearTimeout(e)}}function mt(n=li()){let e=null;return{connect(){return e??(e=Promise.all([ci(n),ui(n.sonda)]).then(([t,i])=>({...t,device:i}))),e}}}var pt=mt();globalThis.caisual=pt;var to=pt;export{pt as caisual,to as default};
|
|
1
|
+
// Caisual game kit v0.20.0
|
|
2
|
+
var kt=["www","api","app","play","live","multi","cdn","assets","static","mail","mx","ns1","ns2","autodiscover","_dmarc","admin","login","account","auth","pay","secure","support","help","blog","status","dev","staging","test","caisual","shipz"],xt=new Set(kt),Mt=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Ct=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function ge(n){return n.length>=3&&n.length<=32&&Mt.test(n)||Ct.test(n)}function Ne(n){return xt.has(n)}function G(n){if(typeof n!="string"||n.length>128)return null;try{return Intl.getCanonicalLocales(n)[0]??null}catch{return null}}function Ce(n){return n.languages?.length?[...n.languages]:[n.language??"en"]}function Pt(n,e="en"){let t=[],i=G(n);for(;i;){t.push(i);let r=i.split("-");r.pop(),r.at(-1)?.length===1&&r.pop(),i=r.join("-")}return t.push(G(e)??e),[...new Set(t)]}function je(n,e=[]){let t=e.map(G).filter(r=>r!==null),i=n.map(G).filter(r=>r!==null);if(!t.length)return i[0]??"en";for(let r of i)for(let s of Pt(r,r))if(t.includes(s))return s;return t[0]}function Ge(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.values(n).every(e=>typeof e=="string")}function Ue(n,e){let t=e===null?void 0:n.modes.find(i=>i.id===e);if(e!==null&&t===void 0)throw new Error("The selected game mode does not exist.");return{players:{...t?.players??n.players},lobby:t?.lobby??n.lobby}}function ve(n,e){return e!==null&&n.modes.some(t=>t.id===e&&t.execution==="local")}var P=24;var Tt=3e3,Je=32,At=new Set(["overlay","manifest","id","name","description","cover","card","icon","screenshots","tags","languages","language","platform","orientation","input","visibility","network","isolated","requires","players","lobby","persistent","replays","spectators","boards","roles","teams","voice","modes"]),It=new Set(["keyboard","mouse","touch","gamepad"]),Ot=new Set(["desktop","mobile","both"]),Et=new Set(["landscape","portrait"]),_t=new Set(["public","unlisted"]),zt=new Set(["none","room","team","proximity"]),Vt=new Set(["light","medium","heavy"]),Lt=/^[a-z0-9-]+$/,qe=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,$t=/^[a-z0-9][a-z0-9-]{0,31}$/,Dt=/^[a-z0-9][a-z0-9_-]{0,31}$/;function J(n){return typeof n!="object"||n===null||Array.isArray(n)?null:n}function Be(n){if(n===""||n.startsWith("/")||n.includes("\\")||n.includes("\0")||n.includes("?")||n.includes("#"))return!1;let e=n.split("/");if(e.some(t=>t===""||t==="."||t===".."))return!1;try{return!e.map(i=>decodeURIComponent(i)).some(i=>i===""||i==="."||i===".."||i.includes("/"))}catch{return!1}}function Nt(n){return n.length===0||n.length>253||n.includes("://")||/[/:?#@]/.test(n)?!1:n.split(".").every(t=>t.length>=1&&t.length<=63&&/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(t))}function V(n,e,t){return typeof n=="number"&&Number.isInteger(n)&&n>=e&&n<=t}function Pe(n,e,t,i){let r=n[e];return r===void 0?t:typeof r!="string"?(i.push(`${e}: must be a string.`),t):r}function ye(n,e,t,i,r){if(n[e]===void 0)return;let s=(h,d)=>{if(typeof h!="string"||h.trim().length===0||h.trim().length>t||/[\r\n\u0000-\u001f]/.test(h)){r.push(`${d}: must contain 1-${t} characters on one line.`);return}return h.trim()},o=n[e],a=i?`${i}.${e}`:e;if(typeof o=="string")return s(o,a);let c=J(o);if(!c||Object.keys(c).length===0){r.push(`${a}: must be a string or a non-empty language-to-text object.`);return}let m={};for(let[h,d]of Object.entries(c)){let u=G(h);if(!u){r.push(`${a}.${h}: must be a BCP 47 language tag.`);continue}Object.hasOwn(m,u)&&r.push(`${a}.${h}: duplicate language.`);let v=s(d,`${a}.${h}`);v!==void 0&&(m[u]=v)}return m}function Te(n){let e=[],t=J(n);if(t===null)return{ok:!1,errori:["manifest: must be a JSON object."]};for(let g of Object.keys(t))At.has(g)||e.push(`${g}: unknown field.`);t.manifest===void 0?e.push("manifest: is required and must be 1."):t.manifest!==1&&e.push("manifest: must be exactly 1.");let i=Pe(t,"id","",e);t.id===void 0?e.push("id: is required."):typeof t.id=="string"&&(ge(i)?Ne(i)&&e.push("id: this slug is reserved."):e.push("id: must be 3-32 lowercase ASCII letters or digits with internal hyphens; historical UUID v4 slugs may be 36 characters."));let r=Pe(t,"name","",e);t.name===void 0?e.push("name: is required."):typeof t.name=="string"&&(r.trim()===""||r.length>60)&&e.push("name: must contain 1-60 characters.");let s=t.description===""?"":ye(t,"description",500,"",e)??"",o={cover:"",card:"",icon:""},a=new Set;for(let g of["cover","card","icon"]){let f=t[g];if(f==null)e.push(`${g}: is required.`);else if(typeof f!="string"||!Be(f))e.push(`${g}: must be a relative file path inside client/ without query, fragment, or parent segments.`);else{/\.(png|jpe?g|webp)$/i.test(f)||e.push(`${g}: must be a PNG, JPEG or WebP file.`);let L=decodeURIComponent(f);a.has(L)&&e.push(`${g}: each image must use a different file; cover, card and icon cannot share a path.`),a.add(L),o[g]=f}}let{cover:c,card:m,icon:h}=o,d=[];if(t.screenshots!==void 0)if(!Array.isArray(t.screenshots))e.push("screenshots: must be an array of relative file paths.");else{t.screenshots.length>8&&e.push("screenshots: must contain at most 8 paths.");for(let[g,f]of t.screenshots.entries())typeof f!="string"||!Be(f)?e.push(`screenshots[${g}]: must be a relative file path without query, fragment, or parent segments.`):d.push(f)}let u=[];if(t.tags!==void 0)if(!Array.isArray(t.tags))e.push("tags: must be an array.");else{t.tags.length>10&&e.push("tags: must contain at most 10 tags.");for(let[g,f]of t.tags.entries())typeof f!="string"||f.length>24||!Lt.test(f)?e.push(`tags[${g}]: must be 1-24 lowercase letters, digits, or hyphens.`):u.push(f)}let v=Pe(t,"language","en",e);/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(v)||e.push("language: must be a BCP 47 language tag such as en, it, or pt-BR.");let x=[];if(!Array.isArray(t.languages)||t.languages.length===0)e.push("languages: must be a non-empty array of BCP 47 language tags.");else for(let[g,f]of t.languages.entries()){let L=G(f);L?x.includes(L)?e.push(`languages[${g}]: duplicate language ${L}.`):x.push(L):e.push(`languages[${g}]: must be a BCP 47 language tag.`)}x.includes("en")||e.push("languages: English is always required alongside the game's own languages.");let w=x[0]??v;if(typeof s=="object")for(let g of Object.keys(s))x.includes(g)||e.push(`description.${g}: language must be declared in languages.`);t.language!==void 0&&t.languages!==void 0&&v.toLowerCase()!==w.toLowerCase()&&e.push("language: must match the first entry in languages when both are present.");let N="both";t.platform===void 0?e.push("platform: is required."):typeof t.platform!="string"||!Ot.has(t.platform)?e.push("platform: must be desktop, mobile, or both."):N=t.platform;let _="landscape";t.orientation!==void 0&&(typeof t.orientation!="string"||!Et.has(t.orientation)?e.push("orientation: must be landscape or portrait."):_=t.orientation);let j=[];if(t.input!==void 0)if(!Array.isArray(t.input))e.push("input: must be an array.");else for(let[g,f]of t.input.entries())typeof f!="string"||!It.has(f)?e.push(`input[${g}]: must be keyboard, mouse, touch, or gamepad.`):j.includes(f)?e.push(`input[${g}]: duplicate value ${f}.`):j.push(f);let z="public";t.visibility!==void 0&&(typeof t.visibility!="string"||!_t.has(t.visibility)?e.push("visibility: must be public or unlisted."):z=t.visibility);let B=[];if(t.network!==void 0)if(!Array.isArray(t.network))e.push("network: must be an array of host names.");else for(let[g,f]of t.network.entries())typeof f!="string"||!Nt(f)?e.push(`network[${g}]: must be a host name without scheme, port, path, query, or fragment.`):B.includes(f)?e.push(`network[${g}]: duplicate host ${f}.`):B.push(f);t.isolated!==void 0&&typeof t.isolated!="boolean"&&e.push("isolated: must be a boolean.");let U={webgl2:!1,webgpu:!1,wasm:!1,threads:!1,memoryMb:null,performance:"light"};if(t.requires!==void 0){let g=J(t.requires);if(g===null)e.push("requires: must be an object.");else{for(let f of Object.keys(g))["webgl2","webgpu","wasm","threads","memoryMb","performance"].includes(f)||e.push(`requires.${f}: unknown field.`);for(let f of["webgl2","webgpu","wasm","threads"])g[f]!==void 0&&(typeof g[f]!="boolean"?e.push(`requires.${f}: must be a boolean.`):U[f]=g[f]);g.memoryMb!==void 0&&(g.memoryMb!==null&&(!V(g.memoryMb,512,32768)||g.memoryMb%256!==0)?e.push("requires.memoryMb: must be an integer from 512 to 32768 in steps of 256, or null."):U.memoryMb=g.memoryMb),g.performance!==void 0&&(typeof g.performance!="string"||!Vt.has(g.performance)?e.push("requires.performance: must be light, medium, or heavy."):U.performance=g.performance)}}let F={min:1,max:1};if(t.players!==void 0){let g=J(t.players);if(g===null)e.push("players: must be an object with min and max.");else{for(let f of Object.keys(g))f!=="min"&&f!=="max"&&e.push(`players.${f}: unknown field.`);V(g.min,1,P)||e.push(`players.min: must be an integer from 1 to ${P}.`),V(g.max,1,P)||e.push(`players.max: must be an integer from 1 to ${P} in manifest version 1.`),V(g.min,1,P)&&V(g.max,1,P)&&(g.min>g.max?e.push("players.max: must be greater than or equal to players.min."):F={min:g.min,max:g.max})}}let W=!1;t.lobby!==void 0&&(typeof t.lobby!="boolean"?e.push("lobby: must be a boolean."):W=t.lobby);let A=!1;t.persistent!==void 0&&(typeof t.persistent!="boolean"?e.push("persistent: must be a boolean."):A=t.persistent);let M=t.replays===!0;t.replays!==void 0&&typeof t.replays!="boolean"&&e.push("replays: must be a boolean.");let ue={delayMs:Tt};if(t.spectators===!1||t.spectators===null)ue=null;else if(t.spectators!==void 0&&t.spectators!==!0){let g=J(t.spectators);if(g===null)e.push("spectators: must be a boolean or an object with delayMs.");else{for(let f of Object.keys(g))f!=="delayMs"&&e.push(`spectators.${f}: unknown field.`);V(g.delayMs,0,3e4)?ue={delayMs:g.delayMs}:e.push("spectators.delayMs: must be an integer from 0 to 30000.")}}let ee=null;if(t.overlay!==void 0&&t.overlay!==null){let g=J(t.overlay);if(g===null)e.push("overlay: must be an object or null.");else{for(let f of Object.keys(g))["version","accent"].includes(f)||e.push(`overlay.${f}: unknown field.`);g.version!==1&&e.push("overlay.version: must be exactly 1."),g.accent!==void 0&&(typeof g.accent!="string"||!/^#[0-9a-fA-F]{6}$/.test(g.accent))&&e.push("overlay.accent: must be a six-digit hexadecimal color, such as #336699."),ee={version:1,...typeof g.accent=="string"?{accent:g.accent}:{}}}}let I={};if(t.boards!==void 0){let g=J(t.boards);if(g===null)e.push("boards: must be an object of board ids.");else{Object.keys(g).length>Je&&e.push(`boards: at most ${Je} boards.`);for(let[f,L]of Object.entries(g)){let S=!0;Dt.test(f)||(e.push(`boards.${f}: invalid board id.`),S=!1);let b=J(L);if(b===null){e.push(`boards.${f}.source: must be "client" or "server".`);continue}for(let E of Object.keys(b))["source","label","periods","day"].includes(E)||e.push(`boards.${f}.${E}: unknown field.`);b.source!=="client"&&b.source!=="server"&&(e.push(`boards.${f}.source: must be "client" or "server".`),S=!1),b.day!==void 0&&b.day!=="submit"&&b.day!=="start"&&e.push(`boards.${f}.day: must be "submit" or "start".`),b.day==="start"&&b.source!=="server"&&e.push(`boards.${f}.day: start requires source "server".`);let O=ye(b,"label",48,`boards.${f}`,e),T=["all-time"];b.periods!==void 0&&(!Array.isArray(b.periods)||b.periods.length<1||b.periods.length>2||b.periods.some(E=>E!=="daily"&&E!=="all-time")||new Set(b.periods).size!==b.periods.length?e.push(`boards.${f}.periods: must contain daily, all-time, or both without duplicates.`):T=[...b.periods]),S&&Object.defineProperty(I,f,{value:{source:b.source,periods:T,...b.day===void 0?{}:{day:b.day},...O===void 0?{}:{label:O}},enumerable:!0,configurable:!0,writable:!0})}}}let te=[];if(t.roles!==void 0)if(!Array.isArray(t.roles))e.push("roles: must be an array.");else{let g=new Set;for(let[f,L]of t.roles.entries()){let S=J(L);if(S===null){e.push(`roles[${f}]: must be an object.`);continue}for(let l of Object.keys(S))["id","min","max","label"].includes(l)||e.push(`roles[${f}].${l}: unknown field.`);let b=S.id,O=S.min,T=S.max,E=!0;typeof b!="string"||b.length>32||!qe.test(b)?(e.push(`roles[${f}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`),E=!1):g.has(b)?(e.push(`roles[${f}].id: duplicate role ${b}.`),E=!1):g.add(b),V(O,0,P)||(e.push(`roles[${f}].min: must be an integer from 0 to ${P}.`),E=!1),T!==void 0&&!V(T,0,P)&&(e.push(`roles[${f}].max: must be an integer from 0 to ${P} when present.`),E=!1),typeof O=="number"&&typeof T=="number"&&O>T&&(e.push(`roles[${f}].max: must be greater than or equal to min.`),E=!1);let ie=ye(S,"label",32,`roles[${f}]`,e);E&&te.push({id:b,min:O,...T===void 0?{}:{max:T},...ie===void 0?{}:{label:ie}})}}let Y=null;if(t.teams!==void 0&&t.teams!==null){let g=J(t.teams);if(g===null)e.push("teams: must be null or an object with min and max.");else{for(let f of Object.keys(g))f!=="min"&&f!=="max"&&e.push(`teams.${f}: unknown field.`);V(g.min,2,P)||e.push(`teams.min: must be an integer from 2 to ${P}.`),V(g.max,2,P)||e.push(`teams.max: must be an integer from 2 to ${P}.`),V(g.min,2,P)&&V(g.max,2,P)&&(g.min>g.max?e.push("teams.max: must be greater than or equal to teams.min."):Y={min:g.min,max:g.max})}}let re="none";t.voice!==void 0&&(typeof t.voice!="string"||!zt.has(t.voice)?e.push("voice: must be none, room, team, or proximity."):re=t.voice);let H=[];if(t.modes!==void 0)if(!Array.isArray(t.modes))e.push("modes: must be an array.");else{let g=new Set;for(let[f,L]of t.modes.entries()){let S=J(L);if(S===null){e.push(`modes[${f}]: must be an object.`);continue}for(let l of Object.keys(S))["id","players","lobby","matchmaking","execution","label","instructions"].includes(l)||e.push(`modes[${f}].${l}: unknown field.`);if(typeof S.id!="string"||S.id.length>32||!qe.test(S.id)){e.push(`modes[${f}].id: must be 1-32 lowercase letters, digits, or internal hyphens.`);continue}if(g.has(S.id)){e.push(`modes[${f}].id: duplicate mode ${S.id}.`);continue}g.add(S.id);let b={id:S.id};for(let[l,y]of[["label",48],["instructions",160]]){let R=ye(S,l,y,`modes[${f}]`,e);R!==void 0&&(b[l]=R)}if(S.execution!==void 0&&(S.execution!=="local"&&S.execution!=="room"?e.push(`modes[${f}].execution: must be local or room.`):b.execution=S.execution),ee!==null&&b.execution===void 0&&e.push(`modes[${f}].execution: is required with the standard overlay.`),S.players!==void 0){let l=`modes[${f}].players`,y=J(S.players);if(y===null)e.push(`${l}: must be an object with min and max.`);else{for(let R of Object.keys(y))R!=="min"&&R!=="max"&&e.push(`${l}.${R}: unknown field.`);V(y.min,1,P)||e.push(`${l}.min: must be an integer from 1 to ${P}.`),V(y.max,1,P)||e.push(`${l}.max: must be an integer from 1 to ${P}.`),V(y.min,1,P)&&V(y.max,1,P)&&(y.min>y.max?e.push(`${l}.max: must be greater than or equal to min.`):b.players={min:y.min,max:y.max})}}if(S.lobby!==void 0&&(typeof S.lobby!="boolean"?e.push(`modes[${f}].lobby: must be a boolean.`):b.lobby=S.lobby),b.execution==="local"){let l=b.players??F;(l.min!==1||l.max!==1)&&e.push(`modes[${f}].players: local execution requires min and max to be 1.`),(b.lobby??W)&&e.push(`modes[${f}].lobby: local execution requires false.`),S.matchmaking!==void 0&&e.push(`modes[${f}].matchmaking: local execution cannot use matchmaking.`)}if(S.matchmaking===void 0){H.push(b);continue}let O=J(S.matchmaking);if(O===null){e.push(`modes[${f}].matchmaking: must be an object.`);continue}for(let l of Object.keys(O))["key","timeoutMs","defaults"].includes(l)||e.push(`modes[${f}].matchmaking.${l}: unknown field.`);let T=!0,E=[];if(!Array.isArray(O.key)||O.key.length<1||O.key.length>8)e.push(`modes[${f}].matchmaking.key: must contain from 1 to 8 fields.`),T=!1;else for(let[l,y]of O.key.entries())typeof y!="string"||!$t.test(y)?(e.push(`modes[${f}].matchmaking.key[${l}]: must be 1-32 lowercase letters, digits, or hyphens and start with a letter or digit.`),T=!1):E.includes(y)?(e.push(`modes[${f}].matchmaking.key[${l}]: duplicate field ${y}.`),T=!1):E.push(y);V(O.timeoutMs,1e3,3e5)||(e.push(`modes[${f}].matchmaking.timeoutMs: must be an integer from 1000 to 300000.`),T=!1);let ie;if(O.defaults!==void 0){let l=J(O.defaults);if(l===null||Object.keys(l).length!==E.length||E.some(y=>!Object.hasOwn(l,y)))e.push(`modes[${f}].matchmaking.defaults: must contain exactly the declared key fields.`);else{ie={};for(let[y,R]of Object.entries(l))!(typeof R=="string"&&R.length>=1&&R.length<=64&&/^[A-Za-z0-9_.:-]+$/.test(R))&&!Number.isSafeInteger(R)?e.push(`modes[${f}].matchmaking.defaults.${y}: must be a string of 1-64 characters or a safe integer.`):Object.defineProperty(ie,y,{value:R,enumerable:!0})}}T&&H.push({...b,matchmaking:{...ie===void 0?{}:{defaults:ie},key:E,timeoutMs:O.timeoutMs}})}}return ee!==null&&H.length===0&&e.push("modes: at least one explicit mode is required with the standard overlay."),e.length>0?{ok:!1,errori:e}:{ok:!0,manifest:{manifest:1,overlay:ee,id:i,name:r,description:s,cover:c,card:m,icon:h,screenshots:d,tags:u,languages:x,language:w,platform:N,orientation:_,input:j,visibility:z,network:B,requires:U,players:F,lobby:W,persistent:A,replays:M,spectators:ue,boards:I,roles:te,teams:Y,voice:re,modes:H}}}function jt(n){return n.gpu!=="hardware"||n.memoryMb!==null&&n.memoryMb<=2048?"low":n.mobile||n.memoryMb!==null&&n.memoryMb<=4096||n.cores!==null&&n.cores<=4?"mid":"high"}function Fe(n){try{n?.getExtension("WEBGL_lose_context")?.loseContext()}catch{}}function Gt(n){let e;try{e=n.navigator}catch{e=void 0}let t=null;try{let o=e?.deviceMemory,a=typeof o=="number"?o*1024:NaN;Number.isFinite(a)&&(t=a)}catch{t=null}let i=null;try{let o=e?.hardwareConcurrency;typeof o=="number"&&Number.isFinite(o)&&(i=o)}catch{i=null}let r=!1;try{r=typeof e?.userAgentData?.mobile=="boolean"?e.userAgentData.mobile:/Android|iPhone|iPad|iPod|Mobile/i.test(e?.userAgent??"")}catch{r=!1}let s=!1;try{s=n.crossOriginIsolated===!0}catch{s=!1}return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:s,gpu:"none",memoryMb:t,cores:i,mobile:r}}async function We(n,e=1500){let t=n??globalThis,i=Gt(t),r=Promise.resolve().then(()=>{try{let m=t.document?.createElement("canvas");if(m===void 0)return;let h=m.getContext("webgl2",{failIfMajorPerformanceCaveat:!0});if(h!==null){i.webgl2=!0,i.gpu="hardware",Fe(h);return}let d=m.getContext("webgl2");d!==null&&(i.webgl2=!0,i.gpu="software",Fe(d))}catch{i.webgl2=!1,i.gpu="none"}}),s=Promise.resolve().then(async()=>{let m;try{let h=t.navigator?.gpu;if(h===void 0)return;let d=await h.requestAdapter();if(d===null)return;m=await d.requestDevice(),i.webgpu=!0}catch{i.webgpu=!1}finally{try{m?.destroy?.()}catch{}}}),o=Promise.resolve().then(()=>{try{i.wasm=t.WebAssembly?.validate(new Uint8Array([0,97,115,109,1,0,0,0]))===!0}catch{i.wasm=!1}}),a=Promise.resolve().then(()=>{try{if(t.WebAssembly===void 0)return;new t.WebAssembly.Memory({initial:1,maximum:1,shared:!0}),i.threads=!0}catch{i.threads=!1}}),c;return await Promise.race([Promise.all([r,s,o,a]),new Promise(m=>{c=setTimeout(m,Math.max(0,e))})]),c!==void 0&&clearTimeout(c),{...i,tier:jt(i)}}function Ae(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>0}var de=/^[A-Za-z0-9_-]{22}$/;function Bt(n,e=null,t=null,i=null){let r=Te(n);if(!r.ok)throw new Error("The overlay manifest is invalid.");return{manifest:r.manifest,coverUrl:e,iconUrl:i,invite:t}}function D(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function Ut(n){let e=D(n),t=D(e?.configuration);return e?.v===1&&typeof e.epoch=="string"&&e.epoch.length>0&&e.epoch.length<=128&&t!==null&&(t.coverUrl===null||typeof t.coverUrl=="string")&&(t.iconUrl===null||typeof t.iconUrl=="string")&&(t.invite===null||typeof t.invite=="string"&&/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(t.invite))&&Te(t.manifest).ok}function He(n){return Ut(n)?{v:1,epoch:n.epoch,configuration:Bt(n.configuration.manifest,n.configuration.coverUrl,n.configuration.invite,n.configuration.iconUrl)}:null}function Ft(n){let e=D(n);return e!==null&&Object.keys(e).length===4&&["top","right","bottom","left"].every(t=>typeof e[t]=="number"&&Number.isFinite(e[t])&&Number(e[t])>=0&&Number(e[t])<=1e5)}function Oe(n){let e=D(n);return e!==null&&Object.keys(e).every(t=>["inputBlocked","reservedRects","safeArea","shortcutEnabled"].includes(t))&&(e.safeArea===void 0||Ft(e.safeArea))&&(e.shortcutEnabled===void 0||typeof e.shortcutEnabled=="boolean")&&typeof e.inputBlocked=="boolean"&&Array.isArray(e.reservedRects)&&e.reservedRects.length<=8&&e.reservedRects.every(t=>{let i=D(t);return i!==null&&Object.keys(i).length===4&&["x","y","width","height"].every(r=>typeof i[r]=="number"&&Number.isFinite(i[r])&&i[r]>=0&&i[r]<=1e5)})}function Ke(n){let e=D(n),t=D(e?.args);if(e?.type!=="caisual:overlay"||e.v!==1||typeof e.epoch!="string"||e.epoch.length<1||e.epoch.length>128||typeof e.requestId!="string"||!(/^[1-9][0-9]{0,15}$/.test(e.requestId)&&Number.isSafeInteger(Number(e.requestId)))||t===null||Object.keys(e).some(s=>!["type","v","epoch","requestId","sessionId","op","args"].includes(s))||!(e.sessionId===void 0||e.sessionId===null||typeof e.sessionId=="string"&&/^[1-9][0-9]{0,15}$/.test(e.sessionId)))return!1;let i=(...s)=>Object.keys(t).every(o=>s.includes(o)),r=s=>typeof t[s]=="string"&&t[s].length>=1&&t[s].length<=64;switch(e.op){case"replay.play":case"replay.pause":return i()&&typeof e.sessionId=="string";case"replay.seek":return i("positionMs")&&typeof e.sessionId=="string"&&typeof t.positionMs=="number"&&Number.isFinite(t.positionMs)&&t.positionMs>=0&&t.positionMs<=18e5;case"replay.speed":return i("speed")&&typeof e.sessionId=="string"&&[.5,1,2,4].includes(Number(t.speed))&&typeof t.speed=="number";case"local.start":return i("mode")&&r("mode");case"room.create":return i("mode")&&(t.mode===null||r("mode"));case"room.join":return i("code")&&(t.code===void 0||r("code"));case"room.watch":return i("code")&&r("code");case"room.match":{let s=D(t.key);return i("mode","key")&&r("mode")&&(t.key===void 0||s!==null&&Object.keys(s).length<=8&&Object.values(s).every(o=>typeof o=="string"&&o.length>=1&&o.length<=64||typeof o=="number"&&Number.isSafeInteger(o)))}case"room.ready":return i("ready")&&typeof t.ready=="boolean";case"room.role":case"room.requestRole":return i("role")&&r("role");case"room.team":return i("team")&&Number.isInteger(t.team)&&t.team>=1&&t.team<=24;case"room.restart":case"room.start":case"session.cancel":case"session.leave":case"session.disconnect":case"session.resume":return i();case"voice.join":case"voice.leave":return i()&&typeof e.sessionId=="string";case"voice.mute":return i("muted")&&typeof t.muted=="boolean"&&typeof e.sessionId=="string";case"voice.setVolume":return i("playerId","volume")&&typeof e.sessionId=="string"&&typeof t.playerId=="string"&&t.playerId.length>0&&t.playerId.length<=128&&typeof t.volume=="number"&&Number.isFinite(t.volume)&&t.volume>=0&&t.volume<=1;case"overlay.view":return Oe(t);default:return!1}}function me(n){if(typeof n!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(n))return!1;let e=Date.parse(`${n}T00:00:00Z`);return Number.isFinite(e)&&new Date(e).toISOString().slice(0,10)===n}function Ye(n,e){let t=a=>a!==null&&typeof a=="object"&&!Array.isArray(a)?a:null,i=t(n);if(!i||!Array.isArray(i.standings))return null;let r=new Set(e),s=new Set,o=[];for(let a of i.standings){let c=t(a);!c||typeof c.playerId!="string"||!r.has(c.playerId)||s.has(c.playerId)||(s.add(c.playerId),o.push({playerId:c.playerId,...typeof c.score=="number"&&Number.isFinite(c.score)?{score:c.score}:{},...typeof c.rank=="number"&&Number.isSafeInteger(c.rank)&&c.rank>0?{rank:c.rank}:{}}))}return o.length?{standings:o,...Array.isArray(i.winners)?{winners:[...new Set(i.winners.filter(a=>typeof a=="string"&&s.has(a)))]}:{},...typeof i.draw=="boolean"?{draw:i.draw}:{},...typeof i.unit=="string"?{unit:i.unit}:{}}:null}function p(n,e,t={}){return Object.assign(new Error(e),{name:"CaisualError",code:n,...t})}function $(){return p("offline","Caisual services are unavailable.")}function pe(n){return typeof n=="object"&&n!==null&&"code"in n?n.code:null}async function Wt(n){let e={};try{e=await n.json()}catch{}return p(typeof e.error?.code=="string"?e.error.code:n.status===401?"invalid_ticket":"internal_error",typeof e.error?.message=="string"?e.error.message:`The request failed with status ${n.status}.`,{currentVersion:e.error?.currentVersion,roomVersion:e.error?.roomVersion})}function be(n,e,t,i){async function r(s,o,a,c){let m=new Headers({Authorization:`Bearer ${a}`}),h;if(c!==void 0){m.set("Content-Type","application/json");try{h=JSON.stringify(c)}catch{throw p("invalid_request","The value must be valid JSON.")}}try{return await t(new URL(e+s,n),{method:o,headers:m,body:h,credentials:"omit"})}catch{throw $()}}return async function(o,a,c,m=!1){let h;try{h=m?await i.rinnova():await i.ottieni()}catch{throw $()}let d=await r(o,a,h,c);if(d.status===401){try{h=await i.rinnova()}catch{throw $()}d=await r(o,a,h,c)}if(!d.ok)throw await Wt(d);try{return await d.json()}catch{throw p("internal_error","The service returned an invalid response.")}}}var Ee=.02,Ze=300,Ht=200,Qe=3e3,Kt=1e4,Yt=[1e3,2e3,4e3];function Xe(n){return Number.isNaN(n)?1:Math.min(1,Math.max(0,n))}function Zt(n){let e=globalThis,t=e.AudioContext??e.webkitAudioContext;return typeof RTCPeerConnection>"u"||typeof MediaStream>"u"||t===void 0||typeof navigator>"u"||navigator.mediaDevices?.getUserMedia===void 0||typeof document>"u"?null:{...n,creaPeerConnection:i=>new RTCPeerConnection(i),getUserMedia:i=>navigator.mediaDevices.getUserMedia(i),creaAudioContext:()=>new t,creaAudioElement:()=>document.createElement("audio"),creaMediaStream:i=>new MediaStream(i)}}var we=class{constructor(e,t,i){this.contesto=e;this.modeCorrente="none";this.stateCorrente="off";this.mutedCorrente=!1;this.speakingCorrente=!1;this.roster=[];this.gains=new Map;this.volumi=new Map;this.speakingPeers=new Map;this.ultimoAudio=new Map;this.zeroDa=new Map;this.timerZero=new Map;this.ascoltatoriPeers=new Set;this.ascoltatoriState=new Set;this.richieste=new Map;this.riproduzioni=new Map;this.sfuAttive=new Map;this.midGiocatori=new Map;this.negati=new Set;this.mesh=new Map;this.stream=null;this.tracciaMic=null;this.audioContext=null;this.analyser=null;this.peerSfu=null;this.sessioneSfu=null;this.connessioneSfuAttesa=!1;this.trasporto=null;this.intervalloAudio=null;this.timerConnessione=null;this.cancellaAttesaConnessione=null;this.timerRiconnessione=null;this.ultimoAudioMic=Number.NEGATIVE_INFINITY;this.sequenzaRichieste=0;this.generazione=0;this.tentativoRiconnessione=0;this.desiderata=!1;this.micDesiderato=!0;this.promessaIngresso=null;this.negoziazione=Promise.resolve();this.dipendenze=i??Zt(t)}get mode(){return this.modeCorrente}get state(){return this.stateCorrente}get mic(){return this.stateCorrente==="on"&&this.tracciaMic!==null}get muted(){return this.mutedCorrente}get speaking(){return this.speakingCorrente}get peers(){return this.copiaPeers()}async join(e={}){if(this.stateCorrente==="on")return;if(this.stateCorrente==="joining"){this.promessaIngresso!==null&&await this.promessaIngresso;return}if(this.stateCorrente==="reconnecting"&&this.desiderata)return;let t=this.scegliMic(e);this.verificaIngresso(t),this.micDesiderato=t,this.desiderata=!0,this.tentativoRiconnessione=0,this.aggiornaState("joining");let i=++this.generazione,r=this.completaIngresso(i);this.promessaIngresso=r;try{await r}finally{this.promessaIngresso===r&&(this.promessaIngresso=null)}}async completaIngresso(e){try{await this.entra(e)}catch(t){if(e!==this.generazione)return;throw this.desiderata=!1,this.chiudiRisorse(),this.aggiornaState("off"),this.mappaErrore(t)}}leave(){let e=this.desiderata||this.stateCorrente!=="off";this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),e&&this.contesto.connessa()&&this.richiedi({t:"voice",op:"stop"}).catch(()=>{}),this.rifiutaRichieste(p("offline","Voice has stopped.")),this.chiudiRisorse(),this.aggiornaState("off")}mute(e=!0){if(this.stateCorrente!=="on"||this.tracciaMic===null)throw p("not_publishing","Join voice before changing mute.");this.mutedCorrente=e,this.tracciaMic.enabled=!e,e&&(this.speakingCorrente=!1),this.notificaPeers(),this.richiedi({t:"voice",op:"mute",muted:e}).catch(()=>{})}setVolume(e,t){let i=Xe(t);this.volumi.set(e,i),this.aggiornaGuadagno(e),this.notificaPeers()}onPeers(e){return this.ascoltatoriPeers.add(e),()=>{this.ascoltatoriPeers.delete(e)}}onState(e){return this.ascoltatoriState.add(e),()=>{this.ascoltatoriState.delete(e)}}ricevi(e){if("r"in e){let t=this.richieste.get(e.r);t!==void 0&&(this.richieste.delete(e.r),"error"in e?t.reject(p(e.error.code,e.error.message)):t.resolve(e));return}if(e.op==="roster"){this.negati.clear(),this.modeCorrente=e.mode;let t=new Set(e.peers.map(i=>i.id));this.roster=[...e.peers.map(i=>({...i,mic:!0})),...e.listeners.flatMap(i=>t.has(i)?[]:[{id:i,mic:!1,muted:!0}])];for(let i of this.roster)i.muted&&this.speakingPeers.set(i.id,!1);this.pulisciPeerAssenti(),this.contesto.rosterPronto(),this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="gain"){this.negati.clear();for(let[t,i]of Object.entries(e.gains))this.gains.set(t,Xe(i)),this.aggiornaZero(t),this.aggiornaGuadagno(t);this.notificaPeers(),this.accodaRiconciliazione();return}if(e.op==="closed"){for(let t of e.mids){let i=this.midGiocatori.get(t);if(i===void 0)continue;let r=this.sfuAttive.get(i);r?.mid===t&&!this.riproduzioni.has(i)&&r.receiver?.track.stop(),r?.mid===t&&this.sfuAttive.delete(i),this.midGiocatori.delete(t),this.scollegaTraccia(i),this.negati.add(i)}this.notificaPeers();return}e.op==="signal"&&this.riceviSegnale(e.from,e.data)}giocatoriCambiati(){this.negati.clear();let e=new Set(this.contesto.giocatori().map(t=>t.id));for(let t of this.gains.keys()){if(e.has(t))continue;this.gains.delete(t),this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t),this.aggiornaGuadagno(t)}this.notificaPeers(),this.accodaRiconciliazione()}socketDisconnesso(){this.sequenzaRichieste=0,this.rifiutaRichieste(p("offline","The room is reconnecting.")),this.desiderata&&(this.generazione++,this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"))}socketRiconnesso(){this.sequenzaRichieste=0,this.desiderata&&this.stateCorrente==="reconnecting"&&this.programmaRiconnessione()}termina(){this.desiderata=!1,this.generazione++,this.fermaRiconnessione(),this.rifiutaRichieste(p("offline","The room connection ended.")),this.chiudiRisorse(),this.aggiornaState("off")}scegliMic(e){return e.mic!==void 0?e.mic:this.contesto.giocatori().find(i=>i.id===this.contesto.you())?.role!=="spectator"}verificaIngresso(e=this.micDesiderato){if(!this.contesto.connessa())throw p("offline","The room is not connected.");if(this.modeCorrente==="none")throw p("voice_disabled","Voice is disabled for this room.");if(this.contesto.giocatori().find(i=>i.id===this.contesto.you())?.role==="spectator"&&e)throw p("spectator","Spectators cannot publish voice.");if(this.dipendenze===null)throw p("unsupported","Voice is not supported in this browser.")}async entra(e){this.verificaIngresso();let t=this.richiediDipendenze(),i=t.creaAudioContext();if(this.audioContext=i,this.micDesiderato){let s;try{s=await t.getUserMedia({audio:!0})}catch(a){throw this.permessoNegato(a)?p("permission_denied","Microphone permission was denied."):p("voice_error","The microphone could not be opened.")}try{this.controllaGenerazione(e)}catch(a){for(let c of s.getTracks())c.stop();throw a}let o=s.getAudioTracks()[0];if(o===void 0)throw p("voice_error","The microphone has no audio track.");this.stream=s,this.tracciaMic=o,o.enabled=!this.mutedCorrente,this.preparaAnalizzatore(s)}try{await i.resume()}catch{}this.controllaGenerazione(e);let r=await this.richiedi({t:"voice",op:"ice"});if(this.controllaGenerazione(e),r.op!=="ice")throw p("voice_error","The voice service returned an invalid response.");if(this.modeCorrente=r.mode,r.mode==="none")throw p("voice_disabled","Voice is disabled for this room.");this.trasporto=r.transport,r.transport==="sfu"?await this.entraSfu(r.iceServers,e):await this.richiedi({t:"voice",op:"publish",mic:this.micDesiderato}),this.micDesiderato&&this.mutedCorrente&&await this.richiedi({t:"voice",op:"mute",muted:!0}),this.controllaGenerazione(e),this.tentativoRiconnessione=0,this.aggiornaState("on"),this.avviaMisuraAudio();for(let s of this.gains.keys())this.aggiornaZero(s);this.accodaRiconciliazione()}async entraSfu(e,t){let i=this.richiediDipendenze().creaPeerConnection({iceServers:e,bundlePolicy:"max-bundle"});this.peerSfu=i,i.ontrack=s=>{let o=s.transceiver.mid,a=o===null?void 0:this.midGiocatori.get(o);a!==void 0&&this.collegaTraccia(a,s.track,s.receiver)},this.osservaCaduta(i);let r;if(this.micDesiderato){let s=i.addTransceiver(this.richiediMic(),{direction:"sendonly"}),o=await i.createOffer();await i.setLocalDescription(o),this.controllaGenerazione(t);let a=s.mid,c=i.localDescription?.sdp;if(a===null||c===void 0)throw p("voice_error","The voice connection could not create an offer.");r=await this.richiedi({t:"voice",op:"session",sdp:c,mid:a})}else r=await this.richiedi({t:"voice",op:"session"});if(r.op!=="session")throw p("voice_error","The voice service returned an invalid response.");if(this.sessioneSfu=r.session,this.micDesiderato){if(r.sdp===null)throw p("voice_error","The voice service returned an invalid response.");await i.setRemoteDescription({type:"answer",sdp:r.sdp}),await this.attendiConnessione(i,t),this.connessioneSfuAttesa=!0;return}if(r.sdp!==null)throw p("voice_error","The voice service returned an invalid response.");this.publisherDesiderati().length>0&&await this.riconciliaSfu()}attendiConnessione(e,t){if(e.connectionState==="connected")return Promise.resolve();let i=this.richiediDipendenze();return new Promise((r,s)=>{let o=()=>{e.removeEventListener("connectionstatechange",a),this.timerConnessione!==null&&i.clearTimeout(this.timerConnessione),this.timerConnessione=null,this.cancellaAttesaConnessione=null},a=()=>{t!==this.generazione?(o(),s(p("offline","Voice was stopped."))):e.connectionState==="connected"?(o(),r()):(e.connectionState==="failed"||e.connectionState==="closed")&&(o(),s(p("voice_error","The voice connection failed.")))};e.addEventListener("connectionstatechange",a),this.cancellaAttesaConnessione=()=>{o(),s(p("offline","Voice was stopped."))},this.timerConnessione=i.setTimeout(()=>{o(),s(p("voice_error","The voice connection timed out."))},Kt)})}accodaRiconciliazione(){this.stateCorrente==="on"&&(this.negoziazione=this.negoziazione.then(async()=>{this.stateCorrente==="on"&&(this.trasporto==="sfu"?await this.riconciliaSfu():this.trasporto==="mesh"&&this.riconciliaMesh())}).catch(()=>this.avviaRiconnessione()))}async riconciliaSfu(){let e=this.sessioneSfu,t=this.peerSfu;if(e===null||t===null)return;let i=new Map(this.publisherDesiderati().map(m=>[m.id,m])),r=[];for(let[m,h]of this.sfuAttive){let d=i.get(m);d!==void 0&&d.session===h.session&&d.track===h.track||(r.push(h),this.riproduzioni.has(m)||h.receiver?.track.stop(),this.sfuAttive.delete(m),this.midGiocatori.delete(h.mid),this.scollegaTraccia(m))}r.length>0&&await this.richiedi({t:"voice",op:"close",session:e,mids:r.map(m=>m.mid)});let s=[...i.values()].filter(m=>!this.sfuAttive.has(m.id));if(s.length===0)return;let o;try{o=await this.richiedi({t:"voice",op:"subscribe",session:e,tracks:s.map(m=>({session:m.session,track:m.track}))})}catch(m){if(pe(m)!=="not_allowed")throw m;for(let h of s)this.negati.add(h.id);return}if(o.op!=="subscribe")throw p("voice_error","The voice service returned an invalid response.");for(let m of o.tracks){let h=s.find(d=>d.session===m.session&&d.track===m.track);m.error==="not_allowed"&&h!==void 0&&this.negati.add(h.id),!(m?.mid===null||m?.mid===void 0||m.error!==null||h===void 0)&&(this.midGiocatori.set(m.mid,h.id),this.sfuAttive.set(h.id,{session:h.session,track:h.track,mid:m.mid,receiver:null}))}await t.setRemoteDescription({type:"offer",sdp:o.sdp});let a=await t.createAnswer();await t.setLocalDescription(a);let c=t.localDescription?.sdp;if(c===void 0)throw p("voice_error","The voice answer is missing.");await this.richiedi({t:"voice",op:"answer",session:e,sdp:c}),this.connessioneSfuAttesa||(await this.attendiConnessione(t,this.generazione),this.connessioneSfuAttesa=!0)}riconciliaMesh(){let e=new Map(this.peerDesiderati().map(t=>[t.id,t]));for(let[t,i]of this.mesh)e.has(t)||(i.pc.close(),this.mesh.delete(t),this.scollegaTraccia(t));for(let t of e.values())this.mesh.has(t.id)||this.creaMesh(t)}creaMesh(e){let t=e.id,i=this.richiediDipendenze().creaPeerConnection(),r={pc:i,makingOffer:!1,ignoreOffer:!1,settingRemoteAnswer:!1,polite:this.contesto.you()>t,receiver:null};this.mesh.set(t,r),i.onicecandidate=s=>{s.candidate!==null&&this.inviaSegnale(t,{kind:"candidate",candidate:s.candidate.toJSON()})},r.polite||(i.onnegotiationneeded=()=>{this.offriMesh(t,r)}),i.ontrack=s=>{r.receiver=s.receiver,this.collegaTraccia(t,s.track,s.receiver)},this.osservaCaduta(i),this.micDesiderato?i.addTransceiver(this.richiediMic(),{direction:e.mic?"sendrecv":"sendonly"}):i.addTransceiver("audio",{direction:"recvonly"})}async offriMesh(e,t){try{t.makingOffer=!0;let i=await t.pc.createOffer();await t.pc.setLocalDescription(i);let r=t.pc.localDescription?.sdp;r!==void 0&&await this.inviaSegnale(e,{kind:"offer",sdp:r})}finally{t.makingOffer=!1}}async riceviSegnale(e,t){if(this.trasporto!=="mesh"||this.stateCorrente!=="on")return;let i=this.peerDesiderati().find(o=>o.id===e);if(i===void 0)return;this.mesh.has(e)||this.creaMesh(i);let r=this.mesh.get(e);if(r===void 0||typeof t!="object"||t===null||Array.isArray(t))return;let s=t;try{if(s.kind==="candidate"){r.ignoreOffer||await r.pc.addIceCandidate(s.candidate);return}if(s.kind!=="offer"&&s.kind!=="answer"||typeof s.sdp!="string")return;let o=!r.makingOffer&&(r.pc.signalingState==="stable"||r.settingRemoteAnswer),a=s.kind==="offer"&&!o;if(r.ignoreOffer=!r.polite&&a,r.ignoreOffer)return;if(r.settingRemoteAnswer=s.kind==="answer",await r.pc.setRemoteDescription({type:s.kind,sdp:s.sdp}),r.settingRemoteAnswer=!1,s.kind==="offer"){let c=await r.pc.createAnswer();await r.pc.setLocalDescription(c);let m=r.pc.localDescription?.sdp;m!==void 0&&await this.inviaSegnale(e,{kind:"answer",sdp:m})}}catch{this.avviaRiconnessione()}}async inviaSegnale(e,t){try{await this.richiedi({t:"voice",op:"signal",to:e,data:t})}catch(i){if(pe(i)!=="not_allowed")throw i;this.mesh.get(e)?.pc.close(),this.mesh.delete(e),this.scollegaTraccia(e),this.negati.add(e)}}peerDesiderati(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.filter(r=>{if(r.id===e||this.negati.has(r.id)||!this.micDesiderato&&!r.mic)return!1;if(this.modeCorrente==="team"){let s=t.find(o=>o.id===r.id);if(i?.role!=="spectator"&&s?.team!==i?.team)return!1}return!0})}publisherDesiderati(){return this.peerDesiderati().filter(e=>{if(!e.mic)return!1;let t=this.zeroDa.get(e.id);return t===void 0||this.richiediDipendenze().ora()-t<Qe})}aggiornaZero(e){let t=this.dipendenze;if(t===null)return;let i=this.timerZero.get(e);if(i!==void 0&&t.clearTimeout(i),this.timerZero.delete(e),(this.gains.get(e)??1)>0){this.zeroDa.delete(e);return}this.zeroDa.has(e)||this.zeroDa.set(e,t.ora());let r=t.ora()-(this.zeroDa.get(e)??t.ora()),s=t.setTimeout(()=>{this.timerZero.delete(e),this.accodaRiconciliazione()},Math.max(0,Qe-r));this.timerZero.set(e,s)}collegaTraccia(e,t,i){this.scollegaTraccia(e);let r=this.richiediDipendenze(),s=r.creaMediaStream([t]),o=this.richiediAudioContext().createMediaStreamSource(s),a=this.richiediAudioContext().createGain();o.connect(a),a.connect(this.richiediAudioContext().destination);let c=null;try{c=this.richiediAudioContext().createAnalyser(),c.fftSize=256,o.connect(c)}catch{c=null}let m=r.creaAudioElement();m.srcObject=s,m.muted=!0,m.playsInline=!0,m.play().catch(()=>{}),this.riproduzioni.set(e,{source:o,gain:a,analyser:c,audio:m,track:t,receiver:i});let h=this.sfuAttive.get(e);h!==void 0&&(h.receiver=i),this.aggiornaGuadagno(e)}scollegaTraccia(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.source.disconnect(),t.gain.disconnect(),t.analyser?.disconnect(),t.track.stop(),t.audio.pause(),t.audio.srcObject=null,this.riproduzioni.delete(e),this.speakingPeers.delete(e),this.ultimoAudio.delete(e))}aggiornaGuadagno(e){let t=this.riproduzioni.get(e);t!==void 0&&(t.gain.gain.value=(this.volumi.get(e)??1)*(this.gains.get(e)??1))}preparaAnalizzatore(e){let t=this.richiediAudioContext(),i=t.createAnalyser();i.fftSize=256,t.createMediaStreamSource(e).connect(i),this.analyser=i}avviaMisuraAudio(){let e=this.richiediDipendenze();this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.intervalloAudio=e.setInterval(()=>this.misuraAudio(),Ht)}misuraAudio(){let e=this.dipendenze;if(e===null)return;let t=!1;this.analyser!==null&&(t=this.livelloAnalizzatore(this.analyser)>Ee),t&&(this.ultimoAudioMic=e.ora());let i=!this.mutedCorrente&&e.ora()-this.ultimoAudioMic<=Ze;i!==this.speakingCorrente&&(this.speakingCorrente=i,this.notificaPeers());let r=!1;for(let s of this.copiaPeers()){let o=this.riproduzioni.get(s.id);this.livelloAnalizzatore(o?.analyser??null)>Ee?this.ultimoAudio.set(s.id,e.ora()):(o?.analyser===null||o?.analyser===void 0)&&(o?.receiver?.getSynchronizationSources?.()??[]).some(m=>(m.audioLevel??0)>Ee)&&this.ultimoAudio.set(s.id,e.ora());let a=!s.muted&&e.ora()-(this.ultimoAudio.get(s.id)??0)<=Ze;(this.speakingPeers.get(s.id)??!1)!==a&&(this.speakingPeers.set(s.id,a),r=!0)}r&&this.notificaPeers()}livelloAnalizzatore(e){let t=e;if(t?.getFloatTimeDomainData===void 0)return 0;let i=new Float32Array(t.fftSize);return t.getFloatTimeDomainData(i),Math.sqrt(i.reduce((r,s)=>r+s*s,0)/Math.max(1,i.length))}copiaPeers(){let e=this.contesto.you(),t=this.contesto.giocatori(),i=t.find(r=>r.id===e);return this.roster.flatMap(r=>{if(r.id===e)return[];if(this.modeCorrente==="team"){let s=t.find(o=>o.id===r.id);if(i?.role!=="spectator"&&s?.team!==i?.team)return[]}return[{id:r.id,mic:r.mic,muted:r.muted,speaking:r.mic&&!r.muted&&(this.speakingPeers.get(r.id)??!1),volume:this.volumi.get(r.id)??1,gain:this.gains.get(r.id)??1}]})}pulisciPeerAssenti(){let e=new Set(this.roster.map(t=>t.id));for(let t of this.speakingPeers.keys())e.has(t)||this.speakingPeers.delete(t);for(let t of this.zeroDa.keys()){if(e.has(t))continue;this.zeroDa.delete(t);let i=this.timerZero.get(t);i!==void 0&&this.dipendenze?.clearTimeout(i),this.timerZero.delete(t)}}osservaCaduta(e){e.addEventListener("connectionstatechange",()=>{this.stateCorrente==="on"&&(e.connectionState==="failed"||e.connectionState==="disconnected")&&this.avviaRiconnessione()})}avviaRiconnessione(){!this.desiderata||this.stateCorrente==="reconnecting"||(this.generazione++,this.rifiutaRichieste(p("voice_error","The voice connection was restarted.")),this.chiudiRisorse(),this.tentativoRiconnessione=0,this.aggiornaState("reconnecting"),this.programmaRiconnessione())}programmaRiconnessione(){if(!this.desiderata||!this.contesto.connessa()||this.timerRiconnessione!==null||this.stateCorrente!=="reconnecting")return;let e=Yt[this.tentativoRiconnessione];if(e===void 0){this.desiderata=!1,this.aggiornaState("off");return}this.tentativoRiconnessione++,this.timerRiconnessione=this.richiediDipendenze().setTimeout(()=>{this.timerRiconnessione=null;let t=++this.generazione;this.entra(t).catch(()=>{t!==this.generazione||!this.desiderata||(this.chiudiRisorse(),this.aggiornaState("reconnecting"),this.programmaRiconnessione())})},e)}fermaRiconnessione(){this.timerRiconnessione===null||this.dipendenze===null||(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}chiudiRisorse(){let e=this.dipendenze;if(this.cancellaAttesaConnessione?.(),this.cancellaAttesaConnessione=null,e!==null){this.intervalloAudio!==null&&e.clearInterval(this.intervalloAudio),this.timerConnessione!==null&&e.clearTimeout(this.timerConnessione);for(let t of this.timerZero.values())e.clearTimeout(t)}this.intervalloAudio=null,this.timerConnessione=null,this.timerZero.clear();for(let t of[...this.riproduzioni.keys()])this.scollegaTraccia(t);this.peerSfu?.close(),this.peerSfu=null;for(let t of this.mesh.values())t.pc.close();this.mesh.clear(),this.sfuAttive.clear(),this.midGiocatori.clear(),this.negati.clear();for(let t of this.stream?.getTracks()??[])t.stop();this.stream=null,this.tracciaMic=null,this.analyser=null,this.audioContext?.close().catch(()=>{}),this.audioContext=null,this.sessioneSfu=null,this.connessioneSfuAttesa=!1,this.trasporto=null,this.speakingCorrente=!1,this.ultimoAudioMic=Number.NEGATIVE_INFINITY,this.speakingPeers.clear(),this.ultimoAudio.clear(),this.negoziazione=Promise.resolve()}richiedi(e){if(!this.contesto.connessa())return Promise.reject(p("offline","The room is reconnecting."));let t=++this.sequenzaRichieste;return new Promise((i,r)=>{this.richieste.set(t,{resolve:i,reject:r});try{this.contesto.invia({...e,r:t})}catch(s){this.richieste.delete(t),r(s)}})}rifiutaRichieste(e){for(let t of this.richieste.values())t.reject(e);this.richieste.clear()}aggiornaState(e){if(e!==this.stateCorrente){this.stateCorrente=e;for(let t of this.ascoltatoriState)try{t(e)}catch{}}}notificaPeers(){let e=this.copiaPeers();for(let t of this.ascoltatoriPeers)try{t(e)}catch{}}controllaGenerazione(e){if(e!==this.generazione||!this.desiderata)throw p("offline","Voice was stopped.")}richiediDipendenze(){if(this.dipendenze===null)throw p("unsupported","Voice is not supported.");return this.dipendenze}richiediMic(){if(this.tracciaMic===null)throw p("voice_error","The microphone is not ready.");return this.tracciaMic}richiediAudioContext(){if(this.audioContext===null)throw p("voice_error","Audio is not ready.");return this.audioContext}permessoNegato(e){return typeof e=="object"&&e!==null&&"name"in e&&(e.name==="NotAllowedError"||e.name==="SecurityError")}mappaErrore(e){if(typeof e=="object"&&e!==null&&"code"in e){let t=e.code;return t==="voice_disabled"||t==="permission_denied"||t==="unsupported"||t==="spectator"||t==="offline"||t==="voice_error"?e:p("voice_error","Voice could not be started.")}return p("voice_error","Voice could not be started.")}};var ne=1,et=[1e3,2e3,4e3,8e3],Qt=6e4,Xt=5e3,ei=2e4,ti=500,ii=2e3,ni=new Set([4003,4004,4005,4006,4008,4009]);function Q(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function tt(n){let e=Q(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.join=="string"&&typeof e.url=="string"}function ri(n){let e=Q(n);return e!==null&&typeof e.roomId=="string"&&typeof e.code=="string"&&typeof e.watch=="string"&&typeof e.url=="string"}function oi(n){let e=Q(n),t=Q(e?.players);return e!==null&&typeof e.url=="string"&&Number.isInteger(e.timeoutMs)&&e.timeoutMs>=1e3&&e.timeoutMs<=3e5&&t!==null&&Number.isInteger(t.min)&&Number.isInteger(t.max)&&t.min>=1&&t.max>=t.min}function Z(n){return JSON.parse(JSON.stringify(n))}function _e(n,e){let t=Z(n);for(let i of e){if(i.path.length===0){if(i.op!=="set")return{ok:!1};t=Z(i.value);continue}let r=t,s=i.path;for(let a=0;a<s.length-1;a++){let c=s[a];if(Array.isArray(r)){if(typeof c!="number"||c>=r.length)return{ok:!1};r=r[c]}else{let m=Q(r);if(m===null||typeof c!="string"||!Object.hasOwn(m,c))return{ok:!1};r=m[c]}}let o=s.at(-1);if(Array.isArray(r)){if(i.op!=="set"||typeof o!="number"||o>=r.length)return{ok:!1};r[o]=Z(i.value)}else{let a=Q(r);if(a===null||typeof o!="string")return{ok:!1};if(i.op==="del"){if(!Object.hasOwn(a,o))return{ok:!1};delete a[o]}else Object.defineProperty(a,o,{configurable:!0,enumerable:!0,value:Z(i.value),writable:!0})}}return{ok:!0,state:t}}function si(n){let e=be(n.liveOrigin,"",n.fetcher,n.biglietto),t=async(o,a,c,m)=>{try{return await e(o,a,{...Q(c),n:n.n},m)}catch(h){if(h instanceof Error&&"code"in h&&["version_outdated","version_mismatch"].includes(String(h.code))){let d=Q(c),u=typeof d?.code=="string"?d.code.toUpperCase().replace(/[\s-]/g,""):void 0,v=typeof d?.roomId=="string"?d.roomId:void 0;n.onVersionError?.(h,h.code==="version_mismatch"?{code:u,roomId:v,watch:o==="/rooms/watch"}:void 0)}throw h}};async function i(o,a,c=!1){let m=await t(o,"POST",a,c);if(!tt(m))throw p("internal_error","The room service returned an invalid response.");return m}async function r(o){let a=await t("/match","POST",{mode:o.mode,key:o.key});if(!oi(a))throw p("internal_error","The matchmaking service returned an invalid response.");return a}async function s(o,a=!1){let c=await t("/rooms/watch","POST",o,a);if(!ri(c))throw p("internal_error","The room service returned an invalid response.");return c}return{create:o=>i("/rooms",{mode:o}),joinCode:o=>i("/rooms/join",{code:o}),joinRoom:o=>i("/rooms/join",{roomId:o},!0),watchCode:o=>s({code:o}),watchRoom:o=>s({roomId:o},!0),match:r,flush:o=>t(`/rooms/${encodeURIComponent(o)}/flush`,"POST")}}var Se=class{constructor(e,t,i,r,s,o,a=!1){this.roomId=e;this.codice=t;this.dipendenze=r;this.api=s;this.segnalaStanza=o;this.spettatore=a;this.meta={host:null,mode:null,countdownAt:null,configuration:null,connection:"connecting",closedCode:null};this.metaListeners=new Set;this.connectionListeners=new Set;this.scoreListeners=new Set;this.scores=[];this.errorListeners=new Set;this.roleId=0;this.roleRequests=new Map;this.statoPubblico=null;this.statoSincronizzato=null;this.tickCorrente=0;this.tickRateCorrente=0;this.latenzaCorrente=null;this.ultimoInput=null;this.inputInviato=null;this.timerInput=null;this.ultimoInvioGioco=-1/0;this.inviiGioco=[];this.seedCorrente=0;this.statusCorrente="lobby";this.giocatoriCorrenti=[];this.youCorrente="";this.hostCorrente=null;this.resultCorrente=null;this.delaySpettatore=0;this.socket=null;this.seq=0;this.scartoOrario=0;this.timerPing=null;this.intervalloPing=null;this.timerRiconnessione=null;this.timerFlush=null;this.flushInCorso=!1;this.flushRichiesto=!1;this.ritardoIndice=0;this.tempoRiconnessione=0;this.resyncRichiesto=!1;this.terminata=!1;this.lasciata=!1;this.prontaRisolta=!1;this.welcomeRicevuto=!1;this.rosterRicevuto=!1;this.timerRoster=null;this.risolviPronta=()=>{};this.rifiutaPronta=()=>{};this.ascoltatoriStato=new Set;this.ascoltatoriGiocatori=new Set;this.ascoltatoriStatus=new Set;this.ascoltatoriMessaggi=new Set;this.replay=!1;this.promessaPronta=new Promise((c,m)=>{this.risolviPronta=c,this.rifiutaPronta=m}),this.voice=new we({invia:c=>this.invia(c),connessa:()=>this.socket?.readyState===ne&&this.welcomeRicevuto&&!this.terminata&&!this.lasciata,you:()=>this.youCorrente,giocatori:()=>this.copiaGiocatori(),rosterPronto:()=>{this.rosterRicevuto=!0,this.risolviProntaSePossibile()}},r,r.voce),a&&(this.rosterRicevuto=!0),this.apri(i)}get mode(){return this.meta.mode}get countdownAt(){return this.meta.countdownAt}get connection(){return this.meta.connection}get metadata(){return structuredClone(this.meta)}get queuedScores(){return structuredClone(this.scores)}onMetadata(e){return this.metaListeners.add(e),()=>this.metaListeners.delete(e)}onConnection(e){return this.connectionListeners.add(e),()=>this.connectionListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onScoreQueued(e){return this.scoreListeners.add(e),()=>this.scoreListeners.delete(e)}metadataChanged(e){let t=this.meta.connection;this.meta={...this.meta,...e},this.notifica(this.metaListeners,this.metadata),t!==this.meta.connection&&this.notifica(this.connectionListeners,this.meta.connection)}initialMetadata(e){this.metadataChanged({host:e.host,mode:e.mode,countdownAt:e.countdownAt??null,rematch:e.rematch??null,configuration:e.configuration??null,connection:"connected",closedCode:null})}requestRole(e){if(typeof e!="string"||e.length<1||e.length>32)return Promise.reject(p("invalid_role","The role is not valid."));if(this.connection!=="connected"||this.status!=="playing"||!this.meta.configuration?.requestRole)return Promise.reject(p("role_change_unavailable","Roles cannot be requested right now."));if(this.roleRequests.size>=8)return Promise.reject(p("rate_limited","Too many role requests."));let t=++this.roleId;return new Promise((i,r)=>{let s=this.dipendenze.setTimeout(()=>{this.roleRequests.delete(t),r(p("timeout","The role request timed out."))},5e3);this.roleRequests.set(t,{resolve:i,reject:r,timer:s});try{this.invia({t:"request-role",r:t,role:e})}catch(o){this.dipendenze.clearTimeout(s),this.roleRequests.delete(t),r(o)}})}clearRoleRequests(){for(let e of this.roleRequests.values())this.dipendenze.clearTimeout(e.timer),e.reject(p("offline","The room connection ended."));this.roleRequests.clear()}disconnect(){if(this.lasciata)return;this.lasciata=!0;let e=this.socket;this.socket=null,this.voice.termina(),this.fermaInput(),this.fermaPing(),this.fermaRiconnessione(),this.clearRoleRequests(),this.timerRoster!==null&&this.dipendenze.clearTimeout(this.timerRoster),e?.close(1e3),this.segnalaStanza(null),this.metadataChanged({connection:"disconnected",closedCode:null}),this.prontaRisolta||(this.prontaRisolta=!0,this.rifiutaPronta(p("cancelled","The room was disconnected.")))}get role(){return this.spettatore?"spectator":this.giocatoriCorrenti.find(e=>e.id===this.youCorrente)?.role??null}get state(){return this.statoPubblico}get tick(){return this.tickCorrente}get tickRate(){return this.tickRateCorrente}get latency(){return this.latenzaCorrente}get seed(){return this.seedCorrente}get status(){return this.statusCorrente}get players(){return this.copiaGiocatori()}get you(){return this.youCorrente}get host(){return this.hostCorrente}get code(){return this.codice}get result(){return this.resultCorrente}get delayMs(){return this.delaySpettatore}pronta(){return this.promessaPronta}invite(){return{code:this.codice,url:new URL(`/r/${this.codice}`,this.dipendenze.appOrigin).href}}onState(e){return this.ascoltatoriStato.add(e),()=>{this.ascoltatoriStato.delete(e)}}onPlayers(e){return this.ascoltatoriGiocatori.add(e),()=>{this.ascoltatoriGiocatori.delete(e)}}onStatus(e){return this.ascoltatoriStatus.add(e),()=>{this.ascoltatoriStatus.delete(e)}}onMessage(e){return this.ascoltatoriMessaggi.add(e),()=>{this.ascoltatoriMessaggi.delete(e)}}send(e){if(this.statusCorrente==="finished")return;let t=this.seq+1;this.invia({t:"msg",seq:t,m:e}),this.seq=t,this.ultimoInvioGioco=this.dipendenze.ora(),this.inviiGioco=[...this.inviiGioco.slice(-29),this.ultimoInvioGioco]}input(e){if(!(this.terminata||this.lasciata||this.statusCorrente==="finished")){try{let t=JSON.stringify(e);if(t===void 0)throw new TypeError;this.ultimoInput=t}catch{throw p("invalid_request","Room input must be valid JSON.")}this.programmaInput()}}pulisciInput(){this.fermaInput(),this.ultimoInput=this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[]}fermaInput(){this.timerInput!==null&&this.dipendenze.clearTimeout(this.timerInput),this.timerInput=null}programmaInput(){if(this.timerInput!==null||this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==ne||this.terminata||this.lasciata)return;let e=this.dipendenze.ora(),i=1e3/(this.tickRateCorrente>0?Math.min(30,this.tickRateCorrente):30);this.inviiGioco=this.inviiGioco.filter(o=>e-o<1e3);let r=this.inviiGioco.length>=30?this.inviiGioco[0]+1e3:e,s=Number.isFinite(this.ultimoInvioGioco)?this.ultimoInvioGioco+i:e+i;this.timerInput=this.dipendenze.setTimeout(()=>{if(this.timerInput=null,this.ultimoInput===null||this.ultimoInput===this.inputInviato||!this.welcomeRicevuto||this.socket?.readyState!==ne||this.terminata||this.lasciata)return;let o=this.dipendenze.ora();if(o<this.ultimoInvioGioco+i||this.inviiGioco.filter(c=>o-c<1e3).length>=30){this.programmaInput();return}let a=this.ultimoInput;try{this.send(JSON.parse(a)),this.inputInviato=a}catch{}},Math.max(0,Math.ceil(Math.max(s,r)-e)))}aggiornaTickRate(e){e===void 0||!Number.isInteger(e)||e<0||e>60||e===this.tickRateCorrente||(this.tickRateCorrente=e,this.fermaInput(),this.programmaInput())}ready(e){this.invia({t:"ready",ready:e})}setRole(e){this.invia({t:"role",role:e})}setTeam(e){this.invia({t:"team",team:e})}start(){this.invia({t:"start"})}restart(){if(this.statusCorrente!=="finished")throw p("rematch_unavailable","This room is not waiting for a rematch.");this.invia({t:"restart"})}leave(){if(!this.lasciata){if(this.spettatore||this.voice.leave(),this.lasciata=!0,this.segnalaStanza(null),this.socket?.readyState===ne){let e=this.socket;this.invia({t:"leave"}),this.spettatore&&e.close(1e3)}this.termina(1e3)}}serverTime(){return this.dipendenze.ora()+this.scartoOrario}copiaGiocatori(){return this.giocatoriCorrenti.map(e=>({...e}))}notifica(e,...t){for(let i of e)try{i(...t)}catch{}}invia(e){if(this.socket?.readyState!==ne)throw p("offline","The room is reconnecting.");let t;try{t=JSON.stringify(e)}catch{throw p("invalid_request","Room messages must be valid JSON.")}this.socket.send(t)}apri(e){let t;try{t=this.dipendenze.apriSocket(e)}catch{this.programmaRiconnessione();return}this.socket=t,t.addEventListener("open",()=>{this.socket===t&&this.avviaPing()}),t.addEventListener("message",i=>{this.socket===t&&typeof i.data=="string"&&this.ricevi(i.data)}),t.addEventListener("close",i=>{this.socket===t&&this.chiuso(i.code,i.reason)})}avviaPing(){if(this.socket?.readyState!==ne||this.terminata||this.lasciata)return;let e=this.statusCorrente==="playing"?Xt:ei;this.timerPing!==null&&this.intervalloPing===e||(this.timerPing!==null&&this.dipendenze.clearInterval(this.timerPing),this.intervalloPing=e,this.timerPing=this.dipendenze.setInterval(()=>{if(this.socket?.readyState===ne)try{this.invia({t:"ping",c:this.dipendenze.ora()})}catch{}},e))}fermaPing(){this.timerPing!==null&&(this.dipendenze.clearInterval(this.timerPing),this.timerPing=null,this.intervalloPing=null)}ricevi(e){let t;try{let i=JSON.parse(e),r=Q(i);if(r===null||typeof r.t!="string")return;t=r}catch{return}try{if(t.t==="watching")this.riceviWatching(t);else if(t.t==="welcome")this.riceviWelcome(t);else if(t.t==="replay-ready"&&/^[A-Za-z0-9_-]{22}$/.test(t.id))this.metadataChanged({replayId:t.id});else if(t.t==="players")this.riceviGiocatori(t.players,t.host);else if(t.t==="status")this.riceviStatus(t);else if(t.t==="state")this.riceviDiff(t);else if(t.t==="snapshot")this.riceviSnapshot(t);else if(t.t==="msg")this.notifica(this.ascoltatoriMessaggi,Z(t.m));else if(t.t==="pong")this.riceviPong(t);else if(t.t==="error")this.notifica(this.errorListeners,{code:t.code,message:t.message});else if(t.t==="flush")this.richiediFlush();else if(t.t==="score-queued"&&!this.spettatore)this.scores.push(structuredClone(t.score)),this.scores=this.scores.slice(-32),this.notifica(this.scoreListeners,structuredClone(t.score));else if(t.t==="role-result"){let i=this.roleRequests.get(t.r);i&&(this.dipendenze.clearTimeout(i.timer),this.roleRequests.delete(t.r),t.ok?i.resolve():i.reject(p(t.code??"role_change_refused","The role change was not accepted.")))}else t.t==="voice"&&this.voice.ricevi(t)}catch{(t.t==="state"||t.t==="snapshot")&&this.chiediResync()}}riceviWatching(e){let t=e.room;!this.spettatore||t.id!==this.roomId||(this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.hostCorrente=t.host,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=Z(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.delaySpettatore=e.delayMs,this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviWelcome(e){let t=e.room;t.id===this.roomId&&(this.youCorrente=e.you,this.aggiornaTickRate(t.tickRate),this.seedCorrente=t.seed,this.hostCorrente=t.host,this.statusCorrente=t.status,this.avviaPing(),this.resultCorrente=Z(t.result??null),t.status==="finished"&&this.pulisciInput(),this.giocatoriCorrenti=e.players.map(i=>({...i})),this.aggiornaStato(e.state,t.tick,t.serverTime),this.scartoOrario=t.serverTime-this.dipendenze.ora(),this.resyncRichiesto=!1,this.welcomeRicevuto=!0,!this.rosterRicevuto&&this.timerRoster===null&&(this.timerRoster=this.dipendenze.setTimeout(()=>{this.timerRoster=null,this.rosterRicevuto=!0,this.risolviProntaSePossibile()},ii)),this.ritardoIndice=0,this.tempoRiconnessione=0,this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati(),this.voice.socketRiconnesso(),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,t.serverTime),this.initialMetadata(t),this.programmaInput(),this.risolviProntaSePossibile())}riceviGiocatori(e,t){this.giocatoriCorrenti=e.map(i=>({...i})),t!==void 0?this.hostCorrente=t:this.giocatoriCorrenti.some(i=>i.id===this.hostCorrente&&i.connected)||(this.hostCorrente=this.giocatoriCorrenti.find(i=>i.connected)?.id??null),this.metadataChanged({host:this.hostCorrente}),this.notifica(this.ascoltatoriGiocatori,this.copiaGiocatori()),this.voice.giocatoriCambiati()}riceviStatus(e){(e.status==="playing"||e.status==="countdown"||e.status==="lobby")&&this.metadataChanged({replayId:null}),this.statusCorrente=e.status,e.host!==void 0&&(this.hostCorrente=e.host),this.resultCorrente=Z(e.result),e.status==="finished"&&(this.pulisciInput(),this.clearRoleRequests()),e.status==="ended"?(this.terminata=!0,this.clearRoleRequests(),this.segnalaStanza(null),this.spettatore||this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),this.fermaInput(),this.ultimoInput=null):this.avviaPing(),this.metadataChanged({rematch:e.rematch??null,host:this.hostCorrente,countdownAt:e.countdownAt??(e.status==="countdown"?e.at:null),...e.status==="ended"?{connection:"ended",closedCode:4004}:{}}),this.notifica(this.ascoltatoriStatus,this.statusCorrente,this.resultCorrente,e.at)}riceviDiff(e){if(this.aggiornaTickRate(e.tickRate),e.base!==this.tickCorrente){this.chiediResync();return}let t=_e(this.statoSincronizzato,e.patch);if(!t.ok){this.chiediResync();return}this.resyncRichiesto=!1,this.aggiornaStato(t.state,e.tick,e.serverTime)}riceviSnapshot(e){e.tick<this.tickCorrente||(this.aggiornaTickRate(e.tickRate),this.resyncRichiesto=!1,this.aggiornaStato(e.state,e.tick,e.serverTime))}aggiornaStato(e,t,i){this.statoSincronizzato=Z(e),this.statoPubblico=Z(e),this.tickCorrente=t,this.notifica(this.ascoltatoriStato,this.statoPubblico,t,i)}chiediResync(){if(!(this.resyncRichiesto||this.socket?.readyState!==ne)){this.resyncRichiesto=!0;try{this.invia({t:"resync"})}catch{this.resyncRichiesto=!1}}}riceviPong(e){let t=this.dipendenze.ora();if(!Number.isFinite(e.c)||!Number.isFinite(e.s)||e.c>t)return;let i=t-e.c;this.latenzaCorrente=this.latenzaCorrente===null?i:this.latenzaCorrente*.8+i*.2,this.scartoOrario=e.s-(e.c+t)/2}chiuso(e,t){if(this.socket=null,this.welcomeRicevuto=!1,this.latenzaCorrente=null,this.fermaInput(),this.inputInviato=null,this.ultimoInvioGioco=-1/0,this.inviiGioco=[],this.fermaPing(),!(this.lasciata||this.terminata)){if(ni.has(e)){let i=e===4009&&t==="message_too_large"?"message_too_large":void 0;i&&this.notifica(this.errorListeners,{code:i,message:"The room message is too large."}),this.termina(e,i);return}this.clearRoleRequests(),this.spettatore||this.voice.socketDisconnesso(),this.programmaRiconnessione()}}programmaRiconnessione(){if(this.terminata||this.lasciata||this.timerRiconnessione!==null)return;this.metadataChanged({connection:"reconnecting"});let e=Math.min(this.ritardoIndice,et.length-1),t=et[e];if(this.tempoRiconnessione+t>Qt){this.termina("timeout");return}this.ritardoIndice++,this.tempoRiconnessione+=t,this.timerRiconnessione=this.dipendenze.setTimeout(()=>{this.timerRiconnessione=null,this.riconnetti()},t)}async riconnetti(){if(!(this.terminata||this.lasciata))try{let e=this.spettatore?await this.api.watchRoom(this.roomId):await this.api.joinRoom(this.roomId);if(this.terminata||this.lasciata)return;let t=this.codice!==e.code;this.codice=e.code,t&&this.prontaRisolta&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.apri(e.url)}catch(e){e instanceof Error&&"code"in e&&["version_mismatch","version_outdated","room_not_found"].includes(String(e.code))?(this.notifica(this.errorListeners,{code:String(e.code),message:e.message}),this.termina(4004,String(e.code))):this.programmaRiconnessione()}}fermaRiconnessione(){this.timerRiconnessione!==null&&(this.dipendenze.clearTimeout(this.timerRiconnessione),this.timerRiconnessione=null)}termina(e,t){this.clearRoleRequests(),this.metadataChanged({connection:e===1e3?"disconnected":e===4006?"replaced":"closed",closedCode:typeof e=="number"?e:null});let i={closed:e},r=this.statusCorrente!=="ended"||JSON.stringify(this.resultCorrente)!==JSON.stringify(i);if(this.terminata=!0,this.fermaInput(),this.ultimoInput=null,this.segnalaStanza(null),this.statusCorrente="ended",this.resultCorrente=i,this.spettatore||this.voice.termina(),this.fermaPing(),this.fermaRiconnessione(),r&&this.notifica(this.ascoltatoriStatus,"ended",i,this.serverTime()),!this.prontaRisolta){this.prontaRisolta=!0;let o=t??(typeof e=="number"?{4003:"kicked",4004:"room_ended",4005:"version_closed",4006:"replaced",4008:"rate_limited",4009:"invalid_request"}[e]??"offline":"offline");this.rifiutaPronta(p(o,"The room connection ended."))}}risolviProntaSePossibile(){this.prontaRisolta||!this.welcomeRicevuto||!this.rosterRicevuto||(this.timerRoster!==null&&(this.dipendenze.clearTimeout(this.timerRoster),this.timerRoster=null),this.prontaRisolta=!0,!this.spettatore&&!this.terminata&&!this.lasciata&&this.segnalaStanza({code:this.codice}),this.risolviPronta())}richiediFlush(){this.flushRichiesto=!0,!(this.flushInCorso||this.timerFlush!==null)&&(this.timerFlush=this.dipendenze.setTimeout(()=>{this.timerFlush=null,this.eseguiFlush()},ti))}async eseguiFlush(){if(!(this.flushInCorso||!this.flushRichiesto)){this.flushInCorso=!0,this.flushRichiesto=!1;try{await this.api.flush(this.roomId)}catch{}finally{this.flushInCorso=!1,this.flushRichiesto&&this.richiediFlush()}}}};function he(n=null){return{replay:!1,invited:n,reload(){typeof window<"u"&&window.location.reload()},onError(){return()=>{}},async create(){throw $()},async join(){throw $()},async watch(){throw $()},async match(){throw $()}}}function it(n,e){let t,i=new Set,r=si({...n,onVersionError(d,u){t=u;for(let v of i)try{v(d)}catch{}}}),s=!1,o=null,a=d=>{let u=d?.code??null;s&&u===o||(s=!0,o=u,n.segnalaStanza?.(d))},c=async d=>{let u=new Se(d.roomId,d.code,d.url,n,r,a);return await u.pronta(),u},m=async d=>{let u=new Se(d.roomId,d.code,d.url,n,r,()=>{},!0);return await u.pronta(),{role:"spectator",replay:!1,get mode(){return u.mode},get countdownAt(){return u.countdownAt},get connection(){return u.connection},get metadata(){return u.metadata},onMetadata:v=>u.onMetadata(v),onConnection:v=>u.onConnection(v),disconnect:()=>u.disconnect(),get state(){return u.state},get tick(){return u.tick},get tickRate(){return u.tickRate},get latency(){return u.latency},get seed(){return u.seed},get status(){return u.status},get players(){return u.players},get host(){return u.host},get code(){return u.code},get result(){return u.result},get delayMs(){return u.delayMs},onState:v=>u.onState(v),onPlayers:v=>u.onPlayers(v),onStatus:v=>u.onStatus(v),onMessage:v=>u.onMessage(v),leave:()=>{u.leave()},serverTime:()=>u.serverTime()}},h=(d,u)=>new Promise((v,x)=>{let w,N=!1,_=()=>{w.removeEventListener("message",W),w.removeEventListener("close",U),w.removeEventListener("error",F),u.signal?.removeEventListener("abort",B)},j=()=>{try{w.close(1e3)}catch{}},z=(A,M)=>{N||(N=!0,_(),M&&j(),x(A))};function B(){z(p("cancelled","The matchmaking search was cancelled."),!0)}function U(){z($(),!1)}function F(){z($(),!0)}function W(A){let M=null;try{M=typeof A.data=="string"?Q(JSON.parse(A.data)):null}catch{}if(M===null||typeof M.t!="string"){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}if(M.t==="waiting"){if(!Number.isInteger(M.players)||!Number.isInteger(M.min)||!Number.isInteger(M.max)){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}try{u.onWaiting?.({players:M.players,min:M.min,max:M.max})}catch{}return}if(M.t==="matched"){if(!tt(M)){z(p("internal_error","The matchmaking service sent an invalid message."),!0);return}N=!0,_(),j(),v(M);return}if(M.t==="no_match"){z(p("no_match","No match was found before the timeout."),!0);return}if(M.t==="error"){z(p(typeof M.code=="string"?M.code:"internal_error",typeof M.message=="string"?M.message:"The matchmaking service could not complete the search."),!0);return}M.t!=="pong"&&z(p("internal_error","The matchmaking service sent an invalid message."),!0)}try{w=n.apriSocket(d)}catch{x($());return}w.addEventListener("message",W),w.addEventListener("close",U),w.addEventListener("error",F),u.signal?.addEventListener("abort",B,{once:!0}),u.signal?.aborted===!0&&B()});return{replay:!1,invited:e,reload(){n.reload?.(t)},onError(d){return i.add(d),()=>{i.delete(d)}},async create(d){return c(await r.create(d.mode))},async join(d){let u=d??e;if(u==null||u.length===0)throw p("invalid_request","A room invitation code is required.");return c(await r.joinCode(u))},async watch(d){if(typeof d!="string"||d.length===0)throw p("invalid_request","A room invitation code is required.");return m(await r.watchCode(d))},async match(d){let u=()=>d.signal?.aborted===!0;if(u())throw p("cancelled","The matchmaking search was cancelled.");let v=await r.match(d);if(u())throw p("cancelled","The matchmaking search was cancelled.");return c(await h(v.url,d))}}}var K=()=>p("replay_invalid","The replay is incomplete or invalid.");function q(n,...e){for(let t of n)try{t(...e)}catch{}}function le(n,e){return n.add(e),()=>{n.delete(e)}}var li={now:()=>performance.now(),setInterval:(n,e)=>globalThis.setInterval(n,e),clearInterval:n=>globalThis.clearInterval(n)},ze=class{constructor(e,t,i=li){this.index=e;this.events=t;this.clock=i;this.replay=!0;this.role="spectator";this.delayMs=0;this.code="";this.latency=null;this.countdownAt=null;this.cursor=1;this.position=0;this.paused=!0;this.speedValue=1;this.timer=null;this.last=0;this.lastEmitted=-1/0;this.disconnected=!1;this.checkpoints=[];this.states=new Set;this.playersListeners=new Set;this.statuses=new Set;this.metadataListeners=new Set;this.connections=new Set;this.playbackListeners=new Set;this.step=()=>{let e=this.clock.now();this.position=Math.min(this.index.durationMs,this.position+Math.max(0,e-this.last)*this.speedValue),this.last=e,this.advance(!0),this.position>=this.index.durationMs&&this.pause(),e-this.lastEmitted>=100&&(this.lastEmitted=e,q(this.playbackListeners,this.playback))};if(t[0]?.message.t!=="start"||t[0].at!==0||t[0].message.room.id!==e.roomId)throw K();let r=t[0].message;this.picture=structuredClone({room:r.room,players:r.players,state:r.state,result:null}),this.checkpoints.push({cursor:1,at:0,picture:structuredClone(this.picture)});let s=Math.max(1,Math.ceil(t.length/32)),o=0;for(let a=1;a<t.length;a++){let c=t[a];if(!Number.isFinite(c.at)||c.at<o||c.at>e.durationMs||c.message.t==="start")throw K();this.apply(c.message,!1),a%s===0&&this.checkpoints.push({cursor:a+1,at:c.at,picture:structuredClone(this.picture)}),o=c.at}this.seek(0)}get mode(){return this.picture.room.mode}get connection(){return this.disconnected?"disconnected":"connected"}get metadata(){return{host:this.host,mode:this.mode,countdownAt:null,configuration:null,rematch:null,connection:this.connection,closedCode:null}}get state(){return structuredClone(this.picture.state)}get tick(){return this.picture.room.tick}get tickRate(){return this.picture.room.tickRate}get seed(){return this.picture.room.seed}get status(){return this.picture.room.status}get players(){return structuredClone(this.picture.players)}get host(){return this.picture.room.host}get result(){return structuredClone(this.picture.result)}get playback(){return{positionMs:this.position,durationMs:this.index.durationMs,speed:this.speedValue,paused:this.paused,truncated:this.index.truncated}}serverTime(){return this.index.startedAt+this.position}onState(e){return le(this.states,e)}onStatus(e){return le(this.statuses,e)}onPlayers(e){return le(this.playersListeners,e)}onMetadata(e){return le(this.metadataListeners,e)}onConnection(e){return le(this.connections,e)}onMessage(e){return()=>{}}onPlayback(e){return le(this.playbackListeners,e)}apply(e,t){let i=this.picture;switch(e.t){case"start":throw K();case"snapshot":i.state=structuredClone(e.state);break;case"state":{if(i.room.tick!==e.base)throw K();let r=_e(i.state,e.patch);if(!r.ok)throw K();i.state=r.state;break}case"players":i.players=structuredClone(e.players),e.host!==void 0&&(i.room.host=e.host),t&&q(this.playersListeners,this.players);return;case"status":i.room.status=e.status,i.result=structuredClone(e.result),e.host!==void 0&&(i.room.host=e.host),t&&q(this.statuses,this.status,this.result,e.at);return;default:throw K()}i.room.tick=e.tick,i.room.serverTime=e.serverTime,i.room.tickRate=e.tickRate??i.room.tickRate,t&&q(this.states,this.state,this.tick,e.serverTime)}seek(e){if(!Number.isFinite(e)||this.disconnected)return;this.position=Math.max(0,Math.min(e,this.index.durationMs));let t=[...this.checkpoints].reverse().find(i=>i.at<=this.position);this.picture=structuredClone(t.picture),this.cursor=t.cursor,this.advance(!1),this.last=this.clock.now(),q(this.playersListeners,this.players),q(this.statuses,this.status,this.result,this.serverTime()),q(this.states,this.state,this.tick,this.serverTime()),q(this.metadataListeners,this.metadata),this.position>=this.index.durationMs&&this.pause(),q(this.playbackListeners,this.playback)}advance(e){for(;this.events[this.cursor]&&this.events[this.cursor].at<=this.position;)this.apply(this.events[this.cursor++].message,e)}play(){!this.paused||this.disconnected||this.index.durationMs===0||(this.position>=this.index.durationMs&&this.seek(0),this.paused=!1,this.last=this.clock.now(),this.timer=this.clock.setInterval(this.step,16),q(this.playbackListeners,this.playback))}pause(){this.timer!==null&&this.clock.clearInterval(this.timer),this.timer=null,this.paused=!0,q(this.playbackListeners,this.playback)}speed(e){if(![.5,1,2,4].includes(e))throw K();this.paused||this.step(),this.speedValue=e,q(this.playbackListeners,this.playback)}disconnect(){this.disconnected||(this.pause(),this.disconnected=!0,q(this.connections,this.connection),q(this.metadataListeners,this.metadata))}leave(){this.disconnect()}};async function rt(n,e){let t=await n(e,{credentials:"omit",cache:"no-store"});if(!t.ok)throw p("replay_unavailable","This replay is no longer available.");let i=await t.json();if(i.format!==1||!de.test(i.id)||!Number.isInteger(i.chunks)||i.chunks<1||i.chunks>Math.ceil(10485760/524288)+1||!Number.isInteger(i.bytes)||i.bytes>10485760||i.bytes<1||!Number.isFinite(i.startedAt)||!Number.isFinite(i.durationMs)||i.durationMs<0||i.durationMs>18e5)throw K();let r=[],s=0;for(let o=0;o<i.chunks;o++){let a=await n(`${e}?chunk=${o}`,{credentials:"omit",cache:"no-store"});if(!a.ok)throw K();let c=await a.text();if(s+=new TextEncoder().encode(c).byteLength,s>i.bytes||!c.endsWith(`
|
|
3
|
+
`))throw K();for(let m of c.trimEnd().split(`
|
|
4
|
+
`))r.push(JSON.parse(m))}if(s!==i.bytes)throw K();try{return new ze(i,r)}catch{throw K()}}var ci=["en","it","es","fr","de","pt","ja"];function ot(n){let e=G(n);return e&&ci.includes(e.split("-")[0])?e:"en"}function st(n,e,t="/"){let i,r=t.match(/^\/rt\/[^/]+\/[1-9][0-9]*\//)?.[0]??"/";return()=>i??(i=(async()=>{let s={};try{let o=await n(`${r}__caisual/text/${encodeURIComponent(e)}.json`);if(o.ok){let a=await o.json();Ge(a)&&(s=a)}}catch{}return(o,a={})=>Object.hasOwn(s,o)?s[o].replace(/\{([^{}]+)\}/g,(m,h)=>Object.hasOwn(a,h)?String(a[h]):m):o})())}var at="caisual-session-v1";function lt(n){let e=D(n);return!e||typeof e.code!="string"||!/^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{6}$/.test(e.code)||!(e.mode===void 0||e.mode===null||typeof e.mode=="string")?null:{version:1,code:e.code,mode:typeof e.mode=="string"?e.mode:null,updatedAt:typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?e.updatedAt:0}}function ct(n,e){let t=null,i=!1,r=Promise.resolve(),s=async()=>{let a={version:1,imported:!0,resume:t};return r=r.catch(()=>{}).then(async()=>{try{await n.set(at,a),i=!1}catch(c){throw i=!0,c}finally{e()}}),r},o=(async()=>{try{let a=await n.get(at),c=D(a);if(c?.version===1&&c.imported===!0)t=lt(c.resume);else{let m=await n.get("resume");t=lt(m),(a!==null||m!==null)&&await s()}}catch{i=!0}e()})();return{loaded:o,get value(){return t===null?null:{...t}},get error(){return i},async set(a){await o,t=a,e(),await s()}}}function X(n,e){for(let t of n)try{t(e)}catch{}}function ut(n,e=null,t=n.connected,i=null){let r=i!==null||e?.manifest.overlay?.version===1,s=e?.manifest,o={kind:"idle"},a=!1,c=0,m=0,h=null,d=null,u=null,v=null,x=[],w=!1,N="",_={inputBlocked:r,reservedRects:[],safeArea:{top:0,right:0,bottom:0,left:0}},j=new Set,z=new Set,B=new Set,U=new Set,F=new Set,W=new Set,A=null,M=()=>({local:i===null,rooms:i===null&&t,overlay:r,requestRole:o.kind==="room"&&o.room.metadata.configuration?.requestRole===!0});function ue(){if(o.kind!=="room"||!s||s.voice==="none")return null;let l=o.room,y=l.voice;return!y||y.mode==="none"||l.players.find(R=>R.id===l.you)?.role==="spectator"?null:{mode:y.mode,state:y.state,mic:y.mic,muted:y.muted,speaking:y.speaking,peers:y.peers.map(({id:R,mic:C,muted:k,speaking:ae,volume:oe})=>({id:R,mic:C,muted:k,speaking:ae,volume:oe}))}}function ee(){let l=o.kind==="room"||o.kind==="watch"?o.room:null,y=l?.metadata.configuration,R=l?Ye(l.result,l.players.map(k=>k.id)):null,C=s&&l&&(l.mode===null||s.modes.some(k=>k.id===l.mode))?Ue(s,l.mode):{players:{min:1,max:1},lobby:!1};return{kind:h??(o.kind==="idle"?a?"home":"boot":o.kind),id:o.kind==="idle"?null:o.id,mode:h?d:o.kind==="local"?o.mode:l?.mode??null,localStatus:o.kind==="local"?o.status:null,ready:a,capabilities:M(),room:l?{...l===i?{replay:i.playback}:{},...l.metadata.replayId?{replayId:l.metadata.replayId}:{},...l.metadata.rematch?.keepSetup||l.metadata.rematch?.autoStart?{rematch:l.metadata.rematch}:{},code:l.code,mode:l.mode,status:l.status,host:l.host,you:o.kind==="room"?o.room.you:null,players:l.players.map(k=>({id:k.id,name:k.name,guest:k.guest,role:k.role,team:k.team,ready:k.ready,connected:k.connected})),...R?{result:R}:{},countdownAt:l.countdownAt,connection:l.connection,closedCode:l.metadata.closedCode,limits:{...y?.players??C.players},lobby:y?.lobby??C.lobby,persistent:y?.persistent??s?.persistent??!1,delayMs:o.kind==="watch"?o.room.delayMs:null,requestRole:y?.requestRole??!1}:null,voice:h?null:ue(),waiting:u?{...u}:null,resume:A?.value??null,resumeError:A?.error??!1}}function I(){if(w)return;let l=ee(),y=JSON.stringify(l);y!==N&&(N=y,X(B,l))}function te(){X(j,{...o}),I()}function Y(){if(o.kind!=="room")throw p("no_room","There is no active player room.");return o.room}function re(){let l=Y();if(l.players.find(y=>y.id===l.you)?.role==="spectator")throw p("spectator","Spectators cannot use voice controls.");if(!s||s.voice==="none"||l.voice.mode==="none")throw p("voice_disabled","Voice is disabled for this room.");return l.voice}function H(){c++,v?.abort(),v=null,h=null,u=null,I()}function g(l){x.splice(0).forEach(y=>y()),(o.kind==="room"||o.kind==="watch")&&(l?o.room.disconnect():o.room.leave()),o={kind:"idle"},te()}async function f(l){A?.value?.code===l&&await A.set(null).catch(()=>{})}async function L(l,y,R){if(R!==c||w)throw l.leave(),p("cancelled","The operation was cancelled.");g(!1),o=y?{kind:"watch",room:l,id:String(++m)}:{kind:"room",room:l,id:String(++m)};let C=l;if(x=[C.onPlayers(I),C.onMetadata(()=>{C.connection==="disconnected"&&(o.kind==="room"||o.kind==="watch")&&o.room===C?(x.splice(0).forEach(k=>k()),!y&&C.metadata.closedCode===1e3&&f(C.code),o={kind:"idle"},te()):I()}),C.onStatus(()=>{I(),!y&&C.connection==="ended"&&f(C.code)})],l===i&&x.push(i.onPlayback(I)),!y){let k=l,ae=o.id;k.voice&&x.push(k.voice.onState(I),k.voice.onPeers(I)),x.push(k.onError(oe=>X(F,{sessionId:ae,error:{...oe}}))),x.push(k.onScoreQueued(oe=>X(W,{...oe})));for(let oe of k.queuedScores)X(W,{...oe})}return h=null,u=null,te(),!y&&A&&C.connection!=="ended"&&await A.set({version:1,code:C.code,mode:C.mode,updatedAt:n.time.now()}).catch(()=>{}),l}async function S(l,y,R,C=!1){H();let k=c;v=new AbortController,h=l,d=y,I();try{let ae=await R(v.signal,k);if(await L(ae,C,k),k!==c||w)throw p("cancelled","The operation was cancelled.");return ae}finally{k===c&&(h=null,u=null,v=null,I())}}let b=n.room,O=b.onError(l=>{!r||w||(l.code==="version_mismatch"?b.reload():l.code==="version_outdated"&&X(F,{sessionId:o.kind==="idle"?null:o.id,error:l}))}),T=i||!r?b:{invited:b.invited,reload:()=>b.reload(),onError:l=>b.onError(l),create(l){return s&&ve(s,l.mode)?Promise.reject(p("invalid_request","Local modes cannot create rooms.")):S("attaching",l.mode,()=>b.create(l))},join(l){return S("attaching",null,()=>b.join(l))},watch(l){return S("attaching",null,()=>b.watch(l),!0)},match(l){return s&&ve(s,l.mode)?Promise.reject(p("invalid_request","Local modes cannot use matchmaking.")):S("matching",l.mode,(y,R)=>{let C=()=>{c===R&&H()};return l.signal?.addEventListener("abort",C,{once:!0}),l.signal?.aborted&&C(),b.match({...l,signal:y,onWaiting(k){R===c&&(u={...k},I(),l.onWaiting?.(k))}}).finally(()=>l.signal?.removeEventListener("abort",C))})}};return r&&!i&&(A=ct(n.save,I)),i&&(a=!0,L(i,!0,c)),{session:{get current(){return{...o}},get capabilities(){return M()},onChange(l){return j.add(l),X(new Set([l]),{...o}),()=>{j.delete(l)}},ready(){w||a||(a=!0,I())},finish(){if(o.kind==="room"||o.kind==="watch")throw p("not_local","Only a local session can be finished by the client.");o.kind==="local"&&(o={...o,status:"ended"},te())}},overlay:{open(l){if(!["home","room","invite","friends","voice","boards"].includes(l))throw p("invalid_request","Unknown overlay panel.");r&&X(U,l)},onChange(l){return z.add(l),X(new Set([l]),structuredClone(_)),()=>{z.delete(l)}}},rooms:T,snapshot:ee,serverTime:()=>o.kind==="room"||o.kind==="watch"?o.room.serverTime():n.time.now(),onState(l){return B.add(l),l(ee()),()=>{B.delete(l)}},onOpen(l){return U.add(l),()=>{U.delete(l)}},onError(l){return F.add(l),()=>{F.delete(l)}},onScore(l){return W.add(l),()=>{W.delete(l)}},async execute(l){if(!r)throw p("overlay_disabled","This game uses its own room flow.");if(l.op==="overlay.view"){if(!Oe(l.args))throw p("invalid_request","The overlay geometry is invalid.");if(_={...structuredClone(l.args),safeArea:{top:0,right:0,bottom:0,left:0,...l.args.safeArea}},typeof document<"u")for(let[y,R]of Object.entries(_.safeArea))document.documentElement.style.setProperty(`--caisual-safe-${y}`,`${R}px`);X(z,structuredClone(_));return}if(l.sessionId!==void 0&&l.sessionId!==(o.kind==="idle"?null:o.id))throw p("session_replaced","The active session changed.");if(l.op.startsWith("replay.")&&(!i||o.kind!=="watch"||o.room!==i||l.sessionId!==o.id))throw p("session_replaced","The replay is no longer active.");if(i&&!l.op.startsWith("replay.")&&!["session.leave","session.disconnect"].includes(l.op))throw p("replay_readonly","Replays are read only.");if(l.op.startsWith("voice.")&&l.sessionId!==(o.kind==="idle"?null:o.id))throw p("session_replaced","The active session changed.");if(!a)throw p("game_not_ready","The game is still loading.");switch(l.op){case"replay.play":i.play();return;case"replay.pause":i.pause();return;case"replay.seek":i.seek(l.args.positionMs);return;case"replay.speed":i.speed(l.args.speed);return;case"local.start":{if(!s||!ve(s,l.args.mode))throw p("invalid_mode","This is not a local mode.");H();let y=c;if(o.kind==="room"&&await f(o.room.code),y!==c||w)throw p("cancelled","The operation was cancelled.");g(!1),o={kind:"local",id:String(++m),mode:l.args.mode,status:"playing"},te();return}case"room.create":await T.create(l.args);return;case"room.join":await T.join(l.args.code);return;case"room.watch":await T.watch(l.args.code);return;case"room.match":{let y=s?.modes.find(C=>C.id===l.args.mode),R=l.args.key??y?.matchmaking?.defaults;if(!R)throw p("invalid_request","Matchmaking needs a complete key.");await T.match({mode:l.args.mode,key:R});return}case"voice.join":{let y=Y();if(await re().join(),o.kind!=="room"||o.room!==y)throw p("session_replaced","The active session changed.");I();return}case"voice.mute":re().mute(l.args.muted),I();return;case"voice.leave":re().leave(),I();return;case"voice.setVolume":{let y=re();if(!y.peers.some(R=>R.id===l.args.playerId))throw p("voice_peer_missing","This voice participant is no longer available.");y.setVolume(l.args.playerId,l.args.volume),I();return}case"room.ready":Y().ready(l.args.ready);return;case"room.role":Y().setRole(l.args.role);return;case"room.requestRole":await Y().requestRole(l.args.role);return;case"room.team":Y().setTeam(l.args.team);return;case"room.start":Y().start();return;case"room.restart":Y().restart();return;case"session.cancel":H();return;case"session.resume":{await S("attaching",null,async y=>{if(await A?.loaded,y.aborted)throw p("cancelled","The operation was cancelled.");if(!A?.value)throw p("no_resume","There is no saved room.");return b.join(A.value.code)});return}case"session.disconnect":{H();let y=c;if(o.kind==="room"&&o.room.connection!=="ended"&&A&&await A.set({version:1,code:o.room.code,mode:o.room.mode,updatedAt:n.time.now()}),y!==c||w)throw p("cancelled","The operation was cancelled.");g(!0);return}case"session.leave":{H();let y=c;if(o.kind==="room"&&await f(o.room.code),y!==c||w)throw p("cancelled","The operation was cancelled.");g(!1);return}}},dispose(){O(),H(),g(!0),w=!0,j.clear(),z.clear(),B.clear(),U.clear(),W.clear(),F.clear()}}}function dt(n,e,t){let i=!0,r=!1,s=e.onChange(a=>{i=a.shortcutEnabled!==!1,r=a.inputBlocked}),o=a=>{let c=a.target;!i||r||a.repeat||a.key!=="Tab"||!a.shiftKey||a.ctrlKey||a.altKey||a.metaKey||c?.closest?.('input,textarea,select,[contenteditable="true"]')||(a.preventDefault(),a.stopImmediatePropagation(),t())};return n.addEventListener("keydown",o,!0),()=>{s(),n.removeEventListener("keydown",o,!0)}}function mt(n,e,t){let i=!1,r=0,s=0,o=0,a=new Map,c=d=>{if(!i)try{n.postMessage(d)}catch{}},m=[...e.configuration.manifest.overlay&&typeof window<"u"?[dt(window,t.overlay,()=>c({type:"caisual:overlay-shortcut",v:1,epoch:e.epoch}))]:[],t.onState(d=>c({type:"caisual:overlay-state",v:1,epoch:e.epoch,seq:++r,serverTime:t.serverTime(),state:d})),t.onOpen(d=>c({type:"caisual:overlay-open",v:1,epoch:e.epoch,panel:d})),t.onError(({sessionId:d,error:u})=>c({type:"caisual:overlay-error",v:1,epoch:e.epoch,sessionId:d,error:u})),t.onScore(d=>c({type:"caisual:overlay-score",v:1,epoch:e.epoch,score:d}))],h=d=>{let u=D(d.data);if(u?.type!=="caisual:overlay"||u.epoch!==e.epoch||i)return;let v={type:"caisual:overlay-response",v:1,epoch:e.epoch,requestId:typeof u.requestId=="string"?u.requestId:""};if(!Ke(u)){c({...v,ok:!1,error:{code:"invalid_request",message:"The overlay request is invalid."}});return}let x=JSON.stringify([u.op,u.args,u.sessionId]),w=a.get(u.requestId);if(w){w.fingerprint!==x?c({...v,ok:!1,error:{code:"duplicate_request",message:"The request id was already used."}}):w.response.then(c);return}if(Number(u.requestId)<=s||o>=32){c({...v,ok:!1,error:{code:"stale_request",message:"The request is stale or too many requests are pending."}});return}s=Number(u.requestId),o++;let N=Promise.resolve().then(()=>t.execute(u)).then(()=>({...v,ok:!0}),_=>({...v,ok:!1,error:{code:typeof D(_)?.code=="string"?D(_).code:"internal_error",message:_ instanceof Error?_.message:"The operation could not be completed."}}));a.set(u.requestId,{fingerprint:x,response:N}),N.then(_=>{if(o--,c(_),a.size>64)for(let j of a.keys())Number(j)<s-64&&a.delete(j)})};return n.addEventListener("message",h),n.start(),()=>{i=!0,n.removeEventListener("message",h),m.forEach(d=>d()),t.dispose(),a.clear()}}function pt(n,e,t){let i=be(n,"/api/kit",e,t);return{me:()=>i("/me","GET"),saveSet:(r,s)=>i(`/saves/${encodeURIComponent(r)}`,"PUT",{value:s}),async saveGet(r){try{return(await i(`/saves/${encodeURIComponent(r)}`,"GET")).value}catch(s){if(pe(s)==="not_found")return null;throw s}},async saveRemove(r){await i(`/saves/${encodeURIComponent(r)}`,"DELETE")},async saveList(){return(await i("/saves","GET")).saves},async boardSubmit(r,s,o){let a=await i("/scores","POST",{board:r,score:s,daily:o});return{accepted:!0,best:a.best,rank:a.rank,day:a.day,verified:a.verified}},async boardTop(r,s){if(s.day!==void 0&&(!me(s.day)||s.daily===!1))throw p("invalid_request","day must be a real UTC date and cannot be combined with daily: false.");let o=new URLSearchParams;s.day!==void 0&&o.set("day",s.day),s.daily&&o.set("daily","1"),s.limit!==void 0&&o.set("limit",String(s.limit)),s.guests&&o.set("guests","1");let a=o.size===0?"":`?${o.toString()}`,{day:c,entries:m,me:h}=await i(`/scores/${encodeURIComponent(r)}${a}`,"GET");return{day:c,entries:m,me:h}}}}function ce(n){return(Math.floor(n/864e5)+1)*864e5}function Re(n,e,t){let i=new Set,r={...n},s,o=!1;function a(){!i.size||s!==void 0||o||(s=setTimeout(c,Math.max(0,Math.min(2147483647,r.expiresAt-e()))),s.unref?.())}async function c(){s=void 0,o=!0;try{let m=await t(),h=m.day!==r.day;if(r={...m},h)for(let d of[...i])try{d({...m})}catch{}}catch{}finally{o=!1,r.expiresAt<=e()&&(r.expiresAt=e()+3e4),a()}}return{...n,random:ft(n.seed),rng:()=>ft(n.seed),onChange(m){return i.add(m),a(),()=>{i.delete(m),!i.size&&s!==void 0&&(clearTimeout(s),s=void 0)}}}}function Ve(n){return new Date(n).toISOString().slice(0,10)}async function Le(n,e,t){let i=new TextEncoder().encode(`caisual:${n}:${e}`),r=new Uint8Array(await t.digest("SHA-256",i));return(r[0]??0)*16777216+((r[1]??0)<<16)+((r[2]??0)<<8)+(r[3]??0)>>>0}function ft(n){let e=n>>>0;return()=>{e=e+1831565813>>>0;let t=e;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}}function ke(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)?n:null}function ht(n,e){return ke(n)?.type===e}function ui(n){if(typeof n!="string")return null;try{let e=new URL(n);return e.origin===n&&(e.protocol==="https:"||e.protocol==="http:")?n:null}catch{return null}}function gt(n,e,t=3e3){return new Promise(i=>{let r=!1,s=globalThis.crypto.randomUUID(),o=h=>{r||(r=!0,n.removeEventListener("message",c),n.clearTimeout(m),i(h))},a=()=>{n.parent.postMessage({type:"caisual:ready",instance:s,overlayVersion:1},e)},c=h=>{if(h.origin!==e||h.source!==n.parent)return;if(ht(h.data,"caisual:ready?")){a();return}if(!ht(h.data,"caisual:hello"))return;let d=ke(h.data),u=h.ports[0];if(typeof d?.ticket!="string"||!Ae(d.n)||u===void 0)return;u.start();let v=He(d.overlay),x=w=>Array.isArray(w)?w.map(G).filter(N=>N!==null):void 0;o({...v?{overlay:v}:{},...G(d.language)?{language:G(d.language)}:{},uiLanguage:G(d.uiLanguage)??void 0,languagePreferences:x(d.languagePreferences),gameLanguages:x(d.gameLanguages),...typeof d.replay=="string"&&de.test(d.replay)?{replay:d.replay}:{},ticket:d.ticket,n:d.n,live:ui(d.live),invite:typeof d.invite=="string"?d.invite:null,porta:u})};n.addEventListener("message",c);let m=n.setTimeout(()=>o(null),t);a()})}function di(n){let e=n.split(".")[1];if(e===void 0)return null;let t=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=");try{let i=ke(JSON.parse(globalThis.atob(t)));return typeof i?.exp=="number"&&Number.isFinite(i.exp)?i.exp*1e3:null}catch{return null}}function mi(n,e,t,i){return new Promise((r,s)=>{let o=!1,a=h=>{o||(o=!0,n.removeEventListener("message",c),e.clearTimeout(m),h===null?s(new Error("Ticket refresh timed out.")):r(h))},c=h=>{let d=ke(h.data),u=d?.aud===void 0?"portal":d.aud;d?.type==="caisual:ticket"&&u===i&&typeof d.ticket=="string"&&a(d.ticket)};n.addEventListener("message",c);let m=e.setTimeout(()=>a(null),t);try{n.postMessage(i==="live"?{type:"caisual:ticket",aud:"live"}:{type:"caisual:ticket"})}catch{a(null)}})}function $e(n,e,t,i,r=3e3,s="portal"){let o=n,a=null,c=()=>{if(a!==null)return a;let h=mi(e,t,r,s).then(d=>(o=d,d)).finally(()=>{a===h&&(a=null)});return a=h,h};return{async ottieni(){if(o===null)return c();let m=di(o);return m!==null&&m-i()<3e4?c():o},rinnova:c}}var se="caisual:save:",pi=/^[a-z0-9][a-z0-9_-]{0,31}$/;function De(n){if(!pi.test(n))throw p("invalid_request","Save keys must use lowercase letters, numbers, underscores, or hyphens.")}function yt(n){if(n===null)return null;try{return JSON.parse(n)}catch{return null}}function vt(n){let e=[];for(let t=0;t<n.length;t++){let i=n.key(t);i?.startsWith(se)&&e.push(i.slice(se.length))}return e}function fi(n,e){let t=()=>{if(n===null)throw $();return n};return{async set(i,r){De(i);let s=t(),o=JSON.stringify({value:r}),a=new TextEncoder().encode(o).byteLength;if(a>262144)throw p("payload_too_large","The save is larger than 262144 bytes.");if(s.getItem(se+i)===null&&vt(s).length>=64)throw p("save_limit","A game can store at most 64 save keys.");let c={value:r,bytes:a,updatedAt:e()};return s.setItem(se+i,JSON.stringify(c)),{key:i,bytes:a,updatedAt:c.updatedAt}},async get(i){return De(i),yt(t().getItem(se+i))?.value??null},async remove(i){De(i),t().removeItem(se+i)},async list(){let i=t();return vt(i).flatMap(r=>{let s=yt(i.getItem(se+r));return s===null?[]:[{key:r,bytes:s.bytes,updatedAt:s.updatedAt}]}).sort((r,s)=>r.key.localeCompare(s.key))}}}async function xe(n,e=null){let t=n.ora(),i=Ve(t),r=await Le(n.hostname,i,n.subtle);return{connected:!1,player:{id:"local",name:"Guest",guest:!0},daily:Re({day:i,seed:r,expiresAt:ce(t)},n.ora,async()=>{let s=n.ora(),o=Ve(s);return{day:o,seed:await Le(n.hostname,o,n.subtle),expiresAt:ce(s)}}),time:{now:n.ora},save:fi(n.archivio,n.ora),board:{async submit(){return{accepted:!1,reason:"offline",verified:!1}},async top(s,o={}){if(o.day!==void 0&&(!me(o.day)||o.daily===!1))throw p("invalid_request","day must be a real UTC date and cannot be combined with daily: false.");return{day:o.day??(o.daily?i:null),entries:[],me:null}}},room:he(e)}}function hi(n){let e=n?.querySelector('meta[name="caisual-app"]')?.getAttribute("content");if(e==null)return null;try{let t=new URL(e);return t.origin===e&&(t.protocol==="https:"||t.protocol==="http:")?e:null}catch{return null}}function gi(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function yi(){return{finestra:typeof window>"u"?null:window,documento:typeof document>"u"?null:document,fetcher:(n,e)=>globalThis.fetch(n,e),archivio:gi(),language:typeof navigator>"u"?"en":navigator.language,pathname:typeof location>"u"?"/":location.pathname,hostname:typeof location>"u"?"":location.hostname,subtle:globalThis.crypto.subtle,ora:Date.now,sonda:()=>We()}}async function vi(n){let e=hi(n.documento),t=n.finestra===null||n.finestra.parent===n.finestra;if(e===null||t)return bt(n);let i=await gt(n.finestra,e,n.timeoutHandshake);if(i===null)return bt(n);if(i.replay){let u=i.overlay?.configuration.manifest.id;if(!u)throw new Error("The replay game is missing.");let v=await rt(n.fetcher,`${e}/api/replays/${encodeURIComponent(u)}/${i.replay}`),x=await xe(n),w=he();return x.connected=!0,x.room=Object.assign(v,{invited:null,reload:()=>w.reload(),onError:w.onError,create:w.create,join:w.join,match:w.match,watch:async()=>v}),Me(x,i,n,v)}let r=$e(i.ticket,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"portal"),s=pt(e,n.fetcher,r),o=n.ora(),a;try{a=await s.me()}catch{let u=await xe(n,i.invite);return Me(u,i,n)}let c=n.ora(),m=a.serverTime-(o+c)/2,h=i.live===null?he(i.invite):it({appOrigin:e,n:i.n,reload:u=>i.porta.postMessage({type:"caisual:reload",target:u}),liveOrigin:i.live,fetcher:n.fetcher,biglietto:$e(null,i.porta,n.finestra,n.ora,n.timeoutRinnovo,"live"),apriSocket(u){if(n.apriSocket!==void 0)return n.apriSocket(u);if(typeof WebSocket>"u")throw $();return new WebSocket(u)},ora:n.ora,setTimeout:(u,v)=>globalThis.setTimeout(u,v),clearTimeout:u=>globalThis.clearTimeout(u),setInterval:(u,v)=>globalThis.setInterval(u,v),clearInterval:u=>globalThis.clearInterval(u),voce:n.voce,segnalaStanza(u){try{i.porta.postMessage({type:"caisual:room",room:u})}catch{}}},i.invite),d={connected:!0,player:a.player,daily:Re({day:a.day,seed:a.seed,expiresAt:a.expiresAt??ce(a.serverTime)},()=>n.ora()+m,async()=>{let u=await s.me();return{day:u.day,seed:u.seed,expiresAt:u.expiresAt??ce(u.serverTime)}}),time:{now:()=>n.ora()+m},save:{set:(u,v)=>s.saveSet(u,v),get:u=>s.saveGet(u),remove:u=>s.saveRemove(u),list:()=>s.saveList()},board:{async submit(u,v,x={}){try{return await s.boardSubmit(u,v,x.daily===!0)}catch(w){if(typeof w=="object"&&w!==null&&"code"in w&&w.code==="offline")return{accepted:!1,reason:"offline",verified:!1};throw w}},top:(u,v={})=>s.boardTop(u,v)},room:h};return Me(d,i,n)}function Me(n,e,t,i=null){let r=ut(n,e?.overlay?.configuration??null,n.connected&&e?.live!=null,i);if(e?.overlay){let c=mt(e.porta,e.overlay,r);r.session.capabilities.overlay&&typeof window<"u"&&t?.finestra===window&&window.addEventListener("pagehide",c,{once:!0})}let s=e?.languagePreferences?.length?e.languagePreferences:[e?.language??t?.language??"en"],o=je(s,e?.gameLanguages??(e?.overlay?Ce(e.overlay.configuration.manifest):void 0)),a=ot(e?.uiLanguage??e?.language??t?.language);return{...n,player:{...n.player,language:o,uiLanguage:a},text:st(t?.fetcher??globalThis.fetch,o,t?.pathname),room:r.rooms,session:r.session,overlay:r.overlay}}async function bt(n){return Me(await xe(n),void 0,n)}function wt(){return{webgl2:!1,webgpu:!1,wasm:!1,threads:!1,isolated:!1,gpu:"none",memoryMb:null,cores:null,mobile:!1,tier:"low"}}async function bi(n){let e;try{return await Promise.race([Promise.resolve().then(n).catch(()=>wt()),new Promise(t=>{e=globalThis.setTimeout(()=>t(wt()),1500)})])}finally{e!==void 0&&globalThis.clearTimeout(e)}}function St(n=yi()){let e=null;return{connect(){return e??(e=Promise.all([vi(n),bi(n.sonda)]).then(([t,i])=>({...t,device:i}))),e}}}var Rt=St();globalThis.caisual=Rt;var xr=Rt;export{Rt as caisual,xr as default};
|