Unverified Commit 5453818a authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Turbopack: Add __turbopack_load_by_url__ (#76814)

Work in progress for PACK-4071 (implementing `config.deploymentId`)

- [x] Implement `?dpl={config.deploymentId}` in client references
manifest
- [x] Implement `?dpl={config.deploymentId}` in Turbopack chunk loading 
- [x] Add `__turbopack_load_by_url__`
- [ ] Change react-dom-turbopack to use __turbopack_load_by_url__

Last item will be a follow-up PR to this one, given it's already a large
enough change in chunk loading right now.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
parent c2d28fa7
......@@ -966,6 +966,7 @@ impl Project {
self.client_relative_path(),
Vc::cell("/ROOT".into()),
self.next_config().computed_asset_prefix(),
self.next_config().chunk_suffix_path(),
self.client_compile_time_info().environment(),
self.next_mode(),
self.module_id_strategy(),
......
......@@ -415,6 +415,7 @@ pub async fn get_client_chunking_context(
client_root: ResolvedVc<FileSystemPath>,
client_root_to_root_path: ResolvedVc<RcStr>,
asset_prefix: ResolvedVc<Option<RcStr>>,
chunk_suffix_path: ResolvedVc<Option<RcStr>>,
environment: ResolvedVc<Environment>,
mode: Vc<NextMode>,
module_id_strategy: ResolvedVc<Box<dyn ModuleIdStrategy>>,
......@@ -437,6 +438,7 @@ pub async fn get_client_chunking_context(
next_mode.runtime_type(),
)
.chunk_base_path(asset_prefix)
.chunk_suffix_path(chunk_suffix_path)
.minify_type(if *minify.await? {
MinifyType::Minify {
mangle: !*no_mangling.await?,
......
......@@ -83,6 +83,7 @@ pub struct NextConfig {
pub transpile_packages: Option<Vec<RcStr>>,
pub modularize_imports: Option<FxIndexMap<String, ModularizeImportPackageConfig>>,
pub dist_dir: Option<RcStr>,
pub deployment_id: Option<RcStr>,
sass_options: Option<serde_json::Value>,
pub trailing_slash: Option<bool>,
pub asset_prefix: Option<RcStr>,
......@@ -670,9 +671,6 @@ pub struct ExperimentalConfig {
turbo: Option<ExperimentalTurboConfig>,
external_middleware_rewrites_resolve: Option<bool>,
scroll_restoration: Option<bool>,
use_deployment_id: Option<bool>,
use_deployment_id_server_actions: Option<bool>,
deployment_id: Option<RcStr>,
manual_client_base_path: Option<bool>,
optimistic_client_cache: Option<bool>,
middleware_prefetch: Option<MiddlewarePrefetchType>,
......@@ -1393,6 +1391,17 @@ impl NextConfig {
)))
}
/// Returns the suffix to use for chunk loading.
#[turbo_tasks::function]
pub async fn chunk_suffix_path(self: Vc<Self>) -> Result<Vc<Option<RcStr>>> {
let this = self.await?;
match &this.deployment_id {
Some(deployment_id) => Ok(Vc::cell(Some(format!("?dpl={}", deployment_id).into()))),
None => Ok(Vc::cell(None)),
}
}
#[turbo_tasks::function]
pub fn enable_ppr(&self) -> Vc<bool> {
Vc::cell(
......
......@@ -71,12 +71,19 @@ impl ClientReferenceManifest {
async move {
let mut entry_manifest: ClientReferenceManifest = Default::default();
let mut references = FxIndexSet::default();
entry_manifest.module_loading.prefix = next_config
let chunk_suffix_path = next_config.chunk_suffix_path().await?;
let prefix_path = next_config
.computed_asset_prefix()
.await?
.as_ref()
.map(|p| p.clone())
.unwrap_or_default();
let suffix_path = chunk_suffix_path
.as_ref()
.map(|p| p.to_string())
.unwrap_or("".into());
entry_manifest.module_loading.prefix = prefix_path;
entry_manifest.module_loading.cross_origin = next_config
.await?
......@@ -195,6 +202,7 @@ impl ClientReferenceManifest {
// It's possible that a chunk also emits CSS files, that will
// be handled separatedly.
.filter(|path| path.ends_with(".js"))
.map(|path| format!("{}{}", path, suffix_path))
.map(RcStr::from)
.collect::<Vec<_>>();
......@@ -355,6 +363,8 @@ impl ClientReferenceManifest {
for (chunk, chunk_path) in client_chunks_with_path {
if let Some(path) = client_relative_path.get_path_to(&chunk_path) {
// The entry CSS files and entry JS files don't have prefix and suffix
// applied because it is added by Nex.js during rendering.
let path = path.into();
if chunk_path.extension_ref() == Some("css") {
entry_css_files_with_chunk.push((path, chunk));
......
......@@ -2,6 +2,7 @@ import type { AppRenderContext } from './app-render'
const isDev = process.env.NODE_ENV === 'development'
const isTurbopack = !!process.env.TURBOPACK
export function getAssetQueryString(
ctx: AppRenderContext,
addTimestamp: boolean
......@@ -12,12 +13,13 @@ export function getAssetQueryString(
// reload assets when a new RSC response is received.
// Turbopack handles HMR of assets itself and react doesn't need to reload them
// so this approach is not needed for Turbopack.
if (isDev && !isTurbopack && addTimestamp) {
const shouldAddVersion = isDev && !isTurbopack && addTimestamp
if (shouldAddVersion) {
qs += `?v=${ctx.requestTimestamp}`
}
if (ctx.renderOpts.deploymentId) {
qs += `${isDev ? '&' : '?'}dpl=${ctx.renderOpts.deploymentId}`
qs += `${shouldAddVersion ? '&' : '?'}dpl=${ctx.renderOpts.deploymentId}`
}
return qs
}
......@@ -1787,11 +1787,17 @@ export async function copy_vendor_react(task_) {
// bundles have unique constraints like a runtime bundle. For browser builds this
// package will be bundled alongside user code and we don't need to introduce the extra
// indirection
if (
(file.base.startsWith('react-server-dom-turbopack-client') &&
!file.base.startsWith(
'react-server-dom-turbopack-client.browser'
)) ||
if (file.base.startsWith('react-server-dom-turbopack-client.browser')) {
const source = file.data.toString()
let newSource = source.replace(
/__turbopack_load__/g,
'__turbopack_load__'
)
file.data = newSource
} else if (
file.base.startsWith('react-server-dom-turbopack-client') ||
(file.base.startsWith('react-server-dom-turbopack-server') &&
!file.base.startsWith('react-server-dom-turbopack-server.browser'))
) {
......
......@@ -17873,7 +17873,8 @@
"runtimeError": false
},
"test/production/deployment-id-handling/deployment-id-handling.test.ts": {
"passed": [
"passed": [],
"failed": [
"deployment-id-handling disabled should not append dpl query to all assets for /",
"deployment-id-handling disabled should not append dpl query to all assets for /from-app",
"deployment-id-handling disabled should not append dpl query to all assets for /from-app/edge",
......@@ -17883,9 +17884,7 @@
"deployment-id-handling enabled with CUSTOM_DEPLOYMENT_ID should have deployment id env available",
"deployment-id-handling enabled with NEXT_DEPLOYMENT_ID should contain deployment id in RSC payload request headers",
"deployment-id-handling enabled with NEXT_DEPLOYMENT_ID should contain deployment id in prefetch request",
"deployment-id-handling enabled with NEXT_DEPLOYMENT_ID should have deployment id env available"
],
"failed": [
"deployment-id-handling enabled with NEXT_DEPLOYMENT_ID should have deployment id env available",
"deployment-id-handling enabled with CUSTOM_DEPLOYMENT_ID should append dpl query to all assets correctly for /",
"deployment-id-handling enabled with CUSTOM_DEPLOYMENT_ID should append dpl query to all assets correctly for /from-app",
"deployment-id-handling enabled with CUSTOM_DEPLOYMENT_ID should append dpl query to all assets correctly for /from-app/edge",
......@@ -67,6 +67,11 @@ impl BrowserChunkingContextBuilder {
self
}
pub fn chunk_suffix_path(mut self, chunk_suffix_path: ResolvedVc<Option<RcStr>>) -> Self {
self.chunking_context.chunk_suffix_path = chunk_suffix_path;
self
}
pub fn runtime_type(mut self, runtime_type: RuntimeType) -> Self {
self.chunking_context.runtime_type = runtime_type;
self
......@@ -135,6 +140,9 @@ pub struct BrowserChunkingContext {
/// Base path that will be prepended to all chunk URLs when loading them.
/// This path will not appear in chunk paths or chunk data.
chunk_base_path: ResolvedVc<Option<RcStr>>,
/// Suffix path that will be appended to all chunk URLs when loading them.
/// This path will not appear in chunk paths or chunk data.
chunk_suffix_path: ResolvedVc<Option<RcStr>>,
/// URL prefix that will be prepended to all static asset URLs when loading
/// them.
asset_base_path: ResolvedVc<Option<RcStr>>,
......@@ -180,6 +188,7 @@ impl BrowserChunkingContext {
should_use_file_source_map_uris: false,
asset_root_path,
chunk_base_path: ResolvedVc::cell(None),
chunk_suffix_path: ResolvedVc::cell(None),
asset_base_path: ResolvedVc::cell(None),
enable_hot_module_replacement: false,
enable_tracing: false,
......@@ -209,6 +218,11 @@ impl BrowserChunkingContext {
*self.chunk_base_path
}
/// Returns the asset suffix path.
pub fn chunk_suffix_path(&self) -> Vc<Option<RcStr>> {
*self.chunk_suffix_path
}
/// Returns the minify type.
pub fn source_maps_type(&self) -> SourceMapsType {
self.source_maps_type
......
......@@ -153,6 +153,7 @@ impl EcmascriptBrowserEvaluateChunk {
let runtime_code = turbopack_ecmascript_runtime::get_browser_runtime_code(
environment,
chunking_context.chunk_base_path(),
chunking_context.chunk_suffix_path(),
Value::new(chunking_context.runtime_type()),
output_root_to_root_path,
source_maps,
......@@ -163,6 +164,7 @@ impl EcmascriptBrowserEvaluateChunk {
let runtime_code = turbopack_ecmascript_runtime::get_browser_runtime_code(
environment,
chunking_context.chunk_base_path(),
chunking_context.chunk_suffix_path(),
Value::new(chunking_context.runtime_type()),
output_root_to_root_path,
source_maps,
......
......@@ -61,7 +61,7 @@ export function connect({
throw new Error("A separate HMR handler was already registered");
}
globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS = {
push: ([chunkPath, callback]: [ChunkPath, UpdateCallback]) => {
push: ([chunkPath, callback]: [ChunkListPath, UpdateCallback]) => {
subscribeToChunkUpdate(chunkPath, sendMessage, callback);
},
};
......@@ -202,7 +202,7 @@ function mergeChunkListChunks(
): Record<ChunkPath, ChunkUpdate> {
const chunks: Record<ChunkPath, ChunkUpdate> = {};
for (const [chunkPath, chunkUpdateA] of Object.entries(chunksA)) {
for (const [chunkPath, chunkUpdateA] of Object.entries(chunksA) as Array<[ChunkPath, ChunkUpdate]>) {
const chunkUpdateB = chunksB[chunkPath];
if (chunkUpdateB != null) {
const mergedUpdate = mergeChunkUpdates(chunkUpdateA, chunkUpdateB);
......@@ -214,7 +214,7 @@ function mergeChunkListChunks(
}
}
for (const [chunkPath, chunkUpdateB] of Object.entries(chunksB)) {
for (const [chunkPath, chunkUpdateB] of Object.entries(chunksB) as Array<[ChunkPath, ChunkUpdate]>) {
if (chunks[chunkPath] == null) {
chunks[chunkPath] = chunkUpdateB;
}
......@@ -280,7 +280,7 @@ function mergeEcmascriptChunksUpdates(
const chunks: Record<ChunkPath, EcmascriptMergedChunkUpdate> = {};
for (const [chunkPath, chunkUpdateA] of Object.entries(chunksA)) {
for (const [chunkPath, chunkUpdateA] of Object.entries(chunksA) as Array<[ChunkPath, EcmascriptMergedChunkUpdate]>) {
const chunkUpdateB = chunksB[chunkPath];
if (chunkUpdateB != null) {
const mergedUpdate = mergeEcmascriptChunkUpdates(
......@@ -295,7 +295,7 @@ function mergeEcmascriptChunksUpdates(
}
}
for (const [chunkPath, chunkUpdateB] of Object.entries(chunksB)) {
for (const [chunkPath, chunkUpdateB] of Object.entries(chunksB) as Array<[ChunkPath, EcmascriptMergedChunkUpdate]>) {
if (chunks[chunkPath] == null) {
chunks[chunkPath] = chunkUpdateB;
}
......@@ -530,13 +530,13 @@ function finalizeUpdate() {
}
function subscribeToChunkUpdate(
chunkPath: ChunkPath,
chunkListPath: ChunkListPath,
sendMessage: SendMessage,
callback: UpdateCallback
): () => void {
return subscribeToUpdate(
{
path: chunkPath,
path: chunkListPath,
},
sendMessage,
callback
......
......@@ -118,6 +118,7 @@ function instantiateModule(id: ModuleId, source: SourceInfo): Module {
c: moduleCache,
M: moduleFactories,
l: loadChunk.bind(null, sourceInfo),
L: loadChunkByUrl.bind(null, sourceInfo),
w: loadWebAssembly.bind(null, sourceInfo),
u: loadWebAssemblyModule.bind(null, sourceInfo),
g: globalThis,
......
......@@ -51,8 +51,8 @@ type ModuleFactory = (
) => undefined
interface DevRuntimeBackend {
reloadChunk?: (chunkPath: ChunkPath) => Promise<void>;
unloadChunk?: (chunkPath: ChunkPath) => void;
reloadChunk?: (chunkUrl: ChunkUrl) => Promise<void>;
unloadChunk?: (chunkUrl: ChunkUrl) => void;
restart: () => void;
}
......@@ -219,6 +219,7 @@ function instantiateModule(id: ModuleId, source: SourceInfo): Module {
c: devModuleCache,
M: moduleFactories,
l: loadChunk.bind(null, sourceInfo),
L: loadChunkByUrl.bind(null, sourceInfo),
w: loadWebAssembly.bind(null, sourceInfo),
u: loadWebAssemblyModule.bind(null, sourceInfo),
g: globalThis,
......@@ -596,16 +597,18 @@ function applyChunkListUpdate(update: ChunkListUpdate) {
}
if (update.chunks != null) {
for (const [chunkPath, chunkUpdate] of Object.entries(update.chunks)) {
for (const [chunkPath, chunkUpdate] of Object.entries(update.chunks) as Array<[ChunkPath, ChunkUpdate]>) {
const chunkUrl = getChunkRelativeUrl(chunkPath);
switch (chunkUpdate.type) {
case "added":
BACKEND.loadChunk(chunkPath, { type: SourceType.Update });
BACKEND.loadChunk(chunkUrl, { type: SourceType.Update });
break;
case "total":
DEV_BACKEND.reloadChunk?.(chunkPath);
DEV_BACKEND.reloadChunk?.(chunkUrl);
break;
case "deleted":
DEV_BACKEND.unloadChunk?.(chunkPath);
DEV_BACKEND.unloadChunk?.(chunkUrl);
break;
case "partial":
invariant(
......@@ -705,7 +708,7 @@ function computeChangedModules(
const modified = new Map();
const deleted: Set<ModuleId> = new Set();
for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates)) {
for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates) as Array<[ChunkPath, EcmascriptMergedChunkUpdate]>) {
switch (mergedChunkUpdate.type) {
case "added": {
const updateAdded = new Set(mergedChunkUpdate.modules);
......@@ -873,7 +876,7 @@ function getAffectedModuleEffects(moduleId: ModuleId): ModuleEffect {
};
}
function handleApply(chunkListPath: ChunkPath, update: ServerMessage) {
function handleApply(chunkListPath: ChunkListPath, update: ServerMessage) {
switch (update.type) {
case "partial": {
// This indicates that the update is can be applied to the current state of the application.
......@@ -1014,7 +1017,7 @@ function removeModuleFromChunk(
/**
* Disposes of a chunk list and its corresponding exclusive chunks.
*/
function disposeChunkList(chunkListPath: ChunkPath): boolean {
function disposeChunkList(chunkListPath: ChunkListPath): boolean {
const chunkPaths = chunkListChunksMap.get(chunkListPath);
if (chunkPaths == null) {
return false;
......@@ -1033,7 +1036,9 @@ function disposeChunkList(chunkListPath: ChunkPath): boolean {
// We must also dispose of the chunk list's chunk itself to ensure it may
// be reloaded properly in the future.
DEV_BACKEND.unloadChunk?.(chunkListPath);
const chunkListUrl = getChunkRelativeUrl(chunkListPath)
DEV_BACKEND.unloadChunk?.(chunkListUrl);
return true;
}
......@@ -1044,9 +1049,10 @@ function disposeChunkList(chunkListPath: ChunkPath): boolean {
* @returns Whether the chunk was disposed of.
*/
function disposeChunk(chunkPath: ChunkPath): boolean {
const chunkUrl = getChunkRelativeUrl(chunkPath)
// This should happen whether the chunk has any modules in it or not.
// For instance, CSS chunks have no modules in them, but they still need to be unloaded.
DEV_BACKEND.unloadChunk?.(chunkPath);
DEV_BACKEND.unloadChunk?.(chunkUrl);
const chunkModules = chunkModulesMap.get(chunkPath);
if (chunkModules == null) {
......@@ -1077,26 +1083,27 @@ function registerChunkList(
chunkUpdateProvider: ChunkUpdateProvider,
chunkList: ChunkList
) {
const chunkListPath = chunkList.path;
chunkUpdateProvider.push([
chunkList.path,
handleApply.bind(null, chunkList.path),
chunkListPath,
handleApply.bind(null, chunkListPath),
]);
// Adding chunks to chunk lists and vice versa.
const chunks = new Set(chunkList.chunks.map(getChunkPath));
chunkListChunksMap.set(chunkList.path, chunks);
for (const chunkPath of chunks) {
const chunkPaths = new Set(chunkList.chunks.map(getChunkPath));
chunkListChunksMap.set(chunkListPath, chunkPaths);
for (const chunkPath of chunkPaths) {
let chunkChunkLists = chunkChunkListsMap.get(chunkPath);
if (!chunkChunkLists) {
chunkChunkLists = new Set([chunkList.path]);
chunkChunkLists = new Set([chunkListPath]);
chunkChunkListsMap.set(chunkPath, chunkChunkLists);
} else {
chunkChunkLists.add(chunkList.path);
chunkChunkLists.add(chunkListPath);
}
}
if (chunkList.source === "entry") {
markChunkListAsRuntime(chunkList.path);
markChunkListAsRuntime(chunkListPath);
}
}
......
......@@ -8,12 +8,12 @@
type UpdateCallback = (update: ServerMessage) => void;
type ChunkUpdateProvider = {
push: (registration: [ChunkPath, UpdateCallback]) => void;
push: (registration: [ChunkListPath, UpdateCallback]) => void;
};
declare var TURBOPACK_CHUNK_UPDATE_LISTENERS:
| ChunkUpdateProvider
| [ChunkPath, UpdateCallback][]
| [ChunkListPath, UpdateCallback][]
| undefined;
// This is used by the Next.js integration test suite to notify it when HMR
// updates have been completed.
......
......@@ -13,6 +13,7 @@
declare var TURBOPACK_WORKER_LOCATION: string;
declare var CHUNK_BASE_PATH: string;
declare var CHUNK_SUFFIX_PATH: string;
declare function instantiateModule(id: ModuleId, source: SourceInfo): Module;
type RuntimeParams = {
......@@ -27,7 +28,7 @@ type ChunkRegistration = [
];
type ChunkList = {
path: ChunkPath;
path: ChunkListPath;
chunks: ChunkData[];
source: "entry" | "dynamic";
};
......@@ -65,12 +66,12 @@ type SourceInfo =
interface RuntimeBackend {
registerChunk: (chunkPath: ChunkPath, params?: RuntimeParams) => void;
loadChunk: (chunkPath: ChunkPath, source: SourceInfo) => Promise<void>;
loadChunk: (chunkUrl: ChunkUrl, source: SourceInfo) => Promise<void>;
}
interface DevRuntimeBackend {
reloadChunk?: (chunkPath: ChunkPath) => Promise<void>;
unloadChunk?: (chunkPath: ChunkPath) => void;
reloadChunk?: (chunkUrl: ChunkUrl) => Promise<void>;
unloadChunk?: (chunkUrl: ChunkUrl) => void;
restart: () => void;
}
......@@ -90,21 +91,21 @@ const moduleChunksMap: Map<ModuleId, Set<ChunkPath>> = new Map();
/**
* Map from a chunk path to all modules it contains.
*/
const chunkModulesMap: Map<ModuleId, Set<ChunkPath>> = new Map();
const chunkModulesMap: Map<ChunkPath, Set<ModuleId>> = new Map();
/**
* Chunk lists that contain a runtime. When these chunk lists receive an update
* that can't be reconciled with the current state of the page, we need to
* reload the runtime entirely.
*/
const runtimeChunkLists: Set<ChunkPath> = new Set();
const runtimeChunkLists: Set<ChunkListPath> = new Set();
/**
* Map from a chunk list to the chunk paths it contains.
*/
const chunkListChunksMap: Map<ChunkPath, Set<ChunkPath>> = new Map();
const chunkListChunksMap: Map<ChunkListPath, Set<ChunkPath>> = new Map();
/**
* Map from a chunk path to the chunk lists it belongs to.
*/
const chunkChunkListsMap: Map<ChunkPath, Set<ChunkPath>> = new Map();
const chunkChunkListsMap: Map<ChunkPath, Set<ChunkListPath>> = new Map();
const availableModules: Map<ModuleId, Promise<any> | true> = new Map();
......@@ -184,12 +185,9 @@ async function loadChunk(
return promise;
}
async function loadChunkPath(
source: SourceInfo,
chunkPath: ChunkPath
): Promise<any> {
async function loadChunkByUrl(source: SourceInfo, chunkUrl: ChunkUrl) {
try {
await BACKEND.loadChunk(chunkPath, source);
await BACKEND.loadChunk(chunkUrl, source);
} catch (error) {
let loadReason;
switch (source.type) {
......@@ -206,7 +204,7 @@ async function loadChunkPath(
invariant(source, (source) => `Unknown source type: ${source?.type}`);
}
throw new Error(
`Failed to load chunk ${chunkPath} ${loadReason}${
`Failed to load chunk ${chunkUrl} ${loadReason}${
error ? `: ${error}` : ""
}`,
error
......@@ -218,6 +216,14 @@ async function loadChunkPath(
}
}
async function loadChunkPath(
source: SourceInfo,
chunkPath: ChunkPath
): Promise<any> {
const url = getChunkRelativeUrl(chunkPath);
return loadChunkByUrl(source, url);
}
/**
* Returns an absolute url to an asset.
*/
......@@ -292,11 +298,11 @@ function instantiateRuntimeModule(
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/
function getChunkRelativeUrl(chunkPath: ChunkPath): string {
function getChunkRelativeUrl(chunkPath: ChunkPath | ChunkListPath): ChunkUrl {
return `${CHUNK_BASE_PATH}${chunkPath
.split("/")
.map((p) => encodeURIComponent(p))
.join("/")}`;
.join("/")}${CHUNK_SUFFIX_PATH}` as ChunkUrl;
}
/**
......@@ -304,7 +310,7 @@ function getChunkRelativeUrl(chunkPath: ChunkPath): string {
* runtime chunk list. For instance, integration tests can have multiple chunk
* groups loaded at runtime, each with its own chunk list.
*/
function markChunkListAsRuntime(chunkListPath: ChunkPath) {
function markChunkListAsRuntime(chunkListPath: ChunkListPath) {
runtimeChunkLists.add(chunkListPath);
}
......@@ -322,3 +328,19 @@ function registerChunk([
return BACKEND.registerChunk(chunkPath, runtimeParams);
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
*/
function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {
return regexJsUrl.test(chunkUrlOrPath);
}
const regexCssUrl = /\.css(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.
*/
function isCss(chunkUrl: ChunkUrl): boolean {
return regexCssUrl.test(chunkUrl);
}
......@@ -16,21 +16,20 @@ let DEV_BACKEND: DevRuntimeBackend;
(() => {
DEV_BACKEND = {
unloadChunk(chunkPath) {
deleteResolver(chunkPath);
unloadChunk(chunkUrl) {
deleteResolver(chunkUrl);
const chunkUrl = getChunkRelativeUrl(chunkPath);
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl);
if (chunkPath.endsWith(".css")) {
if (isCss(chunkUrl)) {
const links = document.querySelectorAll(
`link[href="${chunkUrl}"],link[href^="${chunkUrl}?"],link[href="${decodedChunkUrl}"],link[href^="${decodedChunkUrl}?"]`
);
for (const link of Array.from(links)) {
link.remove();
}
} else if (chunkPath.endsWith(".js")) {
} else if (isJs(chunkUrl)) {
// Unloading a JS chunk would have no effect, as it lives in the JS
// runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep
......@@ -42,26 +41,24 @@ let DEV_BACKEND: DevRuntimeBackend;
script.remove();
}
} else {
throw new Error(`can't infer type of chunk from path ${chunkPath}`);
throw new Error(`can't infer type of chunk from URL ${chunkUrl}`);
}
},
reloadChunk(chunkPath) {
reloadChunk(chunkUrl) {
return new Promise<void>((resolve, reject) => {
if (!chunkPath.endsWith(".css")) {
if (!isCss(chunkUrl)) {
reject(new Error("The DOM backend can only reload CSS chunks"));
return;
}
const chunkUrl = getChunkRelativeUrl(chunkPath);
const decodedChunkUrl = decodeURI(chunkUrl);
const previousLinks = document.querySelectorAll(
`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`
);
if (previousLinks.length === 0) {
reject(new Error(`No link element found for chunk ${chunkPath}`));
reject(new Error(`No link element found for chunk ${chunkUrl}`));
return;
}
......@@ -108,14 +105,14 @@ let DEV_BACKEND: DevRuntimeBackend;
restart: () => self.location.reload(),
};
function deleteResolver(chunkPath: ChunkPath) {
chunkResolvers.delete(chunkPath);
function deleteResolver(chunkUrl: ChunkUrl) {
chunkResolvers.delete(chunkUrl);
}
})();
function _eval({ code, url, map }: EcmascriptModuleEntry): ModuleFactory {
code += `\n\n//# sourceURL=${encodeURI(
location.origin + CHUNK_BASE_PATH + url
location.origin + CHUNK_BASE_PATH + url + CHUNK_SUFFIX_PATH
)}`;
if (map) {
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(
......
......@@ -51,12 +51,14 @@ async function loadWebAssemblyModule(
/**
* Maps chunk paths to the corresponding resolver.
*/
const chunkResolvers: Map<ChunkPath, ChunkResolver> = new Map();
const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map();
(() => {
BACKEND = {
async registerChunk(chunkPath, params) {
const resolver = getOrCreateResolver(chunkPath);
const chunkUrl = getChunkRelativeUrl(chunkPath);
const resolver = getOrCreateResolver(chunkUrl);
resolver.resolve();
if (params == null) {
......@@ -64,9 +66,11 @@ const chunkResolvers: Map<ChunkPath, ChunkResolver> = new Map();
}
for (const otherChunkData of params.otherChunks) {
const otherChunkPath = getChunkPath(otherChunkData);
const otherChunkPath = getChunkPath(otherChunkData)
const otherChunkUrl = getChunkRelativeUrl(otherChunkPath);
// Chunk might have started loading, so we want to avoid triggering another load.
getOrCreateResolver(otherChunkPath);
getOrCreateResolver(otherChunkUrl);
}
// This waits for chunks to be loaded, but also marks included items as available.
......@@ -83,13 +87,17 @@ const chunkResolvers: Map<ChunkPath, ChunkResolver> = new Map();
}
},
loadChunk(chunkPath, source) {
return doLoadChunk(chunkPath, source);
/**
* Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded.
*/
loadChunk(chunkUrl, source) {
return doLoadChunk(chunkUrl, source);
},
};
function getOrCreateResolver(chunkPath: ChunkPath): ChunkResolver {
let resolver = chunkResolvers.get(chunkPath);
function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {
let resolver = chunkResolvers.get(chunkUrl);
if (!resolver) {
let resolve: () => void;
let reject: (error?: Error) => void;
......@@ -106,17 +114,17 @@ const chunkResolvers: Map<ChunkPath, ChunkResolver> = new Map();
},
reject: reject!,
};
chunkResolvers.set(chunkPath, resolver);
chunkResolvers.set(chunkUrl, resolver);
}
return resolver;
}
/**
* Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded.
*/
async function doLoadChunk(chunkPath: ChunkPath, source: SourceInfo) {
const resolver = getOrCreateResolver(chunkPath);
/**
* Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded.
*/
function doLoadChunk(chunkUrl: ChunkUrl, source: SourceInfo) {
const resolver = getOrCreateResolver(chunkUrl);
if (resolver.resolved) {
return resolver.promise;
}
......@@ -125,7 +133,7 @@ const chunkResolvers: Map<ChunkPath, ChunkResolver> = new Map();
// We don't need to load chunks references from runtime code, as they're already
// present in the DOM.
if (chunkPath.endsWith(".css")) {
if (isCss(chunkUrl)) {
// CSS chunks do not register themselves, and as such must be marked as
// loaded instantly.
resolver.resolve();
......@@ -138,20 +146,20 @@ const chunkResolvers: Map<ChunkPath, ChunkResolver> = new Map();
return resolver.promise;
}
const chunkUrl = getChunkRelativeUrl(chunkPath);
const decodedChunkUrl = decodeURI(chunkUrl);
if (typeof importScripts === "function") {
// We're in a web worker
if (chunkPath.endsWith(".css")) {
if (isCss(chunkUrl)) {
// ignore
} else if (chunkPath.endsWith(".js")) {
} else if (isJs(chunkUrl)) {
importScripts(TURBOPACK_WORKER_LOCATION + chunkUrl);
} else {
throw new Error(`can't infer type of chunk from path ${chunkPath} in worker`);
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
}
} else {
if (chunkPath.endsWith(".css")) {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl);
if (isCss(chunkUrl)) {
const previousLinks = document.querySelectorAll(
`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`
);
......@@ -173,7 +181,7 @@ const chunkResolvers: Map<ChunkPath, ChunkResolver> = new Map();
};
document.body.appendChild(link);
}
} else if (chunkPath.endsWith(".js")) {
} else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(
`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`
);
......@@ -197,10 +205,11 @@ const chunkResolvers: Map<ChunkPath, ChunkResolver> = new Map();
document.body.appendChild(script);
}
} else {
throw new Error(`can't infer type of chunk from path ${chunkPath}`);
throw new Error(`can't infer type of chunk from URL ${chunkUrl}`);
}
}
return resolver.promise;
}
})();
......@@ -112,14 +112,14 @@ async function loadWebAssemblyModule(
chunkPath,
params.otherChunks.filter((chunk) =>
// The none runtime can only handle JS chunks, so we only wait for these
getChunkPath(chunk).endsWith(".js")
isJs(getChunkPath(chunk))
),
params.runtimeModuleIds
);
}
},
loadChunk(_chunkPath, _fromChunkPath) {
loadChunk(_chunkUrl, _source) {
throw new Error("chunk loading is not supported");
},
};
......
......@@ -94,7 +94,7 @@ function loadChunk(chunkData: ChunkData, source?: SourceInfo): void {
}
function loadChunkPath(chunkPath: ChunkPath, source?: SourceInfo): void {
if (!chunkPath.endsWith(".js")) {
if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js.
// This branch can be hit when trying to load a CSS chunk.
return;
......@@ -127,7 +127,7 @@ async function loadChunkAsync(
chunkData: ChunkData
): Promise<any> {
const chunkPath = typeof chunkData === "string" ? chunkData : chunkData.path;
if (!chunkPath.endsWith(".js")) {
if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js.
// This branch can be hit when trying to load a CSS chunk.
return;
......@@ -173,6 +173,11 @@ async function loadChunkAsync(
}
}
async function loadChunkAsyncByUrl(source: SourceInfo, chunkUrl: string) {
const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath;
return loadChunkAsync(source, path);
}
function loadWebAssembly(chunkPath: ChunkPath, imports: WebAssembly.Imports) {
const resolved = path.resolve(RUNTIME_ROOT, chunkPath);
......@@ -256,6 +261,7 @@ function instantiateModule(id: ModuleId, source: SourceInfo): ModuleWithDirectio
c: moduleCache,
M: moduleFactories,
l: loadChunkAsync.bind(null, { type: SourceType.Parent, parentId: id }),
L: loadChunkAsyncByUrl.bind(null, { type: SourceType.Parent, parentId: id }),
w: loadWebAssembly,
u: loadWebAssemblyModule,
g: globalThis,
......@@ -337,6 +343,14 @@ function getOrInstantiateRuntimeModule(
return instantiateRuntimeModule(moduleId, chunkPath);
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
*/
function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {
return regexJsUrl.test(chunkUrlOrPath);
}
module.exports = {
getOrInstantiateRuntimeModule,
loadChunk,
......
......@@ -7,7 +7,9 @@
* specific to the runtime context.
*/
type ChunkPath = string;
type ChunkListPath = string & { readonly brand: unique symbol };
type ChunkPath = string & { readonly brand: unique symbol };
type ChunkUrl = string & { readonly brand: unique symbol };
type ModuleId = string;
interface Exports {
......@@ -37,6 +39,7 @@ type ExportNamespace = (namespace: any) => void;
type DynamicExport = (object: Record<string, any>) => void;
type LoadChunk = (chunkPath: ChunkPath) => Promise<any> | undefined;
type LoadChunkByUrl = (chunkUrl: ChunkUrl) => Promise<any> | undefined;
type LoadWebAssembly = (
wasmChunkPath: ChunkPath,
imports: WebAssembly.Imports
......@@ -95,6 +98,7 @@ interface TurbopackBaseContext<M> {
c: ModuleCache<M>;
M: ModuleFactories;
l: LoadChunk;
L: LoadChunkByUrl;
w: LoadWebAssembly;
u: LoadWebAssemblyModule;
g: typeof globalThis;
......
......@@ -18,6 +18,7 @@ use crate::{asset_context::get_runtime_asset_context, embed_js::embed_static_cod
pub async fn get_browser_runtime_code(
environment: Vc<Environment>,
chunk_base_path: Vc<Option<RcStr>>,
chunk_suffix_path: Vc<Option<RcStr>>,
runtime_type: Value<RuntimeType>,
output_root_to_root_path: Vc<RcStr>,
generate_source_map: bool,
......@@ -80,6 +81,10 @@ pub async fn get_browser_runtime_code(
let relative_root_path = output_root_to_root_path.await?;
let chunk_base_path = &*chunk_base_path.await?;
let chunk_base_path = chunk_base_path.as_ref().map_or_else(|| "", |f| f.as_str());
let chunk_suffix_path = &*chunk_suffix_path.await?;
let chunk_suffix_path = chunk_suffix_path
.as_ref()
.map_or_else(|| "", |f| f.as_str());
writedoc!(
code,
......@@ -90,10 +95,12 @@ pub async fn get_browser_runtime_code(
}}
const CHUNK_BASE_PATH = {};
const CHUNK_SUFFIX_PATH = {};
const RELATIVE_ROOT_PATH = {};
const RUNTIME_PUBLIC_PATH = {};
"#,
StringifyJs(chunk_base_path),
StringifyJs(chunk_suffix_path),
StringifyJs(relative_root_path.as_str()),
StringifyJs(chunk_base_path),
)?;
......
......@@ -54,6 +54,8 @@ pub const TURBOPACK_MODULES: &TurbopackRuntimeFunctionShortcut =
&TurbopackRuntimeFunctionShortcut::new("__turbopack_context__.M", "M");
pub const TURBOPACK_LOAD: &TurbopackRuntimeFunctionShortcut =
&TurbopackRuntimeFunctionShortcut::new("__turbopack_context__.l", "l");
pub const TURBOPACK_LOAD_BY_URL: &TurbopackRuntimeFunctionShortcut =
&TurbopackRuntimeFunctionShortcut::new("__turbopack_context__.L", "L");
pub const TURBOPACK_DYNAMIC: &TurbopackRuntimeFunctionShortcut =
&TurbopackRuntimeFunctionShortcut::new("__turbopack_context__.j", "j");
pub const TURBOPACK_RESOLVE_ABSOLUTE_PATH: &TurbopackRuntimeFunctionShortcut =
......@@ -77,7 +79,7 @@ pub const TURBOPACK_REQUIRE_STUB: &TurbopackRuntimeFunctionShortcut =
pub const TURBOPACK_REQUIRE_REAL: &TurbopackRuntimeFunctionShortcut =
&TurbopackRuntimeFunctionShortcut::new("__turbopack_context__.t", "t");
pub const TUBROPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 20] = [
pub const TUBROPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 21] = [
("__turbopack_require__", TURBOPACK_REQUIRE),
("__turbopack_module_context__", TURBOPACK_MODULE_CONTEXT),
("__turbopack_import__", TURBOPACK_IMPORT),
......@@ -87,6 +89,7 @@ pub const TUBROPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio
("__turbopack_cache__", TURBOPACK_CACHE),
("__turbopack_modules__", TURBOPACK_MODULES),
("__turbopack_load__", TURBOPACK_LOAD),
("__turbopack_load_by_url__", TURBOPACK_LOAD_BY_URL),
("__turbopack_dynamic__", TURBOPACK_DYNAMIC),
(
"__turbopack_resolve_absolute_path__",
......
......@@ -466,7 +466,7 @@ function loadChunk(chunkData, source) {
}
}
function loadChunkPath(chunkPath, source) {
if (!chunkPath.endsWith(".js")) {
if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js.
// This branch can be hit when trying to load a CSS chunk.
return;
......@@ -491,7 +491,7 @@ function loadChunkPath(chunkPath, source) {
}
async function loadChunkAsync(source, chunkData) {
const chunkPath = typeof chunkData === "string" ? chunkData : chunkData.path;
if (!chunkPath.endsWith(".js")) {
if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js.
// This branch can be hit when trying to load a CSS chunk.
return;
......@@ -529,6 +529,10 @@ async function loadChunkAsync(source, chunkData) {
});
}
}
async function loadChunkAsyncByUrl(source, chunkUrl) {
const path1 = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT));
return loadChunkAsync(source, path1);
}
function loadWebAssembly(chunkPath, imports) {
const resolved = path.resolve(RUNTIME_ROOT, chunkPath);
return instantiateWebAssemblyFromPath(resolved, imports);
......@@ -607,6 +611,10 @@ function instantiateModule(id, source) {
type: 1,
parentId: id
}),
L: loadChunkAsyncByUrl.bind(null, {
type: 1,
parentId: id
}),
w: loadWebAssembly,
u: loadWebAssemblyModule,
g: globalThis,
......@@ -668,7 +676,13 @@ function getOrInstantiateRuntimeModule(moduleId, chunkPath) {
}
return instantiateRuntimeModule(moduleId, chunkPath);
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
*/ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath);
}
module.exports = {
getOrInstantiateRuntimeModule,
loadChunk
};
};
\ No newline at end of file
......@@ -6,5 +6,5 @@
{"offset": {"line": 338, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/base-externals-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../shared/runtime-utils.ts\" />\n\n/// A 'base' utilities to support runtime can have externals.\n/// Currently this is for node.js / edge runtime both.\n/// If a fn requires node.js specific behavior, it should be placed in `node-external-utils` instead.\n\nasync function externalImport(id: ModuleId) {\n let raw\n try {\n raw = await import(id)\n } catch (err) {\n // TODO(alexkirsz) This can happen when a client-side module tries to load\n // an external module we don't provide a shim for (e.g. querystring, url).\n // For now, we fail semi-silently, but in the future this should be a\n // compilation error.\n throw new Error(`Failed to load external module ${id}: ${err}`)\n }\n\n if (raw && raw.__esModule && raw.default && 'default' in raw.default) {\n return interopEsm(raw.default, createNS(raw), true)\n }\n\n return raw\n}\n\nfunction externalRequire(\n id: ModuleId,\n thunk: () => any,\n esm: boolean = false\n): Exports | EsmNamespaceObject {\n let raw\n try {\n raw = thunk()\n } catch (err) {\n // TODO(alexkirsz) This can happen when a client-side module tries to load\n // an external module we don't provide a shim for (e.g. querystring, url).\n // For now, we fail semi-silently, but in the future this should be a\n // compilation error.\n throw new Error(`Failed to load external module ${id}: ${err}`)\n }\n\n if (!esm || raw.__esModule) {\n return raw\n }\n\n return interopEsm(raw, createNS(raw), true)\n}\n\nexternalRequire.resolve = (\n id: string,\n options?: {\n paths?: string[]\n }\n) => {\n return require.resolve(id, options)\n}\n"],"names":[],"mappings":"AAAA,oDAAoD,GAEpD,mDAAmD;AAEnD,6DAA6D;AAC7D,sDAAsD;AACtD,qGAAqG;AAErG,eAAe,eAAe,EAAY;IACxC,IAAI;IACJ,IAAI;QACF,MAAM,MAAM,MAAM,CAAC;IACrB,EAAE,OAAO,KAAK;QACZ,0EAA0E;QAC1E,0EAA0E;QAC1E,qEAAqE;QACrE,qBAAqB;QACrB,MAAM,IAAI,MAAM,CAAC,+BAA+B,EAAE,GAAG,EAAE,EAAE,KAAK;IAChE;IAEA,IAAI,OAAO,IAAI,UAAU,IAAI,IAAI,OAAO,IAAI,aAAa,IAAI,OAAO,EAAE;QACpE,OAAO,WAAW,IAAI,OAAO,EAAE,SAAS,MAAM;IAChD;IAEA,OAAO;AACT;AAEA,SAAS,gBACP,EAAY,EACZ,KAAgB,EAChB,MAAe,KAAK;IAEpB,IAAI;IACJ,IAAI;QACF,MAAM;IACR,EAAE,OAAO,KAAK;QACZ,0EAA0E;QAC1E,0EAA0E;QAC1E,qEAAqE;QACrE,qBAAqB;QACrB,MAAM,IAAI,MAAM,CAAC,+BAA+B,EAAE,GAAG,EAAE,EAAE,KAAK;IAChE;IAEA,IAAI,CAAC,OAAO,IAAI,UAAU,EAAE;QAC1B,OAAO;IACT;IAEA,OAAO,WAAW,KAAK,SAAS,MAAM;AACxC;AAEA,gBAAgB,OAAO,GAAG,CACxB,IACA;IAIA,OAAO,QAAQ,OAAO,CAAC,IAAI;AAC7B","ignoreList":[0]}},
{"offset": {"line": 377, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/node-externals-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\ndeclare var RUNTIME_PUBLIC_PATH: string;\ndeclare var RELATIVE_ROOT_PATH: string;\ndeclare var ASSET_PREFIX: string;\n\nconst path = require(\"path\");\n\nconst relativePathToRuntimeRoot = path.relative(RUNTIME_PUBLIC_PATH, \".\");\n// Compute the relative path to the `distDir`.\nconst relativePathToDistRoot = path.join(\n relativePathToRuntimeRoot,\n RELATIVE_ROOT_PATH\n);\nconst RUNTIME_ROOT = path.resolve(__filename, relativePathToRuntimeRoot);\n// Compute the absolute path to the root, by stripping distDir from the absolute path to this file.\nconst ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot);\n\n/**\n * Returns an absolute path to the given module path.\n * Module path should be relative, either path to a file or a directory.\n *\n * This fn allows to calculate an absolute path for some global static values, such as\n * `__dirname` or `import.meta.url` that Turbopack will not embeds in compile time.\n * See ImportMetaBinding::code_generation for the usage.\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n if (modulePath) {\n return path.join(ABSOLUTE_ROOT, modulePath);\n }\n return ABSOLUTE_ROOT;\n}\n"],"names":[],"mappings":"AAAA,oDAAoD,GAMpD,MAAM,OAAO,QAAQ;AAErB,MAAM,4BAA4B,KAAK,QAAQ,CAAC,qBAAqB;AACrE,8CAA8C;AAC9C,MAAM,yBAAyB,KAAK,IAAI,CACtC,2BACA;AAEF,MAAM,eAAe,KAAK,OAAO,CAAC,YAAY;AAC9C,mGAAmG;AACnG,MAAM,gBAAgB,KAAK,OAAO,CAAC,YAAY;AAE/C;;;;;;;CAOC,GACD,SAAS,oBAAoB,UAAmB;IAC9C,IAAI,YAAY;QACd,OAAO,KAAK,IAAI,CAAC,eAAe;IAClC;IACA,OAAO;AACT","ignoreList":[0]}},
{"offset": {"line": 397, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/node-wasm-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../shared/runtime-utils.ts\" />\n\nfunction readWebAssemblyAsResponse(path: string) {\n const { createReadStream } = require(\"fs\") as typeof import(\"fs\");\n const { Readable } = require(\"stream\") as typeof import(\"stream\");\n\n const stream = createReadStream(path);\n\n // @ts-ignore unfortunately there's a slight type mismatch with the stream.\n return new Response(Readable.toWeb(stream), {\n headers: {\n \"content-type\": \"application/wasm\",\n },\n });\n}\n\nasync function compileWebAssemblyFromPath(\n path: string\n): Promise<WebAssembly.Module> {\n const response = readWebAssemblyAsResponse(path);\n\n return await WebAssembly.compileStreaming(response);\n}\n\nasync function instantiateWebAssemblyFromPath(\n path: string,\n importsObj: WebAssembly.Imports\n): Promise<Exports> {\n const response = readWebAssemblyAsResponse(path);\n\n const { instance } = await WebAssembly.instantiateStreaming(\n response,\n importsObj\n );\n\n return instance.exports;\n}\n"],"names":[],"mappings":"AAAA,oDAAoD,GAEpD,mDAAmD;AAEnD,SAAS,0BAA0B,IAAY;IAC7C,MAAM,EAAE,gBAAgB,EAAE,GAAG,QAAQ;IACrC,MAAM,EAAE,QAAQ,EAAE,GAAG,QAAQ;IAE7B,MAAM,SAAS,iBAAiB;IAEhC,2EAA2E;IAC3E,OAAO,IAAI,SAAS,SAAS,KAAK,CAAC,SAAS;QAC1C,SAAS;YACP,gBAAgB;QAClB;IACF;AACF;AAEA,eAAe,2BACb,IAAY;IAEZ,MAAM,WAAW,0BAA0B;IAE3C,OAAO,MAAM,YAAY,gBAAgB,CAAC;AAC5C;AAEA,eAAe,+BACb,IAAY,EACZ,UAA+B;IAE/B,MAAM,WAAW,0BAA0B;IAE3C,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,YAAY,oBAAoB,CACzD,UACA;IAGF,OAAO,SAAS,OAAO;AACzB","ignoreList":[0]}},
{"offset": {"line": 418, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/runtime.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../shared/runtime-utils.ts\" />\n/// <reference path=\"../shared-node/base-externals-utils.ts\" />\n/// <reference path=\"../shared-node/node-externals-utils.ts\" />\n/// <reference path=\"../shared-node/node-wasm-utils.ts\" />\n\nenum SourceType {\n /**\n * The module was instantiated because it was included in an evaluated chunk's\n * runtime.\n */\n Runtime = 0,\n /**\n * The module was instantiated because a parent module imported it.\n */\n Parent = 1,\n}\n\ntype SourceInfo =\n | {\n type: SourceType.Runtime;\n chunkPath: ChunkPath;\n }\n | {\n type: SourceType.Parent;\n parentId: ModuleId;\n };\n\nfunction stringifySourceInfo(source: SourceInfo): string {\n switch (source.type) {\n case SourceType.Runtime:\n return `runtime for chunk ${source.chunkPath}`;\n case SourceType.Parent:\n return `parent module ${source.parentId}`;\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`);\n }\n}\n\ntype ExternalRequire = (\n id: ModuleId,\n thunk: () => any,\n esm?: boolean\n) => Exports | EsmNamespaceObject;\ntype ExternalImport = (id: ModuleId) => Promise<Exports | EsmNamespaceObject>;\n\ninterface TurbopackNodeBuildContext extends TurbopackBaseContext<Module> {\n R: ResolvePathFromModule;\n x: ExternalRequire;\n y: ExternalImport;\n}\n\ntype ModuleFactory = (\n this: Module[\"exports\"],\n context: TurbopackNodeBuildContext\n) => undefined;\n\nconst url = require(\"url\") as typeof import('url');\nconst fs = require(\"fs/promises\") as typeof import('fs/promises');\n\nconst moduleFactories: ModuleFactories = Object.create(null);\nconst moduleCache: ModuleCache<ModuleWithDirection> = Object.create(null);\n\n/**\n * Returns an absolute path to the given module's id.\n */\nfunction createResolvePathFromModule(\n resolver: (moduleId: string) => Exports\n): (moduleId: string) => string {\n return function resolvePathFromModule(moduleId: string): string {\n const exported = resolver(moduleId);\n const exportedPath = exported?.default ?? exported;\n if (typeof exportedPath !== \"string\") {\n return exported as any;\n }\n\n const strippedAssetPrefix = exportedPath.slice(ASSET_PREFIX.length);\n const resolved = path.resolve(\n RUNTIME_ROOT,\n strippedAssetPrefix\n );\n\n return url.pathToFileURL(resolved).href;\n };\n}\n\nfunction loadChunk(chunkData: ChunkData, source?: SourceInfo): void {\n if (typeof chunkData === \"string\") {\n return loadChunkPath(chunkData, source);\n } else {\n return loadChunkPath(chunkData.path, source);\n }\n}\n\nfunction loadChunkPath(chunkPath: ChunkPath, source?: SourceInfo): void {\n if (!chunkPath.endsWith(\".js\")) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return;\n }\n\n try {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath);\n const chunkModules: ModuleFactories = require(resolved);\n\n for (const [moduleId, moduleFactory] of Object.entries(chunkModules)) {\n if (!moduleFactories[moduleId]) {\n moduleFactories[moduleId] = moduleFactory;\n }\n }\n } catch (e) {\n let errorMessage = `Failed to load chunk ${chunkPath}`;\n\n if (source) {\n errorMessage += ` from ${stringifySourceInfo(source)}`;\n }\n\n throw new Error(errorMessage, {\n cause: e,\n });\n }\n}\n\nasync function loadChunkAsync(\n source: SourceInfo,\n chunkData: ChunkData\n): Promise<any> {\n const chunkPath = typeof chunkData === \"string\" ? chunkData : chunkData.path;\n if (!chunkPath.endsWith(\".js\")) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return;\n }\n\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath);\n\n try {\n const contents = await fs.readFile(resolved, \"utf-8\");\n\n const localRequire = (id: string) => {\n let resolvedId = require.resolve(id, {paths: [path.dirname(resolved)]});\n return require(resolvedId);\n }\n const module = {\n exports: {},\n };\n // TODO: Use vm.runInThisContext once our minimal supported Node.js version includes https://github.com/nodejs/node/pull/52153\n // eslint-disable-next-line no-eval -- Can't use vm.runInThisContext due to https://github.com/nodejs/node/issues/52102\n (0, eval)(\n \"(function(module, exports, require, __dirname, __filename) {\" +\n contents +\n \"\\n})\" +\n \"\\n//# sourceURL=\" + url.pathToFileURL(resolved),\n )(module, module.exports, localRequire, path.dirname(resolved), resolved);\n\n const chunkModules: ModuleFactories = module.exports;\n for (const [moduleId, moduleFactory] of Object.entries(chunkModules)) {\n if (!moduleFactories[moduleId]) {\n moduleFactories[moduleId] = moduleFactory;\n }\n }\n } catch (e) {\n let errorMessage = `Failed to load chunk ${chunkPath}`;\n\n if (source) {\n errorMessage += ` from ${stringifySourceInfo(source)}`;\n }\n\n throw new Error(errorMessage, {\n cause: e,\n });\n }\n}\n\nfunction loadWebAssembly(chunkPath: ChunkPath, imports: WebAssembly.Imports) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath);\n\n return instantiateWebAssemblyFromPath(resolved, imports);\n}\n\nfunction loadWebAssemblyModule(chunkPath: ChunkPath) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath);\n\n return compileWebAssemblyFromPath(resolved);\n}\n\nfunction getWorkerBlobURL(_chunks: ChunkPath[]): string {\n throw new Error(\"Worker blobs are not implemented yet for Node.js\");\n}\n\nfunction instantiateModule(id: ModuleId, source: SourceInfo): ModuleWithDirection {\n const moduleFactory = moduleFactories[id];\n if (typeof moduleFactory !== \"function\") {\n // This can happen if modules incorrectly handle HMR disposes/updates,\n // e.g. when they keep a `setTimeout` around which still executes old code\n // and contains e.g. a `require(\"something\")` call.\n let instantiationReason;\n switch (source.type) {\n case SourceType.Runtime:\n instantiationReason = `as a runtime entry of chunk ${source.chunkPath}`;\n break;\n case SourceType.Parent:\n instantiationReason = `because it was required from module ${source.parentId}`;\n break;\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`);\n }\n throw new Error(\n `Module ${id} was instantiated ${instantiationReason}, but the module factory is not available. It might have been deleted in an HMR update.`\n );\n }\n\n let parents: ModuleId[];\n switch (source.type) {\n case SourceType.Runtime:\n parents = [];\n break;\n case SourceType.Parent:\n // No need to add this module as a child of the parent module here, this\n // has already been taken care of in `getOrInstantiateModuleFromParent`.\n parents = [source.parentId];\n break;\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`);\n }\n\n const module: ModuleWithDirection = {\n exports: {},\n error: undefined,\n loaded: false,\n id,\n parents,\n children: [],\n namespaceObject: undefined,\n };\n moduleCache[id] = module;\n\n // NOTE(alexkirsz) This can fail when the module encounters a runtime error.\n try {\n const r = commonJsRequire.bind(null, module);\n moduleFactory.call(module.exports, {\n a: asyncModule.bind(null, module),\n e: module.exports,\n r,\n t: runtimeRequire,\n x: externalRequire,\n y: externalImport,\n f: moduleContext,\n i: esmImport.bind(null, module),\n s: esmExport.bind(null, module, module.exports),\n j: dynamicExport.bind(null, module, module.exports),\n v: exportValue.bind(null, module),\n n: exportNamespace.bind(null, module),\n m: module,\n c: moduleCache,\n M: moduleFactories,\n l: loadChunkAsync.bind(null, { type: SourceType.Parent, parentId: id }),\n w: loadWebAssembly,\n u: loadWebAssemblyModule,\n g: globalThis,\n P: resolveAbsolutePath,\n U: relativeURL,\n R: createResolvePathFromModule(r),\n b: getWorkerBlobURL,\n z: requireStub,\n __dirname: typeof module.id === \"string\" ? module.id.replace(/(^|\\/)\\/+$/, \"\") : module.id\n });\n } catch (error) {\n module.error = error as any;\n throw error;\n }\n\n module.loaded = true;\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject);\n }\n\n return module;\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore\nfunction getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: ModuleWithDirection\n): ModuleWithDirection {\n const module = moduleCache[id];\n\n if (sourceModule.children.indexOf(id) === -1) {\n sourceModule.children.push(id);\n }\n\n if (module) {\n if (module.parents.indexOf(sourceModule.id) === -1) {\n module.parents.push(sourceModule.id);\n }\n\n return module;\n }\n\n return instantiateModule(id, {\n type: SourceType.Parent,\n parentId: sourceModule.id,\n });\n}\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, { type: SourceType.Runtime, chunkPath });\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.\n */\n// @ts-ignore TypeScript doesn't separate this module space from the browser runtime\nfunction getOrInstantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n const module = moduleCache[moduleId];\n if (module) {\n if (module.error) {\n throw module.error;\n }\n return module;\n }\n\n return instantiateRuntimeModule(moduleId, chunkPath);\n}\n\nmodule.exports = {\n getOrInstantiateRuntimeModule,\n loadChunk,\n};\n"],"names":[],"mappings":"AAAA,oDAAoD,GAEpD,mDAAmD;AACnD,+DAA+D;AAC/D,+DAA+D;AAC/D,0DAA0D;AAE1D,IAAA,AAAK,oCAAA;IACH;;;GAGC;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BAAkB,IAAI;QAC3B,IAAI;QACJ,UAAU,aAAa,EAAE;IAC3B;AACF;AAEA;;CAEC,GACD,SAAS,yBACP,QAAkB,EAClB,SAAoB;IAEpB,OAAO,kBAAkB,UAAU;QAAE,IAAI;QAAsB;IAAU;AAC3E;AAEA;;CAEC,GACD,oFAAoF;AACpF,SAAS,8BACP,QAAkB,EAClB,SAAoB;IAEpB,MAAM,UAAS,WAAW,CAAC,SAAS;IACpC,IAAI,SAAQ;QACV,IAAI,QAAO,KAAK,EAAE;YAChB,MAAM,QAAO,KAAK;QACpB;QACA,OAAO;IACT;IAEA,OAAO,yBAAyB,UAAU;AAC5C;AAEA,OAAO,OAAO,GAAG;IACf;IACA;AACF","ignoreList":[0]}}]
{"offset": {"line": 418, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/runtime.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../shared/runtime-utils.ts\" />\n/// <reference path=\"../shared-node/base-externals-utils.ts\" />\n/// <reference path=\"../shared-node/node-externals-utils.ts\" />\n/// <reference path=\"../shared-node/node-wasm-utils.ts\" />\n\nenum SourceType {\n /**\n * The module was instantiated because it was included in an evaluated chunk's\n * runtime.\n */\n Runtime = 0,\n /**\n * The module was instantiated because a parent module imported it.\n */\n Parent = 1,\n}\n\ntype SourceInfo =\n | {\n type: SourceType.Runtime;\n chunkPath: ChunkPath;\n }\n | {\n type: SourceType.Parent;\n parentId: ModuleId;\n };\n\nfunction stringifySourceInfo(source: SourceInfo): string {\n switch (source.type) {\n case SourceType.Runtime:\n return `runtime for chunk ${source.chunkPath}`;\n case SourceType.Parent:\n return `parent module ${source.parentId}`;\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`);\n }\n}\n\ntype ExternalRequire = (\n id: ModuleId,\n thunk: () => any,\n esm?: boolean\n) => Exports | EsmNamespaceObject;\ntype ExternalImport = (id: ModuleId) => Promise<Exports | EsmNamespaceObject>;\n\ninterface TurbopackNodeBuildContext extends TurbopackBaseContext<Module> {\n R: ResolvePathFromModule;\n x: ExternalRequire;\n y: ExternalImport;\n}\n\ntype ModuleFactory = (\n this: Module[\"exports\"],\n context: TurbopackNodeBuildContext\n) => undefined;\n\nconst url = require(\"url\") as typeof import('url');\nconst fs = require(\"fs/promises\") as typeof import('fs/promises');\n\nconst moduleFactories: ModuleFactories = Object.create(null);\nconst moduleCache: ModuleCache<ModuleWithDirection> = Object.create(null);\n\n/**\n * Returns an absolute path to the given module's id.\n */\nfunction createResolvePathFromModule(\n resolver: (moduleId: string) => Exports\n): (moduleId: string) => string {\n return function resolvePathFromModule(moduleId: string): string {\n const exported = resolver(moduleId);\n const exportedPath = exported?.default ?? exported;\n if (typeof exportedPath !== \"string\") {\n return exported as any;\n }\n\n const strippedAssetPrefix = exportedPath.slice(ASSET_PREFIX.length);\n const resolved = path.resolve(\n RUNTIME_ROOT,\n strippedAssetPrefix\n );\n\n return url.pathToFileURL(resolved).href;\n };\n}\n\nfunction loadChunk(chunkData: ChunkData, source?: SourceInfo): void {\n if (typeof chunkData === \"string\") {\n return loadChunkPath(chunkData, source);\n } else {\n return loadChunkPath(chunkData.path, source);\n }\n}\n\nfunction loadChunkPath(chunkPath: ChunkPath, source?: SourceInfo): void {\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return;\n }\n\n try {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath);\n const chunkModules: ModuleFactories = require(resolved);\n\n for (const [moduleId, moduleFactory] of Object.entries(chunkModules)) {\n if (!moduleFactories[moduleId]) {\n moduleFactories[moduleId] = moduleFactory;\n }\n }\n } catch (e) {\n let errorMessage = `Failed to load chunk ${chunkPath}`;\n\n if (source) {\n errorMessage += ` from ${stringifySourceInfo(source)}`;\n }\n\n throw new Error(errorMessage, {\n cause: e,\n });\n }\n}\n\nasync function loadChunkAsync(\n source: SourceInfo,\n chunkData: ChunkData\n): Promise<any> {\n const chunkPath = typeof chunkData === \"string\" ? chunkData : chunkData.path;\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return;\n }\n\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath);\n\n try {\n const contents = await fs.readFile(resolved, \"utf-8\");\n\n const localRequire = (id: string) => {\n let resolvedId = require.resolve(id, {paths: [path.dirname(resolved)]});\n return require(resolvedId);\n }\n const module = {\n exports: {},\n };\n // TODO: Use vm.runInThisContext once our minimal supported Node.js version includes https://github.com/nodejs/node/pull/52153\n // eslint-disable-next-line no-eval -- Can't use vm.runInThisContext due to https://github.com/nodejs/node/issues/52102\n (0, eval)(\n \"(function(module, exports, require, __dirname, __filename) {\" +\n contents +\n \"\\n})\" +\n \"\\n//# sourceURL=\" + url.pathToFileURL(resolved),\n )(module, module.exports, localRequire, path.dirname(resolved), resolved);\n\n const chunkModules: ModuleFactories = module.exports;\n for (const [moduleId, moduleFactory] of Object.entries(chunkModules)) {\n if (!moduleFactories[moduleId]) {\n moduleFactories[moduleId] = moduleFactory;\n }\n }\n } catch (e) {\n let errorMessage = `Failed to load chunk ${chunkPath}`;\n\n if (source) {\n errorMessage += ` from ${stringifySourceInfo(source)}`;\n }\n\n throw new Error(errorMessage, {\n cause: e,\n });\n }\n}\n\nasync function loadChunkAsyncByUrl(source: SourceInfo, chunkUrl: string) {\n const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath;\n return loadChunkAsync(source, path);\n}\n\nfunction loadWebAssembly(chunkPath: ChunkPath, imports: WebAssembly.Imports) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath);\n\n return instantiateWebAssemblyFromPath(resolved, imports);\n}\n\nfunction loadWebAssemblyModule(chunkPath: ChunkPath) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath);\n\n return compileWebAssemblyFromPath(resolved);\n}\n\nfunction getWorkerBlobURL(_chunks: ChunkPath[]): string {\n throw new Error(\"Worker blobs are not implemented yet for Node.js\");\n}\n\nfunction instantiateModule(id: ModuleId, source: SourceInfo): ModuleWithDirection {\n const moduleFactory = moduleFactories[id];\n if (typeof moduleFactory !== \"function\") {\n // This can happen if modules incorrectly handle HMR disposes/updates,\n // e.g. when they keep a `setTimeout` around which still executes old code\n // and contains e.g. a `require(\"something\")` call.\n let instantiationReason;\n switch (source.type) {\n case SourceType.Runtime:\n instantiationReason = `as a runtime entry of chunk ${source.chunkPath}`;\n break;\n case SourceType.Parent:\n instantiationReason = `because it was required from module ${source.parentId}`;\n break;\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`);\n }\n throw new Error(\n `Module ${id} was instantiated ${instantiationReason}, but the module factory is not available. It might have been deleted in an HMR update.`\n );\n }\n\n let parents: ModuleId[];\n switch (source.type) {\n case SourceType.Runtime:\n parents = [];\n break;\n case SourceType.Parent:\n // No need to add this module as a child of the parent module here, this\n // has already been taken care of in `getOrInstantiateModuleFromParent`.\n parents = [source.parentId];\n break;\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`);\n }\n\n const module: ModuleWithDirection = {\n exports: {},\n error: undefined,\n loaded: false,\n id,\n parents,\n children: [],\n namespaceObject: undefined,\n };\n moduleCache[id] = module;\n\n // NOTE(alexkirsz) This can fail when the module encounters a runtime error.\n try {\n const r = commonJsRequire.bind(null, module);\n moduleFactory.call(module.exports, {\n a: asyncModule.bind(null, module),\n e: module.exports,\n r,\n t: runtimeRequire,\n x: externalRequire,\n y: externalImport,\n f: moduleContext,\n i: esmImport.bind(null, module),\n s: esmExport.bind(null, module, module.exports),\n j: dynamicExport.bind(null, module, module.exports),\n v: exportValue.bind(null, module),\n n: exportNamespace.bind(null, module),\n m: module,\n c: moduleCache,\n M: moduleFactories,\n l: loadChunkAsync.bind(null, { type: SourceType.Parent, parentId: id }),\n L: loadChunkAsyncByUrl.bind(null, { type: SourceType.Parent, parentId: id }),\n w: loadWebAssembly,\n u: loadWebAssemblyModule,\n g: globalThis,\n P: resolveAbsolutePath,\n U: relativeURL,\n R: createResolvePathFromModule(r),\n b: getWorkerBlobURL,\n z: requireStub,\n __dirname: typeof module.id === \"string\" ? module.id.replace(/(^|\\/)\\/+$/, \"\") : module.id\n });\n } catch (error) {\n module.error = error as any;\n throw error;\n }\n\n module.loaded = true;\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject);\n }\n\n return module;\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore\nfunction getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: ModuleWithDirection\n): ModuleWithDirection {\n const module = moduleCache[id];\n\n if (sourceModule.children.indexOf(id) === -1) {\n sourceModule.children.push(id);\n }\n\n if (module) {\n if (module.parents.indexOf(sourceModule.id) === -1) {\n module.parents.push(sourceModule.id);\n }\n\n return module;\n }\n\n return instantiateModule(id, {\n type: SourceType.Parent,\n parentId: sourceModule.id,\n });\n}\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, { type: SourceType.Runtime, chunkPath });\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.\n */\n// @ts-ignore TypeScript doesn't separate this module space from the browser runtime\nfunction getOrInstantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n const module = moduleCache[moduleId];\n if (module) {\n if (module.error) {\n throw module.error;\n }\n return module;\n }\n\n return instantiateRuntimeModule(moduleId, chunkPath);\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/;\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath);\n}\n\nmodule.exports = {\n getOrInstantiateRuntimeModule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C,MAAM,UAAS,WAAW,CAAC,GAAG;IAE9B,IAAI,aAAa,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG;QAC5C,aAAa,QAAQ,CAAC,IAAI,CAAC;IAC7B;IAEA,IAAI,SAAQ;QACV,IAAI,QAAO,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,MAAM,CAAC,GAAG;YAClD,QAAO,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE;QACrC;QAEA,OAAO;IACT;IAEA,OAAO,kBAAkB,IAAI;QAC3B,IAAI;QACJ,UAAU,aAAa,EAAE;IAC3B;AACF;AAEA;;CAEC,GACD,SAAS,yBACP,QAAkB,EAClB,SAAoB;IAEpB,OAAO,kBAAkB,UAAU;QAAE,IAAI;QAAsB;IAAU;AAC3E;AAEA;;CAEC,GACD,oFAAoF;AACpF,SAAS,8BACP,QAAkB,EAClB,SAAoB;IAEpB,MAAM,UAAS,WAAW,CAAC,SAAS;IACpC,IAAI,SAAQ;QACV,IAAI,QAAO,KAAK,EAAE;YAChB,MAAM,QAAO,KAAK;QACpB;QACA,OAAO;IACT;IAEA,OAAO,yBAAyB,UAAU;AAC5C;AAEA,MAAM,aAAa;AACnB;;CAEC,GACD,SAAS,KAAK,cAAoC;IAChD,OAAO,WAAW,IAAI,CAAC;AACzB;AAEA,OAAO,OAAO,GAAG;IACf;IACA;AACF","ignoreList":[0]}}]
}
\ No newline at end of file
......@@ -9,6 +9,7 @@ if (!Array.isArray(globalThis.TURBOPACK)) {
}
const CHUNK_BASE_PATH = "";
const CHUNK_SUFFIX_PATH = "";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const RUNTIME_PUBLIC_PATH = "";
/**
......@@ -451,9 +452,9 @@ async function loadChunk(source, chunkData) {
}
return promise;
}
async function loadChunkPath(source, chunkPath) {
async function loadChunkByUrl(source, chunkUrl) {
try {
await BACKEND.loadChunk(chunkPath, source);
await BACKEND.loadChunk(chunkUrl, source);
} catch (error) {
let loadReason;
switch(source.type){
......@@ -469,11 +470,15 @@ async function loadChunkPath(source, chunkPath) {
default:
invariant(source, (source)=>`Unknown source type: ${source?.type}`);
}
throw new Error(`Failed to load chunk ${chunkPath} ${loadReason}${error ? `: ${error}` : ""}`, error ? {
throw new Error(`Failed to load chunk ${chunkUrl} ${loadReason}${error ? `: ${error}` : ""}`, error ? {
cause: error
} : undefined);
}
}
async function loadChunkPath(source, chunkPath) {
const url = getChunkRelativeUrl(chunkPath);
return loadChunkByUrl(source, url);
}
/**
* Returns an absolute url to an asset.
*/ function createResolvePathFromModule(resolver) {
......@@ -541,7 +546,7 @@ function getWorkerBlobURL(chunks) {
/**
* Returns the URL relative to the origin where a chunk can be fetched from.
*/ function getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split("/").map((p)=>encodeURIComponent(p)).join("/")}`;
return `${CHUNK_BASE_PATH}${chunkPath.split("/").map((p)=>encodeURIComponent(p)).join("/")}${CHUNK_SUFFIX_PATH}`;
}
/**
* Marks a chunk list as a runtime chunk list. There can be more than one
......@@ -559,6 +564,18 @@ function registerChunk([chunkPath, chunkModules, runtimeParams]) {
}
return BACKEND.registerChunk(chunkPath, runtimeParams);
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
*/ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath);
}
const regexCssUrl = /\.css(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.
*/ function isCss(chunkUrl) {
return regexCssUrl.test(chunkUrl);
}
/// <reference path="./dev-globals.d.ts" />
/// <reference path="./dev-protocol.d.ts" />
/// <reference path="./dev-extensions.ts" />
......@@ -705,6 +722,7 @@ function instantiateModule(id, source) {
c: devModuleCache,
M: moduleFactories,
l: loadChunk.bind(null, sourceInfo),
L: loadChunkByUrl.bind(null, sourceInfo),
w: loadWebAssembly.bind(null, sourceInfo),
u: loadWebAssemblyModule.bind(null, sourceInfo),
g: globalThis,
......@@ -997,17 +1015,18 @@ function applyChunkListUpdate(update) {
}
if (update.chunks != null) {
for (const [chunkPath, chunkUpdate] of Object.entries(update.chunks)){
const chunkUrl = getChunkRelativeUrl(chunkPath);
switch(chunkUpdate.type){
case "added":
BACKEND.loadChunk(chunkPath, {
BACKEND.loadChunk(chunkUrl, {
type: SourceType.Update
});
break;
case "total":
DEV_BACKEND.reloadChunk?.(chunkPath);
DEV_BACKEND.reloadChunk?.(chunkUrl);
break;
case "deleted":
DEV_BACKEND.unloadChunk?.(chunkPath);
DEV_BACKEND.unloadChunk?.(chunkUrl);
break;
case "partial":
invariant(chunkUpdate.instruction, (instruction)=>`Unknown partial instruction: ${JSON.stringify(instruction)}.`);
......@@ -1325,7 +1344,8 @@ function createModuleHot(moduleId, hotData) {
}
// We must also dispose of the chunk list's chunk itself to ensure it may
// be reloaded properly in the future.
DEV_BACKEND.unloadChunk?.(chunkListPath);
const chunkListUrl = getChunkRelativeUrl(chunkListPath);
DEV_BACKEND.unloadChunk?.(chunkListUrl);
return true;
}
/**
......@@ -1333,9 +1353,10 @@ function createModuleHot(moduleId, hotData) {
*
* @returns Whether the chunk was disposed of.
*/ function disposeChunk(chunkPath) {
const chunkUrl = getChunkRelativeUrl(chunkPath);
// This should happen whether the chunk has any modules in it or not.
// For instance, CSS chunks have no modules in them, but they still need to be unloaded.
DEV_BACKEND.unloadChunk?.(chunkPath);
DEV_BACKEND.unloadChunk?.(chunkUrl);
const chunkModules = chunkModulesMap.get(chunkPath);
if (chunkModules == null) {
return false;
......@@ -1356,26 +1377,27 @@ function createModuleHot(moduleId, hotData) {
/**
* Subscribes to chunk list updates from the update server and applies them.
*/ function registerChunkList(chunkUpdateProvider, chunkList) {
const chunkListPath = chunkList.path;
chunkUpdateProvider.push([
chunkList.path,
handleApply.bind(null, chunkList.path)
chunkListPath,
handleApply.bind(null, chunkListPath)
]);
// Adding chunks to chunk lists and vice versa.
const chunks = new Set(chunkList.chunks.map(getChunkPath));
chunkListChunksMap.set(chunkList.path, chunks);
for (const chunkPath of chunks){
const chunkPaths = new Set(chunkList.chunks.map(getChunkPath));
chunkListChunksMap.set(chunkListPath, chunkPaths);
for (const chunkPath of chunkPaths){
let chunkChunkLists = chunkChunkListsMap.get(chunkPath);
if (!chunkChunkLists) {
chunkChunkLists = new Set([
chunkList.path
chunkListPath
]);
chunkChunkListsMap.set(chunkPath, chunkChunkLists);
} else {
chunkChunkLists.add(chunkList.path);
chunkChunkLists.add(chunkListPath);
}
}
if (chunkList.source === "entry") {
markChunkListAsRuntime(chunkList.path);
markChunkListAsRuntime(chunkListPath);
}
}
globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS ??= [];
......@@ -1419,15 +1441,17 @@ async function loadWebAssemblyModule(_source, wasmChunkPath) {
(()=>{
BACKEND = {
async registerChunk (chunkPath, params) {
const resolver = getOrCreateResolver(chunkPath);
const chunkUrl = getChunkRelativeUrl(chunkPath);
const resolver = getOrCreateResolver(chunkUrl);
resolver.resolve();
if (params == null) {
return;
}
for (const otherChunkData of params.otherChunks){
const otherChunkPath = getChunkPath(otherChunkData);
const otherChunkUrl = getChunkRelativeUrl(otherChunkPath);
// Chunk might have started loading, so we want to avoid triggering another load.
getOrCreateResolver(otherChunkPath);
getOrCreateResolver(otherChunkUrl);
}
// This waits for chunks to be loaded, but also marks included items as available.
await Promise.all(params.otherChunks.map((otherChunkData)=>loadChunk({
......@@ -1440,12 +1464,15 @@ async function loadWebAssemblyModule(_source, wasmChunkPath) {
}
}
},
loadChunk (chunkPath, source) {
return doLoadChunk(chunkPath, source);
/**
* Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded.
*/ loadChunk (chunkUrl, source) {
return doLoadChunk(chunkUrl, source);
}
};
function getOrCreateResolver(chunkPath) {
let resolver = chunkResolvers.get(chunkPath);
function getOrCreateResolver(chunkUrl) {
let resolver = chunkResolvers.get(chunkUrl);
if (!resolver) {
let resolve;
let reject;
......@@ -1462,22 +1489,22 @@ async function loadWebAssemblyModule(_source, wasmChunkPath) {
},
reject: reject
};
chunkResolvers.set(chunkPath, resolver);
chunkResolvers.set(chunkUrl, resolver);
}
return resolver;
}
/**
* Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded.
*/ async function doLoadChunk(chunkPath, source) {
const resolver = getOrCreateResolver(chunkPath);
* Loads the given chunk, and returns a promise that resolves once the chunk
* has been loaded.
*/ function doLoadChunk(chunkUrl, source) {
const resolver = getOrCreateResolver(chunkUrl);
if (resolver.resolved) {
return resolver.promise;
}
if (source.type === SourceType.Runtime) {
// We don't need to load chunks references from runtime code, as they're already
// present in the DOM.
if (chunkPath.endsWith(".css")) {
if (isCss(chunkUrl)) {
// CSS chunks do not register themselves, and as such must be marked as
// loaded instantly.
resolver.resolve();
......@@ -1487,19 +1514,19 @@ async function loadWebAssemblyModule(_source, wasmChunkPath) {
// `resolver.resolve()` in this branch.
return resolver.promise;
}
const chunkUrl = getChunkRelativeUrl(chunkPath);
const decodedChunkUrl = decodeURI(chunkUrl);
if (typeof importScripts === "function") {
// We're in a web worker
if (chunkPath.endsWith(".css")) {
if (isCss(chunkUrl)) {
// ignore
} else if (chunkPath.endsWith(".js")) {
} else if (isJs(chunkUrl)) {
importScripts(TURBOPACK_WORKER_LOCATION + chunkUrl);
} else {
throw new Error(`can't infer type of chunk from path ${chunkPath} in worker`);
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
}
} else {
if (chunkPath.endsWith(".css")) {
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl);
if (isCss(chunkUrl)) {
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`);
if (previousLinks.length > 0) {
// CSS chunks do not register themselves, and as such must be marked as
......@@ -1519,7 +1546,7 @@ async function loadWebAssemblyModule(_source, wasmChunkPath) {
};
document.body.appendChild(link);
}
} else if (chunkPath.endsWith(".js")) {
} else if (isJs(chunkUrl)) {
const previousScripts = document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);
if (previousScripts.length > 0) {
// There is this edge where the script already failed loading, but we
......@@ -1541,7 +1568,7 @@ async function loadWebAssemblyModule(_source, wasmChunkPath) {
document.body.appendChild(script);
}
} else {
throw new Error(`can't infer type of chunk from path ${chunkPath}`);
throw new Error(`can't infer type of chunk from URL ${chunkUrl}`);
}
}
return resolver.promise;
......@@ -1559,17 +1586,16 @@ async function loadWebAssemblyModule(_source, wasmChunkPath) {
let DEV_BACKEND;
(()=>{
DEV_BACKEND = {
unloadChunk (chunkPath) {
deleteResolver(chunkPath);
const chunkUrl = getChunkRelativeUrl(chunkPath);
unloadChunk (chunkUrl) {
deleteResolver(chunkUrl);
// TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
const decodedChunkUrl = decodeURI(chunkUrl);
if (chunkPath.endsWith(".css")) {
if (isCss(chunkUrl)) {
const links = document.querySelectorAll(`link[href="${chunkUrl}"],link[href^="${chunkUrl}?"],link[href="${decodedChunkUrl}"],link[href^="${decodedChunkUrl}?"]`);
for (const link of Array.from(links)){
link.remove();
}
} else if (chunkPath.endsWith(".js")) {
} else if (isJs(chunkUrl)) {
// Unloading a JS chunk would have no effect, as it lives in the JS
// runtime once evaluated.
// However, we still want to remove the script tag from the DOM to keep
......@@ -1579,20 +1605,19 @@ let DEV_BACKEND;
script.remove();
}
} else {
throw new Error(`can't infer type of chunk from path ${chunkPath}`);
throw new Error(`can't infer type of chunk from URL ${chunkUrl}`);
}
},
reloadChunk (chunkPath) {
reloadChunk (chunkUrl) {
return new Promise((resolve, reject)=>{
if (!chunkPath.endsWith(".css")) {
if (!isCss(chunkUrl)) {
reject(new Error("The DOM backend can only reload CSS chunks"));
return;
}
const chunkUrl = getChunkRelativeUrl(chunkPath);
const decodedChunkUrl = decodeURI(chunkUrl);
const previousLinks = document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`);
if (previousLinks.length === 0) {
reject(new Error(`No link element found for chunk ${chunkPath}`));
reject(new Error(`No link element found for chunk ${chunkUrl}`));
return;
}
const link = document.createElement("link");
......@@ -1628,12 +1653,12 @@ let DEV_BACKEND;
},
restart: ()=>self.location.reload()
};
function deleteResolver(chunkPath) {
chunkResolvers.delete(chunkPath);
function deleteResolver(chunkUrl) {
chunkResolvers.delete(chunkUrl);
}
})();
function _eval({ code, url, map }) {
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url)}`;
code += `\n\n//# sourceURL=${encodeURI(location.origin + CHUNK_BASE_PATH + url + CHUNK_SUFFIX_PATH)}`;
if (map) {
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${btoa(// btoa doesn't handle nonlatin characters, so escape them as \x sequences
// See https://stackoverflow.com/a/26603875
......
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