cotchu 0.1.0 → 0.2.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 +1 -1
- package/dist/cotchu.min.js +1 -1
- package/dist/cotchu.min.js.map +3 -3
- package/dist/index.d.ts +63 -3
- package/dist/index.js +97 -16
- package/dist/index.js.map +3 -3
- package/package.json +2 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cotchu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ No dependencies. Works in browsers and Node 22+. In plain HTML:
|
|
|
14
14
|
|
|
15
15
|
```html
|
|
16
16
|
<script type="module">
|
|
17
|
-
import { cotchu } from "https://cdn.jsdelivr.net/npm/cotchu@0.
|
|
17
|
+
import { cotchu } from "https://cdn.jsdelivr.net/npm/cotchu@0.2/dist/cotchu.min.js";
|
|
18
18
|
</script>
|
|
19
19
|
```
|
|
20
20
|
|
package/dist/cotchu.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var S=1,_e=["shared","turns","realtime","script"],N=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],G="/v1/rooms/",Y="wss://rooms.cotchu.com";var we=new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${63}}$`),E='{"t":"ping"}';function U(t){return typeof t=="string"&&_e.includes(t)}function Z(t){return typeof t=="string"&&N.includes(t)}var ke=/^[a-z0-9][a-z0-9-]{0,31}$/;function Q(t){return typeof t=="string"&&ke.test(t)}function ee(t){return typeof t=="string"&&we.test(t)}var L={FATAL:4e3,REPLACED:4001},te="leave";var f={bad_message:{fatal:!1,message:"That message isn't valid Cotchu protocol; send it through the cotchu SDK or match the formats in llms.txt."},hello_required:{fatal:!1,message:"The room hasn't had your hello yet; send a hello message first, or use cotchu.join(), which sends it for you."},unsupported_version:{fatal:!0,message:"This client speaks a different protocol version than the room; update the cotchu package to the latest."},bad_key:{fatal:!0,message:"That key isn't a valid Cotchu publishable key; pass your project's pk_ key as the key option to cotchu.join()."},bad_origin:{fatal:!0,message:"This page's website isn't on your project's allowed origins; add it to the project's allowed origins, then reload."},room_full:{fatal:!0,message:"Every seat in this room is taken; try again in a moment or join a different room name."},room_limit:{fatal:!0,message:`This project already has ${50} rooms open, its current limit; finished rooms close a minute after their last player leaves.`},type_mismatch:{fatal:!0,message:"This room already exists with a different type; join with the room's type or pick a new room name."},wrong_room_type:{fatal:!1,message:"That call doesn't work in this type of room; use set() in shared rooms, move() in turns rooms and input() in realtime rooms."},rate_limited:{fatal:!1,message:`This player sent more than ${60} messages a second; batch changes into fewer messages or send inputs on a fixed timer.`},too_large:{fatal:!1,message:`That message is over ${16384/1024} KB; send smaller changes, or split large data across several paths.`},forbidden_path:{fatal:!1,message:"This player isn't allowed to write that path; write only to paths the room's writable list allows."},bad_move:{fatal:!1,message:"That move doesn't match the room's move schema; send a move shaped the way the room's moveSchema describes."},not_your_turn:{fatal:!1,message:"It isn't this player's turn; wait for a turn event naming this player before calling move()."},balance_empty:{fatal:!0,message:"This project's Cotchu balance is empty, so new rooms can't open; top up the balance in the console."},action_rejected:{fatal:!1,message:"The room's script turned that action down; check the game's rules, or read the message the script gave."},script_error:{fatal:!1,message:"The room's script failed, so the room restarted it from its last save; try again, and fix the script if it keeps happening."},script_not_found:{fatal:!0,message:"This project has no deployed script by that name; deploy it with npx cotchu deploy room.js --name <name>, then join again."},bad_path:{fatal:!1,message:"That path runs through a value that isn't an object; set the parent to an object first, or write a different path."},unknown_player:{fatal:!1,message:"No player with that id is in the room; send direct messages only to ids from the room's player list."},internal:{fatal:!1,message:"Something went wrong inside Cotchu; retry, and if it keeps happening, report it with the room name and time."},replaced:{fatal:!0,message:"This seat was taken over by a newer connection using the same resume token; keep one connection per player."},room_closed:{fatal:!0,message:"This room is closed because you left or it ended; call cotchu.join() again to get a new room object."},unreachable:{fatal:!0,message:"Couldn't reach a Cotchu room; check the network and any url option you passed, then call cotchu.join() again."},not_found:{fatal:!0,message:"Nothing lives at that path; connect with the cotchu SDK, which opens /v1/rooms/<project>/<room> for you."},bad_room:{fatal:!0,message:"Project ids use lowercase letters and digits, and room names letters, digits, '.', '_' and '-' up to 64 characters; fix the URL."},bad_script:{fatal:!0,message:"That script couldn't be loaded; fix what the message describes in room.js, then deploy again."},bad_region:{fatal:!0,message:`That region isn't one Cotchu knows; use auto or one of ${N.join(", ")}.`},upgrade_required:{fatal:!0,message:"Rooms only speak WebSocket; open the URL with new WebSocket(), or let cotchu.join() do it for you."}},gt=Object.keys(f);function H(t){return typeof t=="string"&&Object.hasOwn(f,t)}function se(t){return H(t)&&f[t].fatal}var Se=/^pk_live_([a-z0-9]{1,32})_([A-Za-z0-9]{16,64})$/;function ne(t){return Se.exec(t)?.[1]??null}var re=["hello","patch","move","input","msg","ping","act"],oe=["welcome","patch","turn","move","snap","join","leave","msg","err","pong","ack","priv","event","sync"];var Ee=new Set(["__proto__","prototype","constructor"]),Oe="$self",xe="*";function b(t){return t.length===0?"is an empty key":t.length>128?`has a key longer than ${128} characters`:Ee.has(t)?`uses the reserved key "${t}"`:null}function ie(t){let s=t.split(".");if(s.length>16)return`has more than ${16} keys`;for(let e of s){if(e===xe||e===Oe)continue;let n=b(e);if(n)return n}return null}var ae=["object","array","string","number","integer","boolean","null"],ue=["type","enum","properties","required","additionalProperties","items","minItems","maxItems","minimum","maximum","minLength","maxLength"],ce=["minItems","maxItems","minLength","maxLength"];function le(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function $(t,s="moveSchema",e=0){if(e>8)return`${s} nests deeper than ${8} levels`;if(!le(t))return`${s} must be an object such as {"type":"integer"}`;for(let p of Object.keys(t))if(!ue.includes(p))return`${s} uses "${p.slice(0,40)}", which move schemas don't support (they support ${ue.join(", ")})`;let{type:n,enum:r,properties:o,required:i,additionalProperties:c,items:l}=t;if(n!==void 0&&!ae.includes(n))return`${s}.type must be one of ${ae.join(", ")}`;if(r!==void 0&&(!Array.isArray(r)||r.length===0))return`${s}.enum must be a non-empty list`;if(o!==void 0){if(!le(o))return`${s}.properties must be an object of schemas`;for(let[p,h]of Object.entries(o)){let W=b(p);if(W)return`${s}.properties ${W}`;let K=$(h,`${s}.properties.${p}`,e+1);if(K)return K}}if(i!==void 0&&(!Array.isArray(i)||!i.every(p=>typeof p=="string")))return`${s}.required must be a list of field names`;if(c!==void 0&&typeof c!="boolean")return`${s}.additionalProperties must be true or false`;if(l!==void 0){let p=$(l,`${s}.items`,e+1);if(p)return p}for(let p of["minimum","maximum",...ce]){let h=t[p];if(h!==void 0){if(typeof h!="number"||!Number.isFinite(h))return`${s}.${p} must be a number`;if(ce.includes(p)&&(!Number.isInteger(h)||h<0))return`${s}.${p} must be a whole number of 0 or more`}}return null}function $e(t){return t===null?"null":Array.isArray(t)?"array":typeof t=="number"?Number.isInteger(t)?"integer":"number":typeof t}function V(t,s){if(t===s)return!0;if(typeof t!="object"||typeof s!="object"||t===null||s===null||Array.isArray(t)!==Array.isArray(s))return!1;if(Array.isArray(t)&&Array.isArray(s))return t.length===s.length&&t.every((r,o)=>V(r,s[o]));let e=Object.keys(t),n=s;return e.length===Object.keys(n).length&&e.every(r=>Object.hasOwn(n,r)&&V(t[r],n[r]))}var pe=t=>t==="object"||t==="array"||t==="integer"?`an ${t}`:`a ${t}`;function R(t,s,e="move"){if(t.enum&&!t.enum.some(r=>V(r,s)))return`${e} must be one of ${t.enum.map(r=>JSON.stringify(r)).join(", ")}`;let n=$e(s);if(t.type&&n!==t.type&&!(t.type==="number"&&n==="integer"))return`${e} must be ${pe(t.type)}, not ${pe(n)}`;if(typeof s=="number"){if(t.minimum!==void 0&&s<t.minimum)return`${e} must be at least ${t.minimum}`;if(t.maximum!==void 0&&s>t.maximum)return`${e} must be at most ${t.maximum}`}if(typeof s=="string"){if(t.minLength!==void 0&&s.length<t.minLength)return`${e} must be at least ${t.minLength} characters`;if(t.maxLength!==void 0&&s.length>t.maxLength)return`${e} must be at most ${t.maxLength} characters`}if(Array.isArray(s)){if(t.minItems!==void 0&&s.length<t.minItems)return`${e} must have at least ${t.minItems} items`;if(t.maxItems!==void 0&&s.length>t.maxItems)return`${e} must have at most ${t.maxItems} items`;if(t.items)for(let[r,o]of s.entries()){let i=R(t.items,o,`${e}[${r}]`);if(i)return i}}if(n==="object"){let r=s;for(let o of t.required??[])if(!Object.hasOwn(r,o))return`${e}.${o} is missing`;for(let[o,i]of Object.entries(r)){let c=t.properties&&Object.hasOwn(t.properties,o)?t.properties[o]:void 0;if(c){let l=R(c,i,`${e}.${o}`);if(l)return l}else if(t.additionalProperties===!1)return`${e} has no field "${o.slice(0,40)}"`}}return null}function Re(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function D(t,s){return t.length+4+JSON.stringify(s).length}function q(t,s,e){let n=Object.hasOwn(t,s),r=t[s];return t[s]=e,{sizeDelta:D(s,e)-(n&&r!==void 0?D(s,r):0),undo:()=>{n&&r!==void 0?t[s]=r:delete t[s]}}}function Pe(t,s){if(!Object.hasOwn(t,s))return{sizeDelta:0,undo:()=>{}};let e=t[s],n=Object.keys(t),r=n.slice(n.indexOf(s)+1);return delete t[s],{sizeDelta:-D(s,e),undo:()=>{t[s]=e;for(let o of r){let i=t[o];delete t[o],t[o]=i}}}}function Ae(t,s,e,n){let r=t;for(let o=0;o<s.length;o++){let i=s[o],c=r[i];if(c===void 0){if(!e)return null;let l={};n.push(q(r,i,l)),r=l}else if(Re(c))r=c;else return s.slice(0,o+1).join(".")}return r}function je(t,s,e){let n=s.op==="merge"?s.path:s.path.slice(0,-1),r=Ae(t,n,s.op!=="delete",e);if(typeof r=="string")return`can't write ${s.path.join(".")||"the root"} because ${r} isn't an object; set ${r} to an object first, or write a different path.`;if(r===null)return null;switch(s.op){case"set":return e.push(q(r,s.path.at(-1),s.value)),null;case"merge":for(let[o,i]of Object.entries(s.value))e.push(q(r,o,i));return null;case"delete":return e.push(Pe(r,s.path.at(-1))),null}}function O(t,s){let e=[],n=()=>{for(let r=e.length-1;r>=0;r--)e[r]?.undo()};for(let[r,o]of s.entries()){let i=je(t,o,e);if(i)return n(),{ok:!1,message:`patch.ops[${r}] ${i}`}}return{ok:!0,sizeDelta:e.reduce((r,o)=>r+o.sizeDelta,0),undo:n}}var X=256,Le=64,He=4096,Ve=64,he=["type","seats","writable","turnMs","tickHz","moveSchema","script"],De="see the message formats in llms.txt, or send it through the cotchu SDK",d=class extends Error{constructor(e,n){super(n);this.code=e}code};function a(t,s,e=De){throw new d("bad_message",`${t} ${s}; ${e}.`)}function v(t,s,e){return{ok:!1,error:e===void 0?{code:t,message:s}:{code:t,message:s,id:e}}}function w(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function g(t){return t===void 0?"missing":typeof t=="string"?JSON.stringify(t.length>40?`${t.slice(0,40)}\u2026`:t):Array.isArray(t)?"a list":t===null?"null":typeof t=="object"?"an object":String(t)}function _(t){let s=0;for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);n<128?s+=1:n<2048?s+=2:n>=55296&&n<=56319&&(t.charCodeAt(e+1)&64512)===56320?(s+=4,e++):s+=3}return s}function qe(t){return t.length>16384?!1:t.length*3<=16384?!0:_(t)<=16384}function T(t,s,e=0){if(e>32&&a(s,`nests deeper than ${32} levels`,"flatten the data"),typeof t=="number"){Number.isFinite(t)||a(s,"has a number too large to store","send it as a string instead");return}if(!(t===null||typeof t=="string"||typeof t=="boolean")){if(Array.isArray(t)){for(let n of t)T(n,s,e+1);return}if(w(t)){for(let[n,r]of Object.entries(t)){let o=b(n);o&&a(s,o,"rename that key"),T(r,s,e+1)}return}a(s,"isn't JSON data")}}function z(t,s,e,n){return(typeof t!="number"||!Number.isInteger(t)||t<e||t>n)&&a(s,`is ${g(t)} but must be a whole number from ${e} to ${n}`,"pick a value in that range"),t}function x(t,s,e,n){return(typeof t!="string"||t.length===0||t.length>e)&&a(s,`must be text of 1 to ${e} characters`,n),t}function ze(t){if(t!==void 0)return(typeof t!="number"||!Number.isSafeInteger(t)||t<0)&&a("id",`is ${g(t)} but must be a whole number of 0 or more`,"number each message from 0 upwards"),t}function B(t,s,e){let n=`${s}.path`;Array.isArray(t)||a(n,"must be a list of keys",'for example ["players", "abc", "x"]'),t.length<e&&a(n,"is empty","name the key to change, or use merge to change the root"),t.length>16&&a(n,`has more than ${16} keys`,"keep the state flatter");let r=[];for(let o of t){typeof o!="string"&&a(n,"must contain only text keys",'write numbers as text, for example ["slots", "3"]');let i=b(o);i&&a(n,i,"pick a different key"),r.push(o)}return r}function Be(t,s){switch(w(t)||a(s,"must be an object with op and path",'"op" is "set", "merge" or "delete"'),t.op){case"set":{let e=B(t.path,s,1);"value"in t||a(`${s}.value`,"is missing",'use "delete" to remove a value');let n=t.value;return T(n,`${s}.value`),{op:"set",path:e,value:n}}case"merge":{let e=B(t.path,s,0),n=t.value;return w(n)||a(`${s}.value`,"must be an object to merge",'use "set" to store other values'),T(n,`${s}.value`),{op:"merge",path:e,value:n}}case"delete":return{op:"delete",path:B(t.path,s,1)};default:return a(`${s}.op`,`is ${g(t.op)}`,'use "set", "merge" or "delete"')}}function Fe(t){return Array.isArray(t)||a("patch.ops","must be a list of operations",'for example [{"op":"set","path":["score"],"value":1}]'),t.length===0&&a("patch.ops","is empty","include at least one operation"),t.length>64&&a("patch.ops",`has more than ${64} operations`,"split the change across several patches"),t.map((s,e)=>Be(s,`patch.ops[${e}]`))}function P(t,s){"data"in t||a(`${s}.data`,"is missing",`put the payload in "data", for example {"t":"${s}","data":{}}`);let e=t.data;return T(e,`${s}.data`),e}function Xe(t){typeof t!="string"&&a("hello.name",`is ${g(t)} but must be text`,"send the name as text");let s=t.trim();return(s.length===0||s.length>32)&&a("hello.name",`must be 1 to ${32} characters`,"shorten the player's name"),/\p{Cc}/u.test(s)&&a("hello.name","contains control characters","remove line breaks and tabs"),s}function We(t){let s="hello.room.writable";return(!Array.isArray(t)||t.length>32)&&a(s,`must be a list of up to ${32} path patterns`,'for example ["players.$self"]'),t.map((e,n)=>{let r=x(e,`${s}[${n}]`,X,'write it like "players.$self"'),o=ie(r);return o&&a(`${s}[${n}]`,o,'write it like "players.$self"'),r})}function Ke(t){let s="hello.room";w(t)||a(s,"must be an object",'for example {"type":"shared","seats":8}');for(let h of Object.keys(t))he.includes(h)||a(s,`has no option ${g(h)}`,`the options are ${he.join(", ")}`);let e={},{type:n,seats:r,writable:o,turnMs:i,tickHz:c,moveSchema:l,script:p}=t;if(n!==void 0&&(U(n)||a(`${s}.type`,`is ${g(n)}`,'use "shared", "turns", "realtime" or "script"'),e.type=n),p!==void 0?(n!==void 0&&n!=="script"&&a(`${s}.script`,"only applies to script rooms",'remove it, or set type to "script"'),Q(p)||a(`${s}.script`,`is ${g(p)}`,'use the name the script was deployed with, like "cards"'),e.type="script",e.script=p):n==="script"&&a(`${s}.script`,"is missing",'name the deployed script, like {"type":"script","script":"cards"}'),r!==void 0&&(e.seats=z(r,`${s}.seats`,1,32)),o!==void 0&&(e.writable=We(o)),i!==void 0&&(n!==void 0&&n!=="turns"&&a(`${s}.turnMs`,"only applies to turns rooms",'remove it, or set type to "turns"'),e.turnMs=z(i,`${s}.turnMs`,1e3,36e5)),c!==void 0&&(e.type!==void 0&&e.type!=="realtime"&&e.type!=="script"&&a(`${s}.tickHz`,"only applies to realtime and script rooms",'remove it, or set type to "realtime"'),e.tickHz=z(c,`${s}.tickHz`,1,30)),l!==void 0){n!==void 0&&n!=="turns"&&a(`${s}.moveSchema`,"only applies to turns rooms",'remove it, or set type to "turns"');let h=$(l,`${s}.moveSchema`);if(h)throw new d("bad_message",`${h}; fix the schema.`);_(JSON.stringify(l))>4096&&a(`${s}.moveSchema`,`is over ${4096/1024} KB`,"describe the move more simply"),e.moveSchema=l}return e}function Ge(t){let{v:s,key:e,sdk:n,name:r,token:o,resume:i,room:c}=t;if((typeof s!="number"||!Number.isInteger(s))&&a("hello.v","must be the protocol version number",`send ${S}`),s!==S)throw new d("unsupported_version",`This client speaks protocol ${s} but the room speaks ${S}; update the cotchu package to the latest.`);if(e===void 0)throw new d("bad_key","No project key was sent; pass your project's pk_ key as the key option to cotchu.join().");if(typeof e!="string"||e.length===0||e.length>X)throw new d("bad_key",f.bad_key.message);let l={t:"hello",v:s,key:e,sdk:x(n,"hello.sdk",Le,'name the client and its version, like "cotchu-js/0.1.0"')};return r!==void 0&&(l.name=Xe(r)),o!==void 0&&(l.token=x(o,"hello.token",He,"send the token as issued")),i!==void 0&&(l.resume=x(i,"hello.resume",X,"send the resume value from welcome unchanged")),c!==void 0&&(l.room=Ke(c)),l}function Ye(t,s){let e=s===void 0?{}:{id:s};switch(t.t){case"hello":return Ge(t);case"patch":return{t:"patch",...e,ops:Fe(t.ops)};case"move":return{t:"move",...e,data:P(t,"move")};case"input":return{t:"input",data:P(t,"input")};case"msg":{let n=P(t,"msg");if(t.to===void 0)return{t:"msg",...e,data:n};let r=x(t.to,"msg.to",Ve,"use a player id from the room");return{t:"msg",...e,to:r,data:n}}case"ping":return{t:"ping"};case"act":return{t:"act",...e,data:P(t,"act")};default:throw new d("bad_message",`Unknown message type ${g(t.t)}; use one of ${re.join(", ")}.`)}}function me(t){if(typeof t!="string")return t.byteLength>16384?v("too_large",f.too_large.message):v("bad_message","Binary frames aren't supported yet; send each message as a JSON text frame.");if(!qe(t))return v("too_large",f.too_large.message);let s;try{s=JSON.parse(t)}catch{return v("bad_message",`That frame isn't valid JSON; send each message as one JSON object, such as ${E}.`)}if(!w(s))return v("bad_message",`Each message must be a JSON object with a "t" field naming its type; for example ${E}.`);let e;try{return e=ze(s.id),{ok:!0,message:Ye(s,e)}}catch(n){if(n instanceof d)return v(n.code,n.message,e);throw n}}function fe(t){let s;try{s=JSON.parse(t)}catch{return v("bad_message","The room sent a frame that isn't JSON; check the SDK is pointed at a Cotchu rooms URL.")}if(!w(s)||!oe.includes(s.t)){let e=w(s)?g(s.t):"missing";return v("bad_message",`The room sent an unknown message type ${e}; update the cotchu package to the latest.`)}return{ok:!0,message:s}}var u=class extends Error{constructor(e,n){super(n??(H(e)?f[e].message:`The room reported "${e}"; update the cotchu package.`));this.code=e;this.fatal=se(e)}code;name="CotchuError";fatal};var A=class{listeners=new Map;on(s,e){let n=this.listeners.get(s);return n||this.listeners.set(s,n=new Set),n.add(e),()=>this.off(s,e)}once(s,e){let n=this.on(s,(...r)=>{n(),e(...r)});return n}off(s,e){this.listeners.get(s)?.delete(e)}emit(s,...e){let n=this.listeners.get(s);if(!n||n.size===0)return!1;for(let r of[...n])try{r(...e)}catch(o){console.error(`[cotchu] A "${String(s)}" listener threw:`,o)}return!0}};var Ue=64,ye=256;function Ze(t,s){return t.length<=s.length&&t.every((e,n)=>s[n]===e)}var j=class{constructor(s,e,n=Date.now){this.transmit=s;this.nextId=e;this.now=n;this.refilledAt=n()}transmit;nextId;now;queue=[];sizes=new WeakMap;tokens=40;refilledAt;timer;flushQueued=!1;get size(){return this.queue.length}queuedOps(){return this.queue.flatMap(s=>s.t==="patch"?s.ops:[])}addOps(s){for(let e of s){let n=_(JSON.stringify(e))+1,r=this.queue.at(-1);if(r?.t==="patch"){e.op!=="merge"&&(r.ops=r.ops.filter(c=>!Ze(e.path,c.path)));let i=r.ops.length===0?0:this.sizes.get(r)??0;if(r.ops.length<64&&i+n<=16384-Ue){r.ops.push(e),this.sizes.set(r,i+n);continue}}if(this.queue.length>=ye)return!1;let o={t:"patch",id:this.nextId(),ops:[e]};this.sizes.set(o,n),this.queue.push(o)}return this.scheduleFlush(),!0}add(s){let e=this.queue.at(-1);return s.t==="input"&&e?.t==="input"?(e.data=s.data,!0):this.queue.length>=ye?!1:(this.queue.push(s),this.scheduleFlush(),!0)}scheduleFlush(){this.flushQueued||this.timer!==void 0||(this.flushQueued=!0,queueMicrotask(()=>{this.flushQueued=!1,this.flush()}))}flush(){for(;this.queue.length>0;){let s=this.queue[0];if(s.t==="patch"&&s.ops.length===0){this.queue.shift();continue}if(!this.take()){let n=Math.ceil((1-this.tokens)*1e3/40);this.timer??=setTimeout(()=>{this.timer=void 0,this.flush()},n);return}let e=this.queue[0];if(!this.transmit(e)){this.tokens+=1;return}this.queue.shift()}}take(){let s=this.now();return this.tokens=Math.min(40,this.tokens+(s-this.refilledAt)*40/1e3),this.refilledAt=s,this.tokens<1?!1:(this.tokens-=1,!0)}clear(){this.queue.length=0,this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}};var Qe="me";function C(t,s,e,n=!1){let r=typeof t=="string"?t===""?[]:t.split(".").map(i=>i===Qe?s:i):[...t],o=JSON.stringify(typeof t=="string"?t:r);if(r.length===0&&!n)throw new u("bad_message",`${e}() needs a path such as "players.me.x"; an empty path names nothing.`);if(r.length>16)throw new u("bad_message",`${e}() path ${o} has more than ${16} keys; keep the state flatter.`);for(let i of r){if(typeof i!="string")throw new u("bad_message",`${e}() path ${o} must contain only text keys; write numbers as text.`);let c=b(i);if(c)throw new u("bad_message",`${e}() path ${o} ${c}; pick a different key.`)}return r}function k(t,s){if(t===void 0||typeof t=="function"||typeof t=="symbol")throw new u("bad_message",`${s}() needs a JSON value, not ${typeof t}; use delete() to remove a value.`);let e;try{e=JSON.stringify(t)}catch{throw new u("bad_message",`${s}() got a value that can't become JSON, such as a circular object; send plain data.`)}if(_(e)>16384)throw new u("too_large",`${s}() got a value over ${16384/1024} KB as JSON; split it across several paths.`);return JSON.parse(e)}var et=1,tt=1e4,st=15e3,nt=35e3,rt=250,ot=5e3,it=3;function at(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var J=class extends A{constructor(e,n){super();this.connection=n;this.name=e,this.outbox=new j(r=>this.transmit(r),()=>this.nextId++)}connection;name;me_={id:"",name:""};config_={type:"shared",seats:0};players_=new Map;confirmed={};view={};inflight=[];turn_={player:null};moves_=[];snap_={tick:0,players:{}};private_={};acts=new Map;outbox;nextId=1;ws=null;welcomed=!1;status_="connecting";resume;attempt=0;lastSeen=0;helloTimer;reconnectTimer;heartbeat;settle;refusal;open(){return new Promise((e,n)=>{this.settle={resolve:e,reject:n},this.resume=this.connection.seats?.take(),this.connect()})}get me(){return this.me_}get state(){return this.view}get players(){return[...this.players_.values()]}get config(){return this.config_}get status(){return this.status_}get turn(){return this.turn_.player}get isMyTurn(){return this.turn_.player!==null&&this.turn_.player===this.me_.id}get deadline(){return this.turn_.deadline??null}get moves(){return this.moves_}get inputs(){return this.snap_.players}get private(){return this.private_}get tick(){return this.snap_.tick}on(e,n){let r=super.on(e,n);return(e==="state"||e==="change")&&queueMicrotask(()=>{this.status_!=="closed"&&(e==="state"?n(this.view,{ops:[],by:null,reset:!0}):n())}),r}set(e,n){this.write("set",{op:"set",path:C(e,this.me_.id,"set"),value:k(n,"set")})}merge(e,n){let r=k(n,"merge");if(!at(r))throw new u("bad_message","merge() needs a plain object such as { x: 1 }; use set() for other values.");this.write("merge",{op:"merge",path:C(e,this.me_.id,"merge",!0),value:r})}delete(e){this.write("delete",{op:"delete",path:C(e,this.me_.id,"delete")})}send(e,n){let r={t:"msg",data:k(e,"send")};n!==void 0&&(r.to=typeof n=="string"?n:n.id),this.enqueue("send",r)}move(e){this.ensureOpen("move"),this.ensureType("move","turns");let n=k(e,"move");if(!this.isMyTurn){let i=this.turn_.player===null?null:this.players_.get(this.turn_.player);throw new u("not_your_turn",i?`It's ${i.name}'s turn, not yours; wait for the turn event, or check room.isMyTurn before calling move().`:"It isn't your turn; wait for the turn event, or check room.isMyTurn before calling move().")}let r=this.config_.moveSchema,o=r?R(r,n):null;if(o)throw new u("bad_move",`${o}; send a move that matches the room's moveSchema.`);this.enqueue("move",{t:"move",id:this.nextId++,data:n})}act(e){this.ensureOpen("act"),this.ensureType("act","script");let n=this.nextId++,r={t:"act",id:n,data:k(e,"act")};return new Promise((o,i)=>{this.acts.set(n,{resolve:o,reject:i});try{this.enqueue("act",r)}catch(c){this.acts.delete(n),i(c)}})}input(e){this.ensureOpen("input"),this.config_.type!=="script"&&this.ensureType("input","realtime");let n=k(e,"input");if(_(JSON.stringify(n))>1024)throw new u("too_large",`input() got more than ${1024/1024} KB; send only what changes each frame, such as keys held or a direction.`);this.enqueue("input",{t:"input",data:n})}ensureType(e,n){if(this.config_.type!==n)throw new u("wrong_room_type",n==="script"?`${e}() only works in script rooms and this is a ${this.config_.type} room; join with a deployed script, like cotchu.join(name, { key, script: "cards" }).`:`${e}() only works in ${n} rooms and this is a ${this.config_.type} room; create the room with type "${n}", or use set() here.`)}leave(){if(this.status_==="closed")return;this.connection.seats?.forget(),this.outbox.flush();let e=this.ws;if(this.shutDown(),e)try{e.close(1e3,te)}catch{}}ensureOpen(e){if(this.status_==="closed")throw new u("room_closed",`${e}() can't run because this room is closed; call cotchu.join() again.`)}write(e,n){if(this.ensureOpen(e),this.config_.type==="script")throw new u("wrong_room_type",`${e}() doesn't work in script rooms, where the script owns the state; send what the player did with room.act().`);let r=this.view===this.confirmed?structuredClone(this.confirmed):this.view,o=O(r,[n]);if(!o.ok)throw new u("bad_path",o.message.replace(/^patch\.ops\[0\] /,`${e}() `));if(!this.outbox.addOps([n]))throw o.undo(),this.backlogError(e);this.view=r,this.emit("state",this.view,{ops:[n],by:this.me_.id,reset:!1}),this.emit("change")}enqueue(e,n){if(this.ensureOpen(e),!this.outbox.add(n))throw this.backlogError(e)}backlogError(e){return new u("rate_limited",`${e}() was dropped because too many messages are waiting to send; send less often, or wait for status "connected".`)}transmit(e){let n=this.ws;if(!n||!this.welcomed||n.readyState!==et)return!1;try{n.send(JSON.stringify(e))}catch{return!1}return e.t==="patch"&&e.id!==void 0&&this.inflight.push({id:e.id,ops:e.ops}),!0}connect(){let{url:e,hello:n,WebSocket:r}=this.connection,o;try{o=new r(e)}catch{return this.fail(new u("unreachable",`Couldn't open a WebSocket to ${e}; check the url option if you passed one.`))}this.ws=o,this.welcomed=!1,o.onopen=()=>{this.ws===o&&o.send(JSON.stringify(this.resume?{...n,resume:this.resume}:n))},o.onmessage=i=>{this.ws===o&&this.receive(typeof i.data=="string"?i.data:"")},o.onclose=i=>{this.ws===o&&this.dropped(i.code)},o.onerror=()=>{},this.helloTimer=setTimeout(()=>{this.ws===o&&!this.welcomed&&this.abandon(o)},tt)}abandon(e){e.onopen=e.onmessage=e.onclose=null;try{e.close()}catch{}this.ws===e&&this.dropped(1006)}dropped(e){if(this.stopTimers(),this.ws=null,this.welcomed=!1,this.status_==="closed")return;if(e===L.FATAL)return this.fail(new u("internal","The room closed this connection; call cotchu.join() again."));if(e===L.REPLACED)return this.fail(new u("replaced"));if(this.attempt++,this.settle&&this.attempt>=it)return this.fail(this.refusal??new u("unreachable",`Couldn't reach a Cotchu room at ${this.connection.url}; check the network (and the url option, if you passed one), then call cotchu.join() again.`));this.settle||this.setStatus("reconnecting");let n=Math.min(ot,rt*2**(this.attempt-1))*(.5+Math.random()/2);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},n)}fail(e){if(this.status_==="closed")return;let n=this.ws;if(this.shutDown(),n){n.onopen=n.onmessage=n.onclose=null;try{n.close()}catch{}}let r=this.settle;this.settle=void 0,r?r.reject(e):this.report(e)}shutDown(){this.settleActs(new u("room_closed","The room closed before it answered this action; join again to keep playing.")),this.connection.seats?.forget(),this.stopTimers(),this.outbox.clear(),this.ws=null,this.welcomed=!1,this.setStatus("closed")}stopTimers(){this.helloTimer!==void 0&&clearTimeout(this.helloTimer),this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.helloTimer=this.reconnectTimer=this.heartbeat=void 0}startHeartbeat(){this.lastSeen=Date.now(),this.heartbeat=setInterval(()=>{let e=this.ws;if(e){if(Date.now()-this.lastSeen>nt)return this.abandon(e);try{e.send(E)}catch{}}},st)}setStatus(e){this.status_!==e&&(this.status_=e,this.emit("status",e),this.emit("change"))}report(e){this.emit("error",e)||console.warn(`[cotchu] ${e.code}: ${e.message}`)}receive(e){this.lastSeen=Date.now();let n=fe(e);if(!n.ok)return this.report(new u(n.error.code,n.error.message));let r=n.message;switch(r.t){case"welcome":return this.welcome(r);case"patch":return this.patched(r);case"err":return this.errored(r);case"join":this.players_.set(r.player.id,r.player),this.emit("join",r.player),this.emit("change");return;case"leave":if(this.players_.delete(r.player.id),Object.hasOwn(this.snap_.players,r.player.id)){let{[r.player.id]:o,...i}=this.snap_.players;this.snap_={tick:this.snap_.tick,players:i}}this.emit("leave",r.player),this.emit("change");return;case"msg":this.emit("message",r.data,this.playerFor(r.from));return;case"turn":this.turn_=r.deadline===void 0?{player:r.player}:{player:r.player,deadline:r.deadline},this.emit("turn",r.player===null?null:this.playerFor(r.player),r.deadline??null),this.emit("change");return;case"move":return this.moved(r);case"snap":this.snap_={tick:r.tick,players:r.players},this.emit("snap",r.players,r.tick),this.emit("change");return;case"ack":this.acts.get(r.id)?.resolve(),this.acts.delete(r.id);return;case"priv":{if(!O(this.private_,r.ops).ok){this.report(new u("internal","This copy of your private state fell out of sync; reconnecting to fix it.")),this.ws&&this.abandon(this.ws);return}this.emit("change");return}case"event":this.emit("event",r.name,r.data);return;case"sync":this.confirmed=r.state,this.private_=r.private,this.inflight=[],this.rebuild(),this.emit("state",this.view,{ops:[],by:null,reset:!0}),this.emit("change");return;default:return}}playerFor(e){return this.players_.get(e)??{id:e,name:e}}moved(e){if(e.n!==this.moves_.length){this.report(new u("internal","This copy of the room's moves fell out of sync; reconnecting to fix it.")),this.ws&&this.abandon(this.ws);return}this.moves_.push({by:e.by,data:e.data}),this.emit("move",e.data,this.playerFor(e.by),e.n),this.emit("change")}welcome(e){this.helloTimer!==void 0&&clearTimeout(this.helloTimer),this.helloTimer=void 0,this.welcomed=!0,this.attempt=0;let n=new Map(this.players_);this.me_=e.you,this.config_=e.config,this.resume=e.resume,this.connection.seats?.watch(()=>this.status_==="closed"?void 0:this.resume),this.players_.clear();for(let o of e.players)this.players_.set(o.id,o);this.confirmed=e.state,this.inflight=[],this.turn_=e.turn??{player:null},this.moves_=e.moves??[],this.snap_=e.snap??{tick:0,players:{}},this.private_=e.private??{},this.settleActs(new u("internal","The connection dropped before the room answered this action; check room.state, and act again if it didn't happen.")),this.rebuild(),this.startHeartbeat(),this.setStatus("connected");let r=this.settle;if(this.settle=void 0,r)r.resolve(this);else{for(let[o,i]of n)this.players_.has(o)||this.emit("leave",i);for(let[o,i]of this.players_)n.has(o)||this.emit("join",i);this.emit("state",this.view,{ops:[],by:null,reset:!0}),this.emit("change")}this.outbox.flush()}patched(e){if(!O(this.confirmed,e.ops).ok){this.report(new u("internal","This copy of the room fell out of sync; reconnecting to fix it.")),this.ws&&this.abandon(this.ws);return}let r=e.by!==null&&e.by===this.me_.id,o=e.id;r&&o!==void 0&&(this.inflight=this.inflight.filter(i=>i.id>o)),this.rebuild(),r||(this.emit("state",this.view,{ops:e.ops,by:e.by,reset:!1}),this.emit("change"))}settleActs(e){for(let[,n]of this.acts)n.reject(e);this.acts.clear()}errored(e){let n=new u(e.code,e.message),r=e.id,o=r===void 0?void 0:this.acts.get(r);if(o&&r!==void 0){this.acts.delete(r),o.reject(n);return}if(r!==void 0){let i=this.inflight.length;this.inflight=this.inflight.filter(c=>c.id!==r),this.inflight.length!==i&&(this.rebuild(),this.emit("state",this.view,{ops:[],by:null,reset:!0}),this.emit("change"))}if(n.fatal)return this.fail(n);this.settle&&(this.refusal=n),this.report(n)}rebuild(){let e=[...this.inflight.flatMap(r=>r.ops),...this.outbox.queuedOps()];if(e.length===0){this.view=this.confirmed;return}let n=structuredClone(this.confirmed);for(let r of e)O(n,[r]);this.view=n}};var I=class t{constructor(s,e){this.key=s;this.browser=e}key;browser;token;onPageHide=()=>{let s=this.token?.();s&&this.write(s)};static for(s,e){let n=globalThis;try{if(!n.sessionStorage||!n.addEventListener||!n.removeEventListener)return null;n.sessionStorage.length}catch{return null}return new t(`cotchu:seat:${s}/${e}`,n)}take(){try{let s=this.browser.sessionStorage.getItem(this.key)??void 0;return this.browser.sessionStorage.removeItem(this.key),s}catch{return}}watch(s){this.token=s,this.browser.addEventListener("pagehide",this.onPageHide)}forget(){this.token=void 0,this.browser.removeEventListener("pagehide",this.onPageHide);try{this.browser.sessionStorage.removeItem(this.key)}catch{}}write(s){try{this.browser.sessionStorage.setItem(this.key,s)}catch{}}};var ve="0.1.0";function y(t,s){throw new u(t,s)}function ut(t){let s;try{s=new URL(t.replace(/^http(s?):/,"ws$1:"))}catch{y("unreachable",`The url option ${JSON.stringify(t)} isn't a valid address; pass one like wss://rooms.example.com.`)}return s.protocol!=="ws:"&&s.protocol!=="wss:"&&y("unreachable",`The url option must start with wss:// or ws://, not ${s.protocol}//; fix the url.`),s.origin.replace(/^http/,"ws")+s.pathname.replace(/\/+$/,"")}function ct(t,s){(typeof s!="object"||s===null)&&y("bad_key",'cotchu.join() needs options with your key, like cotchu.join("lobby", { key: "pk_live_\u2026" }).');let{key:e}=s;typeof e=="string"&&e.startsWith("sk_")&&y("bad_key","That's a secret key, which must never be in game code; pass your project's pk_live_ key instead.");let n=typeof e=="string"?ne(e):null;n===null&&y("bad_key","That isn't a Cotchu publishable key; pass your project's key, which looks like pk_live_<project>_<secret>, as the key option."),ee(t)||y("bad_room",`Room name ${JSON.stringify(t)} isn't valid; use letters, digits, '.', '_' and '-', up to 64 characters, starting with a letter or digit.`);let r=s.region??"auto";r!=="auto"&&!Z(r)&&y("bad_region",`Region ${JSON.stringify(r)} isn't valid; use "auto".`);let o=s.WebSocket??globalThis.WebSocket;o||y("unreachable","This runtime has no WebSocket; use Node 22 or newer, or pass one with the WebSocket option.");let i={};s.type!==void 0&&(i.type=s.type),s.seats!==void 0&&(i.seats=s.seats),s.writable!==void 0&&(i.writable=s.writable),s.turnMs!==void 0&&(i.turnMs=s.turnMs),s.tickHz!==void 0&&(i.tickHz=s.tickHz),s.script!==void 0&&(i.script=s.script),s.moveSchema!==void 0&&(i.moveSchema=s.moveSchema);let c={t:"hello",v:S,key:e,sdk:`cotchu-js/${ve}`};s.name!==void 0&&(c.name=s.name),Object.keys(i).length>0&&(c.room=i);let l=me(JSON.stringify(c));l.ok||y(l.error.code,l.error.message.replace(/^hello\.room\./,"cotchu.join() option ").replace(/^hello\./,"cotchu.join() option "));let p=r==="auto"?"":`?region=${r}`;return{url:`${ut(s.url??Y)}${G}${n}/${t}${p}`,hello:l.message,WebSocket:o,seats:s.rememberSeat===!1?null:I.for(n,t)}}function lt(t,s){let e;try{e=ct(t,s)}catch(n){return Promise.reject(n)}return new J(t,e).open()}var es={join:lt,version:ve};export{u as CotchuError,J as Room,ve as SDK_VERSION,es as cotchu,lt as join};
|
|
1
|
+
var E=1,xe=["shared","turns","realtime","script"],D=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],Q="/v1/rooms/";var F=["auto","create","join"];function ee(e){return typeof e=="string"&&F.includes(e)}function te(e){return e.replace(/^ws(s?):\/\//,"http$1://").replace(/\/+$/,"")}var q="wss://rooms.cotchu.com";var Te=new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${63}}$`),T='{"t":"ping"}';function se(e){return typeof e=="string"&&xe.includes(e)}function ne(e){return typeof e=="string"&&D.includes(e)}var $e=/^[a-z0-9][a-z0-9-]{0,31}$/;function re(e){return typeof e=="string"&&$e.test(e)}function oe(e){return typeof e=="string"&&Te.test(e)}var z={FATAL:4e3,REPLACED:4001},ie="leave";var g={bad_message:{fatal:!1,message:"That message isn't valid Cotchu protocol; send it through the cotchu SDK or match the formats in llms.txt."},hello_required:{fatal:!1,message:"The room hasn't had your hello yet; send a hello message first, or use cotchu.join(), which sends it for you."},unsupported_version:{fatal:!0,message:"This client speaks a different protocol version than the room; update the cotchu package to the latest."},bad_key:{fatal:!0,message:"That key isn't a valid Cotchu publishable key; pass your project's pk_ key as the key option to cotchu.join()."},bad_origin:{fatal:!0,message:"This page's website isn't on your project's allowed origins; add it to the project's allowed origins, then reload."},room_full:{fatal:!0,message:"Every seat in this room is taken; try again in a moment or join a different room name."},room_exists:{fatal:!0,message:'A room with this name is already open, and this join used mode "create"; pick a new name (for a lobby code, generate another) or join it with mode "join".'},room_not_found:{fatal:!0,message:'No room with this name is open, and this join used mode "join"; check the name or code, or create the room with mode "create".'},room_limit:{fatal:!0,message:`This project already has ${50} rooms open, its current limit; finished rooms close a minute after their last player leaves.`},type_mismatch:{fatal:!0,message:"This room already exists with a different type; join with the room's type or pick a new room name."},wrong_room_type:{fatal:!1,message:"That call doesn't work in this type of room; use set() in shared rooms, move() in turns rooms and input() in realtime rooms."},rate_limited:{fatal:!1,message:`This player sent more than ${60} messages a second; batch changes into fewer messages or send inputs on a fixed timer.`},too_large:{fatal:!1,message:`That message is over ${16384/1024} KB; send smaller changes, or split large data across several paths.`},forbidden_path:{fatal:!1,message:"This player isn't allowed to write that path; write only to paths the room's writable list allows."},bad_move:{fatal:!1,message:"That move doesn't match the room's move schema; send a move shaped the way the room's moveSchema describes."},not_your_turn:{fatal:!1,message:"It isn't this player's turn; wait for a turn event naming this player before calling move()."},balance_empty:{fatal:!0,message:"This project's Cotchu balance is empty, so new rooms can't open; top up the balance in the console."},action_rejected:{fatal:!1,message:"The room's script turned that action down; check the game's rules, or read the message the script gave."},script_error:{fatal:!1,message:"The room's script failed, so the room restarted it from its last save; try again, and fix the script if it keeps happening."},script_not_found:{fatal:!0,message:"This project has no deployed script by that name; deploy it with npx cotchu deploy room.js --name <name>, then join again."},bad_path:{fatal:!1,message:"That path runs through a value that isn't an object; set the parent to an object first, or write a different path."},unknown_player:{fatal:!1,message:"No player with that id is in the room; send direct messages only to ids from the room's player list."},internal:{fatal:!1,message:"Something went wrong inside Cotchu; retry, and if it keeps happening, report it with the room name and time."},replaced:{fatal:!0,message:"This seat was taken over by a newer connection using the same resume token; keep one connection per player."},room_closed:{fatal:!0,message:"This room is closed because you left or it ended; call cotchu.join() again to get a new room object."},unreachable:{fatal:!0,message:"Couldn't reach a Cotchu room; check the network and any url option you passed, then call cotchu.join() again."},not_found:{fatal:!0,message:"Nothing lives at that path; connect with the cotchu SDK, which opens /v1/rooms/<project>/<room> for you."},bad_room:{fatal:!0,message:"Project ids use lowercase letters and digits, and room names letters, digits, '.', '_' and '-' up to 64 characters; fix the URL."},bad_script:{fatal:!0,message:"That script couldn't be loaded; fix what the message describes in room.js, then deploy again."},bad_region:{fatal:!0,message:`That region isn't one Cotchu knows; use auto or one of ${D.join(", ")}.`},upgrade_required:{fatal:!0,message:"Rooms only speak WebSocket; open the URL with new WebSocket(), or let cotchu.join() do it for you."}},kt=Object.keys(g);function $(e){return typeof e=="string"&&Object.hasOwn(g,e)}function ae(e){return $(e)&&g[e].fatal}var Re=/^pk_live_([a-z0-9]{1,32})_([A-Za-z0-9]{16,64})$/;function ue(e){return Re.exec(e)?.[1]??null}var ce=["hello","patch","move","input","msg","ping","act"],le=["welcome","patch","turn","move","snap","join","leave","msg","err","pong","ack","priv","event","sync"];var je=new Set(["__proto__","prototype","constructor"]),B="$self",X="*";function y(e){return e.length===0?"is an empty key":e.length>128?`has a key longer than ${128} characters`:je.has(e)?`uses the reserved key "${e}"`:null}function pe(e){let s=e.split(".");if(s.length>16)return`has more than ${16} keys`;for(let t of s){if(t===X||t===B)continue;let n=y(t);if(n)return n}return null}var he=["object","array","string","number","integer","boolean","null"],me=["type","enum","properties","required","additionalProperties","items","minItems","maxItems","minimum","maximum","minLength","maxLength"],fe=["minItems","maxItems","minLength","maxLength"];function de(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function j(e,s="moveSchema",t=0){if(t>8)return`${s} nests deeper than ${8} levels`;if(!de(e))return`${s} must be an object such as {"type":"integer"}`;for(let l of Object.keys(e))if(!me.includes(l))return`${s} uses "${l.slice(0,40)}", which move schemas don't support (they support ${me.join(", ")})`;let{type:n,enum:r,properties:o,required:i,additionalProperties:u,items:p}=e;if(n!==void 0&&!he.includes(n))return`${s}.type must be one of ${he.join(", ")}`;if(r!==void 0&&(!Array.isArray(r)||r.length===0))return`${s}.enum must be a non-empty list`;if(o!==void 0){if(!de(o))return`${s}.properties must be an object of schemas`;for(let[l,h]of Object.entries(o)){let x=y(l);if(x)return`${s}.properties ${x}`;let v=j(h,`${s}.properties.${l}`,t+1);if(v)return v}}if(i!==void 0&&(!Array.isArray(i)||!i.every(l=>typeof l=="string")))return`${s}.required must be a list of field names`;if(u!==void 0&&typeof u!="boolean")return`${s}.additionalProperties must be true or false`;if(p!==void 0){let l=j(p,`${s}.items`,t+1);if(l)return l}for(let l of["minimum","maximum",...fe]){let h=e[l];if(h!==void 0){if(typeof h!="number"||!Number.isFinite(h))return`${s}.${l} must be a number`;if(fe.includes(l)&&(!Number.isInteger(h)||h<0))return`${s}.${l} must be a whole number of 0 or more`}}return null}function Je(e){return e===null?"null":Array.isArray(e)?"array":typeof e=="number"?Number.isInteger(e)?"integer":"number":typeof e}function W(e,s){if(e===s)return!0;if(typeof e!="object"||typeof s!="object"||e===null||s===null||Array.isArray(e)!==Array.isArray(s))return!1;if(Array.isArray(e)&&Array.isArray(s))return e.length===s.length&&e.every((r,o)=>W(r,s[o]));let t=Object.keys(e),n=s;return t.length===Object.keys(n).length&&t.every(r=>Object.hasOwn(n,r)&&W(e[r],n[r]))}var ge=e=>e==="object"||e==="array"||e==="integer"?`an ${e}`:`a ${e}`;function A(e,s,t="move"){if(e.enum&&!e.enum.some(r=>W(r,s)))return`${t} must be one of ${e.enum.map(r=>JSON.stringify(r)).join(", ")}`;let n=Je(s);if(e.type&&n!==e.type&&!(e.type==="number"&&n==="integer"))return`${t} must be ${ge(e.type)}, not ${ge(n)}`;if(typeof s=="number"){if(e.minimum!==void 0&&s<e.minimum)return`${t} must be at least ${e.minimum}`;if(e.maximum!==void 0&&s>e.maximum)return`${t} must be at most ${e.maximum}`}if(typeof s=="string"){if(e.minLength!==void 0&&s.length<e.minLength)return`${t} must be at least ${e.minLength} characters`;if(e.maxLength!==void 0&&s.length>e.maxLength)return`${t} must be at most ${e.maxLength} characters`}if(Array.isArray(s)){if(e.minItems!==void 0&&s.length<e.minItems)return`${t} must have at least ${e.minItems} items`;if(e.maxItems!==void 0&&s.length>e.maxItems)return`${t} must have at most ${e.maxItems} items`;if(e.items)for(let[r,o]of s.entries()){let i=A(e.items,o,`${t}[${r}]`);if(i)return i}}if(n==="object"){let r=s;for(let o of e.required??[])if(!Object.hasOwn(r,o))return`${t}.${o} is missing`;for(let[o,i]of Object.entries(r)){let u=e.properties&&Object.hasOwn(e.properties,o)?e.properties[o]:void 0;if(u){let p=A(u,i,`${t}.${o}`);if(p)return p}else if(e.additionalProperties===!1)return`${t} has no field "${o.slice(0,40)}"`}}return null}function Ce(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function G(e,s){return e.length+4+JSON.stringify(s).length}function K(e,s,t){let n=Object.hasOwn(e,s),r=e[s];return e[s]=t,{sizeDelta:G(s,t)-(n&&r!==void 0?G(s,r):0),undo:()=>{n&&r!==void 0?e[s]=r:delete e[s]}}}function Ie(e,s){if(!Object.hasOwn(e,s))return{sizeDelta:0,undo:()=>{}};let t=e[s],n=Object.keys(e),r=n.slice(n.indexOf(s)+1);return delete e[s],{sizeDelta:-G(s,t),undo:()=>{e[s]=t;for(let o of r){let i=e[o];delete e[o],e[o]=i}}}}function Ne(e,s,t,n){let r=e;for(let o=0;o<s.length;o++){let i=s[o],u=r[i];if(u===void 0){if(!t)return null;let p={};n.push(K(r,i,p)),r=p}else if(Ce(u))r=u;else return s.slice(0,o+1).join(".")}return r}function Le(e,s,t){let n=s.op==="merge"?s.path:s.path.slice(0,-1),r=Ne(e,n,s.op!=="delete",t);if(typeof r=="string")return`can't write ${s.path.join(".")||"the root"} because ${r} isn't an object; set ${r} to an object first, or write a different path.`;if(r===null)return null;switch(s.op){case"set":return t.push(K(r,s.path.at(-1),s.value)),null;case"merge":for(let[o,i]of Object.entries(s.value))t.push(K(r,o,i));return null;case"delete":return t.push(Ie(r,s.path.at(-1))),null}}function R(e,s){let t=[],n=()=>{for(let r=t.length-1;r>=0;r--)t[r]?.undo()};for(let[r,o]of s.entries()){let i=Le(e,o,t);if(i)return n(),{ok:!1,message:`patch.ops[${r}] ${i}`}}return{ok:!0,sizeDelta:t.reduce((r,o)=>r+o.sizeDelta,0),undo:n}}var C=256,qe=64,ze=4096,Be=64,ye=["type","seats","writable","turnMs","tickHz","moveSchema","script","listed","listing"],Xe="see the message formats in llms.txt, or send it through the cotchu SDK",b=class extends Error{constructor(t,n){super(n);this.code=t}code};function a(e,s,t=Xe){throw new b("bad_message",`${e} ${s}; ${t}.`)}function _(e,s,t){return{ok:!1,error:t===void 0?{code:e,message:s}:{code:e,message:s,id:t}}}function M(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function f(e){return e===void 0?"missing":typeof e=="string"?JSON.stringify(e.length>40?`${e.slice(0,40)}\u2026`:e):Array.isArray(e)?"a list":e===null?"null":typeof e=="object"?"an object":String(e)}function k(e){let s=0;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);n<128?s+=1:n<2048?s+=2:n>=55296&&n<=56319&&(e.charCodeAt(t+1)&64512)===56320?(s+=4,t++):s+=3}return s}function We(e){return e.length>16384?!1:e.length*3<=16384?!0:k(e)<=16384}function P(e,s,t=0){if(t>32&&a(s,`nests deeper than ${32} levels`,"flatten the data"),typeof e=="number"){Number.isFinite(e)||a(s,"has a number too large to store","send it as a string instead");return}if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(Array.isArray(e)){for(let n of e)P(n,s,t+1);return}if(M(e)){for(let[n,r]of Object.entries(e)){let o=y(n);o&&a(s,o,"rename that key"),P(r,s,t+1)}return}a(s,"isn't JSON data")}}function U(e,s,t,n){return(typeof e!="number"||!Number.isInteger(e)||e<t||e>n)&&a(s,`is ${f(e)} but must be a whole number from ${t} to ${n}`,"pick a value in that range"),e}function O(e,s,t,n){return(typeof e!="string"||e.length===0||e.length>t)&&a(s,`must be text of 1 to ${t} characters`,n),e}function Ge(e){if(e!==void 0)return(typeof e!="number"||!Number.isSafeInteger(e)||e<0)&&a("id",`is ${f(e)} but must be a whole number of 0 or more`,"number each message from 0 upwards"),e}function Y(e,s,t){let n=`${s}.path`;Array.isArray(e)||a(n,"must be a list of keys",'for example ["players", "abc", "x"]'),e.length<t&&a(n,"is empty","name the key to change, or use merge to change the root"),e.length>16&&a(n,`has more than ${16} keys`,"keep the state flatter");let r=[];for(let o of e){typeof o!="string"&&a(n,"must contain only text keys",'write numbers as text, for example ["slots", "3"]');let i=y(o);i&&a(n,i,"pick a different key"),r.push(o)}return r}function Ke(e,s){switch(M(e)||a(s,"must be an object with op and path",'"op" is "set", "merge" or "delete"'),e.op){case"set":{let t=Y(e.path,s,1);"value"in e||a(`${s}.value`,"is missing",'use "delete" to remove a value');let n=e.value;return P(n,`${s}.value`),{op:"set",path:t,value:n}}case"merge":{let t=Y(e.path,s,0),n=e.value;return M(n)||a(`${s}.value`,"must be an object to merge",'use "set" to store other values'),P(n,`${s}.value`),{op:"merge",path:t,value:n}}case"delete":return{op:"delete",path:Y(e.path,s,1)};default:return a(`${s}.op`,`is ${f(e.op)}`,'use "set", "merge" or "delete"')}}function Ue(e){return Array.isArray(e)||a("patch.ops","must be a list of operations",'for example [{"op":"set","path":["score"],"value":1}]'),e.length===0&&a("patch.ops","is empty","include at least one operation"),e.length>64&&a("patch.ops",`has more than ${64} operations`,"split the change across several patches"),e.map((s,t)=>Ke(s,`patch.ops[${t}]`))}function J(e,s){"data"in e||a(`${s}.data`,"is missing",`put the payload in "data", for example {"t":"${s}","data":{}}`);let t=e.data;return P(t,`${s}.data`),t}function Ye(e){typeof e!="string"&&a("hello.name",`is ${f(e)} but must be text`,"send the name as text");let s=e.trim();return(s.length===0||s.length>32)&&a("hello.name",`must be 1 to ${32} characters`,"shorten the player's name"),/\p{Cc}/u.test(s)&&a("hello.name","contains control characters","remove line breaks and tabs"),s}function Ze(e){let s="hello.room.writable";return(!Array.isArray(e)||e.length>32)&&a(s,`must be a list of up to ${32} path patterns`,'for example ["players.$self"]'),e.map((t,n)=>{let r=O(t,`${s}[${n}]`,C,'write it like "players.$self"'),o=pe(r);return o&&a(`${s}[${n}]`,o,'write it like "players.$self"'),r})}function Qe(e){let s="hello.room";M(e)||a(s,"must be an object",'for example {"type":"shared","seats":8}');for(let v of Object.keys(e))ye.includes(v)||a(s,`has no option ${f(v)}`,`the options are ${ye.join(", ")}`);let t={},{type:n,seats:r,writable:o,turnMs:i,tickHz:u,moveSchema:p,script:l,listed:h,listing:x}=e;if(n!==void 0&&(se(n)||a(`${s}.type`,`is ${f(n)}`,'use "shared", "turns", "realtime" or "script"'),t.type=n),l!==void 0?(n!==void 0&&n!=="script"&&a(`${s}.script`,"only applies to script rooms",'remove it, or set type to "script"'),re(l)||a(`${s}.script`,`is ${f(l)}`,'use the name the script was deployed with, like "cards"'),t.type="script",t.script=l):n==="script"&&a(`${s}.script`,"is missing",'name the deployed script, like {"type":"script","script":"cards"}'),r!==void 0&&(t.seats=U(r,`${s}.seats`,1,32)),o!==void 0&&(t.writable=Ze(o)),i!==void 0&&(n!==void 0&&n!=="turns"&&a(`${s}.turnMs`,"only applies to turns rooms",'remove it, or set type to "turns"'),t.turnMs=U(i,`${s}.turnMs`,1e3,36e5)),u!==void 0&&(t.type!==void 0&&t.type!=="realtime"&&t.type!=="script"&&a(`${s}.tickHz`,"only applies to realtime and script rooms",'remove it, or set type to "realtime"'),t.tickHz=U(u,`${s}.tickHz`,1,30)),p!==void 0){n!==void 0&&n!=="turns"&&a(`${s}.moveSchema`,"only applies to turns rooms",'remove it, or set type to "turns"');let v=j(p,`${s}.moveSchema`);if(v)throw new b("bad_message",`${v}; fix the schema.`);k(JSON.stringify(p))>4096&&a(`${s}.moveSchema`,`is over ${4096/1024} KB`,"describe the move more simply"),t.moveSchema=p}return h!==void 0&&(typeof h!="boolean"&&a(`${s}.listed`,`is ${f(h)}`,"use true or false"),h&&(t.listed=!0)),x!==void 0&&(h===!1&&a(`${s}.listing`,"only applies to listed rooms","remove it, or drop listed: false"),t.listing=et(x),t.listed=!0),t}function et(e){let s="hello.room.listing",t=O(e,s,C,'name a state path, like "lobby"'),n=t.split(".");n.length>16&&a(s,`has more than ${16} keys`,"point at a shallower path");for(let r of n){(r===X||r===B)&&a(s,`uses "${r}", which only works in writable patterns`,'name one exact state path, like "lobby"');let o=y(r);o&&a(s,o,'name a state path, like "lobby"')}return t}function tt(e){let{v:s,key:t,sdk:n,name:r,token:o,resume:i,mode:u,room:p}=e;if((typeof s!="number"||!Number.isInteger(s))&&a("hello.v","must be the protocol version number",`send ${E}`),s!==E)throw new b("unsupported_version",`This client speaks protocol ${s} but the room speaks ${E}; update the cotchu package to the latest.`);if(t===void 0)throw new b("bad_key","No project key was sent; pass your project's pk_ key as the key option to cotchu.join().");if(typeof t!="string"||t.length===0||t.length>C)throw new b("bad_key",g.bad_key.message);let l={t:"hello",v:s,key:t,sdk:O(n,"hello.sdk",qe,'name the client and its version, like "cotchu-js/0.1.0"')};return r!==void 0&&(l.name=Ye(r)),o!==void 0&&(l.token=O(o,"hello.token",ze,"send the token as issued")),i!==void 0&&(l.resume=O(i,"hello.resume",C,"send the resume value from welcome unchanged")),u!==void 0&&(ee(u)||a("hello.mode",`is ${f(u)}`,`use ${F.map(h=>`"${h}"`).join(", ")}`),u!=="auto"&&(l.mode=u)),p!==void 0&&(l.room=Qe(p)),l}function st(e,s){let t=s===void 0?{}:{id:s};switch(e.t){case"hello":return tt(e);case"patch":return{t:"patch",...t,ops:Ue(e.ops)};case"move":return{t:"move",...t,data:J(e,"move")};case"input":return{t:"input",data:J(e,"input")};case"msg":{let n=J(e,"msg");if(e.to===void 0)return{t:"msg",...t,data:n};let r=O(e.to,"msg.to",Be,"use a player id from the room");return{t:"msg",...t,to:r,data:n}}case"ping":return{t:"ping"};case"act":return{t:"act",...t,data:J(e,"act")};default:throw new b("bad_message",`Unknown message type ${f(e.t)}; use one of ${ce.join(", ")}.`)}}function be(e){if(typeof e!="string")return e.byteLength>16384?_("too_large",g.too_large.message):_("bad_message","Binary frames aren't supported yet; send each message as a JSON text frame.");if(!We(e))return _("too_large",g.too_large.message);let s;try{s=JSON.parse(e)}catch{return _("bad_message",`That frame isn't valid JSON; send each message as one JSON object, such as ${T}.`)}if(!M(s))return _("bad_message",`Each message must be a JSON object with a "t" field naming its type; for example ${T}.`);let t;try{return t=Ge(s.id),{ok:!0,message:st(s,t)}}catch(n){if(n instanceof b)return _(n.code,n.message,t);throw n}}function ve(e){let s;try{s=JSON.parse(e)}catch{return _("bad_message","The room sent a frame that isn't JSON; check the SDK is pointed at a Cotchu rooms URL.")}if(!M(s)||!le.includes(s.t)){let t=M(s)?f(s.t):"missing";return _("bad_message",`The room sent an unknown message type ${t}; update the cotchu package to the latest.`)}return{ok:!0,message:s}}var c=class extends Error{constructor(t,n){super(n??($(t)?g[t].message:`The room reported "${t}"; update the cotchu package.`));this.code=t;this.fatal=ae(t)}code;name="CotchuError";fatal};var I=class{listeners=new Map;on(s,t){let n=this.listeners.get(s);return n||this.listeners.set(s,n=new Set),n.add(t),()=>this.off(s,t)}once(s,t){let n=this.on(s,(...r)=>{n(),t(...r)});return n}off(s,t){this.listeners.get(s)?.delete(t)}emit(s,...t){let n=this.listeners.get(s);if(!n||n.size===0)return!1;for(let r of[...n])try{r(...t)}catch(o){console.error(`[cotchu] A "${String(s)}" listener threw:`,o)}return!0}};var nt=64,ke=256;function rt(e,s){return e.length<=s.length&&e.every((t,n)=>s[n]===t)}var N=class{constructor(s,t,n=Date.now){this.transmit=s;this.nextId=t;this.now=n;this.refilledAt=n()}transmit;nextId;now;queue=[];sizes=new WeakMap;tokens=40;refilledAt;timer;flushQueued=!1;get size(){return this.queue.length}queuedOps(){return this.queue.flatMap(s=>s.t==="patch"?s.ops:[])}addOps(s){for(let t of s){let n=k(JSON.stringify(t))+1,r=this.queue.at(-1);if(r?.t==="patch"){t.op!=="merge"&&(r.ops=r.ops.filter(u=>!rt(t.path,u.path)));let i=r.ops.length===0?0:this.sizes.get(r)??0;if(r.ops.length<64&&i+n<=16384-nt){r.ops.push(t),this.sizes.set(r,i+n);continue}}if(this.queue.length>=ke)return!1;let o={t:"patch",id:this.nextId(),ops:[t]};this.sizes.set(o,n),this.queue.push(o)}return this.scheduleFlush(),!0}add(s){let t=this.queue.at(-1);return s.t==="input"&&t?.t==="input"?(t.data=s.data,!0):this.queue.length>=ke?!1:(this.queue.push(s),this.scheduleFlush(),!0)}scheduleFlush(){this.flushQueued||this.timer!==void 0||(this.flushQueued=!0,queueMicrotask(()=>{this.flushQueued=!1,this.flush()}))}flush(){for(;this.queue.length>0;){let s=this.queue[0];if(s.t==="patch"&&s.ops.length===0){this.queue.shift();continue}if(!this.take()){let n=Math.ceil((1-this.tokens)*1e3/40);this.timer??=setTimeout(()=>{this.timer=void 0,this.flush()},n);return}let t=this.queue[0];if(!this.transmit(t)){this.tokens+=1;return}this.queue.shift()}}take(){let s=this.now();return this.tokens=Math.min(40,this.tokens+(s-this.refilledAt)*40/1e3),this.refilledAt=s,this.tokens<1?!1:(this.tokens-=1,!0)}clear(){this.queue.length=0,this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}};var ot="me";function L(e,s,t,n=!1){let r=typeof e=="string"?e===""?[]:e.split(".").map(i=>i===ot?s:i):[...e],o=JSON.stringify(typeof e=="string"?e:r);if(r.length===0&&!n)throw new c("bad_message",`${t}() needs a path such as "players.me.x"; an empty path names nothing.`);if(r.length>16)throw new c("bad_message",`${t}() path ${o} has more than ${16} keys; keep the state flatter.`);for(let i of r){if(typeof i!="string")throw new c("bad_message",`${t}() path ${o} must contain only text keys; write numbers as text.`);let u=y(i);if(u)throw new c("bad_message",`${t}() path ${o} ${u}; pick a different key.`)}return r}function S(e,s){if(e===void 0||typeof e=="function"||typeof e=="symbol")throw new c("bad_message",`${s}() needs a JSON value, not ${typeof e}; use delete() to remove a value.`);let t;try{t=JSON.stringify(e)}catch{throw new c("bad_message",`${s}() got a value that can't become JSON, such as a circular object; send plain data.`)}if(k(t)>16384)throw new c("too_large",`${s}() got a value over ${16384/1024} KB as JSON; split it across several paths.`);return JSON.parse(t)}var it=1,at=1e4,ut=15e3,ct=35e3,lt=250,pt=5e3,ht=3;function mt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var H=class extends I{constructor(t,n){super();this.connection=n;this.name=t,this.outbox=new N(r=>this.transmit(r),()=>this.nextId++)}connection;name;me_={id:"",name:""};config_={type:"shared",seats:0};players_=new Map;confirmed={};view={};inflight=[];turn_={player:null};moves_=[];snap_={tick:0,players:{}};private_={};acts=new Map;outbox;nextId=1;ws=null;welcomed=!1;status_="connecting";resume;attempt=0;lastSeen=0;helloTimer;reconnectTimer;heartbeat;settle;refusal;open(){return new Promise((t,n)=>{this.settle={resolve:t,reject:n},this.resume=this.connection.seats?.take(),this.connect()})}get me(){return this.me_}get state(){return this.view}get players(){return[...this.players_.values()]}get config(){return this.config_}get status(){return this.status_}get turn(){return this.turn_.player}get isMyTurn(){return this.turn_.player!==null&&this.turn_.player===this.me_.id}get deadline(){return this.turn_.deadline??null}get moves(){return this.moves_}get inputs(){return this.snap_.players}get private(){return this.private_}get tick(){return this.snap_.tick}on(t,n){let r=super.on(t,n);return(t==="state"||t==="change")&&queueMicrotask(()=>{this.status_!=="closed"&&(t==="state"?n(this.view,{ops:[],by:null,reset:!0}):n())}),r}set(t,n){this.write("set",{op:"set",path:L(t,this.me_.id,"set"),value:S(n,"set")})}merge(t,n){let r=S(n,"merge");if(!mt(r))throw new c("bad_message","merge() needs a plain object such as { x: 1 }; use set() for other values.");this.write("merge",{op:"merge",path:L(t,this.me_.id,"merge",!0),value:r})}delete(t){this.write("delete",{op:"delete",path:L(t,this.me_.id,"delete")})}send(t,n){let r={t:"msg",data:S(t,"send")};n!==void 0&&(r.to=typeof n=="string"?n:n.id),this.enqueue("send",r)}move(t){this.ensureOpen("move"),this.ensureType("move","turns");let n=S(t,"move");if(!this.isMyTurn){let i=this.turn_.player===null?null:this.players_.get(this.turn_.player);throw new c("not_your_turn",i?`It's ${i.name}'s turn, not yours; wait for the turn event, or check room.isMyTurn before calling move().`:"It isn't your turn; wait for the turn event, or check room.isMyTurn before calling move().")}let r=this.config_.moveSchema,o=r?A(r,n):null;if(o)throw new c("bad_move",`${o}; send a move that matches the room's moveSchema.`);this.enqueue("move",{t:"move",id:this.nextId++,data:n})}act(t){this.ensureOpen("act"),this.ensureType("act","script");let n=this.nextId++,r={t:"act",id:n,data:S(t,"act")};return new Promise((o,i)=>{this.acts.set(n,{resolve:o,reject:i});try{this.enqueue("act",r)}catch(u){this.acts.delete(n),i(u)}})}input(t){this.ensureOpen("input"),this.config_.type!=="script"&&this.ensureType("input","realtime");let n=S(t,"input");if(k(JSON.stringify(n))>1024)throw new c("too_large",`input() got more than ${1024/1024} KB; send only what changes each frame, such as keys held or a direction.`);this.enqueue("input",{t:"input",data:n})}ensureType(t,n){if(this.config_.type!==n)throw new c("wrong_room_type",n==="script"?`${t}() only works in script rooms and this is a ${this.config_.type} room; join with a deployed script, like cotchu.join(name, { key, script: "cards" }).`:`${t}() only works in ${n} rooms and this is a ${this.config_.type} room; create the room with type "${n}", or use set() here.`)}leave(){if(this.status_==="closed")return;this.connection.seats?.forget(),this.outbox.flush();let t=this.ws;if(this.shutDown(),t)try{t.close(1e3,ie)}catch{}}ensureOpen(t){if(this.status_==="closed")throw new c("room_closed",`${t}() can't run because this room is closed; call cotchu.join() again.`)}write(t,n){if(this.ensureOpen(t),this.config_.type==="script")throw new c("wrong_room_type",`${t}() doesn't work in script rooms, where the script owns the state; send what the player did with room.act().`);let r=this.view===this.confirmed?structuredClone(this.confirmed):this.view,o=R(r,[n]);if(!o.ok)throw new c("bad_path",o.message.replace(/^patch\.ops\[0\] /,`${t}() `));if(!this.outbox.addOps([n]))throw o.undo(),this.backlogError(t);this.view=r,this.emit("state",this.view,{ops:[n],by:this.me_.id,reset:!1}),this.emit("change")}enqueue(t,n){if(this.ensureOpen(t),!this.outbox.add(n))throw this.backlogError(t)}backlogError(t){return new c("rate_limited",`${t}() was dropped because too many messages are waiting to send; send less often, or wait for status "connected".`)}transmit(t){let n=this.ws;if(!n||!this.welcomed||n.readyState!==it)return!1;try{n.send(JSON.stringify(t))}catch{return!1}return t.t==="patch"&&t.id!==void 0&&this.inflight.push({id:t.id,ops:t.ops}),!0}connect(){let{url:t,hello:n,WebSocket:r}=this.connection,o;try{o=new r(t)}catch{return this.fail(new c("unreachable",`Couldn't open a WebSocket to ${t}; check the url option if you passed one.`))}this.ws=o,this.welcomed=!1,o.onopen=()=>{this.ws===o&&o.send(JSON.stringify(this.resume?{...n,resume:this.resume}:n))},o.onmessage=i=>{this.ws===o&&this.receive(typeof i.data=="string"?i.data:"")},o.onclose=i=>{this.ws===o&&this.dropped(i.code)},o.onerror=()=>{},this.helloTimer=setTimeout(()=>{this.ws===o&&!this.welcomed&&this.abandon(o)},at)}abandon(t){t.onopen=t.onmessage=t.onclose=null;try{t.close()}catch{}this.ws===t&&this.dropped(1006)}dropped(t){if(this.stopTimers(),this.ws=null,this.welcomed=!1,this.status_==="closed")return;if(t===z.FATAL)return this.fail(new c("internal","The room closed this connection; call cotchu.join() again."));if(t===z.REPLACED)return this.fail(new c("replaced"));if(this.attempt++,this.settle&&this.attempt>=ht)return this.fail(this.refusal??new c("unreachable",`Couldn't reach a Cotchu room at ${this.connection.url}; check the network (and the url option, if you passed one), then call cotchu.join() again.`));this.settle||this.setStatus("reconnecting");let n=Math.min(pt,lt*2**(this.attempt-1))*(.5+Math.random()/2);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},n)}fail(t){if(this.status_==="closed")return;let n=this.ws;if(this.shutDown(),n){n.onopen=n.onmessage=n.onclose=null;try{n.close()}catch{}}let r=this.settle;this.settle=void 0,r?r.reject(t):this.report(t)}shutDown(){this.settleActs(new c("room_closed","The room closed before it answered this action; join again to keep playing.")),this.connection.seats?.forget(),this.stopTimers(),this.outbox.clear(),this.ws=null,this.welcomed=!1,this.setStatus("closed")}stopTimers(){this.helloTimer!==void 0&&clearTimeout(this.helloTimer),this.reconnectTimer!==void 0&&clearTimeout(this.reconnectTimer),this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.helloTimer=this.reconnectTimer=this.heartbeat=void 0}startHeartbeat(){this.lastSeen=Date.now(),this.heartbeat=setInterval(()=>{let t=this.ws;if(t){if(Date.now()-this.lastSeen>ct)return this.abandon(t);try{t.send(T)}catch{}}},ut)}setStatus(t){this.status_!==t&&(this.status_=t,this.emit("status",t),this.emit("change"))}report(t){this.emit("error",t)||console.warn(`[cotchu] ${t.code}: ${t.message}`)}receive(t){this.lastSeen=Date.now();let n=ve(t);if(!n.ok)return this.report(new c(n.error.code,n.error.message));let r=n.message;switch(r.t){case"welcome":return this.welcome(r);case"patch":return this.patched(r);case"err":return this.errored(r);case"join":this.players_.set(r.player.id,r.player),this.emit("join",r.player),this.emit("change");return;case"leave":if(this.players_.delete(r.player.id),Object.hasOwn(this.snap_.players,r.player.id)){let{[r.player.id]:o,...i}=this.snap_.players;this.snap_={tick:this.snap_.tick,players:i}}this.emit("leave",r.player),this.emit("change");return;case"msg":this.emit("message",r.data,this.playerFor(r.from));return;case"turn":this.turn_=r.deadline===void 0?{player:r.player}:{player:r.player,deadline:r.deadline},this.emit("turn",r.player===null?null:this.playerFor(r.player),r.deadline??null),this.emit("change");return;case"move":return this.moved(r);case"snap":this.snap_={tick:r.tick,players:r.players},this.emit("snap",r.players,r.tick),this.emit("change");return;case"ack":this.acts.get(r.id)?.resolve(),this.acts.delete(r.id);return;case"priv":{if(!R(this.private_,r.ops).ok){this.report(new c("internal","This copy of your private state fell out of sync; reconnecting to fix it.")),this.ws&&this.abandon(this.ws);return}this.emit("change");return}case"event":this.emit("event",r.name,r.data);return;case"sync":this.confirmed=r.state,this.private_=r.private,this.inflight=[],this.rebuild(),this.emit("state",this.view,{ops:[],by:null,reset:!0}),this.emit("change");return;default:return}}playerFor(t){return this.players_.get(t)??{id:t,name:t}}moved(t){if(t.n!==this.moves_.length){this.report(new c("internal","This copy of the room's moves fell out of sync; reconnecting to fix it.")),this.ws&&this.abandon(this.ws);return}this.moves_.push({by:t.by,data:t.data}),this.emit("move",t.data,this.playerFor(t.by),t.n),this.emit("change")}welcome(t){this.helloTimer!==void 0&&clearTimeout(this.helloTimer),this.helloTimer=void 0,this.welcomed=!0,this.attempt=0;let n=new Map(this.players_);this.me_=t.you,this.config_=t.config,this.resume=t.resume,this.connection.seats?.watch(()=>this.status_==="closed"?void 0:this.resume),this.players_.clear();for(let o of t.players)this.players_.set(o.id,o);this.confirmed=t.state,this.inflight=[],this.turn_=t.turn??{player:null},this.moves_=t.moves??[],this.snap_=t.snap??{tick:0,players:{}},this.private_=t.private??{},this.settleActs(new c("internal","The connection dropped before the room answered this action; check room.state, and act again if it didn't happen.")),this.rebuild(),this.startHeartbeat(),this.setStatus("connected");let r=this.settle;if(this.settle=void 0,r)r.resolve(this);else{for(let[o,i]of n)this.players_.has(o)||this.emit("leave",i);for(let[o,i]of this.players_)n.has(o)||this.emit("join",i);this.emit("state",this.view,{ops:[],by:null,reset:!0}),this.emit("change")}this.outbox.flush()}patched(t){if(!R(this.confirmed,t.ops).ok){this.report(new c("internal","This copy of the room fell out of sync; reconnecting to fix it.")),this.ws&&this.abandon(this.ws);return}let r=t.by!==null&&t.by===this.me_.id,o=t.id;r&&o!==void 0&&(this.inflight=this.inflight.filter(i=>i.id>o)),this.rebuild(),r||(this.emit("state",this.view,{ops:t.ops,by:t.by,reset:!1}),this.emit("change"))}settleActs(t){for(let[,n]of this.acts)n.reject(t);this.acts.clear()}errored(t){let n=new c(t.code,t.message),r=t.id,o=r===void 0?void 0:this.acts.get(r);if(o&&r!==void 0){this.acts.delete(r),o.reject(n);return}if(r!==void 0){let i=this.inflight.length;this.inflight=this.inflight.filter(u=>u.id!==r),this.inflight.length!==i&&(this.rebuild(),this.emit("state",this.view,{ops:[],by:null,reset:!0}),this.emit("change"))}if(n.fatal)return this.fail(n);this.settle&&(this.refusal=n),this.report(n)}rebuild(){let t=[...this.inflight.flatMap(r=>r.ops),...this.outbox.queuedOps()];if(t.length===0){this.view=this.confirmed;return}let n=structuredClone(this.confirmed);for(let r of t)R(n,[r]);this.view=n}};var V=class e{constructor(s,t){this.key=s;this.browser=t}key;browser;token;onPageHide=()=>{let s=this.token?.();s&&this.write(s)};static for(s,t){let n=globalThis;try{if(!n.sessionStorage||!n.addEventListener||!n.removeEventListener)return null;n.sessionStorage.length}catch{return null}return new e(`cotchu:seat:${s}/${t}`,n)}take(){try{let s=this.browser.sessionStorage.getItem(this.key)??void 0;return this.browser.sessionStorage.removeItem(this.key),s}catch{return}}watch(s){this.token=s,this.browser.addEventListener("pagehide",this.onPageHide)}forget(){this.token=void 0,this.browser.removeEventListener("pagehide",this.onPageHide);try{this.browser.sessionStorage.removeItem(this.key)}catch{}}write(s){try{this.browser.sessionStorage.setItem(this.key,s)}catch{}}};var Se="0.2.0";function m(e,s){throw new c(e,s)}function Ee(e,s){typeof e=="string"&&e.startsWith("sk_")&&m("bad_key","That's a secret key, which must never be in game code; pass your project's pk_live_ key instead.");let t=typeof e=="string"?ue(e):null;return t===null&&m("bad_key",`That isn't a Cotchu publishable key; pass your project's key, which looks like pk_live_<project>_<secret>, as the key option to ${s}.`),t}function Oe(e){let s;try{s=new URL(e.replace(/^http(s?):/,"ws$1:"))}catch{m("unreachable",`The url option ${JSON.stringify(e)} isn't a valid address; pass one like wss://rooms.example.com.`)}return s.protocol!=="ws:"&&s.protocol!=="wss:"&&m("unreachable",`The url option must start with wss:// or ws://, not ${s.protocol}//; fix the url.`),s.origin.replace(/^http/,"ws")+s.pathname.replace(/\/+$/,"")}function ft(e,s){(typeof s!="object"||s===null)&&m("bad_key",'cotchu.join() needs options with your key, like cotchu.join("lobby", { key: "pk_live_\u2026" }).');let{key:t}=s,n=Ee(t,"cotchu.join()");oe(e)||m("bad_room",`Room name ${JSON.stringify(e)} isn't valid; use letters, digits, '.', '_' and '-', up to 64 characters, starting with a letter or digit.`);let r=s.region??"auto";r!=="auto"&&!ne(r)&&m("bad_region",`Region ${JSON.stringify(r)} isn't valid; use "auto".`);let o=s.WebSocket??globalThis.WebSocket;o||m("unreachable","This runtime has no WebSocket; use Node 22 or newer, or pass one with the WebSocket option.");let i={};s.type!==void 0&&(i.type=s.type),s.seats!==void 0&&(i.seats=s.seats),s.writable!==void 0&&(i.writable=s.writable),s.turnMs!==void 0&&(i.turnMs=s.turnMs),s.tickHz!==void 0&&(i.tickHz=s.tickHz),s.script!==void 0&&(i.script=s.script),s.moveSchema!==void 0&&(i.moveSchema=s.moveSchema),s.listed!==void 0&&(i.listed=s.listed),s.listing!==void 0&&(i.listing=s.listing);let u={t:"hello",v:E,key:t,sdk:`cotchu-js/${Se}`};s.name!==void 0&&(u.name=s.name),s.mode!==void 0&&(u.mode=s.mode),Object.keys(i).length>0&&(u.room=i);let p=be(JSON.stringify(u));p.ok||m(p.error.code,p.error.message.replace(/^hello\.room\./,"cotchu.join() option ").replace(/^hello\./,"cotchu.join() option "));let l=r==="auto"?"":`?region=${r}`;return{url:`${Oe(s.url??q)}${Q}${n}/${e}${l}`,hello:p.message,WebSocket:o,seats:s.rememberSeat===!1?null:V.for(n,e)}}function dt(e,s){let t;try{t=ft(e,s)}catch(n){return Promise.reject(n)}return new H(e,t).open()}async function gt(e){let s=Ee(e?.key,"cotchu.rooms()"),t=e.fetch??globalThis.fetch;t||m("unreachable","This runtime has no fetch; use Node 22 or newer, or pass one with the fetch option.");let r=`${te(Oe(e.url??q))}/v1/projects/${s}/rooms?key=${encodeURIComponent(e.key)}`,o;try{o=await t(r)}catch{m("unreachable","Couldn't reach Cotchu to list rooms; check the network and any url option, then try again.")}let i=await o.json().catch(()=>null);if(o.ok&&Array.isArray(i?.rooms))return i.rooms;let u=$(i?.error)?i.error:"internal";m(u,i?.message??`Listing rooms failed with HTTP ${o.status}; try again in a moment.`)}var is={join:dt,rooms:gt,version:Se};export{c as CotchuError,H as Room,Se as SDK_VERSION,is as cotchu,dt as join,gt as rooms};
|
|
2
2
|
//# sourceMappingURL=cotchu.min.js.map
|