Unverified Commit 539efa8c authored by Sam Poder's avatar Sam Poder Committed by GitHub

[turbopack] Only ship top-level async support in the runtime when needed (#94376)

There's a lot of code in the runtime that enables top-level async
support. We may not always need to ship this. It makes up approximately
10% of the runtime. This PR separates this code into a separate module:
`async-module.ts`. This is included in the runtime based on this
condition:

```rust
!self.module_graph.async_module_info().await?.is_empty()
```

---------
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
parent d6d439c6
...@@ -174,6 +174,13 @@ impl EcmascriptBrowserEvaluateChunk { ...@@ -174,6 +174,13 @@ impl EcmascriptBrowserEvaluateChunk {
let asset_context = turbopack::get_runtime_asset_context(environment); let asset_context = turbopack::get_runtime_asset_context(environment);
let runtime_type = *this.chunking_context.runtime_type().await?; let runtime_type = *this.chunking_context.runtime_type().await?;
// Detect async modules from the whole-app graph in production. In development, the graph
// is per-page. To keep the shared `runtime.js` stable, always include the machinery.
let has_async_modules = if matches!(runtime_type, RuntimeType::Production) {
!this.module_graph.async_module_info().await?.is_empty()
} else {
true
};
match runtime_type { match runtime_type {
RuntimeType::Production | RuntimeType::Development => { RuntimeType::Production | RuntimeType::Development => {
let runtime_code = turbopack_ecmascript_runtime::get_browser_runtime_code( let runtime_code = turbopack_ecmascript_runtime::get_browser_runtime_code(
...@@ -187,6 +194,7 @@ impl EcmascriptBrowserEvaluateChunk { ...@@ -187,6 +194,7 @@ impl EcmascriptBrowserEvaluateChunk {
source_maps, source_maps,
this.chunking_context.chunk_loading_global(), this.chunking_context.chunk_loading_global(),
this.chunking_context.cross_origin(), this.chunking_context.cross_origin(),
has_async_modules,
); );
code.push_code(&*runtime_code.await?); code.push_code(&*runtime_code.await?);
} }
......
/// <reference path="./runtime-types.d.ts" />
/// <reference path="./runtime-utils.ts" />
/**
* Top-level-await / async-module machinery. This is only included in the runtime
* when the module graph actually contains an async module (a module with
* top-level await, or one that transitively depends on one). When no async
* module is present, the chunk items never reference `__turbopack_context__.a`,
* so this whole file can be omitted.
*
* everything below is adapted from webpack
* https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
*/
const turbopackQueues = Symbol('turbopack queues')
const turbopackExports = Symbol('turbopack exports')
const turbopackError = Symbol('turbopack error')
const enum QueueStatus {
Unknown = -1,
Unresolved = 0,
Resolved = 1,
}
type AsyncQueueFn = (() => void) & { queueCount: number }
type AsyncQueue = AsyncQueueFn[] & {
status: QueueStatus
}
type Dep = Exports | AsyncModulePromise | Promise<Exports>
type AsyncModuleExt = {
[turbopackQueues]: (fn: (queue: AsyncQueue) => void) => void
[turbopackExports]: Exports
[turbopackError]?: any
}
type AsyncModulePromise<T = Exports> = Promise<T> & AsyncModuleExt
function isPromise<T = any>(maybePromise: any): maybePromise is Promise<T> {
return (
maybePromise != null &&
typeof maybePromise === 'object' &&
'then' in maybePromise &&
typeof maybePromise.then === 'function'
)
}
function isAsyncModuleExt<T extends {}>(obj: T): obj is AsyncModuleExt & T {
return turbopackQueues in obj
}
function createPromise<T>() {
let resolve: (value: T | PromiseLike<T>) => void
let reject: (reason?: any) => void
const promise = new Promise<T>((res, rej) => {
reject = rej
resolve = res
})
return {
promise,
resolve: resolve!,
reject: reject!,
}
}
function resolveQueue(queue?: AsyncQueue) {
if (queue && queue.status !== QueueStatus.Resolved) {
queue.status = QueueStatus.Resolved
queue.forEach((fn) => fn.queueCount--)
queue.forEach((fn) => (fn.queueCount-- ? fn.queueCount++ : fn()))
}
}
function wrapDeps(deps: Dep[]): AsyncModuleExt[] {
return deps.map((dep): AsyncModuleExt => {
if (dep !== null && typeof dep === 'object') {
if (isAsyncModuleExt(dep)) return dep
if (isPromise(dep)) {
const queue: AsyncQueue = Object.assign([], {
status: QueueStatus.Unresolved,
})
const obj: AsyncModuleExt = {
[turbopackExports]: {},
[turbopackQueues]: (fn: (queue: AsyncQueue) => void) => fn(queue),
}
dep.then(
(res) => {
obj[turbopackExports] = res
resolveQueue(queue)
},
(err) => {
obj[turbopackError] = err
resolveQueue(queue)
}
)
return obj
}
}
return {
[turbopackExports]: dep,
[turbopackQueues]: () => {},
}
})
}
function asyncModule(
this: TurbopackBaseContext<Module>,
body: (
handleAsyncDependencies: (
deps: Dep[]
) => Exports[] | Promise<() => Exports[]>,
asyncResult: (err?: any) => void
) => void,
hasAwait: boolean
) {
const module = this.m
const queue: AsyncQueue | undefined = hasAwait
? Object.assign([], { status: QueueStatus.Unknown })
: undefined
const depQueues: Set<AsyncQueue> = new Set()
const { resolve, reject, promise: rawPromise } = createPromise<Exports>()
const promise: AsyncModulePromise = Object.assign(rawPromise, {
[turbopackExports]: module.exports,
[turbopackQueues]: (fn) => {
queue && fn(queue)
depQueues.forEach(fn)
promise['catch'](() => {})
},
} satisfies AsyncModuleExt)
const attributes: PropertyDescriptor = {
get(): any {
return promise
},
set(v: any) {
// Calling `esmExport` leads to this.
if (v !== promise) {
promise[turbopackExports] = v
}
},
}
Object.defineProperty(module, 'exports', attributes)
Object.defineProperty(module, 'namespaceObject', attributes)
function handleAsyncDependencies(deps: Dep[]) {
const currentDeps = wrapDeps(deps)
const getResult = () =>
currentDeps.map((d) => {
if (d[turbopackError]) throw d[turbopackError]
return d[turbopackExports]
})
const { promise, resolve } = createPromise<() => Exports[]>()
const fn: AsyncQueueFn = Object.assign(() => resolve(getResult), {
queueCount: 0,
})
function fnQueue(q: AsyncQueue) {
if (q !== queue && !depQueues.has(q)) {
depQueues.add(q)
if (q && q.status === QueueStatus.Unresolved) {
fn.queueCount++
q.push(fn)
}
}
}
currentDeps.map((dep) => dep[turbopackQueues](fnQueue))
return fn.queueCount ? promise : getResult()
}
function asyncResult(err?: any) {
if (err) {
reject((promise[turbopackError] = err))
} else {
resolve(promise[turbopackExports])
}
resolveQueue(queue)
}
body(handleAsyncDependencies, asyncResult)
if (queue && queue.status === QueueStatus.Unknown) {
queue.status = QueueStatus.Unresolved
}
}
contextPrototype.a = asyncModule
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-unused-vars */
/// <reference path="./runtime-types.d.ts" /> /// <reference path="./runtime-types.d.ts" />
/// <reference path="./async-module.ts" />
type EsmNamespaceObject = Record<string, any> type EsmNamespaceObject = Record<string, any>
...@@ -508,35 +509,6 @@ function getChunkPath(chunkData: ChunkData): ChunkPath { ...@@ -508,35 +509,6 @@ function getChunkPath(chunkData: ChunkData): ChunkPath {
return typeof chunkData === 'string' ? chunkData : chunkData.path return typeof chunkData === 'string' ? chunkData : chunkData.path
} }
function isPromise<T = any>(maybePromise: any): maybePromise is Promise<T> {
return (
maybePromise != null &&
typeof maybePromise === 'object' &&
'then' in maybePromise &&
typeof maybePromise.then === 'function'
)
}
function isAsyncModuleExt<T extends {}>(obj: T): obj is AsyncModuleExt & T {
return turbopackQueues in obj
}
function createPromise<T>() {
let resolve: (value: T | PromiseLike<T>) => void
let reject: (reason?: any) => void
const promise = new Promise<T>((res, rej) => {
reject = rej
resolve = res
})
return {
promise,
resolve: resolve!,
reject: reject!,
}
}
// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. // Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.
// The CompressedModuleFactories format is // The CompressedModuleFactories format is
// - 1 or more module ids // - 1 or more module ids
...@@ -597,169 +569,6 @@ function installCompressedModuleFactories( ...@@ -597,169 +569,6 @@ function installCompressedModuleFactories(
} }
} }
// everything below is adapted from webpack
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
const turbopackQueues = Symbol('turbopack queues')
const turbopackExports = Symbol('turbopack exports')
const turbopackError = Symbol('turbopack error')
const enum QueueStatus {
Unknown = -1,
Unresolved = 0,
Resolved = 1,
}
type AsyncQueueFn = (() => void) & { queueCount: number }
type AsyncQueue = AsyncQueueFn[] & {
status: QueueStatus
}
function resolveQueue(queue?: AsyncQueue) {
if (queue && queue.status !== QueueStatus.Resolved) {
queue.status = QueueStatus.Resolved
queue.forEach((fn) => fn.queueCount--)
queue.forEach((fn) => (fn.queueCount-- ? fn.queueCount++ : fn()))
}
}
type Dep = Exports | AsyncModulePromise | Promise<Exports>
type AsyncModuleExt = {
[turbopackQueues]: (fn: (queue: AsyncQueue) => void) => void
[turbopackExports]: Exports
[turbopackError]?: any
}
type AsyncModulePromise<T = Exports> = Promise<T> & AsyncModuleExt
function wrapDeps(deps: Dep[]): AsyncModuleExt[] {
return deps.map((dep): AsyncModuleExt => {
if (dep !== null && typeof dep === 'object') {
if (isAsyncModuleExt(dep)) return dep
if (isPromise(dep)) {
const queue: AsyncQueue = Object.assign([], {
status: QueueStatus.Unresolved,
})
const obj: AsyncModuleExt = {
[turbopackExports]: {},
[turbopackQueues]: (fn: (queue: AsyncQueue) => void) => fn(queue),
}
dep.then(
(res) => {
obj[turbopackExports] = res
resolveQueue(queue)
},
(err) => {
obj[turbopackError] = err
resolveQueue(queue)
}
)
return obj
}
}
return {
[turbopackExports]: dep,
[turbopackQueues]: () => {},
}
})
}
function asyncModule(
this: TurbopackBaseContext<Module>,
body: (
handleAsyncDependencies: (
deps: Dep[]
) => Exports[] | Promise<() => Exports[]>,
asyncResult: (err?: any) => void
) => void,
hasAwait: boolean
) {
const module = this.m
const queue: AsyncQueue | undefined = hasAwait
? Object.assign([], { status: QueueStatus.Unknown })
: undefined
const depQueues: Set<AsyncQueue> = new Set()
const { resolve, reject, promise: rawPromise } = createPromise<Exports>()
const promise: AsyncModulePromise = Object.assign(rawPromise, {
[turbopackExports]: module.exports,
[turbopackQueues]: (fn) => {
queue && fn(queue)
depQueues.forEach(fn)
promise['catch'](() => {})
},
} satisfies AsyncModuleExt)
const attributes: PropertyDescriptor = {
get(): any {
return promise
},
set(v: any) {
// Calling `esmExport` leads to this.
if (v !== promise) {
promise[turbopackExports] = v
}
},
}
Object.defineProperty(module, 'exports', attributes)
Object.defineProperty(module, 'namespaceObject', attributes)
function handleAsyncDependencies(deps: Dep[]) {
const currentDeps = wrapDeps(deps)
const getResult = () =>
currentDeps.map((d) => {
if (d[turbopackError]) throw d[turbopackError]
return d[turbopackExports]
})
const { promise, resolve } = createPromise<() => Exports[]>()
const fn: AsyncQueueFn = Object.assign(() => resolve(getResult), {
queueCount: 0,
})
function fnQueue(q: AsyncQueue) {
if (q !== queue && !depQueues.has(q)) {
depQueues.add(q)
if (q && q.status === QueueStatus.Unresolved) {
fn.queueCount++
q.push(fn)
}
}
}
currentDeps.map((dep) => dep[turbopackQueues](fnQueue))
return fn.queueCount ? promise : getResult()
}
function asyncResult(err?: any) {
if (err) {
reject((promise[turbopackError] = err))
} else {
resolve(promise[turbopackExports])
}
resolveQueue(queue)
}
body(handleAsyncDependencies, asyncResult)
if (queue && queue.status === QueueStatus.Unknown) {
queue.status = QueueStatus.Unresolved
}
}
contextPrototype.a = asyncModule
/** /**
* A pseudo "fake" URL object to resolve to its relative path. * A pseudo "fake" URL object to resolve to its relative path.
* *
......
...@@ -27,6 +27,7 @@ pub async fn get_browser_runtime_code( ...@@ -27,6 +27,7 @@ pub async fn get_browser_runtime_code(
generate_source_map: bool, generate_source_map: bool,
chunk_loading_global: Vc<RcStr>, chunk_loading_global: Vc<RcStr>,
cross_origin: Vc<CrossOrigin>, cross_origin: Vc<CrossOrigin>,
has_async_modules: bool,
) -> Result<Vc<Code>> { ) -> Result<Vc<Code>> {
let asset_context = *asset_context; let asset_context = *asset_context;
let environment = asset_context.compile_time_info().environment(); let environment = asset_context.compile_time_info().environment();
...@@ -189,6 +190,17 @@ pub async fn get_browser_runtime_code( ...@@ -189,6 +190,17 @@ pub async fn get_browser_runtime_code(
)?; )?;
code.push_code(&*shared_runtime_utils_code.await?); code.push_code(&*shared_runtime_utils_code.await?);
// Only include the async-module (top-level await) machinery when the app uses it.
if has_async_modules {
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("shared/runtime/async-module.ts"),
generate_source_map,
)
.await?,
);
}
for runtime_code in runtime_base_code { for runtime_code in runtime_base_code {
code.push_code( code.push_code(
&*embed_static_code(asset_context, runtime_code.into(), generate_source_map).await?, &*embed_static_code(asset_context, runtime_code.into(), generate_source_map).await?,
......
...@@ -13,6 +13,7 @@ use crate::{RuntimeType, embed_js::embed_static_code}; ...@@ -13,6 +13,7 @@ use crate::{RuntimeType, embed_js::embed_static_code};
pub async fn get_nodejs_runtime_code( pub async fn get_nodejs_runtime_code(
asset_context: ResolvedVc<Box<dyn AssetContext>>, asset_context: ResolvedVc<Box<dyn AssetContext>>,
runtime_type: RuntimeType, runtime_type: RuntimeType,
has_async_modules: bool,
generate_source_map: bool, generate_source_map: bool,
) -> Result<Vc<Code>> { ) -> Result<Vc<Code>> {
let asset_context = *asset_context; let asset_context = *asset_context;
...@@ -47,6 +48,17 @@ pub async fn get_nodejs_runtime_code( ...@@ -47,6 +48,17 @@ pub async fn get_nodejs_runtime_code(
let mut code = CodeBuilder::default(); let mut code = CodeBuilder::default();
code.push_code(&*shared_runtime_utils_code.await?); code.push_code(&*shared_runtime_utils_code.await?);
// Only include the async-module (top-level await) machinery when the app uses it.
if has_async_modules {
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("shared/runtime/async-module.ts"),
generate_source_map,
)
.await?,
);
}
code.push_code(&*shared_base_external_utils_code.await?); code.push_code(&*shared_base_external_utils_code.await?);
code.push_code(&*shared_node_external_utils_code.await?); code.push_code(&*shared_node_external_utils_code.await?);
code.push_code(&*shared_node_wasm_utils_code.await?); code.push_code(&*shared_node_wasm_utils_code.await?);
......
...@@ -16,6 +16,7 @@ use turbopack_core::{ ...@@ -16,6 +16,7 @@ use turbopack_core::{
source_map::{GenerateSourceMap, SourceMapAsset}, source_map::{GenerateSourceMap, SourceMapAsset},
}; };
use turbopack_ecmascript::{chunk::EcmascriptChunkPlaceable, utils::StringifyJs}; use turbopack_ecmascript::{chunk::EcmascriptChunkPlaceable, utils::StringifyJs};
use turbopack_ecmascript_runtime::RuntimeType;
use super::runtime::EcmascriptBuildNodeRuntimeChunk; use super::runtime::EcmascriptBuildNodeRuntimeChunk;
use crate::NodeJsChunkingContext; use crate::NodeJsChunkingContext;
...@@ -149,8 +150,21 @@ impl EcmascriptBuildNodeEntryChunk { ...@@ -149,8 +150,21 @@ impl EcmascriptBuildNodeEntryChunk {
} }
#[turbo_tasks::function] #[turbo_tasks::function]
fn runtime_chunk(&self) -> Vc<EcmascriptBuildNodeRuntimeChunk> { async fn runtime_chunk(&self) -> Result<Vc<EcmascriptBuildNodeRuntimeChunk>> {
EcmascriptBuildNodeRuntimeChunk::new(*self.chunking_context) // Detect async modules from the whole-app graph in production. In development, the graph
// is per-page. To keep the shared `runtime.js` stable, always include the machinery.
let has_async_modules = if matches!(
*self.chunking_context.runtime_type().await?,
RuntimeType::Production
) {
!self.module_graph.async_module_info().await?.is_empty()
} else {
true
};
Ok(EcmascriptBuildNodeRuntimeChunk::new(
*self.chunking_context,
has_async_modules,
))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
......
...@@ -24,14 +24,22 @@ use crate::NodeJsChunkingContext; ...@@ -24,14 +24,22 @@ use crate::NodeJsChunkingContext;
#[value_to_string("Ecmascript Build Node Runtime Chunk")] #[value_to_string("Ecmascript Build Node Runtime Chunk")]
pub(crate) struct EcmascriptBuildNodeRuntimeChunk { pub(crate) struct EcmascriptBuildNodeRuntimeChunk {
chunking_context: ResolvedVc<NodeJsChunkingContext>, chunking_context: ResolvedVc<NodeJsChunkingContext>,
has_async_modules: bool,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl EcmascriptBuildNodeRuntimeChunk { impl EcmascriptBuildNodeRuntimeChunk {
/// Creates a new [`Vc<EcmascriptBuildNodeRuntimeChunk>`]. /// Creates a new [`Vc<EcmascriptBuildNodeRuntimeChunk>`].
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new(chunking_context: ResolvedVc<NodeJsChunkingContext>) -> Vc<Self> { pub fn new(
EcmascriptBuildNodeRuntimeChunk { chunking_context }.cell() chunking_context: ResolvedVc<NodeJsChunkingContext>,
has_async_modules: bool,
) -> Vc<Self> {
EcmascriptBuildNodeRuntimeChunk {
chunking_context,
has_async_modules,
}
.cell()
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -105,6 +113,7 @@ impl EcmascriptBuildNodeRuntimeChunk { ...@@ -105,6 +113,7 @@ impl EcmascriptBuildNodeRuntimeChunk {
let runtime_code = turbopack_ecmascript_runtime::get_nodejs_runtime_code( let runtime_code = turbopack_ecmascript_runtime::get_nodejs_runtime_code(
asset_context, asset_context,
RuntimeType::Development, RuntimeType::Development,
this.has_async_modules,
generate_source_map, generate_source_map,
); );
code.push_code(&*runtime_code.await?); code.push_code(&*runtime_code.await?);
...@@ -113,6 +122,7 @@ impl EcmascriptBuildNodeRuntimeChunk { ...@@ -113,6 +122,7 @@ impl EcmascriptBuildNodeRuntimeChunk {
let runtime_code = turbopack_ecmascript_runtime::get_nodejs_runtime_code( let runtime_code = turbopack_ecmascript_runtime::get_nodejs_runtime_code(
asset_context, asset_context,
RuntimeType::Production, RuntimeType::Production,
this.has_async_modules,
generate_source_map, generate_source_map,
); );
code.push_code(&*runtime_code.await?); code.push_code(&*runtime_code.await?);
......
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="c62d338f-1706-8257-26fe-07dd3a11b4a5")}catch(e){}}(); ;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="85ec7745-dee3-171d-a84e-b72344bb90d4")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1i9t_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js", "output/1i9t_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js",
{"otherChunks":["output/1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvs.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvs.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
...@@ -21,6 +21,7 @@ var WORKER_FORWARDED_GLOBALS = []; ...@@ -21,6 +21,7 @@ var WORKER_FORWARDED_GLOBALS = [];
* *
* It will be prepended to the runtime code of each runtime. * It will be prepended to the runtime code of each runtime.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" />
/// <reference path="./async-module.ts" />
/** /**
* Describes why a module was instantiated. * Describes why a module was instantiated.
* Shared between browser and Node.js runtimes. * Shared between browser and Node.js runtimes.
...@@ -356,25 +357,6 @@ contextPrototype.f = moduleContext; ...@@ -356,25 +357,6 @@ contextPrototype.f = moduleContext;
*/ function getChunkPath(chunkData) { */ function getChunkPath(chunkData) {
return typeof chunkData === 'string' ? chunkData : chunkData.path; return typeof chunkData === 'string' ? chunkData : chunkData.path;
} }
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. // Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.
// The CompressedModuleFactories format is // The CompressedModuleFactories format is
// - 1 or more module ids // - 1 or more module ids
...@@ -424,11 +406,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories, ...@@ -424,11 +406,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories,
i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array. i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array.
} }
} }
// everything below is adapted from webpack /**
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13 * A pseudo "fake" URL object to resolve to its relative path.
const turbopackQueues = Symbol('turbopack queues'); *
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/// <reference path="./runtime-types.d.ts" />
/// <reference path="./runtime-utils.ts" />
/**
* Top-level-await / async-module machinery. This is only included in the runtime
* when the module graph actually contains an async module (a module with
* top-level await, or one that transitively depends on one). When no async
* module is present, the chunk items never reference `__turbopack_context__.a`,
* so this whole file can be omitted.
*
* everything below is adapted from webpack
* https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
*/ const turbopackQueues = Symbol('turbopack queues');
const turbopackExports = Symbol('turbopack exports'); const turbopackExports = Symbol('turbopack exports');
const turbopackError = Symbol('turbopack error'); const turbopackError = Symbol('turbopack error');
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
function resolveQueue(queue) { function resolveQueue(queue) {
if (queue && queue.status !== 1) { if (queue && queue.status !== 1) {
queue.status = 1; queue.status = 1;
...@@ -528,69 +601,6 @@ function asyncModule(body, hasAwait) { ...@@ -528,69 +601,6 @@ function asyncModule(body, hasAwait) {
} }
} }
contextPrototype.a = asyncModule; contextPrototype.a = asyncModule;
/**
* A pseudo "fake" URL object to resolve to its relative path.
*
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* Turbopack *browser* ECMAScript runtimes. * Turbopack *browser* ECMAScript runtimes.
...@@ -2262,5 +2272,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2262,5 +2272,5 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# debugId=c62d338f-1706-8257-26fe-07dd3a11b4a5 //# debugId=85ec7745-dee3-171d-a84e-b72344bb90d4
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js.map //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_19boa0e.js.map
\ No newline at end of file
...@@ -8,6 +8,7 @@ var WORKER_FORWARDED_GLOBALS = []; ...@@ -8,6 +8,7 @@ var WORKER_FORWARDED_GLOBALS = [];
* *
* It will be prepended to the runtime code of each runtime. * It will be prepended to the runtime code of each runtime.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" />
/// <reference path="./async-module.ts" />
/** /**
* Describes why a module was instantiated. * Describes why a module was instantiated.
* Shared between browser and Node.js runtimes. * Shared between browser and Node.js runtimes.
...@@ -343,25 +344,6 @@ contextPrototype.f = moduleContext; ...@@ -343,25 +344,6 @@ contextPrototype.f = moduleContext;
*/ function getChunkPath(chunkData) { */ function getChunkPath(chunkData) {
return typeof chunkData === 'string' ? chunkData : chunkData.path; return typeof chunkData === 'string' ? chunkData : chunkData.path;
} }
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. // Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.
// The CompressedModuleFactories format is // The CompressedModuleFactories format is
// - 1 or more module ids // - 1 or more module ids
...@@ -411,11 +393,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories, ...@@ -411,11 +393,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories,
i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array. i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array.
} }
} }
// everything below is adapted from webpack /**
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13 * A pseudo "fake" URL object to resolve to its relative path.
const turbopackQueues = Symbol('turbopack queues'); *
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/// <reference path="./runtime-types.d.ts" />
/// <reference path="./runtime-utils.ts" />
/**
* Top-level-await / async-module machinery. This is only included in the runtime
* when the module graph actually contains an async module (a module with
* top-level await, or one that transitively depends on one). When no async
* module is present, the chunk items never reference `__turbopack_context__.a`,
* so this whole file can be omitted.
*
* everything below is adapted from webpack
* https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
*/ const turbopackQueues = Symbol('turbopack queues');
const turbopackExports = Symbol('turbopack exports'); const turbopackExports = Symbol('turbopack exports');
const turbopackError = Symbol('turbopack error'); const turbopackError = Symbol('turbopack error');
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
function resolveQueue(queue) { function resolveQueue(queue) {
if (queue && queue.status !== 1) { if (queue && queue.status !== 1) {
queue.status = 1; queue.status = 1;
...@@ -515,69 +588,6 @@ function asyncModule(body, hasAwait) { ...@@ -515,69 +588,6 @@ function asyncModule(body, hasAwait) {
} }
} }
contextPrototype.a = asyncModule; contextPrototype.a = asyncModule;
/**
* A pseudo "fake" URL object to resolve to its relative path.
*
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/// <reference path="../shared/runtime/runtime-utils.ts" /> /// <reference path="../shared/runtime/runtime-utils.ts" />
/// A 'base' utilities to support runtime can have externals. /// A 'base' utilities to support runtime can have externals.
/// Currently this is for node.js / edge runtime both. /// Currently this is for node.js / edge runtime both.
......
...@@ -8,6 +8,7 @@ var WORKER_FORWARDED_GLOBALS = []; ...@@ -8,6 +8,7 @@ var WORKER_FORWARDED_GLOBALS = [];
* *
* It will be prepended to the runtime code of each runtime. * It will be prepended to the runtime code of each runtime.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" />
/// <reference path="./async-module.ts" />
/** /**
* Describes why a module was instantiated. * Describes why a module was instantiated.
* Shared between browser and Node.js runtimes. * Shared between browser and Node.js runtimes.
...@@ -343,25 +344,6 @@ contextPrototype.f = moduleContext; ...@@ -343,25 +344,6 @@ contextPrototype.f = moduleContext;
*/ function getChunkPath(chunkData) { */ function getChunkPath(chunkData) {
return typeof chunkData === 'string' ? chunkData : chunkData.path; return typeof chunkData === 'string' ? chunkData : chunkData.path;
} }
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. // Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.
// The CompressedModuleFactories format is // The CompressedModuleFactories format is
// - 1 or more module ids // - 1 or more module ids
...@@ -411,110 +393,6 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories, ...@@ -411,110 +393,6 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories,
i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array. i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array.
} }
} }
// everything below is adapted from webpack
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
const turbopackQueues = Symbol('turbopack queues');
const turbopackExports = Symbol('turbopack exports');
const turbopackError = Symbol('turbopack error');
function resolveQueue(queue) {
if (queue && queue.status !== 1) {
queue.status = 1;
queue.forEach((fn)=>fn.queueCount--);
queue.forEach((fn)=>fn.queueCount-- ? fn.queueCount++ : fn());
}
}
function wrapDeps(deps) {
return deps.map((dep)=>{
if (dep !== null && typeof dep === 'object') {
if (isAsyncModuleExt(dep)) return dep;
if (isPromise(dep)) {
const queue = Object.assign([], {
status: 0
});
const obj = {
[turbopackExports]: {},
[turbopackQueues]: (fn)=>fn(queue)
};
dep.then((res)=>{
obj[turbopackExports] = res;
resolveQueue(queue);
}, (err)=>{
obj[turbopackError] = err;
resolveQueue(queue);
});
return obj;
}
}
return {
[turbopackExports]: dep,
[turbopackQueues]: ()=>{}
};
});
}
function asyncModule(body, hasAwait) {
const module = this.m;
const queue = hasAwait ? Object.assign([], {
status: -1
}) : undefined;
const depQueues = new Set();
const { resolve, reject, promise: rawPromise } = createPromise();
const promise = Object.assign(rawPromise, {
[turbopackExports]: module.exports,
[turbopackQueues]: (fn)=>{
queue && fn(queue);
depQueues.forEach(fn);
promise['catch'](()=>{});
}
});
const attributes = {
get () {
return promise;
},
set (v) {
// Calling `esmExport` leads to this.
if (v !== promise) {
promise[turbopackExports] = v;
}
}
};
Object.defineProperty(module, 'exports', attributes);
Object.defineProperty(module, 'namespaceObject', attributes);
function handleAsyncDependencies(deps) {
const currentDeps = wrapDeps(deps);
const getResult = ()=>currentDeps.map((d)=>{
if (d[turbopackError]) throw d[turbopackError];
return d[turbopackExports];
});
const { promise, resolve } = createPromise();
const fn = Object.assign(()=>resolve(getResult), {
queueCount: 0
});
function fnQueue(q) {
if (q !== queue && !depQueues.has(q)) {
depQueues.add(q);
if (q && q.status === 0) {
fn.queueCount++;
q.push(fn);
}
}
}
currentDeps.map((dep)=>dep[turbopackQueues](fnQueue));
return fn.queueCount ? promise : getResult();
}
function asyncResult(err) {
if (err) {
reject(promise[turbopackError] = err);
} else {
resolve(promise[turbopackExports]);
}
resolveQueue(queue);
}
body(handleAsyncDependencies, asyncResult);
if (queue && queue.status === -1) {
queue.status = 0;
}
}
contextPrototype.a = asyncModule;
/** /**
* A pseudo "fake" URL object to resolve to its relative path. * A pseudo "fake" URL object to resolve to its relative path.
* *
......
...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = []; ...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = [];
* *
* It will be prepended to the runtime code of each runtime. * It will be prepended to the runtime code of each runtime.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" />
/// <reference path="./async-module.ts" />
/** /**
* Describes why a module was instantiated. * Describes why a module was instantiated.
* Shared between browser and Node.js runtimes. * Shared between browser and Node.js runtimes.
...@@ -355,25 +356,6 @@ contextPrototype.f = moduleContext; ...@@ -355,25 +356,6 @@ contextPrototype.f = moduleContext;
*/ function getChunkPath(chunkData) { */ function getChunkPath(chunkData) {
return typeof chunkData === 'string' ? chunkData : chunkData.path; return typeof chunkData === 'string' ? chunkData : chunkData.path;
} }
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. // Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.
// The CompressedModuleFactories format is // The CompressedModuleFactories format is
// - 1 or more module ids // - 1 or more module ids
...@@ -423,11 +405,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories, ...@@ -423,11 +405,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories,
i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array. i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array.
} }
} }
// everything below is adapted from webpack /**
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13 * A pseudo "fake" URL object to resolve to its relative path.
const turbopackQueues = Symbol('turbopack queues'); *
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/// <reference path="./runtime-types.d.ts" />
/// <reference path="./runtime-utils.ts" />
/**
* Top-level-await / async-module machinery. This is only included in the runtime
* when the module graph actually contains an async module (a module with
* top-level await, or one that transitively depends on one). When no async
* module is present, the chunk items never reference `__turbopack_context__.a`,
* so this whole file can be omitted.
*
* everything below is adapted from webpack
* https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
*/ const turbopackQueues = Symbol('turbopack queues');
const turbopackExports = Symbol('turbopack exports'); const turbopackExports = Symbol('turbopack exports');
const turbopackError = Symbol('turbopack error'); const turbopackError = Symbol('turbopack error');
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
function resolveQueue(queue) { function resolveQueue(queue) {
if (queue && queue.status !== 1) { if (queue && queue.status !== 1) {
queue.status = 1; queue.status = 1;
...@@ -527,69 +600,6 @@ function asyncModule(body, hasAwait) { ...@@ -527,69 +600,6 @@ function asyncModule(body, hasAwait) {
} }
} }
contextPrototype.a = asyncModule; contextPrototype.a = asyncModule;
/**
* A pseudo "fake" URL object to resolve to its relative path.
*
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* Turbopack *browser* ECMAScript runtimes. * Turbopack *browser* ECMAScript runtimes.
......
...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = []; ...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = [];
* *
* It will be prepended to the runtime code of each runtime. * It will be prepended to the runtime code of each runtime.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" />
/// <reference path="./async-module.ts" />
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try { try {
var info = gen[key](arg); var info = gen[key](arg);
...@@ -49,19 +50,6 @@ function _async_to_generator(fn) { ...@@ -49,19 +50,6 @@ function _async_to_generator(fn) {
}); });
}; };
} }
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _type_of(obj) { function _type_of(obj) {
"@swc/helpers - typeof"; "@swc/helpers - typeof";
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
...@@ -592,25 +580,6 @@ contextPrototype.f = moduleContext; ...@@ -592,25 +580,6 @@ contextPrototype.f = moduleContext;
*/ function getChunkPath(chunkData) { */ function getChunkPath(chunkData) {
return typeof chunkData === 'string' ? chunkData : chunkData.path; return typeof chunkData === 'string' ? chunkData : chunkData.path;
} }
function isPromise(maybePromise) {
return maybePromise != null && (typeof maybePromise === "undefined" ? "undefined" : _type_of(maybePromise)) === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
var resolve;
var reject;
var promise = new Promise(function(res, rej) {
reject = rej;
resolve = res;
});
return {
promise: promise,
resolve: resolve,
reject: reject
};
}
// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. // Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.
// The CompressedModuleFactories format is // The CompressedModuleFactories format is
// - 1 or more module ids // - 1 or more module ids
...@@ -660,116 +629,6 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories, ...@@ -660,116 +629,6 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories,
i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array. i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array.
} }
} }
// everything below is adapted from webpack
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
var turbopackQueues = Symbol('turbopack queues');
var turbopackExports = Symbol('turbopack exports');
var turbopackError = Symbol('turbopack error');
function resolveQueue(queue) {
if (queue && queue.status !== 1) {
queue.status = 1;
queue.forEach(function(fn) {
return fn.queueCount--;
});
queue.forEach(function(fn) {
return fn.queueCount-- ? fn.queueCount++ : fn();
});
}
}
function wrapDeps(deps) {
return deps.map(function(dep) {
if (dep !== null && (typeof dep === "undefined" ? "undefined" : _type_of(dep)) === 'object') {
if (isAsyncModuleExt(dep)) return dep;
if (isPromise(dep)) {
var queue = Object.assign([], {
status: 0
});
var _obj;
var obj = (_obj = {}, _define_property(_obj, turbopackExports, {}), _define_property(_obj, turbopackQueues, function(fn) {
return fn(queue);
}), _obj);
dep.then(function(res) {
obj[turbopackExports] = res;
resolveQueue(queue);
}, function(err) {
obj[turbopackError] = err;
resolveQueue(queue);
});
return obj;
}
}
var _obj1;
return _obj1 = {}, _define_property(_obj1, turbopackExports, dep), _define_property(_obj1, turbopackQueues, function() {}), _obj1;
});
}
function asyncModule(body, hasAwait) {
var module = this.m;
var queue = hasAwait ? Object.assign([], {
status: -1
}) : undefined;
var depQueues = new Set();
var _createPromise = createPromise(), resolve = _createPromise.resolve, reject = _createPromise.reject, rawPromise = _createPromise.promise;
var _obj;
var promise = Object.assign(rawPromise, (_obj = {}, _define_property(_obj, turbopackExports, module.exports), _define_property(_obj, turbopackQueues, function(fn) {
queue && fn(queue);
depQueues.forEach(fn);
promise['catch'](function() {});
}), _obj));
var attributes = {
get: function get() {
return promise;
},
set: function set(v) {
// Calling `esmExport` leads to this.
if (v !== promise) {
promise[turbopackExports] = v;
}
}
};
Object.defineProperty(module, 'exports', attributes);
Object.defineProperty(module, 'namespaceObject', attributes);
function handleAsyncDependencies(deps) {
var currentDeps = wrapDeps(deps);
var getResult = function getResult() {
return currentDeps.map(function(d) {
if (d[turbopackError]) throw d[turbopackError];
return d[turbopackExports];
});
};
var _createPromise = createPromise(), promise = _createPromise.promise, resolve = _createPromise.resolve;
var fn = Object.assign(function() {
return resolve(getResult);
}, {
queueCount: 0
});
function fnQueue(q) {
if (q !== queue && !depQueues.has(q)) {
depQueues.add(q);
if (q && q.status === 0) {
fn.queueCount++;
q.push(fn);
}
}
}
currentDeps.map(function(dep) {
return dep[turbopackQueues](fnQueue);
});
return fn.queueCount ? promise : getResult();
}
function asyncResult(err) {
if (err) {
reject(promise[turbopackError] = err);
} else {
resolve(promise[turbopackExports]);
}
resolveQueue(queue);
}
body(handleAsyncDependencies, asyncResult);
if (queue && queue.status === -1) {
queue.status = 0;
}
}
contextPrototype.a = asyncModule;
/** /**
* A pseudo "fake" URL object to resolve to its relative path. * A pseudo "fake" URL object to resolve to its relative path.
* *
......
...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = []; ...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = [];
* *
* It will be prepended to the runtime code of each runtime. * It will be prepended to the runtime code of each runtime.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" />
/// <reference path="./async-module.ts" />
/** /**
* Describes why a module was instantiated. * Describes why a module was instantiated.
* Shared between browser and Node.js runtimes. * Shared between browser and Node.js runtimes.
...@@ -355,25 +356,6 @@ contextPrototype.f = moduleContext; ...@@ -355,25 +356,6 @@ contextPrototype.f = moduleContext;
*/ function getChunkPath(chunkData) { */ function getChunkPath(chunkData) {
return typeof chunkData === 'string' ? chunkData : chunkData.path; return typeof chunkData === 'string' ? chunkData : chunkData.path;
} }
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. // Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.
// The CompressedModuleFactories format is // The CompressedModuleFactories format is
// - 1 or more module ids // - 1 or more module ids
...@@ -423,11 +405,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories, ...@@ -423,11 +405,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories,
i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array. i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array.
} }
} }
// everything below is adapted from webpack /**
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13 * A pseudo "fake" URL object to resolve to its relative path.
const turbopackQueues = Symbol('turbopack queues'); *
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/// <reference path="./runtime-types.d.ts" />
/// <reference path="./runtime-utils.ts" />
/**
* Top-level-await / async-module machinery. This is only included in the runtime
* when the module graph actually contains an async module (a module with
* top-level await, or one that transitively depends on one). When no async
* module is present, the chunk items never reference `__turbopack_context__.a`,
* so this whole file can be omitted.
*
* everything below is adapted from webpack
* https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
*/ const turbopackQueues = Symbol('turbopack queues');
const turbopackExports = Symbol('turbopack exports'); const turbopackExports = Symbol('turbopack exports');
const turbopackError = Symbol('turbopack error'); const turbopackError = Symbol('turbopack error');
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
function resolveQueue(queue) { function resolveQueue(queue) {
if (queue && queue.status !== 1) { if (queue && queue.status !== 1) {
queue.status = 1; queue.status = 1;
...@@ -527,69 +600,6 @@ function asyncModule(body, hasAwait) { ...@@ -527,69 +600,6 @@ function asyncModule(body, hasAwait) {
} }
} }
contextPrototype.a = asyncModule; contextPrototype.a = asyncModule;
/**
* A pseudo "fake" URL object to resolve to its relative path.
*
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* Turbopack *browser* ECMAScript runtimes. * Turbopack *browser* ECMAScript runtimes.
......
...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = []; ...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = [];
* *
* It will be prepended to the runtime code of each runtime. * It will be prepended to the runtime code of each runtime.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" />
/// <reference path="./async-module.ts" />
/** /**
* Describes why a module was instantiated. * Describes why a module was instantiated.
* Shared between browser and Node.js runtimes. * Shared between browser and Node.js runtimes.
...@@ -355,25 +356,6 @@ contextPrototype.f = moduleContext; ...@@ -355,25 +356,6 @@ contextPrototype.f = moduleContext;
*/ function getChunkPath(chunkData) { */ function getChunkPath(chunkData) {
return typeof chunkData === 'string' ? chunkData : chunkData.path; return typeof chunkData === 'string' ? chunkData : chunkData.path;
} }
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. // Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.
// The CompressedModuleFactories format is // The CompressedModuleFactories format is
// - 1 or more module ids // - 1 or more module ids
...@@ -423,11 +405,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories, ...@@ -423,11 +405,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories,
i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array. i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array.
} }
} }
// everything below is adapted from webpack /**
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13 * A pseudo "fake" URL object to resolve to its relative path.
const turbopackQueues = Symbol('turbopack queues'); *
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/// <reference path="./runtime-types.d.ts" />
/// <reference path="./runtime-utils.ts" />
/**
* Top-level-await / async-module machinery. This is only included in the runtime
* when the module graph actually contains an async module (a module with
* top-level await, or one that transitively depends on one). When no async
* module is present, the chunk items never reference `__turbopack_context__.a`,
* so this whole file can be omitted.
*
* everything below is adapted from webpack
* https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
*/ const turbopackQueues = Symbol('turbopack queues');
const turbopackExports = Symbol('turbopack exports'); const turbopackExports = Symbol('turbopack exports');
const turbopackError = Symbol('turbopack error'); const turbopackError = Symbol('turbopack error');
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
function resolveQueue(queue) { function resolveQueue(queue) {
if (queue && queue.status !== 1) { if (queue && queue.status !== 1) {
queue.status = 1; queue.status = 1;
...@@ -527,69 +600,6 @@ function asyncModule(body, hasAwait) { ...@@ -527,69 +600,6 @@ function asyncModule(body, hasAwait) {
} }
} }
contextPrototype.a = asyncModule; contextPrototype.a = asyncModule;
/**
* A pseudo "fake" URL object to resolve to its relative path.
*
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* Turbopack *browser* ECMAScript runtimes. * Turbopack *browser* ECMAScript runtimes.
......
...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = []; ...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = [];
* *
* It will be prepended to the runtime code of each runtime. * It will be prepended to the runtime code of each runtime.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" />
/// <reference path="./async-module.ts" />
/** /**
* Describes why a module was instantiated. * Describes why a module was instantiated.
* Shared between browser and Node.js runtimes. * Shared between browser and Node.js runtimes.
...@@ -355,25 +356,6 @@ contextPrototype.f = moduleContext; ...@@ -355,25 +356,6 @@ contextPrototype.f = moduleContext;
*/ function getChunkPath(chunkData) { */ function getChunkPath(chunkData) {
return typeof chunkData === 'string' ? chunkData : chunkData.path; return typeof chunkData === 'string' ? chunkData : chunkData.path;
} }
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. // Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.
// The CompressedModuleFactories format is // The CompressedModuleFactories format is
// - 1 or more module ids // - 1 or more module ids
...@@ -423,11 +405,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories, ...@@ -423,11 +405,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories,
i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array. i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array.
} }
} }
// everything below is adapted from webpack /**
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13 * A pseudo "fake" URL object to resolve to its relative path.
const turbopackQueues = Symbol('turbopack queues'); *
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/// <reference path="./runtime-types.d.ts" />
/// <reference path="./runtime-utils.ts" />
/**
* Top-level-await / async-module machinery. This is only included in the runtime
* when the module graph actually contains an async module (a module with
* top-level await, or one that transitively depends on one). When no async
* module is present, the chunk items never reference `__turbopack_context__.a`,
* so this whole file can be omitted.
*
* everything below is adapted from webpack
* https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
*/ const turbopackQueues = Symbol('turbopack queues');
const turbopackExports = Symbol('turbopack exports'); const turbopackExports = Symbol('turbopack exports');
const turbopackError = Symbol('turbopack error'); const turbopackError = Symbol('turbopack error');
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
function resolveQueue(queue) { function resolveQueue(queue) {
if (queue && queue.status !== 1) { if (queue && queue.status !== 1) {
queue.status = 1; queue.status = 1;
...@@ -527,69 +600,6 @@ function asyncModule(body, hasAwait) { ...@@ -527,69 +600,6 @@ function asyncModule(body, hasAwait) {
} }
} }
contextPrototype.a = asyncModule; contextPrototype.a = asyncModule;
/**
* A pseudo "fake" URL object to resolve to its relative path.
*
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* Turbopack *browser* ECMAScript runtimes. * Turbopack *browser* ECMAScript runtimes.
......
...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = []; ...@@ -20,6 +20,7 @@ var WORKER_FORWARDED_GLOBALS = [];
* *
* It will be prepended to the runtime code of each runtime. * It will be prepended to the runtime code of each runtime.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-types.d.ts" />
/// <reference path="./async-module.ts" />
/** /**
* Describes why a module was instantiated. * Describes why a module was instantiated.
* Shared between browser and Node.js runtimes. * Shared between browser and Node.js runtimes.
...@@ -355,25 +356,6 @@ contextPrototype.f = moduleContext; ...@@ -355,25 +356,6 @@ contextPrototype.f = moduleContext;
*/ function getChunkPath(chunkData) { */ function getChunkPath(chunkData) {
return typeof chunkData === 'string' ? chunkData : chunkData.path; return typeof chunkData === 'string' ? chunkData : chunkData.path;
} }
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. // Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.
// The CompressedModuleFactories format is // The CompressedModuleFactories format is
// - 1 or more module ids // - 1 or more module ids
...@@ -423,11 +405,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories, ...@@ -423,11 +405,102 @@ function installCompressedModuleFactories(chunkModules, offset, moduleFactories,
i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array. i = end + 1; // end is pointing at the last factory advance to the next id or the end of the array.
} }
} }
// everything below is adapted from webpack /**
// https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13 * A pseudo "fake" URL object to resolve to its relative path.
const turbopackQueues = Symbol('turbopack queues'); *
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/// <reference path="./runtime-types.d.ts" />
/// <reference path="./runtime-utils.ts" />
/**
* Top-level-await / async-module machinery. This is only included in the runtime
* when the module graph actually contains an async module (a module with
* top-level await, or one that transitively depends on one). When no async
* module is present, the chunk items never reference `__turbopack_context__.a`,
* so this whole file can be omitted.
*
* everything below is adapted from webpack
* https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13
*/ const turbopackQueues = Symbol('turbopack queues');
const turbopackExports = Symbol('turbopack exports'); const turbopackExports = Symbol('turbopack exports');
const turbopackError = Symbol('turbopack error'); const turbopackError = Symbol('turbopack error');
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
}
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
}
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
}
function resolveQueue(queue) { function resolveQueue(queue) {
if (queue && queue.status !== 1) { if (queue && queue.status !== 1) {
queue.status = 1; queue.status = 1;
...@@ -527,69 +600,6 @@ function asyncModule(body, hasAwait) { ...@@ -527,69 +600,6 @@ function asyncModule(body, hasAwait) {
} }
} }
contextPrototype.a = asyncModule; contextPrototype.a = asyncModule;
/**
* A pseudo "fake" URL object to resolve to its relative path.
*
* When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
* runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
* hydration mismatch.
*
* This is based on webpack's existing implementation:
* https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js
*/ const relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
};
relativeURL.prototype = URL.prototype;
contextPrototype.U = relativeURL;
/**
* Utility function to ensure all variants of an enum are handled.
*/ function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
* Constructs an error message for when a module factory is not available.
*/ function factoryNotAvailableMessage(moduleId, sourceType, sourceData) {
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
break;
case 2:
instantiationReason = 'because of an HMR update';
break;
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
}
return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`;
}
/**
* A stub function to make `require` available but non-functional in ESM.
*/ function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
}
contextPrototype.z = requireStub;
// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.
contextPrototype.g = globalThis;
function applyModuleFactoryName(factory) {
// Give the module factory a nice name to improve stack traces.
Object.defineProperty(factory, 'name', {
value: 'module evaluation'
});
}
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
* Turbopack *browser* ECMAScript runtimes. * Turbopack *browser* ECMAScript runtimes.
......
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