Commit 3fd2cd00 authored by Tobias Koppers's avatar Tobias Koppers

Fix SharedWorker initialization race and address review feedback

- Make ESM evaluate chunk IIFE async and await `BACKEND.registerChunk()` so
  `import(evaluate_chunk)` only resolves after all modules are instantiated.
  Without this, SharedWorkers fire the `connect` event before `onconnect`
  listeners are registered.
- Rename `worker_chunk_context(is_esm)` → `esm_chunking_context()` (no param).
  Callers only call it when `is_esm` is true; the impl returns `self` when
  `esm_chunks` is already set (fixes the comparison-vs-self.esm_chunks concern).
- Remove redundant `chunkUrls.reverse()` from ESM worker bootstrap; `import()`
  loads in parallel so order doesn't matter.
- Deduplicate preinit loop in `required-scripts.tsx` using a `preinitFn`
  variable instead of duplicating the loop body.
- Remove debug logging from shared worker test.
- Fix comment wording: "not yet an array" → "not an array".
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 6adf1869
......@@ -56,6 +56,7 @@ export function getRequiredScripts(
'Invariant: missing bootstrap script. This is a bug in Next.js'
)
}
const preinitFn = isEsmChunks ? ReactDOM.preinitModule : ReactDOM.preinit
if (SRIManifest) {
bootstrapScript.src = `${assetPrefix}/_next/` + files[0] + qs
bootstrapScript.integrity = SRIManifest[files[0]]
......@@ -65,29 +66,15 @@ export function getRequiredScripts(
const integrity = SRIManifest[files[i]]
preinitScriptCommands.push(src, integrity)
}
if (isEsmChunks) {
preinitScripts = () => {
// preinitScriptCommands is a double indexed array of src/integrity pairs
for (let i = 0; i < preinitScriptCommands.length; i += 2) {
ReactDOM.preinitModule(preinitScriptCommands[i], {
as: 'script',
integrity: preinitScriptCommands[i + 1],
crossOrigin,
nonce,
})
}
}
} else {
preinitScripts = () => {
// preinitScriptCommands is a double indexed array of src/integrity pairs
for (let i = 0; i < preinitScriptCommands.length; i += 2) {
ReactDOM.preinit(preinitScriptCommands[i], {
as: 'script',
integrity: preinitScriptCommands[i + 1],
crossOrigin,
nonce,
})
}
preinitScripts = () => {
// preinitScriptCommands is a double indexed array of src/integrity pairs
for (let i = 0; i < preinitScriptCommands.length; i += 2) {
preinitFn(preinitScriptCommands[i], {
as: 'script',
integrity: preinitScriptCommands[i + 1],
crossOrigin,
nonce,
})
}
}
} else {
......@@ -97,27 +84,14 @@ export function getRequiredScripts(
const src = `${assetPrefix}/_next/` + files[i] + qs
preinitScriptCommands.push(src)
}
if (isEsmChunks) {
preinitScripts = () => {
// preinitScriptCommands is a singled indexed array of src values
for (let i = 0; i < preinitScriptCommands.length; i++) {
ReactDOM.preinitModule(preinitScriptCommands[i], {
as: 'script',
nonce,
crossOrigin,
})
}
}
} else {
preinitScripts = () => {
// preinitScriptCommands is a singled indexed array of src values
for (let i = 0; i < preinitScriptCommands.length; i++) {
ReactDOM.preinit(preinitScriptCommands[i], {
as: 'script',
nonce,
crossOrigin,
})
}
preinitScripts = () => {
// preinitScriptCommands is a singled indexed array of src values
for (let i = 0; i < preinitScriptCommands.length; i++) {
preinitFn(preinitScriptCommands[i], {
as: 'script',
nonce,
crossOrigin,
})
}
}
}
......
......@@ -128,12 +128,9 @@ describe('app dir - workers', () => {
await browser.elementByCss('button').click()
await retry(async () => {
const text = await browser.elementByCss('#worker-state').text()
// Log the state for debugging CI failures
if (text !== 'default' && text !== 'shared-worker.ts:worker-dep:2') {
console.log('Unexpected worker state:', text)
}
expect(text).toBe('shared-worker.ts:worker-dep:2')
expect(await browser.elementByCss('#worker-state').text()).toBe(
'shared-worker.ts:worker-dep:2'
)
})
})
......
......@@ -985,11 +985,8 @@ impl ChunkingContext for BrowserChunkingContext {
}
#[turbo_tasks::function]
async fn worker_chunk_context(
self: Vc<Self>,
is_esm: bool,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
if !is_esm {
async fn esm_chunking_context(self: Vc<Self>) -> Result<Vc<Box<dyn ChunkingContext>>> {
if self.await?.esm_chunks {
return Ok(Vc::upcast(self));
}
let mut inner = (*self.await?).clone();
......
......@@ -267,10 +267,6 @@ fn generate_module_worker_bootstrap_code(forwarded_globals: &[RcStr]) -> Result<
{globals}
}});
// Restore original chunk order (params are stored reversed) so that
// TURBOPACK_NEXT_CHUNK_URLS matches the original order.
chunkUrls.reverse();
await Promise.all(chunkUrls.map(function(chunk) {{
var chunkUrl = new URL(chunk, location.origin);
if (chunkUrl.origin !== location.origin) {{
......
......@@ -495,18 +495,15 @@ pub trait ChunkingContext {
turbobail!("Worker entrypoint is not supported by {}", self.name());
}
/// Returns a derived chunking context suitable for building a worker's chunk group.
/// Returns a derived chunking context that always emits ESM chunks.
///
/// When `is_esm` is true the returned context must emit ESM chunks (using `import()`
/// for chunk loading) so that the worker runtime can load dependencies without
/// calling `importScripts`, which is forbidden in module workers.
/// Used when building a module worker's chunk group: ESM chunks use `import()`
/// for chunk loading instead of `importScripts`, which is forbidden in module workers.
/// Returns `self` if the context already emits ESM chunks.
#[turbo_tasks::function]
async fn worker_chunk_context(
self: Vc<Self>,
_is_esm: bool,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
async fn esm_chunking_context(self: Vc<Self>) -> Result<Vc<Box<dyn ChunkingContext>>> {
turbobail!(
"worker_chunk_context is not implemented for {}",
"esm_chunking_context is not implemented for {}",
self.name()
)
}
......
......@@ -98,7 +98,24 @@ pub async fn get_browser_runtime_code(
let chunk_loading_global = chunk_loading_global.await?;
let chunk_lists_global = format!("{}_CHUNK_LISTS", &*chunk_loading_global);
if *environment
if esm_chunks {
// In ESM mode the evaluate chunk is itself an ES module, so top-level `await` is
// available. We make the IIFE async and await it at the module level so that
// `import(evaluate_chunk)` only resolves after `registerChunk` (and all its async
// sub-tasks — loading other chunks, instantiating runtime modules) has completed.
// This is required for SharedWorkers where the `connect` event fires right after the
// module's top-level execution is done; without the await, `shared-worker.ts`'s
// `addEventListener('connect', ...)` would not yet have been registered.
if *environment
.runtime_versions()
.supports_arrow_functions()
.await?
{
code += "await (async () => {\n";
} else {
code += "await (async function(){\n";
}
} else if *environment
.runtime_versions()
.supports_arrow_functions()
.await?
......@@ -109,7 +126,7 @@ pub async fn get_browser_runtime_code(
}
if !esm_chunks {
// In classic script mode the IIFE bails out if TURBOPACK is not yet an array
// In classic script mode the IIFE bails out if TURBOPACK is not an array
// (i.e., a second evaluate chunk ran before the first finished bootstrapping).
writedoc!(
code,
......@@ -254,10 +271,12 @@ pub async fn get_browser_runtime_code(
// ESM mode: the RuntimeParams are in __turbopack_params__ (a const defined before
// the runtime IIFE in the same evaluate chunk file). No TURBOPACK global to drain.
// Pass an empty string as the chunk path — the ESM registerChunk ignores it.
// We await here (inside the async IIFE) so the module-level `await` at the top
// propagates all the way through chunk loading and module instantiation.
writedoc!(
code,
r#"
BACKEND.registerChunk("", __turbopack_params__);
await BACKEND.registerChunk("", __turbopack_params__);
"#,
)?;
} else {
......
......@@ -68,7 +68,11 @@ impl WorkerLoaderModule {
// When `is_esm` is true, use a derived context that emits ESM chunks so the
// worker runtime can load dependencies via `import()` instead of
// `importScripts` (which is forbidden in module workers).
let worker_context = chunking_context.worker_chunk_context(this.is_esm);
let worker_context = if this.is_esm {
chunking_context.esm_chunking_context()
} else {
chunking_context
};
worker_context.evaluated_chunk_group_assets(
this.inner
.ident()
......
......@@ -737,10 +737,7 @@ impl ChunkingContext for NodeJsChunkingContext {
}
#[turbo_tasks::function]
async fn worker_chunk_context(
self: Vc<Self>,
_is_esm: bool,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
async fn esm_chunking_context(self: Vc<Self>) -> Result<Vc<Box<dyn ChunkingContext>>> {
Ok(Vc::upcast(self))
}
}
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