Open History to see the last commit
1// Split chunks are fetched lazily, so a deploy (or desktop server swap)
2// between page load and a later fetch can 404 the old hashed assets. One
3// reload picks up the fresh index.html. Remember failures per build so a
4// persistent failure cannot loop and later deploys still get a reload.
5const CHUNK_RELOAD_GUARD_KEY = "t3code:chunk-load-reloads";
6const MAX_CHUNK_RELOADS = 20;
7
8/** Returns whether the preload-error listener should swallow the failure for a reload. */
9export function reloadOnceForChunkLoadError(
10 build: string,
11 failure: string,
12 getStorage: () => Storage = () => window.sessionStorage,
13 reload: () => void = () => window.location.reload(),
14): boolean {
15 try {
16 const storage = getStorage();
17 const stored: unknown = JSON.parse(storage.getItem(CHUNK_RELOAD_GUARD_KEY) ?? "null");
18 const reloaded =
19 stored !== null &&
20 typeof stored === "object" &&
21 "build" in stored &&
22 stored.build === build &&
23 "failures" in stored &&
24 Array.isArray(stored.failures)
25 ? stored.failures
26 : [];
27 if (reloaded.includes(failure) || reloaded.length >= MAX_CHUNK_RELOADS) return false;
28 storage.setItem(
29 CHUNK_RELOAD_GUARD_KEY,
30 JSON.stringify({ build, failures: [...reloaded, failure] }),
31 );
32 } catch {
33 // Without storage the guard cannot survive a reload, so a persistent
34 // failure would loop forever. Let the error surface instead.
35 return false;
36 }
37 reload();
38 return true;
39}
40
41let speculativeLoads = 0;
42const speculativeFailures = new WeakSet<object>();
43
44/** Swallow speculative failures; real use must import again to retry and get a guarded reload. */
45export function preloadSpeculatively<T>(load: () => Promise<T>): Promise<T | undefined> {
46 speculativeLoads += 1;
47 return new Promise<T>((resolve) => resolve(load())).then(
48 (value) => {
49 speculativeLoads -= 1;
50 return value;
51 },
52 (error: unknown) => {
53 if (typeof error === "object" && error !== null) speculativeFailures.add(error);
54 speculativeLoads -= 1;
55 return undefined;
56 },
57 );
58}
59
60// Rejections settle after vite:preloadError, so the listener must check ownership a task later.
61export function isSpeculativeLoadPending(): boolean {
62 return speculativeLoads > 0;
63}
64
65export function isSpeculativeLoadFailure(failure: unknown): boolean {
66 return typeof failure === "object" && failure !== null && speculativeFailures.has(failure);
67}
68
69let routePreloads = 0;
70
71// Route components retain chunk failures and reload on navigation; leave those failures to them.
72export function preloadRouteSpeculatively<T>(load: () => Promise<T>): Promise<T> {
73 routePreloads += 1;
74 return new Promise<T>((resolve) => resolve(load())).finally(() => {
75 routePreloads -= 1;
76 });
77}
78
79export function isRoutePreloadPending(): boolean {
80 return routePreloads > 0;
81}