@hadoku/game-ui 0.1.103 → 0.1.105

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.
@@ -1,271 +0,0 @@
1
- import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- /*
3
- * Watchparty's room around our table.
4
- *
5
- * The operator asked for this three times — *"we gotta connect this to my room
6
- * and network system"* — and it was blocked, not ignored: until
7
- * `@wolffm/watchparty-ui@0.39.0` the package exported only a whole-app
8
- * `mount()` that brought its own React root, its own router, 6.76 MB of bundle
9
- * and 34 inlined PNGs, and had no slot to put a table in (D17). `RoomChrome`
10
- * is the export we asked them for, and it lands at **152 KB with zero inlined
11
- * images**, importing nothing from their chunk graph.
12
- *
13
- * ## One chrome per page
14
- *
15
- * Their store and socket are module singletons, so a second `RoomChrome` on
16
- * the same page would share — and then tear down — the first one's connection.
17
- * That is why this mounts once, in `App`, and never per screen.
18
- *
19
- * ## The room is ours; only the art is theirs
20
- *
21
- * `roomOrigin` points the chrome's whole room socket — join, roster, identity,
22
- * chat — at `appOrigin()`: this app's own `/room` namespace
23
- * (`games/magic/server/src/room/serve.ts`), behind cardtable's member gate, with the
24
- * roster read from the same presence tracker our seats use. Watchparty never
25
- * hears of a cardtable room, so it neither counts one nor holds a deploy for
26
- * it. `serverOrigin` is still watchparty's, for the characters' names and art.
27
- * Name, picture and character are the account's, resolved by our server.
28
- *
29
- * ## Identity comes from the fleet, not from us
30
- *
31
- * This used to call cardtable's own `/api/whoami`, which returns `{ userId,
32
- * tier }` and no display name — so the app rendered `anon`, which is literally
33
- * `ANON_USER_ID` from `@wolffm/prefs-client`, beside a chat column that knew
34
- * the operator's real name. That is the same gap that left this app with no
35
- * theme picker: it was hydrated from `tunnel-loopback-ui`, which scaffolds no
36
- * UI, and the hydrator's chrome warning only fires for proxy apps
37
- * (`docs/requests/HADOKU_SITE_GAME_TEMPLATE.md`).
38
- *
39
- * `whoami()` from `@wolffm/prefs-client` is the fleet's own, returns `name`,
40
- * and shares one in-flight promise per page (`globalThis.__hadokuWhoami`) so
41
- * several apps on a page do not each re-fetch it.
42
- *
43
- * We still do NOT invent an identity: if it fails the chrome is not mounted
44
- * and the table renders alone, because a room that cannot say who you are is
45
- * worse than no room.
46
- */
47
- import { useCallback, useEffect, useRef, useState } from 'react';
48
- import { createPortal } from 'react-dom';
49
- import '@wolffm/watchparty-ui/room-chrome.css';
50
- import { ANON_USER_ID } from '@wolffm/prefs-client';
51
- import { useHadokuTheme } from '@wolffm/themes';
52
- import { ROOM_ID_RE } from '@wolffm/platform-wire/room-feed';
53
- import { appId } from '@wolffm/ui-shell/app-id';
54
- import { useRoomFrame } from '@wolffm/ui-shell/chrome/shell';
55
- // The watchparty seam's two data answers — which origin serves their sprites,
56
- // and which character this viewer picked — live in one module with the bundle
57
- // evidence beside them. `watchpartyOrigin` used to be a private function here;
58
- // it moved because `avatarSquareUrl` needs the same string and two derivations
59
- // of one origin is how the chrome and the faces come to disagree about it.
60
- import { watchpartyOrigin } from "./avatar.js";
61
- import { useWhoami } from "./whoami.js";
62
- import { useChatless, useToolbarPageOn } from "../chrome/toolbarPage.js";
63
- /*
64
- * Their chrome, in its own chunk: only a room needs it, and a game's front door is lighter by the
65
- * whole of it. Loaded as soon as a RoomShell first draws (one per page, from the app's root), so by
66
- * the time a room's route is shown it is usually here; until it is, the room waits exactly as it
67
- * waits for whoami.
68
- */
69
- let chromeLoad = null;
70
- let loadedChrome = null;
71
- /** Starts loading the chrome's chunk, once per page; a front door may call it to fetch it early. */
72
- export function loadRoomChrome() {
73
- chromeLoad ??= import('@wolffm/watchparty-ui/room-chrome').then((m) => (loadedChrome = m.RoomChrome), (err) => {
74
- // The next RoomShell to draw asks again.
75
- chromeLoad = null;
76
- throw err;
77
- });
78
- return chromeLoad;
79
- }
80
- /** The chrome's component once its chunk is here, else null. */
81
- function useRoomChrome() {
82
- const [chrome, setChrome] = useState(() => loadedChrome);
83
- useEffect(() => {
84
- if (chrome !== null)
85
- return;
86
- let live = true;
87
- loadRoomChrome().then((loaded) => {
88
- if (live)
89
- setChrome(() => loaded);
90
- }, (err) => {
91
- // The room renders without its chat: a degraded room, not an outage.
92
- console.error('room chrome: its chunk did not load', err);
93
- });
94
- return () => {
95
- live = false;
96
- };
97
- }, [chrome]);
98
- return chrome;
99
- }
100
- /**
101
- * The page's resolved theme, handed to the chrome as-is.
102
- *
103
- * ## Why the two disagreed, diagnosed rather than assumed (w20 §E)
104
- *
105
- * `RoomChrome` takes an optional `theme` prop. Left unset — which is what this
106
- * file did until w20 — it resolves its OWN default from ITS OWN internal
107
- * store, entirely independent of `HadokuThemeRoot` (quoted in full below).
108
- * Measured live (a stub-`whoami` build served
109
- * locally, `#/match/…`, no saved theme in either storage): the page resolved
110
- * `data-theme="light"` on `.cardtable-chrome` while `.wp-room-chrome` sat at
111
- * `data-theme="dark"` — two independent defaults, not a shared one that drifted.
112
- * Passing our theme through removes the second default entirely; they cannot
113
- * disagree once there is only one source.
114
- *
115
- * ## Why this casts instead of validating (w22 §G, found by hadoku_site)
116
- *
117
- * This used to filter through `THEMES` and answer `undefined` for a name it did
118
- * not recognise. `undefined` is not a neutral value here — it is precisely what
119
- * sends the chrome back to that second default, so the filter reintroduced the
120
- * split-theme bug in the one case it was written to protect against.
121
- *
122
- * That case is unreachable today: one `@wolffm/themes` install (5.8.6), and
123
- * `room-chrome.d.ts:3` imports `Theme` from it, so there is a single union. But
124
- * watchparty-ui takes themes as a regular **dependency** (`^5.8.5`), not a peer,
125
- * so a host outside that range resolves a second nested copy and two distinct
126
- * unions exist. There, passing an unrecognised name through is strictly better
127
- * than dropping it, and the shipped code is why — read out of the installed
128
- * bundle, its fallback is:
129
- *
130
- * function Do(e) { if (e) return e; const t = ze().theme;
131
- * return t && tn.includes(t) ? t : "dark"; }
132
- *
133
- * The prop is honoured VERBATIM, unvalidated, and lands on `data-theme` of the
134
- * chrome's own `aside.wp-room-chrome` — never on the host document. Only a
135
- * FALSY prop makes the chrome consult its own store and then hard-code `dark`.
136
- * So an unknown name resolves against whichever `[data-theme=…]` palettes are
137
- * loaded and otherwise falls to a neutral light base; `undefined` resolves to
138
- * an actively wrong `dark`. `undefined` is the only value that cannot be
139
- * ignored.
140
- *
141
- * Corrected against the installed bundle rather than taken on trust: the §G brief said
142
- * `room-chrome.css` "styles only its own light/dark internals". It does not —
143
- * it ships all 18 `[data-theme=…]` blocks under `@scope (.wp-room-chrome)`,
144
- * with `:scope,:scope[data-theme=light]` as the fallback rule, the same 18 the
145
- * host's `@wolffm/themes/src/style.css` carries unscoped. That changes the
146
- * reason, not the fix: what makes the pass-through work is `if (e) return e`,
147
- * not a gap in the chrome's own palettes.
148
- *
149
- * ## The trap, for whoever edits this next
150
- *
151
- * The cast is load-bearing twice, and only one half announces itself.
152
- * `theme={theme}` fails typecheck — TS2322, because `useHadokuTheme()` types
153
- * `theme` as `string` (the picker's families are data-driven) — which is what
154
- * sends people looking for a validator in the first place. But
155
- * `theme={filtered ?? undefined}` compiles cleanly and IS the defect. Only the
156
- * type error is loud; the wrong fix is silent. The `Theme` return type below,
157
- * with no `| undefined`, is what makes the silent half loud too: a re-added
158
- * `?? undefined` stops compiling here instead of shipping a chrome that resolves
159
- * its own theme.
160
- */
161
- export function watchpartyTheme(theme) {
162
- // Total by construction — every name reaches the chrome, including one this
163
- // install's union does not know. Never narrow this to `Theme | undefined`.
164
- return theme;
165
- }
166
- /**
167
- * A room key for one of our pods or matches, or null when the id is not a
168
- * shape watchparty will accept.
169
- *
170
- * Null means "render the table with no room" — never a guessed or coerced key,
171
- * because two ids that collapse to the same key would put two unrelated groups
172
- * in one room, and they would each see the other's chat.
173
- */
174
- export function roomKeyFor(id) {
175
- return ROOM_ID_RE.test(id) ? `${appId()}-${id}` : null;
176
- }
177
- /**
178
- * This app's own origin, on whatever host serves this page — never
179
- * hardcoded, so PPE (built with `CARDTABLE_BASE_PREFIX=/cardtable-ppe`) gets
180
- * PPE's own origin rather than prod's. The same derivation
181
- * `room/socket-options.ts`'s `defaultSocketPath` uses for the draft socket's
182
- * path, here producing an ORIGIN string: `RoomChrome` derives its socket
183
- * path, `/cardtable[-ppe]/socket.io/`, from its pathname, so passing the
184
- * bare base is enough — no `roomSocketPath` override needed.
185
- */
186
- export function appOrigin() {
187
- const base = import.meta.env?.BASE_URL;
188
- const prefix = typeof base === 'string' && base !== '' ? base : '/';
189
- return `${globalThis.location.origin}${prefix}`.replace(/\/$/, '');
190
- }
191
- /**
192
- * Wraps `children` in watchparty's room when there is a room to be in.
193
- *
194
- * Renders the children alone when there is no room id or when whoami failed. A
195
- * table without chat is a degraded room; a table that will not draw because
196
- * chat is down is an outage.
197
- *
198
- * The children mount ONCE, whatever the chrome does around them. Remounted, they
199
- * lose everything they hold and open their sockets again: a match opened from a
200
- * link joined on two sockets and hung up the first, and when the hang-up beat the
201
- * second join the server saw the seat leave (`e2e/w69-name-card.spec.ts`, "nobody
202
- * disconnected"); a joiner's room screen, drawn before its join and wrapped once
203
- * the join let the chat in (`App.tsx`'s `useJoined`), dropped an open Room
204
- * settings and connected its draft socket twice (`e2e/w83b-draft-rope.spec.ts`).
205
- * So they are rendered through a portal from one place in this component's tree,
206
- * into a node that moves into the chrome when it draws and out when it goes. That
207
- * node and the slot holding it are both `.chrome-slot` (`display: contents`), and
208
- * the chrome's rules for its content's own child reach through exactly those two
209
- * (`@hadoku/ui-shell`'s `chrome.css`; `display: contents` is also set on them here, for a game
210
- * that loads no such sheet). While whoami or the chrome's chunk is in flight on a room's route,
211
- * before they have first mounted, they wait for it, showing `fallback`: their first frame is already
212
- * inside. After that, they show bare while the chrome is not drawn.
213
- */
214
- export function RoomShell({ roomId, collapsible = true, inert = false, fallback = null, requireIdentified = false, toolbar, pending = false, children, }) {
215
- const who = useWhoami();
216
- const RoomChrome = useRoomChrome();
217
- // Always inside `AppChrome`'s `HadokuThemeRoot` — see chrome/AppChrome.tsx,
218
- // which mounts this component. `useHadokuTheme()` throws with no provider
219
- // on purpose (a silent fallback is the bug this removes), so a caller that
220
- // ever renders `RoomShell` outside the theme root takes that throw here.
221
- const { theme } = useHadokuTheme();
222
- const key = roomId === null ? null : roomKeyFor(roomId);
223
- const roomFrameRef = useRoomFrame();
224
- const [host] = useState(createHost);
225
- const mounted = useRef(false);
226
- const unknown = who === null || (requireIdentified && who !== 'pending' && who.userId === ANON_USER_ID);
227
- // No chat will draw here, so the page keeps its top bar whatever its screen asked for.
228
- useChatless(!pending && (key === null || unknown));
229
- const toolbarPage = useToolbarPageOn();
230
- const waiting = key !== null && !unknown && (who === 'pending' || RoomChrome === null);
231
- // Waiting before the first mount shows the fallback; after it, the content stays where it is.
232
- const holding = waiting && !mounted.current;
233
- if (!holding)
234
- mounted.current = true;
235
- // One keyed element in every branch below, so React keeps the children; last, so the slot has
236
- // taken the host in before their layout effects run.
237
- const content = mounted.current ? createPortal(children, host, 'content') : null;
238
- if (holding)
239
- return _jsx(_Fragment, { children: fallback });
240
- if (key === null || unknown || who === 'pending' || RoomChrome === null)
241
- return (_jsxs(_Fragment, { children: [_jsx(Slot, { host: host }, "bare"), content] }));
242
- return (
243
- /*
244
- * Wave 89 §B: `data-collapsible` is this element's own, not a prop
245
- * `RoomChrome` takes — `RoomChromeProps` (the installed `room-chrome.d.ts`)
246
- * has nothing for a host to read or set the chat column's open state from
247
- * outside. `live.css`'s portrait rules key the chat-sheet behaviour off
248
- * this attribute rather than off `collapsible` turning the chrome's own
249
- * "Hide chat" button on or off, because `collapsible` is a prop value, not
250
- * a selector a stylesheet in another file can see — and only present at
251
- * all when `collapsible` is true, i.e. a match route (`App.tsx`'s
252
- * `route.kind !== 'room'`), never the room lobby (Settled 10: "the room
253
- * lobby is unchanged").
254
- */
255
- _jsxs(_Fragment, { children: [_jsx("div", { className: "room-shell", "data-testid": "room-shell", "data-collapsible": collapsible ? '' : undefined, inert: inert || undefined, children: _jsxs(RoomChrome, { roomKey: key, serverOrigin: watchpartyOrigin(), roomOrigin: appOrigin(), userType: who.tier, userId: who.userId, theme: watchpartyTheme(theme), collapsible: collapsible, toolbar: toolbarPage ? toolbar : undefined, children: [_jsx(Slot, { host: host }), _jsx("span", { hidden: true, ref: roomFrameRef })] }) }, "chrome"), content] }));
256
- }
257
- /** The node {@link RoomShell}'s children are drawn into: it takes no box of its own, so they lay out as its parent's. */
258
- function createHost() {
259
- const host = document.createElement('div');
260
- host.className = 'chrome-slot';
261
- host.style.display = 'contents';
262
- return host;
263
- }
264
- const SLOT_STYLE = { display: 'contents' };
265
- /** Where the children stand now: the host is moved in when this mounts. */
266
- function Slot({ host }) {
267
- const place = useCallback((slot) => {
268
- slot?.appendChild(host);
269
- }, [host]);
270
- return _jsx("div", { ref: place, className: "chrome-slot", style: SLOT_STYLE });
271
- }
@@ -1,30 +0,0 @@
1
- import { type ReactNode } from 'react';
2
- import { whoami as hadokuWhoami } from '@wolffm/prefs-client';
3
- export interface Who {
4
- userId: string;
5
- /** The fleet's own tier list, so a tier it adds (`member`) is not a type error here. */
6
- tier: WhoamiAnswer['userType'];
7
- /** The viewer's display name. Null when the fleet has none for them. */
8
- name: string | null;
9
- }
10
- type WhoamiAnswer = Awaited<ReturnType<typeof hadokuWhoami>>;
11
- /** The viewer, `null` when the fleet could not say, `'pending'` while it is asked. */
12
- export type WhoState = Who | null | 'pending';
13
- export declare const registerWhoamiTier: (value: (r: Pick<WhoamiAnswer, "userType">) => Who["tier"]) => void;
14
- /**
15
- * The viewer's tier as cardtable treats it: a member (a guest the operator has verified) IS a friend
16
- * here (the operator, 2026-11-05: *"for cardtable they will be equivalent"*); a guest is never
17
- * promoted. Read from the tier alone, never the fleet's `verified` flag. The server's `tierOf` makes
18
- * the same call for every gate; this is the tier the fleet chrome is handed to show.
19
- */
20
- export declare function tierOfWhoami(r: Pick<WhoamiAnswer, 'userType'>): Who['tier'];
21
- /** Hands `who` to every `useWhoami` below, which then asks nothing of its own. */
22
- export declare function WhoProvider({ who, children }: {
23
- who: WhoState;
24
- children: ReactNode;
25
- }): import("react").FunctionComponentElement<import("react").ProviderProps<WhoState | undefined>>;
26
- /** The viewer: the app shell's answer when there is one above, else this hook's own. */
27
- export declare function useWhoami(): WhoState;
28
- /** Asks the fleet once, while `enabled`. */
29
- export declare function useResolvedWhoami(enabled?: boolean): WhoState;
30
- export {};
@@ -1,71 +0,0 @@
1
- /*
2
- * Who this viewer is, from the fleet.
3
- *
4
- * `whoami()` from `@wolffm/prefs-client` is the fleet's own, returns `name`,
5
- * and shares one in-flight promise per page (`globalThis.__hadokuWhoami`) so
6
- * several apps on a page do not each re-fetch it. Read the same way by the
7
- * standalone app (`RoomShell`) and by the watchparty embed (`EmbedApp`): the
8
- * edge path, never the host's `ctx.identity` (D21's identity rule).
9
- *
10
- * Nothing here invents an identity: a failed answer is `null`, and the caller
11
- * decides what a table with nobody known at it looks like.
12
- */
13
- import { createContext, createElement, useContext, useEffect, useState } from 'react';
14
- import { whoami as hadokuWhoami } from '@wolffm/prefs-client';
15
- import { registered } from "../registered.js";
16
- /**
17
- * How a game reads the fleet's tier for the viewer. Default: as the fleet answered it. Cardtable's
18
- * composition root registers {@link tierOfWhoami}.
19
- */
20
- const whoamiTier = registered('whoami tier', () => (r) => r.userType);
21
- export const registerWhoamiTier = whoamiTier.set;
22
- /**
23
- * The viewer's tier as cardtable treats it: a member (a guest the operator has verified) IS a friend
24
- * here (the operator, 2026-11-05: *"for cardtable they will be equivalent"*); a guest is never
25
- * promoted. Read from the tier alone, never the fleet's `verified` flag. The server's `tierOf` makes
26
- * the same call for every gate; this is the tier the fleet chrome is handed to show.
27
- */
28
- export function tierOfWhoami(r) {
29
- return r.userType === 'member' ? 'friend' : r.userType;
30
- }
31
- /** The page's one resolution, when an app shell above has made it (`../app/GameAppShell.tsx`). */
32
- const WhoContext = createContext(undefined);
33
- /** Hands `who` to every `useWhoami` below, which then asks nothing of its own. */
34
- export function WhoProvider({ who, children }) {
35
- return createElement(WhoContext.Provider, { value: who }, children);
36
- }
37
- /** The viewer: the app shell's answer when there is one above, else this hook's own. */
38
- export function useWhoami() {
39
- const given = useContext(WhoContext);
40
- const own = useResolvedWhoami(given === undefined);
41
- return given ?? own;
42
- }
43
- /** Asks the fleet once, while `enabled`. */
44
- export function useResolvedWhoami(enabled = true) {
45
- const [who, setWho] = useState('pending');
46
- useEffect(() => {
47
- if (!enabled)
48
- return;
49
- let live = true;
50
- // Same-origin on purpose. `whoami()` defaults to the edge-router origin,
51
- // which in production IS this page's origin — but hard-coding it makes the
52
- // app reach `https://hadoku.me` from wherever it happens to be served,
53
- // which the e2e correctly flags as an off-host request and which would be
54
- // wrong for any future preview host. Same-origin gives the identical
55
- // answer in production and stays local everywhere else.
56
- hadokuWhoami({ whoamiUrl: `${globalThis.location.origin}/session/whoami` })
57
- .then((r) => {
58
- if (!live)
59
- return;
60
- setWho({ userId: r.userId, tier: whoamiTier.get()(r), name: r.name ?? null });
61
- })
62
- .catch(() => {
63
- if (live)
64
- setWho(null);
65
- });
66
- return () => {
67
- live = false;
68
- };
69
- }, [enabled]);
70
- return who;
71
- }
@@ -1,71 +0,0 @@
1
- import { type Fetch } from '../http.js';
2
- import type { RoomFrontClient, RoomFrontJoinOutcome, RoomFrontRoom } from '../front/RoomFront.js';
3
- /** A room write's answer: the room as the server now has it, or why not. */
4
- export type RoomOutcome<R> = {
5
- ok: true;
6
- room: R;
7
- } | {
8
- ok: false;
9
- message: string;
10
- };
11
- /** A write that ends the room for everyone (a close, a testing room's reset): answered with no room. */
12
- export type RoomEndOutcome = {
13
- ok: true;
14
- } | {
15
- ok: false;
16
- message: string;
17
- };
18
- export type RoomJoinOutcome<R> = RoomFrontJoinOutcome<R>;
19
- export interface RoomCoreClientOptions<R> {
20
- /** The game's own room body, or `null` for a body that is not one (it is dropped from a list, refused elsewhere). */
21
- parse(body: unknown): R | null;
22
- fetch?: Fetch;
23
- /** The `/api/` base, `apiBase()` (this bundle's own) unless given. */
24
- base?: string;
25
- }
26
- export interface RoomCoreClient<R> {
27
- /** `GET /api/rooms`: every room the caller may see, and the whole body for a game's own extras (a featured pick, say). Throws a sentence. */
28
- list(): Promise<{
29
- rooms: R[];
30
- body: Record<string, unknown>;
31
- }>;
32
- /** `GET /api/rooms/:id`: `null` on the usual 404, a thrown sentence for anything else. */
33
- get(roomId: string): Promise<R | null>;
34
- create(body: Record<string, unknown>): Promise<RoomOutcome<R>>;
35
- join(roomId: string, password?: string): Promise<RoomJoinOutcome<R>>;
36
- leave(roomId: string): Promise<RoomOutcome<R>>;
37
- ready(roomId: string, ready: boolean): Promise<RoomOutcome<R>>;
38
- close(roomId: string): Promise<RoomEndOutcome>;
39
- reset(roomId: string): Promise<RoomEndOutcome>;
40
- /** The viewer takes `seat`, or the first open one (the room grows by one when none is). */
41
- sit(roomId: string, seat?: number): Promise<RoomOutcome<R>>;
42
- /** The viewer gives their seat back. */
43
- stand(roomId: string): Promise<RoomOutcome<R>>;
44
- /** The leader closes an empty seat, or opens a closed one. */
45
- setSeatClosed(roomId: string, seat: number, closed: boolean): Promise<RoomOutcome<R>>;
46
- /** The leader puts the bot in `seat`, evicting a human holder first. */
47
- bot(roomId: string, seat: number): Promise<RoomOutcome<R>>;
48
- /** The leader takes the bot back out of `seat`. */
49
- botOff(roomId: string, seat: number): Promise<RoomOutcome<R>>;
50
- /** The leader moves a seated member to the spectators. */
51
- removeFromSeat(roomId: string, memberId: string): Promise<RoomOutcome<R>>;
52
- /** The leader closes seats from the top down until `count` are open. */
53
- lowerSeatCapacity(roomId: string, count: number): Promise<RoomOutcome<R>>;
54
- /** The leader hands the room to another member, seated or watching. */
55
- makeLeader(roomId: string, memberId: string): Promise<RoomOutcome<R>>;
56
- /** The room a host's room (watchparty's game slot) plays in, made on first use and joined after: the server derives it from `hostRoom`. */
57
- bindWatchparty(hostRoom: string): Promise<RoomOutcome<R>>;
58
- /** Any other write that answers with the room, under `/api/rooms`: `path` starts with `/` or is `''`. */
59
- write(path: string, payload: unknown, whatFailed: string, method?: 'POST' | 'PATCH' | 'PUT'): Promise<RoomOutcome<R>>;
60
- /** Any other read of one room under `/api/rooms`, as `get` reads one. */
61
- read(path: string): Promise<R | null>;
62
- }
63
- export declare function roomCoreClient<R>({ parse, fetch: fetchImpl, base }: RoomCoreClientOptions<R>): RoomCoreClient<R>;
64
- /**
65
- * `RoomFront`'s client over a core client: the game's own projection of its room (`toFront`: the
66
- * seats, the state and the primary action a row draws) applied to every list, create and join.
67
- * `reset` offers an admin's Reset on the game's seeded testing rooms.
68
- */
69
- export declare function roomFrontClient<R, V extends RoomFrontRoom>(core: RoomCoreClient<R>, toFront: (room: R) => V, opts?: {
70
- reset?: boolean;
71
- }): RoomFrontClient<V>;
@@ -1,150 +0,0 @@
1
- /*
2
- * The browser's client for game-server's generic room routes (`@hadoku/game-server/http/room-core`):
3
- * the room list, a room, create, join, leave, ready, close, reset, the seat ops (sit, stand, the
4
- * leader's close/open, bot in and out, remove, fewer seats, a new leader) and an embed's binding to
5
- * its host's room. One copy, so every game
6
- * reads the same refusals the same way; a game supplies only how its room body parses
7
- * (`parse`), and adds its own routes with `write`/`read`.
8
- *
9
- * ## One answer for "wrong password" and "no such room"
10
- *
11
- * room-core answers both with the same refusal, on purpose (a 404-vs-403 would tell an enumerator
12
- * which rooms exist). A join refused with either status is `refused`, and nothing downstream can
13
- * tell which it was.
14
- *
15
- * ## The words
16
- *
17
- * A room write that fails reads `<what failed>: <the server's own sentence>.`; a seat op's refusal
18
- * is the server's own sentence as is (the seat strip shows it under the seats). A body that is not a
19
- * room is a refusal too, never a crash: a proxy's error page parses as nothing.
20
- */
21
- import { apiBase, bodyOf, getJson, isRecord, pageFetch, sendJson, serverMessage } from "../http.js";
22
- const UNREACHABLE = 'Could not reach the server.';
23
- const NOT_A_ROOM = 'The server answered with something that is not a room.';
24
- const id = (roomId) => `/${encodeURIComponent(roomId)}`;
25
- export function roomCoreClient({ parse, fetch: fetchImpl = pageFetch, base = apiBase() }) {
26
- const url = (path) => `${base}rooms${path}`;
27
- /** A write answered with the room; `whatFailed` null for a seat op, whose refusal is the server's own sentence. */
28
- const send = async (path, payload, whatFailed, method = 'POST') => {
29
- let res;
30
- try {
31
- res = await sendJson(url(path), method, payload, fetchImpl);
32
- }
33
- catch {
34
- return { ok: false, message: UNREACHABLE };
35
- }
36
- const body = await bodyOf(res);
37
- if (!res.ok)
38
- return { ok: false, message: whatFailed === null ? serverMessage(body, res.status) : `${whatFailed}: ${serverMessage(body, res.status)}.` };
39
- const room = parse(body);
40
- return room === null ? { ok: false, message: NOT_A_ROOM } : { ok: true, room };
41
- };
42
- const end = async (roomId, verb, whatFailed) => {
43
- let res;
44
- try {
45
- res = await sendJson(url(`${id(roomId)}/${verb}`), 'POST', {}, fetchImpl);
46
- }
47
- catch {
48
- return { ok: false, message: UNREACHABLE };
49
- }
50
- if (res.ok)
51
- return { ok: true };
52
- return { ok: false, message: `${whatFailed}: ${serverMessage(await bodyOf(res), res.status)}.` };
53
- };
54
- const read = async (path) => {
55
- let res;
56
- try {
57
- res = await getJson(url(path), fetchImpl);
58
- }
59
- catch {
60
- throw new Error(UNREACHABLE);
61
- }
62
- if (res.status === 404)
63
- return null;
64
- const body = await bodyOf(res);
65
- if (!res.ok)
66
- throw new Error(`Could not load the room: ${serverMessage(body, res.status)}.`);
67
- const room = parse(body);
68
- if (room === null)
69
- throw new Error('The server sent something that is not a room.');
70
- return room;
71
- };
72
- const seat = (roomId, op, payload) => send(`${id(roomId)}/${op}`, payload, null);
73
- return {
74
- async list() {
75
- let res;
76
- try {
77
- res = await getJson(url(''), fetchImpl);
78
- }
79
- catch {
80
- throw new Error(UNREACHABLE);
81
- }
82
- const body = await bodyOf(res);
83
- if (!res.ok)
84
- throw new Error(`Could not load the rooms: ${serverMessage(body, res.status)}.`);
85
- if (!isRecord(body) || !Array.isArray(body.rooms))
86
- throw new Error('Could not load the rooms: the server sent something that is not a room list.');
87
- const rooms = body.rooms.map(parse).filter((r) => r !== null);
88
- return { rooms, body };
89
- },
90
- get: (roomId) => read(id(roomId)),
91
- create: (body) => send('', body, 'Could not create the room'),
92
- async join(roomId, password) {
93
- let res;
94
- try {
95
- res = await sendJson(url(`${id(roomId)}/join`), 'POST', password === undefined || password === '' ? {} : { password }, fetchImpl);
96
- }
97
- catch {
98
- return { ok: false, reason: 'error', message: UNREACHABLE };
99
- }
100
- if (res.status === 403 || res.status === 404)
101
- return { ok: false, reason: 'refused' };
102
- if (res.status === 429)
103
- return { ok: false, reason: 'rate-limited' };
104
- const body = await bodyOf(res);
105
- if (!res.ok)
106
- return { ok: false, reason: 'error', message: `Could not join: ${serverMessage(body, res.status)}.` };
107
- const room = parse(body);
108
- if (room === null)
109
- return { ok: false, reason: 'error', message: 'The server answered the join with something that is not a room.' };
110
- return { ok: true, room };
111
- },
112
- leave: (roomId) => send(`${id(roomId)}/leave`, {}, 'Could not leave the room'),
113
- ready: (roomId, ready) => send(`${id(roomId)}/ready`, { ready }, 'Could not change your readiness'),
114
- close: (roomId) => end(roomId, 'close', 'Could not close the room'),
115
- reset: (roomId) => end(roomId, 'reset', 'Could not reset the room'),
116
- sit: (roomId, at) => seat(roomId, 'seats/sit', at === undefined ? {} : { seat: at }),
117
- stand: (roomId) => seat(roomId, 'seats/stand', {}),
118
- setSeatClosed: (roomId, at, closed) => seat(roomId, 'seats/close', { seat: at, closed }),
119
- bot: (roomId, at) => seat(roomId, 'seats/bot', { seat: at }),
120
- botOff: (roomId, at) => seat(roomId, 'seats/bot-off', { seat: at }),
121
- removeFromSeat: (roomId, memberId) => seat(roomId, 'seats/remove', { memberId }),
122
- lowerSeatCapacity: (roomId, count) => seat(roomId, 'seats/capacity', { count }),
123
- makeLeader: (roomId, memberId) => seat(roomId, 'leader', { memberId }),
124
- bindWatchparty: (hostRoom) => send('/watchparty', { room: hostRoom }, 'Could not open this room’s table'),
125
- write: (path, payload, whatFailed, method = 'POST') => send(path, payload, whatFailed, method),
126
- read,
127
- };
128
- }
129
- /**
130
- * `RoomFront`'s client over a core client: the game's own projection of its room (`toFront`: the
131
- * seats, the state and the primary action a row draws) applied to every list, create and join.
132
- * `reset` offers an admin's Reset on the game's seeded testing rooms.
133
- */
134
- export function roomFrontClient(core, toFront, opts = {}) {
135
- return {
136
- async list() {
137
- const { rooms } = await core.list();
138
- return { rooms: rooms.map(toFront) };
139
- },
140
- async create(body) {
141
- const outcome = await core.create(body);
142
- return outcome.ok ? { ok: true, room: toFront(outcome.room) } : outcome;
143
- },
144
- async join(roomId, password) {
145
- const outcome = await core.join(roomId, password);
146
- return outcome.ok ? { ok: true, room: toFront(outcome.room) } : outcome;
147
- },
148
- ...(opts.reset === true ? { reset: (roomId) => core.reset(roomId) } : {}),
149
- };
150
- }