ludicord 4.1.0 → 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 (51) hide show
  1. package/dist/compiler/build.d.ts +2 -0
  2. package/dist/compiler/build.js +13 -4
  3. package/dist/compiler/client-assets.d.ts +2 -0
  4. package/dist/compiler/client-assets.js +5 -0
  5. package/dist/compiler/client-entry.js +40 -15
  6. package/dist/docs/README.md +1 -1
  7. package/dist/docs/activity-rooms.md +1 -1
  8. package/dist/docs/ai-agents.md +1 -1
  9. package/dist/docs/api-reference.md +1 -1
  10. package/dist/docs/api-routes.md +15 -1
  11. package/dist/docs/build.md +1 -1
  12. package/dist/docs/cli.md +1 -1
  13. package/dist/docs/configuration.md +1 -1
  14. package/dist/docs/deployment.md +18 -1
  15. package/dist/docs/development.md +32 -1
  16. package/dist/docs/discord-developer-portal.md +1 -1
  17. package/dist/docs/discord-sdk.md +1 -1
  18. package/dist/docs/distribution.md +1 -1
  19. package/dist/docs/embeds.md +1 -1
  20. package/dist/docs/environment-variables.md +1 -1
  21. package/dist/docs/getting-started.md +1 -1
  22. package/dist/docs/installation.md +2 -2
  23. package/dist/docs/login.md +1 -1
  24. package/dist/docs/migration.md +5 -5
  25. package/dist/docs/mobile-layout.md +1 -1
  26. package/dist/docs/navigation.md +1 -1
  27. package/dist/docs/pages.md +7 -1
  28. package/dist/docs/participants.md +1 -1
  29. package/dist/docs/prefix-router.md +1 -1
  30. package/dist/docs/project-structure.md +1 -1
  31. package/dist/docs/recipes.md +1 -1
  32. package/dist/docs/security.md +1 -1
  33. package/dist/docs/start.md +1 -1
  34. package/dist/docs/state-and-effects.md +1 -1
  35. package/dist/docs/troubleshooting.md +1 -1
  36. package/dist/docs/voice-events.md +1 -1
  37. package/dist/docs/websockets.md +1 -1
  38. package/dist/lint/index.js +1 -1
  39. package/dist/runtime/client/embed-router.js +23 -5
  40. package/dist/runtime/client/root.d.ts +2 -0
  41. package/dist/runtime/client/root.js +5 -1
  42. package/dist/runtime/client/startup.d.ts +17 -0
  43. package/dist/runtime/client/startup.js +72 -0
  44. package/dist/runtime/server/dev-server.js +2 -1
  45. package/dist/runtime/server/production-server.js +38 -2
  46. package/dist/runtime/startup-shell.d.ts +12 -0
  47. package/dist/runtime/startup-shell.js +16 -0
  48. package/dist/skills/ludicord/SKILL.md +2 -2
  49. package/dist/skills/ludicord/manifest.yaml +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +1 -1
@@ -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,6 +9,8 @@ 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";
@@ -172,6 +174,11 @@ async function buildClient(projectRoot, outputDirectory, manifests, config) {
172
174
  },
173
175
  }));
174
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();
175
182
  const entry = outputs
176
183
  .flatMap((output) => output.output)
177
184
  .find((item) => item.type === "chunk" && item.isEntry);
@@ -200,22 +207,24 @@ async function buildClient(projectRoot, outputDirectory, manifests, config) {
200
207
  ${[...styles].map((file) => `<link rel="stylesheet" href="/${file}" />`).join("\n ")}
201
208
  </head>
202
209
  <body>
203
- <div id="ludicord-root"></div>
210
+ <div id="ludicord-root">${STARTUP_SHELL_HTML}</div>
204
211
  <script type="module" src="/${clientEntry}"></script>
205
212
  </body>
206
213
  </html>
207
214
  `, "utf8");
208
215
  return {
209
216
  clientEntry,
217
+ immutableAssets,
210
218
  bundleReport: createBundleReport(path.join(outputDirectory, "client"), clientEntry, config.build.clientAssetWarningLimit),
211
219
  };
212
220
  }
213
- function buildMetadata(clientEntry, api, websocket, instrumentation, proxy, bundleReport, config) {
221
+ function buildMetadata(clientEntry, immutableAssets, api, websocket, instrumentation, proxy, bundleReport, config) {
214
222
  return {
215
223
  buildSchemaVersion: LUDICORD_BUILD_SCHEMA_VERSION,
216
224
  frameworkVersion: LUDICORD_VERSION,
217
225
  createdAt: new Date().toISOString(),
218
226
  clientEntry,
227
+ immutableAssets,
219
228
  api,
220
229
  websocket,
221
230
  ...(instrumentation === undefined ? {} : { instrumentation }),
@@ -259,7 +268,7 @@ export async function buildLudicordProject(projectRoot) {
259
268
  const typeErrors = checkProjectTypes(root);
260
269
  if (typeErrors.length > 0)
261
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"));
262
- const { clientEntry, bundleReport } = await buildClient(root, temporaryDirectory, manifests, config);
271
+ const { clientEntry, immutableAssets, bundleReport } = await buildClient(root, temporaryDirectory, manifests, config);
263
272
  const graph = await bundleServerGraph(root, path.join(temporaryDirectory, "server"), manifests, config.imports.aliases, config.plugins, "production");
264
273
  const api = graph.bundles.filter((route) => route.kind === "api").map((route) => ({ source: route.source, bundle: `server/${route.bundle}` }));
265
274
  const websocket = graph.bundles.filter((route) => route.kind === "ws").map((route) => ({ source: route.source, bundle: `server/${route.bundle}` }));
@@ -276,7 +285,7 @@ export async function buildLudicordProject(projectRoot) {
276
285
  writeFileSync(path.join(temporaryDirectory, "types", "routes.d.ts"), readFileSync(path.join(root, "ludicord.generated.d.ts"), "utf8"), "utf8");
277
286
  writeFileSync(path.join(temporaryDirectory, "types", "plugins.d.ts"), readFileSync(path.join(root, "ludicord.plugins.generated.d.ts"), "utf8"), "utf8");
278
287
  writeFileSync(path.join(temporaryDirectory, "bundle-report.json"), `${JSON.stringify(bundleReport, null, 2)}\n`, "utf8");
279
- const metadata = buildMetadata(clientEntry, api, websocket, instrumentation, proxy, bundleReport, config);
288
+ const metadata = buildMetadata(clientEntry, immutableAssets, api, websocket, instrumentation, proxy, bundleReport, config);
280
289
  writeFileSync(path.join(temporaryDirectory, "build.json"), `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
281
290
  if (clientContainsSecret(path.join(temporaryDirectory, "client")))
282
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
  }
@@ -1,6 +1,6 @@
1
1
  # Ludicord documentation
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
@@ -1,6 +1,6 @@
1
1
  # Activity Rooms
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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:
@@ -1,6 +1,6 @@
1
1
  # AI coding agents
2
2
 
3
- Ludicord 4.1.0 ships documentation and agent skills with the npm package. They
3
+ Ludicord 4.1.1 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
@@ -1,6 +1,6 @@
1
1
  # Public API reference
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  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
 
@@ -1,6 +1,6 @@
1
1
  # API Routes
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  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.
@@ -24,3 +24,17 @@ Handlers use native `Request` and `Response` objects. Export `GET`, `POST`, `PUT
24
24
  Routes require a valid Ludicord session by default. Set `export const auth = false` for a public route. Authenticated handlers should trust identity from `request.ludicord`, never user IDs supplied in a request body.
25
25
 
26
26
  Ludicord returns 404 for no route, 405 with `Allow` for unsupported methods, supplies HEAD from GET, and supplies OPTIONS when no custom handler exists. API and Activity traffic run on the same Node server.
27
+
28
+ The production server defaults dynamic responses to `Cache-Control: no-store`. For intentionally public, non-personalized data, a handler can explicitly opt into caching:
29
+
30
+ ```ts
31
+ export const auth = false;
32
+
33
+ export function GET() {
34
+ return Response.json({ status: "online" }, {
35
+ headers: { "Cache-Control": "public, max-age=60" },
36
+ });
37
+ }
38
+ ```
39
+
40
+ Keep user- and Activity-specific responses out of shared caches. See [production HTTP caching](deployment.md#production-http-caching) for the asset and HTML policies.
@@ -1,6 +1,6 @@
1
1
  # Build
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  ```bash
package/dist/docs/cli.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # CLI reference
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Run commands through your generated package scripts or the locally installed `ludicord` executable.
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Configuration reference
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Create `ludicord.config.mjs` in the application root:
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Deployment
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Deploy Ludicord to a Node.js 20.19+ environment that supports long-lived HTTP upgrades for WebSockets.
@@ -16,6 +16,23 @@ Do not place a CDN cache in front of `/_ludicord/auth`, authenticated `/api/*`,
16
16
 
17
17
  The Client ID can be present during the build or supplied to `ludicord start`. A runtime value takes precedence and is injected into the Activity document, allowing one promoted build to run against the intended Discord application. The same effective ID protects HTTP, authentication, and WebSocket requests. With the default origin policy, the exact Activity proxy origin is `https://<clientId>.discordsays.com`; do not add a wildcard for all Discord applications.
18
18
 
19
+ ## Production HTTP caching
20
+
21
+ The production server applies these policies automatically:
22
+
23
+ | Response | `Cache-Control` | Behavior |
24
+ | --- | --- | --- |
25
+ | Compiler-generated hashed JavaScript, CSS, and other assets | `public, max-age=31536000, immutable` | Browsers and CDNs can reuse the file for one year. Changed content receives a new URL on the next build. |
26
+ | Activity HTML, including `/index.html` and nested pages | `no-cache` | Validate before reuse so the document points to the current build and runtime Client ID. |
27
+ | Files copied from `public/` and other unversioned static files | `no-cache` | Validate before reuse, even when a filename happens to look hashed. |
28
+ | Auth, API, health, missing assets, and other dynamic responses | `no-store` by default | Do not store responses unless an application handler deliberately supplies its own caching header. |
29
+
30
+ HTML and static files include ETags for conditional requests. Unchanged resources return `304 Not Modified` without retransmitting their body; static files also provide `Last-Modified` validators. GET, HEAD, and successful range responses use the same resource cache policy. Missing hashed chunks return an uncached 404 even when the app defines a catch-all page.
31
+
32
+ The build records the immutable asset list from compiler output in `build.json`; it does not infer immutability from arbitrary public filenames. Older schema-4 builds without that list remain supported and revalidate all static files. Rebuild with the updated compiler to enable long-lived asset caching.
33
+
34
+ Configure your CDN or reverse proxy to honor these headers. When deploying, retain older hashed assets for existing Activity sessions that may still request lazy chunks from the previous build. The local build replacement does not retain those assets automatically. Do not apply a one-year cache policy to HTML or the entire `public/` directory.
35
+
19
36
  The built-in session, OAuth-token, WebSocket, and shared-state implementations are process-local. Multiple replicas should use a custom launcher:
20
37
 
21
38
  ```ts
@@ -1,6 +1,6 @@
1
1
  # Development runtime
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  `ludicord dev` owns the HTTP server, API routes, WebSockets, React hot updates, and diagnostics. It binds and announces the local URL before the initial compilation, then reports a clear `listening` → `compiling` → `ready` lifecycle. Requests wait for that first compilation instead of racing an incomplete server:
@@ -25,3 +25,34 @@ Ludicord's development panel handles syntax, TypeScript, render, event-handler,
25
25
  Successful server graph rebuilds remove obsolete temporary bundles; failed rebuilds keep the last working graph. The current run directory is removed on shutdown. Vite remains an internal compiler, not a separate developer-facing server. `vite.config.ts` is unnecessary and ignored. Tailwind is detected when `@tailwindcss/vite` is installed in the app.
26
26
 
27
27
  Run `ludicord routes` to inspect recursive page and embed ownership, `ludicord info` for environment and project details, `ludicord lint` for React Hooks rules, and `ludicord build` for the complete production validation and client-secret scan.
28
+
29
+ ## Startup measurements
30
+
31
+ Generated Activity entries record local User Timing measures in development and production. Record an opening in the browser's Performance panel, or inspect them in the console:
32
+
33
+ ```js
34
+ console.table(performance.getEntriesByType("measure")
35
+ .filter(entry => entry.name.startsWith("ludicord:startup:"))
36
+ .map(entry => ({
37
+ stage: entry.name.replace("ludicord:startup:", ""),
38
+ startMs: Math.round(entry.startTime),
39
+ durationMs: Math.round(entry.duration),
40
+ status: entry.detail?.status,
41
+ })));
42
+ ```
43
+
44
+ | Measure | Meaning |
45
+ | --- | --- |
46
+ | `runtime` | Time from document navigation until the generated entry begins executing, including entry downloads and imported runtime evaluation. |
47
+ | `scope` | Preparation of the selected page's layout, loading UI, metadata, and route registry. |
48
+ | `page-module` | Import and evaluation of the selected page module, started alongside scope preparation. |
49
+ | `discord` | Discord initialization after the Activity mounts. |
50
+ | `auth` | Authentication after Discord initialization; skipped when initialization returns without a session. |
51
+ | `embed-module` | Import and evaluation of the first requested embed module. |
52
+ | `root-commit` | Navigation to the first React root effect, which may still show a loading screen. |
53
+ | `content-commit` | Navigation to the first committed Activity content after its sign-in gate allows rendering. An embed may still be loading. |
54
+ | `embed-commit` | Navigation to the first committed embed subtree, including its layouts. |
55
+
56
+ Stage measures have `detail.status` of `complete`, `skipped`, or `error`. Only stages actually reached are recorded; for example, failed Discord initialization does not produce an authentication measure. Commit milestones use React effects and do not claim to measure browser paint. Use browser network/resource timings to separate download time from module evaluation; deferred modules and shared imports can overlap, so these durations should not be added together.
57
+
58
+ Measures are recorded once per entry boot, including under React Strict Mode. HMR entry disposal prevents old asynchronous imports from mounting a stale root or finishing stale measurements; the next entry clears only Ludicord's startup marks and measures. Later embed navigation does not overwrite opening measurements. These timings remain in the browser and are not sent to a server.
@@ -1,6 +1,6 @@
1
1
  # Discord Developer Portal Setup
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  1. Create a Discord application and enable Activities.
@@ -1,6 +1,6 @@
1
1
  # Discord SDK
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Ludicord uses the official `@discord/embedded-app-sdk` package and initializes one SDK instance per Activity. `LudicordActivity` waits for SDK readiness before authentication and reuses shared subscriptions rather than registering one listener per component.
@@ -1,6 +1,6 @@
1
1
  # Package distribution and automated releases
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Ludicord uses a two-stage release pipeline so its public package links and npm provenance are correct without publishing the original TypeScript implementation.
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Embeds
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  An embed is an internal Activity screen owned by its nearest ancestor page. Create `app/home/embed.tsx` for the root page:
@@ -1,6 +1,6 @@
1
1
  # Environment Variables
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  ```env
@@ -1,6 +1,6 @@
1
1
  # Getting Started
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Create an Activity and start the development server:
@@ -1,11 +1,11 @@
1
1
  # Installation
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Node.js 20.19 or newer is required. A new project is the simplest installation:
7
7
 
8
- The commands below install the latest **published** release. Confirm the registry reports 4.1.0 before upgrading a production deployment.
8
+ The commands below install the latest **published** release. Confirm the registry reports 4.1.1 before upgrading a production deployment.
9
9
 
10
10
  ```bash
11
11
  npx create-ludicord-app my-activity
@@ -1,6 +1,6 @@
1
1
  # Login and sessions
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Ludicord authentication follows the Embedded App SDK authorization-code flow:
@@ -1,15 +1,15 @@
1
- # Upgrading to Ludicord 4.1.0
1
+ # Upgrading to Ludicord 4.1.1
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
- Check that both 4.1.0 packages are available before upgrading:
5
+ Check that both 4.1.1 packages are available before upgrading:
6
6
 
7
7
  ```bash
8
8
  npm view ludicord version
9
9
  npm view create-ludicord-app version
10
10
  ```
11
11
 
12
- Update an existing application's framework dependency with `npm install ludicord@4.1.0` (or your package-manager equivalent), update its lockfile, and create a fresh production build. The generator is for new projects; do not run it over an existing non-empty application. Existing V3 trees remain supported through legacy compatibility mode; follow [the routing migration](migration-v4.md) before switching file conventions.
12
+ Update an existing application's framework dependency with `npm install ludicord@4.1.1` (or your package-manager equivalent), update its lockfile, and create a fresh production build. The generator is for new projects; do not run it over an existing non-empty application. Existing V3 trees remain supported through legacy compatibility mode; follow [the routing migration](migration-v4.md) before switching file conventions.
13
13
 
14
14
  ## Review your application
15
15
 
@@ -42,4 +42,4 @@ Update an existing application's framework dependency with `npm install ludicord
42
42
  - Every expected prefix pathname and default embed URL returns the correct shell.
43
43
  - Unknown production prefixes return 404 instead of falling through to an unrelated scope.
44
44
 
45
- Back up your current lockfile and keep the last deployable build for rollback. Review the detailed [V4 migration guide](migration-v4.md), [plugins and WebAssembly](plugins.md), [4.1.0 release notes](https://github.com/mrcholer/ludicord/blob/main/releases/v4/4.1.0.md), [security](security.md), and [deployment](deployment.md).
45
+ Back up your current lockfile and keep the last deployable build for rollback. Review the detailed [V4 migration guide](migration-v4.md), [plugins and WebAssembly](plugins.md), [4.1.1 release notes](https://github.com/mrcholer/ludicord/blob/main/releases/v4/4.1.1.md), [security](security.md), and [deployment](deployment.md).
@@ -1,6 +1,6 @@
1
1
  # Mobile and Layout
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Ludicord installs four CSS custom properties:
@@ -1,6 +1,6 @@
1
1
  # Navigation and generated route types
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Inside one prefix scope, use the Ludicord embed router. The current local embed is synchronized through the hash (`#/profile/user-one`) for deep links and browser back/forward, and hashes are validated against that prefix's generated registry:
@@ -1,6 +1,6 @@
1
1
  # Pages: page.tsx
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  A default-exported React component in `app/page.tsx` renders at `/`. Nested `page.tsx` files render at their directory paths. A page can render plain UI without any embed:
6
6
 
@@ -30,4 +30,10 @@ Do not hide an explicit Activity boundary in another component: keep it visible
30
30
 
31
31
  Automatic files are discovered without imports in the page: `layout.tsx` receives children, `loading.tsx` supplies a fallback, `error.tsx` receives error/reset, `minimize.tsx` supplies compact UI, and `auth/{loading,error,denied}.tsx` supplies sign-in states. Place them beside the page they configure. Embed directories can have their own layout/loading/error files. Production error components receive sanitized errors.
32
32
 
33
+ The HTML initially contains an accessible “Loading Activity…” shell, visible before the client modules finish loading. The selected page module starts downloading alongside its layout, loading component, and metadata. Those three convention files are prepared before React mounts; keep them small. Your `loading.tsx` then replaces the built-in shell while the page suspends. Global CSS can set `--ludicord-startup-background` and `--ludicord-startup-color` to match the Activity theme.
34
+
35
+ Error, not-found, minimized, and sign-in components load when rendered. Embed layouts, loading screens, and error screens also load on demand, so an unopened embed's UI modules do not block startup. Shared embed layouts retain their identity and state across hash navigation. Lazy convention screens use the page's loading component while downloading, or the built-in shell if none exists. A failed convention-screen import displays a safe reload screen. Keep essential startup work out of module-level side effects in deferred files.
36
+
37
+ See [startup measurements](development.md#startup-measurements) to identify the remaining delays.
38
+
33
39
  See [embeds](embeds.md), [project structure](project-structure.md), and [migration](migration-v4.md).
@@ -1,6 +1,6 @@
1
1
  # Participants
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  ```tsx
@@ -1,6 +1,6 @@
1
1
  # Page scopes and optional prefix navigation
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  ## Choose the simplest structure
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Project structure
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  The `app/` tree is the router. These four files define routes:
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Usage recipes
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  These small application examples illustrate the public API. They are not framework implementation or complete production applications.
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Security
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Ludicord encrypts and authenticates session cookies with AES-256-GCM, validates OAuth state, keeps server secrets out of React stores, requires sessions for API and WebSocket routes by default, and scans production client output for actual secret values.
@@ -1,6 +1,6 @@
1
1
  # Start
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Build once, then run the existing output:
@@ -1,6 +1,6 @@
1
1
  # React state and effects
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Ludicord is React, so ordinary React state is the first choice for ordinary interface state. Framework hooks add Activity-aware lifecycles; they do not replace `useState`, `useReducer`, or correct effect cleanup.
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Troubleshooting
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Run the checks relevant to the failure:
@@ -1,6 +1,6 @@
1
1
  # Voice Events
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Request the `rpc.voice.read` scope, then use:
@@ -1,6 +1,6 @@
1
1
  # WebSockets
2
2
 
3
- > Documentation for Ludicord 4.1.0. 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
  Create `app/ws/presence/socket.ts` for `/ws/presence`, or `app/live/socket.ts` for `/live`. The `ws/` folder is optional. A directory may contain only one route file. Use the full discovered URL in `useWS()`; no `/ws` prefix is added automatically.
@@ -45,7 +45,7 @@ export async function lintLudicordProject(projectRoot) {
45
45
  ludicord: {
46
46
  processors: {
47
47
  conventions: {
48
- meta: { name: "ludicord-conventions", version: "4.1.0" },
48
+ meta: { name: "ludicord-conventions", version: "4.1.1" },
49
49
  preprocess: (source, filename) => [normalizeConventionComponent(source, filename)],
50
50
  postprocess: (messages) => messages[0] ?? [],
51
51
  supportsAutofix: false,
@@ -8,6 +8,7 @@ import { useOptionalLudicordMinimize } from "./minimize.js";
8
8
  import { useLudicordFiles, isDevelopmentRuntime, reportClientError } from "./files.js";
9
9
  import { installLudicordSafeAreaVariables } from "../../discord/safe-area.js";
10
10
  import { compareRouteSpecificity } from "../../router/match.js";
11
+ import { startStartupStage, StartupCommit, StartupLoading } from "./startup.js";
11
12
  const EmbedContext = createContext(null);
12
13
  const HISTORY_INDEX = "__ludicordEmbedIndex";
13
14
  const lazyComponentCache = new WeakMap();
@@ -110,7 +111,12 @@ function loadEmbedModule(definition) {
110
111
  const cached = modulePromiseCache.get(definition.load);
111
112
  if (cached !== undefined)
112
113
  return cached;
113
- const promise = definition.load().catch((error) => {
114
+ const finish = startStartupStage("embed-module");
115
+ const promise = Promise.resolve().then(() => definition.load()).then((module) => {
116
+ finish();
117
+ return module;
118
+ }).catch((error) => {
119
+ finish("error");
114
120
  modulePromiseCache.delete(definition.load);
115
121
  throw error;
116
122
  });
@@ -127,11 +133,23 @@ function useEmbedContext() {
127
133
  export function LudicordActivity({ defaultEmbed, children, embeds, loading = null, errorFallback, }) {
128
134
  useEffect(() => {
129
135
  installLudicordSafeAreaVariables();
136
+ const finishDiscord = startStartupStage("discord");
130
137
  void initializeDiscordFromEnvironment()
131
138
  .then(async (discord) => {
132
- return initializeLudicordAuthFromEnvironment(discord);
139
+ finishDiscord(discord.status === "error" ? "error" : discord.status === "outside-discord" ? "skipped" : "complete");
140
+ const finishAuth = startStartupStage("auth");
141
+ try {
142
+ const auth = await initializeLudicordAuthFromEnvironment(discord);
143
+ finishAuth(auth === null ? "skipped" : "complete");
144
+ return auth;
145
+ }
146
+ catch (error) {
147
+ finishAuth("error");
148
+ throw error;
149
+ }
133
150
  })
134
151
  .catch(() => {
152
+ finishDiscord("error");
135
153
  // Public hooks surface initialization errors to the Activity UI.
136
154
  });
137
155
  }, []);
@@ -240,7 +258,7 @@ export function LudicordActivity({ defaultEmbed, children, embeds, loading = nul
240
258
  router,
241
259
  match,
242
260
  path: currentPath,
243
- loading: loading ?? (Loading === undefined ? null : _jsx(Loading, {})),
261
+ loading: loading ?? (Loading === undefined ? _jsx(StartupLoading, {}) : _jsx(Loading, {})),
244
262
  ...(errorFallback !== undefined ? { errorFallback } : ErrorFile === undefined ? {} : { errorFallback: (error) => _jsx(ErrorFile, { error: error, reset: () => window.dispatchEvent(new Event("ludicord:recover")) }) }),
245
263
  }), [currentPath, errorFallback, loading, match, router, Loading, ErrorFile]);
246
264
  return _jsx(EmbedContext.Provider, { value: value, children: _jsxs(ActivityAuthGate, { children: [_jsx("div", { hidden: minimized, style: { display: minimized ? "none" : "contents" }, children: children }), minimized && Minimized !== undefined ? _jsx(Minimized, {}) : null] }) });
@@ -253,7 +271,7 @@ function ActivityAuthGate({ children }) {
253
271
  // Standalone runtime/tests without generated config retain their explicit UI ownership.
254
272
  if (config?.authRequired !== true || (auth.session !== null && auth.session.expiresAt > Date.now()) ||
255
273
  (discord.status === "outside-discord" && config.environment === "development" && config.outsideDiscord === "allow"))
256
- return children;
274
+ return _jsx(StartupCommit, { milestone: "content-commit", children: children });
257
275
  const retry = () => { void initializeDiscordFromEnvironment().then((snapshot) => initializeLudicordAuthFromEnvironment(snapshot)).catch(() => undefined); };
258
276
  if (auth.status === "denied" && files.authDenied !== undefined) {
259
277
  const Denied = files.authDenied;
@@ -286,7 +304,7 @@ export function EmbedOutlet() {
286
304
  ? errorFallback
287
305
  : (error) => _jsx(RouteError, { error: error, reset: reset });
288
306
  const content = (match.definition.layouts ?? []).reduceRight((children, Layout) => _jsx(Layout, { children: children }), _jsx(Embed, {}));
289
- return (_jsx(LudicordErrorBoundary, { fallback: routeErrorFallback, resetKey: match.path, children: _jsx(LudicordLoadingBoundary, { fallback: routeFallback, children: content }) }));
307
+ return (_jsx(LudicordErrorBoundary, { fallback: routeErrorFallback, resetKey: match.path, children: _jsx(LudicordLoadingBoundary, { fallback: routeFallback, children: _jsx(StartupCommit, { milestone: "embed-commit", children: content }) }) }));
290
308
  }
291
309
  export function useEmbedRouter() {
292
310
  return useEmbedContext().router;
@@ -2,6 +2,8 @@ import type { ReactNode } from "react";
2
2
  import type { LudicordFileComponents } from "./files.js";
3
3
  import type { LudicordMetadata } from "../../metadata/index.js";
4
4
  export { matchPageRoute } from "../../router/prefix.js";
5
+ export { beginActivityStartup, deferredFile, startStartupStage, StartupError } from "./startup.js";
6
+ export { reportClientError } from "./files.js";
5
7
  export interface LudicordRootProps {
6
8
  readonly children: ReactNode;
7
9
  readonly files?: LudicordFileComponents;
@@ -3,7 +3,10 @@ import { useEffect, useState } from "react";
3
3
  import { LudicordErrorBoundary, LudicordLoadingBoundary } from "./embed-router.js";
4
4
  import { LudicordMinimizeProvider } from "./minimize.js";
5
5
  import { LudicordFilesContext } from "./files.js";
6
+ import { recordStartupMilestone, StartupLoading } from "./startup.js";
6
7
  export { matchPageRoute } from "../../router/prefix.js";
8
+ export { beginActivityStartup, deferredFile, startStartupStage, StartupError } from "./startup.js";
9
+ export { reportClientError } from "./files.js";
7
10
  function metadataTitle(title) {
8
11
  return typeof title === "string" ? title : title?.default;
9
12
  }
@@ -23,6 +26,7 @@ function updateMeta(name, content) {
23
26
  }
24
27
  export function LudicordRoot({ children, files = {}, metadata }) {
25
28
  const [revision, setRevision] = useState(0);
29
+ useEffect(() => recordStartupMilestone("root-commit"), []);
26
30
  useEffect(() => {
27
31
  const title = metadataTitle(metadata?.title);
28
32
  if (title !== undefined)
@@ -41,5 +45,5 @@ export function LudicordRoot({ children, files = {}, metadata }) {
41
45
  const Loading = files.loading;
42
46
  const ErrorFile = files.globalError ?? files.error;
43
47
  const reset = () => setRevision((value) => value + 1);
44
- return _jsx(LudicordFilesContext.Provider, { value: files, children: _jsx(LudicordMinimizeProvider, { children: _jsx(LudicordErrorBoundary, { resetKey: String(revision), fallback: ErrorFile === undefined ? undefined : (error) => _jsx(ErrorFile, { error: error, reset: reset }), children: _jsx(LudicordLoadingBoundary, { fallback: Loading === undefined ? null : _jsx(Loading, {}), children: Layout === undefined ? children : _jsx(Layout, { children: children }) }) }) }) });
48
+ return _jsx(LudicordFilesContext.Provider, { value: files, children: _jsx(LudicordMinimizeProvider, { children: _jsx(LudicordErrorBoundary, { resetKey: String(revision), fallback: ErrorFile === undefined ? undefined : (error) => _jsx(ErrorFile, { error: error, reset: reset }), children: _jsx(LudicordLoadingBoundary, { fallback: Loading === undefined ? _jsx(StartupLoading, {}) : _jsx(Loading, {}), children: Layout === undefined ? children : _jsx(Layout, { children: children }) }) }) }) });
45
49
  }
@@ -0,0 +1,17 @@
1
+ import type { ComponentType, ReactNode } from "react";
2
+ type Stage = "scope" | "page-module" | "discord" | "auth" | "embed-module";
3
+ type Milestone = "root-commit" | "content-commit" | "embed-commit";
4
+ export declare function beginActivityStartup(): () => void;
5
+ export declare function startStartupStage(stage: Stage): (status?: "complete" | "error" | "skipped") => void;
6
+ export declare function recordStartupMilestone(milestone: Milestone): void;
7
+ export declare function StartupCommit({ children, milestone }: {
8
+ readonly children: ReactNode;
9
+ readonly milestone: Milestone;
10
+ }): ReactNode;
11
+ export declare function StartupLoading(): import("react").JSX.Element;
12
+ export declare function StartupError(): import("react").JSX.Element;
13
+ /** Stable lazy convention components, declared once per generated page scope. */
14
+ export declare function deferredFile<TProps extends object>(load: () => Promise<{
15
+ readonly default: ComponentType<TProps>;
16
+ }>): ComponentType<TProps>;
17
+ export {};
@@ -0,0 +1,72 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Suspense, createElement, lazy, useEffect } from "react";
3
+ import { STARTUP_SHELL_STYLE } from "../startup-shell.js";
4
+ import { reportClientError, useLudicordFiles } from "./files.js";
5
+ const PREFIX = "ludicord:startup:";
6
+ let startup;
7
+ // Opted in by the generated entry only; standalone runtime consumers are untouched.
8
+ export function beginActivityStartup() {
9
+ const timing = globalThis.performance;
10
+ if (typeof timing?.mark !== "function" || typeof timing.measure !== "function")
11
+ return () => undefined;
12
+ for (const type of ["mark", "measure"]) {
13
+ for (const entry of timing.getEntriesByType(type)) {
14
+ if (entry.name.startsWith(PREFIX)) {
15
+ if (type === "mark")
16
+ timing.clearMarks(entry.name);
17
+ else
18
+ timing.clearMeasures(entry.name);
19
+ }
20
+ }
21
+ }
22
+ const current = { performance: timing, recorded: new Set(["runtime"]) };
23
+ startup = current;
24
+ timing.measure(`${PREFIX}runtime`, { start: 0, end: timing.now() });
25
+ return () => { if (startup === current)
26
+ startup = undefined; };
27
+ }
28
+ export function startStartupStage(stage) {
29
+ const current = startup;
30
+ if (current === undefined || current.recorded.has(stage))
31
+ return () => undefined;
32
+ current.recorded.add(stage);
33
+ const start = `${PREFIX}${stage}:start`;
34
+ current.performance.mark(start);
35
+ let finished = false;
36
+ return (status = "complete") => {
37
+ if (finished || startup !== current)
38
+ return;
39
+ finished = true;
40
+ const end = `${PREFIX}${stage}:end`;
41
+ current.performance.mark(end);
42
+ current.performance.measure(`${PREFIX}${stage}`, { start, end, detail: { status } });
43
+ };
44
+ }
45
+ export function recordStartupMilestone(milestone) {
46
+ const current = startup;
47
+ if (current === undefined || current.recorded.has(milestone))
48
+ return;
49
+ current.recorded.add(milestone);
50
+ current.performance.measure(`${PREFIX}${milestone}`, { start: 0, end: current.performance.now() });
51
+ }
52
+ export function StartupCommit({ children, milestone }) {
53
+ useEffect(() => recordStartupMilestone(milestone), [milestone]);
54
+ return children;
55
+ }
56
+ export function StartupLoading() {
57
+ return _jsx("div", { "data-ludicord-startup": "", role: "status", "aria-live": "polite", style: STARTUP_SHELL_STYLE, children: "Loading Activity\u2026" });
58
+ }
59
+ export function StartupError() {
60
+ return _jsx("main", { role: "alert", style: STARTUP_SHELL_STYLE, children: _jsxs("section", { children: [_jsx("p", { children: "The Activity couldn\u2019t load. Please try again." }), _jsx("button", { type: "button", onClick: () => window.location.reload(), children: "Reload" })] }) });
61
+ }
62
+ /** Stable lazy convention components, declared once per generated page scope. */
63
+ export function deferredFile(load) {
64
+ const Deferred = lazy(() => load().catch((cause) => {
65
+ reportClientError(cause instanceof Error ? cause : new Error(String(cause)));
66
+ return { default: StartupError };
67
+ }));
68
+ return function DeferredFile(props) {
69
+ const Loading = useLudicordFiles().loading;
70
+ return _jsx(Suspense, { fallback: Loading === undefined ? _jsx(StartupLoading, {}) : _jsx(Loading, {}), children: createElement(Deferred, props) });
71
+ };
72
+ }
@@ -10,6 +10,7 @@ import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
10
10
  import { generateManifests } from "../../compiler/scanner.js";
11
11
  import { generateLudicordTypes } from "../../compiler/type-generation.js";
12
12
  import { clientEntry } from "../../compiler/client-entry.js";
13
+ import { STARTUP_SHELL_HTML } from "../startup-shell.js";
13
14
  import { clientAliases, clientPlugins, ludicordLogger } from "../../compiler/client-tooling.js";
14
15
  import { bundleServerGraph } from "../../compiler/server-bundle.js";
15
16
  import { createLudicordAuthRouter } from "../../auth/server.js";
@@ -601,7 +602,7 @@ export async function createLudicordDevServer(options) {
601
602
  return;
602
603
  }
603
604
  try {
604
- const html = await vite?.transformIndexHtml(request.originalUrl, '<!doctype html><html><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Ludicord Activity</title></head><body><div id="ludicord-root"></div><script type="module" src="/@id/' + PANEL + '"></script><script type="module">import "' + ENTRY + '";</script></body></html>');
605
+ const html = await vite?.transformIndexHtml(request.originalUrl, '<!doctype html><html><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Ludicord Activity</title></head><body><div id="ludicord-root">' + STARTUP_SHELL_HTML + '</div><script type="module" src="/@id/' + PANEL + '"></script><script type="module">import "' + ENTRY + '";</script></body></html>');
605
606
  response.status(200).type("html").send(html);
606
607
  }
607
608
  catch (error) {
@@ -6,6 +6,7 @@ import express from "express";
6
6
  import { createApiMiddleware } from "../../api/runtime.js";
7
7
  import { createLudicordAuthRouter } from "../../auth/server.js";
8
8
  import { LUDICORD_BUILD_SCHEMA_VERSION, } from "../../compiler/build.js";
9
+ import { isHashedClientAsset } from "../../compiler/client-assets.js";
9
10
  import { attachWebSocketRuntime, } from "../../ws/server.js";
10
11
  import { LUDICORD_VERSION } from "../../version.js";
11
12
  import { loadProjectEnvironment } from "../../config/environment.js";
@@ -81,6 +82,12 @@ export async function createLudicordProductionServer(options) {
81
82
  const discordClientId = runtimeDiscordClientId(metadata.config.discord.clientId);
82
83
  const app = express();
83
84
  app.set("env", "production");
85
+ // Dynamic responses and failures are not cacheable unless a handler opts in.
86
+ // Static files and Activity documents apply their own policy below.
87
+ app.use((_request, response, next) => {
88
+ response.setHeader("Cache-Control", "no-store");
89
+ next();
90
+ });
84
91
  app.use(createLudicordRequestSecurity(metadata.config.server.allowedHosts, metadata.config.server.allowedOrigins, discordClientId));
85
92
  const httpServer = createServer(app);
86
93
  const sockets = new Set();
@@ -206,21 +213,48 @@ export async function createLudicordProductionServer(options) {
206
213
  onError: (error, file) => { void reportRequestError(error, "websocket", file); },
207
214
  });
208
215
  const clientDirectory = path.join(output, "client");
216
+ const immutableAssets = new Set((metadata.immutableAssets ?? [])
217
+ .filter(isHashedClientAsset)
218
+ .map((file) => path.resolve(clientDirectory, file)));
209
219
  const indexHtml = injectRuntimePublicConfig(readFileSync(path.join(clientDirectory, "index.html"), "utf8"), discordClientId);
210
220
  app.get("/index.html", (_request, response) => {
221
+ response.setHeader("Cache-Control", "no-cache");
211
222
  response.status(200).type("html").send(indexHtml);
212
223
  });
213
- app.use(express.static(clientDirectory, { index: false }));
224
+ app.use(express.static(clientDirectory, {
225
+ index: false,
226
+ etag: true,
227
+ lastModified: true,
228
+ setHeaders(response, file) {
229
+ response.setHeader("Cache-Control", immutableAssets.has(path.resolve(file))
230
+ ? "public, max-age=31536000, immutable"
231
+ : "no-cache");
232
+ },
233
+ }));
214
234
  app.use((request, response, next) => {
215
235
  if (request.method !== "GET" && request.method !== "HEAD") {
216
236
  next();
217
237
  return;
218
238
  }
239
+ // A removed chunk must not fall through to a catch-all Activity page.
240
+ // Keep missing asset responses uncacheable so a retry can recover.
241
+ let requestedFile;
242
+ try {
243
+ requestedFile = decodeURIComponent(request.path).replace(/^\/+/, "");
244
+ }
245
+ catch {
246
+ requestedFile = "";
247
+ }
248
+ if (isHashedClientAsset(requestedFile)) {
249
+ response.status(404).end();
250
+ return;
251
+ }
219
252
  const pathname = normalizeActivityPrefix(new URL(request.originalUrl, "http://ludicord.local").pathname);
220
253
  if (!matchPageRoute(manifests.prefixes, pathname)) {
221
254
  next();
222
255
  return;
223
256
  }
257
+ response.setHeader("Cache-Control", "no-cache");
224
258
  response.status(200).type("html").send(indexHtml);
225
259
  });
226
260
  app.use(async (error, _request, response, _next) => {
@@ -228,8 +262,10 @@ export async function createLudicordProductionServer(options) {
228
262
  method: _request.method,
229
263
  url: _request.originalUrl,
230
264
  });
231
- if (!response.headersSent)
265
+ if (!response.headersSent) {
266
+ response.setHeader("Cache-Control", "no-store");
232
267
  response.status(500).json({ error: "LUDICORD_INTERNAL_ERROR", message: "An internal error occurred. Please try again." });
268
+ }
233
269
  });
234
270
  const portOption = options.port ?? metadata.config.server.port;
235
271
  const host = options.host ?? metadata.config.server.host;
@@ -0,0 +1,12 @@
1
+ export declare const STARTUP_SHELL_STYLE: {
2
+ readonly minHeight: "100svh";
3
+ readonly display: "grid";
4
+ readonly placeItems: "center";
5
+ readonly boxSizing: "border-box";
6
+ readonly padding: "24px";
7
+ readonly fontFamily: "system-ui, sans-serif";
8
+ readonly fontSize: "14px";
9
+ readonly background: "var(--ludicord-startup-background, transparent)";
10
+ readonly color: "var(--ludicord-startup-color, inherit)";
11
+ };
12
+ export declare const STARTUP_SHELL_HTML: string;
@@ -0,0 +1,16 @@
1
+ // Shared by the HTML compiler and React fallback, so boot keeps the same shell.
2
+ export const STARTUP_SHELL_STYLE = {
3
+ minHeight: "100svh",
4
+ display: "grid",
5
+ placeItems: "center",
6
+ boxSizing: "border-box",
7
+ padding: "24px",
8
+ fontFamily: "system-ui, sans-serif",
9
+ fontSize: "14px",
10
+ background: "var(--ludicord-startup-background, transparent)",
11
+ color: "var(--ludicord-startup-color, inherit)",
12
+ };
13
+ const css = Object.entries(STARTUP_SHELL_STYLE)
14
+ .map(([name, value]) => `${name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`)}:${value}`)
15
+ .join(";");
16
+ export const STARTUP_SHELL_HTML = `<div data-ludicord-startup="" role="status" aria-live="polite" style="${css}">Loading Activity…</div>`;
@@ -3,7 +3,7 @@ name: ludicord
3
3
  description: "Build, modify, debug, review, or document Ludicord Discord Activities. Use for Activity roots, embeds, typed navigation, React state and effects, API or WebSocket routes, shared Activity state, Discord SDK data, participants, voice, authentication, security, configuration, compiler plugins, WebAssembly, development diagnostics, deployment, migration, and release compatibility."
4
4
  metadata:
5
5
  author: ludicord
6
- version: "4.1.0"
6
+ version: "4.1.1"
7
7
  ---
8
8
 
9
9
  # Ludicord
@@ -287,7 +287,7 @@ npx create-ludicord-app@latest my-activity --tailwind # scripted styling choice
287
287
  npx create-ludicord-app@latest my-activity --no-tailwind
288
288
  ```
289
289
 
290
- Generated 4.1.0 projects intentionally include only `dev`, `build`, and
290
+ Generated 4.1.1 projects intentionally include only `dev`, `build`, and
291
291
  `start` scripts. Run advanced commands with the project's package runner.
292
292
 
293
293
  ## Routed Intelligence References
@@ -1,5 +1,5 @@
1
1
  schema: 1
2
- framework_version: "4.1.0"
2
+ framework_version: "4.1.1"
3
3
  path_base: package-dist-or-repository-root
4
4
  canonical_skill: skills/ludicord/SKILL.md
5
5
  router: skills/ludicord/references/intelligence/skill-router.md
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const LUDICORD_VERSION = "4.1.0";
1
+ export const LUDICORD_VERSION = "4.1.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ludicord",
3
- "version": "4.1.0",
3
+ "version": "4.1.1",
4
4
  "description": "Full-stack React framework for Discord Activities.",
5
5
  "homepage": "https://github.com/mrcholer/ludicord#readme",
6
6
  "keywords": [