ludicord 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/AGENTS.md +2 -0
  2. package/README.md +6 -2
  3. package/dist/compiler/build.js +14 -2
  4. package/dist/compiler/client-entry.js +7 -1
  5. package/dist/compiler/plugin-runtime.d.ts +5 -0
  6. package/dist/compiler/plugin-runtime.js +155 -0
  7. package/dist/compiler/server-bundle.d.ts +2 -1
  8. package/dist/compiler/server-bundle.js +4 -1
  9. package/dist/compiler/type-generation.js +18 -2
  10. package/dist/config/defaults.js +18 -0
  11. package/dist/config/index.d.ts +2 -2
  12. package/dist/config/index.js +1 -1
  13. package/dist/config/types.d.ts +32 -0
  14. package/dist/config/types.js +3 -0
  15. package/dist/docs/README.md +2 -1
  16. package/dist/docs/activity-rooms.md +1 -1
  17. package/dist/docs/ai-agents.md +28 -7
  18. package/dist/docs/api-reference.md +7 -3
  19. package/dist/docs/api-routes.md +1 -1
  20. package/dist/docs/build.md +1 -1
  21. package/dist/docs/cli.md +2 -2
  22. package/dist/docs/configuration.md +9 -1
  23. package/dist/docs/deployment.md +4 -2
  24. package/dist/docs/development.md +2 -2
  25. package/dist/docs/discord-developer-portal.md +1 -1
  26. package/dist/docs/discord-sdk.md +1 -1
  27. package/dist/docs/distribution.md +1 -1
  28. package/dist/docs/embeds.md +1 -1
  29. package/dist/docs/environment-variables.md +4 -2
  30. package/dist/docs/getting-started.md +1 -1
  31. package/dist/docs/installation.md +2 -2
  32. package/dist/docs/login.md +1 -1
  33. package/dist/docs/migration.md +5 -5
  34. package/dist/docs/mobile-layout.md +1 -1
  35. package/dist/docs/navigation.md +1 -1
  36. package/dist/docs/pages.md +1 -1
  37. package/dist/docs/participants.md +1 -1
  38. package/dist/docs/plugins.md +93 -0
  39. package/dist/docs/prefix-router.md +1 -1
  40. package/dist/docs/project-structure.md +2 -1
  41. package/dist/docs/recipes.md +1 -1
  42. package/dist/docs/security.md +4 -2
  43. package/dist/docs/start.md +1 -1
  44. package/dist/docs/state-and-effects.md +1 -1
  45. package/dist/docs/troubleshooting.md +2 -1
  46. package/dist/docs/voice-events.md +1 -1
  47. package/dist/docs/websockets.md +1 -1
  48. package/dist/lint/index.js +1 -1
  49. package/dist/plugins/index.d.ts +2 -0
  50. package/dist/plugins/index.js +1 -0
  51. package/dist/plugins/wasm.d.ts +7 -0
  52. package/dist/plugins/wasm.js +52 -0
  53. package/dist/runtime/server/dev-server.js +3 -2
  54. package/dist/runtime/server/production-server.js +34 -5
  55. package/dist/server/request-security.js +2 -1
  56. package/dist/skills/ludicord/SKILL.md +11 -6
  57. package/dist/skills/ludicord/manifest.yaml +4 -1
  58. package/dist/skills/ludicord/references/auth-security.md +5 -3
  59. package/dist/skills/ludicord/references/config-deploy.md +11 -2
  60. package/dist/skills/ludicord/references/intelligence/skill-router.md +2 -2
  61. package/dist/version.js +1 -1
  62. 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
 
@@ -34,12 +36,14 @@ Discord helpers include complete raw user/channel/guild/member/role/participant/
34
36
 
35
37
  Activity hooks add application-, instance-, user-, guild-, and channel-scoped persistence, cached queries, lifecycle readiness, raw Discord-event callbacks, presence summaries, animation frames, and revision-safe shared instance state. Use normal React state for local UI and these helpers where Discord Activity behavior needs a framework-owned lifecycle.
36
38
 
37
- V4 adds independently mounted pathname scopes, prefix-aware generated types, `PrefixLink`, `prefixHref()`, `useActivityPrefix()`, `usePageParams()`, project-root `@/` imports, listener-first compiler recovery, a PAGE/HTTP/SOCKET/EMBED route table, and a redesigned development diagnostics surface. Read the [V4 Prefix Router guide](https://github.com/mrcholer/ludicord/blob/main/docs/prefix-router.md), [migration guide](https://github.com/mrcholer/ludicord/blob/main/docs/migration-v4.md), and [4.0.0 release notes](https://github.com/mrcholer/ludicord/blob/main/releases/v4/4.0.0.md).
39
+ V4 adds independently mounted pathname scopes, prefix-aware generated types, `PrefixLink`, `prefixHref()`, `useActivityPrefix()`, `usePageParams()`, project-root `@/` imports, listener-first compiler recovery, a PAGE/HTTP/SOCKET/EMBED route table, and a redesigned development diagnostics surface. Ludicord 4.0.1 fixes Discord iframe navigation and keeps the runtime Discord application ID consistent across the client, HTTP, authentication, and WebSockets. Read the [V4 Prefix Router guide](https://github.com/mrcholer/ludicord/blob/main/docs/prefix-router.md), [migration guide](https://github.com/mrcholer/ludicord/blob/main/docs/migration-v4.md), and [4.0.1 release notes](https://github.com/mrcholer/ludicord/blob/main/releases/v4/4.0.1.md).
38
40
 
39
41
  V4 includes the production authentication, Activity-launch isolation, realtime reliability, and multi-process adapters introduced in 3.1.
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
@@ -15,6 +15,7 @@ import { loadProjectEnvironment } from "../config/environment.js";
15
15
  import { clientContainsSecret } from "../security/secret-scan.js";
16
16
  import { checkProjectTypes } from "../runtime/server/diagnostics.js";
17
17
  import { createBundleReport } from "./bundle-report.js";
18
+ import { vitePluginAdapters } from "./plugin-runtime.js";
18
19
  const VIRTUAL_BUILD_ENTRY = "virtual:ludicord-production-entry";
19
20
  const RESOLVED_BUILD_ENTRY = "\0virtual:ludicord-production-entry";
20
21
  export const LUDICORD_BUILD_SCHEMA_VERSION = 4;
@@ -22,6 +23,11 @@ const STALE_BUILD_DIRECTORY = /^\.ludicord-(?:build|previous)-\d+-[0-9a-f-]+$/i;
22
23
  const STALE_BUILD_AGE_MS = 24 * 60 * 60 * 1_000;
23
24
  function frameworkWarnings(config, manifests) {
24
25
  const warnings = [];
26
+ const usesDiscordActivityOrigins = config.server.allowedOrigins === "discord-activity" ||
27
+ (Array.isArray(config.server.allowedOrigins) && config.server.allowedOrigins.includes("discord-activity"));
28
+ if (usesDiscordActivityOrigins && config.discord.clientId === undefined) {
29
+ warnings.push("LUDICORD_DISCORD_CLIENT_ID is missing. Provide it at build time or production start so Discord Activity HTTP, auth, and WebSocket connections use the same application origin.");
30
+ }
25
31
  if (config.discord.auth.required) {
26
32
  if (config.discord.auth.activityInstanceVerification === false) {
27
33
  warnings.push("Discord Activity instance verification is disabled. Browser-provided guild, channel, and instance identity is not authoritative.");
@@ -145,7 +151,11 @@ async function buildClient(projectRoot, outputDirectory, manifests, config) {
145
151
  publicDir: existsSync(path.join(projectRoot, "public"))
146
152
  ? path.join(projectRoot, "public")
147
153
  : false,
148
- plugins: [buildPlugin(projectRoot, manifests, config), ...await clientPlugins(projectRoot)],
154
+ plugins: [
155
+ buildPlugin(projectRoot, manifests, config),
156
+ ...vitePluginAdapters(config.plugins, projectRoot, "production"),
157
+ ...await clientPlugins(projectRoot),
158
+ ],
149
159
  resolve: { alias: ludicordClientAliases(projectRoot, config.imports.aliases), dedupe: ["react", "react-dom"] },
150
160
  build: {
151
161
  outDir: path.join(outputDirectory, "client"),
@@ -250,7 +260,7 @@ export async function buildLudicordProject(projectRoot) {
250
260
  if (typeErrors.length > 0)
251
261
  throw new Error(typeErrors.map((item) => `${item.file ?? "TypeScript"}:${item.line ?? 1}:${item.column ?? 1}\n${item.message}\n${item.frame ?? ""}`).join("\n\n"));
252
262
  const { clientEntry, bundleReport } = await buildClient(root, temporaryDirectory, manifests, config);
253
- const graph = await bundleServerGraph(root, path.join(temporaryDirectory, "server"), manifests, config.imports.aliases);
263
+ const graph = await bundleServerGraph(root, path.join(temporaryDirectory, "server"), manifests, config.imports.aliases, config.plugins, "production");
254
264
  const api = graph.bundles.filter((route) => route.kind === "api").map((route) => ({ source: route.source, bundle: `server/${route.bundle}` }));
255
265
  const websocket = graph.bundles.filter((route) => route.kind === "ws").map((route) => ({ source: route.source, bundle: `server/${route.bundle}` }));
256
266
  const instrumentationRoute = graph.bundles.find((route) => route.kind === "instrumentation");
@@ -263,6 +273,8 @@ export async function buildLudicordProject(projectRoot) {
263
273
  : { source: proxyRoute.source, bundle: `server/${proxyRoute.bundle}` };
264
274
  writeManifests(manifests, path.join(temporaryDirectory, "manifests"));
265
275
  mkdirSync(path.join(temporaryDirectory, "types"), { recursive: true });
276
+ writeFileSync(path.join(temporaryDirectory, "types", "routes.d.ts"), readFileSync(path.join(root, "ludicord.generated.d.ts"), "utf8"), "utf8");
277
+ writeFileSync(path.join(temporaryDirectory, "types", "plugins.d.ts"), readFileSync(path.join(root, "ludicord.plugins.generated.d.ts"), "utf8"), "utf8");
266
278
  writeFileSync(path.join(temporaryDirectory, "bundle-report.json"), `${JSON.stringify(bundleReport, null, 2)}\n`, "utf8");
267
279
  const metadata = buildMetadata(clientEntry, api, websocket, instrumentation, proxy, bundleReport, config);
268
280
  writeFileSync(path.join(temporaryDirectory, "build.json"), `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
@@ -94,7 +94,13 @@ const normalizePrefix = (value) => {
94
94
  };
95
95
  const activePrefix = normalizePrefix(window.location.pathname);
96
96
  const selectedPage = matchPageRoute(Object.keys(prefixScopes).map((prefix) => ({ prefix })), activePrefix);
97
- globalThis.__LUDICORD_PUBLIC_CONFIG__ = ${JSON.stringify(publicConfig)};
97
+ let runtimePublicConfig = {};
98
+ const runtimePublicConfigElement = document.getElementById("ludicord-runtime-config");
99
+ if (runtimePublicConfigElement?.textContent) {
100
+ try { runtimePublicConfig = JSON.parse(runtimePublicConfigElement.textContent); }
101
+ catch { runtimePublicConfig = {}; }
102
+ }
103
+ globalThis.__LUDICORD_PUBLIC_CONFIG__ = { ...${JSON.stringify(publicConfig)}, ...runtimePublicConfig };
98
104
  globalThis.__LUDICORD_ACTIVE_PREFIX__ = activePrefix;
99
105
  globalThis.__LUDICORD_PAGE_PARAMS__ = selectedPage?.match.params ?? {};
100
106
  installLudicordLaunchIsolation();
@@ -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.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
3
+ > Documentation for Ludicord 4.1.0. 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.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
3
+ > Documentation for Ludicord 4.1.0. 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:
@@ -1,6 +1,6 @@
1
1
  # AI coding agents
2
2
 
3
- Ludicord 4.0.0 ships documentation and agent skills with the npm package. They
3
+ Ludicord 4.1.0 ships documentation and agent skills with the npm package. They
4
4
  are available offline and change together with the installed framework:
5
5
 
6
6
  ```text
@@ -21,6 +21,18 @@ reusable skill stay under `dist/`. Upgrading Ludicord upgrades all of these
21
21
  resources. The generated application receives no extra agent file, and no
22
22
  postinstall hook or external docs download is required.
23
23
 
24
+ ## Install from skills.sh
25
+
26
+ Install the public skill from the canonical repository:
27
+
28
+ ```bash
29
+ npx skills add mrcholer/ludicord --skill ludicord
30
+ ```
31
+
32
+ The searchable listing is [Ludicord on skills.sh](https://skills.sh/mrcholer/ludicord/ludicord).
33
+ The public copy helps discovery, while the skill under
34
+ `node_modules/ludicord/dist/skills/` stays version-matched to the project.
35
+
24
36
  For an existing project, add this instruction to its existing `AGENTS.md`,
25
37
  preserving the project's own rules:
26
38
 
@@ -36,15 +48,24 @@ package manager uses a different layout, locate `ludicord/package.json` with
36
48
  the project's resolver and read `dist` beside it. Read only task-relevant
37
49
  references; do not load the entire documentation tree on every request.
38
50
 
39
- ## Prefix routing is optional
51
+ ## Additional pathname pages are optional
40
52
 
41
53
  Agents should keep ordinary applications on `app/page.tsx` and `app/`.
42
- Use prefixes only when project scale calls for independent product surfaces,
43
- or an important requirement needs distinct pathname entry points, shells, or
44
- provider lifetimes. Explain that requirement before creating a prefix. A v4
45
- upgrade, additional screens, realtime, or a deep directory tree alone do not
46
- justify one. See [Prefix Router](prefix-router.md) when it applies.
54
+ Add another pathname page only when project scale calls for independent product
55
+ surfaces, or an important requirement needs distinct pathname entry points,
56
+ shells, or provider lifetimes. Explain that requirement before creating the
57
+ page. A v4 upgrade, additional screens, realtime, or a deep directory tree
58
+ alone does not justify one. There is no structural `prefix/` folder in unified
59
+ mode. See [Page scopes and unified routing](prefix-router.md) when it applies.
47
60
 
48
61
  Installed declarations and generated route types take precedence over older
49
62
  online guidance or a globally installed skill. For v3 applications, use the
50
63
  matching v3 docs instead of adding v4-only imports.
64
+
65
+ Use this authority order when sources disagree:
66
+
67
+ 1. installed declarations and `ludicord.generated.d.ts`;
68
+ 2. matching files in `node_modules/ludicord/dist/docs/`;
69
+ 3. the bundled skill;
70
+ 4. public docs and the skills.sh copy;
71
+ 5. remembered examples from another Ludicord release.
@@ -1,6 +1,6 @@
1
1
  # Public API reference
2
2
 
3
- > Documentation for Ludicord 4.0.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
3
+ > Documentation for Ludicord 4.1.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
4
4
 
5
5
  This page describes supported import paths and their purpose. The package includes TypeScript declarations for exact signatures and data shapes; use editor completion against the version you actually installed.
6
6
 
@@ -11,11 +11,15 @@ This page describes supported import paths and their purpose. The package includ
11
11
  | `ludicord` | `LudicordActivity`, `EmbedOutlet`, `PrefixLink`, `prefixHref`, `useActivityPrefix`, error/loading/minimize APIs, generated prefix types, `LUDICORD_VERSION` |
12
12
  | `ludicord/navigation` | `Link`, `PrefixLink`, `prefixHref`, `useEmbedRouter`, `useEmbedPath`, `useEmbedParams`, `usePageParams`, `useActivityPrefix`, and generated prefix/route/parameter types |
13
13
  | `ludicord/runtime` | `useLudicordRuntime` for environment, version, Activity/Discord/WebSocket readiness and auth status |
14
- | `ludicord/config` | `defineConfig` and configuration types |
14
+ | `ludicord/config` | `defineConfig`, `definePlugin`, plugin hook/context types, and configuration types |
15
+ | `ludicord/plugins` | Official plugin exports |
16
+ | `ludicord/plugins/wasm` | `wasm()` and `LudicordWasmPluginOptions` |
15
17
 
16
18
  The compiler supplies the minimize provider for automatic files; do not manually wrap it just to use `app/minimize.tsx`. See [automatic files](pages.md) and [navigation](navigation.md).
17
19
 
18
- `PrefixLink` and `prefixHref()` navigate between pathname-owned Activity scopes. `Link` and `useEmbedRouter()` navigate among local embeds without remounting the active scope. Read [V4 Prefix Router](prefix-router.md) before constructing cross-prefix URLs.
20
+ Configured plugins may add generated ambient declarations in `ludicord.plugins.generated.d.ts`. The official WASM plugin types `.wasm` imports and supplies `instantiate`, `compile`, and `byteLength`. See [Plugins and WebAssembly](plugins.md).
21
+
22
+ `PrefixLink` and `prefixHref()` navigate between pathname-owned Activity pages. `Link` and `useEmbedRouter()` navigate among local embeds without remounting the active page. Read [Page scopes and unified routing](prefix-router.md) before constructing cross-page URLs.
19
23
 
20
24
  ## Authentication
21
25
 
@@ -1,6 +1,6 @@
1
1
  # API Routes
2
2
 
3
- > Documentation for Ludicord 4.0.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
3
+ > Documentation for Ludicord 4.1.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
4
4
 
5
5
 
6
6
  Create a `route.ts` anywhere under `app/`. For example, `app/api/hello/route.ts` serves `/api/hello`; `app/health/route.ts` serves `/health`. The `api/` directory is optional. Do not place another route file in the same directory.
@@ -1,6 +1,6 @@
1
1
  # Build
2
2
 
3
- > Documentation for Ludicord 4.0.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
3
+ > Documentation for Ludicord 4.1.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
4
4
 
5
5
 
6
6
  ```bash
package/dist/docs/cli.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # CLI reference
2
2
 
3
- > Documentation for Ludicord 4.0.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
3
+ > Documentation for Ludicord 4.1.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
4
4
 
5
5
  Run commands through your generated package scripts or the locally installed `ludicord` executable.
6
6
 
@@ -27,7 +27,7 @@ npx ludicord start --port 3000
27
27
 
28
28
  Use `npx ludicord` inside an application where the package is already installed. Review diagnostics before sharing them publicly.
29
29
 
30
- Generated V4 projects intentionally keep only `dev`, `build`, and `start` in `package.json`. Run advanced commands through the project's package runner, for example `pnpm exec ludicord routes` or `npx ludicord lint`. In V4, `routes` prints the prefix ownership tree and `info` reports the prefix count and total scoped embeds. Use `ludicord --help` as the authority for flags supported by the installed version.
30
+ Generated V4 projects intentionally keep only `dev`, `build`, and `start` in `package.json`. Run advanced commands through the project's package runner, for example `pnpm exec ludicord routes` or `npx ludicord lint`. In V4, `routes` prints the page and embed ownership tree, and `info` reports the page-scope count and total owned embeds. Use `ludicord --help` as the authority for flags supported by the installed version.
31
31
 
32
32
  ## Project generator
33
33
 
@@ -1,13 +1,15 @@
1
1
  # Configuration reference
2
2
 
3
- > Documentation for Ludicord 4.0.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
3
+ > Documentation for Ludicord 4.1.0. See [release status](https://github.com/mrcholer/ludicord/blob/main/releases/README.md).
4
4
 
5
5
  Create `ludicord.config.mjs` in the application root:
6
6
 
7
7
  ```js
8
8
  import { defineConfig } from "ludicord/config";
9
+ import { wasm } from "ludicord/plugins/wasm";
9
10
 
10
11
  export default defineConfig({
12
+ plugins: [wasm()],
11
13
  discord: { scopes: ["identify", "guilds"] },
12
14
  activity: { defaultEmbed: "home", outsideDiscord: "error" },
13
15
  imports: {
@@ -23,6 +25,12 @@ export default defineConfig({
23
25
 
24
26
  Client ID may come from `LUDICORD_DISCORD_CLIENT_ID`. Keep secrets in server environment variables, never config literals or client imports.
25
27
 
28
+ ## Plugins
29
+
30
+ `plugins` accepts extensions created with `definePlugin()` as well as official plugins such as `wasm()`. False, null, and undefined entries are ignored so a plugin may be enabled conditionally. Plugin names must be unique. Plugins run in the browser and server compilers unless their hooks choose a target from the supplied context.
31
+
32
+ See [Plugins and WebAssembly](plugins.md) for the hook API, generated declarations, security boundary, and WASM imports. Do not create a Vite config; Ludicord owns its compiler configuration.
33
+
26
34
  ## Discord and Activity
27
35
 
28
36
  | Setting | Default | Meaning |