cotchu 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../protocol/src/limits.ts", "../../protocol/src/room.ts", "../../protocol/src/errors.ts", "../../protocol/src/keys.ts", "../../protocol/src/messages.ts", "../../protocol/src/paths.ts", "../../protocol/src/schema.ts", "../../protocol/src/state.ts", "../../protocol/src/validate.ts", "../src/errors.ts", "../src/emitter.ts", "../src/outbox.ts", "../src/paths.ts", "../src/room.ts", "../src/seat-memory.ts", "../src/index.ts"],
4
+ "sourcesContent": ["/**\n * Hard limits shared by the rooms Worker and the SDK. Change them here only.\n */\n\n/** Largest message a client may send, in UTF-8 bytes. */\nexport const MAX_MSG_BYTES = 16_384;\n\n/**\n * Most seats one room can have. 32 by the founder's decision (Nov 18, 2026),\n * after staging load tests: 32 players at 30 Hz were comfortable, 64 degraded\n * (docs/staging.md).\n */\nexport const MAX_SEATS = 32;\n\n/** Seats a room gets when the first joiner doesn't say. */\nexport const DEFAULT_SEATS = 8;\n\n/** Per-player rate limit: sustained messages per second. */\nexport const RATE_LIMIT_PER_SEC = 60;\n\n/** Per-player rate limit: messages allowed in one burst above the sustained rate. */\nexport const RATE_LIMIT_BURST = 60;\n\n/**\n * The SDK holds itself to this, below the room's limit, so messages that the\n * network delivers in a bunch still fit the room's burst allowance.\n */\nexport const CLIENT_RATE_LIMIT_PER_SEC = 40;\nexport const CLIENT_RATE_LIMIT_BURST = 40;\n\n// Abuse limits. Until billing exists, usage is paid by Cotchu, so these keep a flood or a\n// copied key from running away. They stay after launch as a second line of defence.\n\n/** New room connections allowed per IP address per minute. Generous: a classroom shares one IP. */\nexport const CONNECT_LIMIT_PER_MIN = 120;\n\n/** A connection that hasn't said hello by now is closed. Above the SDK's own 10 s hello timeout. */\nexport const HELLO_TIMEOUT_MS = 15_000;\n\n/** Most connections one room holds that haven't said hello yet. */\nexport const MAX_PENDING_CONNECTIONS = 32;\n\n/** Most rooms one project may have open at once, until per-project limits arrive with billing. */\nexport const MAX_OPEN_ROOMS_PER_PROJECT = 50;\n\n/** A player who drops keeps their seat for this long and can resume it. */\nexport const RESUME_WINDOW_MS = 60_000;\n\n/** `realtime` rooms: snapshot rate when the first joiner doesn't say. */\nexport const DEFAULT_TICK_HZ = 20;\n\n/** `realtime` rooms: slowest and fastest snapshot rates in v1. */\nexport const MIN_TICK_HZ = 1;\nexport const MAX_TICK_HZ = 30;\n\n/**\n * `realtime` rooms: largest single input, in UTF-8 bytes of JSON. Every\n * snapshot carries every player's input, up to 30 times a second, so inputs\n * stay small: keys held, a direction, an aim.\n */\nexport const MAX_INPUT_BYTES = 1_024;\n\n/** `turns` rooms: shortest and longest turn timer. No timer when unset. */\nexport const MIN_TURN_MS = 1_000;\nexport const MAX_TURN_MS = 3_600_000;\n\n/** Most keys in one state path, e.g. `players.abc.x` is 3. */\nexport const MAX_PATH_DEPTH = 16;\n\n/** Longest single key in a state path or JSON object, in characters. */\nexport const MAX_KEY_LENGTH = 128;\n\n/** Deepest nesting allowed inside any JSON value a client sends. */\nexport const MAX_VALUE_DEPTH = 32;\n\n/** Most operations in one `patch` message. */\nexport const MAX_OPS_PER_PATCH = 64;\n\n/** Largest a room's whole shared state may grow, in UTF-8 bytes of JSON. */\nexport const MAX_STATE_BYTES = 262_144;\n\n/** Most entries in a room's `writable` list. */\nexport const MAX_WRITABLE_PATTERNS = 32;\n\n/** `turns` rooms: most a room's move history may hold, in UTF-8 bytes of JSON. */\nexport const MAX_MOVES_BYTES = 262_144;\n\n/** `turns` rooms: largest move schema, in UTF-8 bytes of JSON, and its deepest nesting. */\nexport const MAX_SCHEMA_BYTES = 4_096;\nexport const MAX_SCHEMA_DEPTH = 8;\n\n/** Room scripts: largest script, in UTF-8 bytes. */\nexport const MAX_SCRIPT_BYTES = 262_144;\n\n/** Room scripts: CPU time one call into a script may use before it's stopped. */\nexport const SCRIPT_CPU_MS = 50;\n\n/** Room scripts: longest event name a script may send. */\nexport const MAX_EVENT_NAME_LENGTH = 64;\n\n/** Longest player display name, in characters. */\nexport const MAX_NAME_LENGTH = 32;\n\n/** Longest room name, in characters. */\nexport const MAX_ROOM_NAME_LENGTH = 64;\n", "import { MAX_ROOM_NAME_LENGTH } from \"./limits.js\";\n\n/** Bumped on any breaking change to the wire format. Sent as `v` in `hello`. */\nexport const PROTOCOL_VERSION = 1;\n\n/**\n * Room types. The first joiner picks one; it can't change afterwards. `script`\n * rooms run the project's own deployed room script (docs/plans/room-scripts.md).\n */\nexport const ROOM_TYPES = [\"shared\", \"turns\", \"realtime\", \"script\"] as const;\nexport type RoomType = (typeof ROOM_TYPES)[number];\n\n/**\n * Durable Object location hints. Best effort: `sam`, `afr` and `me` currently\n * place rooms elsewhere, and only the hint on a room's first request counts.\n */\nexport const REGIONS = [\n \"wnam\",\n \"enam\",\n \"sam\",\n \"weur\",\n \"eeur\",\n \"apac\",\n \"apac-ne\",\n \"apac-se\",\n \"oc\",\n \"afr\",\n \"me\",\n] as const;\nexport type Region = (typeof REGIONS)[number];\n\n/** What a client may ask for: a region, or `auto` to place the room near the first joiner. */\nexport type RegionOption = Region | \"auto\";\n\n/** Rooms live at `wss://<host>/v1/rooms/<project>/<room>`; the region goes in `?region=`. */\nexport const ROOMS_PATH_PREFIX = \"/v1/rooms/\";\n\n/** The hosted rooms service. The SDK connects here unless given a `url`. */\nexport const DEFAULT_ROOMS_URL = \"wss://rooms.cotchu.com\";\n\n/** The hosted API (projects, scripts). `npx cotchu deploy` uses it unless given `--url`. */\nexport const DEFAULT_API_URL = \"https://api.cotchu.com\";\n\n/** Room names: letters, digits, `.`, `_` and `-`, starting with a letter or digit. */\nexport const ROOM_NAME_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${MAX_ROOM_NAME_LENGTH - 1}}$`);\n\n/**\n * Keep-alive frames, byte for byte. Rooms answer the ping with the pong via\n * `setWebSocketAutoResponse`, so a keep-alive never wakes a hibernating room.\n */\nexport const PING_FRAME = '{\"t\":\"ping\"}';\nexport const PONG_FRAME = '{\"t\":\"pong\"}';\n\nexport function isRoomType(value: unknown): value is RoomType {\n return typeof value === \"string\" && (ROOM_TYPES as readonly string[]).includes(value);\n}\n\nexport function isRegion(value: unknown): value is Region {\n return typeof value === \"string\" && (REGIONS as readonly string[]).includes(value);\n}\n\n/** Deployed script names: lowercase letters, digits and `-`, up to 32 characters. */\nexport const SCRIPT_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;\n\nexport function isScriptName(value: unknown): value is string {\n return typeof value === \"string\" && SCRIPT_NAME_PATTERN.test(value);\n}\n\nexport function isRoomName(value: unknown): value is string {\n return typeof value === \"string\" && ROOM_NAME_PATTERN.test(value);\n}\n\n/**\n * WebSocket close codes a room uses. The SDK reconnects after any other code.\n * FATAL follows an `err` whose code is fatal; the close reason is that code.\n * REPLACED means the same seat reconnected elsewhere (another tab, or a\n * resume that beat the old socket's close); don't reconnect, or the two\n * connections will keep taking the seat from each other.\n */\nexport const CLOSE_CODES = {\n FATAL: 4000,\n REPLACED: 4001,\n} as const;\n\n/**\n * Close reason the SDK sends with code 1000 when a player calls leave(). The\n * room frees that seat at once instead of holding it for a resume.\n */\nexport const LEAVE_REASON = \"leave\";\n", "import { MAX_MSG_BYTES, MAX_OPEN_ROOMS_PER_PROJECT, RATE_LIMIT_PER_SEC } from \"./limits.js\";\nimport { REGIONS } from \"./room.js\";\n\nexport interface ErrorInfo {\n /** True when the room closes the connection; the SDK must not reconnect on its own. */\n readonly fatal: boolean;\n /** One sentence for an AI agent: what went wrong, then how to fix it. */\n readonly message: string;\n}\n\n/**\n * Every error a room can send, keyed by its stable code. Codes never change\n * meaning once shipped; messages may be reworded. A specific error may carry\n * a more precise sentence than the default here.\n */\nexport const ERRORS = {\n bad_message: {\n fatal: false,\n message:\n \"That message isn't valid Cotchu protocol; send it through the cotchu SDK or match the formats in llms.txt.\",\n },\n hello_required: {\n fatal: false,\n message:\n \"The room hasn't had your hello yet; send a hello message first, or use cotchu.join(), which sends it for you.\",\n },\n unsupported_version: {\n fatal: true,\n message: \"This client speaks a different protocol version than the room; update the cotchu package to the latest.\",\n },\n bad_key: {\n fatal: true,\n message:\n \"That key isn't a valid Cotchu publishable key; pass your project's pk_ key as the key option to cotchu.join().\",\n },\n bad_origin: {\n fatal: true,\n message:\n \"This page's website isn't on your project's allowed origins; add it to the project's allowed origins, then reload.\",\n },\n\n room_full: {\n fatal: true,\n message: \"Every seat in this room is taken; try again in a moment or join a different room name.\",\n },\n room_limit: {\n fatal: true,\n message: `This project already has ${MAX_OPEN_ROOMS_PER_PROJECT} rooms open, its current limit; finished rooms close a minute after their last player leaves.`,\n },\n type_mismatch: {\n fatal: true,\n message: \"This room already exists with a different type; join with the room's type or pick a new room name.\",\n },\n wrong_room_type: {\n fatal: false,\n message:\n \"That call doesn't work in this type of room; use set() in shared rooms, move() in turns rooms and input() in realtime rooms.\",\n },\n rate_limited: {\n fatal: false,\n message: `This player sent more than ${RATE_LIMIT_PER_SEC} messages a second; batch changes into fewer messages or send inputs on a fixed timer.`,\n },\n too_large: {\n fatal: false,\n message: `That message is over ${MAX_MSG_BYTES / 1024} KB; send smaller changes, or split large data across several paths.`,\n },\n forbidden_path: {\n fatal: false,\n message: \"This player isn't allowed to write that path; write only to paths the room's writable list allows.\",\n },\n bad_move: {\n fatal: false,\n message:\n \"That move doesn't match the room's move schema; send a move shaped the way the room's moveSchema describes.\",\n },\n not_your_turn: {\n fatal: false,\n message: \"It isn't this player's turn; wait for a turn event naming this player before calling move().\",\n },\n balance_empty: {\n fatal: true,\n message: \"This project's Cotchu balance is empty, so new rooms can't open; top up the balance in the console.\",\n },\n action_rejected: {\n fatal: false,\n message: \"The room's script turned that action down; check the game's rules, or read the message the script gave.\",\n },\n script_error: {\n fatal: false,\n message:\n \"The room's script failed, so the room restarted it from its last save; try again, and fix the script if it keeps happening.\",\n },\n script_not_found: {\n fatal: true,\n message:\n \"This project has no deployed script by that name; deploy it with npx cotchu deploy room.js --name <name>, then join again.\",\n },\n bad_path: {\n fatal: false,\n message:\n \"That path runs through a value that isn't an object; set the parent to an object first, or write a different path.\",\n },\n unknown_player: {\n fatal: false,\n message: \"No player with that id is in the room; send direct messages only to ids from the room's player list.\",\n },\n internal: {\n fatal: false,\n message:\n \"Something went wrong inside Cotchu; retry, and if it keeps happening, report it with the room name and time.\",\n },\n\n replaced: {\n fatal: true,\n message:\n \"This seat was taken over by a newer connection using the same resume token; keep one connection per player.\",\n },\n\n // SDK errors: raised by the cotchu package itself, never sent by a room.\n room_closed: {\n fatal: true,\n message: \"This room is closed because you left or it ended; call cotchu.join() again to get a new room object.\",\n },\n unreachable: {\n fatal: true,\n message:\n \"Couldn't reach a Cotchu room; check the network and any url option you passed, then call cotchu.join() again.\",\n },\n\n // HTTP errors: returned before a WebSocket opens, as JSON { error, message }.\n not_found: {\n fatal: true,\n message: \"Nothing lives at that path; connect with the cotchu SDK, which opens /v1/rooms/<project>/<room> for you.\",\n },\n bad_room: {\n fatal: true,\n message:\n \"Project ids use lowercase letters and digits, and room names letters, digits, '.', '_' and '-' up to 64 characters; fix the URL.\",\n },\n\n bad_script: {\n fatal: true,\n message: \"That script couldn't be loaded; fix what the message describes in room.js, then deploy again.\",\n },\n bad_region: {\n fatal: true,\n message: `That region isn't one Cotchu knows; use auto or one of ${REGIONS.join(\", \")}.`,\n },\n upgrade_required: {\n fatal: true,\n message: \"Rooms only speak WebSocket; open the URL with new WebSocket(), or let cotchu.join() do it for you.\",\n },\n} as const satisfies Record<string, ErrorInfo>;\n\nexport type ErrorCode = keyof typeof ERRORS;\n\nexport const ERROR_CODES = Object.keys(ERRORS) as ErrorCode[];\n\nexport function isErrorCode(value: unknown): value is ErrorCode {\n return typeof value === \"string\" && Object.hasOwn(ERRORS, value);\n}\n\n/** Unknown codes (from a newer server) count as not fatal, so the SDK keeps trying. */\nexport function isFatal(code: string): boolean {\n return isErrorCode(code) && ERRORS[code].fatal;\n}\n", "/**\n * Publishable keys carry their project id: `pk_live_<project>_<secret>`. The\n * SDK reads the project from the key to build the room URL, so a game needs\n * one value, not two. Step 7 issues keys in this format and checks the secret.\n */\nimport { web } from \"./web.js\";\n\n/** Project ids: 1 to 32 lowercase letters and digits. No `_`, so keys parse unambiguously. */\nexport const PROJECT_ID_PATTERN = /^[a-z0-9]{1,32}$/;\n\nexport const PUBLISHABLE_KEY_PREFIX = \"pk_live_\";\n\nexport const PUBLISHABLE_KEY_PATTERN = /^pk_live_([a-z0-9]{1,32})_([A-Za-z0-9]{16,64})$/;\n\nexport function isProjectId(value: unknown): value is string {\n return typeof value === \"string\" && PROJECT_ID_PATTERN.test(value);\n}\n\n/** The project a publishable key belongs to, or null when it isn't a publishable key. */\nexport function projectOfKey(key: string): string | null {\n return PUBLISHABLE_KEY_PATTERN.exec(key)?.[1] ?? null;\n}\n\n/** Secret keys: server-to-server and console API only. Never in game code. */\nexport const SECRET_KEY_PREFIX = \"sk_live_\";\n\nexport const SECRET_KEY_PATTERN = /^sk_live_([a-z0-9]{1,32})_([A-Za-z0-9]{16,64})$/;\n\n/** Length of a generated project id. */\nexport const PROJECT_ID_LENGTH = 12;\n\n/** Length of the random part of a generated key: 32 base62 characters, about 190 bits. */\nexport const KEY_SECRET_LENGTH = 32;\n\n/** Uniform random characters from `alphabet` (rejection sampling, so no bias). */\nfunction randomString(alphabet: string, length: number): string {\n const limit = 256 - (256 % alphabet.length);\n let out = \"\";\n while (out.length < length) {\n for (const byte of web.crypto.getRandomValues(new Uint8Array(length * 2))) {\n if (byte < limit && out.length < length) out += alphabet[byte % alphabet.length];\n }\n }\n return out;\n}\n\nconst LOWER_DIGITS = \"abcdefghijklmnopqrstuvwxyz0123456789\";\nconst BASE62 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\nexport function newProjectId(): string {\n return randomString(LOWER_DIGITS, PROJECT_ID_LENGTH);\n}\n\n/** A fresh publishable and secret key for `project`. */\nexport function newKeys(project: string): { publishable: string; secret: string } {\n return {\n publishable: `${PUBLISHABLE_KEY_PREFIX}${project}_${randomString(BASE62, KEY_SECRET_LENGTH)}`,\n secret: `${SECRET_KEY_PREFIX}${project}_${randomString(BASE62, KEY_SECRET_LENGTH)}`,\n };\n}\n\n/** How keys are stored: SHA-256 of the whole key, as lowercase hex. Keys carry ~190 random bits, so no salt is needed. */\nexport async function hashKey(key: string): Promise<string> {\n const digest = await web.crypto.subtle.digest(\"SHA-256\", new web.TextEncoder().encode(key));\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n", "/**\n * The v1 wire protocol: JSON text frames over one WebSocket. Every message\n * has `t`, its type. Messages a client may tag with `id` get that `id` echoed\n * on any `err` they cause, so the SDK can fail the right call.\n */\nimport type { ErrorCode } from \"./errors.js\";\nimport type { Path } from \"./paths.js\";\nimport type { RoomType } from \"./room.js\";\nimport type { MoveSchema } from \"./schema.js\";\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | JsonObject;\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\n/** A room's rules. The first joiner sets them; later joiners get them in `welcome`. */\nexport interface RoomConfig {\n type: RoomType;\n seats: number;\n /** `shared`/`turns`: paths players may write (see paths.ts). Unset means every path. */\n writable?: string[];\n /** `turns`: milliseconds per turn before the room moves on. Unset means no timer. */\n turnMs?: number;\n /** `turns`: moves must match this schema (a JSON Schema subset; see schema.ts). */\n moveSchema?: MoveSchema;\n /** `realtime`: snapshots per second. `script`: onTick calls per second, if the script has onTick. */\n tickHz?: number;\n /** `script`: the deployed script this room runs, pinned to the version it opened with. */\n script?: { name: string; version: string };\n}\n\n/**\n * What a joiner may ask for. Ignored by a room that already exists, except\n * `type`, which must match. `script` names a deployed script; the room pins its\n * current version.\n */\nexport interface RoomOptions extends Partial<Omit<RoomConfig, \"script\">> {\n script?: string;\n}\n\nexport interface Player {\n id: string;\n name: string;\n}\n\n/** `turns` rooms: one entry in the room's move history. */\nexport interface Move {\n /** Player id that made the move. */\n by: string;\n data: JsonValue;\n}\n\n/** `turns` rooms: whose turn it is. */\nexport interface Turn {\n /** Player id, or null while nobody is seated. */\n player: string | null;\n /** Epoch milliseconds when the turn times out, if the room has a turn timer. */\n deadline?: number;\n}\n\n/** `realtime` rooms: the latest input from each player. */\nexport interface Snapshot {\n /** Snapshot number: ticks since the epoch at the room's tick rate, so it only grows. */\n tick: number;\n /** Latest input by player id. Players who haven't sent one are absent. */\n players: Record<string, JsonValue>;\n}\n\nexport type PatchOp =\n /** Put `value` at `path`, creating missing parents. */\n | { op: \"set\"; path: Path; value: JsonValue }\n /** Shallow-merge `value` into the object at `path`. An empty path merges into the root. */\n | { op: \"merge\"; path: Path; value: JsonObject }\n /** Remove whatever is at `path`. */\n | { op: \"delete\"; path: Path };\n\n// Client \u2192 server\n\nexport interface HelloMessage {\n t: \"hello\";\n /** PROTOCOL_VERSION the client speaks. */\n v: number;\n /** Publishable project key (`pk_\u2026`). Sent here, never in the URL. */\n key: string;\n /** SDK name and version, e.g. `cotchu-js/0.1.0`. */\n sdk: string;\n /** Display name for this player. */\n name?: string;\n /** Player sign-in token (accounts arrive in a later milestone). */\n token?: string;\n /** `resume` from an earlier `welcome`, to take back a seat within RESUME_WINDOW_MS. */\n resume?: string;\n /** Rules for the room if this hello creates it. */\n room?: RoomOptions;\n}\n\nexport interface ClientPatchMessage {\n t: \"patch\";\n id?: number;\n ops: PatchOp[];\n}\n\nexport interface MoveMessage {\n t: \"move\";\n id?: number;\n data: JsonValue;\n}\n\nexport interface InputMessage {\n t: \"input\";\n data: JsonValue;\n}\n\nexport interface ClientMsgMessage {\n t: \"msg\";\n id?: number;\n /** Player id for a direct message. Unset sends to everyone else in the room. */\n to?: string;\n data: JsonValue;\n}\n\nexport interface PingMessage {\n t: \"ping\";\n}\n\n/** `script` rooms: an action for the script's onAction. Answered with `ack` or an `err` with this id. */\nexport interface ActMessage {\n t: \"act\";\n id?: number;\n data: JsonValue;\n}\n\nexport type ClientMessage =\n HelloMessage | ClientPatchMessage | MoveMessage | InputMessage | ClientMsgMessage | PingMessage | ActMessage;\n\nexport const CLIENT_MESSAGE_TYPES = [\n \"hello\",\n \"patch\",\n \"move\",\n \"input\",\n \"msg\",\n \"ping\",\n \"act\",\n] as const satisfies readonly ClientMessage[\"t\"][];\n\n// Server \u2192 client\n\nexport interface WelcomeMessage {\n t: \"welcome\";\n v: number;\n /** This connection's player. */\n you: Player;\n /** The room's name. */\n room: string;\n config: RoomConfig;\n state: JsonObject;\n /** Everyone in the room, including `you`. */\n players: Player[];\n /** Keep this; send it as `resume` in `hello` to get the seat back after a drop. */\n resume: string;\n /** `turns`: whose turn it is. */\n turn?: Turn;\n /** `turns`: every move so far, oldest first. */\n moves?: Move[];\n /** `realtime`: the latest inputs. */\n snap?: Snapshot;\n /** `script`: this player's private state. */\n private?: JsonObject;\n}\n\nexport interface ServerPatchMessage {\n t: \"patch\";\n ops: PatchOp[];\n /** Player id that made the change, or null when the room did. */\n by: string | null;\n /** Only on the writer's own copy: the `id` of the patch message this confirms. */\n id?: number;\n}\n\nexport interface TurnMessage extends Turn {\n t: \"turn\";\n}\n\n/** `turns` rooms: a move the room accepted. The turn message follows. */\nexport interface ServerMoveMessage extends Move {\n t: \"move\";\n /** Position in the room's move history, from 0. */\n n: number;\n /** Only on the mover's own copy: the `id` of the move message this confirms. */\n id?: number;\n}\n\nexport interface SnapMessage extends Snapshot {\n t: \"snap\";\n}\n\nexport interface JoinMessage {\n t: \"join\";\n player: Player;\n}\n\nexport interface LeaveMessage {\n t: \"leave\";\n player: Player;\n}\n\nexport interface ServerMsgMessage {\n t: \"msg\";\n from: string;\n data: JsonValue;\n}\n\nexport interface ErrMessage {\n t: \"err\";\n code: ErrorCode;\n message: string;\n /** The `id` of the client message that caused this, if it had one. */\n id?: number;\n}\n\nexport interface PongMessage {\n t: \"pong\";\n}\n\n/** `script` rooms: the script accepted the action with this id. */\nexport interface AckMessage {\n t: \"ack\";\n id: number;\n}\n\n/** `script` rooms: changes to this player's private state. */\nexport interface PrivateMessage {\n t: \"priv\";\n ops: PatchOp[];\n}\n\n/** `script` rooms: an event the script sent with room.broadcast() or room.send(). */\nexport interface EventMessage {\n t: \"event\";\n name: string;\n data: JsonValue;\n}\n\n/** `script` rooms: the whole state again, after the script restarted from its last save. */\nexport interface SyncMessage {\n t: \"sync\";\n state: JsonObject;\n private: JsonObject;\n}\n\nexport type ServerMessage =\n | WelcomeMessage\n | ServerPatchMessage\n | TurnMessage\n | ServerMoveMessage\n | SnapMessage\n | JoinMessage\n | LeaveMessage\n | ServerMsgMessage\n | ErrMessage\n | PongMessage\n | AckMessage\n | PrivateMessage\n | EventMessage\n | SyncMessage;\n\nexport const SERVER_MESSAGE_TYPES = [\n \"welcome\",\n \"patch\",\n \"turn\",\n \"move\",\n \"snap\",\n \"join\",\n \"leave\",\n \"msg\",\n \"err\",\n \"pong\",\n \"ack\",\n \"priv\",\n \"event\",\n \"sync\",\n] as const satisfies readonly ServerMessage[\"t\"][];\n", "import { MAX_KEY_LENGTH, MAX_PATH_DEPTH } from \"./limits.js\";\n\n/** A location in a room's shared state, one key per level: `[\"players\", \"abc\", \"x\"]`. */\nexport type Path = string[];\n\n/** Keys that could reach an object's prototype. Never allowed in paths or values. */\nexport const FORBIDDEN_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\n\n/** In a writable pattern, matches the id of the player doing the write. */\nexport const SELF_SEGMENT = \"$self\";\n\n/** In a writable pattern, matches any one key. */\nexport const ANY_SEGMENT = \"*\";\n\n/** Returns why `key` can't be used in a path or object, or null when it can. */\nexport function keyProblem(key: string): string | null {\n if (key.length === 0) return \"is an empty key\";\n if (key.length > MAX_KEY_LENGTH) return `has a key longer than ${MAX_KEY_LENGTH} characters`;\n if (FORBIDDEN_KEYS.has(key)) return `uses the reserved key \"${key}\"`;\n return null;\n}\n\n/**\n * Returns why `pattern` isn't a valid writable pattern, or null when it is.\n * Patterns are dot-separated keys; `*` matches any one key and `$self`\n * matches the writer's player id.\n */\nexport function writablePatternProblem(pattern: string): string | null {\n const segments = pattern.split(\".\");\n if (segments.length > MAX_PATH_DEPTH) return `has more than ${MAX_PATH_DEPTH} keys`;\n for (const segment of segments) {\n if (segment === ANY_SEGMENT || segment === SELF_SEGMENT) continue;\n const problem = keyProblem(segment);\n if (problem) return problem;\n }\n return null;\n}\n\n/**\n * True when `pattern` lets player `self` write `path`. A pattern covers its\n * own path and everything beneath it: `players.$self` allows\n * `players.<self>.x` but not `players.<other>.x` or `players`.\n */\nexport function matchesWritable(pattern: string, path: readonly string[], self: string): boolean {\n const segments = pattern.split(\".\");\n if (segments.length > path.length) return false;\n return segments.every((segment, i) => {\n const key = path[i];\n if (segment === ANY_SEGMENT) return true;\n if (segment === SELF_SEGMENT) return key === self;\n return key === segment;\n });\n}\n\n/** True when any pattern lets `self` write `path`. No patterns at all means everything is writable. */\nexport function canWrite(patterns: readonly string[] | undefined, path: readonly string[], self: string): boolean {\n if (patterns === undefined) return true;\n return patterns.some((pattern) => matchesWritable(pattern, path, self));\n}\n", "/**\n * Move schemas for `turns` rooms: a small, strict subset of JSON Schema. The\n * room rejects moves that don't match; the SDK checks first, so a bad move\n * fails at the call. Unknown keywords are refused rather than ignored, so a\n * typo can't silently turn a rule off.\n */\nimport { MAX_SCHEMA_DEPTH } from \"./limits.js\";\nimport type { JsonObject, JsonValue } from \"./messages.js\";\nimport { keyProblem } from \"./paths.js\";\n\nexport const SCHEMA_TYPES = [\"object\", \"array\", \"string\", \"number\", \"integer\", \"boolean\", \"null\"] as const;\nexport type SchemaType = (typeof SCHEMA_TYPES)[number];\n\nexport interface MoveSchema {\n type?: SchemaType;\n /** The value must equal one of these. */\n enum?: JsonValue[];\n properties?: { [key: string]: MoveSchema };\n required?: string[];\n /** false: no fields beyond `properties`. Default true. */\n additionalProperties?: boolean;\n items?: MoveSchema;\n minItems?: number;\n maxItems?: number;\n minimum?: number;\n maximum?: number;\n minLength?: number;\n maxLength?: number;\n}\n\nconst KEYWORDS: readonly string[] = [\n \"type\",\n \"enum\",\n \"properties\",\n \"required\",\n \"additionalProperties\",\n \"items\",\n \"minItems\",\n \"maxItems\",\n \"minimum\",\n \"maximum\",\n \"minLength\",\n \"maxLength\",\n];\nconst COUNTS: readonly string[] = [\"minItems\", \"maxItems\", \"minLength\", \"maxLength\"];\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Returns why `schema` isn't a valid move schema, or null when it is. */\nexport function schemaProblem(schema: unknown, at = \"moveSchema\", depth = 0): string | null {\n if (depth > MAX_SCHEMA_DEPTH) return `${at} nests deeper than ${MAX_SCHEMA_DEPTH} levels`;\n if (!isObject(schema)) return `${at} must be an object such as {\"type\":\"integer\"}`;\n for (const key of Object.keys(schema)) {\n if (!KEYWORDS.includes(key)) {\n return `${at} uses \"${key.slice(0, 40)}\", which move schemas don't support (they support ${KEYWORDS.join(\", \")})`;\n }\n }\n const { type, enum: options, properties, required, additionalProperties, items } = schema;\n if (type !== undefined && !(SCHEMA_TYPES as readonly unknown[]).includes(type)) {\n return `${at}.type must be one of ${SCHEMA_TYPES.join(\", \")}`;\n }\n if (options !== undefined && (!Array.isArray(options) || options.length === 0)) {\n return `${at}.enum must be a non-empty list`;\n }\n if (properties !== undefined) {\n if (!isObject(properties)) return `${at}.properties must be an object of schemas`;\n for (const [key, inner] of Object.entries(properties)) {\n const bad = keyProblem(key);\n if (bad) return `${at}.properties ${bad}`;\n const problem = schemaProblem(inner, `${at}.properties.${key}`, depth + 1);\n if (problem) return problem;\n }\n }\n if (required !== undefined && (!Array.isArray(required) || !required.every((k) => typeof k === \"string\"))) {\n return `${at}.required must be a list of field names`;\n }\n if (additionalProperties !== undefined && typeof additionalProperties !== \"boolean\") {\n return `${at}.additionalProperties must be true or false`;\n }\n if (items !== undefined) {\n const problem = schemaProblem(items, `${at}.items`, depth + 1);\n if (problem) return problem;\n }\n for (const key of [\"minimum\", \"maximum\", ...COUNTS]) {\n const value = schema[key];\n if (value === undefined) continue;\n if (typeof value !== \"number\" || !Number.isFinite(value)) return `${at}.${key} must be a number`;\n if (COUNTS.includes(key) && (!Number.isInteger(value) || value < 0)) {\n return `${at}.${key} must be a whole number of 0 or more`;\n }\n }\n return null;\n}\n\nfunction typeOf(value: JsonValue): SchemaType {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n if (typeof value === \"number\") return Number.isInteger(value) ? \"integer\" : \"number\";\n return typeof value as \"string\" | \"boolean\" | \"object\";\n}\n\nfunction equal(a: JsonValue, b: JsonValue): boolean {\n if (a === b) return true;\n if (typeof a !== \"object\" || typeof b !== \"object\" || a === null || b === null) return false;\n if (Array.isArray(a) !== Array.isArray(b)) return false;\n if (Array.isArray(a) && Array.isArray(b))\n return a.length === b.length && a.every((x, i) => equal(x, b[i] as JsonValue));\n const ak = Object.keys(a);\n const bo = b as JsonObject;\n return (\n ak.length === Object.keys(bo).length &&\n ak.every((k) => Object.hasOwn(bo, k) && equal((a as JsonObject)[k] as JsonValue, bo[k] as JsonValue))\n );\n}\n\nconst article = (type: SchemaType) =>\n type === \"object\" || type === \"array\" || type === \"integer\" ? `an ${type}` : `a ${type}`;\n\n/** Returns why `value` doesn't match `schema` (a sentence fragment), or null when it does. */\nexport function moveProblem(schema: MoveSchema, value: JsonValue, at = \"move\"): string | null {\n if (schema.enum && !schema.enum.some((option) => equal(option, value))) {\n return `${at} must be one of ${schema.enum.map((o) => JSON.stringify(o)).join(\", \")}`;\n }\n const actual = typeOf(value);\n if (schema.type && actual !== schema.type && !(schema.type === \"number\" && actual === \"integer\")) {\n return `${at} must be ${article(schema.type)}, not ${article(actual)}`;\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) return `${at} must be at least ${schema.minimum}`;\n if (schema.maximum !== undefined && value > schema.maximum) return `${at} must be at most ${schema.maximum}`;\n }\n if (typeof value === \"string\") {\n if (schema.minLength !== undefined && value.length < schema.minLength) {\n return `${at} must be at least ${schema.minLength} characters`;\n }\n if (schema.maxLength !== undefined && value.length > schema.maxLength) {\n return `${at} must be at most ${schema.maxLength} characters`;\n }\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) {\n return `${at} must have at least ${schema.minItems} items`;\n }\n if (schema.maxItems !== undefined && value.length > schema.maxItems) {\n return `${at} must have at most ${schema.maxItems} items`;\n }\n if (schema.items) {\n for (const [i, item] of value.entries()) {\n const problem = moveProblem(schema.items, item, `${at}[${i}]`);\n if (problem) return problem;\n }\n }\n }\n if (actual === \"object\") {\n const object = value as JsonObject;\n for (const key of schema.required ?? []) {\n if (!Object.hasOwn(object, key)) return `${at}.${key} is missing`;\n }\n for (const [key, inner] of Object.entries(object)) {\n const rule = schema.properties && Object.hasOwn(schema.properties, key) ? schema.properties[key] : undefined;\n if (rule) {\n const problem = moveProblem(rule, inner, `${at}.${key}`);\n if (problem) return problem;\n } else if (schema.additionalProperties === false) {\n return `${at} has no field \"${key.slice(0, 40)}\"`;\n }\n }\n }\n return null;\n}\n", "/**\n * Applies patch ops to a room's shared state, all or nothing. Shared by the\n * room (authoritative state) and the SDK (instant local updates), so both\n * sides agree exactly. Pure: no storage, no sockets. Ops must already be\n * checked by `parseClientMessage` (or come from the room), so keys are safe.\n */\n/* eslint-disable @typescript-eslint/no-dynamic-delete --\n * Deleting client-named keys is this module's job. parseClientMessage has\n * already rejected __proto__, prototype and constructor in every path and value.\n */\nimport type { JsonObject, JsonValue, PatchOp } from \"./messages.js\";\n\nexport type ApplyResult =\n | {\n ok: true;\n /** Approximate change in the state's JSON size, in characters. */\n sizeDelta: number;\n /** Puts the state back exactly as it was before these ops. */\n undo: () => void;\n }\n | { ok: false; message: string };\n\nfunction isObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Characters `key: value` adds to the state's JSON, roughly. Exact size is recomputed on save. */\nfunction entrySize(key: string, value: JsonValue): number {\n return key.length + 4 + JSON.stringify(value).length;\n}\n\ninterface Applied {\n sizeDelta: number;\n undo: () => void;\n}\n\n/** Writes `value` at `parent[key]` and returns how to undo it. */\nfunction put(parent: JsonObject, key: string, value: JsonValue): Applied {\n const had = Object.hasOwn(parent, key);\n const old = parent[key];\n parent[key] = value;\n return {\n sizeDelta: entrySize(key, value) - (had && old !== undefined ? entrySize(key, old) : 0),\n undo: () => {\n if (had && old !== undefined) parent[key] = old;\n else delete parent[key];\n },\n };\n}\n\nfunction remove(parent: JsonObject, key: string): Applied {\n if (!Object.hasOwn(parent, key)) return { sizeDelta: 0, undo: () => {} };\n const old = parent[key] as JsonValue;\n const keys = Object.keys(parent);\n const after = keys.slice(keys.indexOf(key) + 1);\n delete parent[key];\n return {\n sizeDelta: -entrySize(key, old),\n // Re-adding a key puts it last; move the keys that followed it back behind it,\n // so a rolled-back patch leaves even the key order untouched.\n undo: () => {\n parent[key] = old;\n for (const k of after) {\n const value = parent[k] as JsonValue;\n delete parent[k];\n parent[k] = value;\n }\n },\n };\n}\n\n/**\n * Walks to the object at `path`. With `create`, missing objects are made on\n * the way (and recorded for undo). Returns a sentence fragment when the path\n * runs through something that isn't an object.\n */\nfunction walk(\n state: JsonObject,\n path: readonly string[],\n create: boolean,\n applied: Applied[],\n): JsonObject | null | string {\n let node = state;\n for (let i = 0; i < path.length; i++) {\n const key = path[i] as string;\n const next = node[key];\n if (next === undefined) {\n if (!create) return null;\n const made: JsonObject = {};\n applied.push(put(node, key, made));\n node = made;\n } else if (isObject(next)) {\n node = next;\n } else {\n return path.slice(0, i + 1).join(\".\");\n }\n }\n return node;\n}\n\nfunction applyOp(state: JsonObject, op: PatchOp, applied: Applied[]): string | null {\n const parentPath = op.op === \"merge\" ? op.path : op.path.slice(0, -1);\n const target = walk(state, parentPath, op.op !== \"delete\", applied);\n if (typeof target === \"string\") {\n return `can't write ${op.path.join(\".\") || \"the root\"} because ${target} isn't an object; set ${target} to an object first, or write a different path.`;\n }\n if (target === null) return null; // delete of something already absent\n switch (op.op) {\n case \"set\":\n applied.push(put(target, op.path.at(-1) as string, op.value));\n return null;\n case \"merge\":\n for (const [key, value] of Object.entries(op.value)) applied.push(put(target, key, value));\n return null;\n case \"delete\":\n applied.push(remove(target, op.path.at(-1) as string));\n return null;\n }\n}\n\nexport function applyOps(state: JsonObject, ops: readonly PatchOp[]): ApplyResult {\n const applied: Applied[] = [];\n const undo = () => {\n for (let i = applied.length - 1; i >= 0; i--) applied[i]?.undo();\n };\n for (const [i, op] of ops.entries()) {\n const problem = applyOp(state, op, applied);\n if (problem) {\n undo();\n return { ok: false, message: `patch.ops[${i}] ${problem}` };\n }\n }\n return { ok: true, sizeDelta: applied.reduce((sum, a) => sum + a.sizeDelta, 0), undo };\n}\n", "/**\n * A tiny, dependency-free validator. `parseClientMessage` is the room's front\n * door: every frame a client sends goes through it before any room logic\n * runs. It returns a clean copy holding only known fields.\n */\nimport { ERRORS, type ErrorCode } from \"./errors.js\";\nimport {\n MAX_MSG_BYTES,\n MAX_NAME_LENGTH,\n MAX_OPS_PER_PATCH,\n MAX_PATH_DEPTH,\n MAX_SCHEMA_BYTES,\n MAX_SEATS,\n MAX_TICK_HZ,\n MAX_TURN_MS,\n MAX_VALUE_DEPTH,\n MAX_WRITABLE_PATTERNS,\n MIN_TICK_HZ,\n MIN_TURN_MS,\n} from \"./limits.js\";\nimport {\n CLIENT_MESSAGE_TYPES,\n SERVER_MESSAGE_TYPES,\n type ClientMessage,\n type HelloMessage,\n type JsonObject,\n type JsonValue,\n type PatchOp,\n type RoomOptions,\n type ServerMessage,\n} from \"./messages.js\";\nimport { keyProblem, writablePatternProblem, type Path } from \"./paths.js\";\nimport { PING_FRAME, PROTOCOL_VERSION, isRoomType, isScriptName } from \"./room.js\";\nimport { schemaProblem, type MoveSchema } from \"./schema.js\";\n\nexport interface ProtocolError {\n code: ErrorCode;\n /** One sentence: what went wrong, then how to fix it. */\n message: string;\n /** The `id` of the offending message, when it had a valid one. */\n id?: number;\n}\n\nexport type Parsed<T> = { ok: true; message: T } | { ok: false; error: ProtocolError };\n\nconst MAX_KEY_STRING = 256;\nconst MAX_SDK_STRING = 64;\nconst MAX_TOKEN_STRING = 4096;\nconst MAX_PLAYER_ID_STRING = 64;\nconst ROOM_OPTION_KEYS: readonly string[] = [\"type\", \"seats\", \"writable\", \"turnMs\", \"tickHz\", \"moveSchema\", \"script\"];\nconst FORMATS_HINT = \"see the message formats in llms.txt, or send it through the cotchu SDK\";\n\n/** Thrown inside the validator, caught in the parse functions; never escapes. */\nclass Invalid extends Error {\n constructor(\n readonly code: ErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\nfunction invalid(where: string, problem: string, fix: string = FORMATS_HINT): never {\n throw new Invalid(\"bad_message\", `${where} ${problem}; ${fix}.`);\n}\n\nfunction failure(code: ErrorCode, message: string, id?: number): { ok: false; error: ProtocolError } {\n return { ok: false, error: id === undefined ? { code, message } : { code, message, id } };\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** A short, safe description of an unexpected value, for error sentences. */\nfunction describe(value: unknown): string {\n if (value === undefined) return \"missing\";\n if (typeof value === \"string\") return JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}\u2026` : value);\n if (Array.isArray(value)) return \"a list\";\n if (value === null) return \"null\";\n if (typeof value === \"object\") return \"an object\";\n return String(value);\n}\n\n/** UTF-8 size of `text` in bytes, without allocating. Lone surrogates count as 3, like TextEncoder. */\nexport function utf8ByteLength(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n if (code < 0x80) bytes += 1;\n else if (code < 0x800) bytes += 2;\n else if (code >= 0xd800 && code <= 0xdbff && (text.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n bytes += 4;\n i++;\n } else bytes += 3;\n }\n return bytes;\n}\n\nfunction fitsMessageLimit(text: string): boolean {\n if (text.length > MAX_MSG_BYTES) return false;\n if (text.length * 3 <= MAX_MSG_BYTES) return true;\n return utf8ByteLength(text) <= MAX_MSG_BYTES;\n}\n\n/** Checks that `value` is storable JSON: finite numbers, safe keys, bounded depth. */\nfunction checkValue(value: unknown, where: string, depth = 0): asserts value is JsonValue {\n if (depth > MAX_VALUE_DEPTH) invalid(where, `nests deeper than ${MAX_VALUE_DEPTH} levels`, \"flatten the data\");\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) invalid(where, \"has a number too large to store\", \"send it as a string instead\");\n return;\n }\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n if (Array.isArray(value)) {\n for (const item of value) checkValue(item, where, depth + 1);\n return;\n }\n if (isObject(value)) {\n for (const [key, item] of Object.entries(value)) {\n const problem = keyProblem(key);\n if (problem) invalid(where, problem, \"rename that key\");\n checkValue(item, where, depth + 1);\n }\n return;\n }\n invalid(where, \"isn't JSON data\");\n}\n\nfunction readInt(value: unknown, where: string, min: number, max: number): number {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < min || value > max) {\n invalid(\n where,\n `is ${describe(value)} but must be a whole number from ${min} to ${max}`,\n \"pick a value in that range\",\n );\n }\n return value;\n}\n\nfunction readString(value: unknown, where: string, max: number, fix: string): string {\n if (typeof value !== \"string\" || value.length === 0 || value.length > max) {\n invalid(where, `must be text of 1 to ${max} characters`, fix);\n }\n return value;\n}\n\nfunction readId(value: unknown): number | undefined {\n if (value === undefined) return undefined;\n if (typeof value !== \"number\" || !Number.isSafeInteger(value) || value < 0) {\n invalid(\n \"id\",\n `is ${describe(value)} but must be a whole number of 0 or more`,\n \"number each message from 0 upwards\",\n );\n }\n return value;\n}\n\nfunction readPath(value: unknown, where: string, minLength: 0 | 1): Path {\n const at = `${where}.path`;\n if (!Array.isArray(value)) invalid(at, \"must be a list of keys\", 'for example [\"players\", \"abc\", \"x\"]');\n if (value.length < minLength) invalid(at, \"is empty\", \"name the key to change, or use merge to change the root\");\n if (value.length > MAX_PATH_DEPTH) invalid(at, `has more than ${MAX_PATH_DEPTH} keys`, \"keep the state flatter\");\n const path: Path = [];\n for (const key of value) {\n if (typeof key !== \"string\") {\n invalid(at, \"must contain only text keys\", 'write numbers as text, for example [\"slots\", \"3\"]');\n }\n const problem = keyProblem(key);\n if (problem) invalid(at, problem, \"pick a different key\");\n path.push(key);\n }\n return path;\n}\n\nfunction readOp(value: unknown, where: string): PatchOp {\n if (!isObject(value)) invalid(where, \"must be an object with op and path\", '\"op\" is \"set\", \"merge\" or \"delete\"');\n switch (value.op) {\n case \"set\": {\n const path = readPath(value.path, where, 1);\n if (!(\"value\" in value)) invalid(`${where}.value`, \"is missing\", 'use \"delete\" to remove a value');\n const data = value.value;\n checkValue(data, `${where}.value`);\n return { op: \"set\", path, value: data };\n }\n case \"merge\": {\n const path = readPath(value.path, where, 0);\n const data = value.value;\n if (!isObject(data)) invalid(`${where}.value`, \"must be an object to merge\", 'use \"set\" to store other values');\n checkValue(data, `${where}.value`);\n return { op: \"merge\", path, value: data as JsonObject };\n }\n case \"delete\":\n return { op: \"delete\", path: readPath(value.path, where, 1) };\n default:\n return invalid(`${where}.op`, `is ${describe(value.op)}`, 'use \"set\", \"merge\" or \"delete\"');\n }\n}\n\nfunction readOps(value: unknown): PatchOp[] {\n if (!Array.isArray(value)) {\n invalid(\"patch.ops\", \"must be a list of operations\", 'for example [{\"op\":\"set\",\"path\":[\"score\"],\"value\":1}]');\n }\n if (value.length === 0) invalid(\"patch.ops\", \"is empty\", \"include at least one operation\");\n if (value.length > MAX_OPS_PER_PATCH) {\n invalid(\"patch.ops\", `has more than ${MAX_OPS_PER_PATCH} operations`, \"split the change across several patches\");\n }\n return value.map((op, i) => readOp(op, `patch.ops[${i}]`));\n}\n\nfunction readData(message: Record<string, unknown>, type: string): JsonValue {\n if (!(\"data\" in message)) {\n invalid(`${type}.data`, \"is missing\", `put the payload in \"data\", for example {\"t\":\"${type}\",\"data\":{}}`);\n }\n const data = message.data;\n checkValue(data, `${type}.data`);\n return data;\n}\n\nfunction readName(value: unknown): string {\n if (typeof value !== \"string\")\n invalid(\"hello.name\", `is ${describe(value)} but must be text`, \"send the name as text\");\n const name = value.trim();\n if (name.length === 0 || name.length > MAX_NAME_LENGTH) {\n invalid(\"hello.name\", `must be 1 to ${MAX_NAME_LENGTH} characters`, \"shorten the player's name\");\n }\n if (/\\p{Cc}/u.test(name)) invalid(\"hello.name\", \"contains control characters\", \"remove line breaks and tabs\");\n return name;\n}\n\nfunction readWritable(value: unknown): string[] {\n const where = \"hello.room.writable\";\n if (!Array.isArray(value) || value.length > MAX_WRITABLE_PATTERNS) {\n invalid(where, `must be a list of up to ${MAX_WRITABLE_PATTERNS} path patterns`, 'for example [\"players.$self\"]');\n }\n return value.map((pattern, i) => {\n const text = readString(pattern, `${where}[${i}]`, MAX_KEY_STRING, 'write it like \"players.$self\"');\n const problem = writablePatternProblem(text);\n if (problem) invalid(`${where}[${i}]`, problem, 'write it like \"players.$self\"');\n return text;\n });\n}\n\nfunction readRoomOptions(value: unknown): RoomOptions {\n const where = \"hello.room\";\n if (!isObject(value)) invalid(where, \"must be an object\", 'for example {\"type\":\"shared\",\"seats\":8}');\n for (const key of Object.keys(value)) {\n if (!ROOM_OPTION_KEYS.includes(key)) {\n invalid(where, `has no option ${describe(key)}`, `the options are ${ROOM_OPTION_KEYS.join(\", \")}`);\n }\n }\n const options: RoomOptions = {};\n const { type, seats, writable, turnMs, tickHz, moveSchema, script } = value;\n if (type !== undefined) {\n if (!isRoomType(type)) {\n invalid(`${where}.type`, `is ${describe(type)}`, 'use \"shared\", \"turns\", \"realtime\" or \"script\"');\n }\n options.type = type;\n }\n if (script !== undefined) {\n if (type !== undefined && type !== \"script\") {\n invalid(`${where}.script`, \"only applies to script rooms\", 'remove it, or set type to \"script\"');\n }\n if (!isScriptName(script)) {\n invalid(`${where}.script`, `is ${describe(script)}`, 'use the name the script was deployed with, like \"cards\"');\n }\n options.type = \"script\";\n options.script = script;\n } else if (type === \"script\") {\n invalid(`${where}.script`, \"is missing\", 'name the deployed script, like {\"type\":\"script\",\"script\":\"cards\"}');\n }\n if (seats !== undefined) options.seats = readInt(seats, `${where}.seats`, 1, MAX_SEATS);\n if (writable !== undefined) options.writable = readWritable(writable);\n if (turnMs !== undefined) {\n if (type !== undefined && type !== \"turns\") {\n invalid(`${where}.turnMs`, \"only applies to turns rooms\", 'remove it, or set type to \"turns\"');\n }\n options.turnMs = readInt(turnMs, `${where}.turnMs`, MIN_TURN_MS, MAX_TURN_MS);\n }\n if (tickHz !== undefined) {\n if (options.type !== undefined && options.type !== \"realtime\" && options.type !== \"script\") {\n invalid(`${where}.tickHz`, \"only applies to realtime and script rooms\", 'remove it, or set type to \"realtime\"');\n }\n options.tickHz = readInt(tickHz, `${where}.tickHz`, MIN_TICK_HZ, MAX_TICK_HZ);\n }\n if (moveSchema !== undefined) {\n if (type !== undefined && type !== \"turns\") {\n invalid(`${where}.moveSchema`, \"only applies to turns rooms\", 'remove it, or set type to \"turns\"');\n }\n const problem = schemaProblem(moveSchema, `${where}.moveSchema`);\n if (problem) throw new Invalid(\"bad_message\", `${problem}; fix the schema.`);\n if (utf8ByteLength(JSON.stringify(moveSchema)) > MAX_SCHEMA_BYTES) {\n invalid(`${where}.moveSchema`, `is over ${MAX_SCHEMA_BYTES / 1024} KB`, \"describe the move more simply\");\n }\n options.moveSchema = moveSchema as MoveSchema;\n }\n return options;\n}\n\nfunction readHello(message: Record<string, unknown>): HelloMessage {\n const { v, key, sdk, name, token, resume, room } = message;\n if (typeof v !== \"number\" || !Number.isInteger(v)) {\n invalid(\"hello.v\", \"must be the protocol version number\", `send ${PROTOCOL_VERSION}`);\n }\n if (v !== PROTOCOL_VERSION) {\n throw new Invalid(\n \"unsupported_version\",\n `This client speaks protocol ${v} but the room speaks ${PROTOCOL_VERSION}; update the cotchu package to the latest.`,\n );\n }\n if (key === undefined) {\n throw new Invalid(\n \"bad_key\",\n \"No project key was sent; pass your project's pk_ key as the key option to cotchu.join().\",\n );\n }\n if (typeof key !== \"string\" || key.length === 0 || key.length > MAX_KEY_STRING) {\n throw new Invalid(\"bad_key\", ERRORS.bad_key.message);\n }\n const hello: HelloMessage = {\n t: \"hello\",\n v,\n key,\n sdk: readString(sdk, \"hello.sdk\", MAX_SDK_STRING, 'name the client and its version, like \"cotchu-js/0.1.0\"'),\n };\n if (name !== undefined) hello.name = readName(name);\n if (token !== undefined) hello.token = readString(token, \"hello.token\", MAX_TOKEN_STRING, \"send the token as issued\");\n if (resume !== undefined) {\n hello.resume = readString(resume, \"hello.resume\", MAX_KEY_STRING, \"send the resume value from welcome unchanged\");\n }\n if (room !== undefined) hello.room = readRoomOptions(room);\n return hello;\n}\n\nfunction readClientMessage(message: Record<string, unknown>, id: number | undefined): ClientMessage {\n const tagged = id === undefined ? {} : { id };\n switch (message.t) {\n case \"hello\":\n return readHello(message);\n case \"patch\":\n return { t: \"patch\", ...tagged, ops: readOps(message.ops) };\n case \"move\":\n return { t: \"move\", ...tagged, data: readData(message, \"move\") };\n case \"input\":\n return { t: \"input\", data: readData(message, \"input\") };\n case \"msg\": {\n const data = readData(message, \"msg\");\n if (message.to === undefined) return { t: \"msg\", ...tagged, data };\n const to = readString(message.to, \"msg.to\", MAX_PLAYER_ID_STRING, \"use a player id from the room\");\n return { t: \"msg\", ...tagged, to, data };\n }\n case \"ping\":\n return { t: \"ping\" };\n case \"act\":\n return { t: \"act\", ...tagged, data: readData(message, \"act\") };\n default:\n throw new Invalid(\n \"bad_message\",\n `Unknown message type ${describe(message.t)}; use one of ${CLIENT_MESSAGE_TYPES.join(\", \")}.`,\n );\n }\n}\n\n/**\n * Validates one frame from a client. Size is checked before parsing, so an\n * oversized frame costs almost nothing to reject.\n */\nexport function parseClientMessage(raw: string | ArrayBuffer): Parsed<ClientMessage> {\n if (typeof raw !== \"string\") {\n if (raw.byteLength > MAX_MSG_BYTES) return failure(\"too_large\", ERRORS.too_large.message);\n return failure(\"bad_message\", \"Binary frames aren't supported yet; send each message as a JSON text frame.\");\n }\n if (!fitsMessageLimit(raw)) return failure(\"too_large\", ERRORS.too_large.message);\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return failure(\n \"bad_message\",\n `That frame isn't valid JSON; send each message as one JSON object, such as ${PING_FRAME}.`,\n );\n }\n if (!isObject(parsed)) {\n return failure(\n \"bad_message\",\n `Each message must be a JSON object with a \"t\" field naming its type; for example ${PING_FRAME}.`,\n );\n }\n\n let id: number | undefined;\n try {\n id = readId(parsed.id);\n return { ok: true, message: readClientMessage(parsed, id) };\n } catch (error) {\n if (error instanceof Invalid) return failure(error.code, error.message, id);\n throw error;\n }\n}\n\n/**\n * Reads one frame from a room. The room is trusted, so this only checks that\n * the frame is JSON with a known `t`; unknown types come from a newer server.\n */\nexport function parseServerMessage(raw: string): Parsed<ServerMessage> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return failure(\n \"bad_message\",\n \"The room sent a frame that isn't JSON; check the SDK is pointed at a Cotchu rooms URL.\",\n );\n }\n if (!isObject(parsed) || !(SERVER_MESSAGE_TYPES as readonly unknown[]).includes(parsed.t)) {\n const type = isObject(parsed) ? describe(parsed.t) : \"missing\";\n return failure(\n \"bad_message\",\n `The room sent an unknown message type ${type}; update the cotchu package to the latest.`,\n );\n }\n return { ok: true, message: parsed as unknown as ServerMessage };\n}\n", "import { ERRORS, isErrorCode, isFatal, type ErrorCode } from \"@cotchu/protocol\";\n\n/**\n * Every error the SDK throws, rejects with or emits. `message` is one\n * sentence: what went wrong, then how to fix it. `code` is stable; match on\n * it, not on the message.\n */\nexport class CotchuError extends Error {\n override readonly name = \"CotchuError\";\n /** True when the room is closed for good and the SDK won't reconnect. */\n readonly fatal: boolean;\n\n constructor(\n readonly code: ErrorCode | (string & {}),\n message?: string,\n ) {\n super(\n message ?? (isErrorCode(code) ? ERRORS[code].message : `The room reported \"${code}\"; update the cotchu package.`),\n );\n this.fatal = isFatal(code);\n }\n}\n", "/** Typed event emitter. `Events` maps each event name to its argument list. */\nexport class Emitter<Events extends Record<keyof Events, unknown[]>> {\n // Listeners of every event share one map; on/emit restore their types.\n private readonly listeners = new Map<keyof Events, Set<unknown>>();\n\n /** Calls `listener` on every `event`. Returns a function that stops it. */\n on<E extends keyof Events>(event: E, listener: (...args: Events[E]) => void): () => void {\n let set = this.listeners.get(event);\n if (!set) this.listeners.set(event, (set = new Set()));\n set.add(listener);\n return () => this.off(event, listener);\n }\n\n /** Calls `listener` on the next `event` only. */\n once<E extends keyof Events>(event: E, listener: (...args: Events[E]) => void): () => void {\n const off = this.on(event, (...args) => {\n off();\n listener(...args);\n });\n return off;\n }\n\n off<E extends keyof Events>(event: E, listener: (...args: Events[E]) => void): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n /** Returns false when nobody was listening. A throwing listener is reported, not fatal. */\n protected emit<E extends keyof Events>(event: E, ...args: Events[E]): boolean {\n const set = this.listeners.get(event);\n if (!set || set.size === 0) return false;\n for (const listener of [...set] as ((...args: Events[E]) => void)[]) {\n try {\n listener(...args);\n } catch (error) {\n console.error(`[cotchu] A \"${String(event)}\" listener threw:`, error);\n }\n }\n return true;\n }\n}\n", "import {\n CLIENT_RATE_LIMIT_BURST,\n CLIENT_RATE_LIMIT_PER_SEC,\n MAX_MSG_BYTES,\n MAX_OPS_PER_PATCH,\n utf8ByteLength,\n type ActMessage,\n type ClientMsgMessage,\n type ClientPatchMessage,\n type InputMessage,\n type MoveMessage,\n type PatchOp,\n} from \"@cotchu/protocol\";\n\nexport type Outgoing = ClientPatchMessage | ClientMsgMessage | MoveMessage | InputMessage | ActMessage;\n\n/** Room for the envelope around ops in one patch message. */\nconst PATCH_ENVELOPE_BYTES = 64;\n\n/** Most messages held while offline. Writes to the same path coalesce, so this is rarely reached. */\nexport const OUTBOX_LIMIT = 256;\n\n/** True when `prefix` equals `path` or is an ancestor of it. */\nfunction covers(prefix: readonly string[], path: readonly string[]): boolean {\n return prefix.length <= path.length && prefix.every((key, i) => path[i] === key);\n}\n\n/**\n * Everything a room is waiting to send. Writes made in the same tick go out\n * as one patch; a later set or delete drops earlier queued writes it\n * overrides; the latest input replaces an unsent one. A token bucket keeps\n * the SDK under the room's rate limit, so games can call set() every frame.\n */\nexport class Outbox {\n private readonly queue: Outgoing[] = [];\n private readonly sizes = new WeakMap<Outgoing, number>();\n private tokens = CLIENT_RATE_LIMIT_BURST;\n private refilledAt: number;\n private timer: ReturnType<typeof setTimeout> | undefined;\n private flushQueued = false;\n\n constructor(\n /** Sends one message. Returns false while offline; the message stays queued. */\n private readonly transmit: (message: Outgoing) => boolean,\n private readonly nextId: () => number,\n private readonly now: () => number = Date.now,\n ) {\n this.refilledAt = now();\n }\n\n get size(): number {\n return this.queue.length;\n }\n\n /** Ops not yet sent, in order. */\n queuedOps(): PatchOp[] {\n return this.queue.flatMap((m) => (m.t === \"patch\" ? m.ops : []));\n }\n\n /** Returns false when the outbox is full. */\n addOps(ops: PatchOp[]): boolean {\n for (const op of ops) {\n const bytes = utf8ByteLength(JSON.stringify(op)) + 1;\n const last = this.queue.at(-1);\n if (last?.t === \"patch\") {\n if (op.op !== \"merge\") last.ops = last.ops.filter((queued) => !covers(op.path, queued.path));\n // Sizes only grow on filtering (conservative), but an emptied patch starts over.\n const size = last.ops.length === 0 ? 0 : (this.sizes.get(last) ?? 0);\n if (last.ops.length < MAX_OPS_PER_PATCH && size + bytes <= MAX_MSG_BYTES - PATCH_ENVELOPE_BYTES) {\n last.ops.push(op);\n this.sizes.set(last, size + bytes);\n continue;\n }\n }\n if (this.queue.length >= OUTBOX_LIMIT) return false;\n const patch: ClientPatchMessage = { t: \"patch\", id: this.nextId(), ops: [op] };\n this.sizes.set(patch, bytes);\n this.queue.push(patch);\n }\n this.scheduleFlush();\n return true;\n }\n\n /** Returns false when the outbox is full. */\n add(message: ClientMsgMessage | MoveMessage | InputMessage | ActMessage): boolean {\n const last = this.queue.at(-1);\n if (message.t === \"input\" && last?.t === \"input\") {\n last.data = message.data;\n return true;\n }\n if (this.queue.length >= OUTBOX_LIMIT) return false;\n this.queue.push(message);\n this.scheduleFlush();\n return true;\n }\n\n /** Sends on the next microtask, so every write made in this tick shares one message. */\n scheduleFlush(): void {\n if (this.flushQueued || this.timer !== undefined) return;\n this.flushQueued = true;\n queueMicrotask(() => {\n this.flushQueued = false;\n this.flush();\n });\n }\n\n flush(): void {\n while (this.queue.length > 0) {\n const head = this.queue[0] as Outgoing;\n if (head.t === \"patch\" && head.ops.length === 0) {\n this.queue.shift(); // every op in it was overridden by a later write\n continue;\n }\n if (!this.take()) {\n const wait = Math.ceil(((1 - this.tokens) * 1000) / CLIENT_RATE_LIMIT_PER_SEC);\n this.timer ??= setTimeout(() => {\n this.timer = undefined;\n this.flush();\n }, wait);\n return;\n }\n const next = this.queue[0] as Outgoing;\n if (!this.transmit(next)) {\n this.tokens += 1; // not spent: nothing went out\n return;\n }\n this.queue.shift();\n }\n }\n\n private take(): boolean {\n const now = this.now();\n this.tokens = Math.min(\n CLIENT_RATE_LIMIT_BURST,\n this.tokens + ((now - this.refilledAt) * CLIENT_RATE_LIMIT_PER_SEC) / 1000,\n );\n this.refilledAt = now;\n if (this.tokens < 1) return false;\n this.tokens -= 1;\n return true;\n }\n\n clear(): void {\n this.queue.length = 0;\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n }\n}\n", "import { MAX_MSG_BYTES, MAX_PATH_DEPTH, keyProblem, utf8ByteLength, type JsonValue } from \"@cotchu/protocol\";\nimport { CotchuError } from \"./errors.js\";\n\n/** In a dotted path, this key stands for the current player's id. */\nexport const ME = \"me\";\n\n/** A path as a game writes it: `\"players.me.x\"`, or `[\"players\", id, \"x\"]` for keys that contain dots. */\nexport type PathInput = string | readonly string[];\n\n/**\n * Turns a path into keys. In dotted strings, `me` becomes this player's id;\n * arrays are taken literally. Throws at the call site for paths the room\n * would reject anyway.\n */\nexport function toPath(path: PathInput, me: string, call: string, allowRoot = false): string[] {\n const keys =\n typeof path === \"string\" ? (path === \"\" ? [] : path.split(\".\").map((k) => (k === ME ? me : k))) : [...path];\n const shown = typeof path === \"string\" ? JSON.stringify(path) : JSON.stringify(keys);\n if (keys.length === 0 && !allowRoot) {\n throw new CotchuError(\"bad_message\", `${call}() needs a path such as \"players.me.x\"; an empty path names nothing.`);\n }\n if (keys.length > MAX_PATH_DEPTH) {\n throw new CotchuError(\n \"bad_message\",\n `${call}() path ${shown} has more than ${MAX_PATH_DEPTH} keys; keep the state flatter.`,\n );\n }\n for (const key of keys) {\n if (typeof key !== \"string\") {\n throw new CotchuError(\n \"bad_message\",\n `${call}() path ${shown} must contain only text keys; write numbers as text.`,\n );\n }\n const problem = keyProblem(key);\n if (problem) throw new CotchuError(\"bad_message\", `${call}() path ${shown} ${problem}; pick a different key.`);\n }\n return keys;\n}\n\n/**\n * Copies `value` the way the room will store it: as JSON. Later changes to\n * the caller's object don't leak into the room, and non-JSON values fail here\n * instead of on the server.\n */\nexport function toJson(value: unknown, call: string): JsonValue {\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") {\n throw new CotchuError(\n \"bad_message\",\n `${call}() needs a JSON value, not ${typeof value}; use delete() to remove a value.`,\n );\n }\n let text: string;\n try {\n text = JSON.stringify(value);\n } catch {\n throw new CotchuError(\n \"bad_message\",\n `${call}() got a value that can't become JSON, such as a circular object; send plain data.`,\n );\n }\n if (utf8ByteLength(text) > MAX_MSG_BYTES) {\n throw new CotchuError(\n \"too_large\",\n `${call}() got a value over ${MAX_MSG_BYTES / 1024} KB as JSON; split it across several paths.`,\n );\n }\n return JSON.parse(text) as JsonValue;\n}\n", "import {\n CLOSE_CODES,\n LEAVE_REASON,\n MAX_INPUT_BYTES,\n PING_FRAME,\n applyOps,\n moveProblem,\n parseServerMessage,\n utf8ByteLength,\n type ClientMsgMessage,\n type ErrMessage,\n type HelloMessage,\n type ActMessage,\n type InputMessage,\n type JsonObject,\n type JsonValue,\n type Move,\n type MoveMessage,\n type PatchOp,\n type Player,\n type RoomConfig,\n type ServerMoveMessage,\n type ServerPatchMessage,\n type Snapshot,\n type Turn,\n type WelcomeMessage,\n} from \"@cotchu/protocol\";\nimport { Emitter } from \"./emitter.js\";\nimport { CotchuError } from \"./errors.js\";\nimport { Outbox, type Outgoing } from \"./outbox.js\";\nimport { toJson, toPath, type PathInput } from \"./paths.js\";\nimport type { SeatMemory } from \"./seat-memory.js\";\n\nexport type RoomStatus = \"connecting\" | \"connected\" | \"reconnecting\" | \"closed\";\n\nexport interface StateChange {\n /** The ops that changed the state. Empty when `reset` is true. */\n ops: PatchOp[];\n /** Player id that made the change, or null when the room did. */\n by: string | null;\n /** True when the whole state was replaced: on first listen, after a reconnect, or when the room rejected a write. */\n reset: boolean;\n}\n\nexport interface RoomEvents {\n /** The shared state changed. Fires right away for a new listener, then on every change. */\n state: [state: JsonObject, change: StateChange];\n join: [player: Player];\n leave: [player: Player];\n /** Something another player sent with send(). */\n message: [data: JsonValue, from: Player];\n /** `turns` rooms: the turn passed. `player` is null while nobody is seated. */\n turn: [player: Player | null, deadline: number | null];\n /** `turns` rooms: someone moved. `n` is the move's place in room.moves. */\n move: [data: JsonValue, from: Player, n: number];\n /** `realtime` rooms: new snapshot of everyone's latest input. */\n snap: [inputs: Record<string, JsonValue>, tick: number];\n /** `script` rooms: an event the room's script sent with room.broadcast() or room.send(). */\n event: [name: string, data: JsonValue];\n /**\n * Anything changed: state, players, turn, moves, inputs or status. Fires\n * right away for a new listener. The simplest correct game re-renders\n * everything from the room's getters here.\n */\n change: [];\n /** Something went wrong. With no listener, the SDK logs it with console.warn instead. */\n error: [error: CotchuError];\n status: [status: RoomStatus];\n}\n\n/** What the room needs to (re)connect. Built and checked by cotchu.join(). */\nexport interface Connection {\n url: string;\n hello: HelloMessage;\n WebSocket: typeof WebSocket;\n /** Keeps the seat across reloads of this tab; null outside browsers or when turned off. */\n seats: SeatMemory | null;\n}\n\nconst OPEN = 1;\nconst HELLO_TIMEOUT_MS = 10_000;\nconst HEARTBEAT_MS = 15_000;\n/** No message at all for this long (pongs included) means the connection is dead. */\nconst DEAD_AFTER_MS = 35_000;\nconst BACKOFF_BASE_MS = 250;\nconst BACKOFF_MAX_MS = 5_000;\n/** cotchu.join() gives up after this many failed connection attempts. */\nconst JOIN_ATTEMPTS = 3;\n\nfunction isObject(value: JsonValue): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * A joined room. Get one from `cotchu.join()`. Writes show up locally at once\n * and reach everyone else through the room; the room's order wins, so every\n * player ends up with the same state.\n */\nexport class Room extends Emitter<RoomEvents> {\n /** The room's name, as passed to cotchu.join(). */\n readonly name: string;\n\n private me_: Player = { id: \"\", name: \"\" };\n private config_: RoomConfig = { type: \"shared\", seats: 0 };\n private readonly players_ = new Map<string, Player>();\n /** State in the room's order, as confirmed by the room. */\n private confirmed: JsonObject = {};\n /** What the game sees: `confirmed` plus this player's writes the room hasn't confirmed yet. */\n private view: JsonObject = {};\n private inflight: { id: number; ops: PatchOp[] }[] = [];\n private turn_: Turn = { player: null };\n private moves_: Move[] = [];\n private snap_: Snapshot = { tick: 0, players: {} };\n private private_: JsonObject = {};\n /** `script` rooms: act() calls waiting for the script's answer, by message id. */\n private readonly acts = new Map<number, { resolve: () => void; reject: (error: CotchuError) => void }>();\n private readonly outbox: Outbox;\n private nextId = 1;\n\n private ws: WebSocket | null = null;\n private welcomed = false;\n private status_: RoomStatus = \"connecting\";\n private resume: string | undefined;\n private attempt = 0;\n private lastSeen = 0;\n private helloTimer: ReturnType<typeof setTimeout> | undefined;\n private reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n private heartbeat: ReturnType<typeof setInterval> | undefined;\n private settle: { resolve: (room: Room) => void; reject: (error: CotchuError) => void } | undefined;\n /** The room's last reason for turning a join attempt away, if any; join() rejects with it when it gives up. */\n private refusal: CotchuError | undefined;\n\n /** @internal Use `cotchu.join()`. */\n constructor(\n name: string,\n private readonly connection: Connection,\n ) {\n super();\n this.name = name;\n this.outbox = new Outbox(\n (message) => this.transmit(message),\n () => this.nextId++,\n );\n }\n\n /** @internal Connects; resolves on the room's welcome. */\n open(): Promise<Room> {\n return new Promise((resolve, reject) => {\n this.settle = { resolve, reject };\n this.resume = this.connection.seats?.take();\n this.connect();\n });\n }\n\n /** This player. The id is stable across reconnects within the 60 s resume window. */\n get me(): Player {\n return this.me_;\n }\n\n /** The shared state. Read it freely; change it only with set(), merge() and delete(). */\n get state(): JsonObject {\n return this.view;\n }\n\n /** Everyone connected to the room, this player included. */\n get players(): Player[] {\n return [...this.players_.values()];\n }\n\n /** The room's rules, set by whoever joined first. */\n get config(): RoomConfig {\n return this.config_;\n }\n\n get status(): RoomStatus {\n return this.status_;\n }\n\n /** `turns` rooms: id of the player whose turn it is, or null. */\n get turn(): string | null {\n return this.turn_.player;\n }\n\n /** `turns` rooms: true when this player may move now. */\n get isMyTurn(): boolean {\n return this.turn_.player !== null && this.turn_.player === this.me_.id;\n }\n\n /** `turns` rooms: epoch milliseconds when the current turn times out, or null without a turn timer. */\n get deadline(): number | null {\n return this.turn_.deadline ?? null;\n }\n\n /** `turns` rooms: every move so far, oldest first. Derive the game from these. */\n get moves(): readonly Move[] {\n return this.moves_;\n }\n\n /** `realtime` rooms: each player's latest input, by player id, as of the last snapshot. */\n get inputs(): Record<string, JsonValue> {\n return this.snap_.players;\n }\n\n /** `realtime` rooms: the last snapshot's tick number. Grows by tickHz every second. */\n /** `script` rooms: this player's private state, which only this player receives (a hand of cards, a secret goal). */\n get private(): JsonObject {\n return this.private_;\n }\n\n get tick(): number {\n return this.snap_.tick;\n }\n\n override on<E extends keyof RoomEvents>(event: E, listener: (...args: RoomEvents[E]) => void): () => void {\n const off = super.on(event, listener);\n if (event === \"state\" || event === \"change\") {\n // A new state or change listener draws the current room right away, then every change.\n queueMicrotask(() => {\n if (this.status_ === \"closed\") return;\n if (event === \"state\") {\n (listener as (...args: RoomEvents[\"state\"]) => void)(this.view, { ops: [], by: null, reset: true });\n } else {\n (listener as () => void)();\n }\n });\n }\n return off;\n }\n\n // ---------------------------------------------------------------- writes\n\n /** Puts `value` at `path`. In a dotted path, `me` means this player: `room.set(\"players.me.x\", 120)`. */\n set(path: PathInput, value: unknown): void {\n this.write(\"set\", { op: \"set\", path: toPath(path, this.me_.id, \"set\"), value: toJson(value, \"set\") });\n }\n\n /** Copies the keys of `value` into the object at `path`, leaving its other keys alone. \"\" merges into the root. */\n merge(path: PathInput, value: Record<string, unknown>): void {\n const json = toJson(value, \"merge\");\n if (!isObject(json)) {\n throw new CotchuError(\n \"bad_message\",\n \"merge() needs a plain object such as { x: 1 }; use set() for other values.\",\n );\n }\n this.write(\"merge\", { op: \"merge\", path: toPath(path, this.me_.id, \"merge\", true), value: json });\n }\n\n /** Removes whatever is at `path`. */\n delete(path: PathInput): void {\n this.write(\"delete\", { op: \"delete\", path: toPath(path, this.me_.id, \"delete\") });\n }\n\n /** Sends `data` to everyone else in the room, or to one player. Not saved in the state. */\n send(data: unknown, to?: string | Player): void {\n const message: ClientMsgMessage = { t: \"msg\", data: toJson(data, \"send\") };\n if (to !== undefined) message.to = typeof to === \"string\" ? to : to.id;\n this.enqueue(\"send\", message);\n }\n\n /**\n * `turns` rooms: plays a move on this player's turn. The room records it in\n * room.moves and passes the turn. Throws if it isn't this player's turn or\n * the move doesn't match the room's moveSchema.\n */\n move(data: unknown): void {\n this.ensureOpen(\"move\");\n this.ensureType(\"move\", \"turns\");\n const json = toJson(data, \"move\");\n if (!this.isMyTurn) {\n const holder = this.turn_.player === null ? null : this.players_.get(this.turn_.player);\n throw new CotchuError(\n \"not_your_turn\",\n holder\n ? `It's ${holder.name}'s turn, not yours; wait for the turn event, or check room.isMyTurn before calling move().`\n : \"It isn't your turn; wait for the turn event, or check room.isMyTurn before calling move().\",\n );\n }\n const schema = this.config_.moveSchema;\n const problem = schema ? moveProblem(schema, json) : null;\n if (problem) throw new CotchuError(\"bad_move\", `${problem}; send a move that matches the room's moveSchema.`);\n this.enqueue(\"move\", { t: \"move\", id: this.nextId++, data: json } satisfies MoveMessage);\n }\n\n /**\n * `script` rooms: sends what this player did to the room's script (its\n * onAction). Resolves once the script accepts it; rejects with the script's\n * own reason (code `action_rejected`) if it turns it down.\n */\n act(data: unknown): Promise<void> {\n this.ensureOpen(\"act\");\n this.ensureType(\"act\", \"script\");\n const id = this.nextId++;\n const message: ActMessage = { t: \"act\", id, data: toJson(data, \"act\") };\n return new Promise<void>((resolve, reject) => {\n this.acts.set(id, { resolve, reject });\n try {\n this.enqueue(\"act\", message);\n } catch (error) {\n this.acts.delete(id);\n reject(error);\n }\n });\n }\n\n /** `realtime` and `script` rooms: sets this player's latest input. Unsent inputs are replaced, not queued. */\n input(data: unknown): void {\n this.ensureOpen(\"input\");\n if (this.config_.type !== \"script\") this.ensureType(\"input\", \"realtime\");\n const json = toJson(data, \"input\");\n if (utf8ByteLength(JSON.stringify(json)) > MAX_INPUT_BYTES) {\n throw new CotchuError(\n \"too_large\",\n `input() got more than ${MAX_INPUT_BYTES / 1024} KB; send only what changes each frame, such as keys held or a direction.`,\n );\n }\n this.enqueue(\"input\", { t: \"input\", data: json } satisfies InputMessage);\n }\n\n private ensureType(call: string, type: RoomConfig[\"type\"]): void {\n if (this.config_.type === type) return;\n throw new CotchuError(\n \"wrong_room_type\",\n type === \"script\"\n ? `${call}() 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\" }).`\n : `${call}() only works in ${type} rooms and this is a ${this.config_.type} room; create the room with type \"${type}\", or use set() here.`,\n );\n }\n\n /** Leaves the room for good and frees the seat at once. */\n leave(): void {\n if (this.status_ === \"closed\") return;\n this.connection.seats?.forget();\n this.outbox.flush();\n const ws = this.ws;\n this.shutDown();\n if (ws) {\n try {\n ws.close(1000, LEAVE_REASON);\n } catch {\n // Already closing.\n }\n }\n }\n\n private ensureOpen(call: string): void {\n if (this.status_ === \"closed\") {\n throw new CotchuError(\n \"room_closed\",\n `${call}() can't run because this room is closed; call cotchu.join() again.`,\n );\n }\n }\n\n private write(call: string, op: PatchOp): void {\n this.ensureOpen(call);\n if (this.config_.type === \"script\") {\n throw new CotchuError(\n \"wrong_room_type\",\n `${call}() doesn't work in script rooms, where the script owns the state; send what the player did with room.act().`,\n );\n }\n const target = this.view === this.confirmed ? structuredClone(this.confirmed) : this.view;\n const result = applyOps(target, [op]);\n if (!result.ok) throw new CotchuError(\"bad_path\", result.message.replace(/^patch\\.ops\\[0\\] /, `${call}() `));\n if (!this.outbox.addOps([op])) {\n result.undo();\n throw this.backlogError(call);\n }\n this.view = target;\n this.emit(\"state\", this.view, { ops: [op], by: this.me_.id, reset: false });\n this.emit(\"change\");\n }\n\n private enqueue(call: string, message: ClientMsgMessage | MoveMessage | InputMessage | ActMessage): void {\n this.ensureOpen(call);\n if (!this.outbox.add(message)) throw this.backlogError(call);\n }\n\n private backlogError(call: string): CotchuError {\n return new CotchuError(\n \"rate_limited\",\n `${call}() was dropped because too many messages are waiting to send; send less often, or wait for status \"connected\".`,\n );\n }\n\n /** Sends one queued message if connected. Returns false to keep it queued. */\n private transmit(message: Outgoing): boolean {\n const ws = this.ws;\n if (!ws || !this.welcomed || ws.readyState !== OPEN) return false;\n try {\n ws.send(JSON.stringify(message));\n } catch {\n return false;\n }\n if (message.t === \"patch\" && message.id !== undefined) this.inflight.push({ id: message.id, ops: message.ops });\n return true;\n }\n\n // ------------------------------------------------------------ connection\n\n private connect(): void {\n const { url, hello, WebSocket: Socket } = this.connection;\n let ws: WebSocket;\n try {\n ws = new Socket(url);\n } catch {\n return this.fail(\n new CotchuError(\"unreachable\", `Couldn't open a WebSocket to ${url}; check the url option if you passed one.`),\n );\n }\n this.ws = ws;\n this.welcomed = false;\n ws.onopen = () => {\n if (this.ws === ws) ws.send(JSON.stringify(this.resume ? { ...hello, resume: this.resume } : hello));\n };\n ws.onmessage = (event: MessageEvent) => {\n if (this.ws === ws) this.receive(typeof event.data === \"string\" ? event.data : \"\");\n };\n ws.onclose = (event: CloseEvent) => {\n if (this.ws === ws) this.dropped(event.code);\n };\n ws.onerror = () => {\n // A close event always follows; reconnecting happens there.\n };\n this.helloTimer = setTimeout(() => {\n if (this.ws === ws && !this.welcomed) this.abandon(ws);\n }, HELLO_TIMEOUT_MS);\n }\n\n /** Gives up on a socket that has gone quiet, without waiting for TCP to notice. */\n private abandon(ws: WebSocket): void {\n ws.onopen = ws.onmessage = ws.onclose = null;\n try {\n ws.close();\n } catch {\n // Already closing.\n }\n if (this.ws === ws) this.dropped(1006);\n }\n\n private dropped(code: number): void {\n this.stopTimers();\n this.ws = null;\n this.welcomed = false;\n if (this.status_ === \"closed\") return;\n if (code === CLOSE_CODES.FATAL) {\n // The room explained why in an err message, which already failed us.\n return this.fail(new CotchuError(\"internal\", \"The room closed this connection; call cotchu.join() again.\"));\n }\n if (code === CLOSE_CODES.REPLACED) return this.fail(new CotchuError(\"replaced\"));\n\n this.attempt++;\n if (this.settle && this.attempt >= JOIN_ATTEMPTS) {\n return this.fail(\n this.refusal ??\n new CotchuError(\n \"unreachable\",\n `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.`,\n ),\n );\n }\n if (!this.settle) this.setStatus(\"reconnecting\");\n const delay = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** (this.attempt - 1)) * (0.5 + Math.random() / 2);\n this.reconnectTimer = setTimeout(() => {\n this.reconnectTimer = undefined;\n this.connect();\n }, delay);\n }\n\n /** Closes for good: rejects a pending join, or reports the error. */\n private fail(error: CotchuError): void {\n if (this.status_ === \"closed\") return;\n const ws = this.ws;\n this.shutDown();\n if (ws) {\n ws.onopen = ws.onmessage = ws.onclose = null;\n try {\n ws.close();\n } catch {\n // Already closing.\n }\n }\n const settle = this.settle;\n this.settle = undefined;\n if (settle) settle.reject(error);\n else this.report(error);\n }\n\n private shutDown(): void {\n this.settleActs(\n new CotchuError(\"room_closed\", \"The room closed before it answered this action; join again to keep playing.\"),\n );\n this.connection.seats?.forget();\n this.stopTimers();\n this.outbox.clear();\n this.ws = null;\n this.welcomed = false;\n this.setStatus(\"closed\");\n }\n\n private stopTimers(): void {\n if (this.helloTimer !== undefined) clearTimeout(this.helloTimer);\n if (this.reconnectTimer !== undefined) clearTimeout(this.reconnectTimer);\n if (this.heartbeat !== undefined) clearInterval(this.heartbeat);\n this.helloTimer = this.reconnectTimer = this.heartbeat = undefined;\n }\n\n private startHeartbeat(): void {\n this.lastSeen = Date.now();\n this.heartbeat = setInterval(() => {\n const ws = this.ws;\n if (!ws) return;\n if (Date.now() - this.lastSeen > DEAD_AFTER_MS) return this.abandon(ws);\n try {\n ws.send(PING_FRAME); // the room answers without waking up, so this costs nothing\n } catch {\n // The close event will follow.\n }\n }, HEARTBEAT_MS);\n }\n\n private setStatus(status: RoomStatus): void {\n if (this.status_ === status) return;\n this.status_ = status;\n this.emit(\"status\", status);\n this.emit(\"change\");\n }\n\n private report(error: CotchuError): void {\n if (!this.emit(\"error\", error)) console.warn(`[cotchu] ${error.code}: ${error.message}`);\n }\n\n // -------------------------------------------------------------- receiving\n\n private receive(text: string): void {\n this.lastSeen = Date.now();\n const parsed = parseServerMessage(text);\n if (!parsed.ok) return this.report(new CotchuError(parsed.error.code, parsed.error.message));\n const message = parsed.message;\n switch (message.t) {\n case \"welcome\":\n return this.welcome(message);\n case \"patch\":\n return this.patched(message);\n case \"err\":\n return this.errored(message);\n case \"join\":\n this.players_.set(message.player.id, message.player);\n this.emit(\"join\", message.player);\n this.emit(\"change\");\n return;\n case \"leave\":\n this.players_.delete(message.player.id);\n if (Object.hasOwn(this.snap_.players, message.player.id)) {\n const { [message.player.id]: _gone, ...rest } = this.snap_.players;\n this.snap_ = { tick: this.snap_.tick, players: rest };\n }\n this.emit(\"leave\", message.player);\n this.emit(\"change\");\n return;\n case \"msg\":\n this.emit(\"message\", message.data, this.playerFor(message.from));\n return;\n case \"turn\":\n this.turn_ =\n message.deadline === undefined\n ? { player: message.player }\n : { player: message.player, deadline: message.deadline };\n this.emit(\"turn\", message.player === null ? null : this.playerFor(message.player), message.deadline ?? null);\n this.emit(\"change\");\n return;\n case \"move\":\n return this.moved(message);\n case \"snap\":\n this.snap_ = { tick: message.tick, players: message.players };\n this.emit(\"snap\", message.players, message.tick);\n this.emit(\"change\");\n return;\n case \"ack\":\n this.acts.get(message.id)?.resolve();\n this.acts.delete(message.id);\n return;\n case \"priv\": {\n const result = applyOps(this.private_, message.ops);\n if (!result.ok) {\n this.report(\n new CotchuError(\"internal\", \"This copy of your private state fell out of sync; reconnecting to fix it.\"),\n );\n if (this.ws) this.abandon(this.ws);\n return;\n }\n this.emit(\"change\");\n return;\n }\n case \"event\":\n this.emit(\"event\", message.name, message.data);\n return;\n case \"sync\":\n // The script restarted from its last save: this is the truth now.\n this.confirmed = message.state;\n this.private_ = message.private;\n this.inflight = [];\n this.rebuild();\n this.emit(\"state\", this.view, { ops: [], by: null, reset: true });\n this.emit(\"change\");\n return;\n default:\n return; // pong: keeps lastSeen fresh\n }\n }\n\n private playerFor(id: string): Player {\n return this.players_.get(id) ?? { id, name: id };\n }\n\n private moved(message: ServerMoveMessage): void {\n // n tells us where this move goes; a duplicate or gap means our copy drifted.\n if (message.n !== this.moves_.length) {\n this.report(\n new CotchuError(\"internal\", \"This copy of the room's moves fell out of sync; reconnecting to fix it.\"),\n );\n if (this.ws) this.abandon(this.ws);\n return;\n }\n this.moves_.push({ by: message.by, data: message.data });\n this.emit(\"move\", message.data, this.playerFor(message.by), message.n);\n this.emit(\"change\");\n }\n\n private welcome(message: WelcomeMessage): void {\n if (this.helloTimer !== undefined) clearTimeout(this.helloTimer);\n this.helloTimer = undefined;\n this.welcomed = true;\n this.attempt = 0;\n const previous = new Map(this.players_);\n this.me_ = message.you;\n this.config_ = message.config;\n this.resume = message.resume;\n this.connection.seats?.watch(() => (this.status_ === \"closed\" ? undefined : this.resume));\n this.players_.clear();\n for (const player of message.players) this.players_.set(player.id, player);\n // Writes in flight when the connection dropped are either in this state already or lost.\n this.confirmed = message.state;\n this.inflight = [];\n this.turn_ = message.turn ?? { player: null };\n this.moves_ = message.moves ?? [];\n this.snap_ = message.snap ?? { tick: 0, players: {} };\n this.private_ = message.private ?? {};\n // Actions sent before a reconnect may or may not have reached the script; say so instead of guessing.\n this.settleActs(\n new CotchuError(\n \"internal\",\n \"The connection dropped before the room answered this action; check room.state, and act again if it didn't happen.\",\n ),\n );\n this.rebuild();\n this.startHeartbeat();\n this.setStatus(\"connected\");\n\n const settle = this.settle;\n this.settle = undefined;\n if (settle) {\n settle.resolve(this);\n } else {\n for (const [id, player] of previous) if (!this.players_.has(id)) this.emit(\"leave\", player);\n for (const [id, player] of this.players_) if (!previous.has(id)) this.emit(\"join\", player);\n this.emit(\"state\", this.view, { ops: [], by: null, reset: true });\n this.emit(\"change\");\n }\n this.outbox.flush();\n }\n\n private patched(message: ServerPatchMessage): void {\n const result = applyOps(this.confirmed, message.ops);\n if (!result.ok) {\n // The room applied this, so our copy has drifted. A fresh welcome fixes it.\n this.report(new CotchuError(\"internal\", \"This copy of the room fell out of sync; reconnecting to fix it.\"));\n if (this.ws) this.abandon(this.ws);\n return;\n }\n const own = message.by !== null && message.by === this.me_.id;\n const confirms = message.id;\n if (own && confirms !== undefined) {\n // The room handles messages in order, so anything older without a reply was dropped.\n this.inflight = this.inflight.filter((patch) => patch.id > confirms);\n }\n this.rebuild();\n // Our own writes were shown when we made them; only others' changes are news.\n if (!own) {\n this.emit(\"state\", this.view, { ops: message.ops, by: message.by, reset: false });\n this.emit(\"change\");\n }\n }\n\n private settleActs(error: CotchuError): void {\n for (const [, act] of this.acts) act.reject(error);\n this.acts.clear();\n }\n\n private errored(message: ErrMessage): void {\n const error = new CotchuError(message.code, message.message);\n const rejected = message.id;\n const act = rejected === undefined ? undefined : this.acts.get(rejected);\n if (act && rejected !== undefined) {\n this.acts.delete(rejected);\n act.reject(error); // the caller's promise carries this error; no need to report it again\n return;\n }\n if (rejected !== undefined) {\n const before = this.inflight.length;\n this.inflight = this.inflight.filter((patch) => patch.id !== rejected);\n if (this.inflight.length !== before) {\n this.rebuild();\n this.emit(\"state\", this.view, { ops: [], by: null, reset: true });\n this.emit(\"change\");\n }\n }\n if (error.fatal) return this.fail(error);\n if (this.settle) this.refusal = error; // still joining: this explains a failure better than \"unreachable\"\n this.report(error);\n }\n\n /** view = confirmed + every write the room hasn't confirmed yet, in order. */\n private rebuild(): void {\n const pending = [...this.inflight.flatMap((patch) => patch.ops), ...this.outbox.queuedOps()];\n if (pending.length === 0) {\n this.view = this.confirmed;\n return;\n }\n const view = structuredClone(this.confirmed);\n // A pending write that no longer applies is skipped; the room will reject it too.\n for (const op of pending) applyOps(view, [op]);\n this.view = view;\n }\n}\n", "/**\n * Remembers a tab's seat across reloads, so a player who reloads or reopens\n * the tab within the resume window gets the same seat back.\n *\n * The token lives in sessionStorage (one per tab) but only while the page is\n * going away: it's read and deleted on join, and written again on `pagehide`.\n * A reload or a reopened tab finds it. A duplicated tab copies sessionStorage\n * while the token is absent, so the copy gets its own seat instead of taking\n * the original's.\n */\n\ninterface BrowserLike {\n sessionStorage?: Storage;\n addEventListener?: (type: string, listener: () => void) => void;\n removeEventListener?: (type: string, listener: () => void) => void;\n}\n\nexport class SeatMemory {\n private token: (() => string | undefined) | undefined;\n private readonly onPageHide = () => {\n const token = this.token?.();\n if (token) this.write(token);\n };\n\n private constructor(\n private readonly key: string,\n private readonly browser: Required<BrowserLike>,\n ) {}\n\n /** Null outside browsers, or when storage is blocked (private mode, sandboxed frames). */\n static for(project: string, room: string): SeatMemory | null {\n const browser = globalThis as BrowserLike;\n try {\n if (!browser.sessionStorage || !browser.addEventListener || !browser.removeEventListener) return null;\n void browser.sessionStorage.length; // throws where storage is blocked\n } catch {\n return null;\n }\n return new SeatMemory(`cotchu:seat:${project}/${room}`, browser as Required<BrowserLike>);\n }\n\n /** Returns the remembered token, if any, and forgets it. */\n take(): string | undefined {\n try {\n const token = this.browser.sessionStorage.getItem(this.key) ?? undefined;\n this.browser.sessionStorage.removeItem(this.key);\n return token;\n } catch {\n return undefined;\n }\n }\n\n /** From now on, saves the current token whenever the page is hidden or unloaded. */\n watch(token: () => string | undefined): void {\n this.token = token;\n this.browser.addEventListener(\"pagehide\", this.onPageHide);\n }\n\n /** Stops saving and forgets the token: the player left for good. */\n forget(): void {\n this.token = undefined;\n this.browser.removeEventListener(\"pagehide\", this.onPageHide);\n try {\n this.browser.sessionStorage.removeItem(this.key);\n } catch {\n // Storage went away; nothing to forget.\n }\n }\n\n private write(token: string): void {\n try {\n this.browser.sessionStorage.setItem(this.key, token);\n } catch {\n // Storage full or blocked: the player just gets a new seat next time.\n }\n }\n}\n", "/**\n * cotchu: multiplayer rooms for games. No runtime dependencies.\n *\n * import { cotchu } from \"cotchu\";\n * const room = await cotchu.join(\"main-lobby\", { key: \"pk_live_\u2026\" });\n * room.on(\"state\", (state) => draw(state));\n * room.set(\"players.me\", { x: 10, y: 20 });\n */\nimport {\n DEFAULT_ROOMS_URL,\n PROTOCOL_VERSION,\n ROOMS_PATH_PREFIX,\n isRegion,\n isRoomName,\n parseClientMessage,\n projectOfKey,\n type HelloMessage,\n type MoveSchema,\n type RegionOption,\n type RoomOptions,\n type RoomType,\n} from \"@cotchu/protocol\";\nimport { CotchuError } from \"./errors.js\";\nimport { Room, type Connection } from \"./room.js\";\nimport { SeatMemory } from \"./seat-memory.js\";\n\n/** Matches package.json; sent to rooms in hello. */\nexport const SDK_VERSION = \"0.1.0\";\n\nexport interface JoinOptions {\n /** Your project's publishable key, `pk_live_<project>_<secret>`. Safe to ship in game code. */\n key: string;\n /** Rooms server address. Default: Cotchu's hosted rooms. Pass `ws://localhost:8790` to use a local dev server. */\n url?: string;\n /** This player's display name, up to 32 characters. */\n name?: string;\n /** Where to create the room if it doesn't exist yet. `auto` (default) places it near the first player. */\n region?: RegionOption;\n /** Room rules, used only by the player who creates the room. Later joiners get the room's rules. */\n type?: RoomType;\n /**\n * Run this project's deployed room script (`npx cotchu deploy room.js --name <name>`).\n * Makes the room a `script` room: the script owns the state, and players send actions with room.act().\n */\n script?: string;\n seats?: number;\n /** Paths players may write, such as `[\"players.$self\"]`. Default: every path. */\n writable?: string[];\n /** `turns` rooms: milliseconds per turn before it passes to the next player. Default: no timer. */\n turnMs?: number;\n /** `turns` rooms: the shape every move must have, as a JSON Schema subset. */\n moveSchema?: MoveSchema;\n /** `realtime` rooms: snapshots per second; `script` rooms: onTick calls per second. 1 to 30. */\n tickHz?: number;\n /** A WebSocket class, for runtimes without a global one (Node before 22). */\n WebSocket?: typeof WebSocket;\n /**\n * Browsers: give the seat back after a reload or a reopened tab, within the\n * 60 s resume window. Default true. Each tab keeps its own seat.\n */\n rememberSeat?: boolean;\n}\n\nfunction fail(code: ConstructorParameters<typeof CotchuError>[0], message: string): never {\n throw new CotchuError(code, message);\n}\n\nfunction roomsUrl(raw: string): string {\n let url: URL;\n try {\n url = new URL(raw.replace(/^http(s?):/, \"ws$1:\"));\n } catch {\n fail(\n \"unreachable\",\n `The url option ${JSON.stringify(raw)} isn't a valid address; pass one like wss://rooms.example.com.`,\n );\n }\n if (url.protocol !== \"ws:\" && url.protocol !== \"wss:\") {\n fail(\"unreachable\", `The url option must start with wss:// or ws://, not ${url.protocol}//; fix the url.`);\n }\n return url.origin.replace(/^http/, \"ws\") + url.pathname.replace(/\\/+$/, \"\");\n}\n\n/** Checks every option before connecting, so mistakes fail at the call, not later. */\nfunction prepare(room: string, options: JoinOptions): Connection {\n if (typeof options !== \"object\" || options === null) {\n fail(\"bad_key\", 'cotchu.join() needs options with your key, like cotchu.join(\"lobby\", { key: \"pk_live_\u2026\" }).');\n }\n const { key } = options;\n if (typeof key === \"string\" && key.startsWith(\"sk_\")) {\n fail(\"bad_key\", \"That's a secret key, which must never be in game code; pass your project's pk_live_ key instead.\");\n }\n const project = typeof key === \"string\" ? projectOfKey(key) : null;\n if (project === null) {\n fail(\n \"bad_key\",\n \"That isn't a Cotchu publishable key; pass your project's key, which looks like pk_live_<project>_<secret>, as the key option.\",\n );\n }\n if (!isRoomName(room)) {\n fail(\n \"bad_room\",\n `Room name ${JSON.stringify(room)} isn't valid; use letters, digits, '.', '_' and '-', up to 64 characters, starting with a letter or digit.`,\n );\n }\n const region = options.region ?? \"auto\";\n if (region !== \"auto\" && !isRegion(region))\n fail(\"bad_region\", `Region ${JSON.stringify(region)} isn't valid; use \"auto\".`);\n\n const Socket = options.WebSocket ?? (globalThis as { WebSocket?: typeof WebSocket }).WebSocket;\n if (!Socket) {\n fail(\"unreachable\", \"This runtime has no WebSocket; use Node 22 or newer, or pass one with the WebSocket option.\");\n }\n\n const roomOptions: RoomOptions = {};\n if (options.type !== undefined) roomOptions.type = options.type;\n if (options.seats !== undefined) roomOptions.seats = options.seats;\n if (options.writable !== undefined) roomOptions.writable = options.writable;\n if (options.turnMs !== undefined) roomOptions.turnMs = options.turnMs;\n if (options.tickHz !== undefined) roomOptions.tickHz = options.tickHz;\n if (options.script !== undefined) roomOptions.script = options.script;\n if (options.moveSchema !== undefined) roomOptions.moveSchema = options.moveSchema;\n const hello: HelloMessage = { t: \"hello\", v: PROTOCOL_VERSION, key, sdk: `cotchu-js/${SDK_VERSION}` };\n if (options.name !== undefined) hello.name = options.name;\n if (Object.keys(roomOptions).length > 0) hello.room = roomOptions;\n\n // The room's own validator, run here so bad options fail before connecting.\n const checked = parseClientMessage(JSON.stringify(hello));\n if (!checked.ok) {\n fail(\n checked.error.code,\n checked.error.message\n .replace(/^hello\\.room\\./, \"cotchu.join() option \")\n .replace(/^hello\\./, \"cotchu.join() option \"),\n );\n }\n\n const query = region === \"auto\" ? \"\" : `?region=${region}`;\n return {\n url: `${roomsUrl(options.url ?? DEFAULT_ROOMS_URL)}${ROOMS_PATH_PREFIX}${project}/${room}${query}`,\n hello: checked.message as HelloMessage,\n WebSocket: Socket,\n seats: options.rememberSeat === false ? null : SeatMemory.for(project, room),\n };\n}\n\n/**\n * Joins `room`, creating it if nobody is in it yet. Resolves once the room has\n * welcomed this player, with its current state and players. Rejects with a\n * CotchuError whose message says what to fix.\n */\nexport function join(room: string, options: JoinOptions): Promise<Room> {\n let connection: Connection;\n try {\n connection = prepare(room, options);\n } catch (error) {\n return Promise.reject(error);\n }\n return new Room(room, connection).open();\n}\n\nexport const cotchu = { join, version: SDK_VERSION };\n\nexport { CotchuError, Room };\nexport type { PathInput } from \"./paths.js\";\nexport type { RoomEvents, RoomStatus, StateChange } from \"./room.js\";\nexport type {\n ErrorCode,\n JsonObject,\n JsonValue,\n Move,\n MoveSchema,\n PatchOp,\n Player,\n Region,\n RegionOption,\n RoomConfig,\n RoomType,\n} from \"@cotchu/protocol\";\n"],
5
+ "mappings": ";AAKO,IAAM,gBAAgB;AAOtB,IAAM,YAAY;AAMlB,IAAM,qBAAqB;AAS3B,IAAM,4BAA4B;AAClC,IAAM,0BAA0B;AAehC,IAAM,6BAA6B;AASnC,IAAM,cAAc;AACpB,IAAM,cAAc;AAOpB,IAAM,kBAAkB;AAGxB,IAAM,cAAc;AACpB,IAAM,cAAc;AAGpB,IAAM,iBAAiB;AAGvB,IAAM,iBAAiB;AAGvB,IAAM,kBAAkB;AAGxB,IAAM,oBAAoB;AAM1B,IAAM,wBAAwB;AAM9B,IAAM,mBAAmB;AACzB,IAAM,mBAAmB;AAYzB,IAAM,kBAAkB;AAGxB,IAAM,uBAAuB;;;ACrG7B,IAAM,mBAAmB;AAMzB,IAAM,aAAa,CAAC,UAAU,SAAS,YAAY,QAAQ;AAO3D,IAAM,UAAU;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,IAAM,oBAAoB;AAG1B,IAAM,oBAAoB;AAM1B,IAAM,oBAAoB,IAAI,OAAO,gCAAgC,uBAAuB,CAAC,IAAI;AAMjG,IAAM,aAAa;AAGnB,SAAS,WAAW,OAAmC;AAC5D,SAAO,OAAO,UAAU,YAAa,W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AAO,KAAK,WAAW,EAAE,SAAS,EAAG,OAAM,OAAO;AAGtD,QAAM,UAAU,mBAAmB,KAAK,UAAU,KAAK,CAAC;AACxD,MAAI,CAAC,QAAQ,IAAI;AACf;AAAA,MACE,QAAQ,MAAM;AAAA,MACd,QAAQ,MAAM,QACX,QAAQ,kBAAkB,uBAAuB,EACjD,QAAQ,YAAY,uBAAuB;AAAA,IAChD;AAAA,EACF;AAEA,QAAM,QAAQ,WAAW,SAAS,KAAK,WAAW,MAAM;AACxD,SAAO;AAAA,IACL,KAAK,GAAG,SAAS,QAAQ,OAAO,iBAAiB,CAAC,GAAG,iBAAiB,GAAG,OAAO,IAAI,IAAI,GAAG,KAAK;AAAA,IAChG,OAAO,QAAQ;AAAA,IACf,WAAW;AAAA,IACX,OAAO,QAAQ,iBAAiB,QAAQ,OAAO,WAAW,IAAI,SAAS,IAAI;AAAA,EAC7E;AACF;AAOO,SAAS,KAAK,MAAc,SAAqC;AACtE,MAAI;AACJ,MAAI;AACF,iBAAa,QAAQ,MAAM,OAAO;AAAA,EACpC,SAAS,OAAO;AACd,WAAO,QAAQ,OAAO,KAAK;AAAA,EAC7B;AACA,SAAO,IAAI,KAAK,MAAM,UAAU,EAAE,KAAK;AACzC;AAEO,IAAM,SAAS,EAAE,MAAM,SAAS,YAAY;",
6
+ "names": ["isObject", "isObject", "isObject"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "cotchu",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Multiplayer, settled. The Cotchu client for browsers and Node.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "devDependencies": {
18
+ "@cotchu/protocol": "0.0.0",
19
+ "esbuild": "^0.28.2",
20
+ "rollup": "^4.0.0",
21
+ "rollup-plugin-dts": "^6.5.1",
22
+ "wrangler": "^4.163.0",
23
+ "@types/node": "^24.0.0"
24
+ },
25
+ "bin": {
26
+ "cotchu": "./dist/cli.js"
27
+ },
28
+ "homepage": "https://cotchu.com",
29
+ "keywords": [
30
+ "multiplayer",
31
+ "games",
32
+ "websocket",
33
+ "realtime",
34
+ "rooms"
35
+ ],
36
+ "engines": {
37
+ "node": ">=22"
38
+ },
39
+ "unpkg": "./dist/cotchu.min.js",
40
+ "jsdelivr": "./dist/cotchu.min.js",
41
+ "scripts": {
42
+ "build": "node scripts/build.mjs",
43
+ "typecheck": "tsc -p tsconfig.json && tsc -p cli/tsconfig.json"
44
+ }
6
45
  }