ludicord 2.2.1 → 2.2.4

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 (166) hide show
  1. package/README.md +8 -6
  2. package/bin/ludicord.js +0 -0
  3. package/dist/api/runtime.d.ts +4 -0
  4. package/dist/api/runtime.js +61 -10
  5. package/dist/auth/client.d.ts +10 -0
  6. package/dist/auth/client.js +58 -8
  7. package/dist/auth/index.d.ts +1 -1
  8. package/dist/auth/index.js +1 -1
  9. package/dist/auth/server.js +154 -34
  10. package/dist/auth/types.d.ts +5 -0
  11. package/dist/cli/index.js +14 -13
  12. package/dist/cli/project-commands.js +49 -34
  13. package/dist/compiler/build.js +37 -128
  14. package/dist/compiler/client-entry.d.ts +4 -0
  15. package/dist/compiler/client-entry.js +35 -0
  16. package/dist/compiler/client-tooling.d.ts +5 -0
  17. package/dist/compiler/client-tooling.js +97 -0
  18. package/dist/compiler/scanner.js +8 -0
  19. package/dist/compiler/server-bundle.d.ts +11 -0
  20. package/dist/compiler/server-bundle.js +31 -0
  21. package/dist/compiler/type-generation.js +11 -2
  22. package/dist/config/defaults.js +28 -2
  23. package/dist/config/environment.d.ts +2 -0
  24. package/dist/config/environment.js +18 -0
  25. package/dist/discord/data.d.ts +21 -0
  26. package/dist/discord/data.js +91 -0
  27. package/dist/discord/events.d.ts +42 -4
  28. package/dist/discord/events.js +120 -41
  29. package/dist/discord/index.d.ts +4 -2
  30. package/dist/discord/index.js +2 -1
  31. package/dist/discord/runtime.d.ts +2 -2
  32. package/dist/discord/runtime.js +9 -13
  33. package/dist/discord/testing.d.ts +1 -0
  34. package/dist/discord/testing.js +10 -0
  35. package/dist/manifests/types.d.ts +4 -0
  36. package/dist/navigation/index.d.ts +2 -0
  37. package/dist/runtime/client/dev-panel.d.ts +2 -0
  38. package/dist/runtime/client/dev-panel.js +63 -0
  39. package/dist/runtime/client/embed-router.d.ts +4 -1
  40. package/dist/runtime/client/embed-router.js +69 -17
  41. package/dist/runtime/client/files.d.ts +23 -0
  42. package/dist/runtime/client/files.js +12 -0
  43. package/dist/runtime/client/minimize-card.js +4 -4
  44. package/dist/runtime/client/minimize.d.ts +1 -0
  45. package/dist/runtime/client/minimize.js +1 -0
  46. package/dist/runtime/client/root.d.ts +7 -0
  47. package/dist/runtime/client/root.js +19 -0
  48. package/dist/runtime/index.d.ts +8 -4
  49. package/dist/runtime/index.js +14 -2
  50. package/dist/runtime/server/dev-server.d.ts +1 -0
  51. package/dist/runtime/server/dev-server.js +294 -319
  52. package/dist/runtime/server/diagnostics.d.ts +17 -0
  53. package/dist/runtime/server/diagnostics.js +87 -0
  54. package/dist/runtime/server/index.d.ts +5 -0
  55. package/dist/runtime/server/index.js +3 -0
  56. package/dist/runtime/server/production-server.js +14 -0
  57. package/dist/security/discord.d.ts +9 -0
  58. package/dist/security/discord.js +37 -7
  59. package/dist/security/secret-scan.d.ts +3 -0
  60. package/dist/security/secret-scan.js +40 -0
  61. package/dist/server/discord-rest.d.ts +45 -0
  62. package/dist/server/discord-rest.js +46 -0
  63. package/dist/server/index.d.ts +2 -0
  64. package/dist/server/index.js +1 -0
  65. package/dist/sessions/cookies.d.ts +4 -1
  66. package/dist/sessions/cookies.js +17 -4
  67. package/dist/sessions/crypto.js +6 -0
  68. package/dist/testing/index.d.ts +13 -0
  69. package/dist/testing/index.js +24 -0
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/dist/ws/client.d.ts +6 -0
  73. package/dist/ws/client.js +46 -10
  74. package/dist/ws/server.d.ts +4 -0
  75. package/dist/ws/server.js +35 -14
  76. package/package.json +31 -4
  77. package/dist/api/runtime.d.ts.map +0 -1
  78. package/dist/api/runtime.js.map +0 -1
  79. package/dist/auth/client.d.ts.map +0 -1
  80. package/dist/auth/client.js.map +0 -1
  81. package/dist/auth/index.d.ts.map +0 -1
  82. package/dist/auth/index.js.map +0 -1
  83. package/dist/auth/server.d.ts.map +0 -1
  84. package/dist/auth/server.js.map +0 -1
  85. package/dist/auth/types.d.ts.map +0 -1
  86. package/dist/auth/types.js.map +0 -1
  87. package/dist/cli/index.d.ts.map +0 -1
  88. package/dist/cli/index.js.map +0 -1
  89. package/dist/cli/project-commands.d.ts.map +0 -1
  90. package/dist/cli/project-commands.js.map +0 -1
  91. package/dist/compiler/build.d.ts.map +0 -1
  92. package/dist/compiler/build.js.map +0 -1
  93. package/dist/compiler/index.d.ts.map +0 -1
  94. package/dist/compiler/index.js.map +0 -1
  95. package/dist/compiler/scanner.d.ts.map +0 -1
  96. package/dist/compiler/scanner.js.map +0 -1
  97. package/dist/compiler/type-generation.d.ts.map +0 -1
  98. package/dist/compiler/type-generation.js.map +0 -1
  99. package/dist/compiler/write-manifests.d.ts.map +0 -1
  100. package/dist/compiler/write-manifests.js.map +0 -1
  101. package/dist/config/defaults.d.ts.map +0 -1
  102. package/dist/config/defaults.js.map +0 -1
  103. package/dist/config/index.d.ts.map +0 -1
  104. package/dist/config/index.js.map +0 -1
  105. package/dist/config/loader.d.ts.map +0 -1
  106. package/dist/config/loader.js.map +0 -1
  107. package/dist/config/project-root.d.ts.map +0 -1
  108. package/dist/config/project-root.js.map +0 -1
  109. package/dist/config/types.d.ts.map +0 -1
  110. package/dist/config/types.js.map +0 -1
  111. package/dist/discord/events.d.ts.map +0 -1
  112. package/dist/discord/events.js.map +0 -1
  113. package/dist/discord/index.d.ts.map +0 -1
  114. package/dist/discord/index.js.map +0 -1
  115. package/dist/discord/runtime.d.ts.map +0 -1
  116. package/dist/discord/runtime.js.map +0 -1
  117. package/dist/discord/safe-area.d.ts.map +0 -1
  118. package/dist/discord/safe-area.js.map +0 -1
  119. package/dist/discord/testing.d.ts.map +0 -1
  120. package/dist/discord/testing.js.map +0 -1
  121. package/dist/index.d.ts.map +0 -1
  122. package/dist/index.js.map +0 -1
  123. package/dist/manifests/types.d.ts.map +0 -1
  124. package/dist/manifests/types.js.map +0 -1
  125. package/dist/navigation/index.d.ts.map +0 -1
  126. package/dist/navigation/index.js.map +0 -1
  127. package/dist/router/match.d.ts.map +0 -1
  128. package/dist/router/match.js.map +0 -1
  129. package/dist/runtime/client/embed-router.d.ts.map +0 -1
  130. package/dist/runtime/client/embed-router.js.map +0 -1
  131. package/dist/runtime/client/minimize-card.d.ts.map +0 -1
  132. package/dist/runtime/client/minimize-card.js.map +0 -1
  133. package/dist/runtime/client/minimize.d.ts.map +0 -1
  134. package/dist/runtime/client/minimize.js.map +0 -1
  135. package/dist/runtime/index.d.ts.map +0 -1
  136. package/dist/runtime/index.js.map +0 -1
  137. package/dist/runtime/server/dev-server.d.ts.map +0 -1
  138. package/dist/runtime/server/dev-server.js.map +0 -1
  139. package/dist/runtime/server/production-server.d.ts.map +0 -1
  140. package/dist/runtime/server/production-server.js.map +0 -1
  141. package/dist/security/discord.d.ts.map +0 -1
  142. package/dist/security/discord.js.map +0 -1
  143. package/dist/security/index.d.ts.map +0 -1
  144. package/dist/security/index.js.map +0 -1
  145. package/dist/server/index.d.ts.map +0 -1
  146. package/dist/server/index.js.map +0 -1
  147. package/dist/server/session.d.ts.map +0 -1
  148. package/dist/server/session.js.map +0 -1
  149. package/dist/server/types.d.ts.map +0 -1
  150. package/dist/server/types.js.map +0 -1
  151. package/dist/sessions/cookies.d.ts.map +0 -1
  152. package/dist/sessions/cookies.js.map +0 -1
  153. package/dist/sessions/crypto.d.ts.map +0 -1
  154. package/dist/sessions/crypto.js.map +0 -1
  155. package/dist/shared/errors.d.ts.map +0 -1
  156. package/dist/shared/errors.js.map +0 -1
  157. package/dist/testing/index.d.ts.map +0 -1
  158. package/dist/testing/index.js.map +0 -1
  159. package/dist/version.d.ts.map +0 -1
  160. package/dist/version.js.map +0 -1
  161. package/dist/ws/client.d.ts.map +0 -1
  162. package/dist/ws/client.js.map +0 -1
  163. package/dist/ws/index.d.ts.map +0 -1
  164. package/dist/ws/index.js.map +0 -1
  165. package/dist/ws/server.d.ts.map +0 -1
  166. package/dist/ws/server.js.map +0 -1
@@ -5,11 +5,16 @@ export interface LudicordSessionUser {
5
5
  readonly avatar: string | null;
6
6
  }
7
7
  export interface LudicordSession {
8
+ /** Development and pending credentials are never accepted as production sessions. */
9
+ readonly kind?: "development" | "pending";
10
+ readonly completionToken?: string;
11
+ readonly sessionExpiresAt?: number;
8
12
  readonly authenticated: true;
9
13
  readonly user: LudicordSessionUser;
10
14
  readonly applicationId: string;
11
15
  readonly guildId?: string;
12
16
  readonly guildName?: string;
17
+ readonly guildIcon?: string | null;
13
18
  readonly channelId?: string;
14
19
  readonly instanceId?: string;
15
20
  readonly activityInstanceVerified?: true;
package/dist/cli/index.js CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import { pathToFileURL } from "node:url";
3
- import { loadEnv } from "vite";
3
+ import { spawn } from "node:child_process";
4
+ import { redact } from "../runtime/server/diagnostics.js";
5
+ import { loadProjectEnvironment } from "../config/environment.js";
4
6
  import { loadLudicordConfig } from "../config/loader.js";
5
7
  import { resolveProjectRoot } from "../config/project-root.js";
6
8
  import { buildLudicordProject } from "../compiler/build.js";
@@ -42,6 +44,7 @@ function parseDevArguments(args) {
42
44
  let host;
43
45
  let hmr = true;
44
46
  let open = false;
47
+ let debug = false;
45
48
  for (let index = 0; index < args.length; index += 1) {
46
49
  const argument = args[index];
47
50
  if (argument === "--port" || argument === "-p") {
@@ -67,7 +70,7 @@ function parseDevArguments(args) {
67
70
  open = true;
68
71
  }
69
72
  else if (argument === "--debug") {
70
- // Debug output is consumed by later command phases.
73
+ debug = true;
71
74
  }
72
75
  else {
73
76
  throw new Error(`LUDICORD0002: Unknown dev option "${argument}".`);
@@ -78,6 +81,7 @@ function parseDevArguments(args) {
78
81
  ...(host === undefined ? {} : { host }),
79
82
  hmr,
80
83
  open,
84
+ debug,
81
85
  };
82
86
  }
83
87
  function environmentPort() {
@@ -89,13 +93,6 @@ function environmentPort() {
89
93
  }
90
94
  return Number(value);
91
95
  }
92
- function loadProjectEnvironment(projectRoot, mode) {
93
- const environment = loadEnv(mode, projectRoot, "");
94
- for (const [name, value] of Object.entries(environment)) {
95
- if (process.env[name] === undefined)
96
- process.env[name] = value;
97
- }
98
- }
99
96
  async function runDevCommand(args, output) {
100
97
  const parsed = parseDevArguments(args);
101
98
  const projectRoot = resolveProjectRoot();
@@ -108,10 +105,14 @@ async function runDevCommand(args, output) {
108
105
  port,
109
106
  host,
110
107
  hmr: parsed.hmr,
108
+ debug: parsed.debug,
111
109
  });
112
110
  output.stdout(server.formatReadyMessage());
113
111
  if (parsed.open) {
114
- output.stdout("Open the Local URL above in your browser.");
112
+ const command = process.platform === "win32" ? "rundll32.exe" : process.platform === "darwin" ? "open" : "xdg-open";
113
+ const child = spawn(command, process.platform === "win32" ? ["url.dll,FileProtocolHandler", server.url] : [server.url], { detached: true, stdio: "ignore", windowsHide: true });
114
+ child.on("error", () => output.stderr("Ludicord could not open a browser. Open the Local URL above."));
115
+ child.unref();
115
116
  }
116
117
  const shutdown = async () => {
117
118
  await server.close();
@@ -187,7 +188,7 @@ export async function runLudicordCli(args = process.argv.slice(2), output = defa
187
188
  return await runDevCommand(args.slice(1), output);
188
189
  }
189
190
  catch (error) {
190
- output.stderr(error instanceof Error ? error.message : String(error));
191
+ output.stderr(redact(error instanceof Error ? error.message : String(error)));
191
192
  return 1;
192
193
  }
193
194
  }
@@ -198,7 +199,7 @@ export async function runLudicordCli(args = process.argv.slice(2), output = defa
198
199
  : await runStartCommand(args.slice(1), output);
199
200
  }
200
201
  catch (error) {
201
- output.stderr(error instanceof Error ? error.message : String(error));
202
+ output.stderr(redact(error instanceof Error ? error.message : String(error)));
202
203
  return 1;
203
204
  }
204
205
  }
@@ -210,7 +211,7 @@ export async function runLudicordCli(args = process.argv.slice(2), output = defa
210
211
  return await runProjectCommand(command, args.slice(1), output);
211
212
  }
212
213
  catch (error) {
213
- output.stderr(error instanceof Error ? error.message : String(error));
214
+ output.stderr(redact(error instanceof Error ? error.message : String(error)));
214
215
  return 1;
215
216
  }
216
217
  }
@@ -1,5 +1,9 @@
1
- import { existsSync, readFileSync, readdirSync, rmSync, statSync, } from "node:fs";
1
+ import { existsSync, readFileSync, rmSync, } from "node:fs";
2
2
  import path from "node:path";
3
+ import { createRequire } from "node:module";
4
+ import { createServer } from "node:net";
5
+ import { loadProjectEnvironment } from "../config/environment.js";
6
+ import { clientContainsSecret } from "../security/secret-scan.js";
3
7
  import { loadLudicordConfig } from "../config/loader.js";
4
8
  import { generateManifests } from "../compiler/scanner.js";
5
9
  import { LUDICORD_VERSION } from "../version.js";
@@ -43,35 +47,12 @@ function diagnosticLine(diagnostic) {
43
47
  : "✗";
44
48
  return `${icon} ${diagnostic.message}${diagnostic.detail === undefined ? "" : `\n ${diagnostic.detail}`}`;
45
49
  }
46
- function walkFiles(directory) {
47
- if (!existsSync(directory))
48
- return [];
49
- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
50
- const file = path.join(directory, entry.name);
51
- return entry.isDirectory() ? walkFiles(file) : [file];
52
- });
53
- }
54
- function clientContainsSecret(projectRoot) {
55
- const client = path.join(projectRoot, ".ludicord", "client");
56
- const secrets = [
57
- process.env.LUDICORD_DISCORD_CLIENT_SECRET,
58
- process.env.LUDICORD_SESSION_SECRET,
59
- process.env.LUDICORD_DISCORD_BOT_TOKEN,
60
- ].filter((value) => value !== undefined && value !== "");
61
- if (secrets.length === 0 || !existsSync(client))
62
- return false;
63
- return walkFiles(client).some((file) => {
64
- if (statSync(file).size > 10_000_000)
65
- return false;
66
- const contents = readFileSync(file);
67
- return secrets.some((secret) => contents.includes(Buffer.from(secret)));
68
- });
69
- }
70
50
  export async function runDoctor(projectRoot) {
51
+ loadProjectEnvironment(projectRoot, "production");
71
52
  const diagnostics = [];
72
- const nodeMajor = Number(process.versions.node.split(".")[0]);
53
+ const [nodeMajor = 0, nodeMinor = 0] = process.versions.node.split(".").map(Number);
73
54
  diagnostics.push({
74
- level: nodeMajor >= 20 ? "ok" : "error",
55
+ level: nodeMajor > 20 || (nodeMajor === 20 && nodeMinor >= 19) ? "ok" : "error",
75
56
  message: `Node.js ${process.versions.node}`,
76
57
  });
77
58
  let manifests;
@@ -119,9 +100,9 @@ export async function runDoctor(projectRoot) {
119
100
  : {}),
120
101
  });
121
102
  diagnostics.push({
122
- level: process.env.LUDICORD_DISCORD_CLIENT_SECRET === undefined ? "error" : "ok",
103
+ level: !process.env.LUDICORD_DISCORD_CLIENT_SECRET?.trim() ? "error" : "ok",
123
104
  message: "Discord Client Secret",
124
- ...(process.env.LUDICORD_DISCORD_CLIENT_SECRET === undefined
105
+ ...(!process.env.LUDICORD_DISCORD_CLIENT_SECRET?.trim()
125
106
  ? { detail: "Set LUDICORD_DISCORD_CLIENT_SECRET." }
126
107
  : {}),
127
108
  });
@@ -136,7 +117,7 @@ export async function runDoctor(projectRoot) {
136
117
  : { detail: "LUDICORD_SESSION_SECRET must contain at least 32 characters." }),
137
118
  });
138
119
  if (config.discord.auth.proxyVerification &&
139
- process.env.LUDICORD_DISCORD_PUBLIC_KEY === undefined) {
120
+ !process.env.LUDICORD_DISCORD_PUBLIC_KEY?.trim()) {
140
121
  diagnostics.push({
141
122
  level: "error",
142
123
  message: "Discord Public Key",
@@ -150,7 +131,7 @@ export async function runDoctor(projectRoot) {
150
131
  });
151
132
  }
152
133
  if (config.discord.auth.activityInstanceVerification &&
153
- process.env.LUDICORD_DISCORD_BOT_TOKEN === undefined) {
134
+ !process.env.LUDICORD_DISCORD_BOT_TOKEN?.trim()) {
154
135
  diagnostics.push({
155
136
  level: "error",
156
137
  message: "Activity Instance verification token",
@@ -158,6 +139,33 @@ export async function runDoctor(projectRoot) {
158
139
  });
159
140
  }
160
141
  }
142
+ if (config) {
143
+ if (!config.discord.scopes.includes("guilds"))
144
+ diagnostics.push({ level: "warning", message: 'Add the "guilds" scope for guild and channel details.' });
145
+ if (config.discord.auth.required && !config.discord.auth.activityInstanceVerification)
146
+ diagnostics.push({ level: "warning", message: "Activity Instance verification is disabled; client-provided guild/channel/instance IDs are unverified." });
147
+ if (process.env.LUDICORD_DEV_FAKE_AUTH === "true")
148
+ diagnostics.push({ level: "warning", message: "Development fake authentication is enabled locally; never use fake sessions in production." });
149
+ if (config.server.port !== 0) {
150
+ const available = await new Promise((resolve) => {
151
+ const probe = createServer();
152
+ probe.once("error", () => resolve(false));
153
+ probe.listen(config.server.port, "127.0.0.1", () => probe.close(() => resolve(true)));
154
+ });
155
+ diagnostics.push({ level: available ? "ok" : "warning", message: available ? `Port ${config.server.port} is available` : `Port ${config.server.port} is occupied or unavailable; stop the existing server or select --port.` });
156
+ }
157
+ }
158
+ const metadataFile = path.join(projectRoot, ".ludicord", "build.json");
159
+ if (existsSync(metadataFile)) {
160
+ try {
161
+ const metadata = JSON.parse(readFileSync(metadataFile, "utf8"));
162
+ if (metadata.frameworkVersion !== LUDICORD_VERSION)
163
+ diagnostics.push({ level: "warning", message: "Production output was built with a different framework version. Run ludicord build." });
164
+ }
165
+ catch {
166
+ diagnostics.push({ level: "error", message: "Invalid production build metadata. Run ludicord build." });
167
+ }
168
+ }
161
169
  diagnostics.push({
162
170
  level: existsSync(path.join(projectRoot, ".ludicord", "build.json"))
163
171
  ? "ok"
@@ -169,9 +177,10 @@ export async function runDoctor(projectRoot) {
169
177
  ? {}
170
178
  : { detail: "Run ludicord build before ludicord start." }),
171
179
  });
180
+ const leaked = clientContainsSecret(path.join(projectRoot, ".ludicord", "client"));
172
181
  diagnostics.push({
173
- level: clientContainsSecret(projectRoot) ? "error" : "ok",
174
- message: clientContainsSecret(projectRoot)
182
+ level: leaked ? "error" : "ok",
183
+ message: leaked
175
184
  ? "Server secret detected in client output"
176
185
  : "No server secret leakage detected",
177
186
  });
@@ -193,7 +202,13 @@ function dependencyVersion(projectRoot, packageName) {
193
202
  .version;
194
203
  }
195
204
  catch {
196
- return "not installed";
205
+ try {
206
+ const require = createRequire(import.meta.url);
207
+ return JSON.parse(readFileSync(require.resolve(packageName + "/package.json"), "utf8")).version;
208
+ }
209
+ catch {
210
+ return "not installed";
211
+ }
197
212
  }
198
213
  }
199
214
  export function formatInfo(projectRoot) {
@@ -1,17 +1,17 @@
1
- import { createRequire } from "node:module";
2
- import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
3
2
  import path from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import react from "@vitejs/plugin-react";
6
- import { build as esbuild } from "esbuild";
7
- import { build as viteBuild, normalizePath, } from "vite";
3
+ import { build as viteBuild, } from "vite";
8
4
  import { loadLudicordConfig } from "../config/loader.js";
9
- import { LudicordError } from "../shared/errors.js";
10
5
  import { LUDICORD_VERSION } from "../version.js";
11
6
  import { generateManifests } from "./scanner.js";
12
7
  import { writeManifests } from "./write-manifests.js";
13
8
  import { generateLudicordTypes } from "./type-generation.js";
14
- const require = createRequire(import.meta.url);
9
+ import { clientEntry } from "./client-entry.js";
10
+ import { clientAliases as ludicordClientAliases, clientPlugins, ludicordLogger } from "./client-tooling.js";
11
+ import { bundleServerGraph } from "./server-bundle.js";
12
+ import { loadProjectEnvironment } from "../config/environment.js";
13
+ import { clientContainsSecret } from "../security/secret-scan.js";
14
+ import { checkProjectTypes } from "../runtime/server/diagnostics.js";
15
15
  const VIRTUAL_BUILD_ENTRY = "virtual:ludicord-production-entry";
16
16
  const RESOLVED_BUILD_ENTRY = "\0virtual:ludicord-production-entry";
17
17
  function safeOutputDirectory(projectRoot) {
@@ -21,32 +21,6 @@ function safeOutputDirectory(projectRoot) {
21
21
  }
22
22
  return output;
23
23
  }
24
- function clientEntrySource(projectRoot, manifests, config) {
25
- const activityImport = normalizePath(path.join(projectRoot, manifests.activity.root));
26
- const registry = manifests.embeds
27
- .map(({ route, file }) => {
28
- const importPath = normalizePath(path.join(projectRoot, file));
29
- return `${JSON.stringify(route)}: () => import(${JSON.stringify(importPath)})`;
30
- })
31
- .join(",\n");
32
- const publicConfig = {
33
- discordClientId: config.discord.clientId,
34
- outsideDiscord: config.activity.outsideDiscord,
35
- scopes: config.discord.scopes,
36
- authRequired: config.discord.auth.required,
37
- devFakeAuth: false,
38
- };
39
- return `
40
- import React from "react";
41
- import { createRoot } from "react-dom/client";
42
- import Pages from ${JSON.stringify(activityImport)};
43
- globalThis.__LUDICORD_PUBLIC_CONFIG__ = ${JSON.stringify(publicConfig)};
44
- globalThis.__LUDICORD_EMBEDS__ = { ${registry} };
45
- const container = document.getElementById("ludicord-root");
46
- if (!container) throw new Error("LUDICORD2003: Missing #ludicord-root container.");
47
- createRoot(container).render(React.createElement(Pages));
48
- `;
49
- }
50
24
  function buildPlugin(projectRoot, manifests, config) {
51
25
  return {
52
26
  name: "ludicord:production-entry",
@@ -55,60 +29,22 @@ function buildPlugin(projectRoot, manifests, config) {
55
29
  },
56
30
  load(id) {
57
31
  return id === RESOLVED_BUILD_ENTRY
58
- ? clientEntrySource(projectRoot, manifests, config)
32
+ ? clientEntry(projectRoot, manifests, config, false)
59
33
  : undefined;
60
34
  },
61
35
  };
62
36
  }
63
- function clientAliases() {
64
- return [
65
- { find: /^react$/, replacement: require.resolve("react") },
66
- {
67
- find: /^react\/jsx-runtime$/,
68
- replacement: require.resolve("react/jsx-runtime"),
69
- },
70
- {
71
- find: /^react\/jsx-dev-runtime$/,
72
- replacement: require.resolve("react/jsx-dev-runtime"),
73
- },
74
- {
75
- find: /^react-dom$/,
76
- replacement: require.resolve("react-dom"),
77
- },
78
- {
79
- find: /^react-dom\/client$/,
80
- replacement: require.resolve("react-dom/client"),
81
- },
82
- {
83
- find: /^ludicord$/,
84
- replacement: fileURLToPath(new URL("../index.js", import.meta.url)),
85
- },
86
- {
87
- find: /^ludicord\/navigation$/,
88
- replacement: fileURLToPath(new URL("../navigation/index.js", import.meta.url)),
89
- },
90
- {
91
- find: /^ludicord\/discord$/,
92
- replacement: fileURLToPath(new URL("../discord/index.js", import.meta.url)),
93
- },
94
- {
95
- find: /^ludicord\/auth$/,
96
- replacement: fileURLToPath(new URL("../auth/index.js", import.meta.url)),
97
- },
98
- {
99
- find: /^ludicord\/ws\/client$/,
100
- replacement: fileURLToPath(new URL("../ws/client.js", import.meta.url)),
101
- },
102
- ];
103
- }
104
37
  async function buildClient(projectRoot, outputDirectory, manifests, config) {
105
38
  const result = (await viteBuild({
39
+ configFile: false,
40
+ cacheDir: path.join(projectRoot, ".ludicord", "cache", "client"),
41
+ customLogger: ludicordLogger(),
106
42
  root: projectRoot,
107
43
  publicDir: existsSync(path.join(projectRoot, "public"))
108
44
  ? path.join(projectRoot, "public")
109
45
  : false,
110
- plugins: [buildPlugin(projectRoot, manifests, config), react()],
111
- resolve: { alias: clientAliases() },
46
+ plugins: [buildPlugin(projectRoot, manifests, config), ...await clientPlugins(projectRoot)],
47
+ resolve: { alias: ludicordClientAliases(projectRoot), dedupe: ["react", "react-dom"] },
112
48
  build: {
113
49
  outDir: path.join(outputDirectory, "client"),
114
50
  emptyOutDir: true,
@@ -128,15 +64,28 @@ async function buildClient(projectRoot, outputDirectory, manifests, config) {
128
64
  .flatMap((output) => output.output)
129
65
  .find((item) => item.type === "chunk" && item.isEntry);
130
66
  if (entry === undefined) {
131
- throw new Error("LUDICORD7003: Vite did not generate an Activity entry.");
67
+ throw new Error("LUDICORD7003: The compiler did not generate an Activity entry.");
132
68
  }
133
69
  const clientEntry = entry.fileName.split(path.sep).join("/");
70
+ const viteManifest = JSON.parse(readFileSync(path.join(outputDirectory, "client", "vite-manifest.json"), "utf8"));
71
+ const styles = new Set();
72
+ const visited = new Set();
73
+ const collect = (key) => {
74
+ if (visited.has(key))
75
+ return;
76
+ visited.add(key);
77
+ const chunk = viteManifest[key];
78
+ chunk?.css?.forEach((file) => styles.add(file));
79
+ chunk?.imports?.forEach(collect);
80
+ };
81
+ Object.keys(viteManifest).filter((key) => viteManifest[key]?.isEntry).forEach(collect);
134
82
  writeFileSync(path.join(outputDirectory, "client", "index.html"), `<!doctype html>
135
83
  <html>
136
84
  <head>
137
85
  <meta charset="UTF-8" />
138
86
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
139
87
  <title>Ludicord Activity</title>
88
+ ${[...styles].map((file) => `<link rel="stylesheet" href="/${file}" />`).join("\n ")}
140
89
  </head>
141
90
  <body>
142
91
  <div id="ludicord-root"></div>
@@ -146,52 +95,6 @@ async function buildClient(projectRoot, outputDirectory, manifests, config) {
146
95
  `, "utf8");
147
96
  return clientEntry;
148
97
  }
149
- async function bundleRoutes(projectRoot, outputDirectory, entries, kind) {
150
- const bundles = [];
151
- const destination = path.join(outputDirectory, "server", kind);
152
- mkdirSync(destination, { recursive: true });
153
- for (const [index, entry] of entries.entries()) {
154
- const bundle = path.join("server", kind, `${index}.mjs`).split(path.sep).join("/");
155
- await esbuild({
156
- entryPoints: [path.join(projectRoot, entry.file)],
157
- outfile: path.join(outputDirectory, bundle),
158
- platform: "node",
159
- format: "esm",
160
- target: "node20",
161
- bundle: true,
162
- sourcemap: true,
163
- packages: "external",
164
- logLevel: "silent",
165
- });
166
- bundles.push({ source: entry.file, bundle });
167
- }
168
- return bundles;
169
- }
170
- function walkFiles(directory) {
171
- if (!existsSync(directory))
172
- return [];
173
- return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
174
- const file = path.join(directory, entry.name);
175
- return entry.isDirectory() ? walkFiles(file) : [file];
176
- });
177
- }
178
- function scanForSecrets(clientDirectory) {
179
- const secrets = [
180
- process.env.LUDICORD_DISCORD_CLIENT_SECRET,
181
- process.env.LUDICORD_SESSION_SECRET,
182
- process.env.LUDICORD_DISCORD_BOT_TOKEN,
183
- ].filter((value) => value !== undefined && value !== "");
184
- if (secrets.length === 0)
185
- return;
186
- for (const file of walkFiles(clientDirectory)) {
187
- if (statSync(file).size > 10_000_000)
188
- continue;
189
- const contents = readFileSync(file);
190
- if (secrets.some((secret) => contents.includes(Buffer.from(secret)))) {
191
- throw new Error("LUDICORD7001: Server secret detected in client output.");
192
- }
193
- }
194
- }
195
98
  function buildMetadata(clientEntry, api, websocket, config) {
196
99
  return {
197
100
  frameworkVersion: LUDICORD_VERSION,
@@ -220,6 +123,7 @@ function buildMetadata(clientEntry, api, websocket, config) {
220
123
  }
221
124
  export async function buildLudicordProject(projectRoot) {
222
125
  const root = path.resolve(projectRoot);
126
+ loadProjectEnvironment(root, "production");
223
127
  const outputDirectory = safeOutputDirectory(root);
224
128
  const manifests = generateManifests(root);
225
129
  const { config } = await loadLudicordConfig(root);
@@ -227,14 +131,19 @@ export async function buildLudicordProject(projectRoot) {
227
131
  mkdirSync(outputDirectory, { recursive: true });
228
132
  try {
229
133
  generateLudicordTypes(root, manifests, config);
134
+ const typeErrors = checkProjectTypes(root);
135
+ if (typeErrors.length > 0)
136
+ throw new Error(typeErrors.map((item) => `${item.file ?? "TypeScript"}:${item.line ?? 1}:${item.column ?? 1}\n${item.message}\n${item.frame ?? ""}`).join("\n\n"));
230
137
  const clientEntry = await buildClient(root, outputDirectory, manifests, config);
231
- const api = await bundleRoutes(root, outputDirectory, manifests.api, "api");
232
- const websocket = await bundleRoutes(root, outputDirectory, manifests.websocket, "ws");
138
+ const graph = await bundleServerGraph(root, path.join(outputDirectory, "server"), manifests);
139
+ const api = graph.bundles.filter((route) => route.kind === "api").map((route) => ({ source: route.source, bundle: `server/${route.bundle}` }));
140
+ const websocket = graph.bundles.filter((route) => route.kind === "ws").map((route) => ({ source: route.source, bundle: `server/${route.bundle}` }));
233
141
  writeManifests(manifests, path.join(outputDirectory, "manifests"));
234
142
  mkdirSync(path.join(outputDirectory, "types"), { recursive: true });
235
143
  const metadata = buildMetadata(clientEntry, api, websocket, config);
236
144
  writeFileSync(path.join(outputDirectory, "build.json"), `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
237
- scanForSecrets(path.join(outputDirectory, "client"));
145
+ if (clientContainsSecret(path.join(outputDirectory, "client")))
146
+ throw new Error("LUDICORD7001: Server secret detected in client output.");
238
147
  return {
239
148
  outputDirectory,
240
149
  manifests,
@@ -0,0 +1,4 @@
1
+ import type { ResolvedLudicordConfig } from "../config/types.js";
2
+ import type { LudicordManifests } from "../manifests/types.js";
3
+ export declare function clientEntry(root: string, manifests: LudicordManifests, config: ResolvedLudicordConfig, development: boolean): string;
4
+ //# sourceMappingURL=client-entry.d.ts.map
@@ -0,0 +1,35 @@
1
+ import path from "node:path";
2
+ import { normalizePath } from "vite";
3
+ import { LUDICORD_VERSION } from "../version.js";
4
+ export function clientEntry(root, manifests, config, development) {
5
+ const file = (relative) => `${development ? "/@fs/" : ""}${normalizePath(path.join(root, relative))}`;
6
+ const imports = [`import React from "react";`, `import { createRoot } from "react-dom/client";`,
7
+ `import { LudicordRoot } from "ludicord/internal";`, `import Pages from ${JSON.stringify(file(manifests.activity.root))};`];
8
+ const components = [];
9
+ for (const key of ["layout", "loading", "error", "minimize", "authLoading", "authError", "authDenied"]) {
10
+ const source = manifests.activity[key];
11
+ if (source !== undefined) {
12
+ const name = `File_${key}`;
13
+ imports.push(`import ${name} from ${JSON.stringify(file(source))};`);
14
+ components.push(`${key}: ${name}`);
15
+ }
16
+ }
17
+ const publicConfig = {
18
+ discordServerData: Boolean(process.env.LUDICORD_DISCORD_BOT_TOKEN),
19
+ environment: development ? "development" : "production", version: LUDICORD_VERSION,
20
+ discordClientId: config.discord.clientId, outsideDiscord: config.activity.outsideDiscord,
21
+ scopes: config.discord.scopes, authRequired: config.discord.auth.required,
22
+ defaultEmbed: config.activity.defaultEmbed,
23
+ devFakeAuth: development && process.env.LUDICORD_DEV_FAKE_AUTH === "true",
24
+ websocket: { enabled: config.websocket.enabled, reconnect: config.websocket.reconnect },
25
+ };
26
+ return `${imports.join("\n")}
27
+ globalThis.__LUDICORD_PUBLIC_CONFIG__ = ${JSON.stringify(publicConfig)};
28
+ globalThis.__LUDICORD_EMBEDS__ = {${manifests.embeds.map((route) => `${JSON.stringify(route.route)}: () => import(${JSON.stringify(file(route.file))})`).join(",\n")}};
29
+ const container = document.getElementById("ludicord-root");
30
+ if (!container) throw new Error("LUDICORD2003: Missing #ludicord-root container.");
31
+ const root = createRoot(container);
32
+ root.render(React.createElement(LudicordRoot, { files: {${components.join(",")}} }, React.createElement(Pages)));
33
+ ${development ? `if (import.meta.hot) import.meta.hot.dispose(() => root.unmount());` : ""}`;
34
+ }
35
+ //# sourceMappingURL=client-entry.js.map
@@ -0,0 +1,5 @@
1
+ import type { AliasOptions, Logger, PluginOption } from "vite";
2
+ export declare function clientAliases(projectRoot: string): AliasOptions;
3
+ export declare function ludicordLogger(onError?: (error: unknown) => void): Logger;
4
+ export declare function clientPlugins(projectRoot: string, onCompile?: (file: string, elapsed?: number) => void): Promise<PluginOption[]>;
5
+ //# sourceMappingURL=client-tooling.d.ts.map
@@ -0,0 +1,97 @@
1
+ import { existsSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import path from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+ import MagicString from "magic-string";
6
+ import ts from "typescript";
7
+ import react from "@vitejs/plugin-react";
8
+ import { createLogger, normalizePath } from "vite";
9
+ import { redact } from "../runtime/server/diagnostics.js";
10
+ const require = createRequire(import.meta.url);
11
+ export function clientAliases(projectRoot) {
12
+ const resolve = (name) => {
13
+ try {
14
+ return require.resolve(name, { paths: [projectRoot] });
15
+ }
16
+ catch {
17
+ return require.resolve(name);
18
+ }
19
+ };
20
+ const entries = ["react", "react/jsx-runtime", "react/jsx-dev-runtime", "react-dom", "react-dom/client"].map((name) => ({ find: new RegExp(`^${name.replaceAll("/", "\\/")}$`), replacement: resolve(name) }));
21
+ const runtime = {
22
+ ludicord: "../index.js", "ludicord/internal": "../runtime/client/root.js", "ludicord/runtime": "../runtime/index.js",
23
+ "ludicord/navigation": "../navigation/index.js", "ludicord/discord": "../discord/index.js", "ludicord/auth": "../auth/index.js",
24
+ "ludicord/ws": "../ws/client.js", "ludicord/ws/client": "../ws/client.js",
25
+ };
26
+ return [...entries, ...Object.entries(runtime).map(([name, file]) => ({ find: new RegExp(`^${name.replaceAll("/", "\\/")}$`), replacement: fileURLToPath(new URL(file, import.meta.url)) }))];
27
+ }
28
+ export function ludicordLogger(onError) {
29
+ const base = createLogger("info", { prefix: "Ludicord", allowClearScreen: false });
30
+ return {
31
+ ...base,
32
+ info() { },
33
+ warn(message, options) { base.warn(redact(message).replaceAll("[vite]", "[ludicord]"), options); },
34
+ warnOnce(message, options) { base.warnOnce(redact(message).replaceAll("[vite]", "[ludicord]"), options); },
35
+ error(message, options) {
36
+ const error = options?.error ?? new Error(message);
37
+ onError?.(error);
38
+ if (onError === undefined)
39
+ base.error(redact(message).replaceAll("[vite]", "[ludicord]"), options);
40
+ },
41
+ clearScreen() { },
42
+ };
43
+ }
44
+ export async function clientPlugins(projectRoot, onCompile) {
45
+ const startTimes = new Map();
46
+ const appRoot = normalizePath(path.join(projectRoot, "app"));
47
+ const boundaries = {
48
+ name: "ludicord:client-boundaries", enforce: "pre",
49
+ resolveId(id, _importer, options) {
50
+ if (!options.ssr && /^ludicord\/(server|security|config|ws\/server|runtime\/server)(\/|$)/.test(id)) {
51
+ throw new Error(`LUDICORD7004: ${id} is server-only. Move this import to app/api or app/ws; use type-only imports for types.`);
52
+ }
53
+ return undefined;
54
+ },
55
+ transform(code, id, options) {
56
+ if (options?.ssr)
57
+ return undefined;
58
+ const file = normalizePath(id.split("?", 1)[0] ?? id);
59
+ if (file.startsWith(`${appRoot}/`)) {
60
+ startTimes.set(id, performance.now());
61
+ onCompile?.(path.relative(projectRoot, file).split(path.sep).join("/"));
62
+ }
63
+ if (!/\/embeds\/.*\/embed\.[jt]sx?$/.test(file))
64
+ return undefined;
65
+ // Source code remains `export default function embed`; React Refresh sees a component name.
66
+ const source = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, file.endsWith("tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.JSX);
67
+ const declaration = source.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === "embed" && node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword) === true);
68
+ if (!declaration?.name)
69
+ return undefined;
70
+ const result = new MagicString(code);
71
+ result.overwrite(declaration.name.getStart(source), declaration.name.end, "LudicordEmbed");
72
+ // Preserve self-references and other local references to the authored function name.
73
+ result.appendLeft(declaration.end, "\nconst embed = LudicordEmbed;\n");
74
+ return { code: result.toString(), map: result.generateMap({ source: file, includeContent: true, hires: true }) };
75
+ },
76
+ };
77
+ const finished = {
78
+ name: "ludicord:compile-timing", enforce: "post",
79
+ transform(_code, id) {
80
+ const start = startTimes.get(id);
81
+ if (start !== undefined) {
82
+ startTimes.delete(id);
83
+ onCompile?.(path.relative(projectRoot, id.split("?", 1)[0] ?? id).split(path.sep).join("/"), Math.round(performance.now() - start));
84
+ }
85
+ return undefined;
86
+ },
87
+ };
88
+ const plugins = [boundaries, react({ exclude: /[\\/]node_modules[\\/]|[\\/]\.ludicord[\\/]/ }), finished];
89
+ const manifest = path.join(projectRoot, "node_modules", "@tailwindcss", "vite", "package.json");
90
+ if (existsSync(manifest)) {
91
+ const file = require.resolve("@tailwindcss/vite", { paths: [projectRoot] });
92
+ const tailwind = await import(pathToFileURL(file).href);
93
+ plugins.push(tailwind.default());
94
+ }
95
+ return plugins;
96
+ }
97
+ //# sourceMappingURL=client-tooling.js.map
@@ -133,11 +133,19 @@ export function validateActivityRoot(projectRoot) {
133
133
  const layout = optionalFile("layout.tsx");
134
134
  const loading = optionalFile("loading.tsx");
135
135
  const error = optionalFile("error.tsx");
136
+ const extras = Object.fromEntries([
137
+ ["minimize", "minimize.tsx"], ["authLoading", "auth/loading.tsx"],
138
+ ["authError", "auth/error.tsx"], ["authDenied", "auth/denied.tsx"],
139
+ ].flatMap(([key, file]) => {
140
+ const value = optionalFile(file);
141
+ return value === undefined ? [] : [[key, value]];
142
+ }));
136
143
  return {
137
144
  root: "app/pages.tsx",
138
145
  ...(layout === undefined ? {} : { layout }),
139
146
  ...(loading === undefined ? {} : { loading }),
140
147
  ...(error === undefined ? {} : { error }),
148
+ ...extras,
141
149
  };
142
150
  }
143
151
  export function scanEmbeds(projectRoot) {