ludicord 3.1.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/AGENTS.md +11 -0
  2. package/README.md +19 -2
  3. package/dist/api/runtime.js +3 -8
  4. package/dist/cli/index.js +3 -3
  5. package/dist/cli/project-commands.js +11 -6
  6. package/dist/compiler/build.d.ts +2 -1
  7. package/dist/compiler/build.js +12 -8
  8. package/dist/compiler/client-entry.js +99 -42
  9. package/dist/compiler/client-tooling.d.ts +1 -1
  10. package/dist/compiler/client-tooling.js +14 -7
  11. package/dist/compiler/index.d.ts +2 -2
  12. package/dist/compiler/index.js +1 -1
  13. package/dist/compiler/scanner.d.ts +2 -1
  14. package/dist/compiler/scanner.js +196 -13
  15. package/dist/compiler/server-bundle.d.ts +1 -1
  16. package/dist/compiler/server-bundle.js +2 -1
  17. package/dist/compiler/type-generation.js +18 -3
  18. package/dist/compiler/write-manifests.js +1 -0
  19. package/dist/config/defaults.js +15 -2
  20. package/dist/config/index.d.ts +1 -1
  21. package/dist/config/types.d.ts +15 -3
  22. package/dist/docs/README.md +54 -0
  23. package/dist/docs/activity-hooks.md +109 -0
  24. package/dist/docs/activity-rooms.md +44 -0
  25. package/dist/docs/ai-agents.md +50 -0
  26. package/dist/docs/api-reference.md +69 -0
  27. package/dist/docs/api-routes.md +26 -0
  28. package/dist/docs/build.md +30 -0
  29. package/dist/docs/cli.md +42 -0
  30. package/dist/docs/configuration.md +100 -0
  31. package/dist/docs/deployment.md +30 -0
  32. package/dist/docs/development.md +27 -0
  33. package/dist/docs/discord-developer-portal.md +14 -0
  34. package/dist/docs/discord-sdk.md +36 -0
  35. package/dist/docs/distribution.md +38 -0
  36. package/dist/docs/embeds.md +27 -0
  37. package/dist/docs/environment-variables.md +30 -0
  38. package/dist/docs/getting-started.md +38 -0
  39. package/dist/docs/installation.md +32 -0
  40. package/dist/docs/login.md +24 -0
  41. package/dist/docs/migration-v4.md +33 -0
  42. package/dist/docs/migration.md +45 -0
  43. package/dist/docs/mobile-layout.md +26 -0
  44. package/dist/docs/navigation.md +37 -0
  45. package/dist/docs/pages.md +33 -0
  46. package/dist/docs/participants.md +14 -0
  47. package/dist/docs/prefix-router.md +44 -0
  48. package/dist/docs/project-structure.md +43 -0
  49. package/dist/docs/proxy.md +29 -0
  50. package/dist/docs/recipes.md +71 -0
  51. package/dist/docs/security.md +18 -0
  52. package/dist/docs/start.md +15 -0
  53. package/dist/docs/state-and-effects.md +119 -0
  54. package/dist/docs/troubleshooting.md +33 -0
  55. package/dist/docs/voice-events.md +19 -0
  56. package/dist/docs/websockets.md +37 -0
  57. package/dist/index.d.ts +4 -2
  58. package/dist/index.js +2 -1
  59. package/dist/lint/index.js +2 -2
  60. package/dist/manifests/types.d.ts +16 -1
  61. package/dist/navigation/index.d.ts +8 -1
  62. package/dist/navigation/index.js +2 -1
  63. package/dist/navigation/prefix-link.d.ts +9 -0
  64. package/dist/navigation/prefix-link.js +11 -0
  65. package/dist/router/match.d.ts +2 -1
  66. package/dist/router/match.js +23 -8
  67. package/dist/router/prefix.d.ts +13 -0
  68. package/dist/router/prefix.js +35 -0
  69. package/dist/runtime/client/dev-panel.js +80 -27
  70. package/dist/runtime/client/embed-router.d.ts +5 -1
  71. package/dist/runtime/client/embed-router.js +12 -12
  72. package/dist/runtime/client/root.d.ts +1 -0
  73. package/dist/runtime/client/root.js +1 -0
  74. package/dist/runtime/server/dev-server.d.ts +1 -0
  75. package/dist/runtime/server/dev-server.js +105 -25
  76. package/dist/runtime/server/production-server.js +22 -3
  77. package/dist/server/request-security.d.ts +3 -3
  78. package/dist/server/request-security.js +18 -4
  79. package/dist/shared/errors.d.ts +1 -1
  80. package/dist/skills/ludicord/SKILL.md +319 -0
  81. package/dist/skills/ludicord/agents/openai.yaml +7 -0
  82. package/dist/skills/ludicord/knowledge-map.md +68 -0
  83. package/dist/skills/ludicord/manifest.yaml +92 -0
  84. package/dist/skills/ludicord/references/auth-security.md +104 -0
  85. package/dist/skills/ludicord/references/capabilities/discord-context.md +20 -0
  86. package/dist/skills/ludicord/references/capabilities/persistence.md +33 -0
  87. package/dist/skills/ludicord/references/capabilities/realtime.md +53 -0
  88. package/dist/skills/ludicord/references/config-deploy.md +148 -0
  89. package/dist/skills/ludicord/references/discord-data.md +142 -0
  90. package/dist/skills/ludicord/references/embeds-navigation.md +168 -0
  91. package/dist/skills/ludicord/references/game/architecture.md +52 -0
  92. package/dist/skills/ludicord/references/game/game-first-ui.md +42 -0
  93. package/dist/skills/ludicord/references/game/multiplayer.md +40 -0
  94. package/dist/skills/ludicord/references/game/testing.md +45 -0
  95. package/dist/skills/ludicord/references/intelligence/README.md +22 -0
  96. package/dist/skills/ludicord/references/intelligence/capability-routing.md +70 -0
  97. package/dist/skills/ludicord/references/intelligence/conflict-resolution.md +50 -0
  98. package/dist/skills/ludicord/references/intelligence/implementation-contract.md +64 -0
  99. package/dist/skills/ludicord/references/intelligence/project-analysis.md +89 -0
  100. package/dist/skills/ludicord/references/intelligence/scope-control.md +49 -0
  101. package/dist/skills/ludicord/references/intelligence/skill-router.md +176 -0
  102. package/dist/skills/ludicord/references/intelligence/source-authority.md +51 -0
  103. package/dist/skills/ludicord/references/intelligence/validation-gates.md +64 -0
  104. package/dist/skills/ludicord/references/prefix-router.md +13 -0
  105. package/dist/skills/ludicord/references/products/collaborative-app.md +34 -0
  106. package/dist/skills/ludicord/references/products/dashboard.md +33 -0
  107. package/dist/skills/ludicord/references/products/game.md +58 -0
  108. package/dist/skills/ludicord/references/products/general-activity.md +35 -0
  109. package/dist/skills/ludicord/references/products/media-app.md +29 -0
  110. package/dist/skills/ludicord/references/products/social-app.md +22 -0
  111. package/dist/skills/ludicord/references/products/utility.md +17 -0
  112. package/dist/skills/ludicord/references/react-state.md +71 -0
  113. package/dist/skills/ludicord/references/server-routes.md +155 -0
  114. package/dist/skills/ludicord/references/validation.md +44 -0
  115. package/dist/version.js +1 -1
  116. package/dist/ws/client.js +1 -3
  117. package/dist/ws/server.d.ts +2 -0
  118. package/dist/ws/server.js +6 -5
  119. package/package.json +7 -3
package/AGENTS.md ADDED
@@ -0,0 +1,11 @@
1
+ <!-- BEGIN:ludicord-agent-rules -->
2
+ # Ludicord 4.0
3
+
4
+ Before changing a Ludicord Activity, read the relevant version-matched guide in `dist/docs/` and the reusable skill at `dist/skills/ludicord/SKILL.md`. Treat the installed declarations, project configuration, and generated `ludicord.generated.d.ts` as the API authority.
5
+
6
+ Ludicord's unified router uses `page.tsx` for pages, `route.ts` for HTTP methods, `socket.ts` for WebSockets, and `embed.tsx` for hash routes owned by their nearest ancestor page. Use at most one route file per directory.
7
+
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
+
10
+ Keep secrets and authorization on the server. Run the relevant lint, type, route, production-build, and behavior checks before finishing.
11
+ <!-- END:ludicord-agent-rules -->
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  <p align="center">
2
- <a href="https://github.com/mrcholer/ludicord"><img src="https://raw.githubusercontent.com/mrcholer/ludicord/main/.github/assets/ludicord-banner.png" alt="Ludicord" width="900" /></a>
2
+ <a href="https://github.com/mrcholer/ludicord"><img src="https://raw.githubusercontent.com/mrcholer/ludicord/main/.github/assets/ludicord-logo.png" alt="Ludicord" width="220" /></a>
3
3
  </p>
4
4
 
5
5
  <h1 align="center">ludicord</h1>
@@ -14,6 +14,8 @@
14
14
 
15
15
  The full-stack React framework and CLI for Discord Activities.
16
16
 
17
+ Ludicord 4.0 introduces unified file-system routing: `page.tsx` for pages, `route.ts` for HTTP, `socket.ts` for WebSockets, and `embed.tsx` for hash screens owned by their nearest page. Use at most one route file per directory. Existing V3 applications retain a compatibility path.
18
+
17
19
  ```bash
18
20
  ludicord dev
19
21
  ludicord build
@@ -32,4 +34,19 @@ Discord helpers include complete raw user/channel/guild/member/role/participant/
32
34
 
33
35
  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.
34
36
 
35
- Version 3.1 isolates authentication per Activity launch, renews expiring sessions without discarding a still-valid login, applies one host/origin policy to HTTP and WebSockets, adds acknowledged WebSocket events and bounded slow-client handling, and exposes adapters for multi-process sessions, one-time OAuth tokens, room delivery/counts, and shared-state revisions.
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).
38
+
39
+ V4 includes the production authentication, Activity-launch isolation, realtime reliability, and multi-process adapters introduced in 3.1.
40
+
41
+ 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
+
43
+ ## Version-matched AI guidance
44
+
45
+ Ludicord 4 includes offline docs at `node_modules/ludicord/dist/docs/`, the
46
+ canonical skill at `node_modules/ludicord/dist/skills/ludicord/SKILL.md`, and
47
+ `node_modules/ludicord/AGENTS.md`. The short agent entry point sits at the package root, like Next.js, and points to the detailed resources under `dist/`.
48
+ Point your existing project agent instructions at `node_modules/ludicord/AGENTS.md` when needed.
49
+
50
+ Use one root and ordinary embeds by default. Prefix routing is optional for
51
+ large projects with independent surfaces or a concrete need for separate
52
+ pathname entry points, shells, or provider lifetimes.
@@ -2,7 +2,7 @@ import path from "node:path";
2
2
  import { Readable } from "node:stream";
3
3
  import { pipeline } from "node:stream/promises";
4
4
  import { pathToFileURL } from "node:url";
5
- import { matchRoutePattern, routeSpecificity } from "../router/match.js";
5
+ import { compareRouteSpecificity, matchRoutePattern } from "../router/match.js";
6
6
  import { parseSessionCookie } from "../sessions/cookies.js";
7
7
  import { LUDICORD_LAUNCH_HEADER, normalizeLudicordLaunchId } from "../sessions/launch.js";
8
8
  import { verifyDiscordProxyRequest } from "../security/discord.js";
@@ -140,10 +140,6 @@ export function createApiMiddleware(options) {
140
140
  }
141
141
  return async (request, response, next) => {
142
142
  const pathname = new URL(request.originalUrl, `${request.protocol}://${request.get("host") ?? "localhost"}`).pathname;
143
- if (!pathname.startsWith("/api/") && pathname !== "/api") {
144
- next();
145
- return;
146
- }
147
143
  const matches = options
148
144
  .getRoutes()
149
145
  .map((route) => ({
@@ -151,11 +147,10 @@ export function createApiMiddleware(options) {
151
147
  match: matchRoutePattern(route.route, pathname),
152
148
  }))
153
149
  .filter((candidate) => candidate.match !== null)
154
- .sort((left, right) => routeSpecificity(right.route.route) -
155
- routeSpecificity(left.route.route));
150
+ .sort((left, right) => compareRouteSpecificity(left.route.route, right.route.route));
156
151
  const selected = matches[0];
157
152
  if (selected === undefined) {
158
- response.status(404).json({ error: "LUDICORD_API_NOT_FOUND" });
153
+ next();
159
154
  return;
160
155
  }
161
156
  try {
package/dist/cli/index.js CHANGED
@@ -13,8 +13,8 @@ import { createLudicordProductionServer } from "../runtime/server/production-ser
13
13
  import { cleanLudicordBuild, formatBundleAnalysis, formatInfo, formatRoutes, } from "./project-commands.js";
14
14
  import { LUDICORD_VERSION } from "../version.js";
15
15
  import { lintLudicordProject } from "../lint/index.js";
16
- const HELP = `Ludicord ${LUDICORD_VERSION}
17
- Discord Activity Framework
16
+ const HELP = `Ludicord v${LUDICORD_VERSION}
17
+ V4 · Prefix router
18
18
 
19
19
  Usage:
20
20
  ludicord --help
@@ -29,7 +29,7 @@ Commands:
29
29
  dev Start the development server
30
30
  build Create a production .ludicord build
31
31
  start Run an existing production build
32
- routes List Activity, embed, API, WebSocket, and proxy routes
32
+ routes List prefix, embed, API, WebSocket, and proxy routes
33
33
  lint Validate React Hooks in Activity source
34
34
  analyze Inspect production client bundle sizes
35
35
  info Print environment and project information
@@ -4,6 +4,7 @@ import { createRequire } from "node:module";
4
4
  import { generateManifests } from "../compiler/scanner.js";
5
5
  import { LUDICORD_VERSION } from "../version.js";
6
6
  import { formatBundleReport } from "../compiler/bundle-report.js";
7
+ import { formatRouteTable } from "../router/prefix.js";
7
8
  function formatTree(lines) {
8
9
  return lines
9
10
  .map((line, index) => `${index === lines.length - 1 ? "└─" : "├─"} ${line}`)
@@ -16,7 +17,10 @@ function apiMethods(projectRoot, file) {
16
17
  }
17
18
  export function formatRoutes(projectRoot) {
18
19
  const manifests = generateManifests(projectRoot);
19
- const embeds = manifests.embeds.map(({ route, file }) => `${route.padEnd(22)} ${file}`);
20
+ const prefixes = manifests.prefixes.flatMap((scope) => [
21
+ `${scope.prefix.padEnd(22)} ${scope.activity.root}`,
22
+ ...scope.embeds.map(({ route, file }) => ` #/${route.padEnd(19)} ${file}`),
23
+ ]);
20
24
  const api = manifests.api.flatMap(({ route, file }) => {
21
25
  const methods = apiMethods(projectRoot, file);
22
26
  return (methods.length === 0 ? ["?"] : methods).map((method) => `${method.padEnd(6)} ${route.padEnd(22)} ${file}`);
@@ -24,11 +28,11 @@ export function formatRoutes(projectRoot) {
24
28
  const websocket = manifests.websocket.map(({ route, file }) => `${route.padEnd(29)} ${file}`);
25
29
  return `LUDICORD ROUTES
26
30
 
27
- Activity
28
- ○ / ${manifests.activity.root}
31
+ Routes
32
+ ${formatRouteTable(manifests)}
29
33
 
30
- Embeds (internal)
31
- ${embeds.length === 0 ? "└─ (none)" : formatTree(embeds)}
34
+ Prefix router
35
+ ${formatTree(prefixes)}
32
36
 
33
37
  HTTP
34
38
  ${api.length === 0 ? "└─ (none)" : formatTree(api)}
@@ -66,7 +70,8 @@ Platform ${process.platform}
66
70
  Project
67
71
  Root: ${projectRoot}
68
72
  Activity: ${manifests.activity.root}
69
- Embeds: ${manifests.embeds.length}
73
+ Prefixes: ${manifests.prefixes.length}
74
+ Embeds: ${manifests.prefixes.reduce((total, scope) => total + scope.embeds.length, 0)}
70
75
  API routes: ${manifests.api.length}
71
76
  WS routes: ${manifests.websocket.length}
72
77
  Proxy: ${manifests.activity.proxy ?? "none"}`;
@@ -1,7 +1,7 @@
1
1
  import type { ResolvedLudicordConfig } from "../config/types.js";
2
2
  import type { LudicordManifests } from "../manifests/types.js";
3
3
  import type { LudicordBundleReport } from "./bundle-report.js";
4
- export declare const LUDICORD_BUILD_SCHEMA_VERSION: 3;
4
+ export declare const LUDICORD_BUILD_SCHEMA_VERSION: 4;
5
5
  export interface RouteBundle {
6
6
  readonly source: string;
7
7
  readonly bundle: string;
@@ -31,6 +31,7 @@ export interface LudicordBuildMetadata {
31
31
  };
32
32
  readonly react: ResolvedLudicordConfig["react"];
33
33
  readonly build: ResolvedLudicordConfig["build"];
34
+ readonly imports: ResolvedLudicordConfig["imports"];
34
35
  readonly server: ResolvedLudicordConfig["server"];
35
36
  readonly websocket: ResolvedLudicordConfig["websocket"];
36
37
  };
@@ -17,7 +17,7 @@ import { checkProjectTypes } from "../runtime/server/diagnostics.js";
17
17
  import { createBundleReport } from "./bundle-report.js";
18
18
  const VIRTUAL_BUILD_ENTRY = "virtual:ludicord-production-entry";
19
19
  const RESOLVED_BUILD_ENTRY = "\0virtual:ludicord-production-entry";
20
- export const LUDICORD_BUILD_SCHEMA_VERSION = 3;
20
+ export const LUDICORD_BUILD_SCHEMA_VERSION = 4;
21
21
  const STALE_BUILD_DIRECTORY = /^\.ludicord-(?:build|previous)-\d+-[0-9a-f-]+$/i;
22
22
  const STALE_BUILD_AGE_MS = 24 * 60 * 60 * 1_000;
23
23
  function frameworkWarnings(config, manifests) {
@@ -146,7 +146,7 @@ async function buildClient(projectRoot, outputDirectory, manifests, config) {
146
146
  ? path.join(projectRoot, "public")
147
147
  : false,
148
148
  plugins: [buildPlugin(projectRoot, manifests, config), ...await clientPlugins(projectRoot)],
149
- resolve: { alias: ludicordClientAliases(projectRoot), dedupe: ["react", "react-dom"] },
149
+ resolve: { alias: ludicordClientAliases(projectRoot, config.imports.aliases), dedupe: ["react", "react-dom"] },
150
150
  build: {
151
151
  outDir: path.join(outputDirectory, "client"),
152
152
  emptyOutDir: true,
@@ -228,6 +228,7 @@ function buildMetadata(clientEntry, api, websocket, instrumentation, proxy, bund
228
228
  },
229
229
  react: config.react,
230
230
  build: config.build,
231
+ imports: config.imports,
231
232
  server: config.server,
232
233
  websocket: config.websocket,
233
234
  },
@@ -249,7 +250,7 @@ export async function buildLudicordProject(projectRoot) {
249
250
  if (typeErrors.length > 0)
250
251
  throw new Error(typeErrors.map((item) => `${item.file ?? "TypeScript"}:${item.line ?? 1}:${item.column ?? 1}\n${item.message}\n${item.frame ?? ""}`).join("\n\n"));
251
252
  const { clientEntry, bundleReport } = await buildClient(root, temporaryDirectory, manifests, config);
252
- const graph = await bundleServerGraph(root, path.join(temporaryDirectory, "server"), manifests);
253
+ const graph = await bundleServerGraph(root, path.join(temporaryDirectory, "server"), manifests, config.imports.aliases);
253
254
  const api = graph.bundles.filter((route) => route.kind === "api").map((route) => ({ source: route.source, bundle: `server/${route.bundle}` }));
254
255
  const websocket = graph.bundles.filter((route) => route.kind === "ws").map((route) => ({ source: route.source, bundle: `server/${route.bundle}` }));
255
256
  const instrumentationRoute = graph.bundles.find((route) => route.kind === "instrumentation");
@@ -276,19 +277,22 @@ export async function buildLudicordProject(projectRoot) {
276
277
  warnings,
277
278
  formatSummary() {
278
279
  const routes = [
279
- "/ Activity",
280
- ...manifests.embeds.map(({ route }) => `embed:${route.padEnd(22)} Embed`),
280
+ ...manifests.prefixes.flatMap((scope) => [
281
+ `${scope.prefix.padEnd(29)} Prefix`,
282
+ ...scope.embeds.map(({ route }) => `${(`${scope.prefix === "/" ? "" : scope.prefix}/#/${route}`).padEnd(29)} Embed`),
283
+ ]),
281
284
  ...manifests.api.map(({ route }) => `${route.padEnd(29)} API`),
282
285
  ...manifests.websocket.map(({ route }) => `${route.padEnd(29)} WebSocket`),
283
286
  ...(manifests.activity.proxy === undefined
284
287
  ? []
285
288
  : ["app/proxy.ts Proxy"]),
286
289
  ];
287
- return `Ludicord ${LUDICORD_VERSION}
290
+ return `Ludicord v${LUDICORD_VERSION}
291
+ V4 · Prefix router
288
292
  Building Discord Activity for production...
289
293
 
290
- ✓ Validated app/pages.tsx
291
- ✓ Scanned embeds
294
+ ✓ Validated prefix Activity roots
295
+ ✓ Scanned recursive prefix embeds
292
296
  ✓ Scanned API routes
293
297
  ✓ Scanned WebSocket routes
294
298
  ✓ Scanned request proxy
@@ -1,60 +1,117 @@
1
1
  import path from "node:path";
2
+ import { existsSync } from "node:fs";
2
3
  import { normalizePath } from "vite";
3
4
  import { LUDICORD_VERSION } from "../version.js";
5
+ const FILE_COMPONENTS = [
6
+ "layout", "loading", "error", "globalError", "notFound", "minimize",
7
+ "authLoading", "authError", "authDenied",
8
+ ];
4
9
  export function clientEntry(root, manifests, config, development) {
5
10
  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 { installLudicordLaunchIsolation } from "ludicord/auth";`, `import Pages from ${JSON.stringify(file(manifests.activity.root))};`];
8
- const components = [];
9
- let metadata = "";
10
- if (manifests.activity.metadata !== undefined) {
11
- imports.push(`import ActivityMetadata from ${JSON.stringify(file(manifests.activity.metadata))};`);
12
- metadata = ", metadata: ActivityMetadata";
11
+ const imports = [
12
+ `import React from "react";`,
13
+ `import { createRoot } from "react-dom/client";`,
14
+ `import { LudicordRoot, matchPageRoute } from "ludicord/internal";`,
15
+ `import { LudicordActivity } from "ludicord";`,
16
+ `import { installLudicordLaunchIsolation } from "ludicord/auth";`,
17
+ ];
18
+ if (existsSync(path.join(root, "app", "globals.css"))) {
19
+ imports.push(`import ${JSON.stringify(file("app/globals.css"))};`);
13
20
  }
14
- for (const key of ["layout", "loading", "error", "globalError", "notFound", "minimize", "authLoading", "authError", "authDenied"]) {
15
- const source = manifests.activity[key];
16
- if (source !== undefined) {
17
- const name = `File_${key}`;
18
- imports.push(`import ${name} from ${JSON.stringify(file(source))};`);
21
+ const activityDefinition = (activity, scopeIndex, bindings, loaders) => {
22
+ const bindDefault = (name, source) => {
23
+ bindings.push(name);
24
+ loaders.push(`import(${JSON.stringify(file(source))}).then((module) => module.default)`);
25
+ };
26
+ const pages = `Pages_${scopeIndex}`;
27
+ bindDefault(pages, activity.root);
28
+ const components = [];
29
+ for (const key of FILE_COMPONENTS) {
30
+ const source = activity[key];
31
+ if (source === undefined)
32
+ continue;
33
+ const name = `Scope_${scopeIndex}_${key}`;
34
+ bindDefault(name, source);
19
35
  components.push(`${key}: ${name}`);
20
36
  }
21
- }
37
+ if (activity.metadata === undefined) {
38
+ return { pages, files: `{${components.join(",")}}`, metadata: "undefined" };
39
+ }
40
+ const metadata = `Scope_${scopeIndex}_metadata`;
41
+ bindDefault(metadata, activity.metadata);
42
+ return { pages, files: `{${components.join(",")}}`, metadata };
43
+ };
44
+ const scopeDefinition = (scope, scopeIndex) => {
45
+ const bindings = [];
46
+ 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);
52
+ const embeds = scope.embeds.map((route, routeIndex) => {
53
+ const fields = [`load: () => import(${JSON.stringify(file(route.file))})`];
54
+ for (const [key, source] of [["loading", route.loading], ["error", route.error]]) {
55
+ if (source === undefined)
56
+ continue;
57
+ const name = `Scope_${scopeIndex}_Embed_${routeIndex}_${key}`;
58
+ bindDefault(name, source);
59
+ fields.push(`${key}: ${name}`);
60
+ }
61
+ 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);
65
+ return name;
66
+ });
67
+ fields.push(`layouts: [${layouts.join(",")}]`);
68
+ }
69
+ return `${JSON.stringify(route.route)}: { ${fields.join(", ")} }`;
70
+ });
71
+ return `${JSON.stringify(scope.prefix)}: async () => {
72
+ const [${bindings.join(",")}] = await Promise.all([${loaders.join(",")}]);
73
+ return { Pages: ${activity.pages}, managedActivity: ${scope.activity.managedActivity === true}, files: ${activity.files}, metadata: ${activity.metadata}, embeds: {${embeds.join(",\n")} } };
74
+ }`;
75
+ };
76
+ const scopeDefinitions = manifests.prefixes.map(scopeDefinition);
22
77
  const publicConfig = {
23
78
  discordServerData: Boolean(process.env.LUDICORD_DISCORD_BOT_TOKEN),
24
- environment: development ? "development" : "production", version: LUDICORD_VERSION,
25
- discordClientId: config.discord.clientId, outsideDiscord: config.activity.outsideDiscord,
26
- scopes: config.discord.scopes, authRequired: config.discord.auth.required,
79
+ environment: development ? "development" : "production",
80
+ version: LUDICORD_VERSION,
81
+ discordClientId: config.discord.clientId,
82
+ outsideDiscord: config.activity.outsideDiscord,
83
+ scopes: config.discord.scopes,
84
+ authRequired: config.discord.auth.required,
27
85
  defaultEmbed: config.activity.defaultEmbed,
28
86
  devFakeAuth: development && process.env.LUDICORD_DEV_FAKE_AUTH === "true",
29
87
  websocket: { enabled: config.websocket.enabled, reconnect: config.websocket.reconnect },
30
88
  };
31
- const embedDefinitions = manifests.embeds.map((route, routeIndex) => {
32
- const fields = [`load: () => import(${JSON.stringify(file(route.file))})`];
33
- for (const [key, source] of [["loading", route.loading], ["error", route.error]]) {
34
- if (source === undefined)
35
- continue;
36
- const name = `Embed_${routeIndex}_${key}`;
37
- imports.push(`import ${name} from ${JSON.stringify(file(source))};`);
38
- fields.push(`${key}: ${name}`);
39
- }
40
- if (route.layouts !== undefined) {
41
- const layouts = route.layouts.map((source, layoutIndex) => {
42
- const name = `Embed_${routeIndex}_layout_${layoutIndex}`;
43
- imports.push(`import ${name} from ${JSON.stringify(file(source))};`);
44
- return name;
45
- });
46
- fields.push(`layouts: [${layouts.join(",")}]`);
47
- }
48
- return `${JSON.stringify(route.route)}: { ${fields.join(", ")} }`;
49
- });
50
89
  return `${imports.join("\n")}
90
+ const prefixScopes = {${scopeDefinitions.join(",\n")}};
91
+ const normalizePrefix = (value) => {
92
+ const pathname = value.replace(/\\/{2,}/g, "/").replace(/\\/$/, "");
93
+ return pathname === "" ? "/" : pathname;
94
+ };
95
+ const activePrefix = normalizePrefix(window.location.pathname);
96
+ const selectedPage = matchPageRoute(Object.keys(prefixScopes).map((prefix) => ({ prefix })), activePrefix);
51
97
  globalThis.__LUDICORD_PUBLIC_CONFIG__ = ${JSON.stringify(publicConfig)};
52
- globalThis.__LUDICORD_EMBEDS__ = {${embedDefinitions.join(",\n")}};
98
+ globalThis.__LUDICORD_ACTIVE_PREFIX__ = activePrefix;
99
+ globalThis.__LUDICORD_PAGE_PARAMS__ = selectedPage?.match.params ?? {};
53
100
  installLudicordLaunchIsolation();
54
- const container = document.getElementById("ludicord-root");
55
- if (!container) throw new Error("LUDICORD2003: Missing #ludicord-root container.");
56
- const root = createRoot(container);
57
- const activity = React.createElement(LudicordRoot, { files: {${components.join(",")}}${metadata} }, React.createElement(Pages));
58
- root.render(${config.react.strictMode ? "React.createElement(React.StrictMode, null, activity)" : "activity"});
59
- ${development ? `if (import.meta.hot) import.meta.hot.dispose(() => root.unmount());` : ""}`;
101
+ let mountedRoot;
102
+ const bootPrefix = async () => {
103
+ const loadScope = selectedPage && prefixScopes[selectedPage.scope.prefix];
104
+ if (!loadScope) throw new Error('LUDICORD2004: Unknown Activity prefix "' + activePrefix + '".');
105
+ const selectedScope = await loadScope();
106
+ globalThis.__LUDICORD_EMBEDS__ = selectedScope.embeds;
107
+ const container = document.getElementById("ludicord-root");
108
+ if (!container) throw new Error("LUDICORD2003: Missing #ludicord-root container.");
109
+ mountedRoot = createRoot(container);
110
+ const page = React.createElement(selectedScope.Pages, { params: globalThis.__LUDICORD_PAGE_PARAMS__ });
111
+ const content = selectedScope.managedActivity ? React.createElement(LudicordActivity, { defaultEmbed: ${JSON.stringify(config.activity.defaultEmbed)} }, page) : page;
112
+ const activity = React.createElement(LudicordRoot, { files: selectedScope.files, metadata: selectedScope.metadata }, content);
113
+ mountedRoot.render(${config.react.strictMode ? "React.createElement(React.StrictMode, null, activity)" : "activity"});
114
+ };
115
+ void bootPrefix();
116
+ ${development ? `if (import.meta.hot) import.meta.hot.dispose(() => mountedRoot?.unmount());` : ""}`;
60
117
  }
@@ -1,4 +1,4 @@
1
1
  import type { AliasOptions, Logger, PluginOption } from "vite";
2
- export declare function clientAliases(projectRoot: string): AliasOptions;
2
+ export declare function clientAliases(projectRoot: string, projectAliases?: Readonly<Record<string, string>>): AliasOptions;
3
3
  export declare function ludicordLogger(onError?: (error: unknown) => void): Logger;
4
4
  export declare function clientPlugins(projectRoot: string, onCompile?: (file: string, elapsed?: number) => void): Promise<PluginOption[]>;
@@ -8,7 +8,7 @@ import react from "@vitejs/plugin-react";
8
8
  import { createLogger, normalizePath } from "vite";
9
9
  import { redact } from "../runtime/server/diagnostics.js";
10
10
  const require = createRequire(import.meta.url);
11
- export function clientAliases(projectRoot) {
11
+ export function clientAliases(projectRoot, projectAliases = { "@": "." }) {
12
12
  const resolve = (name) => {
13
13
  try {
14
14
  return require.resolve(name, { paths: [projectRoot] });
@@ -30,7 +30,13 @@ export function clientAliases(projectRoot) {
30
30
  "ludicord/navigation": "../navigation/index.js", "ludicord/discord": "../discord/index.js", "ludicord/auth": "../auth/index.js",
31
31
  "ludicord/ws": "../ws/client.js", "ludicord/ws/client": "../ws/client.js",
32
32
  };
33
- return [...entries, ...Object.entries(runtime).map(([name, file]) => ({ find: new RegExp(`^${name.replaceAll("/", "\\/")}$`), replacement: fileURLToPath(new URL(file, import.meta.url)) }))];
33
+ const projectEntries = Object.entries(projectAliases)
34
+ .sort(([left], [right]) => right.length - left.length)
35
+ .map(([alias, target]) => ({
36
+ find: new RegExp(`^${alias.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?=\\/|$)`),
37
+ replacement: normalizePath(path.resolve(projectRoot, target)),
38
+ }));
39
+ return [...projectEntries, ...entries, ...Object.entries(runtime).map(([name, file]) => ({ find: new RegExp(`^${name.replaceAll("/", "\\/")}$`), replacement: fileURLToPath(new URL(file, import.meta.url)) }))];
34
40
  }
35
41
  export function ludicordLogger(onError) {
36
42
  const base = createLogger("info", { prefix: "Ludicord", allowClearScreen: false });
@@ -55,7 +61,7 @@ export async function clientPlugins(projectRoot, onCompile) {
55
61
  name: "ludicord:client-boundaries", enforce: "pre",
56
62
  resolveId(id, _importer, options) {
57
63
  if (!options.ssr && /^ludicord\/(server|security|config|ws\/server|runtime\/server)(\/|$)/.test(id)) {
58
- throw new Error(`LUDICORD7004: ${id} is server-only. Move this import to app/api or app/ws; use type-only imports for types.`);
64
+ throw new Error(`LUDICORD7004: ${id} is server-only. Move this import to route.ts or socket.ts; use type-only imports for types.`);
59
65
  }
60
66
  return undefined;
61
67
  },
@@ -67,17 +73,18 @@ export async function clientPlugins(projectRoot, onCompile) {
67
73
  startTimes.set(id, performance.now());
68
74
  onCompile?.(path.relative(projectRoot, file).split(path.sep).join("/"));
69
75
  }
70
- if (!/\/embeds\/.*\/embed\.[jt]sx?$/.test(file))
76
+ if (!/\/(?:embed|page)\.[jt]sx?$/.test(file))
71
77
  return undefined;
72
78
  // Source code remains `export default function embed`; React Refresh sees a component name.
73
79
  const source = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true, file.endsWith("tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.JSX);
74
- const declaration = source.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === "embed" && node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword) === true);
80
+ const declaration = source.statements.find((node) => ts.isFunctionDeclaration(node) && (node.name?.text === "embed" || node.name?.text === "page") && node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword) === true);
75
81
  if (!declaration?.name)
76
82
  return undefined;
77
83
  const result = new MagicString(code);
78
- result.overwrite(declaration.name.getStart(source), declaration.name.end, "LudicordEmbed");
84
+ const componentName = declaration.name.text === "embed" ? "LudicordEmbed" : "LudicordPage";
85
+ result.overwrite(declaration.name.getStart(source), declaration.name.end, componentName);
79
86
  // Preserve self-references and other local references to the authored function name.
80
- result.appendLeft(declaration.end, "\nconst embed = LudicordEmbed;\n");
87
+ result.appendLeft(declaration.end, `\nconst ${declaration.name.text} = ${componentName};\n`);
81
88
  return { code: result.toString(), map: result.generateMap({ source: file, includeContent: true, hires: true }) };
82
89
  },
83
90
  };
@@ -1,4 +1,4 @@
1
- export { generateManifests, scanApiRoutes, scanEmbeds, scanWebSocketRoutes, validateActivityRoot, } from "./scanner.js";
1
+ export { generateManifests, scanApiRoutes, scanEmbeds, scanPrefixes, scanWebSocketRoutes, validateActivityRoot, } from "./scanner.js";
2
2
  export { writeManifests } from "./write-manifests.js";
3
3
  export { cleanupStaleBuildDirectories } from "./build.js";
4
4
  export { createBundleReport, formatBundleBytes, formatBundleReport } from "./bundle-report.js";
@@ -6,4 +6,4 @@ export type { LudicordBundleAsset, LudicordBundleReport } from "./bundle-report.
6
6
  export { generateLudicordTypes } from "./type-generation.js";
7
7
  export { loadLudicordConfig } from "../config/loader.js";
8
8
  export { resolveProjectRoot } from "../config/project-root.js";
9
- export type { ActivityManifest, ApiManifestEntry, LudicordManifests, EmbedManifestEntry, RouteParameter, WebSocketManifestEntry, } from "../manifests/types.js";
9
+ export type { ActivityManifest, ApiManifestEntry, LudicordManifests, EmbedManifestEntry, PrefixManifestEntry, RouteParameter, WebSocketManifestEntry, } from "../manifests/types.js";
@@ -1,4 +1,4 @@
1
- export { generateManifests, scanApiRoutes, scanEmbeds, scanWebSocketRoutes, validateActivityRoot, } from "./scanner.js";
1
+ export { generateManifests, scanApiRoutes, scanEmbeds, scanPrefixes, scanWebSocketRoutes, validateActivityRoot, } from "./scanner.js";
2
2
  export { writeManifests } from "./write-manifests.js";
3
3
  export { cleanupStaleBuildDirectories } from "./build.js";
4
4
  export { createBundleReport, formatBundleBytes, formatBundleReport } from "./bundle-report.js";
@@ -1,6 +1,7 @@
1
- import type { ActivityManifest, ApiManifestEntry, LudicordManifests, EmbedManifestEntry, WebSocketManifestEntry } from "../manifests/types.js";
1
+ import type { ActivityManifest, ApiManifestEntry, LudicordManifests, EmbedManifestEntry, PrefixManifestEntry, WebSocketManifestEntry } from "../manifests/types.js";
2
2
  export declare function validateActivityRoot(projectRoot: string): ActivityManifest;
3
3
  export declare function scanEmbeds(projectRoot: string): EmbedManifestEntry[];
4
+ export declare function scanPrefixes(projectRoot: string): PrefixManifestEntry[];
4
5
  export declare function scanApiRoutes(projectRoot: string): ApiManifestEntry[];
5
6
  export declare function scanWebSocketRoutes(projectRoot: string): WebSocketManifestEntry[];
6
7
  export declare function generateManifests(projectRoot: string): LudicordManifests;