Skip to content

Commit 4450a9c

Browse files
committed
provide chunk path to WebWorkers, which doesn't support document.currentScript
1 parent 27aad6a commit 4450a9c

File tree

7 files changed

+39
-16
lines changed

7 files changed

+39
-16
lines changed

turbopack/crates/turbopack-browser/src/chunking_context.rs

+3
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ pub enum CurrentChunkMethod {
3939
DocumentCurrentScript,
4040
}
4141

42+
pub const CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR: &str =
43+
"typeof document === \"object\" ? document.currentScript : undefined";
44+
4245
pub struct BrowserChunkingContextBuilder {
4346
chunking_context: BrowserChunkingContext,
4447
}

turbopack/crates/turbopack-browser/src/ecmascript/content.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@ use super::{
2020
chunk::EcmascriptBrowserChunk, content_entry::EcmascriptBrowserChunkContentEntries,
2121
merged::merger::EcmascriptBrowserChunkContentMerger, version::EcmascriptBrowserChunkVersion,
2222
};
23-
use crate::{chunking_context::CurrentChunkMethod, BrowserChunkingContext};
23+
use crate::{
24+
chunking_context::{CurrentChunkMethod, CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR},
25+
BrowserChunkingContext,
26+
};
2427

2528
#[turbo_tasks::value(serialization = "none")]
2629
pub struct EcmascriptBrowserChunkContent {
@@ -90,7 +93,9 @@ impl EcmascriptBrowserChunkContent {
9093
};
9194
Either::Left(StringifyJs(chunk_server_path))
9295
}
93-
CurrentChunkMethod::DocumentCurrentScript => Either::Right("document.currentScript"),
96+
CurrentChunkMethod::DocumentCurrentScript => {
97+
Either::Right(CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR)
98+
}
9499
};
95100
let mut code = CodeBuilder::new(source_maps);
96101

turbopack/crates/turbopack-browser/src/ecmascript/evaluate/chunk.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ use turbopack_ecmascript::{
2727
};
2828
use turbopack_ecmascript_runtime::RuntimeType;
2929

30-
use crate::{chunking_context::CurrentChunkMethod, BrowserChunkingContext};
30+
use crate::{
31+
chunking_context::{CurrentChunkMethod, CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR},
32+
BrowserChunkingContext,
33+
};
3134

3235
/// An Ecmascript chunk that:
3336
/// * Contains the Turbopack browser runtime code; and
@@ -98,7 +101,9 @@ impl EcmascriptBrowserEvaluateChunk {
98101
};
99102
Either::Left(StringifyJs(chunk_server_path))
100103
}
101-
CurrentChunkMethod::DocumentCurrentScript => Either::Right("document.currentScript"),
104+
CurrentChunkMethod::DocumentCurrentScript => {
105+
Either::Right(CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR)
106+
}
102107
};
103108

104109
let other_chunks_data = self.chunks_data().await?;

turbopack/crates/turbopack-browser/src/ecmascript/list/content.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ use super::{
2525
update::update_chunk_list,
2626
version::EcmascriptDevChunkListVersion,
2727
};
28-
use crate::chunking_context::CurrentChunkMethod;
28+
use crate::chunking_context::{
29+
CurrentChunkMethod, CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR,
30+
};
2931

3032
#[derive(Clone, Debug, Serialize, Deserialize, TraceRawVcs, PartialEq, Eq, NonLocalValue)]
3133
enum CurrentChunkMethodWithData {
@@ -141,7 +143,7 @@ impl EcmascriptDevChunkListContent {
141143
let script_or_path = match &this.current_chunk_method {
142144
CurrentChunkMethodWithData::StringLiteral(path) => Either::Left(StringifyJs(path)),
143145
CurrentChunkMethodWithData::DocumentCurrentScript => {
144-
Either::Right("document.currentScript")
146+
Either::Right(CURRENT_CHUNK_METHOD_DOCUMENT_CURRENT_SCRIPT_EXPR)
145147
}
146148
};
147149

@@ -153,10 +155,6 @@ impl EcmascriptDevChunkListContent {
153155
writedoc!(
154156
code,
155157
r#"
156-
(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push([
157-
{script_or_path},
158-
{{}},
159-
]);
160158
(globalThis.TURBOPACK_CHUNK_LISTS = globalThis.TURBOPACK_CHUNK_LISTS || []).push({{
161159
script: {script_or_path},
162160
chunks: {:#},

turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/base/dev-base.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,6 @@ const devModuleCache: ModuleCache<HotModule> = Object.create(null);
2020
type RefreshRuntimeGlobals =
2121
import("@next/react-refresh-utils/dist/runtime").RefreshRuntimeGlobals;
2222

23-
// Workers are loaded via blob object urls and aren't relative to the main context, this gets
24-
// prefixed to chunk urls in the worker.
25-
// declare var TURBOPACK_WORKER_LOCATION: string;
26-
// declare var CHUNK_BASE_PATH: string;
2723
declare var $RefreshHelpers$: RefreshRuntimeGlobals["$RefreshHelpers$"];
2824
declare var $RefreshReg$: RefreshRuntimeGlobals["$RefreshReg$"];
2925
declare var $RefreshSig$: RefreshRuntimeGlobals["$RefreshSig$"];
@@ -1085,6 +1081,8 @@ function registerChunkList(
10851081
) {
10861082
const chunkListScript = chunkList.script;
10871083
const chunkListPath = getPathFromScript(chunkListScript);
1084+
// The "chunk" is also registered to finish the loading in the backend
1085+
BACKEND.registerChunk(chunkListPath as string as ChunkPath);
10881086
chunkUpdateProvider.push([
10891087
chunkListPath,
10901088
handleApply.bind(null, chunkListPath),

turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/base/runtime-base.ts

+15-2
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,17 @@
1111
/// <reference path="../base/globals.d.ts" />
1212
/// <reference path="../../../shared/runtime-utils.ts" />
1313

14+
// Used in WebWorkers to tell the runtime about the chunk base path
1415
declare var TURBOPACK_WORKER_LOCATION: string;
16+
// Used in WebWorkers to tell the runtime about the current chunk url since it can't be detected via document.currentScript
17+
// Note it's stored in reversed order to use push and pop
18+
declare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined;
19+
20+
// Injected by rust code
1521
declare var CHUNK_BASE_PATH: string;
1622
declare var CHUNK_SUFFIX_PATH: string;
23+
24+
// Provided by build or dev base
1725
declare function instantiateModule(id: ModuleId, source: SourceInfo): Module;
1826

1927
type RuntimeParams = {
@@ -245,7 +253,9 @@ function resolveAbsolutePath(modulePath?: string): string {
245253
}
246254

247255
function getWorkerBlobURL(chunks: ChunkPath[]): string {
248-
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)};importScripts(${chunks.map(c => (`self.TURBOPACK_WORKER_LOCATION + ${JSON.stringify(getChunkRelativeUrl(c))}`)).join(", ")});`;
256+
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)};
257+
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)};
258+
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`;
249259
let blob = new Blob([bootstrap], { type: "text/javascript" });
250260
return URL.createObjectURL(blob);
251261
}
@@ -313,7 +323,10 @@ function getPathFromScript(chunkScript: ChunkPath | ChunkListPath | ChunkScript
313323
if (typeof chunkScript === "string") {
314324
return chunkScript as ChunkPath | ChunkListPath;
315325
}
316-
const src = decodeURIComponent(chunkScript.getAttribute("src")!);
326+
const chunkUrl = typeof TURBOPACK_NEXT_CHUNK_URLS !== "undefined"
327+
? TURBOPACK_NEXT_CHUNK_URLS.pop()!
328+
: chunkScript.getAttribute("src")!;
329+
const src = decodeURIComponent(chunkUrl);
317330
const path = src.startsWith(CHUNK_BASE_PATH) ? src.slice(CHUNK_BASE_PATH.length) : src;
318331
return path as ChunkPath | ChunkListPath;
319332
}

turbopack/crates/turbopack-ecmascript-runtime/js/src/browser/runtime/dom/runtime-backend-dom.ts

+1
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,7 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map();
151151
if (isCss(chunkUrl)) {
152152
// ignore
153153
} else if (isJs(chunkUrl)) {
154+
self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl);
154155
importScripts(TURBOPACK_WORKER_LOCATION + chunkUrl);
155156
} else {
156157
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);

0 commit comments

Comments
 (0)