Unverified Commit 4b519bee authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Retry chunk loading on failure (#94918)

This is a trimmed down PR from
https://github.com/vercel/next.js/pull/88107, it achieves the same thing
(with much of the same code). However, it is Turbopack-only. This is
because the Webpack portions of that PR required patching React - we can
return to this in a different PR or I guess people could use a plugin?
(https://github.com/mattlewis92/webpack-retry-chunk-load-plugin)

---------
Co-authored-by: 's avatarJimmy Lai <laijimmy0@gmail.com>
parent 45d26dfd
...@@ -14,8 +14,8 @@ use turbopack_browser::{ ...@@ -14,8 +14,8 @@ use turbopack_browser::{
}; };
use turbopack_core::{ use turbopack_core::{
chunk::{ chunk::{
AssetSuffix, ChunkingConfig, ChunkingContext, ContentHashing, CrossOrigin, MangleType, AssetSuffix, ChunkLoadRetry, ChunkingConfig, ChunkingContext, ContentHashing, CrossOrigin,
MinifyType, SourceMapSourceType, SourceMapsType, UnusedReferences, UrlBehavior, MangleType, MinifyType, SourceMapSourceType, SourceMapsType, UnusedReferences, UrlBehavior,
chunk_id_strategy::ModuleIdStrategy, chunk_id_strategy::ModuleIdStrategy,
}, },
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences}, compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences},
...@@ -483,6 +483,14 @@ pub struct ClientChunkingContextOptions { ...@@ -483,6 +483,14 @@ pub struct ClientChunkingContextOptions {
pub style_groups_algorithm: StyleGroupsAlgorithm, pub style_groups_algorithm: StyleGroupsAlgorithm,
} }
/// Next.js' chunk-load retry policy for the Turbopack browser runtime.
/// Webpack does not currently support chunk-load retrying.
const NEXT_CHUNK_LOAD_RETRY: ChunkLoadRetry = ChunkLoadRetry {
max_retry_attempts: 1,
base_delay_ms: 200,
max_jitter_ms: 400,
};
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn get_client_chunking_context( pub async fn get_client_chunking_context(
options: ClientChunkingContextOptions, options: ClientChunkingContextOptions,
...@@ -543,6 +551,7 @@ pub async fn get_client_chunking_context( ...@@ -543,6 +551,7 @@ pub async fn get_client_chunking_context(
.asset_base_path(Some(asset_prefix)) .asset_base_path(Some(asset_prefix))
.current_chunk_method(CurrentChunkMethod::DocumentCurrentScript) .current_chunk_method(CurrentChunkMethod::DocumentCurrentScript)
.cross_origin(cross_origin_loading) .cross_origin(cross_origin_loading)
.chunk_load_retry(NEXT_CHUNK_LOAD_RETRY)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?) .unused_references(unused_references.to_resolved().await?)
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
......
...@@ -27,10 +27,12 @@ describe('chunk-load-failure', () => { ...@@ -27,10 +27,12 @@ describe('chunk-load-failure', () => {
it('should report async chunk load failures', async () => { it('should report async chunk load failures', async () => {
let nextDynamicChunk = await getNextDynamicChunk() let nextDynamicChunk = await getNextDynamicChunk()
let chunkRequestCount = 0
let pageError: Error | undefined let pageError: Error | undefined
const browser = await next.browser('/dynamic', { const browser = await next.browser('/dynamic', {
beforePageLoad(page) { beforePageLoad(page) {
page.route(`**/${nextDynamicChunk}*`, async (route) => { page.route(`**/${nextDynamicChunk}*`, async (route) => {
chunkRequestCount++
await route.abort('connectionreset') await route.abort('connectionreset')
}) })
page.on('pageerror', (error: Error) => { page.on('pageerror', (error: Error) => {
...@@ -48,15 +50,61 @@ describe('chunk-load-failure', () => { ...@@ -48,15 +50,61 @@ describe('chunk-load-failure', () => {
expect(pageError).toBeDefined() expect(pageError).toBeDefined()
expect(pageError.name).toBe('ChunkLoadError') expect(pageError.name).toBe('ChunkLoadError')
if (process.env.IS_TURBOPACK_TEST) { if (process.env.IS_TURBOPACK_TEST) {
// Turbopack retries a failed chunk load once before giving up: one initial
// request plus one retry.
expect(chunkRequestCount).toBe(2)
expect(pageError.message).toStartWith( expect(pageError.message).toStartWith(
'Failed to load chunk /_next/' + nextDynamicChunk 'Failed to load chunk /_next/' + nextDynamicChunk
) )
} else { } else {
// Webpack does not retry yet, so the failure surfaces on the first request.
expect(chunkRequestCount).toBe(1)
expect(pageError.message).toMatch(/^Loading chunk \S+ failed./) expect(pageError.message).toMatch(/^Loading chunk \S+ failed./)
expect(pageError.message).toContain('/_next/' + nextDynamicChunk) expect(pageError.message).toContain('/_next/' + nextDynamicChunk)
} }
}) })
// Turbopack-only: webpack does not retry chunk loads yet, so a transient
// failure there surfaces immediately as a ChunkLoadError.
/* eslint-disable jest/no-standalone-expect */
;(process.env.IS_TURBOPACK_TEST ? it : it.skip)(
'should recover after a transient async chunk load failure',
async () => {
let nextDynamicChunk = await getNextDynamicChunk()
let chunkRequestCount = 0
let pageError: Error | undefined
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route(`**/${nextDynamicChunk}*`, async (route) => {
chunkRequestCount++
// Fail only the first attempt; let the retry through.
if (chunkRequestCount === 1) {
await route.abort('connectionreset')
return
}
await route.continue()
})
page.on('pageerror', (error: Error) => {
pageError = error
})
},
})
await retry(async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toContain(
'this is a lazy loaded async component'
)
})
// One initial request that failed + one retry that succeeded.
expect(chunkRequestCount).toBe(2)
expect(pageError).toBeUndefined()
}
)
/* eslint-enable jest/no-standalone-expect */
it('should report aborted chunks when navigating away', async () => { it('should report aborted chunks when navigating away', async () => {
let nextDynamicChunk = await getNextDynamicChunk() let nextDynamicChunk = await getNextDynamicChunk()
......
...@@ -7,9 +7,9 @@ use turbo_tasks_hash::HashAlgorithm; ...@@ -7,9 +7,9 @@ use turbo_tasks_hash::HashAlgorithm;
use turbopack_core::{ use turbopack_core::{
asset::{Asset, AssetContent}, asset::{Asset, AssetContent},
chunk::{ chunk::{
AssetSuffix, Chunk, ChunkGroupResult, ChunkItem, ChunkType, ChunkableModule, AssetSuffix, Chunk, ChunkGroupResult, ChunkItem, ChunkLoadRetry, ChunkType,
ChunkingConfig, ChunkingConfigs, ChunkingContext, ContentHashing, CrossOrigin, ChunkableModule, ChunkingConfig, ChunkingConfigs, ChunkingContext, ContentHashing,
EntryChunkGroupResult, EvaluatableAsset, EvaluatableAssets, MinifyType, CrossOrigin, EntryChunkGroupResult, EvaluatableAsset, EvaluatableAssets, MinifyType,
SourceMapSourceType, SourceMapsType, UnusedReferences, UrlBehavior, SourceMapSourceType, SourceMapsType, UnusedReferences, UrlBehavior,
WorkerConfigurationOptions, WorkerConfigurationOptions,
availability_info::AvailabilityInfo, availability_info::AvailabilityInfo,
...@@ -230,6 +230,11 @@ impl BrowserChunkingContextBuilder { ...@@ -230,6 +230,11 @@ impl BrowserChunkingContextBuilder {
self self
} }
pub fn chunk_load_retry(mut self, chunk_load_retry: ChunkLoadRetry) -> Self {
self.chunking_context.chunk_load_retry = chunk_load_retry;
self
}
pub fn build(self) -> Vc<BrowserChunkingContext> { pub fn build(self) -> Vc<BrowserChunkingContext> {
BrowserChunkingContext::cell(self.chunking_context) BrowserChunkingContext::cell(self.chunking_context)
} }
...@@ -336,6 +341,8 @@ pub struct BrowserChunkingContext { ...@@ -336,6 +341,8 @@ pub struct BrowserChunkingContext {
hash_salt: ResolvedVc<RcStr>, hash_salt: ResolvedVc<RcStr>,
/// The crossorigin mode for dynamically loaded chunks. /// The crossorigin mode for dynamically loaded chunks.
cross_origin: CrossOrigin, cross_origin: CrossOrigin,
/// The retry policy for transient chunk load failures in the browser runtime.
chunk_load_retry: ChunkLoadRetry,
} }
impl BrowserChunkingContext { impl BrowserChunkingContext {
...@@ -390,6 +397,7 @@ impl BrowserChunkingContext { ...@@ -390,6 +397,7 @@ impl BrowserChunkingContext {
chunk_loading_global: Default::default(), chunk_loading_global: Default::default(),
hash_salt: ResolvedVc::cell(RcStr::default()), hash_salt: ResolvedVc::cell(RcStr::default()),
cross_origin: Default::default(), cross_origin: Default::default(),
chunk_load_retry: Default::default(),
}, },
} }
} }
...@@ -524,6 +532,11 @@ impl BrowserChunkingContext { ...@@ -524,6 +532,11 @@ impl BrowserChunkingContext {
pub fn cross_origin(&self) -> Vc<CrossOrigin> { pub fn cross_origin(&self) -> Vc<CrossOrigin> {
self.cross_origin.cell() self.cross_origin.cell()
} }
#[turbo_tasks::function]
pub fn chunk_load_retry(&self) -> Vc<ChunkLoadRetry> {
self.chunk_load_retry.cell()
}
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
......
...@@ -192,6 +192,7 @@ impl EcmascriptBrowserEvaluateChunk { ...@@ -192,6 +192,7 @@ impl EcmascriptBrowserEvaluateChunk {
source_maps, source_maps,
this.chunking_context.chunk_loading_global(), this.chunking_context.chunk_loading_global(),
this.chunking_context.cross_origin(), this.chunking_context.cross_origin(),
this.chunking_context.chunk_load_retry(),
has_async_modules, has_async_modules,
); );
code.push_code(&*runtime_code.await?); code.push_code(&*runtime_code.await?);
......
...@@ -98,6 +98,30 @@ impl TryFrom<Option<&str>> for CrossOrigin { ...@@ -98,6 +98,30 @@ impl TryFrom<Option<&str>> for CrossOrigin {
} }
} }
#[turbo_tasks::value(shared)]
#[derive(Debug, Clone, Copy, Hash, Serialize, Deserialize)]
pub struct ChunkLoadRetry {
/// Number of retry attempts after the initial load fails. `0` disables retries.
pub max_retry_attempts: u32,
/// Base delay before a retry, in milliseconds.
pub base_delay_ms: u32,
/// Maximum random jitter added to the base delay, in milliseconds.
pub max_jitter_ms: u32,
}
impl Default for ChunkLoadRetry {
fn default() -> Self {
// Retry a transient failure once after a short jittered delay. Network
// blips (a brief connection reset, a short CDN hiccup) often succeed on
// a second try.
Self {
max_retry_attempts: 1,
base_delay_ms: 200,
max_jitter_ms: 400,
}
}
}
/// A module id, which can be a number or string /// A module id, which can be a number or string
#[turbo_tasks::value(shared, operation)] #[turbo_tasks::value(shared, operation)]
#[derive(Debug, Clone, Hash, Ord, PartialOrd, DeterministicHash, Serialize, ValueToString)] #[derive(Debug, Clone, Hash, Ord, PartialOrd, DeterministicHash, Serialize, ValueToString)]
......
...@@ -22,6 +22,9 @@ declare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined ...@@ -22,6 +22,9 @@ declare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined
declare var CHUNK_BASE_PATH: string declare var CHUNK_BASE_PATH: string
declare var ASSET_SUFFIX: string declare var ASSET_SUFFIX: string
declare var CROSS_ORIGIN: 'anonymous' | 'use-credentials' | null declare var CROSS_ORIGIN: 'anonymous' | 'use-credentials' | null
declare var CHUNK_LOAD_RETRY_MAX_ATTEMPTS: number
declare var CHUNK_LOAD_RETRY_BASE_DELAY_MS: number
declare var CHUNK_LOAD_RETRY_MAX_JITTER_MS: number
interface TurbopackBrowserBaseContext<M> extends TurbopackBaseContext<M> { interface TurbopackBrowserBaseContext<M> extends TurbopackBaseContext<M> {
R: ResolvePathFromModule R: ResolvePathFromModule
......
...@@ -20,6 +20,7 @@ function getAssetSuffixFromScriptSrc() { ...@@ -20,6 +20,7 @@ function getAssetSuffixFromScriptSrc() {
type ChunkResolver = { type ChunkResolver = {
resolved: boolean resolved: boolean
loadingStarted: boolean loadingStarted: boolean
retryAttempts: number
resolve: () => void resolve: () => void
reject: (error?: Error) => void reject: (error?: Error) => void
promise: Promise<any> promise: Promise<any>
...@@ -88,6 +89,7 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -88,6 +89,7 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
resolver = { resolver = {
resolved: false, resolved: false,
loadingStarted: false, loadingStarted: false,
retryAttempts: 0,
promise, promise,
resolve: () => { resolve: () => {
resolver!.resolved = true resolver!.resolved = true
...@@ -100,6 +102,72 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -100,6 +102,72 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
return resolver return resolver
} }
/**
* Rejects a chunk resolver and drops it from the cache.
* We don't want to cache failed chunk loads: a later
* request for the same chunk should try again.
*/
function rejectChunkResolver(
chunkUrl: ChunkUrl,
resolver: ChunkResolver,
error?: Error
) {
if (chunkResolvers.get(chunkUrl) === resolver) {
chunkResolvers.delete(chunkUrl)
}
resolver.reject(error)
}
function getChunkLoadRetryDelayMs() {
const jitter = Math.floor(
Math.random() * (CHUNK_LOAD_RETRY_MAX_JITTER_MS + 1)
)
return CHUNK_LOAD_RETRY_BASE_DELAY_MS + jitter
}
function isRetryableChunkLoadError(error?: Error): boolean {
return (
error == null ||
(error instanceof DOMException && error.name === 'NetworkError')
)
}
/**
* Handles a failed chunk load: retries the load once after a short delay.
*/
function onChunkLoadError(
sourceType: SourceType,
chunkUrl: ChunkUrl,
resolver: ChunkResolver,
error?: Error,
reload?: () => void
) {
if (
!isRetryableChunkLoadError(error) ||
resolver.retryAttempts >= CHUNK_LOAD_RETRY_MAX_ATTEMPTS ||
chunkResolvers.get(chunkUrl) !== resolver
) {
rejectChunkResolver(chunkUrl, resolver, error)
return
}
resolver.retryAttempts++
setTimeout(() => {
// if this chunk is being fetched multiple times, and one of those
// attempts succeeds. or, if this chunk has another resolver
// mapped to it - it's safe to skip retrying.
if (resolver.resolved || chunkResolvers.get(chunkUrl) !== resolver) {
return
}
if (reload) {
reload()
} else {
resolver.loadingStarted = false
doLoadChunk(sourceType, chunkUrl)
}
}, getChunkLoadRetryDelayMs())
}
/** /**
* Loads the given chunk, and returns a promise that resolves once the chunk * Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded. * has been loaded.
...@@ -134,7 +202,11 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -134,7 +202,11 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl) self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)
try {
importScripts(chunkUrl) importScripts(chunkUrl)
} catch (error) {
onChunkLoadError(sourceType, chunkUrl, resolver, error as Error)
}
} else { } else {
throw new Error( throw new Error(
`can't infer type of chunk from URL ${chunkUrl} in worker` `can't infer type of chunk from URL ${chunkUrl} in worker`
...@@ -153,32 +225,45 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -153,32 +225,45 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
// loaded instantly. // loaded instantly.
resolver.resolve() resolver.resolve()
} else { } else {
const createLink = () => {
const link = document.createElement('link') const link = document.createElement('link')
link.rel = 'stylesheet' link.rel = 'stylesheet'
link.crossOrigin = CROSS_ORIGIN link.crossOrigin = CROSS_ORIGIN
link.href = chunkUrl link.href = chunkUrl
link.onerror = () => { link.onerror = () => {
resolver.reject() // Re-insert a fresh tag at the same position on retry to preserve
// cascade order.
const anchor = document.createComment('')
link.replaceWith(anchor)
onChunkLoadError(sourceType, chunkUrl, resolver, undefined, () =>
anchor.replaceWith(createLink())
)
} }
link.onload = () => { link.onload = () => {
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolver.resolve() resolver.resolve()
} }
return link
}
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(link) document.head.appendChild(createLink())
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll( const previousScripts = document.querySelectorAll(
`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]` `script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`
) )
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
// There is this edge where the script already failed loading, but we
// can't detect that. The Promise will never resolve in this case.
for (const script of Array.from(previousScripts)) { for (const script of Array.from(previousScripts)) {
script.addEventListener('error', () => { script.addEventListener(
resolver.reject() 'error',
}) () => {
// Drop the failed tag so a retry can re-add it cleanly.
script.remove()
onChunkLoadError(sourceType, chunkUrl, resolver)
},
{ once: true }
)
} }
} else { } else {
const script = document.createElement('script') const script = document.createElement('script')
...@@ -188,7 +273,9 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -188,7 +273,9 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
// which happens in `registerChunk`. Hence the absence of `resolve()` in // which happens in `registerChunk`. Hence the absence of `resolve()` in
// this branch. // this branch.
script.onerror = () => { script.onerror = () => {
resolver.reject() // Drop the failed tag so a retry can re-add it cleanly.
script.remove()
onChunkLoadError(sourceType, chunkUrl, resolver)
} }
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(script) document.head.appendChild(script)
......
...@@ -5,7 +5,7 @@ use indoc::writedoc; ...@@ -5,7 +5,7 @@ use indoc::writedoc;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
use turbopack_core::{ use turbopack_core::{
chunk::{AssetSuffix, CrossOrigin}, chunk::{AssetSuffix, ChunkLoadRetry, CrossOrigin},
code_builder::{Code, CodeBuilder}, code_builder::{Code, CodeBuilder},
context::AssetContext, context::AssetContext,
environment::ChunkLoading, environment::ChunkLoading,
...@@ -25,6 +25,7 @@ pub async fn get_browser_runtime_code( ...@@ -25,6 +25,7 @@ pub async fn get_browser_runtime_code(
generate_source_map: bool, generate_source_map: bool,
chunk_loading_global: Vc<RcStr>, chunk_loading_global: Vc<RcStr>,
cross_origin: Vc<CrossOrigin>, cross_origin: Vc<CrossOrigin>,
chunk_load_retry: Vc<ChunkLoadRetry>,
has_async_modules: bool, has_async_modules: bool,
) -> Result<Vc<Code>> { ) -> Result<Vc<Code>> {
let asset_context = *asset_context; let asset_context = *asset_context;
...@@ -167,6 +168,21 @@ pub async fn get_browser_runtime_code( ...@@ -167,6 +168,21 @@ pub async fn get_browser_runtime_code(
StringifyJs(&cross_origin) StringifyJs(&cross_origin)
)?; )?;
// The chunk-load retry policy is owned by the framework (e.g. Next.js) and
// passed in via the chunking context, so the runtime never hard-codes it.
let chunk_load_retry = *chunk_load_retry.await?;
writedoc!(
code,
r#"
var CHUNK_LOAD_RETRY_MAX_ATTEMPTS = {};
var CHUNK_LOAD_RETRY_BASE_DELAY_MS = {};
var CHUNK_LOAD_RETRY_MAX_JITTER_MS = {};
"#,
chunk_load_retry.max_retry_attempts,
chunk_load_retry.base_delay_ms,
chunk_load_retry.max_jitter_ms,
)?;
code.push_code(&*shared_runtime_utils_code.await?); code.push_code(&*shared_runtime_utils_code.await?);
// Only include the async-module (top-level await) machinery when the app uses it. // Only include the async-module (top-level await) machinery when the app uses it.
if has_async_modules { if has_async_modules {
......
;!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]="66516bcd-473e-2cdd-712a-f3f1d535fbca")}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]="557d25bf-c2b0-8db1-31f5-73705b9713cf")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1i9t_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js", "output/1i9t_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js",
{"otherChunks":["output/1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvs.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvs.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
...@@ -13,6 +13,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../.."; ...@@ -13,6 +13,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var CHUNK_LOAD_RETRY_MAX_ATTEMPTS = 1;
var CHUNK_LOAD_RETRY_BASE_DELAY_MS = 200;
var CHUNK_LOAD_RETRY_MAX_JITTER_MS = 400;
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -1998,6 +2001,7 @@ let BACKEND; ...@@ -1998,6 +2001,7 @@ let BACKEND;
resolver = { resolver = {
resolved: false, resolved: false,
loadingStarted: false, loadingStarted: false,
retryAttempts: 0,
promise, promise,
resolve: ()=>{ resolve: ()=>{
resolver.resolved = true; resolver.resolved = true;
...@@ -2010,6 +2014,46 @@ let BACKEND; ...@@ -2010,6 +2014,46 @@ let BACKEND;
return resolver; return resolver;
} }
/** /**
* Rejects a chunk resolver and drops it from the cache.
* We don't want to cache failed chunk loads: a later
* request for the same chunk should try again.
*/ function rejectChunkResolver(chunkUrl, resolver, error) {
if (chunkResolvers.get(chunkUrl) === resolver) {
chunkResolvers.delete(chunkUrl);
}
resolver.reject(error);
}
function getChunkLoadRetryDelayMs() {
const jitter = Math.floor(Math.random() * (CHUNK_LOAD_RETRY_MAX_JITTER_MS + 1));
return CHUNK_LOAD_RETRY_BASE_DELAY_MS + jitter;
}
function isRetryableChunkLoadError(error) {
return error == null || error instanceof DOMException && error.name === 'NetworkError';
}
/**
* Handles a failed chunk load: retries the load once after a short delay.
*/ function onChunkLoadError(sourceType, chunkUrl, resolver, error, reload) {
if (!isRetryableChunkLoadError(error) || resolver.retryAttempts >= CHUNK_LOAD_RETRY_MAX_ATTEMPTS || chunkResolvers.get(chunkUrl) !== resolver) {
rejectChunkResolver(chunkUrl, resolver, error);
return;
}
resolver.retryAttempts++;
setTimeout(()=>{
// if this chunk is being fetched multiple times, and one of those
// attempts succeeds. or, if this chunk has another resolver
// mapped to it - it's safe to skip retrying.
if (resolver.resolved || chunkResolvers.get(chunkUrl) !== resolver) {
return;
}
if (reload) {
reload();
} else {
resolver.loadingStarted = false;
doLoadChunk(sourceType, chunkUrl);
}
}, getChunkLoadRetryDelayMs());
}
/**
* Loads the given chunk, and returns a promise that resolves once the chunk * Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded. * has been loaded.
*/ function doLoadChunk(sourceType, chunkUrl) { */ function doLoadChunk(sourceType, chunkUrl) {
...@@ -2037,7 +2081,11 @@ let BACKEND; ...@@ -2037,7 +2081,11 @@ let BACKEND;
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl);
try {
importScripts(chunkUrl); importScripts(chunkUrl);
} catch (error) {
onChunkLoadError(sourceType, chunkUrl, resolver, error);
}
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
...@@ -2051,29 +2099,38 @@ let BACKEND; ...@@ -2051,29 +2099,38 @@ let BACKEND;
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
} else { } else {
const createLink = ()=>{
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
link.href = chunkUrl; link.href = chunkUrl;
link.onerror = ()=>{ link.onerror = ()=>{
resolver.reject(); // Re-insert a fresh tag at the same position on retry to preserve
// cascade order.
const anchor = document.createComment('');
link.replaceWith(anchor);
onChunkLoadError(sourceType, chunkUrl, resolver, undefined, ()=>anchor.replaceWith(createLink()));
}; };
link.onload = ()=>{ link.onload = ()=>{
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
}; };
return link;
};
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(link); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
// There is this edge where the script already failed loading, but we
// can't detect that. The Promise will never resolve in this case.
for (const script of Array.from(previousScripts)){ for (const script of Array.from(previousScripts)){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}, {
once: true
}); });
} }
} else { } else {
...@@ -2084,7 +2141,9 @@ let BACKEND; ...@@ -2084,7 +2141,9 @@ let BACKEND;
// which happens in `registerChunk`. Hence the absence of `resolve()` in // which happens in `registerChunk`. Hence the absence of `resolve()` in
// this branch. // this branch.
script.onerror = ()=>{ script.onerror = ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}; };
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(script); document.head.appendChild(script);
...@@ -2213,5 +2272,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2213,5 +2272,5 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# debugId=66516bcd-473e-2cdd-712a-f3f1d535fbca //# debugId=557d25bf-c2b0-8db1-31f5-73705b9713cf
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js.map //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js.map
\ No newline at end of file
...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../.."; ...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var CHUNK_LOAD_RETRY_MAX_ATTEMPTS = 1;
var CHUNK_LOAD_RETRY_BASE_DELAY_MS = 200;
var CHUNK_LOAD_RETRY_MAX_JITTER_MS = 400;
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -1997,6 +2000,7 @@ let BACKEND; ...@@ -1997,6 +2000,7 @@ let BACKEND;
resolver = { resolver = {
resolved: false, resolved: false,
loadingStarted: false, loadingStarted: false,
retryAttempts: 0,
promise, promise,
resolve: ()=>{ resolve: ()=>{
resolver.resolved = true; resolver.resolved = true;
...@@ -2009,6 +2013,46 @@ let BACKEND; ...@@ -2009,6 +2013,46 @@ let BACKEND;
return resolver; return resolver;
} }
/** /**
* Rejects a chunk resolver and drops it from the cache.
* We don't want to cache failed chunk loads: a later
* request for the same chunk should try again.
*/ function rejectChunkResolver(chunkUrl, resolver, error) {
if (chunkResolvers.get(chunkUrl) === resolver) {
chunkResolvers.delete(chunkUrl);
}
resolver.reject(error);
}
function getChunkLoadRetryDelayMs() {
const jitter = Math.floor(Math.random() * (CHUNK_LOAD_RETRY_MAX_JITTER_MS + 1));
return CHUNK_LOAD_RETRY_BASE_DELAY_MS + jitter;
}
function isRetryableChunkLoadError(error) {
return error == null || error instanceof DOMException && error.name === 'NetworkError';
}
/**
* Handles a failed chunk load: retries the load once after a short delay.
*/ function onChunkLoadError(sourceType, chunkUrl, resolver, error, reload) {
if (!isRetryableChunkLoadError(error) || resolver.retryAttempts >= CHUNK_LOAD_RETRY_MAX_ATTEMPTS || chunkResolvers.get(chunkUrl) !== resolver) {
rejectChunkResolver(chunkUrl, resolver, error);
return;
}
resolver.retryAttempts++;
setTimeout(()=>{
// if this chunk is being fetched multiple times, and one of those
// attempts succeeds. or, if this chunk has another resolver
// mapped to it - it's safe to skip retrying.
if (resolver.resolved || chunkResolvers.get(chunkUrl) !== resolver) {
return;
}
if (reload) {
reload();
} else {
resolver.loadingStarted = false;
doLoadChunk(sourceType, chunkUrl);
}
}, getChunkLoadRetryDelayMs());
}
/**
* Loads the given chunk, and returns a promise that resolves once the chunk * Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded. * has been loaded.
*/ function doLoadChunk(sourceType, chunkUrl) { */ function doLoadChunk(sourceType, chunkUrl) {
...@@ -2036,7 +2080,11 @@ let BACKEND; ...@@ -2036,7 +2080,11 @@ let BACKEND;
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl);
try {
importScripts(chunkUrl); importScripts(chunkUrl);
} catch (error) {
onChunkLoadError(sourceType, chunkUrl, resolver, error);
}
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
...@@ -2050,29 +2098,38 @@ let BACKEND; ...@@ -2050,29 +2098,38 @@ let BACKEND;
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
} else { } else {
const createLink = ()=>{
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
link.href = chunkUrl; link.href = chunkUrl;
link.onerror = ()=>{ link.onerror = ()=>{
resolver.reject(); // Re-insert a fresh tag at the same position on retry to preserve
// cascade order.
const anchor = document.createComment('');
link.replaceWith(anchor);
onChunkLoadError(sourceType, chunkUrl, resolver, undefined, ()=>anchor.replaceWith(createLink()));
}; };
link.onload = ()=>{ link.onload = ()=>{
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
}; };
return link;
};
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(link); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
// There is this edge where the script already failed loading, but we
// can't detect that. The Promise will never resolve in this case.
for (const script of Array.from(previousScripts)){ for (const script of Array.from(previousScripts)){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}, {
once: true
}); });
} }
} else { } else {
...@@ -2083,7 +2140,9 @@ let BACKEND; ...@@ -2083,7 +2140,9 @@ let BACKEND;
// which happens in `registerChunk`. Hence the absence of `resolve()` in // which happens in `registerChunk`. Hence the absence of `resolve()` in
// this branch. // this branch.
script.onerror = ()=>{ script.onerror = ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}; };
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(script); document.head.appendChild(script);
......
...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../.."; ...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var CHUNK_LOAD_RETRY_MAX_ATTEMPTS = 1;
var CHUNK_LOAD_RETRY_BASE_DELAY_MS = 200;
var CHUNK_LOAD_RETRY_MAX_JITTER_MS = 400;
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -1276,6 +1279,14 @@ function _async_to_generator(fn) { ...@@ -1276,6 +1279,14 @@ function _async_to_generator(fn) {
}); });
}; };
} }
function _instanceof(left, right) {
"@swc/helpers - instanceof";
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
return !!right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
function _ts_generator(thisArg, body) { function _ts_generator(thisArg, body) {
var f, y, t, _ = { var f, y, t, _ = {
label: 0, label: 0,
...@@ -1491,6 +1502,7 @@ var BACKEND; ...@@ -1491,6 +1502,7 @@ var BACKEND;
resolver = { resolver = {
resolved: false, resolved: false,
loadingStarted: false, loadingStarted: false,
retryAttempts: 0,
promise: promise, promise: promise,
resolve: function resolve1() { resolve: function resolve1() {
resolver.resolved = true; resolver.resolved = true;
...@@ -1503,6 +1515,46 @@ var BACKEND; ...@@ -1503,6 +1515,46 @@ var BACKEND;
return resolver; return resolver;
} }
/** /**
* Rejects a chunk resolver and drops it from the cache.
* We don't want to cache failed chunk loads: a later
* request for the same chunk should try again.
*/ function rejectChunkResolver(chunkUrl, resolver, error) {
if (chunkResolvers.get(chunkUrl) === resolver) {
chunkResolvers.delete(chunkUrl);
}
resolver.reject(error);
}
function getChunkLoadRetryDelayMs() {
var jitter = Math.floor(Math.random() * (CHUNK_LOAD_RETRY_MAX_JITTER_MS + 1));
return CHUNK_LOAD_RETRY_BASE_DELAY_MS + jitter;
}
function isRetryableChunkLoadError(error) {
return error == null || _instanceof(error, DOMException) && error.name === 'NetworkError';
}
/**
* Handles a failed chunk load: retries the load once after a short delay.
*/ function onChunkLoadError(sourceType, chunkUrl, resolver, error, reload) {
if (!isRetryableChunkLoadError(error) || resolver.retryAttempts >= CHUNK_LOAD_RETRY_MAX_ATTEMPTS || chunkResolvers.get(chunkUrl) !== resolver) {
rejectChunkResolver(chunkUrl, resolver, error);
return;
}
resolver.retryAttempts++;
setTimeout(function() {
// if this chunk is being fetched multiple times, and one of those
// attempts succeeds. or, if this chunk has another resolver
// mapped to it - it's safe to skip retrying.
if (resolver.resolved || chunkResolvers.get(chunkUrl) !== resolver) {
return;
}
if (reload) {
reload();
} else {
resolver.loadingStarted = false;
doLoadChunk(sourceType, chunkUrl);
}
}, getChunkLoadRetryDelayMs());
}
/**
* Loads the given chunk, and returns a promise that resolves once the chunk * Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded. * has been loaded.
*/ function doLoadChunk(sourceType, chunkUrl) { */ function doLoadChunk(sourceType, chunkUrl) {
...@@ -1530,7 +1582,11 @@ var BACKEND; ...@@ -1530,7 +1582,11 @@ var BACKEND;
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl);
try {
importScripts(chunkUrl); importScripts(chunkUrl);
} catch (error) {
onChunkLoadError(sourceType, chunkUrl, resolver, error);
}
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
...@@ -1544,34 +1600,46 @@ var BACKEND; ...@@ -1544,34 +1600,46 @@ var BACKEND;
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
} else { } else {
var createLink = function createLink1() {
var link = document.createElement('link'); var link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
link.href = chunkUrl; link.href = chunkUrl;
link.onerror = function() { link.onerror = function() {
resolver.reject(); // Re-insert a fresh tag at the same position on retry to preserve
// cascade order.
var anchor = document.createComment('');
link.replaceWith(anchor);
onChunkLoadError(sourceType, chunkUrl, resolver, undefined, function() {
return anchor.replaceWith(createLink());
});
}; };
link.onload = function() { link.onload = function() {
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
}; };
return link;
};
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(link); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
var previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); var previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined; var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try { try {
// There is this edge where the script already failed loading, but we var _loop = function() {
// can't detect that. The Promise will never resolve in this case.
for(var _iterator = Array.from(previousScripts)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
var script = _step.value; var script = _step.value;
script.addEventListener('error', function() { script.addEventListener('error', function() {
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}, {
once: true
}); });
} };
for(var _iterator = Array.from(previousScripts)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
} catch (err) { } catch (err) {
_didIteratorError = true; _didIteratorError = true;
_iteratorError = err; _iteratorError = err;
...@@ -1587,17 +1655,19 @@ var BACKEND; ...@@ -1587,17 +1655,19 @@ var BACKEND;
} }
} }
} else { } else {
var script1 = document.createElement('script'); var script = document.createElement('script');
script1.crossOrigin = CROSS_ORIGIN; script.crossOrigin = CROSS_ORIGIN;
script1.src = chunkUrl; script.src = chunkUrl;
// We'll only mark the chunk as loaded once the script has been executed, // We'll only mark the chunk as loaded once the script has been executed,
// which happens in `registerChunk`. Hence the absence of `resolve()` in // which happens in `registerChunk`. Hence the absence of `resolve()` in
// this branch. // this branch.
script1.onerror = function() { script.onerror = function() {
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}; };
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(script1); document.head.appendChild(script);
} }
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl}`); throw new Error(`can't infer type of chunk from URL ${chunkUrl}`);
......
...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../.."; ...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var CHUNK_LOAD_RETRY_MAX_ATTEMPTS = 1;
var CHUNK_LOAD_RETRY_BASE_DELAY_MS = 200;
var CHUNK_LOAD_RETRY_MAX_JITTER_MS = 400;
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -1997,6 +2000,7 @@ let BACKEND; ...@@ -1997,6 +2000,7 @@ let BACKEND;
resolver = { resolver = {
resolved: false, resolved: false,
loadingStarted: false, loadingStarted: false,
retryAttempts: 0,
promise, promise,
resolve: ()=>{ resolve: ()=>{
resolver.resolved = true; resolver.resolved = true;
...@@ -2009,6 +2013,46 @@ let BACKEND; ...@@ -2009,6 +2013,46 @@ let BACKEND;
return resolver; return resolver;
} }
/** /**
* Rejects a chunk resolver and drops it from the cache.
* We don't want to cache failed chunk loads: a later
* request for the same chunk should try again.
*/ function rejectChunkResolver(chunkUrl, resolver, error) {
if (chunkResolvers.get(chunkUrl) === resolver) {
chunkResolvers.delete(chunkUrl);
}
resolver.reject(error);
}
function getChunkLoadRetryDelayMs() {
const jitter = Math.floor(Math.random() * (CHUNK_LOAD_RETRY_MAX_JITTER_MS + 1));
return CHUNK_LOAD_RETRY_BASE_DELAY_MS + jitter;
}
function isRetryableChunkLoadError(error) {
return error == null || error instanceof DOMException && error.name === 'NetworkError';
}
/**
* Handles a failed chunk load: retries the load once after a short delay.
*/ function onChunkLoadError(sourceType, chunkUrl, resolver, error, reload) {
if (!isRetryableChunkLoadError(error) || resolver.retryAttempts >= CHUNK_LOAD_RETRY_MAX_ATTEMPTS || chunkResolvers.get(chunkUrl) !== resolver) {
rejectChunkResolver(chunkUrl, resolver, error);
return;
}
resolver.retryAttempts++;
setTimeout(()=>{
// if this chunk is being fetched multiple times, and one of those
// attempts succeeds. or, if this chunk has another resolver
// mapped to it - it's safe to skip retrying.
if (resolver.resolved || chunkResolvers.get(chunkUrl) !== resolver) {
return;
}
if (reload) {
reload();
} else {
resolver.loadingStarted = false;
doLoadChunk(sourceType, chunkUrl);
}
}, getChunkLoadRetryDelayMs());
}
/**
* Loads the given chunk, and returns a promise that resolves once the chunk * Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded. * has been loaded.
*/ function doLoadChunk(sourceType, chunkUrl) { */ function doLoadChunk(sourceType, chunkUrl) {
...@@ -2036,7 +2080,11 @@ let BACKEND; ...@@ -2036,7 +2080,11 @@ let BACKEND;
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl);
try {
importScripts(chunkUrl); importScripts(chunkUrl);
} catch (error) {
onChunkLoadError(sourceType, chunkUrl, resolver, error);
}
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
...@@ -2050,29 +2098,38 @@ let BACKEND; ...@@ -2050,29 +2098,38 @@ let BACKEND;
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
} else { } else {
const createLink = ()=>{
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
link.href = chunkUrl; link.href = chunkUrl;
link.onerror = ()=>{ link.onerror = ()=>{
resolver.reject(); // Re-insert a fresh tag at the same position on retry to preserve
// cascade order.
const anchor = document.createComment('');
link.replaceWith(anchor);
onChunkLoadError(sourceType, chunkUrl, resolver, undefined, ()=>anchor.replaceWith(createLink()));
}; };
link.onload = ()=>{ link.onload = ()=>{
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
}; };
return link;
};
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(link); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
// There is this edge where the script already failed loading, but we
// can't detect that. The Promise will never resolve in this case.
for (const script of Array.from(previousScripts)){ for (const script of Array.from(previousScripts)){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}, {
once: true
}); });
} }
} else { } else {
...@@ -2083,7 +2140,9 @@ let BACKEND; ...@@ -2083,7 +2140,9 @@ let BACKEND;
// which happens in `registerChunk`. Hence the absence of `resolve()` in // which happens in `registerChunk`. Hence the absence of `resolve()` in
// this branch. // this branch.
script.onerror = ()=>{ script.onerror = ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}; };
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(script); document.head.appendChild(script);
......
...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../.."; ...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var CHUNK_LOAD_RETRY_MAX_ATTEMPTS = 1;
var CHUNK_LOAD_RETRY_BASE_DELAY_MS = 200;
var CHUNK_LOAD_RETRY_MAX_JITTER_MS = 400;
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -1997,6 +2000,7 @@ let BACKEND; ...@@ -1997,6 +2000,7 @@ let BACKEND;
resolver = { resolver = {
resolved: false, resolved: false,
loadingStarted: false, loadingStarted: false,
retryAttempts: 0,
promise, promise,
resolve: ()=>{ resolve: ()=>{
resolver.resolved = true; resolver.resolved = true;
...@@ -2009,6 +2013,46 @@ let BACKEND; ...@@ -2009,6 +2013,46 @@ let BACKEND;
return resolver; return resolver;
} }
/** /**
* Rejects a chunk resolver and drops it from the cache.
* We don't want to cache failed chunk loads: a later
* request for the same chunk should try again.
*/ function rejectChunkResolver(chunkUrl, resolver, error) {
if (chunkResolvers.get(chunkUrl) === resolver) {
chunkResolvers.delete(chunkUrl);
}
resolver.reject(error);
}
function getChunkLoadRetryDelayMs() {
const jitter = Math.floor(Math.random() * (CHUNK_LOAD_RETRY_MAX_JITTER_MS + 1));
return CHUNK_LOAD_RETRY_BASE_DELAY_MS + jitter;
}
function isRetryableChunkLoadError(error) {
return error == null || error instanceof DOMException && error.name === 'NetworkError';
}
/**
* Handles a failed chunk load: retries the load once after a short delay.
*/ function onChunkLoadError(sourceType, chunkUrl, resolver, error, reload) {
if (!isRetryableChunkLoadError(error) || resolver.retryAttempts >= CHUNK_LOAD_RETRY_MAX_ATTEMPTS || chunkResolvers.get(chunkUrl) !== resolver) {
rejectChunkResolver(chunkUrl, resolver, error);
return;
}
resolver.retryAttempts++;
setTimeout(()=>{
// if this chunk is being fetched multiple times, and one of those
// attempts succeeds. or, if this chunk has another resolver
// mapped to it - it's safe to skip retrying.
if (resolver.resolved || chunkResolvers.get(chunkUrl) !== resolver) {
return;
}
if (reload) {
reload();
} else {
resolver.loadingStarted = false;
doLoadChunk(sourceType, chunkUrl);
}
}, getChunkLoadRetryDelayMs());
}
/**
* Loads the given chunk, and returns a promise that resolves once the chunk * Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded. * has been loaded.
*/ function doLoadChunk(sourceType, chunkUrl) { */ function doLoadChunk(sourceType, chunkUrl) {
...@@ -2036,7 +2080,11 @@ let BACKEND; ...@@ -2036,7 +2080,11 @@ let BACKEND;
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl);
try {
importScripts(chunkUrl); importScripts(chunkUrl);
} catch (error) {
onChunkLoadError(sourceType, chunkUrl, resolver, error);
}
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
...@@ -2050,29 +2098,38 @@ let BACKEND; ...@@ -2050,29 +2098,38 @@ let BACKEND;
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
} else { } else {
const createLink = ()=>{
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
link.href = chunkUrl; link.href = chunkUrl;
link.onerror = ()=>{ link.onerror = ()=>{
resolver.reject(); // Re-insert a fresh tag at the same position on retry to preserve
// cascade order.
const anchor = document.createComment('');
link.replaceWith(anchor);
onChunkLoadError(sourceType, chunkUrl, resolver, undefined, ()=>anchor.replaceWith(createLink()));
}; };
link.onload = ()=>{ link.onload = ()=>{
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
}; };
return link;
};
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(link); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
// There is this edge where the script already failed loading, but we
// can't detect that. The Promise will never resolve in this case.
for (const script of Array.from(previousScripts)){ for (const script of Array.from(previousScripts)){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}, {
once: true
}); });
} }
} else { } else {
...@@ -2083,7 +2140,9 @@ let BACKEND; ...@@ -2083,7 +2140,9 @@ let BACKEND;
// which happens in `registerChunk`. Hence the absence of `resolve()` in // which happens in `registerChunk`. Hence the absence of `resolve()` in
// this branch. // this branch.
script.onerror = ()=>{ script.onerror = ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}; };
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(script); document.head.appendChild(script);
......
...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../.."; ...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var CHUNK_LOAD_RETRY_MAX_ATTEMPTS = 1;
var CHUNK_LOAD_RETRY_BASE_DELAY_MS = 200;
var CHUNK_LOAD_RETRY_MAX_JITTER_MS = 400;
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -1997,6 +2000,7 @@ let BACKEND; ...@@ -1997,6 +2000,7 @@ let BACKEND;
resolver = { resolver = {
resolved: false, resolved: false,
loadingStarted: false, loadingStarted: false,
retryAttempts: 0,
promise, promise,
resolve: ()=>{ resolve: ()=>{
resolver.resolved = true; resolver.resolved = true;
...@@ -2009,6 +2013,46 @@ let BACKEND; ...@@ -2009,6 +2013,46 @@ let BACKEND;
return resolver; return resolver;
} }
/** /**
* Rejects a chunk resolver and drops it from the cache.
* We don't want to cache failed chunk loads: a later
* request for the same chunk should try again.
*/ function rejectChunkResolver(chunkUrl, resolver, error) {
if (chunkResolvers.get(chunkUrl) === resolver) {
chunkResolvers.delete(chunkUrl);
}
resolver.reject(error);
}
function getChunkLoadRetryDelayMs() {
const jitter = Math.floor(Math.random() * (CHUNK_LOAD_RETRY_MAX_JITTER_MS + 1));
return CHUNK_LOAD_RETRY_BASE_DELAY_MS + jitter;
}
function isRetryableChunkLoadError(error) {
return error == null || error instanceof DOMException && error.name === 'NetworkError';
}
/**
* Handles a failed chunk load: retries the load once after a short delay.
*/ function onChunkLoadError(sourceType, chunkUrl, resolver, error, reload) {
if (!isRetryableChunkLoadError(error) || resolver.retryAttempts >= CHUNK_LOAD_RETRY_MAX_ATTEMPTS || chunkResolvers.get(chunkUrl) !== resolver) {
rejectChunkResolver(chunkUrl, resolver, error);
return;
}
resolver.retryAttempts++;
setTimeout(()=>{
// if this chunk is being fetched multiple times, and one of those
// attempts succeeds. or, if this chunk has another resolver
// mapped to it - it's safe to skip retrying.
if (resolver.resolved || chunkResolvers.get(chunkUrl) !== resolver) {
return;
}
if (reload) {
reload();
} else {
resolver.loadingStarted = false;
doLoadChunk(sourceType, chunkUrl);
}
}, getChunkLoadRetryDelayMs());
}
/**
* Loads the given chunk, and returns a promise that resolves once the chunk * Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded. * has been loaded.
*/ function doLoadChunk(sourceType, chunkUrl) { */ function doLoadChunk(sourceType, chunkUrl) {
...@@ -2036,7 +2080,11 @@ let BACKEND; ...@@ -2036,7 +2080,11 @@ let BACKEND;
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl);
try {
importScripts(chunkUrl); importScripts(chunkUrl);
} catch (error) {
onChunkLoadError(sourceType, chunkUrl, resolver, error);
}
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
...@@ -2050,29 +2098,38 @@ let BACKEND; ...@@ -2050,29 +2098,38 @@ let BACKEND;
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
} else { } else {
const createLink = ()=>{
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
link.href = chunkUrl; link.href = chunkUrl;
link.onerror = ()=>{ link.onerror = ()=>{
resolver.reject(); // Re-insert a fresh tag at the same position on retry to preserve
// cascade order.
const anchor = document.createComment('');
link.replaceWith(anchor);
onChunkLoadError(sourceType, chunkUrl, resolver, undefined, ()=>anchor.replaceWith(createLink()));
}; };
link.onload = ()=>{ link.onload = ()=>{
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
}; };
return link;
};
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(link); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
// There is this edge where the script already failed loading, but we
// can't detect that. The Promise will never resolve in this case.
for (const script of Array.from(previousScripts)){ for (const script of Array.from(previousScripts)){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}, {
once: true
}); });
} }
} else { } else {
...@@ -2083,7 +2140,9 @@ let BACKEND; ...@@ -2083,7 +2140,9 @@ let BACKEND;
// which happens in `registerChunk`. Hence the absence of `resolve()` in // which happens in `registerChunk`. Hence the absence of `resolve()` in
// this branch. // this branch.
script.onerror = ()=>{ script.onerror = ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}; };
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(script); document.head.appendChild(script);
......
...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../.."; ...@@ -12,6 +12,9 @@ var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null; var CROSS_ORIGIN = null;
var CHUNK_LOAD_RETRY_MAX_ATTEMPTS = 1;
var CHUNK_LOAD_RETRY_BASE_DELAY_MS = 200;
var CHUNK_LOAD_RETRY_MAX_JITTER_MS = 400;
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes. * TurboPack ECMAScript runtimes.
...@@ -1997,6 +2000,7 @@ let BACKEND; ...@@ -1997,6 +2000,7 @@ let BACKEND;
resolver = { resolver = {
resolved: false, resolved: false,
loadingStarted: false, loadingStarted: false,
retryAttempts: 0,
promise, promise,
resolve: ()=>{ resolve: ()=>{
resolver.resolved = true; resolver.resolved = true;
...@@ -2009,6 +2013,46 @@ let BACKEND; ...@@ -2009,6 +2013,46 @@ let BACKEND;
return resolver; return resolver;
} }
/** /**
* Rejects a chunk resolver and drops it from the cache.
* We don't want to cache failed chunk loads: a later
* request for the same chunk should try again.
*/ function rejectChunkResolver(chunkUrl, resolver, error) {
if (chunkResolvers.get(chunkUrl) === resolver) {
chunkResolvers.delete(chunkUrl);
}
resolver.reject(error);
}
function getChunkLoadRetryDelayMs() {
const jitter = Math.floor(Math.random() * (CHUNK_LOAD_RETRY_MAX_JITTER_MS + 1));
return CHUNK_LOAD_RETRY_BASE_DELAY_MS + jitter;
}
function isRetryableChunkLoadError(error) {
return error == null || error instanceof DOMException && error.name === 'NetworkError';
}
/**
* Handles a failed chunk load: retries the load once after a short delay.
*/ function onChunkLoadError(sourceType, chunkUrl, resolver, error, reload) {
if (!isRetryableChunkLoadError(error) || resolver.retryAttempts >= CHUNK_LOAD_RETRY_MAX_ATTEMPTS || chunkResolvers.get(chunkUrl) !== resolver) {
rejectChunkResolver(chunkUrl, resolver, error);
return;
}
resolver.retryAttempts++;
setTimeout(()=>{
// if this chunk is being fetched multiple times, and one of those
// attempts succeeds. or, if this chunk has another resolver
// mapped to it - it's safe to skip retrying.
if (resolver.resolved || chunkResolvers.get(chunkUrl) !== resolver) {
return;
}
if (reload) {
reload();
} else {
resolver.loadingStarted = false;
doLoadChunk(sourceType, chunkUrl);
}
}, getChunkLoadRetryDelayMs());
}
/**
* Loads the given chunk, and returns a promise that resolves once the chunk * Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded. * has been loaded.
*/ function doLoadChunk(sourceType, chunkUrl) { */ function doLoadChunk(sourceType, chunkUrl) {
...@@ -2036,7 +2080,11 @@ let BACKEND; ...@@ -2036,7 +2080,11 @@ let BACKEND;
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl);
try {
importScripts(chunkUrl); importScripts(chunkUrl);
} catch (error) {
onChunkLoadError(sourceType, chunkUrl, resolver, error);
}
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
...@@ -2050,29 +2098,38 @@ let BACKEND; ...@@ -2050,29 +2098,38 @@ let BACKEND;
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
} else { } else {
const createLink = ()=>{
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN; link.crossOrigin = CROSS_ORIGIN;
link.href = chunkUrl; link.href = chunkUrl;
link.onerror = ()=>{ link.onerror = ()=>{
resolver.reject(); // Re-insert a fresh tag at the same position on retry to preserve
// cascade order.
const anchor = document.createComment('');
link.replaceWith(anchor);
onChunkLoadError(sourceType, chunkUrl, resolver, undefined, ()=>anchor.replaceWith(createLink()));
}; };
link.onload = ()=>{ link.onload = ()=>{
// CSS chunks do not register themselves, and as such must be marked as // CSS chunks do not register themselves, and as such must be marked as
// loaded instantly. // loaded instantly.
resolver.resolve(); resolver.resolve();
}; };
return link;
};
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(link); document.head.appendChild(createLink());
} }
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`); const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
if (previousScripts.length > 0) { if (previousScripts.length > 0) {
// There is this edge where the script already failed loading, but we
// can't detect that. The Promise will never resolve in this case.
for (const script of Array.from(previousScripts)){ for (const script of Array.from(previousScripts)){
script.addEventListener('error', ()=>{ script.addEventListener('error', ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}, {
once: true
}); });
} }
} else { } else {
...@@ -2083,7 +2140,9 @@ let BACKEND; ...@@ -2083,7 +2140,9 @@ let BACKEND;
// which happens in `registerChunk`. Hence the absence of `resolve()` in // which happens in `registerChunk`. Hence the absence of `resolve()` in
// this branch. // this branch.
script.onerror = ()=>{ script.onerror = ()=>{
resolver.reject(); // Drop the failed tag so a retry can re-add it cleanly.
script.remove();
onChunkLoadError(sourceType, chunkUrl, resolver);
}; };
// Append to the `head` for webpack compatibility. // Append to the `head` for webpack compatibility.
document.head.appendChild(script); document.head.appendChild(script);
......
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