ludicord 4.0.1 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/AGENTS.md +2 -0
  2. package/README.md +5 -1
  3. package/dist/compiler/build.d.ts +2 -0
  4. package/dist/compiler/build.js +22 -6
  5. package/dist/compiler/client-assets.d.ts +2 -0
  6. package/dist/compiler/client-assets.js +5 -0
  7. package/dist/compiler/client-entry.js +40 -15
  8. package/dist/compiler/plugin-runtime.d.ts +5 -0
  9. package/dist/compiler/plugin-runtime.js +155 -0
  10. package/dist/compiler/server-bundle.d.ts +2 -1
  11. package/dist/compiler/server-bundle.js +4 -1
  12. package/dist/compiler/type-generation.js +18 -2
  13. package/dist/config/defaults.js +18 -0
  14. package/dist/config/index.d.ts +2 -2
  15. package/dist/config/index.js +1 -1
  16. package/dist/config/types.d.ts +32 -0
  17. package/dist/config/types.js +3 -0
  18. package/dist/docs/README.md +2 -1
  19. package/dist/docs/activity-rooms.md +1 -1
  20. package/dist/docs/ai-agents.md +1 -1
  21. package/dist/docs/api-reference.md +6 -2
  22. package/dist/docs/api-routes.md +15 -1
  23. package/dist/docs/build.md +1 -1
  24. package/dist/docs/cli.md +1 -1
  25. package/dist/docs/configuration.md +9 -1
  26. package/dist/docs/deployment.md +18 -1
  27. package/dist/docs/development.md +32 -1
  28. package/dist/docs/discord-developer-portal.md +1 -1
  29. package/dist/docs/discord-sdk.md +1 -1
  30. package/dist/docs/distribution.md +1 -1
  31. package/dist/docs/embeds.md +1 -1
  32. package/dist/docs/environment-variables.md +1 -1
  33. package/dist/docs/getting-started.md +1 -1
  34. package/dist/docs/installation.md +2 -2
  35. package/dist/docs/login.md +1 -1
  36. package/dist/docs/migration.md +5 -5
  37. package/dist/docs/mobile-layout.md +1 -1
  38. package/dist/docs/navigation.md +1 -1
  39. package/dist/docs/pages.md +7 -1
  40. package/dist/docs/participants.md +1 -1
  41. package/dist/docs/plugins.md +93 -0
  42. package/dist/docs/prefix-router.md +1 -1
  43. package/dist/docs/project-structure.md +2 -1
  44. package/dist/docs/recipes.md +1 -1
  45. package/dist/docs/security.md +1 -1
  46. package/dist/docs/start.md +1 -1
  47. package/dist/docs/state-and-effects.md +1 -1
  48. package/dist/docs/troubleshooting.md +1 -1
  49. package/dist/docs/voice-events.md +1 -1
  50. package/dist/docs/websockets.md +1 -1
  51. package/dist/lint/index.js +1 -1
  52. package/dist/plugins/index.d.ts +2 -0
  53. package/dist/plugins/index.js +1 -0
  54. package/dist/plugins/wasm.d.ts +7 -0
  55. package/dist/plugins/wasm.js +52 -0
  56. package/dist/runtime/client/embed-router.js +23 -5
  57. package/dist/runtime/client/root.d.ts +2 -0
  58. package/dist/runtime/client/root.js +5 -1
  59. package/dist/runtime/client/startup.d.ts +17 -0
  60. package/dist/runtime/client/startup.js +72 -0
  61. package/dist/runtime/server/dev-server.js +5 -3
  62. package/dist/runtime/server/production-server.js +38 -2
  63. package/dist/runtime/startup-shell.d.ts +12 -0
  64. package/dist/runtime/startup-shell.js +16 -0
  65. package/dist/skills/ludicord/SKILL.md +8 -3
  66. package/dist/skills/ludicord/manifest.yaml +4 -1
  67. package/dist/skills/ludicord/references/config-deploy.md +6 -1
  68. package/dist/version.js +1 -1
  69. package/package.json +27 -1
package/AGENTS.md CHANGED
@@ -8,4 +8,6 @@ Ludicord's unified router uses `page.tsx` for pages, `route.ts` for HTTP methods
8
8
  Default to one root page and ordinary embeds. Create independent pathname scopes only for a large project's separate surfaces or an important requirement for distinct URLs, shells, or provider lifetimes; explain the requirement before adding that architecture.
9
9
 
10
10
  Keep secrets and authorization on the server. Run the relevant lint, type, route, production-build, and behavior checks before finishing.
11
+
12
+ Register trusted compiler extensions through `plugins` in `ludicord.config.mjs`. Read `dist/docs/plugins.md` before using `definePlugin()` or the official `wasm()` plugin; do not add a Vite config.
11
13
  <!-- END:ludicord-agent-rules -->
package/README.md CHANGED
@@ -22,7 +22,9 @@ ludicord build
22
22
  ludicord start
23
23
  ```
24
24
 
25
- Public entry points include `ludicord`, `ludicord/config`, `ludicord/metadata`, `ludicord/navigation`, `ludicord/activity`, `ludicord/discord`, `ludicord/auth`, `ludicord/server`, `ludicord/security`, `ludicord/ws`, `ludicord/ws/client`, `ludicord/ws/server`, `ludicord/runtime` (client status), `ludicord/runtime/server` (server tooling), and `ludicord/testing`.
25
+ Public entry points include `ludicord`, `ludicord/config`, `ludicord/plugins`, `ludicord/plugins/wasm`, `ludicord/metadata`, `ludicord/navigation`, `ludicord/activity`, `ludicord/discord`, `ludicord/auth`, `ludicord/server`, `ludicord/security`, `ludicord/ws`, `ludicord/ws/client`, `ludicord/ws/server`, `ludicord/runtime` (client status), `ludicord/runtime/server` (server tooling), and `ludicord/testing`.
26
+
27
+ Projects can register typed compiler extensions in `ludicord.config.mjs`. The official `wasm()` plugin adds portable `.wasm` imports to browser components and server routes while Ludicord keeps ownership of the underlying compiler configuration. See [Plugins and WebAssembly](https://github.com/mrcholer/ludicord/blob/main/docs/plugins.md).
26
28
 
27
29
  See the public [documentation](https://github.com/mrcholer/ludicord/blob/main/docs/README.md), [release history](https://github.com/mrcholer/ludicord/blob/main/CHANGELOG.md), and [issue tracker](https://github.com/mrcholer/ludicord/issues). The public repository contains documentation and release information, not the framework implementation.
28
30
 
@@ -40,6 +42,8 @@ V4 includes the production authentication, Activity-launch isolation, realtime r
40
42
 
41
43
  V4 also accepts the configured application's exact `https://<clientId>.discordsays.com` proxy origin by default for HTTP and WebSocket requests, alongside normal same-origin traffic. The framework derives the hostname from the Discord Application ID and does not trust wildcard Activity origins.
42
44
 
45
+ Ludicord 4.1 adds trusted compiler plugins through `ludicord.config.mjs`. `definePlugin()` provides portable client/server hooks, and the official `wasm()` plugin adds typed precompiled WebAssembly imports in both environments without exposing Ludicord's underlying compiler configuration.
46
+
43
47
  ## Version-matched AI guidance
44
48
 
45
49
  Ludicord 4 includes offline docs at `node_modules/ludicord/dist/docs/`, the
@@ -11,6 +11,8 @@ export interface LudicordBuildMetadata {
11
11
  readonly frameworkVersion: string;
12
12
  readonly createdAt: string;
13
13
  readonly clientEntry: string;
14
+ /** Compiler-emitted content-hashed assets; absent in older schema-4 builds. */
15
+ readonly immutableAssets?: readonly string[];
14
16
  readonly api: readonly RouteBundle[];
15
17
  readonly websocket: readonly RouteBundle[];
16
18
  readonly instrumentation?: RouteBundle;
@@ -9,12 +9,15 @@ import { generateManifests } from "./scanner.js";
9
9
  import { writeManifests } from "./write-manifests.js";
10
10
  import { generateLudicordTypes } from "./type-generation.js";
11
11
  import { clientEntry } from "./client-entry.js";
12
+ import { isHashedClientAsset } from "./client-assets.js";
13
+ import { STARTUP_SHELL_HTML } from "../runtime/startup-shell.js";
12
14
  import { clientAliases as ludicordClientAliases, clientPlugins, ludicordLogger } from "./client-tooling.js";
13
15
  import { bundleServerGraph } from "./server-bundle.js";
14
16
  import { loadProjectEnvironment } from "../config/environment.js";
15
17
  import { clientContainsSecret } from "../security/secret-scan.js";
16
18
  import { checkProjectTypes } from "../runtime/server/diagnostics.js";
17
19
  import { createBundleReport } from "./bundle-report.js";
20
+ import { vitePluginAdapters } from "./plugin-runtime.js";
18
21
  const VIRTUAL_BUILD_ENTRY = "virtual:ludicord-production-entry";
19
22
  const RESOLVED_BUILD_ENTRY = "\0virtual:ludicord-production-entry";
20
23
  export const LUDICORD_BUILD_SCHEMA_VERSION = 4;
@@ -150,7 +153,11 @@ async function buildClient(projectRoot, outputDirectory, manifests, config) {
150
153
  publicDir: existsSync(path.join(projectRoot, "public"))
151
154
  ? path.join(projectRoot, "public")
152
155
  : false,
153
- plugins: [buildPlugin(projectRoot, manifests, config), ...await clientPlugins(projectRoot)],
156
+ plugins: [
157
+ buildPlugin(projectRoot, manifests, config),
158
+ ...vitePluginAdapters(config.plugins, projectRoot, "production"),
159
+ ...await clientPlugins(projectRoot),
160
+ ],
154
161
  resolve: { alias: ludicordClientAliases(projectRoot, config.imports.aliases), dedupe: ["react", "react-dom"] },
155
162
  build: {
156
163
  outDir: path.join(outputDirectory, "client"),
@@ -167,6 +174,11 @@ async function buildClient(projectRoot, outputDirectory, manifests, config) {
167
174
  },
168
175
  }));
169
176
  const outputs = Array.isArray(result) ? result : [result];
177
+ // Rollup output excludes files copied verbatim from public/. A hash-looking
178
+ // public filename alone must never opt mutable content into immutable caching.
179
+ const immutableAssets = [...new Set(outputs.flatMap((output) => output.output)
180
+ .map((item) => item.fileName)
181
+ .filter(isHashedClientAsset))].sort();
170
182
  const entry = outputs
171
183
  .flatMap((output) => output.output)
172
184
  .find((item) => item.type === "chunk" && item.isEntry);
@@ -195,22 +207,24 @@ async function buildClient(projectRoot, outputDirectory, manifests, config) {
195
207
  ${[...styles].map((file) => `<link rel="stylesheet" href="/${file}" />`).join("\n ")}
196
208
  </head>
197
209
  <body>
198
- <div id="ludicord-root"></div>
210
+ <div id="ludicord-root">${STARTUP_SHELL_HTML}</div>
199
211
  <script type="module" src="/${clientEntry}"></script>
200
212
  </body>
201
213
  </html>
202
214
  `, "utf8");
203
215
  return {
204
216
  clientEntry,
217
+ immutableAssets,
205
218
  bundleReport: createBundleReport(path.join(outputDirectory, "client"), clientEntry, config.build.clientAssetWarningLimit),
206
219
  };
207
220
  }
208
- function buildMetadata(clientEntry, api, websocket, instrumentation, proxy, bundleReport, config) {
221
+ function buildMetadata(clientEntry, immutableAssets, api, websocket, instrumentation, proxy, bundleReport, config) {
209
222
  return {
210
223
  buildSchemaVersion: LUDICORD_BUILD_SCHEMA_VERSION,
211
224
  frameworkVersion: LUDICORD_VERSION,
212
225
  createdAt: new Date().toISOString(),
213
226
  clientEntry,
227
+ immutableAssets,
214
228
  api,
215
229
  websocket,
216
230
  ...(instrumentation === undefined ? {} : { instrumentation }),
@@ -254,8 +268,8 @@ export async function buildLudicordProject(projectRoot) {
254
268
  const typeErrors = checkProjectTypes(root);
255
269
  if (typeErrors.length > 0)
256
270
  throw new Error(typeErrors.map((item) => `${item.file ?? "TypeScript"}:${item.line ?? 1}:${item.column ?? 1}\n${item.message}\n${item.frame ?? ""}`).join("\n\n"));
257
- const { clientEntry, bundleReport } = await buildClient(root, temporaryDirectory, manifests, config);
258
- const graph = await bundleServerGraph(root, path.join(temporaryDirectory, "server"), manifests, config.imports.aliases);
271
+ const { clientEntry, immutableAssets, bundleReport } = await buildClient(root, temporaryDirectory, manifests, config);
272
+ const graph = await bundleServerGraph(root, path.join(temporaryDirectory, "server"), manifests, config.imports.aliases, config.plugins, "production");
259
273
  const api = graph.bundles.filter((route) => route.kind === "api").map((route) => ({ source: route.source, bundle: `server/${route.bundle}` }));
260
274
  const websocket = graph.bundles.filter((route) => route.kind === "ws").map((route) => ({ source: route.source, bundle: `server/${route.bundle}` }));
261
275
  const instrumentationRoute = graph.bundles.find((route) => route.kind === "instrumentation");
@@ -268,8 +282,10 @@ export async function buildLudicordProject(projectRoot) {
268
282
  : { source: proxyRoute.source, bundle: `server/${proxyRoute.bundle}` };
269
283
  writeManifests(manifests, path.join(temporaryDirectory, "manifests"));
270
284
  mkdirSync(path.join(temporaryDirectory, "types"), { recursive: true });
285
+ writeFileSync(path.join(temporaryDirectory, "types", "routes.d.ts"), readFileSync(path.join(root, "ludicord.generated.d.ts"), "utf8"), "utf8");
286
+ writeFileSync(path.join(temporaryDirectory, "types", "plugins.d.ts"), readFileSync(path.join(root, "ludicord.plugins.generated.d.ts"), "utf8"), "utf8");
271
287
  writeFileSync(path.join(temporaryDirectory, "bundle-report.json"), `${JSON.stringify(bundleReport, null, 2)}\n`, "utf8");
272
- const metadata = buildMetadata(clientEntry, api, websocket, instrumentation, proxy, bundleReport, config);
288
+ const metadata = buildMetadata(clientEntry, immutableAssets, api, websocket, instrumentation, proxy, bundleReport, config);
273
289
  writeFileSync(path.join(temporaryDirectory, "build.json"), `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
274
290
  if (clientContainsSecret(path.join(temporaryDirectory, "client")))
275
291
  throw new Error("LUDICORD7001: Server secret detected in client output.");
@@ -0,0 +1,2 @@
1
+ /** Matches the content-hashed filenames emitted by the client compiler. */
2
+ export declare function isHashedClientAsset(file: string): boolean;
@@ -0,0 +1,5 @@
1
+ /** Matches the content-hashed filenames emitted by the client compiler. */
2
+ export function isHashedClientAsset(file) {
3
+ return /^assets\/(?:[^/]+\/)*[^/]+-[A-Za-z0-9_-]{8,}\.[^/]+$/.test(file) &&
4
+ !file.split("/").some((segment) => segment === "." || segment === "..");
5
+ }
@@ -11,27 +11,33 @@ export function clientEntry(root, manifests, config, development) {
11
11
  const imports = [
12
12
  `import React from "react";`,
13
13
  `import { createRoot } from "react-dom/client";`,
14
- `import { LudicordRoot, matchPageRoute } from "ludicord/internal";`,
14
+ `import { LudicordRoot, matchPageRoute, beginActivityStartup, deferredFile, startStartupStage, StartupError, reportClientError } from "ludicord/internal";`,
15
15
  `import { LudicordActivity } from "ludicord";`,
16
16
  `import { installLudicordLaunchIsolation } from "ludicord/auth";`,
17
17
  ];
18
18
  if (existsSync(path.join(root, "app", "globals.css"))) {
19
19
  imports.push(`import ${JSON.stringify(file("app/globals.css"))};`);
20
20
  }
21
- const activityDefinition = (activity, scopeIndex, bindings, loaders) => {
21
+ const activityDefinition = (activity, scopeIndex, bindings, loaders, declarations) => {
22
22
  const bindDefault = (name, source) => {
23
23
  bindings.push(name);
24
24
  loaders.push(`import(${JSON.stringify(file(source))}).then((module) => module.default)`);
25
25
  };
26
26
  const pages = `Pages_${scopeIndex}`;
27
- bindDefault(pages, activity.root);
27
+ declarations.push(`const finishPage = startStartupStage("page-module");
28
+ const pageModule = import(${JSON.stringify(file(activity.root))}).then((module) => { finishPage(); return module; }, (error) => { finishPage("error"); throw error; });
29
+ void pageModule.catch(() => undefined);
30
+ const ${pages} = React.lazy(() => pageModule);`);
28
31
  const components = [];
29
32
  for (const key of FILE_COMPONENTS) {
30
33
  const source = activity[key];
31
34
  if (source === undefined)
32
35
  continue;
33
36
  const name = `Scope_${scopeIndex}_${key}`;
34
- bindDefault(name, source);
37
+ if (key === "layout" || key === "loading")
38
+ bindDefault(name, source);
39
+ else
40
+ declarations.push(`const ${name} = deferredFile(() => import(${JSON.stringify(file(source))}));`);
35
41
  components.push(`${key}: ${name}`);
36
42
  }
37
43
  if (activity.metadata === undefined) {
@@ -44,24 +50,26 @@ export function clientEntry(root, manifests, config, development) {
44
50
  const scopeDefinition = (scope, scopeIndex) => {
45
51
  const bindings = [];
46
52
  const loaders = [];
47
- const bindDefault = (name, source) => {
48
- bindings.push(name);
49
- loaders.push(`import(${JSON.stringify(file(source))}).then((module) => module.default)`);
50
- };
51
- const activity = activityDefinition(scope.activity, scopeIndex, bindings, loaders);
53
+ const declarations = [];
54
+ const layoutNames = new Map();
55
+ const activity = activityDefinition(scope.activity, scopeIndex, bindings, loaders, declarations);
52
56
  const embeds = scope.embeds.map((route, routeIndex) => {
53
57
  const fields = [`load: () => import(${JSON.stringify(file(route.file))})`];
54
58
  for (const [key, source] of [["loading", route.loading], ["error", route.error]]) {
55
59
  if (source === undefined)
56
60
  continue;
57
61
  const name = `Scope_${scopeIndex}_Embed_${routeIndex}_${key}`;
58
- bindDefault(name, source);
62
+ declarations.push(`const ${name} = deferredFile(() => import(${JSON.stringify(file(source))}));`);
59
63
  fields.push(`${key}: ${name}`);
60
64
  }
61
65
  if (route.layouts !== undefined) {
62
- const layouts = route.layouts.map((source, layoutIndex) => {
63
- const name = `Scope_${scopeIndex}_Embed_${routeIndex}_layout_${layoutIndex}`;
64
- bindDefault(name, source);
66
+ const layouts = route.layouts.map((source) => {
67
+ const existing = layoutNames.get(source);
68
+ if (existing !== undefined)
69
+ return existing;
70
+ const name = `Scope_${scopeIndex}_layout_${layoutNames.size}`;
71
+ layoutNames.set(source, name);
72
+ declarations.push(`const ${name} = React.lazy(() => import(${JSON.stringify(file(source))}));`);
65
73
  return name;
66
74
  });
67
75
  fields.push(`layouts: [${layouts.join(",")}]`);
@@ -69,6 +77,7 @@ export function clientEntry(root, manifests, config, development) {
69
77
  return `${JSON.stringify(route.route)}: { ${fields.join(", ")} }`;
70
78
  });
71
79
  return `${JSON.stringify(scope.prefix)}: async () => {
80
+ ${declarations.join("\n ")}
72
81
  const [${bindings.join(",")}] = await Promise.all([${loaders.join(",")}]);
73
82
  return { Pages: ${activity.pages}, managedActivity: ${scope.activity.managedActivity === true}, files: ${activity.files}, metadata: ${activity.metadata}, embeds: {${embeds.join(",\n")} } };
74
83
  }`;
@@ -87,6 +96,7 @@ export function clientEntry(root, manifests, config, development) {
87
96
  websocket: { enabled: config.websocket.enabled, reconnect: config.websocket.reconnect },
88
97
  };
89
98
  return `${imports.join("\n")}
99
+ const disposeStartup = beginActivityStartup();
90
100
  const prefixScopes = {${scopeDefinitions.join(",\n")}};
91
101
  const normalizePrefix = (value) => {
92
102
  const pathname = value.replace(/\\/{2,}/g, "/").replace(/\\/$/, "");
@@ -105,10 +115,15 @@ globalThis.__LUDICORD_ACTIVE_PREFIX__ = activePrefix;
105
115
  globalThis.__LUDICORD_PAGE_PARAMS__ = selectedPage?.match.params ?? {};
106
116
  installLudicordLaunchIsolation();
107
117
  let mountedRoot;
118
+ let disposed = false;
108
119
  const bootPrefix = async () => {
120
+ const finishScope = startStartupStage("scope");
121
+ try {
109
122
  const loadScope = selectedPage && prefixScopes[selectedPage.scope.prefix];
110
123
  if (!loadScope) throw new Error('LUDICORD2004: Unknown Activity prefix "' + activePrefix + '".');
111
124
  const selectedScope = await loadScope();
125
+ finishScope();
126
+ if (disposed) return;
112
127
  globalThis.__LUDICORD_EMBEDS__ = selectedScope.embeds;
113
128
  const container = document.getElementById("ludicord-root");
114
129
  if (!container) throw new Error("LUDICORD2003: Missing #ludicord-root container.");
@@ -117,7 +132,17 @@ const bootPrefix = async () => {
117
132
  const content = selectedScope.managedActivity ? React.createElement(LudicordActivity, { defaultEmbed: ${JSON.stringify(config.activity.defaultEmbed)} }, page) : page;
118
133
  const activity = React.createElement(LudicordRoot, { files: selectedScope.files, metadata: selectedScope.metadata }, content);
119
134
  mountedRoot.render(${config.react.strictMode ? "React.createElement(React.StrictMode, null, activity)" : "activity"});
135
+ } catch (error) { finishScope("error"); throw error; }
120
136
  };
121
- void bootPrefix();
122
- ${development ? `if (import.meta.hot) import.meta.hot.dispose(() => mountedRoot?.unmount());` : ""}`;
137
+ const bootPromise = bootPrefix().catch((error) => {
138
+ if (disposed) return;
139
+ reportClientError(error instanceof Error ? error : new Error(String(error)));
140
+ if (globalThis.__LUDICORD_PUBLIC_CONFIG__.environment === "development") console.error(error);
141
+ const container = document.getElementById("ludicord-root");
142
+ if (container) {
143
+ mountedRoot ??= createRoot(container);
144
+ mountedRoot.render(React.createElement(StartupError));
145
+ }
146
+ });
147
+ ${development ? `if (import.meta.hot) import.meta.hot.dispose(() => { disposed = true; disposeStartup(); mountedRoot?.unmount(); });` : ""}`;
123
148
  }
@@ -0,0 +1,5 @@
1
+ import type { Plugin as EsbuildPlugin } from "esbuild";
2
+ import type { Plugin as VitePlugin } from "vite";
3
+ import type { LudicordPlugin, LudicordPluginMode } from "../config/types.js";
4
+ export declare function vitePluginAdapters(plugins: readonly LudicordPlugin[], projectRoot: string, mode: LudicordPluginMode): VitePlugin[];
5
+ export declare function esbuildPluginAdapter(plugins: readonly LudicordPlugin[], projectRoot: string, mode: LudicordPluginMode): EsbuildPlugin | undefined;
@@ -0,0 +1,155 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ function pluginError(plugin, hook, error) {
4
+ const message = error instanceof Error ? error.message : String(error);
5
+ return new Error(`LUDICORD8001: Plugin "${plugin.name}" failed in ${hook}: ${message}`, {
6
+ cause: error,
7
+ });
8
+ }
9
+ function resultCode(result) {
10
+ if (typeof result === "string")
11
+ return result;
12
+ return result?.code;
13
+ }
14
+ function loaderForFile(file) {
15
+ const extension = path.extname(file).slice(1).toLowerCase();
16
+ if (["js", "jsx", "ts", "tsx", "json", "text", "css"].includes(extension)) {
17
+ return extension;
18
+ }
19
+ if (extension === "mjs" || extension === "cjs")
20
+ return "js";
21
+ if (extension === "mts" || extension === "cts")
22
+ return "ts";
23
+ return undefined;
24
+ }
25
+ function context(projectRoot, mode, target) {
26
+ return { projectRoot, mode, target };
27
+ }
28
+ function orderedPlugins(plugins) {
29
+ const rank = (plugin) => plugin.enforce === "pre" ? 0 : plugin.enforce === "post" ? 2 : 1;
30
+ return [...plugins].sort((left, right) => rank(left) - rank(right));
31
+ }
32
+ export function vitePluginAdapters(plugins, projectRoot, mode) {
33
+ const hookContext = context(projectRoot, mode, "client");
34
+ return orderedPlugins(plugins).map((plugin) => ({
35
+ name: `ludicord:user:${plugin.name}`,
36
+ ...(plugin.enforce === undefined ? {} : { enforce: plugin.enforce }),
37
+ async resolveId(id, importer) {
38
+ if (plugin.resolveId === undefined)
39
+ return undefined;
40
+ try {
41
+ return await plugin.resolveId(id, importer, hookContext);
42
+ }
43
+ catch (error) {
44
+ throw pluginError(plugin, "resolveId", error);
45
+ }
46
+ },
47
+ async load(id) {
48
+ if (plugin.load === undefined)
49
+ return undefined;
50
+ try {
51
+ const result = await plugin.load(id, hookContext);
52
+ if (result === null || result === undefined)
53
+ return undefined;
54
+ return typeof result === "string" ? result : { code: result.code, map: result.map ?? null };
55
+ }
56
+ catch (error) {
57
+ throw pluginError(plugin, "load", error);
58
+ }
59
+ },
60
+ async transform(code, id) {
61
+ if (plugin.transform === undefined)
62
+ return undefined;
63
+ try {
64
+ const result = await plugin.transform(code, id, hookContext);
65
+ if (result === null || result === undefined)
66
+ return undefined;
67
+ return typeof result === "string" ? result : { code: result.code, map: result.map ?? null };
68
+ }
69
+ catch (error) {
70
+ throw pluginError(plugin, "transform", error);
71
+ }
72
+ },
73
+ }));
74
+ }
75
+ export function esbuildPluginAdapter(plugins, projectRoot, mode) {
76
+ if (plugins.length === 0)
77
+ return undefined;
78
+ const hookContext = context(projectRoot, mode, "server");
79
+ const ordered = orderedPlugins(plugins);
80
+ return {
81
+ name: "ludicord:user-plugins",
82
+ setup(build) {
83
+ if (ordered.some((plugin) => plugin.resolveId !== undefined)) {
84
+ build.onResolve({ filter: /.*/ }, async (args) => {
85
+ for (const plugin of ordered) {
86
+ if (plugin.resolveId === undefined)
87
+ continue;
88
+ try {
89
+ const result = await plugin.resolveId(args.path, args.importer || undefined, hookContext);
90
+ if (result !== null && result !== undefined) {
91
+ if (path.isAbsolute(result))
92
+ return { path: result };
93
+ if (result.startsWith("\0") || /^[a-z][a-z0-9+.-]*:/i.test(result)) {
94
+ return { path: result, namespace: "ludicord-plugin" };
95
+ }
96
+ return { path: path.resolve(args.resolveDir || projectRoot, result) };
97
+ }
98
+ }
99
+ catch (error) {
100
+ return { errors: [{ text: pluginError(plugin, "resolveId", error).message }] };
101
+ }
102
+ }
103
+ return undefined;
104
+ });
105
+ }
106
+ build.onLoad({ filter: /.*/ }, async (args) => {
107
+ let code;
108
+ let loader;
109
+ for (const plugin of ordered) {
110
+ if (plugin.load === undefined)
111
+ continue;
112
+ try {
113
+ const result = await plugin.load(args.path, hookContext);
114
+ const loaded = resultCode(result);
115
+ if (loaded !== undefined) {
116
+ code = loaded;
117
+ if (typeof result === "object" && result !== null && result.loader !== undefined) {
118
+ loader = result.loader;
119
+ }
120
+ break;
121
+ }
122
+ }
123
+ catch (error) {
124
+ return { errors: [{ text: pluginError(plugin, "load", error).message }] };
125
+ }
126
+ }
127
+ const transformers = ordered.filter((plugin) => plugin.transform !== undefined);
128
+ if (code === undefined && transformers.length > 0) {
129
+ loader = loaderForFile(args.path);
130
+ if (loader === undefined || loader === "text")
131
+ return undefined;
132
+ code = await readFile(args.path, "utf8");
133
+ }
134
+ if (code === undefined)
135
+ return undefined;
136
+ for (const plugin of transformers) {
137
+ try {
138
+ const result = await plugin.transform?.(code, args.path, hookContext);
139
+ const transformed = resultCode(result);
140
+ if (transformed !== undefined) {
141
+ code = transformed;
142
+ if (typeof result === "object" && result !== null && result.loader !== undefined) {
143
+ loader = result.loader;
144
+ }
145
+ }
146
+ }
147
+ catch (error) {
148
+ return { errors: [{ text: pluginError(plugin, "transform", error).message }] };
149
+ }
150
+ }
151
+ return { contents: code, loader: loader ?? "js", resolveDir: path.dirname(args.path) };
152
+ });
153
+ },
154
+ };
155
+ }
@@ -1,5 +1,6 @@
1
1
  import type { LudicordManifests } from "../manifests/types.js";
2
- export declare function bundleServerGraph(root: string, output: string, manifests: LudicordManifests, projectAliases?: Readonly<Record<string, string>>): Promise<{
2
+ import type { LudicordPlugin, LudicordPluginMode } from "../config/types.js";
3
+ export declare function bundleServerGraph(root: string, output: string, manifests: LudicordManifests, projectAliases?: Readonly<Record<string, string>>, plugins?: readonly LudicordPlugin[], mode?: LudicordPluginMode): Promise<{
3
4
  bundles: {
4
5
  source: string;
5
6
  bundle: string;
@@ -1,7 +1,8 @@
1
1
  import path from "node:path";
2
2
  import { pathToFileURL } from "node:url";
3
3
  import { build } from "esbuild";
4
- export async function bundleServerGraph(root, output, manifests, projectAliases = { "@": "." }) {
4
+ import { esbuildPluginAdapter } from "./plugin-runtime.js";
5
+ export async function bundleServerGraph(root, output, manifests, projectAliases = { "@": "." }, plugins = [], mode = "production") {
5
6
  const routes = [...manifests.api.map((route, index) => ({ ...route, name: `api/${index}` })),
6
7
  ...manifests.websocket.map((route, index) => ({ ...route, name: `ws/${index}` })),
7
8
  ...(manifests.activity.instrumentation === undefined ? [] : [{
@@ -17,6 +18,7 @@ export async function bundleServerGraph(root, output, manifests, projectAliases
17
18
  const bundles = routes.map((route) => ({ source: route.file, bundle: `${route.name}.mjs`, kind: route.kind }));
18
19
  const dependencies = new Set();
19
20
  if (routes.length > 0) {
21
+ const plugin = esbuildPluginAdapter(plugins, root, mode);
20
22
  const result = await build({
21
23
  absWorkingDir: root,
22
24
  entryPoints: routes.map((route) => ({ in: path.join(root, route.file), out: route.name })),
@@ -24,6 +26,7 @@ export async function bundleServerGraph(root, output, manifests, projectAliases
24
26
  chunkNames: "shared/[name]-[hash]", platform: "node", format: "esm", target: "node20",
25
27
  bundle: true, splitting: true, sourcemap: true, packages: "external", logLevel: "silent", metafile: true,
26
28
  alias: Object.fromEntries(Object.entries(projectAliases).map(([alias, target]) => [alias, path.resolve(root, target)])),
29
+ ...(plugin === undefined ? {} : { plugins: [plugin] }),
27
30
  });
28
31
  for (const input of Object.keys(result.metafile.inputs))
29
32
  dependencies.add(path.resolve(root, input));
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs";
2
2
  import path from "node:path";
3
3
  const LUDICORD_ENV_REFERENCE = '/// <reference path="./ludicord.generated.d.ts" />';
4
+ const LUDICORD_PLUGIN_ENV_REFERENCE = '/// <reference path="./ludicord.plugins.generated.d.ts" />';
4
5
  function templateSegment(segment) {
5
6
  if (segment.startsWith(":"))
6
7
  return "${string}";
@@ -90,20 +91,35 @@ ${routeParams(manifests.websocket)}
90
91
  function ensureLudicordEnv(projectRoot) {
91
92
  const file = path.join(projectRoot, "ludicord-env.d.ts");
92
93
  const current = existsSync(file) ? readFileSync(file, "utf8") : "";
93
- if (current.includes(LUDICORD_ENV_REFERENCE))
94
+ const references = [LUDICORD_ENV_REFERENCE, LUDICORD_PLUGIN_ENV_REFERENCE]
95
+ .filter((reference) => !current.includes(reference));
96
+ if (references.length === 0)
94
97
  return;
95
- writeFileSync(file, `${LUDICORD_ENV_REFERENCE}\n${current === "" ? "" : `\n${current}`}`, "utf8");
98
+ writeFileSync(file, `${references.join("\n")}\n${current === "" ? "" : `\n${current}`}`, "utf8");
99
+ }
100
+ function pluginDeclarations(config) {
101
+ const declarations = config.plugins
102
+ .map((plugin) => plugin.declarations?.trim())
103
+ .filter((declaration) => Boolean(declaration));
104
+ return `// Generated by Ludicord plugins. Changes will be replaced by ludicord dev or ludicord build.\n${declarations.join("\n\n")}${declarations.length === 0 ? "" : "\n"}`;
96
105
  }
97
106
  export function generateLudicordTypes(projectRoot, manifests, config) {
98
107
  const root = path.resolve(projectRoot);
99
108
  const source = generatedSource(manifests, config);
109
+ const pluginSource = pluginDeclarations(config);
100
110
  const publicFile = path.join(root, "ludicord.generated.d.ts");
111
+ const publicPluginFile = path.join(root, "ludicord.plugins.generated.d.ts");
101
112
  const internalFile = path.join(root, ".ludicord", "types", "routes.d.ts");
113
+ const internalPluginFile = path.join(root, ".ludicord", "types", "plugins.d.ts");
102
114
  mkdirSync(path.dirname(internalFile), { recursive: true });
103
115
  if (!existsSync(publicFile) || readFileSync(publicFile, "utf8") !== source)
104
116
  writeFileSync(publicFile, source, "utf8");
117
+ if (!existsSync(publicPluginFile) || readFileSync(publicPluginFile, "utf8") !== pluginSource)
118
+ writeFileSync(publicPluginFile, pluginSource, "utf8");
105
119
  if (!existsSync(internalFile) || readFileSync(internalFile, "utf8") !== source)
106
120
  writeFileSync(internalFile, source, "utf8");
121
+ if (!existsSync(internalPluginFile) || readFileSync(internalPluginFile, "utf8") !== pluginSource)
122
+ writeFileSync(internalPluginFile, pluginSource, "utf8");
107
123
  ensureLudicordEnv(root);
108
124
  return publicFile;
109
125
  }
@@ -1,6 +1,8 @@
1
1
  export function resolveConfig(config = {}) {
2
2
  const clientId = config.discord?.clientId ?? process.env.LUDICORD_DISCORD_CLIENT_ID;
3
+ const plugins = (config.plugins ?? []).filter((plugin) => Boolean(plugin));
3
4
  const resolved = {
5
+ plugins,
4
6
  discord: {
5
7
  ...(clientId === undefined ? {} : { clientId }),
6
8
  scopes: [...(config.discord?.scopes ?? ["identify"])],
@@ -99,6 +101,22 @@ export function resolveConfig(config = {}) {
99
101
  fail("discord.scopes");
100
102
  if (resolved.discord.auth.activityInstanceVerification !== "auto" && typeof resolved.discord.auth.activityInstanceVerification !== "boolean")
101
103
  fail("discord.auth.activityInstanceVerification");
104
+ const pluginNames = new Set();
105
+ for (const plugin of resolved.plugins) {
106
+ if (typeof plugin !== "object" || typeof plugin.name !== "string" || !/^[a-z0-9][a-z0-9:_./-]*$/i.test(plugin.name))
107
+ fail("plugins");
108
+ if (pluginNames.has(plugin.name))
109
+ fail(`plugins (duplicate ${plugin.name})`);
110
+ pluginNames.add(plugin.name);
111
+ if (plugin.enforce !== undefined && plugin.enforce !== "pre" && plugin.enforce !== "post")
112
+ fail(`plugins (${plugin.name}.enforce)`);
113
+ if (plugin.declarations !== undefined && typeof plugin.declarations !== "string")
114
+ fail(`plugins (${plugin.name}.declarations)`);
115
+ for (const hook of ["resolveId", "load", "transform"]) {
116
+ if (plugin[hook] !== undefined && typeof plugin[hook] !== "function")
117
+ fail(`plugins (${plugin.name}.${hook})`);
118
+ }
119
+ }
102
120
  for (const [field, value] of Object.entries({ "discord.auth.required": resolved.discord.auth.required, "discord.auth.proxyVerification": resolved.discord.auth.proxyVerification, "react.strictMode": resolved.react.strictMode, "websocket.enabled": resolved.websocket.enabled, "websocket.compression": resolved.websocket.compression, "websocket.reconnect.enabled": resolved.websocket.reconnect.enabled })) {
103
121
  if (typeof value !== "boolean")
104
122
  fail(field);
@@ -1,2 +1,2 @@
1
- export { defineConfig } from "./types.js";
2
- export type { LudicordActivityConfig, LudicordAuthConfig, LudicordConfig, LudicordDiscordConfig, LudicordImportsConfig, LudicordReconnectConfig, LudicordServerConfig, LudicordServerLimits, LudicordWebSocketConfig, OutsideDiscordBehavior, ResolvedLudicordConfig, } from "./types.js";
1
+ export { defineConfig, definePlugin } from "./types.js";
2
+ export type { LudicordActivityConfig, LudicordAuthConfig, LudicordConfig, LudicordDiscordConfig, LudicordImportsConfig, LudicordPlugin, LudicordPluginContext, LudicordPluginHookResult, LudicordPluginLoadResult, LudicordPluginMode, LudicordPluginOption, LudicordPluginTarget, LudicordReconnectConfig, LudicordServerConfig, LudicordServerLimits, LudicordWebSocketConfig, OutsideDiscordBehavior, ResolvedLudicordConfig, } from "./types.js";
@@ -1 +1 @@
1
- export { defineConfig } from "./types.js";
1
+ export { defineConfig, definePlugin } from "./types.js";
@@ -71,7 +71,37 @@ export interface LudicordWebSocketConfig {
71
71
  maxQueuedMessages?: number;
72
72
  reconnect?: LudicordReconnectConfig;
73
73
  }
74
+ export type LudicordPluginMode = "development" | "production";
75
+ export type LudicordPluginTarget = "client" | "server";
76
+ export interface LudicordPluginContext {
77
+ /** Absolute Activity project root. */
78
+ readonly projectRoot: string;
79
+ readonly mode: LudicordPluginMode;
80
+ readonly target: LudicordPluginTarget;
81
+ }
82
+ export interface LudicordPluginLoadResult {
83
+ readonly code: string;
84
+ /** Controls how server builds parse the returned module. Defaults to `js`. */
85
+ readonly loader?: "js" | "jsx" | "ts" | "tsx" | "json" | "text" | "css";
86
+ /** JSON-encoded source map for transformed text modules. */
87
+ readonly map?: string;
88
+ }
89
+ export type LudicordPluginHookResult = string | LudicordPluginLoadResult | null | undefined;
90
+ /** A compiler extension registered through `ludicord.config.mjs`. */
91
+ export interface LudicordPlugin {
92
+ /** Stable, diagnostic-friendly plugin name. */
93
+ readonly name: string;
94
+ readonly enforce?: "pre" | "post";
95
+ /** Ambient declarations written into Ludicord's generated plugin types. */
96
+ readonly declarations?: string;
97
+ resolveId?(id: string, importer: string | undefined, context: LudicordPluginContext): string | null | undefined | Promise<string | null | undefined>;
98
+ load?(id: string, context: LudicordPluginContext): LudicordPluginHookResult | Promise<LudicordPluginHookResult>;
99
+ transform?(code: string, id: string, context: LudicordPluginContext): LudicordPluginHookResult | Promise<LudicordPluginHookResult>;
100
+ }
101
+ /** Falsey entries make environment-dependent plugin arrays easy to compose. */
102
+ export type LudicordPluginOption = LudicordPlugin | false | null | undefined;
74
103
  export interface LudicordConfig {
104
+ plugins?: readonly LudicordPluginOption[];
75
105
  discord?: LudicordDiscordConfig;
76
106
  activity?: LudicordActivityConfig;
77
107
  react?: LudicordReactConfig;
@@ -81,6 +111,7 @@ export interface LudicordConfig {
81
111
  websocket?: LudicordWebSocketConfig;
82
112
  }
83
113
  export interface ResolvedLudicordConfig {
114
+ plugins: readonly LudicordPlugin[];
84
115
  discord: {
85
116
  clientId?: string;
86
117
  scopes: readonly string[];
@@ -135,3 +166,4 @@ export interface ResolvedLudicordConfig {
135
166
  };
136
167
  }
137
168
  export declare function defineConfig<const TConfig extends LudicordConfig>(config: TConfig): TConfig;
169
+ export declare function definePlugin<const TPlugin extends LudicordPlugin>(plugin: TPlugin): TPlugin;
@@ -1,3 +1,6 @@
1
1
  export function defineConfig(config) {
2
2
  return config;
3
3
  }
4
+ export function definePlugin(plugin) {
5
+ return plugin;
6
+ }
@@ -1,6 +1,6 @@
1
1
  # Ludicord documentation
2
2
 
3
- > Documentation for Ludicord 4.0.1. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
3
+ > Documentation for Ludicord 4.1.1. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
4
4
 
5
5
 
6
6
  ## Learn Ludicord
@@ -8,6 +8,7 @@
8
8
  - [Getting Started](getting-started.md)
9
9
  - [Installation](installation.md)
10
10
  - [Project Structure](project-structure.md)
11
+ - [Plugins and WebAssembly](plugins.md)
11
12
  - [AI coding agents and bundled docs](ai-agents.md)
12
13
  - [Page scopes and optional prefix navigation](prefix-router.md)
13
14
  - [Pages: page.tsx](pages.md)
@@ -1,6 +1,6 @@
1
1
  # Activity Rooms
2
2
 
3
- > Documentation for Ludicord 4.0.1. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
3
+ > Documentation for Ludicord 4.1.1. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
4
4
 
5
5
 
6
6
  Every authenticated WebSocket client can join the Activity Instance room: