ludicord 2.2.4 → 3.0.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.
Files changed (150) hide show
  1. package/README.md +21 -5
  2. package/dist/activity/game-loop.d.ts +16 -0
  3. package/dist/activity/game-loop.js +33 -0
  4. package/dist/activity/index.d.ts +12 -0
  5. package/dist/activity/index.js +6 -0
  6. package/dist/activity/lifecycle.d.ts +11 -0
  7. package/dist/activity/lifecycle.js +41 -0
  8. package/dist/activity/presence.d.ts +10 -0
  9. package/dist/activity/presence.js +15 -0
  10. package/dist/activity/query.d.ts +21 -0
  11. package/dist/activity/query.js +148 -0
  12. package/dist/activity/shared-state.d.ts +10 -0
  13. package/dist/activity/shared-state.js +100 -0
  14. package/dist/activity/storage.d.ts +16 -0
  15. package/dist/activity/storage.js +88 -0
  16. package/dist/api/runtime.d.ts +5 -2
  17. package/dist/api/runtime.js +53 -10
  18. package/dist/auth/client.d.ts +0 -1
  19. package/dist/auth/client.js +3 -5
  20. package/dist/auth/index.d.ts +0 -1
  21. package/dist/auth/index.js +0 -1
  22. package/dist/auth/server.d.ts +2 -1
  23. package/dist/auth/server.js +161 -16
  24. package/dist/auth/types.d.ts +5 -1
  25. package/dist/auth/types.js +0 -1
  26. package/dist/cli/index.d.ts +0 -1
  27. package/dist/cli/index.js +116 -19
  28. package/dist/cli/project-commands.d.ts +1 -5
  29. package/dist/cli/project-commands.js +14 -162
  30. package/dist/compiler/build.d.ts +10 -1
  31. package/dist/compiler/build.js +124 -16
  32. package/dist/compiler/bundle-report.d.ts +17 -0
  33. package/dist/compiler/bundle-report.js +60 -0
  34. package/dist/compiler/client-entry.d.ts +0 -1
  35. package/dist/compiler/client-entry.js +28 -4
  36. package/dist/compiler/client-tooling.d.ts +0 -1
  37. package/dist/compiler/client-tooling.js +8 -2
  38. package/dist/compiler/index.d.ts +3 -1
  39. package/dist/compiler/index.js +2 -1
  40. package/dist/compiler/scanner.d.ts +0 -1
  41. package/dist/compiler/scanner.js +59 -4
  42. package/dist/compiler/server-bundle.d.ts +1 -2
  43. package/dist/compiler/server-bundle.js +11 -2
  44. package/dist/compiler/type-generation.d.ts +0 -1
  45. package/dist/compiler/type-generation.js +2 -1
  46. package/dist/compiler/write-manifests.d.ts +0 -1
  47. package/dist/compiler/write-manifests.js +0 -1
  48. package/dist/config/defaults.d.ts +0 -1
  49. package/dist/config/defaults.js +14 -2
  50. package/dist/config/environment.d.ts +0 -1
  51. package/dist/config/environment.js +0 -1
  52. package/dist/config/index.d.ts +0 -1
  53. package/dist/config/index.js +0 -1
  54. package/dist/config/loader.d.ts +0 -1
  55. package/dist/config/loader.js +0 -1
  56. package/dist/config/project-root.d.ts +0 -1
  57. package/dist/config/project-root.js +0 -1
  58. package/dist/config/types.d.ts +25 -1
  59. package/dist/config/types.js +0 -1
  60. package/dist/discord/assets.d.ts +5 -0
  61. package/dist/discord/assets.js +29 -0
  62. package/dist/discord/data.d.ts +38 -2
  63. package/dist/discord/data.js +178 -11
  64. package/dist/discord/events.d.ts +28 -2
  65. package/dist/discord/events.js +109 -39
  66. package/dist/discord/index.d.ts +6 -5
  67. package/dist/discord/index.js +3 -3
  68. package/dist/discord/payload.d.ts +6 -0
  69. package/dist/discord/payload.js +5 -0
  70. package/dist/discord/runtime.d.ts +0 -1
  71. package/dist/discord/runtime.js +0 -1
  72. package/dist/discord/safe-area.d.ts +0 -1
  73. package/dist/discord/safe-area.js +0 -1
  74. package/dist/discord/testing.d.ts +0 -1
  75. package/dist/discord/testing.js +0 -1
  76. package/dist/index.d.ts +6 -1
  77. package/dist/index.js +3 -1
  78. package/dist/lint/index.d.ts +6 -0
  79. package/dist/lint/index.js +71 -0
  80. package/dist/manifests/types.d.ts +11 -1
  81. package/dist/manifests/types.js +0 -1
  82. package/dist/metadata/index.d.ts +13 -0
  83. package/dist/metadata/index.js +4 -0
  84. package/dist/navigation/index.d.ts +3 -1
  85. package/dist/navigation/index.js +1 -1
  86. package/dist/navigation/link.d.ts +8 -0
  87. package/dist/navigation/link.js +38 -0
  88. package/dist/router/match.d.ts +0 -1
  89. package/dist/router/match.js +0 -1
  90. package/dist/runtime/client/dev-panel.d.ts +0 -1
  91. package/dist/runtime/client/dev-panel.js +722 -38
  92. package/dist/runtime/client/embed-router.d.ts +8 -1
  93. package/dist/runtime/client/embed-router.js +116 -62
  94. package/dist/runtime/client/files.d.ts +5 -1
  95. package/dist/runtime/client/files.js +0 -1
  96. package/dist/runtime/client/minimize-card.d.ts +0 -1
  97. package/dist/runtime/client/minimize-card.js +0 -1
  98. package/dist/runtime/client/minimize.d.ts +0 -1
  99. package/dist/runtime/client/minimize.js +0 -1
  100. package/dist/runtime/client/root.d.ts +5 -3
  101. package/dist/runtime/client/root.js +28 -3
  102. package/dist/runtime/index.d.ts +1 -2
  103. package/dist/runtime/index.js +0 -1
  104. package/dist/runtime/server/dev-server.d.ts +0 -1
  105. package/dist/runtime/server/dev-server.js +191 -30
  106. package/dist/runtime/server/diagnostics.d.ts +1 -1
  107. package/dist/runtime/server/diagnostics.js +5 -4
  108. package/dist/runtime/server/index.d.ts +0 -1
  109. package/dist/runtime/server/index.js +0 -1
  110. package/dist/runtime/server/production-server.d.ts +2 -1
  111. package/dist/runtime/server/production-server.js +145 -25
  112. package/dist/security/discord.d.ts +0 -1
  113. package/dist/security/discord.js +0 -1
  114. package/dist/security/index.d.ts +0 -1
  115. package/dist/security/index.js +0 -1
  116. package/dist/security/secret-scan.d.ts +0 -1
  117. package/dist/security/secret-scan.js +0 -1
  118. package/dist/server/discord-rest.d.ts +42 -7
  119. package/dist/server/discord-rest.js +135 -18
  120. package/dist/server/index.d.ts +7 -2
  121. package/dist/server/index.js +3 -1
  122. package/dist/server/instrumentation.d.ts +16 -0
  123. package/dist/server/instrumentation.js +3 -0
  124. package/dist/server/proxy.d.ts +21 -0
  125. package/dist/server/proxy.js +76 -0
  126. package/dist/server/session.d.ts +0 -1
  127. package/dist/server/session.js +0 -1
  128. package/dist/server/types.d.ts +0 -1
  129. package/dist/server/types.js +0 -1
  130. package/dist/sessions/cookies.d.ts +0 -1
  131. package/dist/sessions/cookies.js +0 -1
  132. package/dist/sessions/crypto.d.ts +0 -1
  133. package/dist/sessions/crypto.js +0 -1
  134. package/dist/sessions/data-store.d.ts +18 -0
  135. package/dist/sessions/data-store.js +45 -0
  136. package/dist/shared/errors.d.ts +0 -1
  137. package/dist/shared/errors.js +0 -1
  138. package/dist/testing/index.d.ts +0 -1
  139. package/dist/testing/index.js +2 -2
  140. package/dist/version.d.ts +1 -2
  141. package/dist/version.js +1 -2
  142. package/dist/ws/client.d.ts +0 -1
  143. package/dist/ws/client.js +0 -1
  144. package/dist/ws/index.d.ts +3 -2
  145. package/dist/ws/index.js +1 -1
  146. package/dist/ws/server.d.ts +5 -3
  147. package/dist/ws/server.js +65 -19
  148. package/dist/ws/shared-state.d.ts +13 -0
  149. package/dist/ws/shared-state.js +137 -0
  150. package/package.json +16 -3
@@ -0,0 +1,76 @@
1
+ export function defineProxy(proxy) {
2
+ return proxy;
3
+ }
4
+ function toWebRequest(request, signal) {
5
+ const origin = `${request.protocol}://${request.get("host") ?? "localhost"}`;
6
+ const headers = new Headers();
7
+ for (const [name, value] of Object.entries(request.headers)) {
8
+ if (value !== undefined)
9
+ headers.set(name, Array.isArray(value) ? value.join(", ") : value);
10
+ }
11
+ return new Request(new URL(request.originalUrl, origin), {
12
+ method: request.method,
13
+ headers,
14
+ signal,
15
+ });
16
+ }
17
+ async function sendProxyResponse(request, response, result) {
18
+ response.status(result.status);
19
+ for (const [name, value] of result.headers) {
20
+ if (name.toLowerCase() !== "set-cookie")
21
+ response.setHeader(name, value);
22
+ }
23
+ for (const cookie of result.headers.getSetCookie())
24
+ response.appendHeader("set-cookie", cookie);
25
+ if (request.method === "HEAD" || result.body === null) {
26
+ response.end();
27
+ return;
28
+ }
29
+ response.send(Buffer.from(await result.arrayBuffer()));
30
+ }
31
+ export function createProxyMiddleware(options) {
32
+ return async (request, response, next) => {
33
+ if (request.path === "/_ludicord" || request.path.startsWith("/_ludicord/")) {
34
+ next();
35
+ return;
36
+ }
37
+ const controller = new AbortController();
38
+ const abort = () => controller.abort(new Error("The client disconnected."));
39
+ request.once("aborted", abort);
40
+ try {
41
+ const source = typeof options.source === "function" ? options.source() : options.source;
42
+ if (source === undefined) {
43
+ next();
44
+ return;
45
+ }
46
+ const module = await options.loadModule(source);
47
+ const proxy = module.default ?? module.proxy;
48
+ if (typeof proxy !== "function") {
49
+ throw new Error("LUDICORD3005: app/proxy.ts must export a default proxy function.");
50
+ }
51
+ const result = await proxy(toWebRequest(request, controller.signal), {
52
+ environment: options.environment,
53
+ projectRoot: options.projectRoot,
54
+ });
55
+ if (result === undefined) {
56
+ next();
57
+ return;
58
+ }
59
+ if (!(result instanceof Response)) {
60
+ throw new TypeError("LUDICORD3005: app/proxy.ts must return a Response or undefined.");
61
+ }
62
+ await sendProxyResponse(request, response, result);
63
+ }
64
+ catch (error) {
65
+ const source = typeof options.source === "function" ? options.source() : options.source;
66
+ await options.onError?.(error, source ?? "app/proxy.ts", {
67
+ method: request.method,
68
+ url: request.originalUrl,
69
+ });
70
+ next(error);
71
+ }
72
+ finally {
73
+ request.off("aborted", abort);
74
+ }
75
+ };
76
+ }
@@ -1,4 +1,3 @@
1
1
  import type { LudicordSession } from "../auth/types.js";
2
2
  export declare function getLudicordSession(request: Request, secret?: string | undefined): LudicordSession | null;
3
3
  export declare function requireLudicordSession(request: Request, secret?: string): LudicordSession;
4
- //# sourceMappingURL=session.d.ts.map
@@ -11,4 +11,3 @@ export function requireLudicordSession(request, secret) {
11
11
  }
12
12
  return session;
13
13
  }
14
- //# sourceMappingURL=session.js.map
@@ -11,4 +11,3 @@ export interface LudicordRequest extends Request {
11
11
  export interface RouteContext {
12
12
  readonly params: Readonly<Record<string, string>>;
13
13
  }
14
- //# sourceMappingURL=types.d.ts.map
@@ -1,2 +1 @@
1
1
  export {};
2
- //# sourceMappingURL=types.js.map
@@ -13,4 +13,3 @@ export declare function parseCookies(cookieHeader: string | undefined): Readonly
13
13
  export declare function parseSessionCookie(cookieHeader: string | undefined, secret: string, options?: {
14
14
  readonly allowDevelopment?: boolean;
15
15
  }): LudicordSession | null;
16
- //# sourceMappingURL=cookies.d.ts.map
@@ -63,4 +63,3 @@ export function parseSessionCookie(cookieHeader, secret, options = {}) {
63
63
  return null;
64
64
  return session;
65
65
  }
66
- //# sourceMappingURL=cookies.js.map
@@ -2,4 +2,3 @@ import type { LudicordSession } from "../auth/types.js";
2
2
  export declare function sealLudicordSession(session: LudicordSession, secret: string): string;
3
3
  export declare function unsealLudicordSession(value: string, secret: string): LudicordSession | null;
4
4
  export declare function safeEqual(left: string, right: string): boolean;
5
- //# sourceMappingURL=crypto.d.ts.map
@@ -64,4 +64,3 @@ export function safeEqual(left, right) {
64
64
  return (leftBuffer.length === rightBuffer.length &&
65
65
  timingSafeEqual(leftBuffer, rightBuffer));
66
66
  }
67
- //# sourceMappingURL=crypto.js.map
@@ -0,0 +1,18 @@
1
+ import type { DiscordRawPayload } from "../discord/payload.js";
2
+ export interface LudicordExtendedSessionData {
3
+ readonly userRaw?: DiscordRawPayload;
4
+ readonly guildRaw?: DiscordRawPayload;
5
+ }
6
+ export interface LudicordSessionDataStore {
7
+ get(id: string): LudicordExtendedSessionData | null | Promise<LudicordExtendedSessionData | null>;
8
+ set(id: string, data: LudicordExtendedSessionData, expiresAt: number): void | Promise<void>;
9
+ delete(id: string): void | Promise<void>;
10
+ }
11
+ /**
12
+ * Zero-configuration session-data storage for one Ludicord process. Production
13
+ * clusters can provide a shared adapter through createLudicordProductionServer.
14
+ */
15
+ export declare function createMemorySessionDataStore(options?: {
16
+ readonly maxEntries?: number;
17
+ readonly now?: () => number;
18
+ }): LudicordSessionDataStore;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Zero-configuration session-data storage for one Ludicord process. Production
3
+ * clusters can provide a shared adapter through createLudicordProductionServer.
4
+ */
5
+ export function createMemorySessionDataStore(options = {}) {
6
+ const maxEntries = options.maxEntries ?? 2_000;
7
+ if (!Number.isSafeInteger(maxEntries) || maxEntries < 1 || maxEntries > 100_000) {
8
+ throw new Error("LUDICORD6013: Session data maxEntries must be an integer between 1 and 100000.");
9
+ }
10
+ const now = options.now ?? Date.now;
11
+ const entries = new Map();
12
+ const prune = () => {
13
+ const current = now();
14
+ for (const [id, entry] of entries) {
15
+ if (entry.expiresAt <= current)
16
+ entries.delete(id);
17
+ }
18
+ while (entries.size >= maxEntries) {
19
+ const oldest = entries.keys().next().value;
20
+ if (oldest === undefined)
21
+ break;
22
+ entries.delete(oldest);
23
+ }
24
+ };
25
+ return {
26
+ get(id) {
27
+ const entry = entries.get(id);
28
+ if (entry === undefined)
29
+ return null;
30
+ if (entry.expiresAt <= now()) {
31
+ entries.delete(id);
32
+ return null;
33
+ }
34
+ return entry.data;
35
+ },
36
+ set(id, data, expiresAt) {
37
+ entries.delete(id);
38
+ prune();
39
+ entries.set(id, { data, expiresAt });
40
+ },
41
+ delete(id) {
42
+ entries.delete(id);
43
+ },
44
+ };
45
+ }
@@ -4,4 +4,3 @@ export declare class LudicordError extends Error {
4
4
  constructor(code: LudicordErrorCode, message: string);
5
5
  }
6
6
  export declare function isLudicordError(error: unknown): error is LudicordError;
7
- //# sourceMappingURL=errors.d.ts.map
@@ -9,4 +9,3 @@ export class LudicordError extends Error {
9
9
  export function isLudicordError(error) {
10
10
  return error instanceof LudicordError;
11
11
  }
12
- //# sourceMappingURL=errors.js.map
@@ -15,4 +15,3 @@ export declare function renderLudicordActivity(children: ReactNode, options?: {
15
15
  rerender: (node: ReactNode) => Promise<void>;
16
16
  unmount(): Promise<void>;
17
17
  }>;
18
- //# sourceMappingURL=index.d.ts.map
@@ -6,7 +6,8 @@ import { createRoot } from "react-dom/client";
6
6
  import { setMockSessionForTesting } from "../auth/client.js";
7
7
  import { LudicordRoot } from "../runtime/client/root.js";
8
8
  export function createMockSession(overrides = {}) {
9
- return { authenticated: true, user: { id: "mock-user", username: "mock_user", displayName: "Mock User", avatar: null },
9
+ return { authenticated: true, user: { id: "mock-user", username: "mock_user", displayName: "Mock User", avatar: null,
10
+ raw: { id: "mock-user", username: "mock_user", global_name: "Mock User", avatar: null } },
10
11
  applicationId: "mock-application", instanceId: "mock-instance", guildId: "mock-guild", channelId: "mock-channel",
11
12
  scopes: ["identify", "guilds"], issuedAt: Date.now(), expiresAt: Date.now() + 3_600_000, ...overrides };
12
13
  }
@@ -25,4 +26,3 @@ export async function renderLudicordActivity(children, options = {}) {
25
26
  container.remove(); if (options.session !== undefined)
26
27
  setMockSessionForTesting(null); } };
27
28
  }
28
- //# sourceMappingURL=index.js.map
package/dist/version.d.ts CHANGED
@@ -1,2 +1 @@
1
- export declare const LUDICORD_VERSION: "2.2.4";
2
- //# sourceMappingURL=version.d.ts.map
1
+ export declare const LUDICORD_VERSION: "3.0.0";
package/dist/version.js CHANGED
@@ -1,2 +1 @@
1
- export const LUDICORD_VERSION = "2.2.4";
2
- //# sourceMappingURL=version.js.map
1
+ export const LUDICORD_VERSION = "3.0.0";
@@ -59,4 +59,3 @@ export declare class LudicordWebSocketConnection {
59
59
  }
60
60
  export declare function useWS(route: LudicordWSRoute, options?: LudicordWSConnectionOptions): LudicordWSConnection;
61
61
  export {};
62
- //# sourceMappingURL=client.d.ts.map
package/dist/ws/client.js CHANGED
@@ -201,4 +201,3 @@ export function useWS(route, options = {}) {
201
201
  reconnect: () => connection.reconnect(),
202
202
  }), [connection, status]);
203
203
  }
204
- //# sourceMappingURL=client.js.map
@@ -1,5 +1,6 @@
1
1
  export { useWS } from "./client.js";
2
2
  export { defineWS } from "./server.js";
3
- export type { LudicordWSConnection, LudicordWSStatus, } from "./client.js";
3
+ export { defineSharedActivityState } from "./shared-state.js";
4
+ export type { LudicordWSConnection, LudicordWSConnectionOptions, LudicordWSStatus, } from "./client.js";
4
5
  export type { LudicordWebSocketClient, LudicordWebSocketRoute, LudicordWSEventEnvelope, } from "./server.js";
5
- //# sourceMappingURL=index.d.ts.map
6
+ export type { LudicordSharedStateContext, LudicordSharedStateOptions } from "./shared-state.js";
package/dist/ws/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  export { useWS } from "./client.js";
2
2
  export { defineWS } from "./server.js";
3
- //# sourceMappingURL=index.js.map
3
+ export { defineSharedActivityState } from "./shared-state.js";
@@ -55,18 +55,20 @@ export interface WebSocketRuntimeOptions {
55
55
  readonly maxPayload?: number;
56
56
  readonly compression?: boolean;
57
57
  readonly backpressureLimit?: number;
58
+ readonly maxMessagesPerSecond?: number;
58
59
  readonly allowDevelopmentSessions?: boolean;
59
60
  readonly enabled?: boolean;
60
- readonly onError?: (error: unknown, file?: string) => void;
61
+ readonly onError?: (error: unknown, file?: string) => void | Promise<void>;
61
62
  }
62
63
  export interface LudicordWebSocketRuntime {
63
64
  readonly server: WebSocketServer;
64
65
  readonly clientCount: () => number;
65
66
  heartbeatNow(): void;
66
67
  reload(): void;
67
- close(): Promise<void>;
68
+ close(options?: {
69
+ readonly gracePeriodMs?: number;
70
+ }): Promise<void>;
68
71
  }
69
72
  export declare function defineWS<const TRoute extends LudicordWebSocketRoute>(route: TRoute): TRoute;
70
73
  export declare function attachWebSocketRuntime(httpServer: HttpServer, options: WebSocketRuntimeOptions): LudicordWebSocketRuntime;
71
74
  export {};
72
- //# sourceMappingURL=server.d.ts.map
package/dist/ws/server.js CHANGED
@@ -55,6 +55,8 @@ class RuntimeClient {
55
55
  id = randomUUID();
56
56
  memberships = new Set();
57
57
  alive = true;
58
+ messageWindowStarted = Date.now();
59
+ messageCount = 0;
58
60
  room;
59
61
  activity;
60
62
  constructor(socket, ludicord, params, rooms, routeClients, backpressureLimit, routeKey) {
@@ -122,6 +124,14 @@ class RuntimeClient {
122
124
  close(code = 1000, reason = "") {
123
125
  this.socket.close(code, reason);
124
126
  }
127
+ acceptMessage(limit, now = Date.now()) {
128
+ if (now - this.messageWindowStarted >= 1_000) {
129
+ this.messageWindowStarted = now;
130
+ this.messageCount = 0;
131
+ }
132
+ this.messageCount += 1;
133
+ return this.messageCount <= limit;
134
+ }
125
135
  }
126
136
  function normalizeRoom(name) {
127
137
  const normalized = name.trim();
@@ -156,11 +166,25 @@ export function attachWebSocketRuntime(httpServer, options) {
156
166
  const loadModule = options.loadModule ?? defaultLoader;
157
167
  const heartbeatInterval = options.heartbeatInterval ?? 30_000;
158
168
  const backpressureLimit = options.backpressureLimit ?? 1_048_576;
169
+ const maxMessagesPerSecond = options.maxMessagesPerSecond ?? 120;
170
+ if (!Number.isSafeInteger(maxMessagesPerSecond) ||
171
+ maxMessagesPerSecond < 1 ||
172
+ maxMessagesPerSecond > 10_000) {
173
+ throw new Error("LUDICORD9004: websocket.maxMessagesPerSecond must be an integer between 1 and 10000.");
174
+ }
159
175
  const wss = new WebSocketServer({
160
176
  noServer: true,
161
177
  maxPayload: options.maxPayload ?? 1_048_576,
162
178
  perMessageDeflate: options.compression ?? false,
163
179
  });
180
+ const reportError = (error, file) => {
181
+ try {
182
+ void Promise.resolve(options.onError?.(error, file)).catch(() => undefined);
183
+ }
184
+ catch {
185
+ // Error reporting must never create a second WebSocket failure.
186
+ }
187
+ };
164
188
  const onUpgrade = (request, socket, head) => {
165
189
  const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
166
190
  if (!pathname.startsWith("/ws/") && pathname !== "/ws")
@@ -206,31 +230,35 @@ export function attachWebSocketRuntime(httpServer, options) {
206
230
  client.alive = true;
207
231
  });
208
232
  webSocket.on("message", (raw) => {
209
- void dispatchMessage(client, route, raw.toString());
233
+ void dispatchMessage(client, route, raw.toString(), selected.route.file);
210
234
  });
211
235
  webSocket.on("close", (code, reason) => {
212
236
  clients.delete(client);
213
237
  routeClients.delete(client);
214
238
  rooms.remove(client);
215
- void Promise.resolve().then(() => route.disconnect?.(client, code, reason.toString())).catch((error) => options.onError?.(error, selected.route.file));
239
+ void Promise.resolve().then(() => route.disconnect?.(client, code, reason.toString())).catch((error) => reportError(error, selected.route.file));
216
240
  });
217
241
  void Promise.resolve().then(() => route.connect?.(client)).catch((error) => {
218
- options.onError?.(error, selected.route.file);
242
+ reportError(error, selected.route.file);
219
243
  client.close(1011, "Connect handler failed");
220
244
  });
221
245
  });
222
246
  }
223
247
  catch (error) {
224
- options.onError?.(error, selected.route.file);
248
+ reportError(error, selected.route.file);
225
249
  rejectUpgrade(socket, 500, "Internal Server Error");
226
250
  }
227
- })().catch((error) => { options.onError?.(error); rejectUpgrade(socket, 400, "Bad Request"); });
251
+ })().catch((error) => { reportError(error); rejectUpgrade(socket, 400, "Bad Request"); });
228
252
  };
229
- async function dispatchMessage(client, route, raw) {
253
+ async function dispatchMessage(client, route, raw, file) {
230
254
  if (client.ludicord.expiresAt <= Date.now()) {
231
255
  client.close(1008, "Session expired");
232
256
  return;
233
257
  }
258
+ if (!client.acceptMessage(maxMessagesPerSecond)) {
259
+ client.close(1008, "Message rate limit exceeded");
260
+ return;
261
+ }
234
262
  let envelope;
235
263
  try {
236
264
  envelope = JSON.parse(raw);
@@ -261,7 +289,7 @@ export function attachWebSocketRuntime(httpServer, options) {
261
289
  await handler(client, envelope.data);
262
290
  }
263
291
  catch (error) {
264
- options.onError?.(error);
292
+ reportError(error, file);
265
293
  client.sendInternal("error", { code: "LUDICORD_EVENT_HANDLER_FAILED" });
266
294
  }
267
295
  }
@@ -282,6 +310,7 @@ export function attachWebSocketRuntime(httpServer, options) {
282
310
  const heartbeat = setInterval(heartbeatNow, heartbeatInterval);
283
311
  heartbeat.unref();
284
312
  httpServer.on("upgrade", onUpgrade);
313
+ let closePromise = null;
285
314
  return {
286
315
  server: wss,
287
316
  clientCount: () => clients.size,
@@ -290,24 +319,41 @@ export function attachWebSocketRuntime(httpServer, options) {
290
319
  for (const client of clients)
291
320
  client.close(1012, "Ludicord route updated");
292
321
  },
293
- async close() {
322
+ close(closeOptions = {}) {
323
+ if (closePromise !== null)
324
+ return closePromise;
294
325
  httpServer.off("upgrade", onUpgrade);
295
326
  clearInterval(heartbeat);
296
- for (const client of [...clients]) {
297
- client.socket.close(1001, "Server shutting down");
327
+ const gracePeriodMs = closeOptions.gracePeriodMs ?? 1_000;
328
+ if (!Number.isSafeInteger(gracePeriodMs) || gracePeriodMs < 0 || gracePeriodMs > 120_000) {
329
+ throw new Error("LUDICORD9005: WebSocket shutdown gracePeriodMs must be an integer between 0 and 120000.");
298
330
  }
299
- await new Promise((resolve) => {
300
- if (wss.clients.size === 0) {
301
- wss.close(() => resolve());
302
- return;
331
+ closePromise = (async () => {
332
+ const closing = [...wss.clients].map((socket) => new Promise((resolve) => {
333
+ if (socket.readyState === WebSocket.CLOSED) {
334
+ resolve();
335
+ return;
336
+ }
337
+ socket.once("close", () => resolve());
338
+ if (socket.readyState === WebSocket.OPEN)
339
+ socket.close(1001, "Server shutting down");
340
+ }));
341
+ if (closing.length > 0 && gracePeriodMs > 0) {
342
+ let timer;
343
+ await Promise.race([
344
+ Promise.allSettled(closing),
345
+ new Promise((resolve) => { timer = setTimeout(resolve, gracePeriodMs); }),
346
+ ]);
347
+ if (timer !== undefined)
348
+ clearTimeout(timer);
303
349
  }
304
350
  for (const socket of wss.clients)
305
351
  socket.terminate();
306
- wss.close(() => resolve());
307
- });
308
- clients.clear();
309
- clientsByRoute.clear();
352
+ await new Promise((resolve) => wss.close(() => resolve()));
353
+ clients.clear();
354
+ clientsByRoute.clear();
355
+ })();
356
+ return closePromise;
310
357
  },
311
358
  };
312
359
  }
313
- //# sourceMappingURL=server.js.map
@@ -0,0 +1,13 @@
1
+ import type { LudicordWebSocketClient, LudicordWebSocketRoute } from "./server.js";
2
+ export interface LudicordSharedStateContext {
3
+ readonly key: string;
4
+ readonly client: LudicordWebSocketClient;
5
+ }
6
+ export interface LudicordSharedStateOptions<T> {
7
+ readonly initialState: T | ((context: LudicordSharedStateContext) => T);
8
+ readonly validate?: (value: unknown, context: LudicordSharedStateContext) => value is T;
9
+ readonly maxRooms?: number;
10
+ readonly roomTtl?: number;
11
+ readonly maxValueBytes?: number;
12
+ }
13
+ export declare function defineSharedActivityState<T>(options: LudicordSharedStateOptions<T>): LudicordWebSocketRoute;
@@ -0,0 +1,137 @@
1
+ import { defineWS } from "./server.js";
2
+ const SUBSCRIBE_EVENT = "ludicord:shared:subscribe";
3
+ const SET_EVENT = "ludicord:shared:set";
4
+ const STATE_EVENT = "ludicord:shared:state";
5
+ function record(value) {
6
+ return typeof value === "object" && value !== null ? value : null;
7
+ }
8
+ function stateKey(value) {
9
+ if (typeof value !== "string" || value.trim() === "" || value.length > 128) {
10
+ throw new Error("LUDICORD9201: Shared Activity state keys must contain 1-128 characters.");
11
+ }
12
+ return value;
13
+ }
14
+ function roomKey(client) {
15
+ const instanceId = client.ludicord.instanceId;
16
+ if (instanceId === undefined || instanceId === "") {
17
+ throw new Error("LUDICORD9202: Shared Activity state requires a verified Activity instance.");
18
+ }
19
+ return `${client.ludicord.applicationId}:${instanceId}`;
20
+ }
21
+ export function defineSharedActivityState(options) {
22
+ const maxRooms = options.maxRooms ?? 1_000;
23
+ const roomTtl = options.roomTtl ?? 60 * 60 * 1_000;
24
+ const maxValueBytes = options.maxValueBytes ?? 64 * 1_024;
25
+ if (!Number.isSafeInteger(maxRooms) || maxRooms < 1 || maxRooms > 100_000)
26
+ throw new Error("LUDICORD9203: maxRooms must be between 1 and 100000.");
27
+ if (!Number.isSafeInteger(roomTtl) || roomTtl < 1_000 || roomTtl > 7 * 24 * 60 * 60 * 1_000)
28
+ throw new Error("LUDICORD9203: roomTtl must be between 1000 milliseconds and 7 days.");
29
+ if (!Number.isSafeInteger(maxValueBytes) || maxValueBytes < 16 || maxValueBytes > 1_048_576)
30
+ throw new Error("LUDICORD9203: maxValueBytes must be between 16 and 1048576.");
31
+ const rooms = new Map();
32
+ const prune = (now = Date.now()) => {
33
+ for (const [key, room] of rooms)
34
+ if (now - room.touchedAt > roomTtl)
35
+ rooms.delete(key);
36
+ };
37
+ const roomFor = (client) => {
38
+ prune();
39
+ const key = roomKey(client);
40
+ const existing = rooms.get(key);
41
+ if (existing !== undefined) {
42
+ existing.touchedAt = Date.now();
43
+ return existing;
44
+ }
45
+ while (rooms.size >= maxRooms) {
46
+ const oldest = [...rooms].sort((left, right) => left[1].touchedAt - right[1].touchedAt)[0];
47
+ if (oldest === undefined)
48
+ break;
49
+ rooms.delete(oldest[0]);
50
+ }
51
+ const room = { values: new Map(), touchedAt: Date.now() };
52
+ room.touchedAt = Date.now();
53
+ rooms.set(key, room);
54
+ return room;
55
+ };
56
+ const initial = (key, client) => typeof options.initialState === "function"
57
+ ? options.initialState({ key, client })
58
+ : options.initialState;
59
+ const serializableSize = (value) => {
60
+ try {
61
+ const serialized = JSON.stringify(value);
62
+ return serialized === undefined ? null : Buffer.byteLength(serialized);
63
+ }
64
+ catch {
65
+ return null;
66
+ }
67
+ };
68
+ const current = (key, client) => {
69
+ const room = roomFor(client);
70
+ const existing = room.values.get(key);
71
+ if (existing !== undefined)
72
+ return existing;
73
+ const value = initial(key, client);
74
+ const context = { key, client };
75
+ if (options.validate !== undefined && !options.validate(value, context)) {
76
+ throw new Error("LUDICORD9204: initialState did not pass shared state validation.");
77
+ }
78
+ const size = serializableSize(value);
79
+ if (size === null)
80
+ throw new Error("LUDICORD9204: initialState must be JSON-serializable.");
81
+ if (size > maxValueBytes)
82
+ throw new Error("LUDICORD9204: initialState exceeds maxValueBytes.");
83
+ const created = { value, revision: 0 };
84
+ room.values.set(key, created);
85
+ return created;
86
+ };
87
+ const send = (client, key, value) => client.emit(STATE_EVENT, { key, value: value.value, revision: value.revision });
88
+ return defineWS({
89
+ connect(client) {
90
+ try {
91
+ client.activity.join();
92
+ }
93
+ catch {
94
+ client.close(1008, "Activity instance required");
95
+ }
96
+ },
97
+ events: {
98
+ [SUBSCRIBE_EVENT](client, payload) {
99
+ const key = stateKey(record(payload)?.key);
100
+ send(client, key, current(key, client));
101
+ },
102
+ [SET_EVENT](client, payload) {
103
+ const source = record(payload);
104
+ const key = stateKey(source?.key);
105
+ const previous = current(key, client);
106
+ const expectedRevision = source?.revision;
107
+ if (typeof expectedRevision === "number" && expectedRevision !== previous.revision) {
108
+ send(client, key, previous);
109
+ return;
110
+ }
111
+ const context = { key, client };
112
+ if (options.validate !== undefined && !options.validate(source?.value, context)) {
113
+ client.close(1008, "Invalid shared state");
114
+ return;
115
+ }
116
+ const size = serializableSize(source?.value);
117
+ if (size === null) {
118
+ client.close(1008, "Shared state must be serializable");
119
+ return;
120
+ }
121
+ if (size > maxValueBytes) {
122
+ client.close(1009, "Shared state exceeds limit");
123
+ return;
124
+ }
125
+ const next = { value: source?.value, revision: previous.revision + 1 };
126
+ roomFor(client).values.set(key, next);
127
+ client.activity.broadcast(STATE_EVENT, { key, value: next.value, revision: next.revision }, { includeSelf: true });
128
+ },
129
+ },
130
+ disconnect(client) {
131
+ try {
132
+ client.activity.leave();
133
+ }
134
+ catch { /* The client may have lacked an instance. */ }
135
+ },
136
+ });
137
+ }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "ludicord",
3
- "version": "2.2.4",
3
+ "version": "3.0.0",
4
4
  "description": "Full-stack React framework for Discord Activities.",
5
5
  "homepage": "https://github.com/mrcholer/ludicord#readme",
6
6
  "repository": {
7
7
  "type": "git",
8
- "url": "git+https://github.com/mrcholer/ludicord-source.git",
8
+ "url": "git+https://github.com/mrcholer/ludicord.git",
9
9
  "directory": "packages/ludicord"
10
10
  },
11
11
  "bugs": {
@@ -16,7 +16,7 @@
16
16
  "publishConfig": {
17
17
  "access": "public",
18
18
  "registry": "https://registry.npmjs.org/",
19
- "provenance": false
19
+ "provenance": true
20
20
  },
21
21
  "engines": {
22
22
  "node": ">=20.19.0"
@@ -46,6 +46,16 @@
46
46
  "import": "./dist/navigation/index.js",
47
47
  "default": "./dist/navigation/index.js"
48
48
  },
49
+ "./metadata": {
50
+ "types": "./dist/metadata/index.d.ts",
51
+ "import": "./dist/metadata/index.js",
52
+ "default": "./dist/metadata/index.js"
53
+ },
54
+ "./activity": {
55
+ "types": "./dist/activity/index.d.ts",
56
+ "import": "./dist/activity/index.js",
57
+ "default": "./dist/activity/index.js"
58
+ },
49
59
  "./discord": {
50
60
  "types": "./dist/discord/index.d.ts",
51
61
  "import": "./dist/discord/index.js",
@@ -115,8 +125,11 @@
115
125
  "dependencies": {
116
126
  "@discord/embedded-app-sdk": "^2.4.0",
117
127
  "@jridgewell/trace-mapping": "^0.3.31",
128
+ "@typescript-eslint/parser": "^8.69.0",
118
129
  "@vitejs/plugin-react": "^5.1.2",
119
130
  "esbuild": "^0.28.2",
131
+ "eslint": "^10.10.0",
132
+ "eslint-plugin-react-hooks": "^7.1.1",
120
133
  "express": "^5.2.1",
121
134
  "magic-string": "^0.30.17",
122
135
  "typescript": "^5.9.3",