@diffenderfer-games/hub 0.0.0-stage → 2.0.0-next.1

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.
Files changed (164) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +21 -0
  3. package/README.md +191 -3
  4. package/dist/auto.d.ts +36 -0
  5. package/dist/auto.d.ts.map +1 -0
  6. package/dist/auto.js +27 -0
  7. package/dist/auto.js.map +1 -0
  8. package/dist/daily.d.ts +2 -0
  9. package/dist/daily.js +1 -0
  10. package/dist/doctor/cli.mjs +268 -0
  11. package/dist/doctor/cli.mjs.map +1 -0
  12. package/dist/index.d.ts +12 -0
  13. package/dist/index.js +6 -0
  14. package/dist/input.d.ts +2 -0
  15. package/dist/input.js +3 -0
  16. package/dist/mp.d.ts +4 -0
  17. package/dist/mp.js +1 -0
  18. package/dist/race.d.ts +4 -0
  19. package/dist/race.js +1 -0
  20. package/dist/rooms.d.ts +4 -0
  21. package/dist/rooms.js +1 -0
  22. package/dist/shared/bridge.js +209 -0
  23. package/dist/shared/bridge.js.map +1 -0
  24. package/dist/shared/client-version.gen.js +7 -0
  25. package/dist/shared/client-version.gen.js.map +1 -0
  26. package/dist/shared/daily.d.ts +123 -0
  27. package/dist/shared/daily.d.ts.map +1 -0
  28. package/dist/shared/daily.js +191 -0
  29. package/dist/shared/daily.js.map +1 -0
  30. package/dist/shared/dom.js +48 -0
  31. package/dist/shared/dom.js.map +1 -0
  32. package/dist/shared/globals.js +102 -0
  33. package/dist/shared/globals.js.map +1 -0
  34. package/dist/shared/index.d.ts +706 -0
  35. package/dist/shared/index.d.ts.map +1 -0
  36. package/dist/shared/input.d.ts +730 -0
  37. package/dist/shared/input.d.ts.map +1 -0
  38. package/dist/shared/input.js +2718 -0
  39. package/dist/shared/input.js.map +1 -0
  40. package/dist/shared/latest-state.js +17 -0
  41. package/dist/shared/latest-state.js.map +1 -0
  42. package/dist/shared/mp.d.ts +9 -0
  43. package/dist/shared/mp.d.ts.map +1 -0
  44. package/dist/shared/mp.js +30 -0
  45. package/dist/shared/mp.js.map +1 -0
  46. package/dist/shared/multiplayer-types.d.ts +47 -0
  47. package/dist/shared/multiplayer-types.d.ts.map +1 -0
  48. package/dist/shared/page-stack.js +207 -0
  49. package/dist/shared/page-stack.js.map +1 -0
  50. package/dist/shared/race-types.d.ts +126 -0
  51. package/dist/shared/race-types.d.ts.map +1 -0
  52. package/dist/shared/race.d.ts +9 -0
  53. package/dist/shared/race.d.ts.map +1 -0
  54. package/dist/shared/race.js +53 -0
  55. package/dist/shared/race.js.map +1 -0
  56. package/dist/shared/room-types.d.ts +125 -0
  57. package/dist/shared/room-types.d.ts.map +1 -0
  58. package/dist/shared/rooms.d.ts +9 -0
  59. package/dist/shared/rooms.d.ts.map +1 -0
  60. package/dist/shared/rooms.js +62 -0
  61. package/dist/shared/rooms.js.map +1 -0
  62. package/dist/shared/runtime-opener.js +84 -0
  63. package/dist/shared/runtime-opener.js.map +1 -0
  64. package/dist/shared/social.d.ts +148 -0
  65. package/dist/shared/social.d.ts.map +1 -0
  66. package/dist/shared/social.js +73 -0
  67. package/dist/shared/social.js.map +1 -0
  68. package/dist/shared/src.js +2164 -0
  69. package/dist/shared/src.js.map +1 -0
  70. package/dist/shared/wire-types.d.ts +51 -0
  71. package/dist/shared/wire-types.d.ts.map +1 -0
  72. package/dist/social.d.ts +6 -0
  73. package/dist/social.js +3 -0
  74. package/dist/types.d.ts +1 -0
  75. package/dist/types.js +0 -0
  76. package/package.json +89 -6
  77. package/src/auto.ts +39 -0
  78. package/src/core/connection.ts +299 -0
  79. package/src/core/errors.ts +147 -0
  80. package/src/core/game-data.ts +38 -0
  81. package/src/core/hub-economy.ts +179 -0
  82. package/src/core/hub-progress.ts +205 -0
  83. package/src/core/hub.ts +131 -0
  84. package/src/core/menu-control.ts +61 -0
  85. package/src/core/offline/events.ts +50 -0
  86. package/src/core/offline/favorites.ts +21 -0
  87. package/src/core/offline/local-store.ts +261 -0
  88. package/src/core/offline/queue.ts +171 -0
  89. package/src/core/page.ts +74 -0
  90. package/src/core/rest/endpoint-types.ts +22 -0
  91. package/src/core/rest/rest-client.ts +152 -0
  92. package/src/core/rest/routes.gen.ts +90 -0
  93. package/src/core/storage/json-guards.ts +74 -0
  94. package/src/core/storage/key-value.ts +66 -0
  95. package/src/core/ticket.ts +43 -0
  96. package/src/core/types.ts +134 -0
  97. package/src/core/version/client-version.gen.ts +3 -0
  98. package/src/core/version/hub-version.ts +62 -0
  99. package/src/core/version/semver.ts +97 -0
  100. package/src/daily/daily-system.ts +161 -0
  101. package/src/daily/page-daily.ts +36 -0
  102. package/src/daily/types.ts +67 -0
  103. package/src/daily.ts +10 -0
  104. package/src/doctor/checks.ts +78 -0
  105. package/src/doctor/cli.ts +98 -0
  106. package/src/doctor/hub-version-fetch.ts +43 -0
  107. package/src/doctor/tsconfig.json +12 -0
  108. package/src/globals.ts +115 -0
  109. package/src/index.ts +50 -0
  110. package/src/input/device-state.ts +146 -0
  111. package/src/input/edges.ts +55 -0
  112. package/src/input/gamepad.ts +61 -0
  113. package/src/input/input-events.ts +32 -0
  114. package/src/input/input-registry.ts +164 -0
  115. package/src/input/input-system.ts +393 -0
  116. package/src/input/legacy-controls.ts +64 -0
  117. package/src/input/nav-state.ts +191 -0
  118. package/src/input/navigator.ts +171 -0
  119. package/src/input/on-screen-controls.ts +101 -0
  120. package/src/input/page-control.ts +43 -0
  121. package/src/input/page-input.ts +193 -0
  122. package/src/input/player-remaps.ts +77 -0
  123. package/src/input/source-values.ts +116 -0
  124. package/src/input/spatial.ts +47 -0
  125. package/src/input/types.ts +331 -0
  126. package/src/input/zero-config.ts +177 -0
  127. package/src/input.ts +22 -0
  128. package/src/mp.ts +10 -0
  129. package/src/overlay/controls-panel.ts +163 -0
  130. package/src/overlay/dom.ts +46 -0
  131. package/src/overlay/layout-clusters.ts +162 -0
  132. package/src/overlay/layout-geometry.ts +136 -0
  133. package/src/overlay/layout.ts +203 -0
  134. package/src/overlay/listener-scope.ts +23 -0
  135. package/src/overlay/on-screen-keyboard.ts +137 -0
  136. package/src/overlay/overlay.ts +208 -0
  137. package/src/overlay/styles.ts +54 -0
  138. package/src/overlay/virtual-controls.ts +262 -0
  139. package/src/race.ts +10 -0
  140. package/src/realtime/bridge.ts +121 -0
  141. package/src/realtime/cross-bundle.ts +29 -0
  142. package/src/realtime/fallback-notice.ts +48 -0
  143. package/src/realtime/hub-link.ts +65 -0
  144. package/src/realtime/latest-state.ts +33 -0
  145. package/src/realtime/multiplayer-forwarder.ts +28 -0
  146. package/src/realtime/multiplayer-types.ts +52 -0
  147. package/src/realtime/page-runtime.ts +60 -0
  148. package/src/realtime/race-forwarder.ts +59 -0
  149. package/src/realtime/race-types.ts +132 -0
  150. package/src/realtime/room-types.ts +125 -0
  151. package/src/realtime/rooms-forwarder.ts +79 -0
  152. package/src/realtime/runtime-api.ts +49 -0
  153. package/src/realtime/runtime-opener.ts +61 -0
  154. package/src/realtime/social-forwarder.ts +72 -0
  155. package/src/realtime/social-types.ts +78 -0
  156. package/src/realtime/types.ts +53 -0
  157. package/src/realtime/wire-types.ts +72 -0
  158. package/src/rooms.ts +10 -0
  159. package/src/social.ts +18 -0
  160. package/src/types.ts +13 -0
  161. package/src/uistack/page-stack.ts +45 -0
  162. package/src/uistack/play-suspension.ts +82 -0
  163. package/src/uistack/types.ts +76 -0
  164. package/src/uistack/ui-stack.ts +144 -0
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The own-server ticket request (`hub.mp.ticket()`): a 60-second identity
3
+ * ticket for this game's own server, fetched straight from the hub. It must
4
+ * not depend on the social runtime: on the first visit after a deploy the
5
+ * service worker can still serve an older menu that never loads it. When the
6
+ * page has no session yet, a guest one is created and the request retried
7
+ * once.
8
+ */
9
+ import { HubError, OfflineError } from './errors';
10
+ import { detectApiBase, detectSlug } from './page';
11
+ import { createRestClient, type RestClient } from './rest/rest-client';
12
+
13
+ /** A REST client for the page's API base that uses the global fetch at call time. */
14
+ function pageRestClient(): RestClient {
15
+ return createRestClient({ apiBase: detectApiBase(), fetch: (input, init) => globalThis.fetch(input, init) });
16
+ }
17
+
18
+ /** One ticket request; a transport failure is an {@link OfflineError}. */
19
+ async function requestTicket(rest: RestClient, slug: string): Promise<string> {
20
+ try {
21
+ return (await rest.call('getGameServerTicket', { slug })).ticket;
22
+ } catch (failure) {
23
+ throw failure instanceof HubError && failure.isOffline ? new OfflineError() : failure;
24
+ }
25
+ }
26
+
27
+ /** A ticket for this page's game; signs in a guest first when the page has no session. */
28
+ export async function fetchGameServerTicket(): Promise<string> {
29
+ const slug = detectSlug();
30
+ if (slug === null) {
31
+ throw new HubError('Hub: could not determine the game slug.');
32
+ }
33
+ const rest = pageRestClient();
34
+ try {
35
+ return await requestTicket(rest, slug);
36
+ } catch (failure) {
37
+ if (!(failure instanceof HubError) || failure.status !== 401) {
38
+ throw failure;
39
+ }
40
+ await rest.call('ensureGuestSession');
41
+ return requestTicket(rest, slug);
42
+ }
43
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The core client's public types, under the v1 client's names. Each one is
3
+ * the contract's shape (so the contract stays the one source of truth),
4
+ * widened where the offline cache can only know less than the hub (a local
5
+ * user has no role) or made generic over a game's own JSON (`Save<MySave>`).
6
+ */
7
+ import type { Board, GameInfo as ContractGameInfo, Json, Metrics, SessionUser, SortDir } from '@diffenderfer-games/hub-contract';
8
+ import type { GamePayload } from './game-data';
9
+ import type { EndpointReply } from './rest/endpoint-types';
10
+
11
+ export type { GamePayload } from './game-data';
12
+
13
+ export type { Board, GameLeaderboards, GameRecords, Inventory, Json, LeaderboardEntry, Metrics, SortDir, Stats } from '@diffenderfer-games/hub-contract';
14
+
15
+ /** The signed-in player. Offline (a locally stored user) only `id`, `username` and `guest` are known. */
16
+ export type User = Pick<SessionUser, 'id' | 'username'> & Partial<Omit<SessionUser, 'id' | 'username'>>;
17
+
18
+ /** One game the player has a profile in. */
19
+ export interface ProfileSummary {
20
+ /** The game's slug. */
21
+ readonly game: string;
22
+ /** The player's display name there, or `null`. */
23
+ readonly displayName: string | null;
24
+ }
25
+
26
+ /** What `hub.me()` answers: the current user (or `null`) and their game profiles. */
27
+ export interface MeResponse {
28
+ /** The signed-in player, or `null`. */
29
+ readonly user: User | null;
30
+ /** The games the player has a profile in. */
31
+ readonly profiles: ProfileSummary[];
32
+ }
33
+
34
+ /** A player's profile in one game, with the game's own data typed as `TData`. */
35
+ export interface Profile<TData = Json> {
36
+ /** The game's slug. */
37
+ readonly game: string;
38
+ /** Shown to other players; `null` when never set. */
39
+ readonly displayName: string | null;
40
+ /** The game's own profile data. */
41
+ readonly data: TData;
42
+ /** Epoch ms. */
43
+ readonly updatedAt: number;
44
+ }
45
+
46
+ /** A save slot's metadata (no payload). */
47
+ export interface SaveMeta {
48
+ /** The slot key. */
49
+ readonly slot: string;
50
+ /** The slot's label, or `null`. */
51
+ readonly label: string | null;
52
+ /** Epoch ms. */
53
+ readonly updatedAt: number;
54
+ }
55
+
56
+ /** A save slot with its payload typed as `TData`. */
57
+ export interface Save<TData = Json> extends SaveMeta {
58
+ /** The stored JSON. */
59
+ readonly data: TData;
60
+ }
61
+
62
+ /** Options for `hub.submitScore()`, with the score's metadata typed as `TMeta`. */
63
+ export interface SubmitScoreOptions<TMeta extends GamePayload = Json> {
64
+ /** The board's title; only used when the board key is first created. */
65
+ readonly title?: string;
66
+ /** The sort direction; only used on board creation. Default `desc`. */
67
+ readonly sort?: SortDir;
68
+ /** Any JSON stored with the entry (a character, a run seed). */
69
+ readonly meta?: TMeta;
70
+ }
71
+
72
+ /** What `hub.submitScore()` answers: the board, the player's best and rank (offline: rank 1). */
73
+ export interface SubmitScoreResult {
74
+ /** The board. */
75
+ readonly board: Board;
76
+ /** The player's best score, or `null` when it did not count (a zero on a board that hides zeros). */
77
+ readonly best: number | null;
78
+ /** The player's rank, or `null`. */
79
+ readonly rank: number | null;
80
+ }
81
+
82
+ /** One board's ranked entries (`hub.getLeaderboard()`). */
83
+ export type LeaderboardResult = EndpointReply<'getLeaderboard'>;
84
+
85
+ /** A board with its top entries. */
86
+ export type BoardWithTop = EndpointReply<'listTopOfEveryLeaderboard'>['games'][number]['boards'][number];
87
+
88
+ /** One game's play counts, with its slug (`hub.analytics()`). */
89
+ export type GameAnalytics = EndpointReply<'getGameAnalytics'>;
90
+
91
+ /** Catalog-wide play counts with a per-game breakdown (`hub.globalAnalytics()`). */
92
+ export interface GlobalAnalytics {
93
+ /** Across every game. */
94
+ readonly global: Metrics;
95
+ /** Per game. */
96
+ readonly games: (Metrics & { readonly slug: string; readonly title: string })[];
97
+ }
98
+
99
+ /** A listed game (`hub.listGames()`). */
100
+ export type GameInfo = ContractGameInfo;
101
+
102
+ /** What `GET /me/snapshot` answers; `hub.prefetchAll()` warms the offline cache for every game from it. */
103
+ export type SnapshotResponse = EndpointReply<'getMyOfflineSnapshot'>;
104
+
105
+ /** A player's holdings in one game, as the inventory calls answer. */
106
+ export type InventorySnapshot = EndpointReply<'getMyInventory'>;
107
+
108
+ /** The connection and sync status `hub.onStatus()` reports. */
109
+ export interface HubStatus {
110
+ /** The hub is reachable. */
111
+ readonly online: boolean;
112
+ /** Calls are being served from the offline cache. */
113
+ readonly offline: boolean;
114
+ /** Queued writes plus buffered events waiting to sync. */
115
+ readonly pending: number;
116
+ }
117
+
118
+ /** How a client created with `createHub()` / `new Hub()` behaves. */
119
+ export interface HubOptions {
120
+ /** The game's slug. Default: `window.__HUB__.slug`, then the first URL path segment. */
121
+ readonly slug?: string;
122
+ /** The API base. Default: `window.__HUB__.apiBase`, then `/_api`. */
123
+ readonly apiBase?: string;
124
+ /** A custom fetch (tests, non-browser code). Default: the global fetch. */
125
+ readonly fetch?: typeof fetch;
126
+ /**
127
+ * What to do when the hub can't be reached:
128
+ * - `auto` (default): try the network; on a connection failure fall back to
129
+ * the offline cache in `localStorage`, and sync when the hub is back;
130
+ * - `always`: never touch the network (develop a game without a hub);
131
+ * - `never`: never fall back; every call throws when the hub is unreachable.
132
+ */
133
+ readonly offline?: 'auto' | 'always' | 'never';
134
+ }
@@ -0,0 +1,3 @@
1
+ // Generated by tools/hub-client/generate.ts. Do not edit; run `npm run gen:hub-client` in next/.
2
+ /** This client's package version, sent as `x-hub-client` on REST calls and `client` in `hello`. */
3
+ export const HUB_CLIENT_VERSION = '2.0.0-next.1';
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The hub's `GET /_api/version`, read at most once per page and API base
3
+ * (plan §4.3.3), and what it says about this client. Nothing reads it on
4
+ * load: it costs a request only when a game (or `hub-doctor`) asks.
5
+ */
6
+ import type { HubVersion } from '@diffenderfer-games/hub-contract';
7
+ import { HubError, UNSUPPORTED_BY_HUB } from '../errors';
8
+ import type { RestClient } from '../rest/rest-client';
9
+ import { HUB_CLIENT_VERSION } from './client-version.gen';
10
+ import { satisfiesRange } from './semver';
11
+
12
+ /** How a hub regards a client version. */
13
+ export type ClientSupport =
14
+ /** In `supported` and not `deprecated`. */
15
+ | 'supported'
16
+ /** Still supported, but `deprecated`: update soon. */
17
+ | 'deprecated'
18
+ /** Outside `supported`: update now. */
19
+ | 'unsupported'
20
+ /** The hub predates versioning (the old hub): nothing to compare. */
21
+ | 'unknown';
22
+
23
+ /** How `version` fares against a hub's answer (`null`: a hub from before versioning). */
24
+ export function clientSupport(hubVersion: HubVersion | null, version: string = HUB_CLIENT_VERSION): ClientSupport {
25
+ if (hubVersion === null) {
26
+ return 'unknown';
27
+ }
28
+ if (!satisfiesRange(version, hubVersion.supported)) {
29
+ return 'unsupported';
30
+ }
31
+ return satisfiesRange(version, hubVersion.deprecated) ? 'deprecated' : 'supported';
32
+ }
33
+
34
+ const versionsByApiBase = new Map<string, Promise<HubVersion | null>>();
35
+
36
+ /**
37
+ * The hub's version, fetched once per page and API base. Resolves `null` for
38
+ * a hub from before versioning (it has no `/version` route); a failed
39
+ * request is not cached, so a later call tries again.
40
+ */
41
+ export function readHubVersion(rest: RestClient): Promise<HubVersion | null> {
42
+ const cached = versionsByApiBase.get(rest.apiBase);
43
+ if (cached !== undefined) {
44
+ return cached;
45
+ }
46
+ const pending = fetchHubVersion(rest);
47
+ versionsByApiBase.set(rest.apiBase, pending);
48
+ return pending;
49
+ }
50
+
51
+ /** One `GET /version`; `null` when the hub has no such route. */
52
+ async function fetchHubVersion(rest: RestClient): Promise<HubVersion | null> {
53
+ try {
54
+ return await rest.call('getHubVersion');
55
+ } catch (failure) {
56
+ if (failure instanceof HubError && failure.code === UNSUPPORTED_BY_HUB) {
57
+ return null;
58
+ }
59
+ versionsByApiBase.delete(rest.apiBase);
60
+ throw failure;
61
+ }
62
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Just enough semver for version ranges the hub sends (`>=2.0.0-0 <3.0.0`,
3
+ * `<2.2.0`): comparators separated by spaces must all hold, `||` separates
4
+ * alternatives. Versions compare in plain semver order, prereleases included
5
+ * (`2.0.0-next.1 < 2.0.0`); unlike npm, a prerelease is not excluded from a
6
+ * range of another release line, which is why the hub writes `-0` floors.
7
+ */
8
+
9
+ /** A parsed `major.minor.patch[-prerelease]` version. */
10
+ export interface ParsedVersion {
11
+ /** `[major, minor, patch]`. */
12
+ readonly release: readonly [number, number, number];
13
+ /** The dot-separated prerelease identifiers (empty for a release). */
14
+ readonly prerelease: readonly string[];
15
+ }
16
+
17
+ const VERSION_PATTERN = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
18
+
19
+ /** Parse a version (`2`, `2.1`, `2.1.0`, `2.1.0-next.3`); `undefined` when it is not one. */
20
+ export function parseVersion(text: string): ParsedVersion | undefined {
21
+ const match = VERSION_PATTERN.exec(text.trim());
22
+ if (match === null) {
23
+ return undefined;
24
+ }
25
+ const [, major = '0', minor = '0', patch = '0', prerelease] = match;
26
+ return { release: [Number(major), Number(minor), Number(patch)], prerelease: prerelease === undefined ? [] : prerelease.split('.') };
27
+ }
28
+
29
+ /** Compare two prerelease identifiers: numbers by value and before words, words as text. */
30
+ function compareIdentifiers(first: string, second: string): number {
31
+ const isFirstNumeric = /^\d+$/.test(first);
32
+ const isSecondNumeric = /^\d+$/.test(second);
33
+ if (isFirstNumeric && isSecondNumeric) {
34
+ return Number(first) - Number(second);
35
+ }
36
+ if (isFirstNumeric !== isSecondNumeric) {
37
+ return isFirstNumeric ? -1 : 1;
38
+ }
39
+ return first < second ? -1 : first > second ? 1 : 0;
40
+ }
41
+
42
+ /** Negative when `first` is older, positive when newer, 0 when equal. */
43
+ export function compareVersions(first: ParsedVersion, second: ParsedVersion): number {
44
+ for (let i = 0; i < 3; i += 1) {
45
+ const difference = (first.release[i] ?? 0) - (second.release[i] ?? 0);
46
+ if (difference !== 0) {
47
+ return difference;
48
+ }
49
+ }
50
+ if (first.prerelease.length === 0 || second.prerelease.length === 0) {
51
+ return second.prerelease.length - first.prerelease.length;
52
+ }
53
+ const length = Math.max(first.prerelease.length, second.prerelease.length);
54
+ for (let i = 0; i < length; i += 1) {
55
+ const firstIdentifier = first.prerelease[i];
56
+ const secondIdentifier = second.prerelease[i];
57
+ if (firstIdentifier === undefined || secondIdentifier === undefined) {
58
+ return firstIdentifier === undefined ? -1 : 1;
59
+ }
60
+ const difference = compareIdentifiers(firstIdentifier, secondIdentifier);
61
+ if (difference !== 0) {
62
+ return difference;
63
+ }
64
+ }
65
+ return 0;
66
+ }
67
+
68
+ const COMPARATOR_PATTERN = /^(>=|<=|>|<|=)?\s*(.+)$/;
69
+
70
+ /** Whether `version` meets one comparator (`>=2.0.0`); a malformed comparator never holds. */
71
+ function meetsComparator(version: ParsedVersion, comparator: string): boolean {
72
+ const match = COMPARATOR_PATTERN.exec(comparator);
73
+ const bound = match?.[2] === undefined ? undefined : parseVersion(match[2]);
74
+ if (match === null || bound === undefined) {
75
+ return false;
76
+ }
77
+ const order = compareVersions(version, bound);
78
+ switch (match[1]) {
79
+ case '>=': return order >= 0;
80
+ case '<=': return order <= 0;
81
+ case '>': return order > 0;
82
+ case '<': return order < 0;
83
+ default: return order === 0;
84
+ }
85
+ }
86
+
87
+ /** Whether `versionText` is in `range`; a malformed version or empty range never is. */
88
+ export function satisfiesRange(versionText: string, range: string): boolean {
89
+ const version = parseVersion(versionText);
90
+ if (version === undefined) {
91
+ return false;
92
+ }
93
+ return range.split('||').some((alternative) => {
94
+ const comparators = alternative.trim().split(/\s+/).filter((comparator) => comparator !== '');
95
+ return comparators.length > 0 && comparators.every((comparator) => meetsComparator(version, comparator));
96
+ });
97
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Daily challenges, client side. A daily-enabled game calls
3
+ * `hub.daily.define({ play })` once at load; `play` receives a
4
+ * {@link DailyChallenge} and starts exactly that challenge. When the player
5
+ * finishes, the game calls `hub.daily.complete({ score, … })`.
6
+ *
7
+ * The system is a page-wide singleton shared by the game's client and the
8
+ * injected menu, so the menu can start a day on the instance the game
9
+ * registered `play` on. Deep links (`/<slug>/?daily=YYYY-MM-DD`) auto-start.
10
+ */
11
+ import { readField } from '../realtime/cross-bundle';
12
+ import type { DailyAll, DailyChallenge, DailyCompleteResponse, DailyCompletionMeta, DailyDefinition, DailyHost, DailyStatus } from './types';
13
+
14
+ const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
15
+
16
+ /** The window event the injected menu fires to start a day on the game's instance. */
17
+ export const DAILY_START_EVENT = 'hub:daily-start';
18
+
19
+ /** A day key, or `null` when `candidate` isn't one. */
20
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: a URL parameter or a window global set by the host page
21
+ function asDayKey(candidate: unknown): string | null {
22
+ return typeof candidate === 'string' && DAY_PATTERN.test(candidate) ? candidate : null;
23
+ }
24
+
25
+ /** The day the page was deep-linked to, if any. */
26
+ function readDeepLinkDay(): string | null {
27
+ // Prefer the value the host's injected snippet captured at parse time: it
28
+ // survives games that rewrite their own URL on boot.
29
+ const captured = typeof window === 'undefined' ? null : asDayKey(readField(window, '__hubDailyDeep'));
30
+ if (captured !== null || typeof location === 'undefined') {
31
+ return captured;
32
+ }
33
+ return asDayKey(new URL(location.href).searchParams.get('daily'));
34
+ }
35
+
36
+ /** The message of a thrown value. */
37
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: anything a REST call can throw
38
+ function messageOf(error: unknown): string {
39
+ return error instanceof Error ? error.message : String(error);
40
+ }
41
+
42
+ /** Daily challenges (`hub.daily`). */
43
+ export class DailySystem {
44
+ /**
45
+ * The challenge in progress (set when a day starts, cleared on complete).
46
+ * A game's win handler checks it: `if (hub.daily.active) hub.daily.complete(…)`.
47
+ */
48
+ active: DailyChallenge | null = null;
49
+ private readonly host: DailyHost;
50
+ private play: DailyDefinition['play'] | null = null;
51
+ private pendingDay: string | null = null;
52
+ private isRelaying = false;
53
+
54
+ constructor(host: DailyHost) {
55
+ this.host = host;
56
+ if (typeof window !== 'undefined') {
57
+ // The injected menu (another module instance) asks us to start a day.
58
+ window.addEventListener(DAILY_START_EVENT, (event) => {
59
+ if (this.isRelaying) {
60
+ return;
61
+ }
62
+ const day = event instanceof CustomEvent ? readField(event.detail, 'day') : undefined;
63
+ if (typeof day === 'string') {
64
+ void this.startAndPlay(day);
65
+ }
66
+ });
67
+ }
68
+ }
69
+
70
+ /** Whether a game registered a daily-challenge handler on this page. */
71
+ get isDefined(): boolean {
72
+ return this.play !== null;
73
+ }
74
+
75
+ /**
76
+ * Register the game's challenge runner. Call once at load. If the page was
77
+ * deep-linked with `?daily=DATE` (or a start was requested before this),
78
+ * that day starts now.
79
+ */
80
+ define(definition: DailyDefinition): void {
81
+ this.play = definition.play;
82
+ const day = readDeepLinkDay() ?? this.pendingDay;
83
+ this.pendingDay = null;
84
+ if (day !== null) {
85
+ void this.startAndPlay(day);
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Fetch the signed token for `day`, make it active and call the game's
91
+ * `play`. Before `define`, the day is kept and played then, so the menu's
92
+ * own instance never fetches a token; it is also relayed to any other
93
+ * daily system on the page (a client copy that couldn't share this one).
94
+ */
95
+ async startAndPlay(day: string): Promise<void> {
96
+ const play = this.play;
97
+ if (play === null) {
98
+ this.pendingDay = day;
99
+ this.relayStart(day);
100
+ return;
101
+ }
102
+ try {
103
+ const started = await this.host.start(day);
104
+ const challenge: DailyChallenge = { day: started.day, seed: started.seed, token: started.token, alreadyCompleted: started.alreadyCompleted };
105
+ this.active = challenge;
106
+ this.host.emit('hub:daily-started', { day: started.day, seed: started.seed, alreadyCompleted: started.alreadyCompleted });
107
+ play({ ...challenge });
108
+ } catch (error) {
109
+ this.host.emit('hub:daily-error', { day, error: messageOf(error) });
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Record completion of the active challenge with optional metadata.
115
+ * Resolves with the new completion count and rank, or `null` when no
116
+ * challenge is active or the hub refused.
117
+ */
118
+ async complete(meta: DailyCompletionMeta = {}): Promise<DailyCompleteResponse | null> {
119
+ const challenge = this.active;
120
+ if (challenge === null) {
121
+ return null;
122
+ }
123
+ try {
124
+ const completed = await this.host.complete(challenge.day, challenge.token, meta);
125
+ this.active = null;
126
+ this.host.emit('hub:daily-complete', { day: challenge.day, count: completed.count, rank: completed.rank, meta });
127
+ return completed;
128
+ } catch (error) {
129
+ this.host.emit('hub:daily-error', { day: challenge.day, error: messageOf(error) });
130
+ return null;
131
+ }
132
+ }
133
+
134
+ /** Ask the page's other daily systems to start `day` (this one ignores its own event). */
135
+ private relayStart(day: string): void {
136
+ if (typeof window === 'undefined') {
137
+ return;
138
+ }
139
+ this.isRelaying = true;
140
+ try {
141
+ window.dispatchEvent(new CustomEvent(DAILY_START_EVENT, { detail: { day } }));
142
+ } finally {
143
+ this.isRelaying = false;
144
+ }
145
+ }
146
+
147
+ /** Abandon the active challenge without recording it (e.g. the player quit). */
148
+ cancel(): void {
149
+ this.active = null;
150
+ }
151
+
152
+ /** This game's window and the player's completions. */
153
+ status(): Promise<DailyStatus> {
154
+ return this.host.status();
155
+ }
156
+
157
+ /** Every daily-enabled game and the global standings (for the home hub). */
158
+ all(): Promise<DailyAll> {
159
+ return this.host.all();
160
+ }
161
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The page's one daily-challenge system (plan §4.4): the first bundle to
3
+ * create it wins, so the menu starts days on the instance the game defined.
4
+ */
5
+ import { HUB_CLIENT_VERSION } from '../core/version/client-version.gen';
6
+ import { claimSingleton } from '../globals';
7
+ import { hasMethods } from '../realtime/cross-bundle';
8
+ import { DailySystem } from './daily-system';
9
+ import type { DailyHost } from './types';
10
+
11
+ /** The cross-bundle shape number of the `daily` singleton. Bump only on an incompatible change. */
12
+ export const DAILY_SINGLETON_API = 1;
13
+
14
+ /** Whether `candidate` is some bundle's daily system (v1 copies included). */
15
+ // eslint-disable-next-line no-restricted-syntax -- trust boundary: the instance may come from another bundle
16
+ export function isDailySystem(candidate: unknown): candidate is DailySystem {
17
+ return hasMethods(candidate, ['define', 'startAndPlay', 'complete', 'cancel', 'status', 'all']);
18
+ }
19
+
20
+ let claimedDaily: DailySystem | null = null;
21
+
22
+ /**
23
+ * The page-wide daily system, created with `host` if no bundle has made one
24
+ * yet. On a shape mismatch the registered one is kept and this bundle gets a
25
+ * private instance. The answer is kept for this bundle.
26
+ */
27
+ export function getDaily(host: DailyHost): DailySystem {
28
+ claimedDaily ??= claimSingleton({
29
+ name: 'daily',
30
+ version: HUB_CLIENT_VERSION,
31
+ api: DAILY_SINGLETON_API,
32
+ create: () => new DailySystem(host),
33
+ isInstance: isDailySystem,
34
+ });
35
+ return claimedDaily;
36
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Daily challenge shapes: what a game's `play` receives, and the hub's
3
+ * answers (typed from the contract's daily endpoints).
4
+ */
5
+ import type { dailyEndpoints, Json } from '@diffenderfer-games/hub-contract';
6
+ import type { SchemaOutput } from '../realtime/wire-types';
7
+
8
+ /** The response type of a daily endpoint. */
9
+ type DailyResponse<Name extends keyof typeof dailyEndpoints> = SchemaOutput<(typeof dailyEndpoints)[Name]['cfg']['response']>;
10
+
11
+ /** This game's daily window and the player's completions (`GET /games/:slug/daily`). */
12
+ export type DailyStatus = DailyResponse<'getGameDailyChallenges'>;
13
+
14
+ /** Every daily game and the global standings (`GET /daily`). */
15
+ export type DailyAll = DailyResponse<'listDailyChallengesForAllGames'>;
16
+
17
+ /** One game's row in {@link DailyAll}. */
18
+ export type DailyGameStatus = DailyAll['games'][number];
19
+
20
+ /** The answer to starting a day: its seed and the signed token to present on completion. */
21
+ export type DailyStartResponse = DailyResponse<'startDailyChallenge'>;
22
+
23
+ /** The answer to completing a day: the player's new completion count and rank. */
24
+ export type DailyCompleteResponse = DailyResponse<'completeDailyChallenge'>;
25
+
26
+ /** The challenge a game's `play` receives: set up and start exactly this day (derive the level from `seed`). */
27
+ export interface DailyChallenge {
28
+ /** The day, `YYYY-MM-DD`. */
29
+ day: string;
30
+ /** Deterministic per game and day. */
31
+ seed: number;
32
+ /** The signed token `complete` presents. */
33
+ token: string;
34
+ /** The player already completed this day (a replay). */
35
+ alreadyCompleted?: boolean;
36
+ }
37
+
38
+ /** What `hub.daily.define` takes. */
39
+ export interface DailyDefinition {
40
+ /** Start this challenge now. */
41
+ play: (challenge: DailyChallenge) => void;
42
+ }
43
+
44
+ /** Metadata a game records with a completion (`{ score, difficulty, timeMs, … }`). */
45
+ export type DailyCompletionMeta = Record<string, Json>;
46
+
47
+ /** What the daily system needs from the hub client: the REST calls and its window events. */
48
+ export interface DailyHost {
49
+ /** This page's game slug. */
50
+ readonly slug: string | null;
51
+ /** `GET /games/:slug/daily`. */
52
+ status(): Promise<DailyStatus>;
53
+ /** `GET /daily`. */
54
+ all(): Promise<DailyAll>;
55
+ /** `POST /games/:slug/daily/:day/start`. */
56
+ start(day: string): Promise<DailyStartResponse>;
57
+ /** `POST /games/:slug/daily/:day/complete`. */
58
+ complete(day: string, token: string, meta: DailyCompletionMeta): Promise<DailyCompleteResponse>;
59
+ /** Fire a `hub:*` window event (the menu listens). */
60
+ emit(name: string, detail: DailyEventDetail): void;
61
+ }
62
+
63
+ /** The detail of the `hub:daily-*` window events. */
64
+ export type DailyEventDetail =
65
+ | { day: string; seed: number; alreadyCompleted: boolean }
66
+ | { day: string; count: number; rank: number | null; meta: DailyCompletionMeta }
67
+ | { day: string; error: string };
package/src/daily.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `@diffenderfer-games/hub/daily`: daily challenges (`hub.daily`): the
3
+ * {@link DailySystem} and the page-wide {@link getDaily}.
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ export { DAILY_START_EVENT, DailySystem } from './daily/daily-system';
8
+ export { DAILY_SINGLETON_API, getDaily, isDailySystem } from './daily/page-daily';
9
+ export type * from './daily/types';
10
+ export type { DailyCompletion, DailyCompletions } from '@diffenderfer-games/hub-contract';