Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions apps/web/src/bootstrap.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { describe, expect, it, vi } from "vite-plus/test";

const mocks = vi.hoisted(() => ({ showBootError: vi.fn().mockName("showBootError") }));

vi.mock("./lib/bootError", () => ({ showBootError: mocks.showBootError }));

// Mirrors Vite's build preload helper when main's CSS or JS chunk fails to load.
vi.mock("./main", () => {
const error = new TypeError("Failed to fetch dynamically imported module: /assets/main.js");
const event = Object.assign(new Event("vite:preloadError", { cancelable: true }), {
payload: error,
});
window.dispatchEvent(event);
throw error;
});

function createStorageStub(initial: Record<string, string> = {}): Storage {
const store = new Map(Object.entries(initial));
return {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => {
store.set(key, value);
},
removeItem: (key) => {
store.delete(key);
},
clear: () => store.clear(),
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
};
}

async function bootWithFailingMainChunk(storage: Storage) {
vi.resetModules();
mocks.showBootError.mockClear();
const reload = vi.fn().mockName("location.reload");
vi.stubGlobal(
"window",
Object.assign(new EventTarget(), { sessionStorage: storage, location: { reload } }),
);
try {
const { boot } = await import("./bootstrap");
await boot;
return { reload, showBootError: mocks.showBootError };
} finally {
vi.unstubAllGlobals();
}
}

describe("bootstrap", () => {
it("reloads once instead of showing the boot error when the main chunk fails to load", async () => {
const { reload, showBootError } = await bootWithFailingMainChunk(createStorageStub());

expect(reload).toHaveBeenCalledTimes(1);
expect(showBootError).not.toHaveBeenCalled();
});

it("shows the boot error when the main chunk fails again after the reload", async () => {
const { reload, showBootError } = await bootWithFailingMainChunk(
createStorageStub({ "t3code:chunk-load-reloaded": import.meta.env.APP_VERSION }),
);

expect(reload).not.toHaveBeenCalled();
expect(showBootError).toHaveBeenCalledTimes(1);
});
});
9 changes: 8 additions & 1 deletion apps/web/src/bootstrap.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { showBootError } from "./lib/bootError";
import { chunkLoadState, handleChunkLoadErrors } from "./lib/chunkReloadGuard";

handleChunkLoadErrors();

// Shared dev chunks need the React refresh preamble first. Catch failures before React mounts.
void import("./main").then(({ startup }) => startup).catch(showBootError);
export const boot = import("./main")
.then(({ startup }) => startup)
.catch((error: unknown) => {
if (!chunkLoadState.reloadScheduled) showBootError(error);
});
8 changes: 7 additions & 1 deletion apps/web/src/bundledDev.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@ it("initializes React refresh before a shared UI chunk runs in bundled dev", asy
try {
await NodeFSP.mkdir(NodePath.join(root, "src/lib"), { recursive: true });
await NodeFSP.writeFile(NodePath.join(root, "package.json"), '{"type":"module"}');
for (const file of ["index.html", "src/bootstrap.ts", "src/lib/bootError.ts"]) {
for (const file of [
"index.html",
"src/bootstrap.ts",
"src/lib/bootError.ts",
"src/lib/chunkReloadGuard.ts",
]) {
await NodeFSP.copyFile(new URL(`../${file}`, import.meta.url), NodePath.join(root, file));
}
await NodeFSP.writeFile(
Expand Down Expand Up @@ -94,6 +99,7 @@ export const startup = Promise.resolve().then(() => globalThis.onStarted(Shared(
`import assert from "node:assert/strict";
const started = Promise.withResolvers();
globalThis.window = globalThis;
globalThis.addEventListener = () => {};
globalThis.document = {
createElement: () => ({ relList: { supports: () => true } }),
getElementById: () => null,
Expand Down
12 changes: 12 additions & 0 deletions apps/web/src/lib/chunkReloadGuard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,15 @@ export function isChunkLoadError(error: unknown): boolean {
message !== undefined && CHUNK_LOAD_ERROR_PREFIXES.some((prefix) => message.startsWith(prefix))
);
}

export const chunkLoadState = { reloadScheduled: false };

// Registered from the entry before main loads, so main-chunk and route-chunk failures share one decision.
export function handleChunkLoadErrors() {
window.addEventListener("vite:preloadError", (event) => {
if (reloadOnceForChunkLoadError()) {
chunkLoadState.reloadScheduled = true;
event.preventDefault();
}
});
}
6 changes: 3 additions & 3 deletions apps/web/src/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ vi.mock("./AppRoot", () => ({ AppRoot: () => null }));
vi.mock("./i18n/runtime", () => ({ whenLocaleReady: async () => {} }));
vi.mock("react-dom/client", () => ({ default: { createRoot: () => ({ render: () => {} }) } }));

// Boots main in a fresh page that shares the tab's sessionStorage, as a reload does.
// Boots the entry in a fresh page that shares the tab's sessionStorage, as a reload does.
async function bootThenFailLazyChunk(sessionStorage: Map<string, string>) {
vi.resetModules();
const reload = vi.fn().mockName("location.reload");
Expand All @@ -20,8 +20,8 @@ async function bootThenFailLazyChunk(sessionStorage: Map<string, string>) {
vi.stubGlobal("window", page);
vi.stubGlobal("document", { getElementById: () => ({}) });
try {
const { startup } = await import("./main");
await startup;
const { boot } = await import("./bootstrap");
await boot;
page.dispatchEvent(new Event("vite:preloadError", { cancelable: true }));
return reload;
} finally {
Expand Down
14 changes: 3 additions & 11 deletions apps/web/src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,12 @@ import { isElectron } from "./env";
import { startAppServices } from "./appInit";
import { AppRoot } from "./AppRoot";
import { whenLocaleReady } from "./i18n/runtime";
import { reloadOnceForChunkLoadError } from "./lib/chunkReloadGuard";
import { chunkLoadState } from "./lib/chunkReloadGuard";

const router = startAppServices();

const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined;

let reloadScheduled = false;
window.addEventListener("vite:preloadError", (event) => {
if (reloadOnceForChunkLoadError()) {
reloadScheduled = true;
event.preventDefault();
}
});

const app = <AppRoot router={router} />;

// Split by runtime to keep Clerk out of local startup and clerk-js out of browser builds.
Expand All @@ -40,7 +32,7 @@ export const startup = Promise.all([
])
.then(([ManagedAuthShell]) => {
// Route chunk failures resolve router.load() and surface later through the error boundary.
if (reloadScheduled) return;
if (chunkLoadState.reloadScheduled) return;
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
{ManagedAuthShell && clerkPublishableKey ? (
Expand All @@ -52,6 +44,6 @@ export const startup = Promise.all([
);
})
.catch((error: unknown) => {
if (reloadScheduled) return;
if (chunkLoadState.reloadScheduled) return;
throw error;
});
Loading