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.
- package/README.md +21 -5
- package/dist/activity/game-loop.d.ts +16 -0
- package/dist/activity/game-loop.js +33 -0
- package/dist/activity/index.d.ts +12 -0
- package/dist/activity/index.js +6 -0
- package/dist/activity/lifecycle.d.ts +11 -0
- package/dist/activity/lifecycle.js +41 -0
- package/dist/activity/presence.d.ts +10 -0
- package/dist/activity/presence.js +15 -0
- package/dist/activity/query.d.ts +21 -0
- package/dist/activity/query.js +148 -0
- package/dist/activity/shared-state.d.ts +10 -0
- package/dist/activity/shared-state.js +100 -0
- package/dist/activity/storage.d.ts +16 -0
- package/dist/activity/storage.js +88 -0
- package/dist/api/runtime.d.ts +5 -2
- package/dist/api/runtime.js +53 -10
- package/dist/auth/client.d.ts +0 -1
- package/dist/auth/client.js +3 -5
- package/dist/auth/index.d.ts +0 -1
- package/dist/auth/index.js +0 -1
- package/dist/auth/server.d.ts +2 -1
- package/dist/auth/server.js +161 -16
- package/dist/auth/types.d.ts +5 -1
- package/dist/auth/types.js +0 -1
- package/dist/cli/index.d.ts +0 -1
- package/dist/cli/index.js +116 -19
- package/dist/cli/project-commands.d.ts +1 -5
- package/dist/cli/project-commands.js +14 -162
- package/dist/compiler/build.d.ts +10 -1
- package/dist/compiler/build.js +124 -16
- package/dist/compiler/bundle-report.d.ts +17 -0
- package/dist/compiler/bundle-report.js +60 -0
- package/dist/compiler/client-entry.d.ts +0 -1
- package/dist/compiler/client-entry.js +28 -4
- package/dist/compiler/client-tooling.d.ts +0 -1
- package/dist/compiler/client-tooling.js +8 -2
- package/dist/compiler/index.d.ts +3 -1
- package/dist/compiler/index.js +2 -1
- package/dist/compiler/scanner.d.ts +0 -1
- package/dist/compiler/scanner.js +59 -4
- package/dist/compiler/server-bundle.d.ts +1 -2
- package/dist/compiler/server-bundle.js +11 -2
- package/dist/compiler/type-generation.d.ts +0 -1
- package/dist/compiler/type-generation.js +2 -1
- package/dist/compiler/write-manifests.d.ts +0 -1
- package/dist/compiler/write-manifests.js +0 -1
- package/dist/config/defaults.d.ts +0 -1
- package/dist/config/defaults.js +14 -2
- package/dist/config/environment.d.ts +0 -1
- package/dist/config/environment.js +0 -1
- package/dist/config/index.d.ts +0 -1
- package/dist/config/index.js +0 -1
- package/dist/config/loader.d.ts +0 -1
- package/dist/config/loader.js +0 -1
- package/dist/config/project-root.d.ts +0 -1
- package/dist/config/project-root.js +0 -1
- package/dist/config/types.d.ts +25 -1
- package/dist/config/types.js +0 -1
- package/dist/discord/assets.d.ts +5 -0
- package/dist/discord/assets.js +29 -0
- package/dist/discord/data.d.ts +38 -2
- package/dist/discord/data.js +178 -11
- package/dist/discord/events.d.ts +28 -2
- package/dist/discord/events.js +109 -39
- package/dist/discord/index.d.ts +6 -5
- package/dist/discord/index.js +3 -3
- package/dist/discord/payload.d.ts +6 -0
- package/dist/discord/payload.js +5 -0
- package/dist/discord/runtime.d.ts +0 -1
- package/dist/discord/runtime.js +0 -1
- package/dist/discord/safe-area.d.ts +0 -1
- package/dist/discord/safe-area.js +0 -1
- package/dist/discord/testing.d.ts +0 -1
- package/dist/discord/testing.js +0 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +3 -1
- package/dist/lint/index.d.ts +6 -0
- package/dist/lint/index.js +71 -0
- package/dist/manifests/types.d.ts +11 -1
- package/dist/manifests/types.js +0 -1
- package/dist/metadata/index.d.ts +13 -0
- package/dist/metadata/index.js +4 -0
- package/dist/navigation/index.d.ts +3 -1
- package/dist/navigation/index.js +1 -1
- package/dist/navigation/link.d.ts +8 -0
- package/dist/navigation/link.js +38 -0
- package/dist/router/match.d.ts +0 -1
- package/dist/router/match.js +0 -1
- package/dist/runtime/client/dev-panel.d.ts +0 -1
- package/dist/runtime/client/dev-panel.js +722 -38
- package/dist/runtime/client/embed-router.d.ts +8 -1
- package/dist/runtime/client/embed-router.js +116 -62
- package/dist/runtime/client/files.d.ts +5 -1
- package/dist/runtime/client/files.js +0 -1
- package/dist/runtime/client/minimize-card.d.ts +0 -1
- package/dist/runtime/client/minimize-card.js +0 -1
- package/dist/runtime/client/minimize.d.ts +0 -1
- package/dist/runtime/client/minimize.js +0 -1
- package/dist/runtime/client/root.d.ts +5 -3
- package/dist/runtime/client/root.js +28 -3
- package/dist/runtime/index.d.ts +1 -2
- package/dist/runtime/index.js +0 -1
- package/dist/runtime/server/dev-server.d.ts +0 -1
- package/dist/runtime/server/dev-server.js +191 -30
- package/dist/runtime/server/diagnostics.d.ts +1 -1
- package/dist/runtime/server/diagnostics.js +5 -4
- package/dist/runtime/server/index.d.ts +0 -1
- package/dist/runtime/server/index.js +0 -1
- package/dist/runtime/server/production-server.d.ts +2 -1
- package/dist/runtime/server/production-server.js +145 -25
- package/dist/security/discord.d.ts +0 -1
- package/dist/security/discord.js +0 -1
- package/dist/security/index.d.ts +0 -1
- package/dist/security/index.js +0 -1
- package/dist/security/secret-scan.d.ts +0 -1
- package/dist/security/secret-scan.js +0 -1
- package/dist/server/discord-rest.d.ts +42 -7
- package/dist/server/discord-rest.js +135 -18
- package/dist/server/index.d.ts +7 -2
- package/dist/server/index.js +3 -1
- package/dist/server/instrumentation.d.ts +16 -0
- package/dist/server/instrumentation.js +3 -0
- package/dist/server/proxy.d.ts +21 -0
- package/dist/server/proxy.js +76 -0
- package/dist/server/session.d.ts +0 -1
- package/dist/server/session.js +0 -1
- package/dist/server/types.d.ts +0 -1
- package/dist/server/types.js +0 -1
- package/dist/sessions/cookies.d.ts +0 -1
- package/dist/sessions/cookies.js +0 -1
- package/dist/sessions/crypto.d.ts +0 -1
- package/dist/sessions/crypto.js +0 -1
- package/dist/sessions/data-store.d.ts +18 -0
- package/dist/sessions/data-store.js +45 -0
- package/dist/shared/errors.d.ts +0 -1
- package/dist/shared/errors.js +0 -1
- package/dist/testing/index.d.ts +0 -1
- package/dist/testing/index.js +2 -2
- package/dist/version.d.ts +1 -2
- package/dist/version.js +1 -2
- package/dist/ws/client.d.ts +0 -1
- package/dist/ws/client.js +0 -1
- package/dist/ws/index.d.ts +3 -2
- package/dist/ws/index.js +1 -1
- package/dist/ws/server.d.ts +5 -3
- package/dist/ws/server.js +65 -19
- package/dist/ws/shared-state.d.ts +13 -0
- package/dist/ws/shared-state.js +137 -0
- package/package.json +16 -3
|
@@ -5,9 +5,11 @@ import { pathToFileURL } from "node:url";
|
|
|
5
5
|
import express from "express";
|
|
6
6
|
import { createApiMiddleware } from "../../api/runtime.js";
|
|
7
7
|
import { createLudicordAuthRouter } from "../../auth/server.js";
|
|
8
|
+
import { LUDICORD_BUILD_SCHEMA_VERSION, } from "../../compiler/build.js";
|
|
8
9
|
import { attachWebSocketRuntime, } from "../../ws/server.js";
|
|
9
10
|
import { LUDICORD_VERSION } from "../../version.js";
|
|
10
11
|
import { loadProjectEnvironment } from "../../config/environment.js";
|
|
12
|
+
import { createProxyMiddleware } from "../../server/proxy.js";
|
|
11
13
|
import { redact } from "./diagnostics.js";
|
|
12
14
|
function readJson(file) {
|
|
13
15
|
return JSON.parse(readFileSync(file, "utf8"));
|
|
@@ -19,8 +21,8 @@ function loadProductionBuild(projectRoot) {
|
|
|
19
21
|
throw new Error("LUDICORD3001: Production build not found.\n\nRun:\n ludicord build");
|
|
20
22
|
}
|
|
21
23
|
const metadata = readJson(buildFile);
|
|
22
|
-
if (metadata.
|
|
23
|
-
throw new Error(`LUDICORD3002: Build
|
|
24
|
+
if (metadata.buildSchemaVersion !== LUDICORD_BUILD_SCHEMA_VERSION) {
|
|
25
|
+
throw new Error(`LUDICORD3002: Build schema ${String(metadata.buildSchemaVersion ?? "missing")} is incompatible with schema ${LUDICORD_BUILD_SCHEMA_VERSION}. Run \`ludicord build\` again.`);
|
|
24
26
|
}
|
|
25
27
|
return {
|
|
26
28
|
output,
|
|
@@ -54,18 +56,83 @@ export async function createLudicordProductionServer(options) {
|
|
|
54
56
|
const app = express();
|
|
55
57
|
app.set("env", "production");
|
|
56
58
|
const httpServer = createServer(app);
|
|
59
|
+
const sockets = new Set();
|
|
60
|
+
let draining = false;
|
|
61
|
+
let closePromise = null;
|
|
62
|
+
httpServer.on("connection", (socket) => {
|
|
63
|
+
sockets.add(socket);
|
|
64
|
+
socket.once("close", () => sockets.delete(socket));
|
|
65
|
+
});
|
|
66
|
+
app.use((request, response, next) => {
|
|
67
|
+
const finish = () => {
|
|
68
|
+
response.off("finish", finish);
|
|
69
|
+
response.off("close", finish);
|
|
70
|
+
if (draining && !request.socket.destroyed)
|
|
71
|
+
request.socket.end();
|
|
72
|
+
};
|
|
73
|
+
response.once("finish", finish);
|
|
74
|
+
response.once("close", finish);
|
|
75
|
+
if (!draining) {
|
|
76
|
+
next();
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
response.setHeader("Connection", "close");
|
|
80
|
+
response.status(503).json({
|
|
81
|
+
error: "LUDICORD_SHUTTING_DOWN",
|
|
82
|
+
message: "The Ludicord server is shutting down. Please retry shortly.",
|
|
83
|
+
});
|
|
84
|
+
});
|
|
57
85
|
const apiLoader = bundleLoader(output, metadata.api);
|
|
58
86
|
const wsLoader = bundleLoader(output, metadata.websocket);
|
|
87
|
+
let instrumentationCleanup;
|
|
88
|
+
let instrumentation;
|
|
89
|
+
const reportedRequestErrors = new WeakSet();
|
|
90
|
+
const reportRequestError = async (error, source, file, request) => {
|
|
91
|
+
if (error !== null && typeof error === "object") {
|
|
92
|
+
if (reportedRequestErrors.has(error))
|
|
93
|
+
return;
|
|
94
|
+
reportedRequestErrors.add(error);
|
|
95
|
+
}
|
|
96
|
+
console.error(redact(error instanceof Error ? error.stack ?? error.message : String(error)));
|
|
97
|
+
const notify = instrumentation?.onRequestError;
|
|
98
|
+
if (notify === undefined)
|
|
99
|
+
return;
|
|
100
|
+
try {
|
|
101
|
+
await notify(error, {
|
|
102
|
+
environment: "production",
|
|
103
|
+
projectRoot,
|
|
104
|
+
source,
|
|
105
|
+
...(file === undefined ? {} : { file }),
|
|
106
|
+
...(request === undefined ? {} : request),
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
catch (notificationError) {
|
|
110
|
+
console.error(redact(notificationError instanceof Error ? notificationError.stack ?? notificationError.message : String(notificationError)));
|
|
111
|
+
}
|
|
112
|
+
};
|
|
59
113
|
app.use("/_ludicord/auth", createLudicordAuthRouter({
|
|
60
114
|
...(metadata.config.discord.clientId === undefined
|
|
61
115
|
? {}
|
|
62
116
|
: { clientId: metadata.config.discord.clientId }),
|
|
63
117
|
production: true,
|
|
64
118
|
activityInstanceVerification: metadata.config.discord.activityInstanceVerification,
|
|
119
|
+
...(options.sessionDataStore === undefined
|
|
120
|
+
? {}
|
|
121
|
+
: { sessionDataStore: options.sessionDataStore }),
|
|
65
122
|
}));
|
|
66
123
|
app.get("/_ludicord/health", (_request, response) => {
|
|
67
124
|
response.json({ ok: true, version: LUDICORD_VERSION });
|
|
68
125
|
});
|
|
126
|
+
if (metadata.proxy !== undefined) {
|
|
127
|
+
const proxyLoader = bundleLoader(output, [metadata.proxy]);
|
|
128
|
+
app.use(createProxyMiddleware({
|
|
129
|
+
projectRoot,
|
|
130
|
+
environment: "production",
|
|
131
|
+
source: path.join(projectRoot, metadata.proxy.source),
|
|
132
|
+
loadModule: proxyLoader,
|
|
133
|
+
onError: (error, file, request) => reportRequestError(error, "proxy", file, request),
|
|
134
|
+
}));
|
|
135
|
+
}
|
|
69
136
|
app.use(createApiMiddleware({
|
|
70
137
|
projectRoot,
|
|
71
138
|
getRoutes: () => manifests.api,
|
|
@@ -75,7 +142,9 @@ export async function createLudicordProductionServer(options) {
|
|
|
75
142
|
: { sessionSecret: process.env.LUDICORD_SESSION_SECRET }),
|
|
76
143
|
proxyVerification: metadata.config.discord.proxyVerification,
|
|
77
144
|
bodyLimit: metadata.config.server.limits.body,
|
|
145
|
+
requestTimeout: metadata.config.server.requestTimeout,
|
|
78
146
|
allowDevelopmentSessions: false,
|
|
147
|
+
onError: (error, file, request) => reportRequestError(error, "api", file, request),
|
|
79
148
|
...(process.env.LUDICORD_DISCORD_PUBLIC_KEY === undefined
|
|
80
149
|
? {}
|
|
81
150
|
: { discordPublicKey: process.env.LUDICORD_DISCORD_PUBLIC_KEY }),
|
|
@@ -90,9 +159,10 @@ export async function createLudicordProductionServer(options) {
|
|
|
90
159
|
heartbeatInterval: metadata.config.websocket.heartbeatInterval,
|
|
91
160
|
maxPayload: metadata.config.websocket.maxPayload,
|
|
92
161
|
compression: metadata.config.websocket.compression,
|
|
162
|
+
maxMessagesPerSecond: metadata.config.websocket.maxMessagesPerSecond,
|
|
93
163
|
enabled: metadata.config.websocket.enabled,
|
|
94
164
|
allowDevelopmentSessions: false,
|
|
95
|
-
onError: (error) =>
|
|
165
|
+
onError: (error, file) => { void reportRequestError(error, "websocket", file); },
|
|
96
166
|
});
|
|
97
167
|
const clientDirectory = path.join(output, "client");
|
|
98
168
|
const indexHtml = readFileSync(path.join(clientDirectory, "index.html"), "utf8");
|
|
@@ -100,21 +170,43 @@ export async function createLudicordProductionServer(options) {
|
|
|
100
170
|
app.get("/", (_request, response) => {
|
|
101
171
|
response.status(200).type("html").send(indexHtml);
|
|
102
172
|
});
|
|
103
|
-
app.use((error, _request, response, _next) => {
|
|
104
|
-
|
|
173
|
+
app.use(async (error, _request, response, _next) => {
|
|
174
|
+
await reportRequestError(error, "server", undefined, {
|
|
175
|
+
method: _request.method,
|
|
176
|
+
url: _request.originalUrl,
|
|
177
|
+
});
|
|
105
178
|
if (!response.headersSent)
|
|
106
179
|
response.status(500).json({ error: "LUDICORD_INTERNAL_ERROR", message: "An internal error occurred. Please try again." });
|
|
107
180
|
});
|
|
108
181
|
const portOption = options.port ?? metadata.config.server.port;
|
|
109
182
|
const host = options.host ?? metadata.config.server.host;
|
|
110
|
-
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
183
|
+
if (metadata.instrumentation !== undefined) {
|
|
184
|
+
const loadInstrumentation = bundleLoader(output, [metadata.instrumentation]);
|
|
185
|
+
const loaded = await loadInstrumentation(path.join(projectRoot, metadata.instrumentation.source));
|
|
186
|
+
const candidate = loaded.default ?? (typeof loaded.register === "function" ? loaded : undefined);
|
|
187
|
+
if (candidate === undefined) {
|
|
188
|
+
throw new Error("LUDICORD3004: app/instrumentation.ts must export a default instrumentation object with register().");
|
|
189
|
+
}
|
|
190
|
+
instrumentation = candidate;
|
|
191
|
+
const cleanup = await candidate.register({ environment: "production", projectRoot });
|
|
192
|
+
if (typeof cleanup === "function")
|
|
193
|
+
instrumentationCleanup = cleanup;
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
await new Promise((resolve, reject) => {
|
|
197
|
+
const error = (cause) => reject(cause);
|
|
198
|
+
httpServer.once("error", error);
|
|
199
|
+
httpServer.listen(portOption, host, () => {
|
|
200
|
+
httpServer.off("error", error);
|
|
201
|
+
resolve();
|
|
202
|
+
});
|
|
116
203
|
});
|
|
117
|
-
}
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
await websocket.close({ gracePeriodMs: 0 });
|
|
207
|
+
await instrumentationCleanup?.();
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
118
210
|
const address = httpServer.address();
|
|
119
211
|
const port = address.port;
|
|
120
212
|
const displayHost = host === "0.0.0.0" || host === "::" ? "localhost" : host;
|
|
@@ -142,19 +234,47 @@ WebSocket: ws://${displayHost}:${port}/ws/*
|
|
|
142
234
|
|
|
143
235
|
Ready`;
|
|
144
236
|
},
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
237
|
+
close() {
|
|
238
|
+
if (closePromise !== null)
|
|
239
|
+
return closePromise;
|
|
240
|
+
draining = true;
|
|
241
|
+
closePromise = (async () => {
|
|
242
|
+
try {
|
|
243
|
+
const shutdownTimeout = metadata.config.server.shutdownTimeout;
|
|
244
|
+
const closed = new Promise((resolve, reject) => {
|
|
245
|
+
httpServer.close((error) => {
|
|
246
|
+
if (error === undefined)
|
|
247
|
+
resolve();
|
|
248
|
+
else
|
|
249
|
+
reject(error);
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
httpServer.closeIdleConnections();
|
|
253
|
+
const websocketClosed = websocket.close({
|
|
254
|
+
gracePeriodMs: Math.min(1_000, shutdownTimeout),
|
|
255
|
+
});
|
|
256
|
+
let timeout;
|
|
257
|
+
const graceful = Promise.all([closed, websocketClosed]);
|
|
258
|
+
const completed = await Promise.race([
|
|
259
|
+
graceful.then(() => true),
|
|
260
|
+
new Promise((resolve) => {
|
|
261
|
+
timeout = setTimeout(() => resolve(false), shutdownTimeout);
|
|
262
|
+
}),
|
|
263
|
+
]);
|
|
264
|
+
if (timeout !== undefined)
|
|
265
|
+
clearTimeout(timeout);
|
|
266
|
+
if (!completed) {
|
|
267
|
+
httpServer.closeAllConnections();
|
|
268
|
+
for (const socket of sockets)
|
|
269
|
+
socket.destroy();
|
|
270
|
+
await Promise.allSettled([closed, websocketClosed]);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
finally {
|
|
274
|
+
await instrumentationCleanup?.();
|
|
275
|
+
}
|
|
276
|
+
})();
|
|
277
|
+
return closePromise;
|
|
157
278
|
},
|
|
158
279
|
};
|
|
159
280
|
}
|
|
160
|
-
//# sourceMappingURL=production-server.js.map
|
|
@@ -41,4 +41,3 @@ export interface DiscordActivityInstance {
|
|
|
41
41
|
}
|
|
42
42
|
export declare function verifyDiscordActivityInstance(options: VerifyDiscordActivityInstanceOptions): Promise<DiscordActivityInstanceVerificationResult>;
|
|
43
43
|
export declare function resetDiscordSecurityCacheForTesting(): void;
|
|
44
|
-
//# sourceMappingURL=discord.d.ts.map
|
package/dist/security/discord.js
CHANGED
package/dist/security/index.d.ts
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
1
|
export { resetDiscordSecurityCacheForTesting, verifyDiscordActivityInstance, verifyDiscordProxyRequest, } from "./discord.js";
|
|
2
2
|
export type { DiscordActivityInstanceVerificationResult, DiscordProxyVerificationResult, VerifyDiscordActivityInstanceOptions, VerifyDiscordProxyRequestOptions, } from "./discord.js";
|
|
3
|
-
//# sourceMappingURL=index.d.ts.map
|
package/dist/security/index.js
CHANGED
|
@@ -9,11 +9,20 @@ export interface DiscordRestMember {
|
|
|
9
9
|
readonly username: string;
|
|
10
10
|
readonly global_name?: string | null;
|
|
11
11
|
readonly avatar?: string | null;
|
|
12
|
+
readonly [key: string]: unknown;
|
|
12
13
|
};
|
|
13
14
|
readonly nick?: string | null;
|
|
14
15
|
readonly avatar?: string | null;
|
|
15
16
|
readonly roles: readonly string[];
|
|
16
17
|
readonly joined_at?: string;
|
|
18
|
+
readonly [key: string]: unknown;
|
|
19
|
+
}
|
|
20
|
+
export interface DiscordRestUser {
|
|
21
|
+
readonly id: string;
|
|
22
|
+
readonly username: string;
|
|
23
|
+
readonly global_name?: string | null;
|
|
24
|
+
readonly avatar?: string | null;
|
|
25
|
+
readonly [key: string]: unknown;
|
|
17
26
|
}
|
|
18
27
|
export interface DiscordRestGuild {
|
|
19
28
|
readonly id: string;
|
|
@@ -22,6 +31,7 @@ export interface DiscordRestGuild {
|
|
|
22
31
|
readonly description?: string | null;
|
|
23
32
|
readonly approximate_member_count?: number;
|
|
24
33
|
readonly features?: readonly string[];
|
|
34
|
+
readonly [key: string]: unknown;
|
|
25
35
|
}
|
|
26
36
|
export interface DiscordRestChannel {
|
|
27
37
|
readonly id: string;
|
|
@@ -29,17 +39,42 @@ export interface DiscordRestChannel {
|
|
|
29
39
|
readonly name?: string;
|
|
30
40
|
readonly guild_id?: string;
|
|
31
41
|
readonly topic?: string | null;
|
|
42
|
+
readonly [key: string]: unknown;
|
|
32
43
|
}
|
|
33
|
-
|
|
34
|
-
|
|
44
|
+
export interface DiscordRestRole {
|
|
45
|
+
readonly id: string;
|
|
46
|
+
readonly name: string;
|
|
47
|
+
readonly permissions?: string;
|
|
48
|
+
readonly position?: number;
|
|
49
|
+
readonly color?: number;
|
|
50
|
+
readonly managed?: boolean;
|
|
51
|
+
readonly [key: string]: unknown;
|
|
52
|
+
}
|
|
53
|
+
export interface DiscordRestRequestOptions {
|
|
54
|
+
readonly signal?: AbortSignal;
|
|
55
|
+
readonly cacheTtlMs?: number;
|
|
56
|
+
}
|
|
57
|
+
export interface DiscordRestOptions {
|
|
35
58
|
readonly botToken?: string;
|
|
36
59
|
readonly fetch?: typeof fetch;
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
60
|
+
readonly timeoutMs?: number;
|
|
61
|
+
readonly cacheTtlMs?: number;
|
|
62
|
+
readonly maxCacheEntries?: number;
|
|
63
|
+
readonly maxRetries?: number;
|
|
64
|
+
}
|
|
65
|
+
/** REST only: no Gateway connection, bot runtime, or client-side token exposure. */
|
|
66
|
+
export declare function createDiscordRest(options?: DiscordRestOptions): {
|
|
67
|
+
/** Read any Discord API v10 resource from server code. Mutating methods are intentionally not exposed. */
|
|
68
|
+
get: <T = unknown>(resource: string, requestOptions?: DiscordRestRequestOptions) => Promise<T>;
|
|
69
|
+
getUser: (userId: string, requestOptions?: DiscordRestRequestOptions) => Promise<DiscordRestUser>;
|
|
70
|
+
getGuild: (guildId: string, requestOptions?: DiscordRestRequestOptions) => Promise<DiscordRestGuild>;
|
|
71
|
+
getChannel: (channelId: string, requestOptions?: DiscordRestRequestOptions) => Promise<DiscordRestChannel>;
|
|
72
|
+
getGuildMember: (guildId: string, userId: string, requestOptions?: DiscordRestRequestOptions) => Promise<DiscordRestMember>;
|
|
73
|
+
listGuildChannels: (guildId: string, requestOptions?: DiscordRestRequestOptions) => Promise<DiscordRestChannel[]>;
|
|
74
|
+
listGuildRoles: (guildId: string, requestOptions?: DiscordRestRequestOptions) => Promise<DiscordRestRole[]>;
|
|
40
75
|
listGuildMembers(guildId: string, pagination?: {
|
|
41
76
|
readonly limit?: number;
|
|
42
77
|
readonly after?: string;
|
|
43
|
-
}): Promise<DiscordRestMember[]>;
|
|
78
|
+
}, requestOptions?: DiscordRestRequestOptions): Promise<DiscordRestMember[]>;
|
|
79
|
+
clearCache(resource?: string): void;
|
|
44
80
|
};
|
|
45
|
-
//# sourceMappingURL=discord-rest.d.ts.map
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
1
2
|
export class LudicordDiscordRestError extends Error {
|
|
2
3
|
status;
|
|
3
4
|
retryAfterMs;
|
|
@@ -8,39 +9,155 @@ export class LudicordDiscordRestError extends Error {
|
|
|
8
9
|
this.name = "LudicordDiscordRestError";
|
|
9
10
|
}
|
|
10
11
|
}
|
|
12
|
+
const DISCORD_API = "https://discord.com/api/v10";
|
|
13
|
+
function integer(value, minimum, maximum, name) {
|
|
14
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
|
|
15
|
+
throw new Error(`LUDICORD6101: ${name} must be an integer between ${minimum} and ${maximum}.`);
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
function validateResource(resource) {
|
|
20
|
+
const pathname = resource.split(/[?#]/, 1)[0] ?? "";
|
|
21
|
+
if (!resource.startsWith("/") ||
|
|
22
|
+
resource.startsWith("//") ||
|
|
23
|
+
/[\\\r\n]/.test(resource) ||
|
|
24
|
+
pathname.split("/").some((segment) => segment === "." || segment === "..")) {
|
|
25
|
+
throw new LudicordDiscordRestError(400, "Invalid Discord API resource path.");
|
|
26
|
+
}
|
|
27
|
+
return resource;
|
|
28
|
+
}
|
|
29
|
+
function discordId(value) {
|
|
30
|
+
if (!/^\d+$/.test(value)) {
|
|
31
|
+
throw new LudicordDiscordRestError(400, "Invalid Discord ID.");
|
|
32
|
+
}
|
|
33
|
+
return encodeURIComponent(value);
|
|
34
|
+
}
|
|
35
|
+
function retryDelay(response, body) {
|
|
36
|
+
const seconds = Number(response.headers.get("retry-after") ?? body.retry_after ?? 1);
|
|
37
|
+
return Math.max(1_000, Number.isFinite(seconds) ? Math.ceil(seconds * 1_000) : 1_000);
|
|
38
|
+
}
|
|
39
|
+
async function abortableDelay(milliseconds, signal) {
|
|
40
|
+
await delay(milliseconds, undefined, signal === undefined ? {} : { signal });
|
|
41
|
+
}
|
|
11
42
|
/** REST only: no Gateway connection, bot runtime, or client-side token exposure. */
|
|
12
43
|
export function createDiscordRest(options = {}) {
|
|
13
44
|
const token = options.botToken ?? process.env.LUDICORD_DISCORD_BOT_TOKEN;
|
|
14
45
|
const fetchImplementation = options.fetch ?? globalThis.fetch;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
46
|
+
const timeoutMs = integer(options.timeoutMs ?? 10_000, 100, 120_000, "Discord REST timeoutMs");
|
|
47
|
+
const defaultCacheTtlMs = integer(options.cacheTtlMs ?? 5_000, 0, 300_000, "Discord REST cacheTtlMs");
|
|
48
|
+
const maxCacheEntries = integer(options.maxCacheEntries ?? 500, 1, 10_000, "Discord REST maxCacheEntries");
|
|
49
|
+
const maxRetries = integer(options.maxRetries ?? 1, 0, 3, "Discord REST maxRetries");
|
|
50
|
+
const cache = new Map();
|
|
51
|
+
const inFlight = new Map();
|
|
52
|
+
const bucketByResource = new Map();
|
|
53
|
+
const limitedUntilByBucket = new Map();
|
|
54
|
+
let globalLimitedUntil = 0;
|
|
55
|
+
const pruneCache = () => {
|
|
56
|
+
const current = Date.now();
|
|
57
|
+
for (const [key, entry] of cache) {
|
|
58
|
+
if (entry.expiresAt <= current)
|
|
59
|
+
cache.delete(key);
|
|
60
|
+
}
|
|
61
|
+
while (cache.size >= maxCacheEntries) {
|
|
62
|
+
const oldest = cache.keys().next().value;
|
|
63
|
+
if (oldest === undefined)
|
|
64
|
+
break;
|
|
65
|
+
cache.delete(oldest);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
async function request(resource, requestOptions, attempt) {
|
|
69
|
+
const bucket = bucketByResource.get(resource);
|
|
70
|
+
const limitedUntil = Math.max(globalLimitedUntil, bucket === undefined ? 0 : limitedUntilByBucket.get(bucket) ?? 0);
|
|
71
|
+
if (attempt === 0 && limitedUntil > Date.now()) {
|
|
20
72
|
throw new LudicordDiscordRestError(429, "Discord rate limit reached. Please retry later.", limitedUntil - Date.now());
|
|
21
|
-
|
|
73
|
+
}
|
|
74
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
75
|
+
const signal = requestOptions.signal === undefined
|
|
76
|
+
? timeoutSignal
|
|
77
|
+
: AbortSignal.any([requestOptions.signal, timeoutSignal]);
|
|
78
|
+
const response = await fetchImplementation(DISCORD_API + resource, {
|
|
79
|
+
headers: { authorization: "Bot " + token },
|
|
80
|
+
signal,
|
|
81
|
+
});
|
|
82
|
+
const responseBucket = response.headers.get("x-ratelimit-bucket") ?? bucket;
|
|
83
|
+
if (responseBucket !== undefined)
|
|
84
|
+
bucketByResource.set(resource, responseBucket);
|
|
85
|
+
const resetAfter = Number(response.headers.get("x-ratelimit-reset-after"));
|
|
86
|
+
if (responseBucket !== undefined && response.headers.get("x-ratelimit-remaining") === "0" && Number.isFinite(resetAfter)) {
|
|
87
|
+
limitedUntilByBucket.set(responseBucket, Date.now() + Math.max(0, Math.ceil(resetAfter * 1_000)));
|
|
88
|
+
}
|
|
22
89
|
if (response.status === 429) {
|
|
23
90
|
const data = await response.json().catch(() => ({}));
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
91
|
+
const retryAfterMs = retryDelay(response, data);
|
|
92
|
+
if (data.global === true)
|
|
93
|
+
globalLimitedUntil = Date.now() + retryAfterMs;
|
|
94
|
+
else if (responseBucket !== undefined)
|
|
95
|
+
limitedUntilByBucket.set(responseBucket, Date.now() + retryAfterMs);
|
|
96
|
+
if (attempt < maxRetries && retryAfterMs <= 5_000) {
|
|
97
|
+
await abortableDelay(retryAfterMs, requestOptions.signal);
|
|
98
|
+
return request(resource, requestOptions, attempt + 1);
|
|
99
|
+
}
|
|
27
100
|
throw new LudicordDiscordRestError(429, "Discord rate limit reached. Please retry later.", retryAfterMs);
|
|
28
101
|
}
|
|
29
|
-
if (!response.ok)
|
|
30
|
-
throw new LudicordDiscordRestError(response.status, response.status === 403
|
|
102
|
+
if (!response.ok) {
|
|
103
|
+
throw new LudicordDiscordRestError(response.status, response.status === 403
|
|
104
|
+
? "Discord denied access. Check the application's guild access, permissions, and privileged intents."
|
|
105
|
+
: response.status === 401
|
|
106
|
+
? "Discord rejected the server credential. Check LUDICORD_DISCORD_BOT_TOKEN."
|
|
107
|
+
: "Discord could not provide the requested server data.");
|
|
108
|
+
}
|
|
31
109
|
return response.json();
|
|
32
110
|
}
|
|
33
|
-
|
|
34
|
-
|
|
111
|
+
async function get(resourceValue, requestOptions = {}) {
|
|
112
|
+
if (!token) {
|
|
113
|
+
throw new LudicordDiscordRestError(501, "Discord server data requires LUDICORD_DISCORD_BOT_TOKEN. The token stays server-only.");
|
|
114
|
+
}
|
|
115
|
+
const resource = validateResource(resourceValue);
|
|
116
|
+
const cacheTtlMs = requestOptions.cacheTtlMs ?? defaultCacheTtlMs;
|
|
117
|
+
integer(cacheTtlMs, 0, 300_000, "Discord REST request cacheTtlMs");
|
|
118
|
+
const cached = cache.get(resource);
|
|
119
|
+
if (cached !== undefined && cached.expiresAt > Date.now())
|
|
120
|
+
return cached.data;
|
|
121
|
+
const shared = requestOptions.signal === undefined ? inFlight.get(resource) : undefined;
|
|
122
|
+
if (shared !== undefined)
|
|
123
|
+
return shared;
|
|
124
|
+
const operation = request(resource, requestOptions, 0).then((data) => {
|
|
125
|
+
if (cacheTtlMs > 0) {
|
|
126
|
+
pruneCache();
|
|
127
|
+
cache.set(resource, { data, expiresAt: Date.now() + cacheTtlMs });
|
|
128
|
+
}
|
|
129
|
+
return data;
|
|
130
|
+
});
|
|
131
|
+
if (requestOptions.signal === undefined)
|
|
132
|
+
inFlight.set(resource, operation);
|
|
133
|
+
try {
|
|
134
|
+
return await operation;
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
if (inFlight.get(resource) === operation)
|
|
138
|
+
inFlight.delete(resource);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
35
141
|
return {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
142
|
+
/** Read any Discord API v10 resource from server code. Mutating methods are intentionally not exposed. */
|
|
143
|
+
get: (resource, requestOptions) => get(resource, requestOptions),
|
|
144
|
+
getUser: (userId, requestOptions) => get(`/users/${discordId(userId)}`, requestOptions),
|
|
145
|
+
getGuild: (guildId, requestOptions) => get(`/guilds/${discordId(guildId)}?with_counts=true`, requestOptions),
|
|
146
|
+
getChannel: (channelId, requestOptions) => get(`/channels/${discordId(channelId)}`, requestOptions),
|
|
147
|
+
getGuildMember: (guildId, userId, requestOptions) => get(`/guilds/${discordId(guildId)}/members/${discordId(userId)}`, requestOptions),
|
|
148
|
+
listGuildChannels: (guildId, requestOptions) => get(`/guilds/${discordId(guildId)}/channels`, requestOptions),
|
|
149
|
+
listGuildRoles: (guildId, requestOptions) => get(`/guilds/${discordId(guildId)}/roles`, requestOptions),
|
|
150
|
+
listGuildMembers(guildId, pagination = {}, requestOptions) {
|
|
39
151
|
const limit = Math.min(1000, Math.max(1, Math.floor(pagination.limit ?? 100)));
|
|
40
152
|
if (!Number.isFinite(limit))
|
|
41
153
|
throw new LudicordDiscordRestError(400, "Invalid member page size.");
|
|
42
|
-
return get(`/guilds/${
|
|
154
|
+
return get(`/guilds/${discordId(guildId)}/members?limit=${limit}${pagination.after ? `&after=${discordId(pagination.after)}` : ""}`, requestOptions);
|
|
155
|
+
},
|
|
156
|
+
clearCache(resource) {
|
|
157
|
+
if (resource === undefined)
|
|
158
|
+
cache.clear();
|
|
159
|
+
else
|
|
160
|
+
cache.delete(validateResource(resource));
|
|
43
161
|
},
|
|
44
162
|
};
|
|
45
163
|
}
|
|
46
|
-
//# sourceMappingURL=discord-rest.js.map
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
export { getLudicordSession, requireLudicordSession, } from "./session.js";
|
|
2
2
|
export type { LudicordRequest, LudicordRequestVerification, RouteContext, } from "./types.js";
|
|
3
3
|
export { createDiscordRest, LudicordDiscordRestError } from "./discord-rest.js";
|
|
4
|
-
export type {
|
|
5
|
-
|
|
4
|
+
export type { DiscordRestChannel, DiscordRestGuild, DiscordRestMember, DiscordRestOptions, DiscordRestRequestOptions, DiscordRestRole, DiscordRestUser, } from "./discord-rest.js";
|
|
5
|
+
export { defineInstrumentation } from "./instrumentation.js";
|
|
6
|
+
export type { LudicordInstrumentation, LudicordInstrumentationCleanup, LudicordInstrumentationContext, LudicordRequestErrorContext, } from "./instrumentation.js";
|
|
7
|
+
export { defineProxy } from "./proxy.js";
|
|
8
|
+
export type { LudicordProxy, LudicordProxyContext } from "./proxy.js";
|
|
9
|
+
export { createMemorySessionDataStore } from "../sessions/data-store.js";
|
|
10
|
+
export type { LudicordExtendedSessionData, LudicordSessionDataStore } from "../sessions/data-store.js";
|
package/dist/server/index.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export { getLudicordSession, requireLudicordSession, } from "./session.js";
|
|
2
2
|
export { createDiscordRest, LudicordDiscordRestError } from "./discord-rest.js";
|
|
3
|
-
|
|
3
|
+
export { defineInstrumentation } from "./instrumentation.js";
|
|
4
|
+
export { defineProxy } from "./proxy.js";
|
|
5
|
+
export { createMemorySessionDataStore } from "../sessions/data-store.js";
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export interface LudicordInstrumentationContext {
|
|
2
|
+
readonly environment: "development" | "production";
|
|
3
|
+
readonly projectRoot: string;
|
|
4
|
+
}
|
|
5
|
+
export type LudicordInstrumentationCleanup = () => void | Promise<void>;
|
|
6
|
+
export interface LudicordRequestErrorContext extends LudicordInstrumentationContext {
|
|
7
|
+
readonly source: "api" | "websocket" | "proxy" | "server";
|
|
8
|
+
readonly file?: string;
|
|
9
|
+
readonly method?: string;
|
|
10
|
+
readonly url?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface LudicordInstrumentation {
|
|
13
|
+
register(context: LudicordInstrumentationContext): void | LudicordInstrumentationCleanup | Promise<void | LudicordInstrumentationCleanup>;
|
|
14
|
+
onRequestError?(error: unknown, context: LudicordRequestErrorContext): void | Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
export declare function defineInstrumentation<const TInstrumentation extends LudicordInstrumentation>(instrumentation: TInstrumentation): TInstrumentation;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { RequestHandler } from "express";
|
|
2
|
+
export interface LudicordProxyContext {
|
|
3
|
+
readonly environment: "development" | "production";
|
|
4
|
+
readonly projectRoot: string;
|
|
5
|
+
}
|
|
6
|
+
export type LudicordProxy = (request: Request, context: LudicordProxyContext) => void | Response | Promise<void | Response>;
|
|
7
|
+
export interface LudicordProxyModule {
|
|
8
|
+
readonly default?: LudicordProxy;
|
|
9
|
+
readonly proxy?: LudicordProxy;
|
|
10
|
+
}
|
|
11
|
+
export declare function defineProxy<const TProxy extends LudicordProxy>(proxy: TProxy): TProxy;
|
|
12
|
+
interface ProxyRuntimeOptions extends LudicordProxyContext {
|
|
13
|
+
readonly source: string | (() => string | undefined);
|
|
14
|
+
readonly loadModule: (absoluteFile: string) => Promise<LudicordProxyModule>;
|
|
15
|
+
readonly onError?: (error: unknown, file: string, request: {
|
|
16
|
+
readonly method: string;
|
|
17
|
+
readonly url: string;
|
|
18
|
+
}) => void | Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
export declare function createProxyMiddleware(options: ProxyRuntimeOptions): RequestHandler;
|
|
21
|
+
export {};
|