Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

🥅 Log Turbopack chunk registrations on module factory errors

Luke Vella818af71af4ed
diff --git a/apps/web/instrumentation-client.ts b/apps/web/instrumentation-client.ts
index f4563f06c..444afd4b3 100644
--- a/apps/web/instrumentation-client.ts
+++ b/apps/web/instrumentation-client.ts
@@ -10,6 +10,7 @@ import {
isModuleFactoryError,
reloadOnceForChunkError,
} from "@/lib/chunk-recovery";
+import { getChunkRegistrationContext } from "@/lib/chunk-registration-log";
const SENTRY_DSN = process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN;
@@ -50,7 +51,17 @@ Sentry.init({
...event.tags,
chunk_reloaded_recently: context.reloadedRecently,
};
- event.contexts = { ...event.contexts, chunk_recovery: context };
+ event.contexts = {
+ ...event.contexts,
+ chunk_recovery: context,
+ chunk_registrations: getChunkRegistrationContext(
+ String(
+ hint.originalException instanceof Error
+ ? hint.originalException.message
+ : hint.originalException,
+ ),
+ ),
+ };
}
return event;
},
diff --git a/apps/web/src/app/[locale]/layout.tsx b/apps/web/src/app/[locale]/layout.tsx
index 42e15143e..31e423b9e 100644
--- a/apps/web/src/app/[locale]/layout.tsx
+++ b/apps/web/src/app/[locale]/layout.tsx
@@ -19,6 +19,7 @@ import { InstancePolicyProvider } from "@/features/instance-policy/client";
import { loadInstancePolicy } from "@/features/instance-policy/loaders";
import { I18nProvider } from "@/i18n/client";
import { initI18next } from "@/i18n/i18n";
+import { chunkRegistrationLogScript } from "@/lib/chunk-registration-log";
import { TimeZoneSync } from "@/lib/datetime/timezone-sync";
import { FeatureFlagsProvider } from "@/lib/feature-flags/client";
import { featureFlagConfig } from "@/lib/feature-flags/config";
@@ -78,6 +79,12 @@ export default async function Root({
suppressHydrationWarning={true}
style={brandingStyles}
>
+ <head>
+ <script
+ // biome-ignore lint/security/noDangerouslySetInnerHtml: static diagnostics script with no user input
+ dangerouslySetInnerHTML={{ __html: chunkRegistrationLogScript }}
+ />
+ </head>
<body>
<ThemeProvider>
<FeatureFlagsProvider value={featureFlagConfig}>
diff --git a/apps/web/src/lib/chunk-registration-log.test.ts b/apps/web/src/lib/chunk-registration-log.test.ts
new file mode 100644
index 000000000..3af089a1e
--- /dev/null
+++ b/apps/web/src/lib/chunk-registration-log.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ chunkRegistrationLogScript,
+ getChunkRegistrationContext,
+} from "./chunk-registration-log";
+
+const g = globalThis as Record<string, unknown>;
+
+const script = (src: string) => ({ getAttribute: () => src });
+const chunk = (src: string, ...ids: number[]) => [
+ script(`https://static.rallly.co/_next/static/immutable/chunks/${src}`),
+ ...ids,
+ () => {},
+];
+
+// What every chunk does: `(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(...)`.
+const pushChunk = (entry: unknown) => {
+ if (!g.TURBOPACK) g.TURBOPACK = [];
+ (g.TURBOPACK as { push: (e: unknown) => void }).push(entry);
+};
+
+// Runs the exact string the layout inlines.
+const install = () => new Function(chunkRegistrationLogScript)();
+
+// Stands in for the Turbopack runtime: replay the queue, then take over push.
+function loadRuntime() {
+ const received: unknown[] = [];
+ const queued = g.TURBOPACK as unknown[];
+ g.TURBOPACK = { push: (entry: unknown) => received.push(entry) };
+ for (const entry of queued) received.push(entry);
+ return received;
+}
+
+afterEach(() => {
+ delete g.TURBOPACK;
+ delete g.__chunkRegistrations;
+ delete g.__chunkRegistrationsLate;
+});
+
+describe("installChunkRegistrationLog", () => {
+ it("records chunks queued before it, pushed after it, and after the runtime loads", () => {
+ g.TURBOPACK = [chunk("a.js", 1, 2)];
+ install();
+ pushChunk(chunk("b.js", 3));
+ const received = loadRuntime();
+ pushChunk(chunk("c.js", 4, 5));
+
+ expect(received).toHaveLength(3);
+ const context = getChunkRegistrationContext(
+ "Module 4 was instantiated because it was required from module 3, but the module factory is not available.",
+ );
+ expect(context).toMatchObject({
+ installedLate: false,
+ missingModule: 4,
+ missingModuleRegisteredBy: [{ file: "c.js" }],
+ requiredFrom: 3,
+ requiredFromRegisteredBy: [{ file: "b.js" }],
+ });
+ expect(context?.registrations.map((r) => [r.file, r.modules])).toEqual([
+ ["a.js", 2],
+ ["b.js", 1],
+ ["c.js", 2],
+ ]);
+ });
+
+ it("reports a missing module no chunk carried", () => {
+ install();
+ pushChunk(chunk("a.js", 1));
+ expect(
+ getChunkRegistrationContext(
+ "Module 9 was instantiated because it was required from module 1, but the module factory is not available.",
+ )?.missingModuleRegisteredBy,
+ ).toEqual([]);
+ });
+
+ it("flags a log installed after the runtime replayed the queue", () => {
+ g.TURBOPACK = { push: () => {} };
+ install();
+ pushChunk(chunk("a.js", 1));
+ expect(getChunkRegistrationContext("")).toMatchObject({
+ installedLate: true,
+ registrations: [{ file: "a.js", modules: 1 }],
+ });
+ });
+
+ it("records a null src when the chunk has no current script", () => {
+ install();
+ pushChunk([undefined, 1, () => {}]);
+ expect(getChunkRegistrationContext("")?.registrations[0]?.file).toBe(null);
+ });
+});
+
+describe("getChunkRegistrationContext", () => {
+ it("returns nothing when the log was never installed", () => {
+ expect(getChunkRegistrationContext("")).toBeUndefined();
+ });
+});
diff --git a/apps/web/src/lib/chunk-registration-log.ts b/apps/web/src/lib/chunk-registration-log.ts
new file mode 100644
index 000000000..3e2114a58
--- /dev/null
+++ b/apps/web/src/lib/chunk-registration-log.ts
@@ -0,0 +1,118 @@
+// Records every chunk Turbopack registers so a module factory error can say
+// whether the chunk holding the missing module ever ran, and under which
+// script src. Chunks hand their modules to `globalThis.TURBOPACK.push`: an
+// array until the runtime loads, then the runtime's own object, which this
+// wraps when the runtime assigns it.
+
+type ChunkRegistration = { src: string | null; ids: number[]; at: number };
+
+type ChunkRegistrationGlobal = {
+ TURBOPACK?: { push: (...entries: unknown[]) => unknown };
+ __chunkRegistrations?: ChunkRegistration[];
+ __chunkRegistrationsLate?: boolean;
+};
+
+// Serialized into an inline <head> script, so it must stay self contained: no
+// imports and no references to anything else in this module.
+export function installChunkRegistrationLog() {
+ try {
+ const g = globalThis as unknown as ChunkRegistrationGlobal;
+ if (g.__chunkRegistrations) return;
+ const log: ChunkRegistration[] = [];
+ g.__chunkRegistrations = log;
+
+ const record = (entry: unknown) => {
+ // The runtime chunk pushes [script, params]; other pushes are
+ // [script, ...moduleIds and factories].
+ if (!Array.isArray(entry)) return;
+ const script = entry[0] as { getAttribute?: (name: string) => string };
+ const ids: number[] = [];
+ for (let i = 1; i < entry.length; i++) {
+ if (typeof entry[i] === "number") ids.push(entry[i]);
+ }
+ log.push({
+ src:
+ typeof script === "string"
+ ? script
+ : typeof script?.getAttribute === "function"
+ ? script.getAttribute("src")
+ : null,
+ ids,
+ at: Math.round(performance.now()),
+ });
+ };
+
+ const wrap = (
+ target: NonNullable<ChunkRegistrationGlobal["TURBOPACK"]>,
+ ) => {
+ const push = target.push;
+ target.push = function (this: unknown, ...entries: unknown[]) {
+ for (const entry of entries) record(entry);
+ return push.apply(this, entries);
+ };
+ };
+
+ let current = g.TURBOPACK;
+ if (Array.isArray(current)) {
+ // Chunks that ran before this script are still queued for the runtime.
+ for (const entry of current) record(entry);
+ wrap(current);
+ } else if (current) {
+ // The runtime already replayed the queue, so earlier chunks are lost.
+ g.__chunkRegistrationsLate = true;
+ wrap(current);
+ }
+
+ Object.defineProperty(g, "TURBOPACK", {
+ configurable: true,
+ enumerable: true,
+ get: () => current,
+ // The first chunk creates the queue array; the runtime replaces it.
+ set: (value: ChunkRegistrationGlobal["TURBOPACK"]) => {
+ if (value) wrap(value);
+ current = value;
+ },
+ });
+ } catch {
+ // Diagnostics only; never break page boot.
+ }
+}
+
+export const chunkRegistrationLogScript = `(${installChunkRegistrationLog.toString()})()`;
+
+function fileName(src: string | null) {
+ return src === null ? null : src.slice(src.lastIndexOf("/") + 1);
+}
+
+export function getChunkRegistrationContext(message: string) {
+ const g = globalThis as unknown as ChunkRegistrationGlobal;
+ const log = g.__chunkRegistrations;
+ if (!Array.isArray(log)) return undefined;
+
+ const match = message.match(
+ /Module (\d+) was instantiated (?:because it was required from module (\d+))?/,
+ );
+ const missingModule = match ? Number(match[1]) : undefined;
+ const requiredFrom = match?.[2] ? Number(match[2]) : undefined;
+ const registeredBy = (id: number | undefined) =>
+ id === undefined
+ ? []
+ : log
+ .filter((entry) => entry.ids.includes(id))
+ .map((entry) => ({ file: fileName(entry.src), at: entry.at }));
+
+ return {
+ installedLate: g.__chunkRegistrationsLate === true,
+ at: Math.round(performance.now()),
+ missingModule,
+ // Empty means no chunk carrying the module ran before the error.
+ missingModuleRegisteredBy: registeredBy(missingModule),
+ requiredFrom,
+ requiredFromRegisteredBy: registeredBy(requiredFrom),
+ registrations: log.map((entry) => ({
+ file: fileName(entry.src),
+ modules: entry.ids.length,
+ at: entry.at,
+ })),
+ };
+}