Commit 7b2d8614 authored by Luke Sandberg's avatar Luke Sandberg

Turbopack: extract WASM and Worker loading into importable `@turbopack/wasm-*`…

Turbopack: extract WASM and Worker loading into importable `@turbopack/wasm-*` and `@turbopack/worker-*` modules

Follow the pattern of #92549 (base64 extraction) to move rarely-used WASM loading
and Worker creation logic out of the always-shipped runtime into on-demand modules.

WASM loading is split into three environment-specific modules:
- `@turbopack/wasm-node` (uses fs/stream for Node.js)
- `@turbopack/wasm-dom` (uses fetch for browsers)
- `@turbopack/wasm-edge` (uses pre-compiled edge modules)

Worker creation is split into two modules:
- `@turbopack/worker-browser` (Web Worker / SharedWorker via URL params)
- `@turbopack/worker-node` (worker_threads with forwarded globals)

The runtime now exposes four new context shortcuts (`w`, `u`, `X`, `b`) that
provide environment-specific primitives (chunk URL resolution, asset suffix,
forwarded globals, chunk path resolution) which the extracted modules consume
via `__turbopack_*__` free variables.
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent ce33784b
...@@ -68,19 +68,6 @@ interface RuntimeBackend { ...@@ -68,19 +68,6 @@ interface RuntimeBackend {
* Returns the same Promise for the same chunk URL. * Returns the same Promise for the same chunk URL.
*/ */
loadChunkCached: (sourceType: SourceType, chunkUrl: ChunkUrl) => Promise<void> loadChunkCached: (sourceType: SourceType, chunkUrl: ChunkUrl) => Promise<void>
loadWebAssembly: (
sourceType: SourceType,
sourceData: SourceData,
wasmChunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module,
importsObj: WebAssembly.Imports
) => Promise<Exports>
loadWebAssemblyModule: (
sourceType: SourceType,
sourceData: SourceData,
wasmChunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module
) => Promise<WebAssembly.Module>
} }
interface DevRuntimeBackend { interface DevRuntimeBackend {
...@@ -290,51 +277,37 @@ function exportUrl( ...@@ -290,51 +277,37 @@ function exportUrl(
browserContextPrototype.q = exportUrl browserContextPrototype.q = exportUrl
/** /**
* Creates a worker by instantiating the given WorkerConstructor with the * Returns the full chunk URL for a chunk path, including CHUNK_BASE_PATH prefix
* appropriate URL and options. * and ASSET_SUFFIX. Used by extracted worker/wasm modules.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ */
function createWorker( function chunkUrl(chunkPath: ChunkPath): ChunkUrl {
WorkerConstructor: { new (url: URL, options?: object): Worker }, return getChunkRelativeUrl(chunkPath)
entrypoint: ChunkPath, }
moduleChunks: ChunkPath[], browserContextPrototype.w = chunkUrl
workerOptions?: object
): Worker {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker'
const chunkUrls = moduleChunks
.map((chunk) => getChunkRelativeUrl(chunk))
.reverse()
const params: unknown[] = [chunkUrls, ASSET_SUFFIX]
for (const globalName of WORKER_FORWARDED_GLOBALS) {
params.push((globalThis as Record<string, unknown>)[globalName])
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin) /**
const paramsJson = JSON.stringify(params) * Returns the ASSET_SUFFIX string. Used by extracted worker modules.
if (isSharedWorker) { */
url.searchParams.set('params', paramsJson) function assetSuffix(): string {
} else { return ASSET_SUFFIX
url.hash = '#params=' + encodeURIComponent(paramsJson) }
} browserContextPrototype.X = assetSuffix
/**
* Returns the list of worker-forwarded global names.
*/
function forwardedGlobals(): string[] {
return WORKER_FORWARDED_GLOBALS
}
browserContextPrototype.b = forwardedGlobals
// Remove type: "module" from options since our worker entrypoint is not a module /**
const options = workerOptions * Resolves a chunk path. On browser, returns the path as-is (not applicable).
? { ...workerOptions, type: undefined } */
: undefined function resolveChunkPath(chunkPath: string): string {
return new WorkerConstructor(url, options) return chunkPath
} }
browserContextPrototype.b = createWorker browserContextPrototype.u = resolveChunkPath
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
...@@ -435,33 +408,3 @@ function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean { ...@@ -435,33 +408,3 @@ function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {
function isCss(chunkUrl: ChunkUrl): boolean { function isCss(chunkUrl: ChunkUrl): boolean {
return endsWithExtension(chunkUrl, '.css') return endsWithExtension(chunkUrl, '.css')
} }
function loadWebAssembly(
this: TurbopackBaseContext<Module>,
chunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module,
importsObj: WebAssembly.Imports
): Promise<Exports> {
return BACKEND.loadWebAssembly(
SourceType.Parent,
this.m.id,
chunkPath,
edgeModule,
importsObj
)
}
contextPrototype.w = loadWebAssembly
function loadWebAssemblyModule(
this: TurbopackBaseContext<Module>,
chunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module
): Promise<WebAssembly.Module> {
return BACKEND.loadWebAssemblyModule(
SourceType.Parent,
this.m.id,
chunkPath,
edgeModule
)
}
contextPrototype.u = loadWebAssemblyModule
...@@ -74,34 +74,6 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -74,34 +74,6 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) { loadChunkCached(sourceType: SourceType, chunkUrl: ChunkUrl) {
return doLoadChunk(sourceType, chunkUrl) return doLoadChunk(sourceType, chunkUrl)
}, },
async loadWebAssembly(
_sourceType: SourceType,
_sourceData: SourceData,
wasmChunkPath: ChunkPath,
_edgeModule: () => WebAssembly.Module,
importsObj: WebAssembly.Imports
): Promise<Exports> {
const req = fetchWebAssembly(wasmChunkPath)
const { instance } = await WebAssembly.instantiateStreaming(
req,
importsObj
)
return instance.exports
},
async loadWebAssemblyModule(
_sourceType: SourceType,
_sourceData: SourceData,
wasmChunkPath: ChunkPath,
_edgeModule: () => WebAssembly.Module
): Promise<WebAssembly.Module> {
const req = fetchWebAssembly(wasmChunkPath)
return await WebAssembly.compileStreaming(req)
},
} }
function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver { function getOrCreateResolver(chunkUrl: ChunkUrl): ChunkResolver {
...@@ -229,8 +201,4 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -229,8 +201,4 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
resolver.loadingStarted = true resolver.loadingStarted = true
return resolver.promise return resolver.promise
} }
function fetchWebAssembly(wasmChunkPath: ChunkPath) {
return fetch(getChunkRelativeUrl(wasmChunkPath))
}
})() })()
...@@ -56,27 +56,6 @@ let BACKEND: RuntimeBackend ...@@ -56,27 +56,6 @@ let BACKEND: RuntimeBackend
loadChunkCached(_sourceType: SourceType, _chunkUrl: ChunkUrl) { loadChunkCached(_sourceType: SourceType, _chunkUrl: ChunkUrl) {
throw new Error('chunk loading is not supported') throw new Error('chunk loading is not supported')
}, },
async loadWebAssembly(
_sourceType: SourceType,
_sourceData: SourceData,
chunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module,
imports: WebAssembly.Imports
): Promise<Exports> {
const module = await loadEdgeWasm(chunkPath, edgeModule)
return await WebAssembly.instantiate(module, imports)
},
async loadWebAssemblyModule(
_sourceType: SourceType,
_sourceData: SourceData,
chunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module
): Promise<WebAssembly.Module> {
return loadEdgeWasm(chunkPath, edgeModule)
},
} }
const registeredChunks: Set<ChunkPath> = new Set() const registeredChunks: Set<ChunkPath> = new Set()
...@@ -149,22 +128,4 @@ let BACKEND: RuntimeBackend ...@@ -149,22 +128,4 @@ let BACKEND: RuntimeBackend
getOrInstantiateRuntimeModule(chunkPath, moduleId) getOrInstantiateRuntimeModule(chunkPath, moduleId)
} }
} }
async function loadEdgeWasm(
chunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module
): Promise<WebAssembly.Module> {
let module
try {
module = edgeModule()
} catch (_e) {}
if (!module) {
throw new Error(
`dynamically loading WebAssembly is not supported in this runtime as global was not injected for chunk '${chunkPath}'`
)
}
return module
}
})() })()
...@@ -27,7 +27,6 @@ nodeContextPrototype.M = moduleFactories ...@@ -27,7 +27,6 @@ nodeContextPrototype.M = moduleFactories
// Cast moduleCache to ModuleWithDirection for production mode // Cast moduleCache to ModuleWithDirection for production mode
nodeContextPrototype.c = moduleCache as ModuleCache<ModuleWithDirection> nodeContextPrototype.c = moduleCache as ModuleCache<ModuleWithDirection>
nodeContextPrototype.R = resolvePathFromModule nodeContextPrototype.R = resolvePathFromModule
nodeContextPrototype.b = createWorker
nodeContextPrototype.C = clearChunkCache nodeContextPrototype.C = clearChunkCache
function instantiateModule( function instantiateModule(
......
...@@ -36,7 +36,6 @@ nodeDevContextPrototype.q = exportUrl ...@@ -36,7 +36,6 @@ nodeDevContextPrototype.q = exportUrl
nodeDevContextPrototype.M = moduleFactories nodeDevContextPrototype.M = moduleFactories
nodeDevContextPrototype.c = devModuleCache nodeDevContextPrototype.c = devModuleCache
nodeDevContextPrototype.R = resolvePathFromModule nodeDevContextPrototype.R = resolvePathFromModule
nodeDevContextPrototype.b = createWorker
nodeDevContextPrototype.C = clearChunkCache nodeDevContextPrototype.C = clearChunkCache
/** /**
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
/// <reference path="../../shared/runtime/runtime-utils.ts" /> /// <reference path="../../shared/runtime/runtime-utils.ts" />
/// <reference path="../../shared-node/base-externals-utils.ts" /> /// <reference path="../../shared-node/base-externals-utils.ts" />
/// <reference path="../../shared-node/node-externals-utils.ts" /> /// <reference path="../../shared-node/node-externals-utils.ts" />
/// <reference path="../../shared-node/node-wasm-utils.ts" />
/// <reference path="./nodejs-globals.d.ts" /> /// <reference path="./nodejs-globals.d.ts" />
/** /**
...@@ -143,58 +142,39 @@ function loadChunkAsyncByUrl<TModule extends Module>( ...@@ -143,58 +142,39 @@ function loadChunkAsyncByUrl<TModule extends Module>(
} }
contextPrototype.L = loadChunkAsyncByUrl contextPrototype.L = loadChunkAsyncByUrl
function loadWebAssembly( /**
chunkPath: ChunkPath, * Returns the chunk path as-is. On Node.js, chunks are loaded by path.
_edgeModule: () => WebAssembly.Module, */
imports: WebAssembly.Imports function chunkUrl(chunkPath: ChunkPath): string {
) { return chunkPath
const resolved = path.resolve(RUNTIME_ROOT, chunkPath)
return instantiateWebAssemblyFromPath(resolved, imports)
} }
contextPrototype.w = loadWebAssembly contextPrototype.w = chunkUrl
function loadWebAssemblyModule( /**
chunkPath: ChunkPath, * Resolves a chunk path to an absolute filesystem path using RUNTIME_ROOT.
_edgeModule: () => WebAssembly.Module */
) { function resolveChunkPath(chunkPath: string): string {
const resolved = path.resolve(RUNTIME_ROOT, chunkPath) return path.resolve(RUNTIME_ROOT, chunkPath)
return compileWebAssemblyFromPath(resolved)
} }
contextPrototype.u = loadWebAssemblyModule contextPrototype.u = resolveChunkPath
/** /**
* Creates a Node.js worker thread by instantiating the given WorkerConstructor * Returns the list of worker-forwarded global names.
* with the appropriate path and options, including forwarded globals.
*
* @param WorkerConstructor The Worker constructor from worker_threads
* @param workerPath Path to the worker entry chunk
* @param workerOptions options to pass to the Worker constructor (optional)
*/ */
function createWorker( function forwardedGlobals(): string[] {
WorkerConstructor: { new (path: string, options?: object): unknown }, return typeof WORKER_FORWARDED_GLOBALS !== 'undefined'
workerPath: string, ? WORKER_FORWARDED_GLOBALS
workerOptions?: { workerData?: unknown; [key: string]: unknown } : []
): unknown { }
// Build the forwarded globals object contextPrototype.b = forwardedGlobals
const forwardedGlobals: Record<string, unknown> = {}
for (const name of WORKER_FORWARDED_GLOBALS) {
forwardedGlobals[name] = (globalThis as Record<string, unknown>)[name]
}
// Merge workerData with forwarded globals
const existingWorkerData = workerOptions?.workerData || {}
const options = {
...workerOptions,
workerData: {
...(typeof existingWorkerData === 'object' ? existingWorkerData : {}),
__turbopack_globals__: forwardedGlobals,
},
}
return new WorkerConstructor(workerPath, options) /**
* Returns the asset suffix (empty string on Node.js).
*/
function assetSuffix(): string {
return ''
} }
contextPrototype.X = assetSuffix
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/ const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/
/** /**
......
...@@ -63,15 +63,10 @@ type DynamicExport = ( ...@@ -63,15 +63,10 @@ type DynamicExport = (
type LoadChunk = (chunkPath: ChunkPath) => Promise<any> | undefined type LoadChunk = (chunkPath: ChunkPath) => Promise<any> | undefined
type LoadChunkByUrl = (chunkUrl: ChunkUrl) => Promise<any> | undefined type LoadChunkByUrl = (chunkUrl: ChunkUrl) => Promise<any> | undefined
type LoadWebAssembly = ( type ChunkUrlResolver = (chunkPath: ChunkPath) => string
wasmChunkPath: ChunkPath, type ChunkPathResolver = (chunkPath: string) => string
edgeModule: () => WebAssembly.Module, type ForwardedGlobals = () => string[]
imports: WebAssembly.Imports type AssetSuffix = () => string
) => Exports
type LoadWebAssemblyModule = (
wasmChunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module
) => WebAssembly.Module
type ModuleCache<M> = Record<ModuleId, M> type ModuleCache<M> = Record<ModuleId, M>
// TODO properly type values here // TODO properly type values here
...@@ -97,11 +92,6 @@ type AsyncModule = ( ...@@ -97,11 +92,6 @@ type AsyncModule = (
) => void ) => void
type ResolveAbsolutePath = (modulePath?: string) => string type ResolveAbsolutePath = (modulePath?: string) => string
type GetWorkerURL = (
entrypoint: ChunkPath,
moduleChunks: ChunkPath[],
shared: boolean
) => URL
type ExternalRequire = ( type ExternalRequire = (
id: DependencySpecifier, id: DependencySpecifier,
...@@ -145,11 +135,12 @@ interface TurbopackBaseContext<M> { ...@@ -145,11 +135,12 @@ interface TurbopackBaseContext<M> {
M: ModuleFactories M: ModuleFactories
l: LoadChunk l: LoadChunk
L: LoadChunkByUrl L: LoadChunkByUrl
w: LoadWebAssembly w: ChunkUrlResolver
u: LoadWebAssemblyModule u: ChunkPathResolver
P: ResolveAbsolutePath P: ResolveAbsolutePath
U: RelativeURL U: RelativeURL
b: GetWorkerURL b: ForwardedGlobals
X: AssetSuffix
x: ExternalRequire x: ExternalRequire
y: ExternalImport y: ExternalImport
z: CommonJsRequire z: CommonJsRequire
......
/**
* Browser DOM WebAssembly loading module.
* Only included when a .wasm file is actually imported.
*/
'use turbopack no side effects'
declare function __turbopack_chunk_url__(chunkPath: string): string
export async function instantiateWebAssembly(
chunkPath: string,
_edgeModule: () => WebAssembly.Module,
imports: WebAssembly.Imports
): Promise<Record<string, unknown>> {
const url = __turbopack_chunk_url__(chunkPath)
const req = fetch(url)
const { instance } = await WebAssembly.instantiateStreaming(req, imports)
return instance.exports
}
export async function compileWebAssembly(
chunkPath: string,
_edgeModule: () => WebAssembly.Module
): Promise<WebAssembly.Module> {
const url = __turbopack_chunk_url__(chunkPath)
const req = fetch(url)
return await WebAssembly.compileStreaming(req)
}
/**
* Edge runtime WebAssembly loading module.
* Only included when a .wasm file is actually imported.
*/
'use turbopack no side effects'
async function loadEdgeWasm(
chunkPath: string,
edgeModule: () => WebAssembly.Module
): Promise<WebAssembly.Module> {
let module
try {
module = edgeModule()
} catch (_e) {}
if (!module) {
throw new Error(
`dynamically loading WebAssembly is not supported in this runtime as global was not injected for chunk '${chunkPath}'`
)
}
return module
}
export async function instantiateWebAssembly(
chunkPath: string,
edgeModule: () => WebAssembly.Module,
imports: WebAssembly.Imports
): Promise<Record<string, unknown>> {
const module = await loadEdgeWasm(chunkPath, edgeModule)
const instance = await WebAssembly.instantiate(module, imports)
return instance.exports
}
export async function compileWebAssembly(
chunkPath: string,
edgeModule: () => WebAssembly.Module
): Promise<WebAssembly.Module> {
return loadEdgeWasm(chunkPath, edgeModule)
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /**
* Node.js WebAssembly loading module.
* Only included when a .wasm file is actually imported.
*/
/// <reference path="../shared/runtime/runtime-utils.ts" />
'use turbopack no side effects'
declare function __turbopack_resolve_chunk_path__(path: string): string
function readWebAssemblyAsResponse(path: string) { function readWebAssemblyAsResponse(path: string) {
const { createReadStream } = require('fs') as typeof import('fs') const { createReadStream } = require('fs') as typeof import('fs')
...@@ -16,24 +23,25 @@ function readWebAssemblyAsResponse(path: string) { ...@@ -16,24 +23,25 @@ function readWebAssemblyAsResponse(path: string) {
}) })
} }
async function compileWebAssemblyFromPath( export async function instantiateWebAssembly(
path: string chunkPath: string,
): Promise<WebAssembly.Module> { _edgeModule: () => WebAssembly.Module,
const response = readWebAssemblyAsResponse(path) imports: WebAssembly.Imports
): Promise<Record<string, unknown>> {
const resolved = __turbopack_resolve_chunk_path__(chunkPath)
const response = readWebAssemblyAsResponse(resolved)
return await WebAssembly.compileStreaming(response) const { instance } = await WebAssembly.instantiateStreaming(response, imports)
}
async function instantiateWebAssemblyFromPath( return instance.exports
path: string, }
importsObj: WebAssembly.Imports
): Promise<Exports> {
const response = readWebAssemblyAsResponse(path)
const { instance } = await WebAssembly.instantiateStreaming( export async function compileWebAssembly(
response, chunkPath: string,
importsObj _edgeModule: () => WebAssembly.Module
) ): Promise<WebAssembly.Module> {
const resolved = __turbopack_resolve_chunk_path__(chunkPath)
const response = readWebAssemblyAsResponse(resolved)
return instance.exports return await WebAssembly.compileStreaming(response)
} }
/**
* Browser worker creation module.
* Only included when a Web Worker or SharedWorker is actually used.
*/
'use turbopack no side effects'
declare function __turbopack_chunk_url__(chunkPath: string): string
declare function __turbopack_forwarded_globals__(): string[]
declare function __turbopack_asset_suffix__(): string
/**
* Creates a worker by instantiating the given WorkerConstructor with the
* appropriate URL and options.
*
* The entrypoint is a pre-compiled worker runtime file. The params configure
* which module chunks to load and which module to run as the entry point.
*
* The params are a JSON array of the following structure:
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`
*
* @param WorkerConstructor The Worker or SharedWorker constructor
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/
export function createWorker(
WorkerConstructor: { new (url: URL, options?: object): Worker },
entrypoint: string,
moduleChunks: string[],
workerOptions?: object
): Worker {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker'
const chunkUrls = moduleChunks
.map((chunk) => __turbopack_chunk_url__(chunk))
.reverse()
const params: unknown[] = [chunkUrls, __turbopack_asset_suffix__()]
for (const globalName of __turbopack_forwarded_globals__()) {
params.push((globalThis as Record<string, unknown>)[globalName])
}
const url = new URL(__turbopack_chunk_url__(entrypoint), location.origin)
const paramsJson = JSON.stringify(params)
if (isSharedWorker) {
url.searchParams.set('params', paramsJson)
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson)
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions
? { ...workerOptions, type: undefined }
: undefined
return new WorkerConstructor(url, options)
}
/**
* Node.js worker creation module.
* Only included when a Node.js worker_threads Worker is actually used.
*/
'use turbopack no side effects'
declare function __turbopack_forwarded_globals__(): string[]
/**
* Creates a Node.js worker thread by instantiating the given WorkerConstructor
* with the appropriate path and options, including forwarded globals.
*
* @param WorkerConstructor The Worker constructor from worker_threads
* @param workerPath Path to the worker entry chunk
* @param workerOptions options to pass to the Worker constructor (optional)
*/
export function createWorker(
WorkerConstructor: { new (path: string, options?: object): unknown },
workerPath: string,
workerOptions?: { workerData?: unknown; [key: string]: unknown }
): unknown {
// Build the forwarded globals object
const forwardedGlobals: Record<string, unknown> = {}
for (const name of __turbopack_forwarded_globals__()) {
forwardedGlobals[name] = (globalThis as Record<string, unknown>)[name]
}
// Merge workerData with forwarded globals
const existingWorkerData = workerOptions?.workerData || {}
const options = {
...workerOptions,
workerData: {
...(typeof existingWorkerData === 'object' ? existingWorkerData : {}),
__turbopack_globals__: forwardedGlobals,
},
}
return new WorkerConstructor(workerPath, options)
}
...@@ -204,16 +204,6 @@ pub async fn get_browser_runtime_code( ...@@ -204,16 +204,6 @@ pub async fn get_browser_runtime_code(
.await?, .await?,
); );
} }
if *environment.supports_wasm().await? {
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("shared-node/node-wasm-utils.ts"),
generate_source_map,
)
.await?,
);
}
for backend_code in runtime_backend_code { for backend_code in runtime_backend_code {
code.push_code( code.push_code(
......
...@@ -64,7 +64,45 @@ pub async fn turbopack_runtime_import_map() -> Result<Vc<ImportMap>> { ...@@ -64,7 +64,45 @@ pub async fn turbopack_runtime_import_map() -> Result<Vc<ImportMap>> {
// Exact alias: @turbopack/base64 // Exact alias: @turbopack/base64
import_map.insert_exact_alias( import_map.insert_exact_alias(
rcstr!("@turbopack/base64"), rcstr!("@turbopack/base64"),
ImportMapping::PrimaryAlternative(rcstr!("./shared/base64.ts"), Some(embed_root)) ImportMapping::PrimaryAlternative(rcstr!("./shared/base64.ts"), Some(embed_root.clone()))
.resolved_cell(),
);
// WebAssembly loading modules (per-environment)
import_map.insert_exact_alias(
rcstr!("@turbopack/wasm-node"),
ImportMapping::PrimaryAlternative(
rcstr!("./shared/wasm-node.ts"),
Some(embed_root.clone()),
)
.resolved_cell(),
);
import_map.insert_exact_alias(
rcstr!("@turbopack/wasm-dom"),
ImportMapping::PrimaryAlternative(rcstr!("./shared/wasm-dom.ts"), Some(embed_root.clone()))
.resolved_cell(),
);
import_map.insert_exact_alias(
rcstr!("@turbopack/wasm-edge"),
ImportMapping::PrimaryAlternative(
rcstr!("./shared/wasm-edge.ts"),
Some(embed_root.clone()),
)
.resolved_cell(),
);
// Worker creation modules (per-environment)
import_map.insert_exact_alias(
rcstr!("@turbopack/worker-browser"),
ImportMapping::PrimaryAlternative(
rcstr!("./shared/worker-browser.ts"),
Some(embed_root.clone()),
)
.resolved_cell(),
);
import_map.insert_exact_alias(
rcstr!("@turbopack/worker-node"),
ImportMapping::PrimaryAlternative(rcstr!("./shared/worker-node.ts"), Some(embed_root))
.resolved_cell(), .resolved_cell(),
); );
......
...@@ -32,11 +32,6 @@ pub async fn get_nodejs_runtime_code( ...@@ -32,11 +32,6 @@ pub async fn get_nodejs_runtime_code(
rcstr!("shared-node/node-externals-utils.ts"), rcstr!("shared-node/node-externals-utils.ts"),
generate_source_map, generate_source_map,
); );
let shared_node_wasm_utils_code = embed_static_code(
asset_context,
rcstr!("shared-node/node-wasm-utils.ts"),
generate_source_map,
);
// Runtime base is shared between production and development // Runtime base is shared between production and development
let runtime_base_code = embed_static_code( let runtime_base_code = embed_static_code(
...@@ -49,7 +44,6 @@ pub async fn get_nodejs_runtime_code( ...@@ -49,7 +44,6 @@ pub async fn get_nodejs_runtime_code(
code.push_code(&*shared_runtime_utils_code.await?); code.push_code(&*shared_runtime_utils_code.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(&*runtime_base_code.await?); code.push_code(&*runtime_base_code.await?);
match runtime_type { match runtime_type {
......
...@@ -83,20 +83,21 @@ pub const TURBOPACK_DYNAMIC: &TurbopackRuntimeFunctionShortcut = make_shortcut!( ...@@ -83,20 +83,21 @@ pub const TURBOPACK_DYNAMIC: &TurbopackRuntimeFunctionShortcut = make_shortcut!(
pub const TURBOPACK_RESOLVE_ABSOLUTE_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("P"); pub const TURBOPACK_RESOLVE_ABSOLUTE_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("P");
pub const TURBOPACK_RELATIVE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("U"); pub const TURBOPACK_RELATIVE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("U");
pub const TURBOPACK_RESOLVE_MODULE_ID_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("R"); pub const TURBOPACK_RESOLVE_MODULE_ID_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("R");
pub const TURBOPACK_CREATE_WORKER: &TurbopackRuntimeFunctionShortcut = make_shortcut!("b");
pub const TURBOPACK_ASYNC_MODULE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("a"); pub const TURBOPACK_ASYNC_MODULE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("a");
pub const TURBOPACK_EXTERNAL_REQUIRE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("x"); pub const TURBOPACK_EXTERNAL_REQUIRE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("x");
pub const TURBOPACK_EXTERNAL_IMPORT: &TurbopackRuntimeFunctionShortcut = make_shortcut!("y"); pub const TURBOPACK_EXTERNAL_IMPORT: &TurbopackRuntimeFunctionShortcut = make_shortcut!("y");
pub const TURBOPACK_REFRESH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("k"); pub const TURBOPACK_REFRESH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("k");
pub const TURBOPACK_REQUIRE_STUB: &TurbopackRuntimeFunctionShortcut = make_shortcut!("z"); pub const TURBOPACK_REQUIRE_STUB: &TurbopackRuntimeFunctionShortcut = make_shortcut!("z");
pub const TURBOPACK_REQUIRE_REAL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("t"); pub const TURBOPACK_REQUIRE_REAL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("t");
pub const TURBOPACK_WASM: &TurbopackRuntimeFunctionShortcut = make_shortcut!("w");
pub const TURBOPACK_WASM_MODULE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("u");
pub const TURBOPACK_GLOBAL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("g"); pub const TURBOPACK_GLOBAL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("g");
pub const TURBOPACK_CHUNK_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("w");
pub const TURBOPACK_RESOLVE_CHUNK_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("u");
pub const TURBOPACK_FORWARDED_GLOBALS: &TurbopackRuntimeFunctionShortcut = make_shortcut!("b");
pub const TURBOPACK_ASSET_SUFFIX: &TurbopackRuntimeFunctionShortcut = make_shortcut!("X");
/// Adding an entry to this list will automatically ensure that `__turbopack_XXX__` can be called /// Adding an entry to this list will automatically ensure that `__turbopack_XXX__` can be called
/// from user code (by inserting a replacement into free_var_references) /// from user code (by inserting a replacement into free_var_references)
pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 23] = [ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 24] = [
("__turbopack_require__", TURBOPACK_REQUIRE), ("__turbopack_require__", TURBOPACK_REQUIRE),
("__turbopack_module_context__", TURBOPACK_MODULE_CONTEXT), ("__turbopack_module_context__", TURBOPACK_MODULE_CONTEXT),
("__turbopack_import__", TURBOPACK_IMPORT), ("__turbopack_import__", TURBOPACK_IMPORT),
...@@ -117,7 +118,6 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio ...@@ -117,7 +118,6 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio
"__turbopack_resolve_module_id_path__", "__turbopack_resolve_module_id_path__",
TURBOPACK_RESOLVE_MODULE_ID_PATH, TURBOPACK_RESOLVE_MODULE_ID_PATH,
), ),
("__turbopack_create_worker__", TURBOPACK_CREATE_WORKER),
("__turbopack_external_require__", TURBOPACK_EXTERNAL_REQUIRE), ("__turbopack_external_require__", TURBOPACK_EXTERNAL_REQUIRE),
("__turbopack_external_import__", TURBOPACK_EXTERNAL_IMPORT), ("__turbopack_external_import__", TURBOPACK_EXTERNAL_IMPORT),
("__turbopack_refresh__", TURBOPACK_REFRESH), ("__turbopack_refresh__", TURBOPACK_REFRESH),
...@@ -127,6 +127,14 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio ...@@ -127,6 +127,14 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio
"__turbopack_clear_chunk_cache__", "__turbopack_clear_chunk_cache__",
TURBOPACK_CLEAR_CHUNK_CACHE, TURBOPACK_CLEAR_CHUNK_CACHE,
), ),
("__turbopack_wasm__", TURBOPACK_WASM), ("__turbopack_chunk_url__", TURBOPACK_CHUNK_URL),
("__turbopack_wasm_module__", TURBOPACK_WASM_MODULE), (
"__turbopack_resolve_chunk_path__",
TURBOPACK_RESOLVE_CHUNK_PATH,
),
(
"__turbopack_forwarded_globals__",
TURBOPACK_FORWARDED_GLOBALS,
),
("__turbopack_asset_suffix__", TURBOPACK_ASSET_SUFFIX),
]; ];
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use indoc::formatdoc; use indoc::formatdoc;
use turbo_rcstr::rcstr; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryJoinIterExt, ValueToString, Vc}; use turbo_tasks::{ResolvedVc, TryJoinIterExt, ValueToString, Vc};
use turbopack_core::{ use turbopack_core::{
chunk::{ chunk::{
AsyncModuleInfo, ChunkData, ChunkGroupType, ChunkableModule, ChunkingContext, AsyncModuleInfo, ChunkData, ChunkGroupType, ChunkableModule, ChunkingContext,
ChunkingContextExt, ChunkingType, ChunksData, EvaluatableAsset, ChunkingContextExt, ChunkingType, ChunksData, EvaluatableAsset, ModuleChunkItemIdExt,
availability_info::AvailabilityInfo, availability_info::AvailabilityInfo,
}, },
context::AssetContext, context::AssetContext,
environment::ChunkLoading,
ident::AssetIdent, ident::AssetIdent,
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
module_graph::{ModuleGraph, chunk_group_info::ChunkGroup}, module_graph::{ModuleGraph, chunk_group_info::ChunkGroup},
output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced}, output::{OutputAsset, OutputAssets, OutputAssetsWithReferenced},
reference::{ModuleReference, ModuleReferences}, reference::{ModuleReference, ModuleReferences, SingleChunkableModuleReference},
resolve::ModuleResolveResult, reference_type::{EcmaScriptModulesReferenceSubType, ReferenceType},
resolve::{ExportUsage, ModuleResolveResult, parse::Request},
}; };
use super::worker_type::WorkerType; use super::worker_type::WorkerType;
...@@ -23,7 +25,7 @@ use crate::{ ...@@ -23,7 +25,7 @@ use crate::{
EcmascriptChunkItemContent, EcmascriptChunkItemOptions, EcmascriptChunkPlaceable, EcmascriptChunkItemContent, EcmascriptChunkItemOptions, EcmascriptChunkPlaceable,
EcmascriptExports, data::EcmascriptChunkData, ecmascript_chunk_item, EcmascriptExports, data::EcmascriptChunkData, ecmascript_chunk_item,
}, },
runtime_functions::{TURBOPACK_CREATE_WORKER, TURBOPACK_EXPORT_VALUE}, runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_REQUIRE},
utils::StringifyJs, utils::StringifyJs,
}; };
...@@ -52,6 +54,49 @@ impl WorkerLoaderModule { ...@@ -52,6 +54,49 @@ impl WorkerLoaderModule {
}) })
} }
/// Resolves the `@turbopack/worker-*` helper module for the current environment.
#[turbo_tasks::function]
async fn worker_helper_module(&self) -> Result<Vc<Box<dyn Module>>> {
let environment = self.asset_context.compile_time_info().environment();
let chunk_loading = &*environment.chunk_loading().await?;
let helper_request: RcStr = match chunk_loading {
ChunkLoading::NodeJs => rcstr!("@turbopack/worker-node"),
ChunkLoading::Edge | ChunkLoading::Dom => rcstr!("@turbopack/worker-browser"),
};
let origin_path = self.inner.ident().path().owned().await?;
let request = Request::parse_string(helper_request.clone());
let resolve_options = self.asset_context.resolve_options(origin_path.clone());
let result = self.asset_context.resolve_asset(
origin_path,
request,
resolve_options,
ReferenceType::EcmaScriptModules(EcmaScriptModulesReferenceSubType::Import),
);
let module = result.first_module().await?;
let Some(module) = *module else {
bail!(
"Could not resolve worker helper module '{}'",
helper_request
);
};
Ok(*module)
}
/// Gets the worker helper module as an EcmascriptChunkPlaceable.
#[turbo_tasks::function]
async fn worker_helper_placeable(
self: Vc<Self>,
) -> Result<Vc<Box<dyn EcmascriptChunkPlaceable>>> {
let module = self.worker_helper_module().to_resolved().await?;
let Some(placeable) = ResolvedVc::try_sidecast::<Box<dyn EcmascriptChunkPlaceable>>(module)
else {
bail!("Worker helper module was not processed into an EcmascriptChunkPlaceable");
};
Ok(*placeable)
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn chunk_group( async fn chunk_group(
self: Vc<Self>, self: Vc<Self>,
...@@ -160,11 +205,25 @@ impl Module for WorkerLoaderModule { ...@@ -160,11 +205,25 @@ impl Module for WorkerLoaderModule {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn references(self: Vc<Self>) -> Result<Vc<ModuleReferences>> { async fn references(self: Vc<Self>) -> Result<Vc<ModuleReferences>> {
let this = self.await?; let this = self.await?;
Ok(Vc::cell(vec![ResolvedVc::upcast( let worker_ref =
WorkerModuleReference::new(*ResolvedVc::upcast(this.inner), this.worker_type) WorkerModuleReference::new(*ResolvedVc::upcast(this.inner), this.worker_type)
.to_resolved() .to_resolved()
.await?, .await?;
)]))
// Add a reference to the worker helper module so it's included in the chunk
let helper_module = self.worker_helper_module().to_resolved().await?;
let helper_ref = SingleChunkableModuleReference::new(
*helper_module,
rcstr!("worker helper"),
ExportUsage::all(),
)
.to_resolved()
.await?;
Ok(Vc::cell(vec![
ResolvedVc::upcast(worker_ref),
ResolvedVc::upcast(helper_ref),
]))
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -219,10 +278,9 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -219,10 +278,9 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
inner_code: formatdoc! { inner_code: formatdoc! {
r#" r#"
{TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{ {TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{
return {TURBOPACK_CREATE_WORKER}(Ctor, __dirname + "/" + {worker_path:#}, opts); return Ctor;
}}); }});
"#, "#,
worker_path = StringifyJs(&"a_fake_path_for_size_estimation"),
} }
.into(), .into(),
options, options,
...@@ -231,6 +289,10 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -231,6 +289,10 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
.cell()); .cell());
} }
// Get the worker helper module's chunk item ID for use in TURBOPACK_REQUIRE
let helper_placeable = self.worker_helper_placeable();
let helper_id = helper_placeable.chunk_item_id(chunking_context).await?;
let code = match this.worker_type { let code = match this.worker_type {
WorkerType::WebWorker | WorkerType::SharedWebWorker => { WorkerType::WebWorker | WorkerType::SharedWebWorker => {
// For web workers, generate code that exports a function to create the worker. // For web workers, generate code that exports a function to create the worker.
...@@ -255,10 +317,12 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -255,10 +317,12 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
formatdoc! { formatdoc! {
r#" r#"
var createWorker = {TURBOPACK_REQUIRE}({helper_id}).createWorker;
{TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{ {TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{
return {TURBOPACK_CREATE_WORKER}(Ctor, {entrypoint}, {chunks}, opts); return createWorker(Ctor, {entrypoint}, {chunks}, opts);
}}); }});
"#, "#,
helper_id = StringifyJs(&helper_id),
entrypoint = StringifyJs(&entrypoint_path), entrypoint = StringifyJs(&entrypoint_path),
chunks = StringifyJs(&chunks_data), chunks = StringifyJs(&chunks_data),
} }
...@@ -288,10 +352,12 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule { ...@@ -288,10 +352,12 @@ impl EcmascriptChunkPlaceable for WorkerLoaderModule {
// directory // directory
formatdoc! { formatdoc! {
r#" r#"
var createWorker = {TURBOPACK_REQUIRE}({helper_id}).createWorker;
{TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{ {TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{
return {TURBOPACK_CREATE_WORKER}(Ctor, __dirname + "/" + {worker_path:#}, opts); return createWorker(Ctor, __dirname + "/" + {worker_path:#}, opts);
}}); }});
"#, "#,
helper_id = StringifyJs(&helper_id),
worker_path = StringifyJs(entry_path.file_name()), worker_path = StringifyJs(entry_path.file_name()),
} }
} }
......
;!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]="6a138f62-859e-e13c-84a0-d111b048d46a")}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]="f4476787-0394-ca0a-ac3d-03d90c7ca07d")}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)"]}
...@@ -12,7 +12,6 @@ var CHUNK_BASE_PATH = ""; ...@@ -12,7 +12,6 @@ var CHUNK_BASE_PATH = "";
var RELATIVE_ROOT_PATH = "../../../../../../.."; var RELATIVE_ROOT_PATH = "../../../../../../..";
var RUNTIME_PUBLIC_PATH = ""; var RUNTIME_PUBLIC_PATH = "";
var ASSET_SUFFIX = ""; var ASSET_SUFFIX = "";
var CROSS_ORIGIN = null;
var WORKER_FORWARDED_GLOBALS = []; var WORKER_FORWARDED_GLOBALS = [];
/** /**
* This file contains runtime types and functions that are shared between all * This file contains runtime types and functions that are shared between all
...@@ -733,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath; ...@@ -733,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath;
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/** /**
* Creates a worker by instantiating the given WorkerConstructor with the * Returns the full chunk URL for a chunk path, including CHUNK_BASE_PATH prefix
* appropriate URL and options. * and ASSET_SUFFIX. Used by extracted worker/wasm modules.
* */ function chunkUrl(chunkPath) {
* The entrypoint is a pre-compiled worker runtime file. The params configure return getChunkRelativeUrl(chunkPath);
* which module chunks to load and which module to run as the entry point. }
* browserContextPrototype.w = chunkUrl;
* The params are a JSON array of the following structure: /**
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]` * Returns the ASSET_SUFFIX string. Used by extracted worker modules.
* */ function assetSuffix() {
* @param WorkerConstructor The Worker or SharedWorker constructor return ASSET_SUFFIX;
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
} }
browserContextPrototype.b = createWorker; browserContextPrototype.X = assetSuffix;
/**
* Returns the list of worker-forwarded global names.
*/ function forwardedGlobals() {
return WORKER_FORWARDED_GLOBALS;
}
browserContextPrototype.b = forwardedGlobals;
/**
* Resolves a chunk path. On browser, returns the path as-is (not applicable).
*/ function resolveChunkPath(chunkPath) {
return chunkPath;
}
browserContextPrototype.u = resolveChunkPath;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -841,14 +826,6 @@ function isJs(chunkUrlOrPath) { ...@@ -841,14 +826,6 @@ function isJs(chunkUrlOrPath) {
function isCss(chunkUrl) { function isCss(chunkUrl) {
return endsWithExtension(chunkUrl, '.css'); return endsWithExtension(chunkUrl, '.css');
} }
function loadWebAssembly(chunkPath, edgeModule, importsObj) {
return BACKEND.loadWebAssembly(SourceType.Parent, this.m.id, chunkPath, edgeModule, importsObj);
}
contextPrototype.w = loadWebAssembly;
function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(SourceType.Parent, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
/// <reference path="./runtime-utils.ts" /> /// <reference path="./runtime-utils.ts" />
/// <reference path="./runtime-types.d.ts" /> /// <reference path="./runtime-types.d.ts" />
/// <reference path="./dev-extensions.ts" /> /// <reference path="./dev-extensions.ts" />
...@@ -2006,15 +1983,6 @@ let BACKEND; ...@@ -2006,15 +1983,6 @@ let BACKEND;
* has been loaded. * has been loaded.
*/ loadChunkCached (sourceType, chunkUrl) { */ loadChunkCached (sourceType, chunkUrl) {
return doLoadChunk(sourceType, chunkUrl); return doLoadChunk(sourceType, chunkUrl);
},
async loadWebAssembly (_sourceType, _sourceData, wasmChunkPath, _edgeModule, importsObj) {
const req = fetchWebAssembly(wasmChunkPath);
const { instance } = await WebAssembly.instantiateStreaming(req, importsObj);
return instance.exports;
},
async loadWebAssemblyModule (_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
} }
}; };
function getOrCreateResolver(chunkUrl) { function getOrCreateResolver(chunkUrl) {
...@@ -2084,7 +2052,6 @@ let BACKEND; ...@@ -2084,7 +2052,6 @@ let BACKEND;
} else { } else {
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN;
link.href = chunkUrl; link.href = chunkUrl;
link.onerror = ()=>{ link.onerror = ()=>{
resolver.reject(); resolver.reject();
...@@ -2109,7 +2076,6 @@ let BACKEND; ...@@ -2109,7 +2076,6 @@ let BACKEND;
} }
} else { } else {
const script = document.createElement('script'); const script = document.createElement('script');
script.crossOrigin = CROSS_ORIGIN;
script.src = chunkUrl; script.src = chunkUrl;
// We'll only mark the chunk as loaded once the script has been executed, // We'll only mark the chunk as loaded once the script has been executed,
// which happens in `registerChunk`. Hence the absence of `resolve()` in // which happens in `registerChunk`. Hence the absence of `resolve()` in
...@@ -2127,9 +2093,6 @@ let BACKEND; ...@@ -2127,9 +2093,6 @@ let BACKEND;
resolver.loadingStarted = true; resolver.loadingStarted = true;
return resolver.promise; return resolver.promise;
} }
function fetchWebAssembly(wasmChunkPath) {
return fetch(getChunkRelativeUrl(wasmChunkPath));
}
})(); })();
/** /**
* This file contains the runtime code specific to the Turbopack development * This file contains the runtime code specific to the Turbopack development
...@@ -2185,7 +2148,6 @@ let DEV_BACKEND; ...@@ -2185,7 +2148,6 @@ let DEV_BACKEND;
} }
const link = document.createElement('link'); const link = document.createElement('link');
link.rel = 'stylesheet'; link.rel = 'stylesheet';
link.crossOrigin = CROSS_ORIGIN;
if (navigator.userAgent.includes('Firefox') || navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Chromium')) { if (navigator.userAgent.includes('Firefox') || navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Chromium')) {
// Firefox won't reload CSS files that were previously loaded on the // Firefox won't reload CSS files that were previously loaded on the
// current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506 // current page: https://bugzilla.mozilla.org/show_bug.cgi?id=1037506
...@@ -2247,5 +2209,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2247,5 +2209,5 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# debugId=6a138f62-859e-e13c-84a0-d111b048d46a //# debugId=f4476787-0394-ca0a-ac3d-03d90c7ca07d
//# 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
...@@ -640,31 +640,9 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot); ...@@ -640,31 +640,9 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot);
return ABSOLUTE_ROOT; return ABSOLUTE_ROOT;
} }
Context.prototype.P = resolveAbsolutePath; Context.prototype.P = resolveAbsolutePath;
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../shared/runtime/runtime-utils.ts" />
function readWebAssemblyAsResponse(path) {
const { createReadStream } = require('fs');
const { Readable } = require('stream');
const stream = createReadStream(path);
// @ts-ignore unfortunately there's a slight type mismatch with the stream.
return new Response(Readable.toWeb(stream), {
headers: {
'content-type': 'application/wasm'
}
});
}
async function compileWebAssemblyFromPath(path) {
const response = readWebAssemblyAsResponse(path);
return await WebAssembly.compileStreaming(response);
}
async function instantiateWebAssemblyFromPath(path, importsObj) {
const response = readWebAssemblyAsResponse(path);
const { instance } = await WebAssembly.instantiateStreaming(response, importsObj);
return instance.exports;
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../shared/runtime/runtime-utils.ts" /> /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../shared/runtime/runtime-utils.ts" />
/// <reference path="../../shared-node/base-externals-utils.ts" /> /// <reference path="../../shared-node/base-externals-utils.ts" />
/// <reference path="../../shared-node/node-externals-utils.ts" /> /// <reference path="../../shared-node/node-externals-utils.ts" />
/// <reference path="../../shared-node/node-wasm-utils.ts" />
/// <reference path="./nodejs-globals.d.ts" /> /// <reference path="./nodejs-globals.d.ts" />
/** /**
* Base Node.js runtime shared between production and development. * Base Node.js runtime shared between production and development.
...@@ -768,40 +746,30 @@ function loadChunkAsyncByUrl(chunkUrl) { ...@@ -768,40 +746,30 @@ function loadChunkAsyncByUrl(chunkUrl) {
return loadChunkAsync.call(this, path1); return loadChunkAsync.call(this, path1);
} }
contextPrototype.L = loadChunkAsyncByUrl; contextPrototype.L = loadChunkAsyncByUrl;
function loadWebAssembly(chunkPath, _edgeModule, imports) { /**
const resolved = path.resolve(RUNTIME_ROOT, chunkPath); * Returns the chunk path as-is. On Node.js, chunks are loaded by path.
return instantiateWebAssemblyFromPath(resolved, imports); */ function chunkUrl(chunkPath) {
return chunkPath;
} }
contextPrototype.w = loadWebAssembly; contextPrototype.w = chunkUrl;
function loadWebAssemblyModule(chunkPath, _edgeModule) { /**
const resolved = path.resolve(RUNTIME_ROOT, chunkPath); * Resolves a chunk path to an absolute filesystem path using RUNTIME_ROOT.
return compileWebAssemblyFromPath(resolved); */ function resolveChunkPath(chunkPath) {
return path.resolve(RUNTIME_ROOT, chunkPath);
} }
contextPrototype.u = loadWebAssemblyModule; contextPrototype.u = resolveChunkPath;
/** /**
* Creates a Node.js worker thread by instantiating the given WorkerConstructor * Returns the list of worker-forwarded global names.
* with the appropriate path and options, including forwarded globals. */ function forwardedGlobals() {
* return typeof WORKER_FORWARDED_GLOBALS !== 'undefined' ? WORKER_FORWARDED_GLOBALS : [];
* @param WorkerConstructor The Worker constructor from worker_threads }
* @param workerPath Path to the worker entry chunk contextPrototype.b = forwardedGlobals;
* @param workerOptions options to pass to the Worker constructor (optional) /**
*/ function createWorker(WorkerConstructor, workerPath, workerOptions) { * Returns the asset suffix (empty string on Node.js).
// Build the forwarded globals object */ function assetSuffix() {
const forwardedGlobals = {}; return '';
for (const name of WORKER_FORWARDED_GLOBALS){
forwardedGlobals[name] = globalThis[name];
}
// Merge workerData with forwarded globals
const existingWorkerData = workerOptions?.workerData || {};
const options = {
...workerOptions,
workerData: {
...typeof existingWorkerData === 'object' ? existingWorkerData : {},
__turbopack_globals__: forwardedGlobals
}
};
return new WorkerConstructor(workerPath, options);
} }
contextPrototype.X = assetSuffix;
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/; const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/** /**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment. * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
...@@ -1523,7 +1491,6 @@ nodeDevContextPrototype.q = exportUrl; ...@@ -1523,7 +1491,6 @@ nodeDevContextPrototype.q = exportUrl;
nodeDevContextPrototype.M = moduleFactories; nodeDevContextPrototype.M = moduleFactories;
nodeDevContextPrototype.c = devModuleCache; nodeDevContextPrototype.c = devModuleCache;
nodeDevContextPrototype.R = resolvePathFromModule; nodeDevContextPrototype.R = resolvePathFromModule;
nodeDevContextPrototype.b = createWorker;
nodeDevContextPrototype.C = clearChunkCache; nodeDevContextPrototype.C = clearChunkCache;
/** /**
* Instantiates a module in development mode using shared HMR logic. * Instantiates a module in development mode using shared HMR logic.
......
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0r_m8l7._.js", (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_mjs_1uszc59._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.mjs [test] (ecmascript, async loader)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.mjs [test] (ecmascript, async loader)", ((__turbopack_context__) => {
__turbopack_context__.v((parentImport) => { __turbopack_context__.v((parentImport) => {
......
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/0rv8_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_1aqs1qt.js", "output/0rv8_turbopack-tests_tests_snapshot_imports_ignore-comments_input_index_1br45df.js",
{"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_mjs_0r_m8l7._.js","output/1do3_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_09jmqs-._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_mjs_1uszc59._.js","output/[root-of-the-server]__1gnyf0f._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js [test] (ecmascript)"]}
]); ]);
// Dummy runtime // Dummy runtime
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_09jmqs-._.js", (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/[root-of-the-server]__1gnyf0f._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript)", ((__turbopack_context__, module, exports) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
module.exports = 'turbopack'; module.exports = 'turbopack';
...@@ -6,10 +6,47 @@ module.exports = 'turbopack'; ...@@ -6,10 +6,47 @@ module.exports = 'turbopack';
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs (static in ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/vercel.0kkt412gy5vj6.cjs");}), __turbopack_context__.q("/static/vercel.0kkt412gy5vj6.cjs");}),
"[turbopack]/shared/worker-browser.ts [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
__turbopack_context__.s([
"createWorker",
()=>createWorker
]);
/**
* Browser worker creation module.
* Only included when a Web Worker or SharedWorker is actually used.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ 'use turbopack no side effects';
function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>__turbopack_chunk_url__(chunk)).reverse();
const params = [
chunkUrls,
__turbopack_asset_suffix__()
];
for (const globalName of __turbopack_forwarded_globals__()){
params.push(globalThis[globalName]);
}
const url = new URL(__turbopack_chunk_url__(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript, worker loader)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
var createWorker = __turbopack_context__.r("[turbopack]/shared/worker-browser.ts [test] (ecmascript)").createWorker;
__turbopack_context__.v(function(Ctor, opts) { __turbopack_context__.v(function(Ctor, opts) {
return __turbopack_context__.b(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_output_0uy0mni._.js", ["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_cjs_0j-fab5._.js","output/0rv8_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_cjs_02p77ng._.js"], opts); return createWorker(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_output_0uy0mni._.js", ["output/0_9x_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_cjs_0j-fab5._.js","output/0rv8_turbopack-tests_tests_snapshot_imports_ignore-comments_input_vercel_cjs_02p77ng._.js"], opts);
}); });
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs (static in ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs (static in ecmascript)", ((__turbopack_context__) => {
...@@ -45,4 +82,4 @@ function foo(plugin) { ...@@ -45,4 +82,4 @@ function foo(plugin) {
}), }),
]); ]);
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_input_09jmqs-._.js.map //# sourceMappingURL=%5Broot-of-the-server%5D__1gnyf0f._.js.map
\ No newline at end of file \ No newline at end of file
...@@ -3,5 +3,6 @@ ...@@ -3,5 +3,6 @@
"sources": [], "sources": [],
"sections": [ "sections": [
{"offset": {"line": 3, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs"],"sourcesContent":["module.exports = 'turbopack'\n"],"names":["module","exports"],"mappings":"AAAAA,OAAOC,OAAO,GAAG"}}, {"offset": {"line": 3, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs"],"sourcesContent":["module.exports = 'turbopack'\n"],"names":["module","exports"],"mappings":"AAAAA,OAAOC,OAAO,GAAG"}},
{"offset": {"line": 20, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js"],"sourcesContent":["import('./vercel.mjs').then(console.log)\nimport(/* webpackIgnore: false */ './vercel.mjs').then(console.log)\nconsole.log(require('./vercel.cjs'))\nnew Worker(\n /* turbopackIgnore: false */ new URL('./vercel.cjs', import.meta.url)\n)\n\n// turbopack shouldn't attempt to bundle these, and they should be preserved in the output\nimport(/* webpackIgnore: true */ './ignore.mjs')\nimport(/* turbopackIgnore: true */ './ignore.mjs')\n\n// this should work for cjs requires too\nrequire(/* webpackIgnore: true */ './ignore.cjs')\nrequire(/* turbopackIgnore: true */ './ignore.cjs')\n\nnew Worker(\n /* turbopackIgnore: true */ new URL('./ignore-worker.cjs', import.meta.url)\n)\nnew Worker(\n /* webpackIgnore: true */ new URL('./ignore-worker.cjs', import.meta.url)\n)\n\nexport function foo(plugin) {\n return require(/* turbopackIgnore: true */ plugin)\n}\n"],"names":["then","console","log","Worker","require","foo","plugin"],"mappings":";;;;;;;;;AAAA,gKAAuBA,IAAI,CAACC,QAAQC,GAAG;AACvC,gKAAkDF,IAAI,CAACC,QAAQC,GAAG;AAClED,QAAQC,GAAG;AACX,iKAAIC;AAIJ,0FAA0F;AAC1F,MAAM,CAAC,uBAAuB,GAAG;AACjC,MAAM,CAAC,yBAAyB,GAAG;AAEnC,wCAAwC;AACxCC,QAAQ,uBAAuB,GAAG;AAClCA,QAAQ,yBAAyB,GAAG;AAEpC,IAAID;AAGJ,IAAIA;AAIG,SAASE,IAAIC,MAAM;IACxB,OAAOF,QAAQ,yBAAyB,GAAGE;AAC7C"}}] {"offset": {"line": 11, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/worker-browser.ts"],"sourcesContent":["/**\n * Browser worker creation module.\n * Only included when a Web Worker or SharedWorker is actually used.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n'use turbopack no side effects'\n\ndeclare function __turbopack_chunk_url__(chunkPath: string): string\ndeclare function __turbopack_forwarded_globals__(): string[]\ndeclare function __turbopack_asset_suffix__(): string\n\n/**\n * Creates a worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint URL path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nexport function createWorker(\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n entrypoint: string,\n moduleChunks: string[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n const chunkUrls = moduleChunks\n .map((chunk) => __turbopack_chunk_url__(chunk))\n .reverse()\n const params: unknown[] = [chunkUrls, __turbopack_asset_suffix__()]\n for (const globalName of __turbopack_forwarded_globals__()) {\n params.push((globalThis as Record<string, unknown>)[globalName])\n }\n\n const url = new URL(__turbopack_chunk_url__(entrypoint), location.origin)\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\n"],"names":["createWorker","WorkerConstructor","entrypoint","moduleChunks","workerOptions","isSharedWorker","name","chunkUrls","map","chunk","__turbopack_chunk_url__","reverse","params","__turbopack_asset_suffix__","globalName","__turbopack_forwarded_globals__","push","globalThis","url","URL","location","origin","paramsJson","JSON","stringify","searchParams","set","hash","encodeURIComponent","options","type","undefined"],"mappings":";;;;AAAA;;;CAGC,GAED,oDAAoD,GAEpD;AAqBO,SAASA,aACdC,iBAA+D,EAC/DC,UAAkB,EAClBC,YAAsB,EACtBC,aAAsB;IAEtB,MAAMC,iBAAiBJ,kBAAkBK,IAAI,KAAK;IAElD,MAAMC,YAAYJ,aACfK,GAAG,CAAC,CAACC,QAAUC,wBAAwBD,QACvCE,OAAO;IACV,MAAMC,SAAoB;QAACL;QAAWM;KAA6B;IACnE,KAAK,MAAMC,cAAcC,kCAAmC;QAC1DH,OAAOI,IAAI,CAAC,AAACC,UAAsC,CAACH,WAAW;IACjE;IAEA,MAAMI,MAAM,IAAIC,IAAIT,wBAAwBR,aAAakB,SAASC,MAAM;IACxE,MAAMC,aAAaC,KAAKC,SAAS,CAACZ;IAClC,IAAIP,gBAAgB;QAClBa,IAAIO,YAAY,CAACC,GAAG,CAAC,UAAUJ;IACjC,OAAO;QACLJ,IAAIS,IAAI,GAAG,aAAaC,mBAAmBN;IAC7C;IAEA,iFAAiF;IACjF,MAAMO,UAAUzB,gBACZ;QAAE,GAAGA,aAAa;QAAE0B,MAAMC;IAAU,IACpCA;IACJ,OAAO,IAAI9B,kBAAkBiB,KAAKW;AACpC","ignoreList":[0]}},
{"offset": {"line": 57, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/index.js"],"sourcesContent":["import('./vercel.mjs').then(console.log)\nimport(/* webpackIgnore: false */ './vercel.mjs').then(console.log)\nconsole.log(require('./vercel.cjs'))\nnew Worker(\n /* turbopackIgnore: false */ new URL('./vercel.cjs', import.meta.url)\n)\n\n// turbopack shouldn't attempt to bundle these, and they should be preserved in the output\nimport(/* webpackIgnore: true */ './ignore.mjs')\nimport(/* turbopackIgnore: true */ './ignore.mjs')\n\n// this should work for cjs requires too\nrequire(/* webpackIgnore: true */ './ignore.cjs')\nrequire(/* turbopackIgnore: true */ './ignore.cjs')\n\nnew Worker(\n /* turbopackIgnore: true */ new URL('./ignore-worker.cjs', import.meta.url)\n)\nnew Worker(\n /* webpackIgnore: true */ new URL('./ignore-worker.cjs', import.meta.url)\n)\n\nexport function foo(plugin) {\n return require(/* turbopackIgnore: true */ plugin)\n}\n"],"names":["then","console","log","Worker","require","foo","plugin"],"mappings":";;;;;;;;;AAAA,gKAAuBA,IAAI,CAACC,QAAQC,GAAG;AACvC,gKAAkDF,IAAI,CAACC,QAAQC,GAAG;AAClED,QAAQC,GAAG;AACX,iKAAIC;AAIJ,0FAA0F;AAC1F,MAAM,CAAC,uBAAuB,GAAG;AACjC,MAAM,CAAC,yBAAyB,GAAG;AAEnC,wCAAwC;AACxCC,QAAQ,uBAAuB,GAAG;AAClCA,QAAQ,yBAAyB,GAAG;AAEpC,IAAID;AAGJ,IAAIA;AAIG,SAASE,IAAIC,MAAM;IACxB,OAAOF,QAAQ,yBAAyB,GAAGE;AAC7C"}}]
} }
\ No newline at end of file
...@@ -640,31 +640,9 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot); ...@@ -640,31 +640,9 @@ const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot);
return ABSOLUTE_ROOT; return ABSOLUTE_ROOT;
} }
Context.prototype.P = resolveAbsolutePath; Context.prototype.P = resolveAbsolutePath;
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../shared/runtime/runtime-utils.ts" />
function readWebAssemblyAsResponse(path) {
const { createReadStream } = require('fs');
const { Readable } = require('stream');
const stream = createReadStream(path);
// @ts-ignore unfortunately there's a slight type mismatch with the stream.
return new Response(Readable.toWeb(stream), {
headers: {
'content-type': 'application/wasm'
}
});
}
async function compileWebAssemblyFromPath(path) {
const response = readWebAssemblyAsResponse(path);
return await WebAssembly.compileStreaming(response);
}
async function instantiateWebAssemblyFromPath(path, importsObj) {
const response = readWebAssemblyAsResponse(path);
const { instance } = await WebAssembly.instantiateStreaming(response, importsObj);
return instance.exports;
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../shared/runtime/runtime-utils.ts" /> /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../shared/runtime/runtime-utils.ts" />
/// <reference path="../../shared-node/base-externals-utils.ts" /> /// <reference path="../../shared-node/base-externals-utils.ts" />
/// <reference path="../../shared-node/node-externals-utils.ts" /> /// <reference path="../../shared-node/node-externals-utils.ts" />
/// <reference path="../../shared-node/node-wasm-utils.ts" />
/// <reference path="./nodejs-globals.d.ts" /> /// <reference path="./nodejs-globals.d.ts" />
/** /**
* Base Node.js runtime shared between production and development. * Base Node.js runtime shared between production and development.
...@@ -768,40 +746,30 @@ function loadChunkAsyncByUrl(chunkUrl) { ...@@ -768,40 +746,30 @@ function loadChunkAsyncByUrl(chunkUrl) {
return loadChunkAsync.call(this, path1); return loadChunkAsync.call(this, path1);
} }
contextPrototype.L = loadChunkAsyncByUrl; contextPrototype.L = loadChunkAsyncByUrl;
function loadWebAssembly(chunkPath, _edgeModule, imports) { /**
const resolved = path.resolve(RUNTIME_ROOT, chunkPath); * Returns the chunk path as-is. On Node.js, chunks are loaded by path.
return instantiateWebAssemblyFromPath(resolved, imports); */ function chunkUrl(chunkPath) {
return chunkPath;
} }
contextPrototype.w = loadWebAssembly; contextPrototype.w = chunkUrl;
function loadWebAssemblyModule(chunkPath, _edgeModule) { /**
const resolved = path.resolve(RUNTIME_ROOT, chunkPath); * Resolves a chunk path to an absolute filesystem path using RUNTIME_ROOT.
return compileWebAssemblyFromPath(resolved); */ function resolveChunkPath(chunkPath) {
return path.resolve(RUNTIME_ROOT, chunkPath);
} }
contextPrototype.u = loadWebAssemblyModule; contextPrototype.u = resolveChunkPath;
/** /**
* Creates a Node.js worker thread by instantiating the given WorkerConstructor * Returns the list of worker-forwarded global names.
* with the appropriate path and options, including forwarded globals. */ function forwardedGlobals() {
* return typeof WORKER_FORWARDED_GLOBALS !== 'undefined' ? WORKER_FORWARDED_GLOBALS : [];
* @param WorkerConstructor The Worker constructor from worker_threads }
* @param workerPath Path to the worker entry chunk contextPrototype.b = forwardedGlobals;
* @param workerOptions options to pass to the Worker constructor (optional) /**
*/ function createWorker(WorkerConstructor, workerPath, workerOptions) { * Returns the asset suffix (empty string on Node.js).
// Build the forwarded globals object */ function assetSuffix() {
const forwardedGlobals = {}; return '';
for (const name of WORKER_FORWARDED_GLOBALS){
forwardedGlobals[name] = globalThis[name];
}
// Merge workerData with forwarded globals
const existingWorkerData = workerOptions?.workerData || {};
const options = {
...workerOptions,
workerData: {
...typeof existingWorkerData === 'object' ? existingWorkerData : {},
__turbopack_globals__: forwardedGlobals
}
};
return new WorkerConstructor(workerPath, options);
} }
contextPrototype.X = assetSuffix;
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/; const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/** /**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment. * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
...@@ -821,7 +789,6 @@ nodeContextPrototype.M = moduleFactories; ...@@ -821,7 +789,6 @@ nodeContextPrototype.M = moduleFactories;
// Cast moduleCache to ModuleWithDirection for production mode // Cast moduleCache to ModuleWithDirection for production mode
nodeContextPrototype.c = moduleCache; nodeContextPrototype.c = moduleCache;
nodeContextPrototype.R = resolvePathFromModule; nodeContextPrototype.R = resolvePathFromModule;
nodeContextPrototype.b = createWorker;
nodeContextPrototype.C = clearChunkCache; nodeContextPrototype.C = clearChunkCache;
function instantiateModule(id, sourceType, sourceData) { function instantiateModule(id, sourceType, sourceData) {
const moduleFactory = moduleFactories.get(id); const moduleFactory = moduleFactories.get(id);
......
...@@ -732,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath; ...@@ -732,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath;
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/** /**
* Creates a worker by instantiating the given WorkerConstructor with the * Returns the full chunk URL for a chunk path, including CHUNK_BASE_PATH prefix
* appropriate URL and options. * and ASSET_SUFFIX. Used by extracted worker/wasm modules.
* */ function chunkUrl(chunkPath) {
* The entrypoint is a pre-compiled worker runtime file. The params configure return getChunkRelativeUrl(chunkPath);
* which module chunks to load and which module to run as the entry point. }
* browserContextPrototype.w = chunkUrl;
* The params are a JSON array of the following structure: /**
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]` * Returns the ASSET_SUFFIX string. Used by extracted worker modules.
* */ function assetSuffix() {
* @param WorkerConstructor The Worker or SharedWorker constructor return ASSET_SUFFIX;
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
} }
browserContextPrototype.b = createWorker; browserContextPrototype.X = assetSuffix;
/**
* Returns the list of worker-forwarded global names.
*/ function forwardedGlobals() {
return WORKER_FORWARDED_GLOBALS;
}
browserContextPrototype.b = forwardedGlobals;
/**
* Resolves a chunk path. On browser, returns the path as-is (not applicable).
*/ function resolveChunkPath(chunkPath) {
return chunkPath;
}
browserContextPrototype.u = resolveChunkPath;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -840,14 +826,6 @@ function isJs(chunkUrlOrPath) { ...@@ -840,14 +826,6 @@ function isJs(chunkUrlOrPath) {
function isCss(chunkUrl) { function isCss(chunkUrl) {
return endsWithExtension(chunkUrl, '.css'); return endsWithExtension(chunkUrl, '.css');
} }
function loadWebAssembly(chunkPath, edgeModule, importsObj) {
return BACKEND.loadWebAssembly(SourceType.Parent, this.m.id, chunkPath, edgeModule, importsObj);
}
contextPrototype.w = loadWebAssembly;
function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(SourceType.Parent, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
/// <reference path="./runtime-utils.ts" /> /// <reference path="./runtime-utils.ts" />
/// <reference path="./runtime-types.d.ts" /> /// <reference path="./runtime-types.d.ts" />
/// <reference path="./dev-extensions.ts" /> /// <reference path="./dev-extensions.ts" />
...@@ -2005,15 +1983,6 @@ let BACKEND; ...@@ -2005,15 +1983,6 @@ let BACKEND;
* has been loaded. * has been loaded.
*/ loadChunkCached (sourceType, chunkUrl) { */ loadChunkCached (sourceType, chunkUrl) {
return doLoadChunk(sourceType, chunkUrl); return doLoadChunk(sourceType, chunkUrl);
},
async loadWebAssembly (_sourceType, _sourceData, wasmChunkPath, _edgeModule, importsObj) {
const req = fetchWebAssembly(wasmChunkPath);
const { instance } = await WebAssembly.instantiateStreaming(req, importsObj);
return instance.exports;
},
async loadWebAssemblyModule (_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
} }
}; };
function getOrCreateResolver(chunkUrl) { function getOrCreateResolver(chunkUrl) {
...@@ -2126,9 +2095,6 @@ let BACKEND; ...@@ -2126,9 +2095,6 @@ let BACKEND;
resolver.loadingStarted = true; resolver.loadingStarted = true;
return resolver.promise; return resolver.promise;
} }
function fetchWebAssembly(wasmChunkPath) {
return fetch(getChunkRelativeUrl(wasmChunkPath));
}
})(); })();
/** /**
* This file contains the runtime code specific to the Turbopack development * This file contains the runtime code specific to the Turbopack development
......
...@@ -877,58 +877,6 @@ function _async_to_generator(fn) { ...@@ -877,58 +877,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 _object_spread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_define_property(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _object_spread_props(target, source) {
source = source != null ? source : {};
if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _ts_generator(thisArg, body) { function _ts_generator(thisArg, body) {
var f, y, t, _ = { var f, y, t, _ = {
label: 0, label: 0,
...@@ -1282,62 +1230,30 @@ browserContextPrototype.P = resolveAbsolutePath; ...@@ -1282,62 +1230,30 @@ browserContextPrototype.P = resolveAbsolutePath;
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/** /**
* Creates a worker by instantiating the given WorkerConstructor with the * Returns the full chunk URL for a chunk path, including CHUNK_BASE_PATH prefix
* appropriate URL and options. * and ASSET_SUFFIX. Used by extracted worker/wasm modules.
* */ function chunkUrl(chunkPath) {
* The entrypoint is a pre-compiled worker runtime file. The params configure return getChunkRelativeUrl(chunkPath);
* which module chunks to load and which module to run as the entry point. }
* browserContextPrototype.w = chunkUrl;
* The params are a JSON array of the following structure: /**
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]` * Returns the ASSET_SUFFIX string. Used by extracted worker modules.
* */ function assetSuffix() {
* @param WorkerConstructor The Worker or SharedWorker constructor return ASSET_SUFFIX;
* @param entrypoint URL path to the worker entrypoint chunk }
* @param moduleChunks list of module chunk paths to load browserContextPrototype.X = assetSuffix;
* @param workerOptions options to pass to the Worker constructor (optional) /**
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) { * Returns the list of worker-forwarded global names.
var isSharedWorker = WorkerConstructor.name === 'SharedWorker'; */ function forwardedGlobals() {
var chunkUrls = moduleChunks.map(function(chunk) { return WORKER_FORWARDED_GLOBALS;
return getChunkRelativeUrl(chunk);
}).reverse();
var params = [
chunkUrls,
ASSET_SUFFIX
];
var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
try {
for(var _iterator = WORKER_FORWARDED_GLOBALS[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
var globalName = _step.value;
params.push(globalThis[globalName]);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally{
if (_didIteratorError) {
throw _iteratorError;
}
}
}
var url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
var paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
var options = workerOptions ? _object_spread_props(_object_spread({}, workerOptions), {
type: undefined
}) : undefined;
return new WorkerConstructor(url, options);
} }
browserContextPrototype.b = createWorker; browserContextPrototype.b = forwardedGlobals;
/**
* Resolves a chunk path. On browser, returns the path as-is (not applicable).
*/ function resolveChunkPath(chunkPath) {
return chunkPath;
}
browserContextPrototype.u = resolveChunkPath;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -1354,8 +1270,8 @@ function getPathFromScript(chunkScript) { ...@@ -1354,8 +1270,8 @@ function getPathFromScript(chunkScript) {
if (typeof chunkScript === 'string') { if (typeof chunkScript === 'string') {
return chunkScript; return chunkScript;
} }
var chunkUrl = chunkScript.src; var _$chunkUrl = chunkScript.src;
var src = decodeURIComponent(chunkUrl.replace(/[?#].*$/, '')); var src = decodeURIComponent(_$chunkUrl.replace(/[?#].*$/, ''));
var path = src.startsWith(CHUNK_BASE_PATH) ? src.slice(CHUNK_BASE_PATH.length) : src; var path = src.startsWith(CHUNK_BASE_PATH) ? src.slice(CHUNK_BASE_PATH.length) : src;
return path; return path;
} }
...@@ -1410,14 +1326,6 @@ function isJs(chunkUrlOrPath) { ...@@ -1410,14 +1326,6 @@ function isJs(chunkUrlOrPath) {
function isCss(chunkUrl) { function isCss(chunkUrl) {
return endsWithExtension(chunkUrl, '.css'); return endsWithExtension(chunkUrl, '.css');
} }
function loadWebAssembly(chunkPath, edgeModule, importsObj) {
return BACKEND.loadWebAssembly(SourceType.Parent, this.m.id, chunkPath, edgeModule, importsObj);
}
contextPrototype.w = loadWebAssembly;
function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(SourceType.Parent, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
/// <reference path="./runtime-base.ts" /> /// <reference path="./runtime-base.ts" />
/// <reference path="./dummy.ts" /> /// <reference path="./dummy.ts" />
var moduleCache = {}; var moduleCache = {};
...@@ -1719,47 +1627,6 @@ var BACKEND; ...@@ -1719,47 +1627,6 @@ var BACKEND;
* has been loaded. * has been loaded.
*/ loadChunkCached: function loadChunkCached(sourceType, chunkUrl) { */ loadChunkCached: function loadChunkCached(sourceType, chunkUrl) {
return doLoadChunk(sourceType, chunkUrl); return doLoadChunk(sourceType, chunkUrl);
},
loadWebAssembly: function loadWebAssembly(_sourceType, _sourceData, wasmChunkPath, _edgeModule, importsObj) {
return _async_to_generator(function() {
var req, instance;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
req = fetchWebAssembly(wasmChunkPath);
return [
4,
WebAssembly.instantiateStreaming(req, importsObj)
];
case 1:
instance = _state.sent().instance;
return [
2,
instance.exports
];
}
});
})();
},
loadWebAssemblyModule: function loadWebAssemblyModule(_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
return _async_to_generator(function() {
var req;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
req = fetchWebAssembly(wasmChunkPath);
return [
4,
WebAssembly.compileStreaming(req)
];
case 1:
return [
2,
_state.sent()
];
}
});
})();
} }
}; };
function getOrCreateResolver(chunkUrl) { function getOrCreateResolver(chunkUrl) {
...@@ -1889,9 +1756,6 @@ var BACKEND; ...@@ -1889,9 +1756,6 @@ var BACKEND;
resolver.loadingStarted = true; resolver.loadingStarted = true;
return resolver.promise; return resolver.promise;
} }
function fetchWebAssembly(wasmChunkPath) {
return fetch(getChunkRelativeUrl(wasmChunkPath));
}
})(); })();
var chunksToRegister = globalThis["TURBOPACK"]; var chunksToRegister = globalThis["TURBOPACK"];
globalThis["TURBOPACK"] = { push: registerChunk }; globalThis["TURBOPACK"] = { push: registerChunk };
......
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1i9t_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_09-gc7x.js", "output/1i9t_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_0s9gn-l.js",
{"otherChunks":["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_input_0z18is9._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/[root-of-the-server]__08j45iv._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)"]}
]); ]);
(() => { (() => {
if (!Array.isArray(globalThis["TURBOPACK"])) { if (!Array.isArray(globalThis["TURBOPACK"])) {
...@@ -732,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath; ...@@ -732,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath;
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/** /**
* Creates a worker by instantiating the given WorkerConstructor with the * Returns the full chunk URL for a chunk path, including CHUNK_BASE_PATH prefix
* appropriate URL and options. * and ASSET_SUFFIX. Used by extracted worker/wasm modules.
* */ function chunkUrl(chunkPath) {
* The entrypoint is a pre-compiled worker runtime file. The params configure return getChunkRelativeUrl(chunkPath);
* which module chunks to load and which module to run as the entry point. }
* browserContextPrototype.w = chunkUrl;
* The params are a JSON array of the following structure: /**
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]` * Returns the ASSET_SUFFIX string. Used by extracted worker modules.
* */ function assetSuffix() {
* @param WorkerConstructor The Worker or SharedWorker constructor return ASSET_SUFFIX;
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
} }
browserContextPrototype.b = createWorker; browserContextPrototype.X = assetSuffix;
/**
* Returns the list of worker-forwarded global names.
*/ function forwardedGlobals() {
return WORKER_FORWARDED_GLOBALS;
}
browserContextPrototype.b = forwardedGlobals;
/**
* Resolves a chunk path. On browser, returns the path as-is (not applicable).
*/ function resolveChunkPath(chunkPath) {
return chunkPath;
}
browserContextPrototype.u = resolveChunkPath;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -840,14 +826,6 @@ function isJs(chunkUrlOrPath) { ...@@ -840,14 +826,6 @@ function isJs(chunkUrlOrPath) {
function isCss(chunkUrl) { function isCss(chunkUrl) {
return endsWithExtension(chunkUrl, '.css'); return endsWithExtension(chunkUrl, '.css');
} }
function loadWebAssembly(chunkPath, edgeModule, importsObj) {
return BACKEND.loadWebAssembly(SourceType.Parent, this.m.id, chunkPath, edgeModule, importsObj);
}
contextPrototype.w = loadWebAssembly;
function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(SourceType.Parent, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
/// <reference path="./runtime-utils.ts" /> /// <reference path="./runtime-utils.ts" />
/// <reference path="./runtime-types.d.ts" /> /// <reference path="./runtime-types.d.ts" />
/// <reference path="./dev-extensions.ts" /> /// <reference path="./dev-extensions.ts" />
...@@ -2005,15 +1983,6 @@ let BACKEND; ...@@ -2005,15 +1983,6 @@ let BACKEND;
* has been loaded. * has been loaded.
*/ loadChunkCached (sourceType, chunkUrl) { */ loadChunkCached (sourceType, chunkUrl) {
return doLoadChunk(sourceType, chunkUrl); return doLoadChunk(sourceType, chunkUrl);
},
async loadWebAssembly (_sourceType, _sourceData, wasmChunkPath, _edgeModule, importsObj) {
const req = fetchWebAssembly(wasmChunkPath);
const { instance } = await WebAssembly.instantiateStreaming(req, importsObj);
return instance.exports;
},
async loadWebAssemblyModule (_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
} }
}; };
function getOrCreateResolver(chunkUrl) { function getOrCreateResolver(chunkUrl) {
...@@ -2126,9 +2095,6 @@ let BACKEND; ...@@ -2126,9 +2095,6 @@ let BACKEND;
resolver.loadingStarted = true; resolver.loadingStarted = true;
return resolver.promise; return resolver.promise;
} }
function fetchWebAssembly(wasmChunkPath) {
return fetch(getChunkRelativeUrl(wasmChunkPath));
}
})(); })();
/** /**
* This file contains the runtime code specific to the Turbopack development * This file contains the runtime code specific to the Turbopack development
...@@ -2246,4 +2212,4 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2246,4 +2212,4 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_09-gc7x.js.map //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_workers_basic_input_index_0s9gn-l.js.map
\ No newline at end of file \ No newline at end of file
...@@ -732,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath; ...@@ -732,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath;
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/** /**
* Creates a worker by instantiating the given WorkerConstructor with the * Returns the full chunk URL for a chunk path, including CHUNK_BASE_PATH prefix
* appropriate URL and options. * and ASSET_SUFFIX. Used by extracted worker/wasm modules.
* */ function chunkUrl(chunkPath) {
* The entrypoint is a pre-compiled worker runtime file. The params configure return getChunkRelativeUrl(chunkPath);
* which module chunks to load and which module to run as the entry point. }
* browserContextPrototype.w = chunkUrl;
* The params are a JSON array of the following structure: /**
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]` * Returns the ASSET_SUFFIX string. Used by extracted worker modules.
* */ function assetSuffix() {
* @param WorkerConstructor The Worker or SharedWorker constructor return ASSET_SUFFIX;
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
} }
browserContextPrototype.b = createWorker; browserContextPrototype.X = assetSuffix;
/**
* Returns the list of worker-forwarded global names.
*/ function forwardedGlobals() {
return WORKER_FORWARDED_GLOBALS;
}
browserContextPrototype.b = forwardedGlobals;
/**
* Resolves a chunk path. On browser, returns the path as-is (not applicable).
*/ function resolveChunkPath(chunkPath) {
return chunkPath;
}
browserContextPrototype.u = resolveChunkPath;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -840,14 +826,6 @@ function isJs(chunkUrlOrPath) { ...@@ -840,14 +826,6 @@ function isJs(chunkUrlOrPath) {
function isCss(chunkUrl) { function isCss(chunkUrl) {
return endsWithExtension(chunkUrl, '.css'); return endsWithExtension(chunkUrl, '.css');
} }
function loadWebAssembly(chunkPath, edgeModule, importsObj) {
return BACKEND.loadWebAssembly(SourceType.Parent, this.m.id, chunkPath, edgeModule, importsObj);
}
contextPrototype.w = loadWebAssembly;
function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(SourceType.Parent, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
/// <reference path="./runtime-utils.ts" /> /// <reference path="./runtime-utils.ts" />
/// <reference path="./runtime-types.d.ts" /> /// <reference path="./runtime-types.d.ts" />
/// <reference path="./dev-extensions.ts" /> /// <reference path="./dev-extensions.ts" />
...@@ -2005,15 +1983,6 @@ let BACKEND; ...@@ -2005,15 +1983,6 @@ let BACKEND;
* has been loaded. * has been loaded.
*/ loadChunkCached (sourceType, chunkUrl) { */ loadChunkCached (sourceType, chunkUrl) {
return doLoadChunk(sourceType, chunkUrl); return doLoadChunk(sourceType, chunkUrl);
},
async loadWebAssembly (_sourceType, _sourceData, wasmChunkPath, _edgeModule, importsObj) {
const req = fetchWebAssembly(wasmChunkPath);
const { instance } = await WebAssembly.instantiateStreaming(req, importsObj);
return instance.exports;
},
async loadWebAssemblyModule (_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
} }
}; };
function getOrCreateResolver(chunkUrl) { function getOrCreateResolver(chunkUrl) {
...@@ -2126,9 +2095,6 @@ let BACKEND; ...@@ -2126,9 +2095,6 @@ let BACKEND;
resolver.loadingStarted = true; resolver.loadingStarted = true;
return resolver.promise; return resolver.promise;
} }
function fetchWebAssembly(wasmChunkPath) {
return fetch(getChunkRelativeUrl(wasmChunkPath));
}
})(); })();
/** /**
* This file contains the runtime code specific to the Turbopack development * This file contains the runtime code specific to the Turbopack development
......
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_input_0z18is9._.js", (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/[root-of-the-server]__08j45iv._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js (static in ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/worker.2-qnq-strt8dn.js");}), __turbopack_context__.q("/static/worker.2-qnq-strt8dn.js");}),
"[turbopack]/shared/worker-browser.ts [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
__turbopack_context__.s([
"createWorker",
()=>createWorker
]);
/**
* Browser worker creation module.
* Only included when a Web Worker or SharedWorker is actually used.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ 'use turbopack no side effects';
function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>__turbopack_chunk_url__(chunk)).reverse();
const params = [
chunkUrls,
__turbopack_asset_suffix__()
];
for (const globalName of __turbopack_forwarded_globals__()){
params.push(globalThis[globalName]);
}
const url = new URL(__turbopack_chunk_url__(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
var createWorker = __turbopack_context__.r("[turbopack]/shared/worker-browser.ts [test] (ecmascript)").createWorker;
__turbopack_context__.v(function(Ctor, opts) { __turbopack_context__.v(function(Ctor, opts) {
return __turbopack_context__.b(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_workers_basic_output_0uy0mni._.js", ["output/1do3_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ygioo.js","output/1i9t_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_0yr5fg0.js"], opts); return createWorker(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_workers_basic_output_0uy0mni._.js", ["output/1do3_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_11ygioo.js","output/1i9t_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_0yr5fg0.js"], opts);
}); });
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
...@@ -21,4 +58,4 @@ __turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapsh ...@@ -21,4 +58,4 @@ __turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapsh
}), }),
]); ]);
//# sourceMappingURL=turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_input_0z18is9._.js.map //# sourceMappingURL=%5Broot-of-the-server%5D__08j45iv._.js.map
\ No newline at end of file \ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 7, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/worker-browser.ts"],"sourcesContent":["/**\n * Browser worker creation module.\n * Only included when a Web Worker or SharedWorker is actually used.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n'use turbopack no side effects'\n\ndeclare function __turbopack_chunk_url__(chunkPath: string): string\ndeclare function __turbopack_forwarded_globals__(): string[]\ndeclare function __turbopack_asset_suffix__(): string\n\n/**\n * Creates a worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint URL path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nexport function createWorker(\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n entrypoint: string,\n moduleChunks: string[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n const chunkUrls = moduleChunks\n .map((chunk) => __turbopack_chunk_url__(chunk))\n .reverse()\n const params: unknown[] = [chunkUrls, __turbopack_asset_suffix__()]\n for (const globalName of __turbopack_forwarded_globals__()) {\n params.push((globalThis as Record<string, unknown>)[globalName])\n }\n\n const url = new URL(__turbopack_chunk_url__(entrypoint), location.origin)\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\n"],"names":["createWorker","WorkerConstructor","entrypoint","moduleChunks","workerOptions","isSharedWorker","name","chunkUrls","map","chunk","__turbopack_chunk_url__","reverse","params","__turbopack_asset_suffix__","globalName","__turbopack_forwarded_globals__","push","globalThis","url","URL","location","origin","paramsJson","JSON","stringify","searchParams","set","hash","encodeURIComponent","options","type","undefined"],"mappings":";;;;AAAA;;;CAGC,GAED,oDAAoD,GAEpD;AAqBO,SAASA,aACdC,iBAA+D,EAC/DC,UAAkB,EAClBC,YAAsB,EACtBC,aAAsB;IAEtB,MAAMC,iBAAiBJ,kBAAkBK,IAAI,KAAK;IAElD,MAAMC,YAAYJ,aACfK,GAAG,CAAC,CAACC,QAAUC,wBAAwBD,QACvCE,OAAO;IACV,MAAMC,SAAoB;QAACL;QAAWM;KAA6B;IACnE,KAAK,MAAMC,cAAcC,kCAAmC;QAC1DH,OAAOI,IAAI,CAAC,AAACC,UAAsC,CAACH,WAAW;IACjE;IAEA,MAAMI,MAAM,IAAIC,IAAIT,wBAAwBR,aAAakB,SAASC,MAAM;IACxE,MAAMC,aAAaC,KAAKC,SAAS,CAACZ;IAClC,IAAIP,gBAAgB;QAClBa,IAAIO,YAAY,CAACC,GAAG,CAAC,UAAUJ;IACjC,OAAO;QACLJ,IAAIS,IAAI,GAAG,aAAaC,mBAAmBN;IAC7C;IAEA,iFAAiF;IACjF,MAAMO,UAAUzB,gBACZ;QAAE,GAAGA,aAAa;QAAE0B,MAAMC;IAAU,IACpCA;IACJ,OAAO,IAAI9B,kBAAkBiB,KAAKW;AACpC","ignoreList":[0]}},
{"offset": {"line": 49, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js"],"sourcesContent":["console.log('index.js')\nconst url = new URL('./worker.js', import.meta.url)\nnew Worker(url)\n"],"names":["console","log","url","Worker"],"mappings":";;;;;AAAAA,QAAQC,GAAG,CAAC;AACZ,MAAMC;AACN,sJAAIC"}}]
}
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 12, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js"],"sourcesContent":["console.log('index.js')\nconst url = new URL('./worker.js', import.meta.url)\nnew Worker(url)\n"],"names":["console","log","url","Worker"],"mappings":";;;;;AAAAA,QAAQC,GAAG,CAAC;AACZ,MAAMC;AACN,sJAAIC"}}]
}
\ No newline at end of file
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/1i9t_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_0arnewp.js", "output/1i9t_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_1eutg7d.js",
{"otherChunks":["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_input_0g-vw3t._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/[root-of-the-server]__09q-mwc._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)"]}
]); ]);
(() => { (() => {
if (!Array.isArray(globalThis["TURBOPACK"])) { if (!Array.isArray(globalThis["TURBOPACK"])) {
...@@ -732,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath; ...@@ -732,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath;
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/** /**
* Creates a worker by instantiating the given WorkerConstructor with the * Returns the full chunk URL for a chunk path, including CHUNK_BASE_PATH prefix
* appropriate URL and options. * and ASSET_SUFFIX. Used by extracted worker/wasm modules.
* */ function chunkUrl(chunkPath) {
* The entrypoint is a pre-compiled worker runtime file. The params configure return getChunkRelativeUrl(chunkPath);
* which module chunks to load and which module to run as the entry point. }
* browserContextPrototype.w = chunkUrl;
* The params are a JSON array of the following structure: /**
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]` * Returns the ASSET_SUFFIX string. Used by extracted worker modules.
* */ function assetSuffix() {
* @param WorkerConstructor The Worker or SharedWorker constructor return ASSET_SUFFIX;
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
} }
browserContextPrototype.b = createWorker; browserContextPrototype.X = assetSuffix;
/**
* Returns the list of worker-forwarded global names.
*/ function forwardedGlobals() {
return WORKER_FORWARDED_GLOBALS;
}
browserContextPrototype.b = forwardedGlobals;
/**
* Resolves a chunk path. On browser, returns the path as-is (not applicable).
*/ function resolveChunkPath(chunkPath) {
return chunkPath;
}
browserContextPrototype.u = resolveChunkPath;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -840,14 +826,6 @@ function isJs(chunkUrlOrPath) { ...@@ -840,14 +826,6 @@ function isJs(chunkUrlOrPath) {
function isCss(chunkUrl) { function isCss(chunkUrl) {
return endsWithExtension(chunkUrl, '.css'); return endsWithExtension(chunkUrl, '.css');
} }
function loadWebAssembly(chunkPath, edgeModule, importsObj) {
return BACKEND.loadWebAssembly(SourceType.Parent, this.m.id, chunkPath, edgeModule, importsObj);
}
contextPrototype.w = loadWebAssembly;
function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(SourceType.Parent, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
/// <reference path="./runtime-utils.ts" /> /// <reference path="./runtime-utils.ts" />
/// <reference path="./runtime-types.d.ts" /> /// <reference path="./runtime-types.d.ts" />
/// <reference path="./dev-extensions.ts" /> /// <reference path="./dev-extensions.ts" />
...@@ -2005,15 +1983,6 @@ let BACKEND; ...@@ -2005,15 +1983,6 @@ let BACKEND;
* has been loaded. * has been loaded.
*/ loadChunkCached (sourceType, chunkUrl) { */ loadChunkCached (sourceType, chunkUrl) {
return doLoadChunk(sourceType, chunkUrl); return doLoadChunk(sourceType, chunkUrl);
},
async loadWebAssembly (_sourceType, _sourceData, wasmChunkPath, _edgeModule, importsObj) {
const req = fetchWebAssembly(wasmChunkPath);
const { instance } = await WebAssembly.instantiateStreaming(req, importsObj);
return instance.exports;
},
async loadWebAssemblyModule (_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
} }
}; };
function getOrCreateResolver(chunkUrl) { function getOrCreateResolver(chunkUrl) {
...@@ -2126,9 +2095,6 @@ let BACKEND; ...@@ -2126,9 +2095,6 @@ let BACKEND;
resolver.loadingStarted = true; resolver.loadingStarted = true;
return resolver.promise; return resolver.promise;
} }
function fetchWebAssembly(wasmChunkPath) {
return fetch(getChunkRelativeUrl(wasmChunkPath));
}
})(); })();
/** /**
* This file contains the runtime code specific to the Turbopack development * This file contains the runtime code specific to the Turbopack development
...@@ -2246,4 +2212,4 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2246,4 +2212,4 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_0arnewp.js.map //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_workers_shared_input_index_1eutg7d.js.map
\ No newline at end of file \ No newline at end of file
...@@ -732,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath; ...@@ -732,44 +732,30 @@ browserContextPrototype.P = resolveAbsolutePath;
} }
browserContextPrototype.q = exportUrl; browserContextPrototype.q = exportUrl;
/** /**
* Creates a worker by instantiating the given WorkerConstructor with the * Returns the full chunk URL for a chunk path, including CHUNK_BASE_PATH prefix
* appropriate URL and options. * and ASSET_SUFFIX. Used by extracted worker/wasm modules.
* */ function chunkUrl(chunkPath) {
* The entrypoint is a pre-compiled worker runtime file. The params configure return getChunkRelativeUrl(chunkPath);
* which module chunks to load and which module to run as the entry point. }
* browserContextPrototype.w = chunkUrl;
* The params are a JSON array of the following structure: /**
* `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]` * Returns the ASSET_SUFFIX string. Used by extracted worker modules.
* */ function assetSuffix() {
* @param WorkerConstructor The Worker or SharedWorker constructor return ASSET_SUFFIX;
* @param entrypoint URL path to the worker entrypoint chunk
* @param moduleChunks list of module chunk paths to load
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk)).reverse();
const params = [
chunkUrls,
ASSET_SUFFIX
];
for (const globalName of WORKER_FORWARDED_GLOBALS){
params.push(globalThis[globalName]);
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
} }
browserContextPrototype.b = createWorker; browserContextPrototype.X = assetSuffix;
/**
* Returns the list of worker-forwarded global names.
*/ function forwardedGlobals() {
return WORKER_FORWARDED_GLOBALS;
}
browserContextPrototype.b = forwardedGlobals;
/**
* Resolves a chunk path. On browser, returns the path as-is (not applicable).
*/ function resolveChunkPath(chunkPath) {
return chunkPath;
}
browserContextPrototype.u = resolveChunkPath;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -840,14 +826,6 @@ function isJs(chunkUrlOrPath) { ...@@ -840,14 +826,6 @@ function isJs(chunkUrlOrPath) {
function isCss(chunkUrl) { function isCss(chunkUrl) {
return endsWithExtension(chunkUrl, '.css'); return endsWithExtension(chunkUrl, '.css');
} }
function loadWebAssembly(chunkPath, edgeModule, importsObj) {
return BACKEND.loadWebAssembly(SourceType.Parent, this.m.id, chunkPath, edgeModule, importsObj);
}
contextPrototype.w = loadWebAssembly;
function loadWebAssemblyModule(chunkPath, edgeModule) {
return BACKEND.loadWebAssemblyModule(SourceType.Parent, this.m.id, chunkPath, edgeModule);
}
contextPrototype.u = loadWebAssemblyModule;
/// <reference path="./runtime-utils.ts" /> /// <reference path="./runtime-utils.ts" />
/// <reference path="./runtime-types.d.ts" /> /// <reference path="./runtime-types.d.ts" />
/// <reference path="./dev-extensions.ts" /> /// <reference path="./dev-extensions.ts" />
...@@ -2005,15 +1983,6 @@ let BACKEND; ...@@ -2005,15 +1983,6 @@ let BACKEND;
* has been loaded. * has been loaded.
*/ loadChunkCached (sourceType, chunkUrl) { */ loadChunkCached (sourceType, chunkUrl) {
return doLoadChunk(sourceType, chunkUrl); return doLoadChunk(sourceType, chunkUrl);
},
async loadWebAssembly (_sourceType, _sourceData, wasmChunkPath, _edgeModule, importsObj) {
const req = fetchWebAssembly(wasmChunkPath);
const { instance } = await WebAssembly.instantiateStreaming(req, importsObj);
return instance.exports;
},
async loadWebAssemblyModule (_sourceType, _sourceData, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
} }
}; };
function getOrCreateResolver(chunkUrl) { function getOrCreateResolver(chunkUrl) {
...@@ -2126,9 +2095,6 @@ let BACKEND; ...@@ -2126,9 +2095,6 @@ let BACKEND;
resolver.loadingStarted = true; resolver.loadingStarted = true;
return resolver.promise; return resolver.promise;
} }
function fetchWebAssembly(wasmChunkPath) {
return fetch(getChunkRelativeUrl(wasmChunkPath));
}
})(); })();
/** /**
* This file contains the runtime code specific to the Turbopack development * This file contains the runtime code specific to the Turbopack development
......
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_input_0g-vw3t._.js", (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/[root-of-the-server]__09q-mwc._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.q("/static/worker.1n36e5vaxakik.js");}), __turbopack_context__.q("/static/worker.1n36e5vaxakik.js");}),
"[turbopack]/shared/worker-browser.ts [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";
__turbopack_context__.s([
"createWorker",
()=>createWorker
]);
/**
* Browser worker creation module.
* Only included when a Web Worker or SharedWorker is actually used.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ 'use turbopack no side effects';
function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker';
const chunkUrls = moduleChunks.map((chunk)=>__turbopack_chunk_url__(chunk)).reverse();
const params = [
chunkUrls,
__turbopack_asset_suffix__()
];
for (const globalName of __turbopack_forwarded_globals__()){
params.push(globalThis[globalName]);
}
const url = new URL(__turbopack_chunk_url__(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
// Remove type: "module" from options since our worker entrypoint is not a module
const options = workerOptions ? {
...workerOptions,
type: undefined
} : undefined;
return new WorkerConstructor(url, options);
}
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
var createWorker = __turbopack_context__.r("[turbopack]/shared/worker-browser.ts [test] (ecmascript)").createWorker;
__turbopack_context__.v(function(Ctor, opts) { __turbopack_context__.v(function(Ctor, opts) {
return __turbopack_context__.b(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_workers_shared_output_0uy0mni._.js", ["output/1do3_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_1u1i0a1.js","output/1i9t_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_1xw116u.js"], opts); return createWorker(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_workers_shared_output_0uy0mni._.js", ["output/1do3_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_1u1i0a1.js","output/1i9t_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_1xw116u.js"], opts);
}); });
}), }),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { "[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
...@@ -20,4 +57,4 @@ __turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapsh ...@@ -20,4 +57,4 @@ __turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapsh
}), }),
]); ]);
//# sourceMappingURL=turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_input_0g-vw3t._.js.map //# sourceMappingURL=%5Broot-of-the-server%5D__09q-mwc._.js.map
\ No newline at end of file \ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 7, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/worker-browser.ts"],"sourcesContent":["/**\n * Browser worker creation module.\n * Only included when a Web Worker or SharedWorker is actually used.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n'use turbopack no side effects'\n\ndeclare function __turbopack_chunk_url__(chunkPath: string): string\ndeclare function __turbopack_forwarded_globals__(): string[]\ndeclare function __turbopack_asset_suffix__(): string\n\n/**\n * Creates a worker by instantiating the given WorkerConstructor with the\n * appropriate URL and options.\n *\n * The entrypoint is a pre-compiled worker runtime file. The params configure\n * which module chunks to load and which module to run as the entry point.\n *\n * The params are a JSON array of the following structure:\n * `[TURBOPACK_NEXT_CHUNK_URLS, ASSET_SUFFIX, ...WORKER_FORWARDED_GLOBALS values]`\n *\n * @param WorkerConstructor The Worker or SharedWorker constructor\n * @param entrypoint URL path to the worker entrypoint chunk\n * @param moduleChunks list of module chunk paths to load\n * @param workerOptions options to pass to the Worker constructor (optional)\n */\nexport function createWorker(\n WorkerConstructor: { new (url: URL, options?: object): Worker },\n entrypoint: string,\n moduleChunks: string[],\n workerOptions?: object\n): Worker {\n const isSharedWorker = WorkerConstructor.name === 'SharedWorker'\n\n const chunkUrls = moduleChunks\n .map((chunk) => __turbopack_chunk_url__(chunk))\n .reverse()\n const params: unknown[] = [chunkUrls, __turbopack_asset_suffix__()]\n for (const globalName of __turbopack_forwarded_globals__()) {\n params.push((globalThis as Record<string, unknown>)[globalName])\n }\n\n const url = new URL(__turbopack_chunk_url__(entrypoint), location.origin)\n const paramsJson = JSON.stringify(params)\n if (isSharedWorker) {\n url.searchParams.set('params', paramsJson)\n } else {\n url.hash = '#params=' + encodeURIComponent(paramsJson)\n }\n\n // Remove type: \"module\" from options since our worker entrypoint is not a module\n const options = workerOptions\n ? { ...workerOptions, type: undefined }\n : undefined\n return new WorkerConstructor(url, options)\n}\n"],"names":["createWorker","WorkerConstructor","entrypoint","moduleChunks","workerOptions","isSharedWorker","name","chunkUrls","map","chunk","__turbopack_chunk_url__","reverse","params","__turbopack_asset_suffix__","globalName","__turbopack_forwarded_globals__","push","globalThis","url","URL","location","origin","paramsJson","JSON","stringify","searchParams","set","hash","encodeURIComponent","options","type","undefined"],"mappings":";;;;AAAA;;;CAGC,GAED,oDAAoD,GAEpD;AAqBO,SAASA,aACdC,iBAA+D,EAC/DC,UAAkB,EAClBC,YAAsB,EACtBC,aAAsB;IAEtB,MAAMC,iBAAiBJ,kBAAkBK,IAAI,KAAK;IAElD,MAAMC,YAAYJ,aACfK,GAAG,CAAC,CAACC,QAAUC,wBAAwBD,QACvCE,OAAO;IACV,MAAMC,SAAoB;QAACL;QAAWM;KAA6B;IACnE,KAAK,MAAMC,cAAcC,kCAAmC;QAC1DH,OAAOI,IAAI,CAAC,AAACC,UAAsC,CAACH,WAAW;IACjE;IAEA,MAAMI,MAAM,IAAIC,IAAIT,wBAAwBR,aAAakB,SAASC,MAAM;IACxE,MAAMC,aAAaC,KAAKC,SAAS,CAACZ;IAClC,IAAIP,gBAAgB;QAClBa,IAAIO,YAAY,CAACC,GAAG,CAAC,UAAUJ;IACjC,OAAO;QACLJ,IAAIS,IAAI,GAAG,aAAaC,mBAAmBN;IAC7C;IAEA,iFAAiF;IACjF,MAAMO,UAAUzB,gBACZ;QAAE,GAAGA,aAAa;QAAE0B,MAAMC;IAAU,IACpCA;IACJ,OAAO,IAAI9B,kBAAkBiB,KAAKW;AACpC","ignoreList":[0]}},
{"offset": {"line": 49, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js"],"sourcesContent":["const url = new URL('./worker.js', import.meta.url)\nnew SharedWorker(url)\n"],"names":["url","SharedWorker"],"mappings":";;;;;AAAA,MAAMA;AACN,uJAAIC"}}]
}
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 12, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js"],"sourcesContent":["const url = new URL('./worker.js', import.meta.url)\nnew SharedWorker(url)\n"],"names":["url","SharedWorker"],"mappings":";;;;;AAAA,MAAMA;AACN,uJAAIC"}}]
}
\ No newline at end of file
...@@ -5,18 +5,34 @@ use indoc::{formatdoc, writedoc}; ...@@ -5,18 +5,34 @@ use indoc::{formatdoc, writedoc};
use turbo_rcstr::RcStr; use turbo_rcstr::RcStr;
use turbo_tasks::Vc; use turbo_tasks::Vc;
use turbo_tasks_fs::{File, FileContent}; use turbo_tasks_fs::{File, FileContent};
use turbopack_core::{asset::AssetContent, source::Source, virtual_source::VirtualSource}; use turbopack_core::{
asset::AssetContent, context::AssetContext, environment::ChunkLoading, source::Source,
virtual_source::VirtualSource,
};
use turbopack_ecmascript::utils::StringifyJs; use turbopack_ecmascript::utils::StringifyJs;
use crate::{analysis::analyze, source::WebAssemblySource, wasm_edge_var_name}; use crate::{analysis::analyze, source::WebAssemblySource, wasm_edge_var_name};
/// Determines the `@turbopack/wasm-*` module name based on the environment.
async fn wasm_module_name(asset_context: Vc<Box<dyn AssetContext>>) -> Result<&'static str> {
let environment = asset_context.compile_time_info().environment();
let chunk_loading = &*environment.chunk_loading().await?;
Ok(match chunk_loading {
ChunkLoading::NodeJs => "@turbopack/wasm-node",
ChunkLoading::Edge => "@turbopack/wasm-edge",
ChunkLoading::Dom => "@turbopack/wasm-dom",
})
}
/// Create a javascript loader to instantiate the WebAssembly module with the /// Create a javascript loader to instantiate the WebAssembly module with the
/// necessary imports and exports to be processed by [turbopack_ecmascript]. /// necessary imports and exports to be processed by [turbopack_ecmascript].
#[turbo_tasks::function] #[turbo_tasks::function]
pub(crate) async fn instantiating_loader_source( pub(crate) async fn instantiating_loader_source(
source: Vc<WebAssemblySource>, source: Vc<WebAssemblySource>,
asset_context: Vc<Box<dyn AssetContext>>,
) -> Result<Vc<Box<dyn Source>>> { ) -> Result<Vc<Box<dyn Source>>> {
let analysis = analyze(source).await?; let analysis = analyze(source).await?;
let wasm_module = wasm_module_name(asset_context).await?;
let mut code = String::new(); let mut code = String::new();
...@@ -37,6 +53,11 @@ pub(crate) async fn instantiating_loader_source( ...@@ -37,6 +53,11 @@ pub(crate) async fn instantiating_loader_source(
} }
writeln!(imports_obj, "}}")?; writeln!(imports_obj, "}}")?;
writeln!(
code,
"import {{ instantiateWebAssembly }} from {:?};",
wasm_module
)?;
writeln!(code, "import wasmPath from \"WASM_PATH\";")?; writeln!(code, "import wasmPath from \"WASM_PATH\";")?;
writeln!(code)?; writeln!(code)?;
...@@ -44,7 +65,7 @@ pub(crate) async fn instantiating_loader_source( ...@@ -44,7 +65,7 @@ pub(crate) async fn instantiating_loader_source(
writedoc!( writedoc!(
code, code,
r#" r#"
const {{ {exports} }} = await __turbopack_wasm__(wasmPath, () => {edgeVariable}, {imports}); const {{ {exports} }} = await instantiateWebAssembly(wasmPath, () => {edgeVariable}, {imports});
export {{ {exports} }}; export {{ {exports} }};
"#, "#,
...@@ -66,15 +87,20 @@ pub(crate) async fn instantiating_loader_source( ...@@ -66,15 +87,20 @@ pub(crate) async fn instantiating_loader_source(
#[turbo_tasks::function] #[turbo_tasks::function]
pub(crate) async fn compiling_loader_source( pub(crate) async fn compiling_loader_source(
source: Vc<WebAssemblySource>, source: Vc<WebAssemblySource>,
asset_context: Vc<Box<dyn AssetContext>>,
) -> Result<Vc<Box<dyn Source>>> { ) -> Result<Vc<Box<dyn Source>>> {
let wasm_module = wasm_module_name(asset_context).await?;
let code: RcStr = formatdoc! { let code: RcStr = formatdoc! {
r#" r#"
import {{ compileWebAssembly }} from {:?};
import wasmPath from "WASM_PATH"; import wasmPath from "WASM_PATH";
const mod = await __turbopack_wasm_module__(wasmPath, () => {edgeVariable}); const mod = await compileWebAssembly(wasmPath, () => {edgeVariable});
export default mod; export default mod;
"#, "#,
wasm_module,
edgeVariable = wasm_edge_var_name(Vc::upcast(source)).await? edgeVariable = wasm_edge_var_name(Vc::upcast(source)).await?
} }
.into(); .into();
......
...@@ -63,9 +63,9 @@ impl WebAssemblyModuleAsset { ...@@ -63,9 +63,9 @@ impl WebAssemblyModuleAsset {
let query = &self.source.ident().await?.query; let query = &self.source.ident().await?.query;
let loader_source = if query == "?module" { let loader_source = if query == "?module" {
compiling_loader_source(*self.source) compiling_loader_source(*self.source, *self.asset_context)
} else { } else {
instantiating_loader_source(*self.source) instantiating_loader_source(*self.source, *self.asset_context)
}; };
let module = self.asset_context.process( let module = self.asset_context.process(
......
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