Unverified Commit a1c12562 authored by Matt Mastracci's avatar Matt Mastracci Committed by GitHub

Turbopack: Pass globals to node.js workers as well (#89261)

## What

Changes how Turbopack creates Web Workers and Worker Threads to use a unified factory function pattern. Workers now receive the same runtime globals (like `NEXT_DEPLOYMENT_ID` and `NEXT_CLIENT_ASSET_SUFFIX`) as the parent context, and asset loading works correctly inside workers.

## Why

Previously, worker creation was split between compile-time URL generation and runtime initialization, which made it difficult to:
- Forward runtime globals to worker contexts
- Ensure workers could load chunked assets with the correct suffix
- Maintain consistent initialization logic across browser and Node.js workers

This caused issues when workers needed to dynamically import assets or access deployment-specific configuration.

## How

Worker loader modules now export a factory function that receives the Worker constructor and options, rather than just a URL. The runtime handles all worker initialization, including forwarding necessary globals. This keeps all worker creation logic in a single place (the runtime) rather than being split between Rust code generation and JavaScript execution.

Tests added for PNG asset loading in workers to verify the asset suffix forwarding works correctly in both browser and Node.js contexts.
parent 869b45ef
......@@ -71,7 +71,7 @@ use crate::{
util::{
OptionEnvMap, defines, foreign_code_context_condition,
free_var_references_with_vercel_system_env_warnings, internal_assets_conditions,
module_styles_rule_condition,
module_styles_rule_condition, worker_forwarded_globals,
},
};
......@@ -503,7 +503,7 @@ pub async fn get_client_chunking_context(
.debug_ids(*debug_ids.await?)
.should_use_absolute_url_references(*should_use_absolute_url_references.await?)
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(vec![rcstr!("NEXT_DEPLOYMENT_ID")]);
.worker_forwarded_globals(worker_forwarded_globals());
if next_mode.is_development() {
builder = builder
......
......@@ -33,7 +33,7 @@ use crate::{
},
util::{
NextRuntime, OptionEnvMap, defines, foreign_code_context_condition,
free_var_references_with_vercel_system_env_warnings,
free_var_references_with_vercel_system_env_warnings, worker_forwarded_globals,
},
};
......@@ -273,7 +273,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
.export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?)
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(vec![rcstr!("NEXT_DEPLOYMENT_ID")]);
.worker_forwarded_globals(worker_forwarded_globals());
if !next_mode.is_development() {
builder = builder
......@@ -357,7 +357,7 @@ pub async fn get_edge_chunking_context(
.export_usage(*export_usage.await?)
.unused_references(unused_references.to_resolved().await?)
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(vec![rcstr!("NEXT_DEPLOYMENT_ID")]);
.worker_forwarded_globals(worker_forwarded_globals());
if !next_mode.is_development() {
builder = builder
......
......@@ -75,6 +75,7 @@ use crate::{
NextRuntime, OptionEnvMap, defines, foreign_code_context_condition,
free_var_references_with_vercel_system_env_warnings, get_transpiled_packages,
internal_assets_conditions, load_next_js_jsonc_file, module_styles_rule_condition,
worker_forwarded_globals,
},
};
......@@ -1094,7 +1095,8 @@ pub async fn get_server_chunking_context_with_client_assets(
.unused_references(unused_references.to_resolved().await?)
.file_tracing(next_mode.is_production())
.debug_ids(*debug_ids.await?)
.nested_async_availability(*nested_async_chunking.await?);
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals());
builder = builder.source_map_source_type(if next_mode.is_development() {
SourceMapSourceType::AbsoluteFileUri
......@@ -1184,7 +1186,8 @@ pub async fn get_server_chunking_context(
.unused_references(unused_references.to_resolved().await?)
.file_tracing(next_mode.is_production())
.debug_ids(*debug_ids.await?)
.nested_async_availability(*nested_async_chunking.await?);
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals());
if next_mode.is_development() {
builder = builder.source_map_source_type(SourceMapSourceType::AbsoluteFileUri);
......
......@@ -555,3 +555,13 @@ pub fn module_styles_rule_condition() -> RuleCondition {
RuleCondition::ContentTypeStartsWith("text/scss+module".into()),
])
}
/// Returns the list of global variables that should be forwarded from the main
/// context to web workers. These are Next.js-specific globals that need to be
/// available in worker contexts.
pub fn worker_forwarded_globals() -> Vec<RcStr> {
vec![
rcstr!("NEXT_DEPLOYMENT_ID"),
rcstr!("NEXT_CLIENT_ASSET_SUFFIX"),
]
}
import { Worker } from 'node:worker_threads'
import { NextResponse } from 'next/server'
interface PngInfo {
url: string
width: number
height: number
}
export async function GET() {
try {
const worker = new Worker('./app/worker-dir/png-worker.ts')
const pngInfo = await new Promise<PngInfo>((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error('Worker timeout'))
}, 5000)
worker.on('message', (msg: PngInfo) => {
clearTimeout(timeout)
resolve(msg)
})
worker.on('error', (err) => {
clearTimeout(timeout)
reject(err)
})
worker.on('exit', (code) => {
if (code !== 0) {
clearTimeout(timeout)
reject(new Error(`Worker stopped with exit code ${code}`))
}
})
worker.postMessage('get-png-info')
})
await worker.terminate()
return NextResponse.json({ success: true, pngInfo })
} catch (error) {
return NextResponse.json(
{ success: false, error: String(error) },
{ status: 500 }
)
}
}
import { Worker } from 'node:worker_threads'
export async function GET() {
try {
const worker = new Worker('./app/worker-dir/workerdata-check-worker.ts')
const result = await new Promise<{
workerDataKeys: string[]
hasTurbopackKeys: boolean
turbopackKeys: string[]
}>((resolve, reject) => {
worker.on('message', resolve)
worker.on('error', reject)
})
await worker.terminate()
return Response.json({
success: true,
...result,
})
} catch (error) {
return Response.json(
{ success: false, error: String(error) },
{ status: 500 }
)
}
}
import { parentPort } from 'node:worker_threads'
import pngUrl from './test-image.png'
if (parentPort) {
parentPort.on('message', (msg) => {
if (msg === 'get-png-info') {
// Return the PNG info - the URL will be fetched by the client
// to verify it's correctly formed and accessible
parentPort!.postMessage({
url: pngUrl.src,
width: pngUrl.width,
height: pngUrl.height,
})
}
})
}
import { parentPort, workerData } from 'node:worker_threads'
if (parentPort) {
// Check if any __turbopack prefixed keys are visible in workerData
const turbopackKeys = Object.keys(workerData || {}).filter((key) =>
key.startsWith('__turbopack')
)
parentPort.postMessage({
workerDataKeys: Object.keys(workerData || {}),
hasTurbopackKeys: turbopackKeys.length > 0,
turbopackKeys,
})
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
deploymentId: 'test-deployment-id',
}
module.exports = nextConfig
......@@ -48,4 +48,52 @@ describe('node-worker-threads', () => {
expect(res.status).toBe(200)
expect(data.success).toBe(true)
})
it('should not expose __turbopack internal workerData to user code', async () => {
// Verify that internal __turbopack_globals__ data used to forward globals
// is not visible to user code accessing workerData
const res = await next.fetch('/api/workerdata-check')
const data = await res.json()
console.log('WorkerData check response:', data)
expect(res.status).toBe(200)
expect(data.success).toBe(true)
// The __turbopack_globals__ key should NOT be visible to user code
expect(data.hasTurbopackKeys).toBe(false)
expect(data.turbopackKeys).toEqual([])
})
it('should handle PNG file import in worker', async () => {
// Test that static assets (like PNG images) can be imported and used in workers
// The server worker returns the PNG URL, then we fetch it from the client
// to verify the URL is correctly formed and accessible
const res = await next.fetch('/api/png-worker-test')
const data = await res.json()
expect(res.status).toBe(200)
expect(data.success).toBe(true)
expect(data.pngInfo).toBeDefined()
expect(data.pngInfo.width).toBe(1)
expect(data.pngInfo.height).toBe(1)
// Verify the URL is a valid static asset URL with Next.js format
expect(data.pngInfo.url).toContain('/_next/static/')
expect(data.pngInfo.url).toContain('test-image')
expect(data.pngInfo.url).toContain('.png')
// Verify the URL includes the deployment ID suffix (dpl=)
// This tests that NEXT_CLIENT_ASSET_SUFFIX is correctly applied in the worker
expect(data.pngInfo.url).toContain('dpl=test-deployment-id')
// Now fetch the PNG URL from the client to verify it's accessible
// This tests that the URL generated by the server worker is correct
const pngRes = await next.fetch(data.pngInfo.url)
expect(pngRes.status).toBe(200)
expect(pngRes.headers.get('content-type')).toBe('image/png')
// Log for visual inspection
console.log('Node.js Worker PNG verification:', {
url: data.pngInfo.url,
hasDplSuffix: data.pngInfo.url.includes('dpl='),
clientFetchStatus: pngRes.status,
clientFetchContentType: pngRes.headers.get('content-type'),
})
})
})
// Use dynamic import to test that chunk loading works in worker
// This exercises the ASSET_SUFFIX mechanism for loading chunks
async function verifyPng() {
const pngModule = await import('./test-image.png')
const pngUrl = pngModule.default
const fullUrl = new URL(pngUrl.src, location.origin).toString()
const response = await fetch(fullUrl)
const contentType = response.headers.get('content-type')
const contentLength = response.headers.get('content-length')
self.postMessage({
url: pngUrl.src,
width: pngUrl.width,
height: pngUrl.height,
// Verification that we actually fetched it
fetchedFrom: fullUrl,
contentType,
contentLength: contentLength ? parseInt(contentLength, 10) : null,
status: response.status,
})
}
verifyPng()
'use client'
import { useState } from 'react'
export default function Home() {
const [pngInfo, setPngInfo] = useState(null)
return (
<div>
<button
onClick={() => {
const worker = new Worker(new URL('../png-worker', import.meta.url), {
type: 'module',
})
worker.addEventListener('message', (event) => {
setPngInfo(event.data)
})
}}
>
Get PNG info from worker
</button>
<p>
PNG URL: <span id="png-url">{pngInfo?.url ?? 'default'}</span>
</p>
<p>
PNG Width: <span id="png-width">{pngInfo?.width ?? 'default'}</span>
</p>
<p>
PNG Height: <span id="png-height">{pngInfo?.height ?? 'default'}</span>
</p>
<p>
Fetched From:{' '}
<span id="fetched-from">{pngInfo?.fetchedFrom ?? 'default'}</span>
</p>
<p>
Content-Type:{' '}
<span id="content-type">{pngInfo?.contentType ?? 'default'}</span>
</p>
<p>
Fetch Status:{' '}
<span id="fetch-status">{pngInfo?.status ?? 'default'}</span>
</p>
</div>
)
}
......@@ -17,7 +17,7 @@ describe('app dir - workers', () => {
const url = request.url()
// TODO fix deployment id for webpack
if (isTurbopack) {
if (url.includes('_next') && !url.includes('wasm')) {
if (url.includes('/_next/') && !url.includes('wasm')) {
expect(url).toMatch(/^[^?]+\?(v=\d+&)?dpl=test-deployment-id$/)
}
}
......@@ -131,4 +131,51 @@ describe('app dir - workers', () => {
)
)
})
it('should support loading PNG files in web workers', async () => {
const browser = await next.browser('/png', {
beforePageLoad,
})
// Initial state should be default
expect(await browser.elementByCss('#png-url').text()).toBe('default')
// Trigger worker to get PNG info
await browser.elementByCss('button').click()
// Wait for worker to respond and verify PNG info
await retry(async () => {
const pngUrl = await browser.elementByCss('#png-url').text()
expect(pngUrl).toContain('test-image')
expect(pngUrl).toContain('.png')
})
await retry(async () => {
const pngWidth = await browser.elementByCss('#png-width').text()
expect(pngWidth).toBe('1')
})
await retry(async () => {
const pngHeight = await browser.elementByCss('#png-height').text()
expect(pngHeight).toBe('1')
})
// Verify the worker actually fetched the PNG (proves asset URL works in worker)
await retry(async () => {
const fetchStatus = await browser.elementByCss('#fetch-status').text()
expect(fetchStatus).toBe('200')
})
await retry(async () => {
const contentType = await browser.elementByCss('#content-type').text()
expect(contentType).toBe('image/png')
})
// Log the full verification info for visual inspection
const fetchedFrom = await browser.elementByCss('#fetched-from').text()
console.log('Web Worker PNG verification:', {
fetchedFrom,
contentType: await browser.elementByCss('#content-type').text(),
status: await browser.elementByCss('#fetch-status').text(),
})
})
})
......@@ -335,22 +335,28 @@ function exportUrl(
browserContextPrototype.q = exportUrl
/**
* Returns a URL for the worker.
* 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 shared whether this is a SharedWorker (uses querystring for URL identity)
* @param workerOptions options to pass to the Worker constructor (optional)
*/
function getWorkerURL(
function createWorker(
WorkerConstructor: { new (url: URL, options?: object): Worker },
entrypoint: ChunkPath,
moduleChunks: ChunkPath[],
shared: boolean
): URL {
workerOptions?: object
): Worker {
const isSharedWorker = WorkerConstructor.name === 'SharedWorker'
const chunkUrls = moduleChunks
.map((chunk) => getChunkRelativeUrl(chunk))
.reverse()
......@@ -361,14 +367,19 @@ function getWorkerURL(
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin)
const paramsJson = JSON.stringify(params)
if (shared) {
if (isSharedWorker) {
url.searchParams.set('params', paramsJson)
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson)
}
return url
// 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 = getWorkerURL
browserContextPrototype.b = createWorker
/**
* Instantiates a runtime module.
......
......@@ -191,15 +191,39 @@ function loadWebAssemblyModule(
}
contextPrototype.u = loadWebAssemblyModule
function getWorkerURL(
_entrypoint: ChunkPath,
_moduleChunks: ChunkPath[],
_shared: boolean
): URL {
throw new Error('Worker urls are not implemented yet for Node.js')
/**
* 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)
*/
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 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)
}
nodeContextPrototype.b = getWorkerURL
nodeContextPrototype.b = createWorker
function instantiateModule(
id: ModuleId,
......
......@@ -2,7 +2,7 @@ use anyhow::Result;
use bincode::{Decode, Encode};
use swc_core::{
common::util::take::Take,
ecma::ast::{Expr, ExprOrSpread, Lit, NewExpr},
ecma::ast::{CallExpr, Callee, Expr, ExprOrSpread, Lit},
quote_expr,
};
use turbo_rcstr::{RcStr, rcstr};
......@@ -341,34 +341,38 @@ impl WorkerAssetReferenceCodeGen {
)
.await?;
// Transform `new Worker(url, opts)` into `require(id)(Worker, opts)`
// The loader module exports a function that creates the worker with all necessary
// configuration (entrypoint, chunks, forwarded globals, etc.)
let visitor = create_visitor!(self.path, visit_mut_expr, |expr: &mut Expr| {
let message = if let Expr::New(NewExpr { args, .. }) = expr {
if let Some(args) = args {
let message = if let Expr::New(new_expr) = expr {
if let Some(args) = &mut new_expr.args {
match args.first_mut() {
Some(ExprOrSpread {
spread: None,
expr: key_expr,
expr: url_expr,
}) => {
// Replace the first argument (the URL/path) with a turbopack_require
// call that uses the pattern mapping to resolve to the correct loader
// module
*key_expr = quote_expr!(
"$require",
require: Expr = pm.create_require(*key_expr.take())
);
// Get the Worker constructor (callee)
let constructor = new_expr.callee.take();
// For web workers, remove type: "module" if it exists
if matches!(
reference.worker_type,
WorkerType::WebWorker | WorkerType::SharedWebWorker
) && let Some(opts) = args.get_mut(1)
&& opts.spread.is_none()
{
*opts.expr = *quote_expr!(
"{...$opts, type: undefined}",
opts: Expr = (*opts.expr).take()
);
}
// Build the require call for the loader module
let require_call = pm.create_require(*url_expr.take());
// Build the arguments: (WorkerConstructor, ...rest_args)
let mut call_args = vec![ExprOrSpread {
spread: None,
expr: constructor,
}];
// Add any remaining arguments (e.g., worker options)
call_args.extend(args.drain(1..));
// Transform to: require(id)(Worker, opts)
*expr = Expr::Call(CallExpr {
span: new_expr.span,
callee: Callee::Expr(Box::new(require_call)),
args: call_args,
..Default::default()
});
return;
}
// These are SWC bugs: https://github.com/swc-project/swc/issues/5394
......
......@@ -83,7 +83,7 @@ pub const TURBOPACK_DYNAMIC: &TurbopackRuntimeFunctionShortcut = make_shortcut!(
pub const TURBOPACK_RESOLVE_ABSOLUTE_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("P");
pub const TURBOPACK_RELATIVE_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("U");
pub const TURBOPACK_RESOLVE_MODULE_ID_PATH: &TurbopackRuntimeFunctionShortcut = make_shortcut!("R");
pub const TURBOPACK_WORKER_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("b");
pub const TURBOPACK_CREATE_WORKER: &TurbopackRuntimeFunctionShortcut = make_shortcut!("b");
pub const TURBOPACK_ASYNC_MODULE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("a");
pub const TURBOPACK_EXTERNAL_REQUIRE: &TurbopackRuntimeFunctionShortcut = make_shortcut!("x");
pub const TURBOPACK_EXTERNAL_IMPORT: &TurbopackRuntimeFunctionShortcut = make_shortcut!("y");
......@@ -117,7 +117,7 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio
"__turbopack_resolve_module_id_path__",
TURBOPACK_RESOLVE_MODULE_ID_PATH,
),
("__turbopack_worker_url__", TURBOPACK_WORKER_URL),
("__turbopack_create_worker__", TURBOPACK_CREATE_WORKER),
("__turbopack_external_require__", TURBOPACK_EXTERNAL_REQUIRE),
("__turbopack_external_import__", TURBOPACK_EXTERNAL_IMPORT),
("__turbopack_refresh__", TURBOPACK_REFRESH),
......
......@@ -20,7 +20,7 @@ use crate::{
EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkType,
data::EcmascriptChunkData,
},
runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_WORKER_URL},
runtime_functions::{TURBOPACK_CREATE_WORKER, TURBOPACK_EXPORT_VALUE},
utils::StringifyJs,
};
......@@ -117,10 +117,30 @@ impl EcmascriptChunkItem for WorkerLoaderChunkItem {
) -> Result<Vc<EcmascriptChunkItemContent>> {
let this = self.await?;
if estimated {
// In estimation mode we cannot call into chunking context APIs
// otherwise we will induce a turbo tasks cycle. But we only need an
// approximate solution. We'll use the same estimate for both web
// and Node.js workers.
return Ok(EcmascriptChunkItemContent {
inner_code: formatdoc! {
r#"
{TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{
return {TURBOPACK_CREATE_WORKER}(Ctor, __dirname + "/" + {worker_path:#}, opts);
}});
"#,
worker_path = StringifyJs(&"a_fake_path_for_size_estimation"),
}.into(),
..Default::default()
}
.cell());
}
let code = match this.worker_type {
WorkerType::WebWorker | WorkerType::SharedWebWorker => {
// For web workers, generate code that creates a worker URL using the real
// entrypoint
// For web workers, generate code that exports a function to create the worker.
// The function takes (WorkerConstructor, workerOptions) and calls createWorker
// with the entrypoint and chunks baked in.
let entrypoint_full_path = this.chunking_context.worker_entrypoint().path().await?;
// Get the entrypoint path relative to output root
......@@ -138,55 +158,46 @@ impl EcmascriptChunkItem for WorkerLoaderChunkItem {
.map(|chunk_data| EcmascriptChunkData::new(chunk_data))
.collect();
// Determine if this is a SharedWorker
let is_shared = matches!(this.worker_type, WorkerType::SharedWebWorker);
formatdoc! {
r#"
{TURBOPACK_EXPORT_VALUE}({TURBOPACK_WORKER_URL}({entrypoint}, {chunks}, {shared}));
{TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{
return {TURBOPACK_CREATE_WORKER}(Ctor, {entrypoint}, {chunks}, opts);
}});
"#,
entrypoint = StringifyJs(&entrypoint_path),
chunks = StringifyJs(&chunks_data),
shared = is_shared,
}
}
WorkerType::NodeWorkerThread => {
// For Node.js workers, export the path to the worker entry chunk
if estimated {
// In estimation mode we cannot call into chunking context APIs otherwise we
// will induce a turbo tasks cycle. But we only need an approximate solution.
formatdoc! {
r#"
{TURBOPACK_EXPORT_VALUE}(__dirname + "/" + {worker_path:#});
"#,
worker_path = StringifyJs(&"a_fake_path_for_size_estimation"),
}
} else {
let chunk_group = self.chunk_group().await?;
let assets = chunk_group.assets.await?;
// The last asset is the evaluate chunk (entry point) for the worker.
// The evaluated_chunk_group adds regular chunks first, then pushes the
// evaluate chunk last. The evaluate chunk contains the bootstrap code that
// loads the runtime and other chunks. For Node.js workers, we need a single
// file path (not a blob URL like browser workers), so we use the evaluate
// chunk which serves as the entry point.
let Some(entry_asset) = assets.last() else {
bail!("cannot find worker entry point asset");
};
let entry_path = entry_asset.path().await?;
// Get the filename of the worker entry chunk
// We use just the filename because both the loader module and the worker
// entry chunk are in the same directory (typically server/chunks/), so we
// don't need a relative path - __dirname will already point to the correct
// directory
formatdoc! {
r#"
{TURBOPACK_EXPORT_VALUE}(__dirname + "/" + {worker_path:#});
"#,
worker_path = StringifyJs(entry_path.file_name()),
}
// For Node.js workers, export a function to create the worker.
// The function takes (WorkerConstructor, workerOptions) and calls createWorker
// with the worker path baked in.
let chunk_group = self.chunk_group().await?;
let assets = chunk_group.assets.await?;
// The last asset is the evaluate chunk (entry point) for the worker.
// The evaluated_chunk_group adds regular chunks first, then pushes the
// evaluate chunk last. The evaluate chunk contains the bootstrap code that
// loads the runtime and other chunks. For Node.js workers, we need a single
// file path (not a blob URL like browser workers), so we use the evaluate
// chunk which serves as the entry point.
let Some(entry_asset) = assets.last() else {
bail!("cannot find worker entry point asset");
};
let entry_path = entry_asset.path().await?;
// Get the filename of the worker entry chunk
// We use just the filename because both the loader module and the worker
// entry chunk are in the same directory (typically server/chunks/), so we
// don't need a relative path - __dirname will already point to the correct
// directory
formatdoc! {
r#"
{TURBOPACK_EXPORT_VALUE}(function(Ctor, opts) {{
return {TURBOPACK_CREATE_WORKER}(Ctor, __dirname + "/" + {worker_path:#}, opts);
}});
"#,
worker_path = StringifyJs(entry_path.file_name()),
}
}
};
......
......@@ -149,6 +149,13 @@ impl NodeJsChunkingContextBuilder {
self
}
pub fn worker_forwarded_globals(mut self, globals: Vec<RcStr>) -> Self {
self.chunking_context
.worker_forwarded_globals
.extend(globals);
self
}
/// Builds the chunking context.
pub fn build(self) -> Vc<NodeJsChunkingContext> {
NodeJsChunkingContext::cell(self.chunking_context)
......@@ -217,6 +224,8 @@ pub struct NodeJsChunkingContext {
chunking_configs: Vec<(ResolvedVc<Box<dyn ChunkType>>, ChunkingConfig)>,
/// Enable debug IDs for chunks and source maps.
debug_ids: bool,
/// Global variable names to forward to workers (e.g. NEXT_DEPLOYMENT_ID)
worker_forwarded_globals: Vec<RcStr>,
}
impl NodeJsChunkingContext {
......@@ -260,6 +269,7 @@ impl NodeJsChunkingContext {
unused_references: None,
chunking_configs: Default::default(),
debug_ids: false,
worker_forwarded_globals: vec![],
},
}
}
......@@ -678,4 +688,9 @@ impl ChunkingContext for NodeJsChunkingContext {
fn debug_ids_enabled(&self) -> Vc<bool> {
Vc::cell(self.debug_ids)
}
#[turbo_tasks::function]
fn worker_forwarded_globals(&self) -> Vc<Vec<RcStr>> {
Vc::cell(self.worker_forwarded_globals.clone())
}
}
......@@ -53,18 +53,48 @@ impl EcmascriptBuildNodeRuntimeChunk {
let asset_prefix = this.chunking_context.asset_prefix().await?;
let asset_prefix = asset_prefix.as_deref().unwrap_or("/");
// Get the list of global variable names to forward to workers
let worker_forwarded_globals =
Vc::upcast::<Box<dyn ChunkingContext>>(*this.chunking_context)
.worker_forwarded_globals()
.await?;
writedoc!(
code,
r#"
const RUNTIME_PUBLIC_PATH = {};
const RELATIVE_ROOT_PATH = {};
const ASSET_PREFIX = {};
const WORKER_FORWARDED_GLOBALS = {};
"#,
StringifyJs(runtime_public_path),
StringifyJs(output_root_to_root_path.as_str()),
StringifyJs(asset_prefix),
StringifyJs(&*worker_forwarded_globals),
)?;
// Add preamble to read forwarded globals from workerData (for worker_threads)
if !worker_forwarded_globals.is_empty() {
writedoc!(
code,
r#"
// Apply forwarded globals from workerData if running in a worker thread
if (typeof require !== 'undefined') {{
try {{
const {{ workerData }} = require('worker_threads');
if (workerData?.__turbopack_globals__) {{
Object.assign(globalThis, workerData.__turbopack_globals__);
// Remove internal data so it's not visible to user code
delete workerData.__turbopack_globals__;
}}
}} catch (_) {{
// Not in a worker thread context, ignore
}}
}}
"#,
)?;
}
match *this.chunking_context.runtime_type().await? {
RuntimeType::Development => {
let runtime_code = turbopack_ecmascript_runtime::get_nodejs_runtime_code(
......
const RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const ASSET_PREFIX = "/";
const WORKER_FORWARDED_GLOBALS = [];
// Dummy runtime
\ No newline at end of file
const RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const ASSET_PREFIX = "/";
const WORKER_FORWARDED_GLOBALS = [];
// Dummy runtime
\ No newline at end of file
;!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]="bd85f361-1530-0170-a15f-b3e3bd9abe29")}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]="5770f9e6-b0e5-5a25-603c-089a0fc1f085")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/ba425_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js",
{"otherChunks":["output/aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0b8736b3.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
......@@ -691,17 +691,21 @@ browserContextPrototype.P = resolveAbsolutePath;
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* 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 shared whether this is a SharedWorker (uses querystring for URL identity)
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
* @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,
......@@ -712,14 +716,19 @@ browserContextPrototype.q = exportUrl;
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (shared) {
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
return url;
// 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 = getWorkerURL;
browserContextPrototype.b = createWorker;
/**
* Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) {
......@@ -1911,5 +1920,5 @@ chunkListsToRegister.forEach(registerChunkList);
})();
//# debugId=bd85f361-1530-0170-a15f-b3e3bd9abe29
//# debugId=5770f9e6-b0e5-5a25-603c-089a0fc1f085
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js.map
\ No newline at end of file
const RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const ASSET_PREFIX = "/";
const WORKER_FORWARDED_GLOBALS = [];
/**
* This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes.
......@@ -714,10 +715,31 @@ function loadWebAssemblyModule(chunkPath, _edgeModule) {
return compileWebAssemblyFromPath(resolved);
}
contextPrototype.u = loadWebAssemblyModule;
function getWorkerURL(_entrypoint, _moduleChunks, _shared) {
throw new Error('Worker urls are not implemented yet for Node.js');
/**
* 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)
*/ function createWorker(WorkerConstructor, workerPath, workerOptions) {
// Build the forwarded globals object
const forwardedGlobals = {};
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);
}
nodeContextPrototype.b = getWorkerURL;
nodeContextPrototype.b = createWorker;
function instantiateModule(id, sourceType, sourceData) {
const moduleFactory = moduleFactories.get(id);
if (typeof moduleFactory !== 'function') {
......
......@@ -8,7 +8,9 @@ module.exports = 'turbopack';
__turbopack_context__.q("/static/vercel.242d4ff2.cjs");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(__turbopack_context__.b("output/6642e_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_output_664a0dec._.js", ["output/bf321_tests_snapshot_imports_ignore-comments_input_vercel_cjs_422a38f6._.js","output/ad3e4_tests_snapshot_imports_ignore-comments_input_vercel_cjs_6f11dd5d._.js"], false));
__turbopack_context__.v(function(Ctor, opts) {
return __turbopack_context__.b(Ctor, "output/6642e_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_output_664a0dec._.js", ["output/bf321_tests_snapshot_imports_ignore-comments_input_vercel_cjs_422a38f6._.js","output/ad3e4_tests_snapshot_imports_ignore-comments_input_vercel_cjs_6f11dd5d._.js"], opts);
});
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/ignore-worker.cjs (static in ecmascript)", ((__turbopack_context__) => {
......@@ -28,7 +30,7 @@ const __TURBOPACK__import$2e$meta__ = {
__turbopack_context__.A("[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.mjs [test] (ecmascript, async loader)").then(console.log);
__turbopack_context__.A("[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.mjs [test] (ecmascript, async loader)").then(console.log);
console.log(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript)"));
new Worker(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript, worker loader)"));
__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/imports/ignore-comments/input/vercel.cjs [test] (ecmascript, worker loader)")(Worker);
// turbopack shouldn't attempt to bundle these, and they should be preserved in the output
import(/* webpackIgnore: true */ './ignore.mjs');
import(/* turbopackIgnore: true */ './ignore.mjs');
......
......@@ -3,5 +3,5 @@
"sources": [],
"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": 18, "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,IAAIC;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": 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"}}]
}
\ No newline at end of file
const RUNTIME_PUBLIC_PATH = "output/[turbopack]_runtime.js";
const RELATIVE_ROOT_PATH = "../../../../../../..";
const ASSET_PREFIX = "/";
const WORKER_FORWARDED_GLOBALS = [];
/**
* This file contains runtime types and functions that are shared between all
* TurboPack ECMAScript runtimes.
......@@ -714,10 +715,31 @@ function loadWebAssemblyModule(chunkPath, _edgeModule) {
return compileWebAssemblyFromPath(resolved);
}
contextPrototype.u = loadWebAssemblyModule;
function getWorkerURL(_entrypoint, _moduleChunks, _shared) {
throw new Error('Worker urls are not implemented yet for Node.js');
/**
* 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)
*/ function createWorker(WorkerConstructor, workerPath, workerOptions) {
// Build the forwarded globals object
const forwardedGlobals = {};
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);
}
nodeContextPrototype.b = getWorkerURL;
nodeContextPrototype.b = createWorker;
function instantiateModule(id, sourceType, sourceData) {
const moduleFactory = moduleFactories.get(id);
if (typeof moduleFactory !== 'function') {
......
......@@ -690,17 +690,21 @@ browserContextPrototype.P = resolveAbsolutePath;
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* 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 shared whether this is a SharedWorker (uses querystring for URL identity)
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
* @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,
......@@ -711,14 +715,19 @@ browserContextPrototype.q = exportUrl;
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (shared) {
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
return url;
// 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 = getWorkerURL;
browserContextPrototype.b = createWorker;
/**
* Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) {
......
......@@ -799,6 +799,58 @@ 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) {
var f, y, t, _ = {
label: 0,
......@@ -1188,17 +1240,21 @@ browserContextPrototype.P = resolveAbsolutePath;
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* 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 shared whether this is a SharedWorker (uses querystring for URL identity)
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
* @param workerOptions options to pass to the Worker constructor (optional)
*/ function createWorker(WorkerConstructor, entrypoint, moduleChunks, workerOptions) {
var isSharedWorker = WorkerConstructor.name === 'SharedWorker';
var chunkUrls = moduleChunks.map(function(chunk) {
return getChunkRelativeUrl(chunk);
}).reverse();
......@@ -1228,14 +1284,18 @@ browserContextPrototype.q = exportUrl;
}
var url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
var paramsJson = JSON.stringify(params);
if (shared) {
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
return url;
// 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 = getWorkerURL;
browserContextPrototype.b = createWorker;
/**
* Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) {
......
......@@ -690,17 +690,21 @@ browserContextPrototype.P = resolveAbsolutePath;
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* 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 shared whether this is a SharedWorker (uses querystring for URL identity)
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
* @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,
......@@ -711,14 +715,19 @@ browserContextPrototype.q = exportUrl;
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (shared) {
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
return url;
// 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 = getWorkerURL;
browserContextPrototype.b = createWorker;
/**
* Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) {
......
......@@ -690,17 +690,21 @@ browserContextPrototype.P = resolveAbsolutePath;
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* 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 shared whether this is a SharedWorker (uses querystring for URL identity)
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
* @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,
......@@ -711,14 +715,19 @@ browserContextPrototype.q = exportUrl;
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (shared) {
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
return url;
// 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 = getWorkerURL;
browserContextPrototype.b = createWorker;
/**
* Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) {
......
......@@ -4,7 +4,9 @@
__turbopack_context__.q("/static/worker.60655f93.js");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(__turbopack_context__.b("output/6642e_crates_turbopack-tests_tests_snapshot_workers_basic_output_664a0dec._.js", ["output/aaf3a_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_841f9693.js","output/ba425_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_01a12aa6.js"], false));
__turbopack_context__.v(function(Ctor, opts) {
return __turbopack_context__.b(Ctor, "output/6642e_crates_turbopack-tests_tests_snapshot_workers_basic_output_664a0dec._.js", ["output/aaf3a_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_841f9693.js","output/ba425_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_01a12aa6.js"], opts);
});
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
......@@ -15,7 +17,7 @@ const __TURBOPACK__import$2e$meta__ = {
};
console.log('index.js');
const url = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js (static in ecmascript)"));
new Worker(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)"));
__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)")(Worker);
}),
]);
......
......@@ -2,5 +2,5 @@
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 10, "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,IAAIC"}}]
{"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
......@@ -690,17 +690,21 @@ browserContextPrototype.P = resolveAbsolutePath;
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* 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 shared whether this is a SharedWorker (uses querystring for URL identity)
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
* @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,
......@@ -711,14 +715,19 @@ browserContextPrototype.q = exportUrl;
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (shared) {
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
return url;
// 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 = getWorkerURL;
browserContextPrototype.b = createWorker;
/**
* Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) {
......
......@@ -690,17 +690,21 @@ browserContextPrototype.P = resolveAbsolutePath;
}
browserContextPrototype.q = exportUrl;
/**
* Returns a URL for the worker.
* 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 shared whether this is a SharedWorker (uses querystring for URL identity)
*/ function getWorkerURL(entrypoint, moduleChunks, shared) {
* @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,
......@@ -711,14 +715,19 @@ browserContextPrototype.q = exportUrl;
}
const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
const paramsJson = JSON.stringify(params);
if (shared) {
if (isSharedWorker) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
return url;
// 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 = getWorkerURL;
browserContextPrototype.b = createWorker;
/**
* Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) {
......
......@@ -4,7 +4,9 @@
__turbopack_context__.q("/static/worker.35b5336b.js");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {
__turbopack_context__.v(__turbopack_context__.b("output/6642e_crates_turbopack-tests_tests_snapshot_workers_shared_output_664a0dec._.js", ["output/aaf3a_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_e14430d8.js","output/ba425_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_87533493.js"], true));
__turbopack_context__.v(function(Ctor, opts) {
return __turbopack_context__.b(Ctor, "output/6642e_crates_turbopack-tests_tests_snapshot_workers_shared_output_664a0dec._.js", ["output/aaf3a_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_e14430d8.js","output/ba425_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_87533493.js"], opts);
});
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
......@@ -14,7 +16,7 @@ const __TURBOPACK__import$2e$meta__ = {
}
};
const url = new __turbopack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)"));
new SharedWorker(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)"));
__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)")(SharedWorker);
}),
]);
......
......@@ -2,5 +2,5 @@
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 10, "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,IAAIC"}}]
{"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
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