Commit 8eeb1f6f authored by Jimmy Lai's avatar Jimmy Lai

Add retry logic for chunk load errors

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: 's avatarClaude Opus 4.5 <noreply@anthropic.com>
parent f2573ed3
......@@ -973,5 +973,6 @@
"972": "Failed to resolve pattern \"%s\": %s",
"973": "Server Actions are not enabled for this application. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"974": "Failed to find Server Action%s. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"975": "Failed to find Server Action. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action"
"975": "Failed to find Server Action. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"976": "Chunk load failed after retry attempts"
}
......@@ -81,6 +81,7 @@ import {
} from './create-compiler-aliases'
import { hasCustomExportOutput } from '../export/utils'
import { CssChunkingPlugin } from './webpack/plugins/css-chunking-plugin'
import { ChunkCacheClearPlugin } from './webpack/plugins/chunk-cache-clear-plugin'
import {
getBabelLoader,
getReactCompilerLoader,
......@@ -2039,6 +2040,8 @@ export default async function getBaseWebpackConfig(
runtimeAsset: `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`,
dev,
}),
// Expose chunk cache clearing for retry logic (webpack only - Turbopack has its own mechanism)
isClient && !isRspack && new ChunkCacheClearPlugin(),
isNodeServer &&
!dev &&
new ((
......
import type { webpack } from 'next/dist/compiled/webpack/webpack'
const PLUGIN_NAME = 'ChunkCacheClearPlugin'
/**
* This plugin exposes a global function to clear webpack's chunk cache (installedChunks).
* This allows Next.js to retry loading chunks after a failure.
*
* Webpack caches chunk loading promises in `installedChunks`, which is a private variable
* inside the JSONP chunk loading runtime. When a chunk fails to load, the rejected promise
* is cached and subsequent loads return the same rejected promise.
*
* This plugin adds code to the webpack runtime that exposes `__next_clear_chunk_cache__`
* on globalThis, allowing Next.js to clear failed entries before retrying.
*/
export class ChunkCacheClearPlugin {
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
// Hook into runtime module generation
compilation.hooks.runtimeModule.tap(PLUGIN_NAME, (module) => {
// Target the jsonp chunk loading module (used in browsers)
// The module name varies by webpack version, so check for common names
const moduleName = module.name || ''
if (
moduleName === 'jsonp chunk loading' ||
moduleName === 'chunk loading' ||
moduleName.includes('chunk loading')
) {
// Get the original generated code
const originalGenerateCode = module.generate?.bind(module)
if (originalGenerateCode) {
module.generate = function () {
const code = originalGenerateCode()
if (typeof code !== 'string') return code
// Find where installedChunks is defined and inject our clearing function
// The pattern is: var installedChunks = { ... };
const installedChunksPattern =
/(var\s+installedChunks\s*=\s*\{[^}]*\};?)/
if (installedChunksPattern.test(code)) {
const injectedCode = `
// Next.js chunk cache clearing for retry logic
if (typeof globalThis !== 'undefined') {
globalThis.__next_clear_chunk_cache__ = function(chunkId) {
// Only clear if not already loaded (0 means loaded)
if (installedChunks[chunkId] !== 0 && installedChunks[chunkId] !== undefined) {
delete installedChunks[chunkId];
}
};
}
`
return code.replace(
installedChunksPattern,
`$1\n${injectedCode}`
)
}
return code
}
}
}
})
})
}
}
/**
* Type definitions for chunk load error handling.
* Chunk load error handling with silent retry logic.
*
* This module is intentionally minimal - it only provides types.
* No retry logic, no escalation logic, no background failure handling.
* This module provides retry orchestration for chunk/network loading failures.
* It tracks failures in sessionStorage per {route, buildId, chunkKey} and
* implements silent retry with jittered backoff.
*/
export type ChunkErrorAction = 'banner'
import { getAppBuildId } from '../../app-build-id'
import { isChunkLoadError, isNetworkError } from './is-chunk-load-error'
// Bundler-specific chunk cache clearing globals
declare global {
var __turbopack_clear_chunk_resolver__:
| ((chunkUrl: string) => void)
| undefined
var __next_clear_chunk_cache__: ((chunkId: string) => void) | undefined
}
export type ChunkErrorAction = 'retry' | 'banner'
/**
* Context for chunk error handling.
* Tracks where the error occurred and what kind of error it was.
*/
export interface ChunkErrorContext {
/** The current route/pathname */
route: string
/** Whether this error is blocking a user-visible operation (navigation, render) */
userVisible: boolean
/** Error message for generating chunk key */
message: string
/** URL of the failed chunk if extractable */
chunkUrl?: string
}
interface FailureState {
failCount: number
lastTs: number
retriedTs?: number
}
const STORAGE_PREFIX = '__next_chunk_fail:'
const RETRY_WINDOW_MS = 30_000 // Don't retry same chunk within 30s of a retry
const MAX_FAIL_COUNT_FOR_RETRY = 2 // After 2 failures, skip silent retry
/**
* Simple hash function for generating chunk keys when URL isn't available.
*/
function simpleHash(str: string): string {
let hash = 0
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i)
hash = ((hash << 5) - hash + char) | 0
}
return Math.abs(hash).toString(36)
}
/**
* Extract chunk URL from error message if possible.
* ChunkLoadError messages typically contain the URL.
*/
function extractChunkUrl(error: Error): string | undefined {
const message = error.message
// Turbopack format: "Failed to load chunk <url> from <reason>: <cause>"
// The URL can be relative (/_next/...) or absolute (http://...)
const turbopackMatch = message.match(
/Failed to load chunk ([^\s]+\.(?:js|css))/
)
if (turbopackMatch) {
return turbopackMatch[1]
}
// Webpack format: "Loading chunk <id> failed. (error: <url>)"
const webpackMatch = message.match(/https?:\/\/[^\s)]+/)
return webpackMatch?.[0]
}
/**
* Extract the chunk ID from a webpack chunk URL.
* URLs look like: /_next/static/chunks/123.hash.js
*/
function extractWebpackChunkId(chunkUrl: string): string | undefined {
// Match chunk ID from URL path: /chunks/123.abc123.js or /chunks/pages_foo_bar.abc123.js
const match = chunkUrl.match(/\/chunks\/([^/.]+)\.[a-f0-9]+\.js/)
return match?.[1]
}
/**
* Clear the bundler's chunk cache so retry will fetch fresh.
* Works for both Turbopack and Webpack.
*
* @param error - The chunk load error
* @returns true if cache was cleared, false otherwise
*/
export function clearChunkCache(error: Error): boolean {
const chunkUrl = extractChunkUrl(error)
if (!chunkUrl) return false
// Turbopack: clear by chunk URL
if (typeof globalThis.__turbopack_clear_chunk_resolver__ === 'function') {
// Extract the relative URL path that Turbopack uses as key
try {
const url = new URL(chunkUrl)
globalThis.__turbopack_clear_chunk_resolver__(url.pathname + url.search)
return true
} catch {
// Invalid URL, try using the full URL
globalThis.__turbopack_clear_chunk_resolver__(chunkUrl)
return true
}
}
// Webpack: extract chunk ID from URL and clear by ID
if (typeof globalThis.__next_clear_chunk_cache__ === 'function') {
const chunkId = extractWebpackChunkId(chunkUrl)
if (chunkId) {
globalThis.__next_clear_chunk_cache__(chunkId)
return true
}
}
return false
}
/**
* Generate a unique key for this chunk error, used for deduplication.
*/
function getChunkKey(ctx: ChunkErrorContext): string {
return ctx.chunkUrl ?? simpleHash(ctx.message)
}
/**
* Get the sessionStorage key for tracking this chunk failure.
*/
function getStorageKey(ctx: ChunkErrorContext): string {
const buildId = getAppBuildId()
const chunkKey = getChunkKey(ctx)
return `${STORAGE_PREFIX}${buildId}:${ctx.route}:${chunkKey}`
}
/**
* Read failure state from sessionStorage.
*/
function readFailureState(key: string): FailureState | null {
if (typeof sessionStorage === 'undefined') return null
try {
const stored = sessionStorage.getItem(key)
if (!stored) return null
return JSON.parse(stored) as FailureState
} catch {
return null
}
}
/**
* Write failure state to sessionStorage.
*/
function writeFailureState(key: string, state: FailureState): void {
if (typeof sessionStorage === 'undefined') return
try {
sessionStorage.setItem(key, JSON.stringify(state))
} catch {
// Storage might be full or disabled - continue without tracking
}
}
/**
* Clear failure state for a route (called on successful navigation).
*/
export function clearFailureState(route: string): void {
if (typeof sessionStorage === 'undefined') return
try {
const buildId = getAppBuildId()
const prefix = `${STORAGE_PREFIX}${buildId}:${route}:`
const keysToRemove: string[] = []
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i)
if (key?.startsWith(prefix)) {
keysToRemove.push(key)
}
}
keysToRemove.forEach((key) => sessionStorage.removeItem(key))
} catch {
// Ignore storage errors
}
}
/**
* Increment the failure count for this chunk.
*/
function bumpFailCount(ctx: ChunkErrorContext): FailureState {
const key = getStorageKey(ctx)
const existing = readFailureState(key)
const now = Date.now()
const state: FailureState = {
failCount: (existing?.failCount ?? 0) + 1,
lastTs: now,
retriedTs: existing?.retriedTs,
}
writeFailureState(key, state)
return state
}
/**
* Mark that a retry was attempted for this chunk.
*/
function markRetried(ctx: ChunkErrorContext): void {
const key = getStorageKey(ctx)
const existing = readFailureState(key)
const now = Date.now()
const state: FailureState = {
failCount: existing?.failCount ?? 1,
lastTs: existing?.lastTs ?? now,
retriedTs: now,
}
writeFailureState(key, state)
}
/**
* Check if we should attempt a silent retry for this chunk error.
*/
export function shouldSilentRetry(ctx: ChunkErrorContext): boolean {
// Don't retry if offline
if (typeof navigator !== 'undefined' && !navigator.onLine) {
return false
}
const key = getStorageKey(ctx)
const state = readFailureState(key)
const now = Date.now()
// If we already retried within the window, don't retry again
if (state?.retriedTs && now - state.retriedTs < RETRY_WINDOW_MS) {
return false
}
// Too many failures - skip silent retry to avoid annoying the user
if ((state?.failCount ?? 0) >= MAX_FAIL_COUNT_FOR_RETRY) {
return false
}
return true
}
/**
* Get the failure count for this chunk (for showing "hard refresh" hint).
*/
export function getFailCount(ctx: ChunkErrorContext): number {
const key = getStorageKey(ctx)
const state = readFailureState(key)
return state?.failCount ?? 0
}
/**
* Calculate retry delay with jitter based on RTT.
* Returns delay in milliseconds: 200 + random(0-400) + min(500, RTT)
*/
export function getRetryDelayMs(): number {
const baseDelay = 200
const jitter = Math.floor(Math.random() * 401) // 0-400ms
// Get RTT if available via Network Information API
let rtt = 0
if (typeof navigator !== 'undefined' && 'connection' in navigator) {
const connection = (navigator as any).connection
if (connection?.rtt) {
rtt = Math.min(500, connection.rtt) // Cap at 500ms
}
}
return Math.min(1500, baseDelay + jitter + rtt) // Cap total at 1500ms
}
/**
* Sleep for a given number of milliseconds.
*/
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/**
* Create a ChunkErrorContext from an error.
*/
export function createChunkErrorContext(
error: Error,
route: string,
userVisible: boolean = true
): ChunkErrorContext | null {
if (!isChunkLoadError(error) && !isNetworkError(error)) {
return null
}
return {
route,
userVisible,
message: error.message,
chunkUrl: extractChunkUrl(error),
}
}
/**
* Handle a chunk load failure.
*
* Returns 'retry' if a silent retry should be attempted,
* or 'banner' if the error should be shown to the user.
*
* This function updates the failure tracking state.
*/
export function handleChunkFailure(ctx: ChunkErrorContext): ChunkErrorAction {
// Always increment fail count first
bumpFailCount(ctx)
// Check if we should try a silent retry
if (shouldSilentRetry(ctx)) {
markRetried(ctx)
return 'retry'
}
// Show banner to the user
return 'banner'
}
/**
* Attempt to retry a failed chunk import.
*
* @param ctx - The chunk error context
* @param importFn - The function that performs the import
* @returns The result of the import, or throws if retry also fails
*/
export async function retryChunkImport<T>(
ctx: ChunkErrorContext,
importFn: () => Promise<T>
): Promise<T> {
const action = handleChunkFailure(ctx)
if (action === 'retry') {
const delay = getRetryDelayMs()
await sleep(delay)
return importFn()
}
// If we shouldn't retry, re-throw to trigger error boundary
throw new Error('Chunk load failed after retry attempts')
}
......@@ -26,6 +26,13 @@ import {
NEXT_HTML_REQUEST_ID_HEADER,
NEXT_REQUEST_ID_HEADER,
} from '../app-router-headers'
import { isChunkOrNetworkError } from '../chunk-load-error/is-chunk-load-error'
import {
createChunkErrorContext,
handleChunkFailure,
getRetryDelayMs,
sleep,
} from '../chunk-load-error/chunk-load-error-handler'
import { callServer } from '../../app-call-server'
import { findSourceMapURL } from '../../app-find-source-map-url'
import {
......@@ -264,6 +271,44 @@ export async function fetchServerResponse(
debugInfo: flightResponsePromise._debugInfo ?? null,
}
} catch (err) {
// Check if this is a chunk/network error that we can retry
if (
err instanceof Error &&
isChunkOrNetworkError(err) &&
!isPageUnloading
) {
const ctx = createChunkErrorContext(
err,
originalUrl.pathname,
true // user-visible navigation
)
if (ctx) {
// handleChunkFailure updates failure tracking and returns action
const action = handleChunkFailure(ctx)
if (action === 'retry') {
// Silent retry with jittered delay
const delay = getRetryDelayMs()
await sleep(delay)
try {
// Retry the fetch once
return await fetchServerResponse(url, options)
} catch (retryErr) {
// Retry failed, fall through to MPA navigation
if (!isPageUnloading) {
console.error(
`Retry failed for RSC payload ${originalUrl}. Falling back to browser navigation.`,
retryErr
)
}
return originalUrl.toString()
}
}
}
}
if (!isPageUnloading) {
console.error(
`Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,
......
......@@ -2,6 +2,11 @@ import { Suspense, Fragment, lazy } from 'react'
import { BailoutToCSR } from './dynamic-bailout-to-csr'
import type { ComponentModule } from './types'
import { PreloadChunks } from './preload-chunks'
import { isChunkLoadError } from '../../../client/components/chunk-load-error/is-chunk-load-error'
import {
clearChunkCache,
getRetryDelayMs,
} from '../../../client/components/chunk-load-error/chunk-load-error-handler'
// Normalize loader to return the module as form { default: Component } for `React.lazy`.
// Also for backward compatible since next/dynamic allows to resolve a component directly with loader
......@@ -25,6 +30,40 @@ function convertModule<P>(
}
}
/**
* Creates a loader function with automatic retry for chunk load errors.
* On first failure, clears the bundler cache and retries after a delay.
*/
function createRetryableLoader<T>(loader: () => Promise<T>): () => Promise<T> {
let hasRetried = false
return () =>
loader().catch((err) => {
// Only retry chunk load errors, and only once
if (
typeof window !== 'undefined' &&
isChunkLoadError(err) &&
!hasRetried
) {
hasRetried = true
// Clear bundler's chunk cache so retry will fetch fresh
clearChunkCache(err)
// Retry after a short delay with jitter
return new Promise<T>((resolve, reject) => {
const delay = getRetryDelayMs()
setTimeout(() => {
loader().then(resolve, reject)
}, delay)
})
}
// No retry - propagate error
throw err
})
}
const defaultOptions = {
loader: () => Promise.resolve(convertModule(() => null)),
loading: null,
......@@ -40,7 +79,11 @@ interface LoadableOptions {
function Loadable(options: LoadableOptions) {
const opts = { ...defaultOptions, ...options }
const Lazy = lazy(() => opts.loader().then(convertModule))
// Wrap loader with retry logic for chunk load errors (client-side only)
const retryableLoader = createRetryableLoader(() =>
opts.loader().then(convertModule)
)
const Lazy = lazy(retryableLoader)
const Loading = opts.loading
function LoadableComponent(props: any) {
......
......@@ -24,6 +24,11 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
import React from 'react'
import { LoadableContext } from './loadable-context.shared-runtime'
import { isChunkLoadError } from '../../client/components/chunk-load-error/is-chunk-load-error'
import {
clearChunkCache,
getRetryDelayMs,
} from '../../client/components/chunk-load-error/chunk-load-error-handler'
function resolve(obj: any) {
return obj && obj.default ? obj.default : obj
......@@ -167,12 +172,14 @@ class LoadableSubscription {
_timeout: any
_res: any
_state: any
_hasAutoRetried: boolean
constructor(loadFn: any, opts: any) {
this._loadFn = loadFn
this._opts = opts
this._callbacks = new Set()
this._delay = null
this._timeout = null
this._hasAutoRetried = false
this.retry()
}
......@@ -217,7 +224,28 @@ class LoadableSubscription {
this._update({})
this._clearTimeouts()
})
.catch((_err: any) => {
.catch((err: any) => {
// Auto-retry for chunk load errors (once)
// This handles transient network failures during dynamic imports
if (
typeof window !== 'undefined' &&
isChunkLoadError(err) &&
!this._hasAutoRetried
) {
this._hasAutoRetried = true
// Clear bundler's chunk cache so retry will fetch fresh
clearChunkCache(err)
// Retry after a short delay with jitter
const delay = getRetryDelayMs()
setTimeout(() => {
this.retry()
}, delay)
return
}
// No more retries - propagate error
this._update({})
this._clearTimeouts()
})
......
......@@ -5,7 +5,7 @@ import fs from 'fs'
import { retry } from 'next-test-utils'
describe('chunk-load-error-banner', () => {
const { next } = nextTestSetup({
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
})
......@@ -138,7 +138,7 @@ describe('chunk-load-error-banner', () => {
})
// Verify error message format
if (process.env.IS_TURBOPACK_TEST) {
if (isTurbopack) {
expect(capturedError!.message).toContain('Failed to load chunk')
} else {
expect(capturedError!.message).toMatch(/Loading chunk .* failed/)
......@@ -233,4 +233,205 @@ describe('chunk-load-error-banner', () => {
expect(hasAlertRole).toBe(true)
})
})
describe('Auto-Retry with Cache Clearing', () => {
it('should expose chunk cache clearing global for Turbopack', async () => {
if (!isTurbopack) {
return
}
const browser = await next.browser('/dynamic')
const hasGlobal = await browser.eval(() => {
return (
typeof (globalThis as any).__turbopack_clear_chunk_resolver__ ===
'function'
)
})
expect(hasGlobal).toBe(true)
})
it('should expose chunk cache clearing global for Webpack', async () => {
if (isTurbopack) {
return
}
const browser = await next.browser('/dynamic')
const hasGlobal = await browser.eval(() => {
return (
typeof (globalThis as any).__next_clear_chunk_cache__ === 'function'
)
})
expect(hasGlobal).toBe(true)
})
it('should retry dynamic import failure once before showing banner', async () => {
const lazyChunk = await getLazyComponentChunk()
let requestCount = 0
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
requestCount++
if (requestCount === 1) {
// First request fails
await route.abort('connectionreset')
} else {
// Retry succeeds
await route.continue()
}
})
},
})
// Component should render after retry
await retry(async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toContain(
'this is a lazy loaded async component'
)
})
// Verify 2 requests were made (original + retry)
expect(requestCount).toBe(2)
})
it('should show banner if retry also fails', async () => {
const lazyChunk = await getLazyComponentChunk()
let requestCount = 0
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
requestCount++
await route.abort('connectionreset') // Always fail
})
},
})
// Banner should show after retry exhausted
await retry(async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toContain(
"This page couldn't be fully loaded"
)
})
// Should have made 2 requests (original + 1 retry)
expect(requestCount).toBe(2)
})
it('should have delay between original request and retry', async () => {
const lazyChunk = await getLazyComponentChunk()
const requestTimes: number[] = []
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
requestTimes.push(Date.now())
if (requestTimes.length === 1) {
await route.abort('connectionreset')
} else {
await route.continue()
}
})
},
})
// Wait for component to render
await retry(async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toContain(
'this is a lazy loaded async component'
)
})
// Verify delay between requests (should be ~200-500ms)
expect(requestTimes.length).toBe(2)
const delay = requestTimes[1] - requestTimes[0]
expect(delay).toBeGreaterThanOrEqual(150) // Allow some tolerance
expect(delay).toBeLessThan(2000)
})
})
describe('Error Handling Behavior', () => {
it('should show banner for chunk load failure in next/dynamic', async () => {
const lazyChunk = await getLazyComponentChunk()
let requestCount = 0
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
requestCount++
await route.abort('connectionreset')
})
},
})
// Wait for the banner to appear
await retry(async () => {
const body = await browser.elementByCss('body')
const text = await body.text()
expect(text).toContain("This page couldn't be fully loaded")
})
// Should have made 2 requests (original + 1 retry)
expect(requestCount).toBe(2)
})
it('should preserve frozen content when chunk load fails', async () => {
const lazyChunk = await getLazyComponentChunk()
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
await route.abort('connectionreset')
})
},
})
// Wait for banner to appear
await retry(async () => {
const body = await browser.elementByCss('body')
const text = await body.text()
// Both banner and original page content should be visible
expect(text).toContain("This page couldn't be fully loaded")
expect(text).toContain('Dynamic Page')
})
})
it('should allow subsequent navigation after chunk error', async () => {
const lazyChunk = await getLazyComponentChunk()
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
await route.abort('connectionreset')
})
},
})
// Wait for banner to appear
await retry(async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toContain(
"This page couldn't be fully loaded"
)
})
// Navigate to another page using browser navigation
await browser.get(next.url + '/other')
// Should successfully navigate and banner should be gone
await retry(async () => {
const body = await browser.elementByCss('body')
const text = await body.text()
expect(text).toContain('Other Page')
expect(text).not.toContain("This page couldn't be fully loaded")
})
})
})
})
......@@ -93,6 +93,11 @@ interface RuntimeBackend {
wasmChunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module
) => Promise<WebAssembly.Module>
/**
* Clears a failed chunk resolver so it can be retried.
* Used by Next.js for chunk load error retry logic.
*/
clearChunkResolver?: (chunkUrl: ChunkUrl) => void
}
interface DevRuntimeBackend {
......@@ -418,3 +423,12 @@ function loadWebAssemblyModule(
)
}
contextPrototype.u = loadWebAssemblyModule
// Expose chunk resolver clearing to Next.js for retry logic
if (typeof globalThis !== 'undefined') {
;(globalThis as any).__turbopack_clear_chunk_resolver__ = (
chunkUrl: ChunkUrl
) => {
BACKEND.clearChunkResolver?.(chunkUrl)
}
}
......@@ -94,6 +94,34 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
return await WebAssembly.compileStreaming(req)
},
/**
* Clears a failed chunk resolver so it can be retried.
* This is used by Next.js for chunk load error retry logic.
*/
clearChunkResolver(chunkUrl: ChunkUrl) {
const resolver = chunkResolvers.get(chunkUrl)
if (resolver && !resolver.resolved) {
chunkResolvers.delete(chunkUrl)
// Remove failed script/link tag so it can be re-added on retry
const decodedChunkUrl = decodeURI(chunkUrl)
if (isJs(chunkUrl)) {
const scripts = document.querySelectorAll(
`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`
)
for (const script of Array.from(scripts)) {
script.remove()
}
} else if (isCss(chunkUrl)) {
const links = document.querySelectorAll(
`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`
)
for (const link of Array.from(links)) {
link.remove()
}
}
}
},
}
function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {
......
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="daa7096d-88eb-4aef-8d70-6aae41560fce")}catch(e){}}();
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="ea8c7f06-bd06-8c68-dd64-026f2dc028cc")}catch(e){}}();
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push([
"output/ba425_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js",
{"otherChunks":["output/aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0b8736b3.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
......@@ -740,6 +740,13 @@ function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(1, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
// Expose chunk resolver clearing to Next.js for retry logic
if (typeof globalThis !== 'undefined') {
;
globalThis.__turbopack_clear_chunk_resolver__ = (chunkUrl)=>{
BACKEND.clearChunkResolver?.(chunkUrl);
};
}
/// <reference path="./dev-globals.d.ts" />
/// <reference path="./dev-protocol.d.ts" />
/// <reference path="./dev-extensions.ts" />
......@@ -1642,6 +1649,28 @@ let BACKEND;
async loadWebAssemblyModule (_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
},
/**
* Clears a failed chunk resolver so it can be retried.
* This is used by Next.js for chunk load error retry logic.
*/ clearChunkResolver (chunkUrl) {
const resolver = chunkResolvers.get(chunkUrl);
if (resolver && !resolver.resolved) {
chunkResolvers.delete(chunkUrl);
// Remove failed script/link tag so it can be re-added on retry
const decodedChunkUrl = decodeURI(chunkUrl);
if (isJs(chunkUrl)) {
const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
for (const script of Array.from(scripts)){
script.remove();
}
} else if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`);
for (const link of Array.from(links)){
link.remove();
}
}
}
}
};
function getOrCreateResolver(chunkUrl) {
......@@ -1858,5 +1887,5 @@ chunkListsToRegister.forEach(registerChunkList);
})();
//# debugId=daa7096d-88eb-4aef-8d70-6aae41560fce
//# debugId=ea8c7f06-bd06-8c68-dd64-026f2dc028cc
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js.map
\ No newline at end of file
......@@ -739,6 +739,13 @@ function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(1, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
// Expose chunk resolver clearing to Next.js for retry logic
if (typeof globalThis !== 'undefined') {
;
globalThis.__turbopack_clear_chunk_resolver__ = (chunkUrl)=>{
BACKEND.clearChunkResolver?.(chunkUrl);
};
}
/// <reference path="./dev-globals.d.ts" />
/// <reference path="./dev-protocol.d.ts" />
/// <reference path="./dev-extensions.ts" />
......@@ -1641,6 +1648,28 @@ let BACKEND;
async loadWebAssemblyModule (_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
},
/**
* Clears a failed chunk resolver so it can be retried.
* This is used by Next.js for chunk load error retry logic.
*/ clearChunkResolver (chunkUrl) {
const resolver = chunkResolvers.get(chunkUrl);
if (resolver && !resolver.resolved) {
chunkResolvers.delete(chunkUrl);
// Remove failed script/link tag so it can be re-added on retry
const decodedChunkUrl = decodeURI(chunkUrl);
if (isJs(chunkUrl)) {
const scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
for (const script of Array.from(scripts)){
script.remove();
}
} else if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`);
for (const link of Array.from(links)){
link.remove();
}
}
}
}
};
function getOrCreateResolver(chunkUrl) {
......
......@@ -1223,6 +1223,14 @@ function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(1, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
// Expose chunk resolver clearing to Next.js for retry logic
if (typeof globalThis !== 'undefined') {
;
globalThis.__turbopack_clear_chunk_resolver__ = function(chunkUrl) {
var _BACKEND_clearChunkResolver, _BACKEND;
(_BACKEND_clearChunkResolver = (_BACKEND = BACKEND).clearChunkResolver) === null || _BACKEND_clearChunkResolver === void 0 ? void 0 : _BACKEND_clearChunkResolver.call(_BACKEND, chunkUrl);
};
}
/// <reference path="./runtime-base.ts" />
/// <reference path="./dummy.ts" />
var moduleCache = {};
......@@ -1548,6 +1556,62 @@ var BACKEND;
}
});
})();
},
/**
* Clears a failed chunk resolver so it can be retried.
* This is used by Next.js for chunk load error retry logic.
*/ clearChunkResolver: function clearChunkResolver(chunkUrl) {
var resolver = chunkResolvers.get(chunkUrl);
if (resolver && !resolver.resolved) {
chunkResolvers.delete(chunkUrl);
// Remove failed script/link tag so it can be re-added on retry
var decodedChunkUrl = decodeURI(chunkUrl);
if (isJs(chunkUrl)) {
var scripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
for(var _iterator = Array.from(scripts)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
var script = _step.value;
script.remove();
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
}
} else if (isCss(chunkUrl)) {
var links = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`);
var _iteratorNormalCompletion1 = true, _didIteratorError1 = false, _iteratorError1 = undefined;
try {
for(var _iterator1 = Array.from(links)[Symbol.iterator](), _step1; !(_iteratorNormalCompletion1 = (_step1 = _iterator1.next()).done); _iteratorNormalCompletion1 = true){
var link = _step1.value;
link.remove();
}
} catch (err) {
_didIteratorError1 = true;
_iteratorError1 = err;
} finally{
try {
if (!_iteratorNormalCompletion1 && _iterator1.return != null) {
_iterator1.return();
}
} finally{
if (_didIteratorError1) {
throw _iteratorError1;
}
}
}
}
}
}
};
function getOrCreateResolver(chunkUrl) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment