cotchu 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -28,6 +28,14 @@ declare const ERRORS: {
28
28
  readonly fatal: true;
29
29
  readonly message: "Every seat in this room is taken; try again in a moment or join a different room name.";
30
30
  };
31
+ readonly room_exists: {
32
+ readonly fatal: true;
33
+ readonly message: "A room with this name is already open, and this join used mode \"create\"; pick a new name (for a lobby code, generate another) or join it with mode \"join\".";
34
+ };
35
+ readonly room_not_found: {
36
+ readonly fatal: true;
37
+ readonly message: "No room with this name is open, and this join used mode \"join\"; check the name or code, or create the room with mode \"create\".";
38
+ };
31
39
  readonly room_limit: {
32
40
  readonly fatal: true;
33
41
  readonly message: "This project already has 50 rooms open, its current limit; finished rooms close a minute after their last player leaves.";
@@ -190,6 +198,10 @@ interface RoomConfig {
190
198
  name: string;
191
199
  version: string;
192
200
  };
201
+ /** The room appears in its project's room list (GET /v1/projects/<project>/rooms). */
202
+ listed?: true;
203
+ /** Listed rooms: dot path in the room's state whose value the list shows as `info`, e.g. "lobby". */
204
+ listing?: string;
193
205
  }
194
206
  /**
195
207
  * What a joiner may ask for. Ignored by a room that already exists, except
@@ -199,6 +211,26 @@ interface RoomConfig {
199
211
  interface RoomOptions extends Partial<Omit<RoomConfig, "script">> {
200
212
  script?: string;
201
213
  }
214
+ /**
215
+ * How a hello treats the room's existence. `auto` joins the room, creating it
216
+ * if needed. `create` only creates: it's refused with `room_exists` if the room
217
+ * is open. `join` only joins: it's refused with `room_not_found` if it isn't.
218
+ * Resuming a seat always works, whatever the mode.
219
+ */
220
+ type JoinMode = "auto" | "create" | "join";
221
+ /** One room in a project's room list. */
222
+ interface RoomListing {
223
+ /** Room name: join it with this. */
224
+ name: string;
225
+ type: RoomType;
226
+ /** Players connected right now. */
227
+ players: number;
228
+ seats: number;
229
+ /** The value at the room's `listing` path, or null (unset, or over MAX_LISTING_BYTES). */
230
+ info: JsonValue;
231
+ /** Epoch milliseconds when the room opened. */
232
+ openedAt: number;
233
+ }
202
234
  interface Player {
203
235
  id: string;
204
236
  name: string;
@@ -241,6 +273,8 @@ interface HelloMessage {
241
273
  token?: string;
242
274
  /** `resume` from an earlier `welcome`, to take back a seat within RESUME_WINDOW_MS. */
243
275
  resume?: string;
276
+ /** Whether this hello may create the room, join it, or both (the default, `auto`). */
277
+ mode?: JoinMode;
244
278
  /** Rules for the room if this hello creates it. */
245
279
  room?: RoomOptions;
246
280
  }
@@ -470,7 +504,7 @@ declare class Room extends Emitter<RoomEvents> {
470
504
  */
471
505
 
472
506
  /** Matches package.json; sent to rooms in hello. */
473
- declare const SDK_VERSION = "0.1.0";
507
+ declare const SDK_VERSION = "0.2.0";
474
508
  interface JoinOptions {
475
509
  /** Your project's publishable key, `pk_live_<project>_<secret>`. Safe to ship in game code. */
476
510
  key: string;
@@ -478,6 +512,12 @@ interface JoinOptions {
478
512
  url?: string;
479
513
  /** This player's display name, up to 32 characters. */
480
514
  name?: string;
515
+ /**
516
+ * `"auto"` (default): join the room, creating it if needed. `"create"`: only
517
+ * create it; rejects with `room_exists` if it's open. `"join"`: only join;
518
+ * rejects with `room_not_found` if it isn't open. Building block for lobby codes.
519
+ */
520
+ mode?: JoinMode;
481
521
  /** Where to create the room if it doesn't exist yet. `auto` (default) places it near the first player. */
482
522
  region?: RegionOption;
483
523
  /** Room rules, used only by the player who creates the room. Later joiners get the room's rules. */
@@ -496,6 +536,10 @@ interface JoinOptions {
496
536
  moveSchema?: MoveSchema;
497
537
  /** `realtime` rooms: snapshots per second; `script` rooms: onTick calls per second. 1 to 30. */
498
538
  tickHz?: number;
539
+ /** Show the room in cotchu.rooms(), the project's room list. Default false: only people who know the name can join. */
540
+ listed?: boolean;
541
+ /** Listed rooms: a state path whose value cotchu.rooms() shows as `info`, like `"lobby"`. Implies `listed`. */
542
+ listing?: string;
499
543
  /** A WebSocket class, for runtimes without a global one (Node before 22). */
500
544
  WebSocket?: typeof WebSocket;
501
545
  /**
@@ -510,10 +554,26 @@ interface JoinOptions {
510
554
  * CotchuError whose message says what to fix.
511
555
  */
512
556
  declare function join(room: string, options: JoinOptions): Promise<Room>;
557
+ interface RoomsOptions {
558
+ /** Your project's publishable key, the same one the game joins with. */
559
+ key: string;
560
+ /** Rooms server address, as for join(). Default: Cotchu's hosted rooms. */
561
+ url?: string;
562
+ /** A fetch function, for runtimes without a global one. */
563
+ fetch?: typeof fetch;
564
+ }
565
+ /**
566
+ * The project's listed rooms (joined with `listed: true` or a `listing`),
567
+ * newest first, up to 100. Each has `name`, `type`, `players`, `seats`,
568
+ * `info` (the value at the room's listing path) and `openedAt`. Filter and
569
+ * sort them however the game likes, then join one by name.
570
+ */
571
+ declare function rooms(options: RoomsOptions): Promise<RoomListing[]>;
513
572
  declare const cotchu: {
514
573
  join: typeof join;
574
+ rooms: typeof rooms;
515
575
  version: string;
516
576
  };
517
577
 
518
- export { CotchuError, Room, SDK_VERSION, cotchu, join };
519
- export type { ErrorCode, JoinOptions, JsonObject, JsonValue, Move, MoveSchema, PatchOp, PathInput, Player, Region, RegionOption, RoomConfig, RoomEvents, RoomStatus, RoomType, StateChange };
578
+ export { CotchuError, Room, SDK_VERSION, cotchu, join, rooms };
579
+ export type { ErrorCode, JoinMode, JoinOptions, JsonObject, JsonValue, Move, MoveSchema, PatchOp, PathInput, Player, Region, RegionOption, RoomConfig, RoomEvents, RoomListing, RoomStatus, RoomType, RoomsOptions, StateChange };
package/dist/index.js CHANGED
@@ -37,6 +37,13 @@ var REGIONS = [
37
37
  "me"
38
38
  ];
39
39
  var ROOMS_PATH_PREFIX = "/v1/rooms/";
40
+ var JOIN_MODES = ["auto", "create", "join"];
41
+ function isJoinMode(value) {
42
+ return typeof value === "string" && JOIN_MODES.includes(value);
43
+ }
44
+ function httpUrlFor(roomsUrl2) {
45
+ return roomsUrl2.replace(/^ws(s?):\/\//, "http$1://").replace(/\/+$/, "");
46
+ }
40
47
  var DEFAULT_ROOMS_URL = "wss://rooms.cotchu.com";
41
48
  var ROOM_NAME_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._-]{0,${MAX_ROOM_NAME_LENGTH - 1}}$`);
42
49
  var PING_FRAME = '{"t":"ping"}';
@@ -85,6 +92,14 @@ var ERRORS = {
85
92
  fatal: true,
86
93
  message: "Every seat in this room is taken; try again in a moment or join a different room name."
87
94
  },
95
+ room_exists: {
96
+ fatal: true,
97
+ message: 'A room with this name is already open, and this join used mode "create"; pick a new name (for a lobby code, generate another) or join it with mode "join".'
98
+ },
99
+ room_not_found: {
100
+ fatal: true,
101
+ message: 'No room with this name is open, and this join used mode "join"; check the name or code, or create the room with mode "create".'
102
+ },
88
103
  room_limit: {
89
104
  fatal: true,
90
105
  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.`
@@ -472,7 +487,17 @@ var MAX_KEY_STRING = 256;
472
487
  var MAX_SDK_STRING = 64;
473
488
  var MAX_TOKEN_STRING = 4096;
474
489
  var MAX_PLAYER_ID_STRING = 64;
475
- var ROOM_OPTION_KEYS = ["type", "seats", "writable", "turnMs", "tickHz", "moveSchema", "script"];
490
+ var ROOM_OPTION_KEYS = [
491
+ "type",
492
+ "seats",
493
+ "writable",
494
+ "turnMs",
495
+ "tickHz",
496
+ "moveSchema",
497
+ "script",
498
+ "listed",
499
+ "listing"
500
+ ];
476
501
  var FORMATS_HINT = "see the message formats in llms.txt, or send it through the cotchu SDK";
477
502
  var Invalid = class extends Error {
478
503
  constructor(code, message) {
@@ -652,7 +677,7 @@ function readRoomOptions(value) {
652
677
  }
653
678
  }
654
679
  const options = {};
655
- const { type, seats, writable, turnMs, tickHz, moveSchema, script } = value;
680
+ const { type, seats, writable, turnMs, tickHz, moveSchema, script, listed, listing } = value;
656
681
  if (type !== void 0) {
657
682
  if (!isRoomType(type)) {
658
683
  invalid(`${where}.type`, `is ${describe(type)}`, 'use "shared", "turns", "realtime" or "script"');
@@ -696,10 +721,35 @@ function readRoomOptions(value) {
696
721
  }
697
722
  options.moveSchema = moveSchema;
698
723
  }
724
+ if (listed !== void 0) {
725
+ if (typeof listed !== "boolean") invalid(`${where}.listed`, `is ${describe(listed)}`, "use true or false");
726
+ if (listed) options.listed = true;
727
+ }
728
+ if (listing !== void 0) {
729
+ if (listed === false) {
730
+ invalid(`${where}.listing`, "only applies to listed rooms", "remove it, or drop listed: false");
731
+ }
732
+ options.listing = readListingPath(listing);
733
+ options.listed = true;
734
+ }
699
735
  return options;
700
736
  }
737
+ function readListingPath(value) {
738
+ const where = "hello.room.listing";
739
+ const text = readString(value, where, MAX_KEY_STRING, 'name a state path, like "lobby"');
740
+ const keys = text.split(".");
741
+ if (keys.length > MAX_PATH_DEPTH) invalid(where, `has more than ${MAX_PATH_DEPTH} keys`, "point at a shallower path");
742
+ for (const key of keys) {
743
+ if (key === ANY_SEGMENT || key === SELF_SEGMENT) {
744
+ invalid(where, `uses "${key}", which only works in writable patterns`, 'name one exact state path, like "lobby"');
745
+ }
746
+ const problem = keyProblem(key);
747
+ if (problem) invalid(where, problem, 'name a state path, like "lobby"');
748
+ }
749
+ return text;
750
+ }
701
751
  function readHello(message) {
702
- const { v, key, sdk, name, token, resume, room } = message;
752
+ const { v, key, sdk, name, token, resume, mode, room } = message;
703
753
  if (typeof v !== "number" || !Number.isInteger(v)) {
704
754
  invalid("hello.v", "must be the protocol version number", `send ${PROTOCOL_VERSION}`);
705
755
  }
@@ -729,6 +779,11 @@ function readHello(message) {
729
779
  if (resume !== void 0) {
730
780
  hello.resume = readString(resume, "hello.resume", MAX_KEY_STRING, "send the resume value from welcome unchanged");
731
781
  }
782
+ if (mode !== void 0) {
783
+ if (!isJoinMode(mode))
784
+ invalid("hello.mode", `is ${describe(mode)}`, `use ${JOIN_MODES.map((m) => `"${m}"`).join(", ")}`);
785
+ if (mode !== "auto") hello.mode = mode;
786
+ }
732
787
  if (room !== void 0) hello.room = readRoomOptions(room);
733
788
  return hello;
734
789
  }
@@ -1656,10 +1711,23 @@ var SeatMemory = class _SeatMemory {
1656
1711
  };
1657
1712
 
1658
1713
  // src/index.ts
1659
- var SDK_VERSION = "0.1.0";
1714
+ var SDK_VERSION = "0.2.0";
1660
1715
  function fail(code, message) {
1661
1716
  throw new CotchuError(code, message);
1662
1717
  }
1718
+ function projectFor(key, call) {
1719
+ if (typeof key === "string" && key.startsWith("sk_")) {
1720
+ fail("bad_key", "That's a secret key, which must never be in game code; pass your project's pk_live_ key instead.");
1721
+ }
1722
+ const project = typeof key === "string" ? projectOfKey(key) : null;
1723
+ if (project === null) {
1724
+ fail(
1725
+ "bad_key",
1726
+ `That isn't a Cotchu publishable key; pass your project's key, which looks like pk_live_<project>_<secret>, as the key option to ${call}.`
1727
+ );
1728
+ }
1729
+ return project;
1730
+ }
1663
1731
  function roomsUrl(raw) {
1664
1732
  let url;
1665
1733
  try {
@@ -1680,16 +1748,7 @@ function prepare(room, options) {
1680
1748
  fail("bad_key", 'cotchu.join() needs options with your key, like cotchu.join("lobby", { key: "pk_live_\u2026" }).');
1681
1749
  }
1682
1750
  const { key } = options;
1683
- if (typeof key === "string" && key.startsWith("sk_")) {
1684
- fail("bad_key", "That's a secret key, which must never be in game code; pass your project's pk_live_ key instead.");
1685
- }
1686
- const project = typeof key === "string" ? projectOfKey(key) : null;
1687
- if (project === null) {
1688
- fail(
1689
- "bad_key",
1690
- "That isn't a Cotchu publishable key; pass your project's key, which looks like pk_live_<project>_<secret>, as the key option."
1691
- );
1692
- }
1751
+ const project = projectFor(key, "cotchu.join()");
1693
1752
  if (!isRoomName(room)) {
1694
1753
  fail(
1695
1754
  "bad_room",
@@ -1711,8 +1770,11 @@ function prepare(room, options) {
1711
1770
  if (options.tickHz !== void 0) roomOptions.tickHz = options.tickHz;
1712
1771
  if (options.script !== void 0) roomOptions.script = options.script;
1713
1772
  if (options.moveSchema !== void 0) roomOptions.moveSchema = options.moveSchema;
1773
+ if (options.listed !== void 0) roomOptions.listed = options.listed;
1774
+ if (options.listing !== void 0) roomOptions.listing = options.listing;
1714
1775
  const hello = { t: "hello", v: PROTOCOL_VERSION, key, sdk: `cotchu-js/${SDK_VERSION}` };
1715
1776
  if (options.name !== void 0) hello.name = options.name;
1777
+ if (options.mode !== void 0) hello.mode = options.mode;
1716
1778
  if (Object.keys(roomOptions).length > 0) hello.room = roomOptions;
1717
1779
  const checked = parseClientMessage(JSON.stringify(hello));
1718
1780
  if (!checked.ok) {
@@ -1738,12 +1800,31 @@ function join(room, options) {
1738
1800
  }
1739
1801
  return new Room(room, connection).open();
1740
1802
  }
1741
- var cotchu = { join, version: SDK_VERSION };
1803
+ async function rooms(options) {
1804
+ const project = projectFor(options?.key, "cotchu.rooms()");
1805
+ const doFetch = options.fetch ?? globalThis.fetch;
1806
+ if (!doFetch)
1807
+ fail("unreachable", "This runtime has no fetch; use Node 22 or newer, or pass one with the fetch option.");
1808
+ const base = httpUrlFor(roomsUrl(options.url ?? DEFAULT_ROOMS_URL));
1809
+ const address = `${base}/v1/projects/${project}/rooms?key=${encodeURIComponent(options.key)}`;
1810
+ let response;
1811
+ try {
1812
+ response = await doFetch(address);
1813
+ } catch {
1814
+ fail("unreachable", "Couldn't reach Cotchu to list rooms; check the network and any url option, then try again.");
1815
+ }
1816
+ const body = await response.json().catch(() => null);
1817
+ if (response.ok && Array.isArray(body?.rooms)) return body.rooms;
1818
+ const code = isErrorCode(body?.error) ? body.error : "internal";
1819
+ fail(code, body?.message ?? `Listing rooms failed with HTTP ${response.status}; try again in a moment.`);
1820
+ }
1821
+ var cotchu = { join, rooms, version: SDK_VERSION };
1742
1822
  export {
1743
1823
  CotchuError,
1744
1824
  Room,
1745
1825
  SDK_VERSION,
1746
1826
  cotchu,
1747
- join
1827
+ join,
1828
+ rooms
1748
1829
  };
1749
1830
  //# sourceMappingURL=index.js.map