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

Turbopack: Use a real file entrypoint for Workers (and SharedWorkers) (#88602)

# What

Closes https://github.com/vercel/next.js/issues/84782  
Closes https://github.com/vercel/next.js/issues/74842  
Closes https://github.com/vercel/next.js/issues/82520
Closes PACK-3723

Replace blob URLs for web workers with real entrypoint files, fixing relative URL resolution inside workers. Implements support for `SharedWorkers` since it's now a simple variation of the `Worker` case.

Note that all generated files (and shared-worker querystrings) are appropriately content-hashed and do not rely on deployment IDs and will work w/immutable resources.

# Why

Workers created via `new Worker(new URL('./worker.js', import.meta.url))` previously got blob URLs. This breaks relative URL resolution inside workers - WASM imports like `new URL('./file.wasm', import.meta.url)` fail because `import.meta.url` returns `blob:http://...` instead of a real path.

# How

We emit a real worker entrypoint file instead of blob URLs. The entrypoint reads bootstrap config from URL hash params (`#params=....`), then loads the worker's chunks via `importScripts`.

The `ChunkingContext` trait gets a new `worker_entrypoint()` method returning a singleton bootstrap asset. Node.js `bail!`s for now but could implement its own in the future. The browser implementation (`EcmascriptBrowserWorkerEntrypoint`) compiles and minifies `worker-entrypoint.ts`, which parses `#params={globals,chunks}` from the URL at runtime.

`WorkerLoaderChunkItem` now emits `__turbopack_worker_url__(entrypoint, chunks, shared)` instead of the old blob URL shim. SharedWorker passes `shared=true` which adds a querystring - the browser handles worker identity via URL, so same URL means same instance.

Generated code changes (pseudocode):

```javascript
__turbopack_export_value__(__turbopack_worker_blob_url__(["chunk1.js", "chunk2.js"]));
```

After:

```javascript
__turbopack_export_value__(__turbopack_worker_url__("worker-entrypoint.js", ["chunk1.js", "chunk2.js"], false));
```

# Notes

Webpack doesn't currently correctly support `SharedWorkers`. The e2e test behaves properly in turbopack after this change, but webpack spins up two separate workers where it should only be spinning up one.

I generated snapshot tests for workers in the first and last commits to help understand the generated code better.

# Testing

- Snapshot tests for Worker, SharedWorker, and minified output
- E2E tests for WASM loading in workers (`test/e2e/app-dir/worker/`)
parent c986bccc
// SharedWorkers use onconnect to handle incoming connections
let count = 0
self.addEventListener('connect', function (e: MessageEvent) {
const port = e.ports[0]
import('./worker-dep').then((mod) => {
port.postMessage('shared-worker.ts:' + mod.default + ':' + ++count)
})
})
'use client'
import { useState } from 'react'
export default function Home() {
const [state, setState] = useState('default')
return (
<div>
<button
onClick={() => {
const worker = new SharedWorker(
new URL('../shared-worker', import.meta.url),
{
type: 'module',
}
)
worker.port.addEventListener('message', (event) => {
setState(event.data)
// Run a second time, which will use the same worker
const worker = new SharedWorker(
new URL('../shared-worker', import.meta.url),
{
type: 'module',
}
)
worker.port.addEventListener('message', (event) => {
setState(event.data)
})
worker.port.start()
})
worker.port.start()
}}
>
Get web worker data
</button>
<p>Worker state: </p>
<p id="worker-state">{state}</p>
</div>
)
}
// This worker tries to load WASM using a relative URL to ensure that
// `import.meta.url` returns a URL valid for relative URL resolution.
async function loadWasm() {
try {
// This is the pattern that fails with blob URLs
const wasmUrl = new URL('./add.wasm', import.meta.url)
const response = await fetch(wasmUrl)
const wasmBuffer = await response.arrayBuffer()
const wasmModule = await WebAssembly.instantiate(wasmBuffer)
const addOne = wasmModule.instance.exports.add_one as (n: number) => number
const result = addOne(41)
self.postMessage({ success: true, result })
} catch (error) {
self.postMessage({
success: false,
error: error instanceof Error ? error.message : String(error),
})
}
}
loadWasm()
'use client'
import { useState } from 'react'
export default function WasmWorkerPage() {
const [state, setState] = useState('default')
return (
<div>
<button
onClick={() => {
const worker = new Worker(new URL('../wasm-worker', import.meta.url))
worker.addEventListener('message', (event) => {
if (event.data.success) {
setState(`result:${event.data.result}`)
} else {
setState(`error:${event.data.error}`)
}
})
}}
>
Load WASM in worker
</button>
<p>Worker state: </p>
<p id="worker-state">{state}</p>
</div>
)
}
...@@ -17,7 +17,7 @@ describe('app dir - workers', () => { ...@@ -17,7 +17,7 @@ describe('app dir - workers', () => {
const url = request.url() const url = request.url()
// TODO fix deployment id for webpack // TODO fix deployment id for webpack
if (isTurbopack) { if (isTurbopack) {
if (url.includes('_next')) { if (url.includes('_next') && !url.includes('wasm')) {
expect(url).toMatch(/^[^?]+\?(v=\d+&)?dpl=test-deployment-id$/) expect(url).toMatch(/^[^?]+\?(v=\d+&)?dpl=test-deployment-id$/)
} }
} }
...@@ -96,4 +96,39 @@ describe('app dir - workers', () => { ...@@ -96,4 +96,39 @@ describe('app dir - workers', () => {
expect(workerDeploymentId).toBe('test-deployment-id') expect(workerDeploymentId).toBe('test-deployment-id')
}) })
}) })
it('should support loading WASM files in workers', async () => {
const browser = await next.browser('/wasm', {
beforePageLoad,
})
expect(await browser.elementByCss('#worker-state').text()).toBe('default')
await browser.elementByCss('button').click()
// The WASM add_one(41) should return 42
await retry(async () =>
expect(await browser.elementByCss('#worker-state').text()).toBe(
'result:42'
)
)
})
it('should support shared workers', async () => {
if (!isTurbopack) {
// webpack requires a magic attribute for shared workers to function
return
}
const browser = await next.browser('/shared', {
beforePageLoad,
})
expect(await browser.elementByCss('#worker-state').text()).toBe('default')
await browser.elementByCss('button').click()
await retry(async () =>
expect(await browser.elementByCss('#worker-state').text()).toBe(
'shared-worker.ts:worker-dep:2'
)
)
})
}) })
...@@ -18,6 +18,7 @@ use turbopack_core::{ ...@@ -18,6 +18,7 @@ use turbopack_core::{
chunk_group::{MakeChunkGroupResult, make_chunk_group}, chunk_group::{MakeChunkGroupResult, make_chunk_group},
chunk_id_strategy::ModuleIdStrategy, chunk_id_strategy::ModuleIdStrategy,
}, },
context::AssetContext,
environment::Environment, environment::Environment,
ident::AssetIdent, ident::AssetIdent,
module::Module, module::Module,
...@@ -39,6 +40,7 @@ use crate::ecmascript::{ ...@@ -39,6 +40,7 @@ use crate::ecmascript::{
chunk::EcmascriptBrowserChunk, chunk::EcmascriptBrowserChunk,
evaluate::chunk::EcmascriptBrowserEvaluateChunk, evaluate::chunk::EcmascriptBrowserEvaluateChunk,
list::asset::{EcmascriptDevChunkList, EcmascriptDevChunkListSource}, list::asset::{EcmascriptDevChunkList, EcmascriptDevChunkListSource},
worker::EcmascriptBrowserWorkerEntrypoint,
}; };
#[turbo_tasks::value] #[turbo_tasks::value]
...@@ -897,6 +899,17 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -897,6 +899,17 @@ impl ChunkingContext for BrowserChunkingContext {
async fn debug_ids_enabled(self: Vc<Self>) -> Result<Vc<bool>> { async fn debug_ids_enabled(self: Vc<Self>) -> Result<Vc<bool>> {
Ok(Vc::cell(self.await?.debug_ids)) Ok(Vc::cell(self.await?.debug_ids))
} }
#[turbo_tasks::function]
fn worker_entrypoint(
self: Vc<Self>,
asset_context: Vc<Box<dyn AssetContext>>,
) -> Vc<Box<dyn OutputAsset>> {
Vc::upcast(EcmascriptBrowserWorkerEntrypoint::new(
Vc::upcast(self),
asset_context,
))
}
} }
#[turbo_tasks::value] #[turbo_tasks::value]
......
...@@ -6,6 +6,8 @@ pub(crate) mod list; ...@@ -6,6 +6,8 @@ pub(crate) mod list;
pub(crate) mod merged; pub(crate) mod merged;
pub(crate) mod update; pub(crate) mod update;
pub(crate) mod version; pub(crate) mod version;
pub(crate) mod worker;
pub use chunk::EcmascriptBrowserChunk; pub use chunk::EcmascriptBrowserChunk;
pub use content::EcmascriptBrowserChunkContent; pub use content::EcmascriptBrowserChunkContent;
pub use worker::EcmascriptBrowserWorkerEntrypoint;
use anyhow::Result;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, ValueToString, Vc};
use turbo_tasks_fs::{File, FileContent, FileSystemPath};
use turbopack_core::{
asset::{Asset, AssetContent},
chunk::{ChunkingContext, MinifyType},
code_builder::Code,
context::AssetContext,
ident::AssetIdent,
output::{OutputAsset, OutputAssetsReference, OutputAssetsWithReferenced},
source_map::{GenerateSourceMap, SourceMapAsset},
};
use turbopack_ecmascript::minify::minify;
use turbopack_ecmascript_runtime::get_worker_runtime_code;
/// A pre-compiled worker entrypoint that bootstraps workers by reading config from URL params.
/// The entrypoint is keyed by (chunking_context, asset_context) to ensure proper compilation.
#[turbo_tasks::value(shared)]
pub struct EcmascriptBrowserWorkerEntrypoint {
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
}
#[turbo_tasks::value_impl]
impl EcmascriptBrowserWorkerEntrypoint {
#[turbo_tasks::function]
pub async fn new(
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
) -> Result<Vc<Self>> {
Ok(EcmascriptBrowserWorkerEntrypoint {
chunking_context,
asset_context,
}
.cell())
}
#[turbo_tasks::function]
async fn code(self: Vc<Self>) -> Result<Vc<Code>> {
let this = self.await?;
let source_maps = *this
.chunking_context
.reference_chunk_source_maps(Vc::upcast(self))
.await?;
let mut code = get_worker_runtime_code(*this.asset_context, source_maps)?
.owned()
.await?;
if let MinifyType::Minify { mangle } = *this.chunking_context.minify_type().await? {
code = minify(code, source_maps, mangle)?;
}
Ok(code.cell())
}
#[turbo_tasks::function]
async fn ident_for_path(&self) -> Result<Vc<AssetIdent>> {
let chunk_root_path = self.chunking_context.chunk_root_path().owned().await?;
let ident = AssetIdent::from_path(chunk_root_path)
.with_modifier(rcstr!("turbopack worker entrypoint"));
Ok(ident)
}
#[turbo_tasks::function]
async fn source_map(self: Vc<Self>) -> Result<Vc<SourceMapAsset>> {
let this = self.await?;
Ok(SourceMapAsset::new(
*this.chunking_context,
self.ident_for_path(),
Vc::upcast(self),
))
}
}
#[turbo_tasks::value_impl]
impl ValueToString for EcmascriptBrowserWorkerEntrypoint {
#[turbo_tasks::function]
fn to_string(&self) -> Vc<RcStr> {
Vc::cell(rcstr!("Ecmascript Browser Worker Entrypoint"))
}
}
#[turbo_tasks::value_impl]
impl OutputAssetsReference for EcmascriptBrowserWorkerEntrypoint {
#[turbo_tasks::function]
async fn references(self: Vc<Self>) -> Result<Vc<OutputAssetsWithReferenced>> {
Ok(OutputAssetsWithReferenced::from_assets(Vc::cell(vec![
ResolvedVc::upcast(self.source_map().to_resolved().await?),
])))
}
}
#[turbo_tasks::value_impl]
impl OutputAsset for EcmascriptBrowserWorkerEntrypoint {
#[turbo_tasks::function]
async fn path(self: Vc<Self>) -> Result<Vc<FileSystemPath>> {
let this = self.await?;
let ident = self.ident_for_path();
Ok(this.chunking_context.chunk_path(
Some(Vc::upcast(self)),
ident,
Some(rcstr!("turbopack-worker")),
rcstr!(".js"),
))
}
}
#[turbo_tasks::value_impl]
impl Asset for EcmascriptBrowserWorkerEntrypoint {
#[turbo_tasks::function]
async fn content(self: Vc<Self>) -> Result<Vc<AssetContent>> {
Ok(AssetContent::file(
FileContent::Content(File::from(
self.code()
.to_rope_with_magic_comments(|| self.source_map())
.await?,
))
.cell(),
))
}
}
#[turbo_tasks::value_impl]
impl GenerateSourceMap for EcmascriptBrowserWorkerEntrypoint {
#[turbo_tasks::function]
fn generate_source_map(self: Vc<Self>) -> Vc<FileContent> {
self.code().generate_source_map()
}
}
...@@ -13,6 +13,7 @@ use crate::{ ...@@ -13,6 +13,7 @@ use crate::{
ChunkItem, ChunkType, ChunkableModule, EvaluatableAssets, ChunkItem, ChunkType, ChunkableModule, EvaluatableAssets,
availability_info::AvailabilityInfo, chunk_id_strategy::ModuleIdStrategy, availability_info::AvailabilityInfo, chunk_id_strategy::ModuleIdStrategy,
}, },
context::AssetContext,
environment::Environment, environment::Environment,
ident::AssetIdent, ident::AssetIdent,
module::Module, module::Module,
...@@ -444,8 +445,21 @@ pub trait ChunkingContext { ...@@ -444,8 +445,21 @@ pub trait ChunkingContext {
/// Returns whether debug IDs are enabled for this chunking context. /// Returns whether debug IDs are enabled for this chunking context.
#[turbo_tasks::function] #[turbo_tasks::function]
fn debug_ids_enabled(self: Vc<Self>) -> Vc<bool>; fn debug_ids_enabled(self: Vc<Self>) -> Vc<bool>;
}
/// Returns the worker entrypoint for this chunking context.
/// The asset_context should come from the origin where the worker was created.
#[turbo_tasks::function]
async fn worker_entrypoint(
self: Vc<Self>,
asset_context: Vc<Box<dyn AssetContext>>,
) -> Result<Vc<Box<dyn OutputAsset>>> {
let _ = asset_context;
bail!(
"Worker entrypoint is not supported by {name}",
name = self.name().await?
);
}
}
pub trait ChunkingContextExt { pub trait ChunkingContextExt {
fn root_chunk_group( fn root_chunk_group(
self: Vc<Self>, self: Vc<Self>,
......
...@@ -82,6 +82,13 @@ impl OutputAssets { ...@@ -82,6 +82,13 @@ impl OutputAssets {
Ok(Vc::cell(assets.into_iter().collect())) Ok(Vc::cell(assets.into_iter().collect()))
} }
#[turbo_tasks::function]
pub async fn concat_asset(&self, asset: ResolvedVc<Box<dyn OutputAsset>>) -> Result<Vc<Self>> {
let mut assets: FxIndexSet<_> = self.0.iter().copied().collect();
assets.extend([asset]);
Ok(Vc::cell(assets.into_iter().collect()))
}
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn concat(other: Vec<Vc<Self>>) -> Result<Vc<Self>> { pub async fn concat(other: Vec<Vc<Self>>) -> Result<Vc<Self>> {
let mut assets: FxIndexSet<_> = FxIndexSet::default(); let mut assets: FxIndexSet<_> = FxIndexSet::default();
...@@ -161,26 +168,36 @@ impl OutputAssetsWithReferenced { ...@@ -161,26 +168,36 @@ impl OutputAssetsWithReferenced {
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn concatenate(&self, other: Vc<Self>) -> Result<Vc<Self>> { pub async fn concatenate(&self, other: Vc<Self>) -> Result<Vc<Self>> {
let other = other.await?;
Ok(Self { Ok(Self {
assets: self assets: self.assets.concatenate(*other.assets).to_resolved().await?,
.assets
.concatenate(*other.await?.assets)
.to_resolved()
.await?,
referenced_assets: self referenced_assets: self
.referenced_assets .referenced_assets
.concatenate(*other.await?.referenced_assets) .concatenate(*other.referenced_assets)
.to_resolved() .to_resolved()
.await?, .await?,
references: self references: self
.references .references
.concatenate(*other.await?.references) .concatenate(*other.references)
.to_resolved() .to_resolved()
.await?, .await?,
} }
.cell()) .cell())
} }
#[turbo_tasks::function]
pub async fn concatenate_asset(
&self,
asset: ResolvedVc<Box<dyn OutputAsset>>,
) -> Result<Vc<Self>> {
Ok(Self {
assets: self.assets.concat_asset(*asset).to_resolved().await?,
referenced_assets: self.referenced_assets,
references: self.references,
}
.cell())
}
/// Returns all assets, including referenced assets and nested assets. /// Returns all assets, including referenced assets and nested assets.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn expand_all_assets(&self) -> Result<Vc<ExpandedOutputAssets>> { pub async fn expand_all_assets(&self) -> Result<Vc<ExpandedOutputAssets>> {
......
...@@ -480,7 +480,7 @@ pub enum ResolveResultItem { ...@@ -480,7 +480,7 @@ pub enum ResolveResultItem {
/// resolving. /// resolving.
/// ///
/// A primary factor is the actual request string, but there are /// A primary factor is the actual request string, but there are
/// other factors like exports conditions that can affect resolting and become /// other factors like exports conditions that can affect resolving and become
/// part of the key (assuming the condition is unknown at compile time) /// part of the key (assuming the condition is unknown at compile time)
#[derive(Clone, Debug, Default, Hash, TaskInput)] #[derive(Clone, Debug, Default, Hash, TaskInput)]
#[turbo_tasks::value] #[turbo_tasks::value]
......
...@@ -11,12 +11,11 @@ ...@@ -11,12 +11,11 @@
/// <reference path="../base/globals.d.ts" /> /// <reference path="../base/globals.d.ts" />
/// <reference path="../../../shared/runtime-utils.ts" /> /// <reference path="../../../shared/runtime-utils.ts" />
// Used in WebWorkers to tell the runtime about the chunk base path
declare var TURBOPACK_WORKER_LOCATION: string
// Used in WebWorkers to tell the runtime about the chunk suffix // Used in WebWorkers to tell the runtime about the chunk suffix
declare var TURBOPACK_CHUNK_SUFFIX: string declare var TURBOPACK_CHUNK_SUFFIX: string
// Used in WebWorkers to tell the runtime about the current chunk url since it can't be detected via document.currentScript // Used in WebWorkers to tell the runtime about the current chunk url since it
// Note it's stored in reversed order to use push and pop // can't be detected via `document.currentScript`. Note it's stored in reversed
// order to use `push` and `pop`
declare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined declare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined
// Injected by rust code // Injected by rust code
...@@ -315,21 +314,36 @@ function resolveAbsolutePath(modulePath?: string): string { ...@@ -315,21 +314,36 @@ function resolveAbsolutePath(modulePath?: string): string {
browserContextPrototype.P = resolveAbsolutePath browserContextPrototype.P = resolveAbsolutePath
/** /**
* Returns a blob URL for the worker. * Returns a URL for the worker.
* @param chunks list of chunks to load * 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.
*
* @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 getWorkerBlobURL(chunks: ChunkPath[]): string { function getWorkerURL(
// It is important to reverse the array so when bootstrapping we can infer what chunk is being entrypoint: ChunkPath,
// evaluated by poping urls off of this array. See `getPathFromScript` moduleChunks: ChunkPath[],
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)}; shared: boolean
self.TURBOPACK_CHUNK_SUFFIX = ${JSON.stringify(CHUNK_SUFFIX)}; ): URL {
self.NEXT_DEPLOYMENT_ID = ${JSON.stringify((globalThis as any).NEXT_DEPLOYMENT_ID)}; const url = new URL(getChunkRelativeUrl(entrypoint), location.origin)
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)};
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());` const params = {
let blob = new Blob([bootstrap], { type: 'text/javascript' }) S: CHUNK_SUFFIX,
return URL.createObjectURL(blob) N: (globalThis as any).NEXT_DEPLOYMENT_ID,
NC: moduleChunks.map((chunk) => getChunkRelativeUrl(chunk)),
}
const paramsJson = JSON.stringify(params)
if (shared) {
url.searchParams.set('params', paramsJson)
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson)
}
return url
} }
browserContextPrototype.b = getWorkerBlobURL browserContextPrototype.b = getWorkerURL
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
......
/**
* Worker entrypoint bootstrap.
*/
interface WorkerBootstrapConfig {
// TURBOPACK_CHUNK_SUFFIX
S?: string
// NEXT_DEPLOYMENT_ID
N?: string
// TURBOPACK_NEXT_CHUNK_URLS
NC?: string[]
}
;(() => {
function abort(message: string): never {
console.error(message)
throw new Error(message)
}
// Security: Ensure this code is running in a worker environment to prevent
// the worker entrypoint being used as an XSS gadget. If this is a worker, we
// know that the origin of the caller is the same as our origin.
if (
typeof (self as any)['WorkerGlobalScope'] === 'undefined' ||
!(self instanceof (self as any)['WorkerGlobalScope'])
) {
abort('Worker entrypoint must be loaded in a worker context')
}
const url = new URL(location.href)
// Try querystring first (SharedWorker), then hash (regular Worker)
let paramsString = url.searchParams.get('params')
if (!paramsString && url.hash.startsWith('#params=')) {
paramsString = decodeURIComponent(url.hash.slice('#params='.length))
}
if (!paramsString) abort('Missing worker bootstrap config')
// Safety: this string requires that a script on the same origin has loaded
// this code as a module. We still don't fully trust it, so we'll validate the
// types and ensure that the next chunk URLs are same-origin.
const config: WorkerBootstrapConfig = JSON.parse(paramsString)
const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : ''
const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''
// In a normal browser context, the runtime can figure out which chunk is
// currently executing via `document.currentScript`. Workers don't have that
// luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead
// (`reverse()`d below).
//
// Each chunk pops its URL off the front of the array when it runs, so we need
// to store them in reverse order to make sure the first chunk to execute sees
// its own URL at the front.
const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []
Object.assign(self, {
TURBOPACK_CHUNK_SUFFIX,
TURBOPACK_NEXT_CHUNK_URLS,
NEXT_DEPLOYMENT_ID,
})
if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {
const scriptsToLoad: string[] = []
for (const chunk of TURBOPACK_NEXT_CHUNK_URLS) {
// Chunks are relative to the origin.
const chunkUrl = new URL(chunk, location.origin)
// Security: Only load scripts from the same origin. This prevents this
// worker entrypoint from being used as a gadget to load scripts from
// foreign origins if someone happens to find a separate XSS vector
// elsewhere on this origin.
if (chunkUrl.origin !== location.origin) {
abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`)
}
scriptsToLoad.push(chunkUrl.toString())
}
TURBOPACK_NEXT_CHUNK_URLS.reverse()
importScripts(...scriptsToLoad)
}
})()
...@@ -164,7 +164,7 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map() ...@@ -164,7 +164,7 @@ const chunkResolvers: Map<ChunkUrl, ChunkResolver> = new Map()
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl) self.TURBOPACK_NEXT_CHUNK_URLS!.push(chunkUrl)
importScripts(TURBOPACK_WORKER_LOCATION + chunkUrl) importScripts(chunkUrl)
} else { } else {
throw new Error( throw new Error(
`can't infer type of chunk from URL ${chunkUrl} in worker` `can't infer type of chunk from URL ${chunkUrl} in worker`
......
...@@ -178,11 +178,15 @@ function loadWebAssemblyModule( ...@@ -178,11 +178,15 @@ function loadWebAssemblyModule(
} }
contextPrototype.u = loadWebAssemblyModule contextPrototype.u = loadWebAssemblyModule
function getWorkerBlobURL(_chunks: ChunkPath[]): string { function getWorkerURL(
throw new Error('Worker blobs are not implemented yet for Node.js') _entrypoint: ChunkPath,
_moduleChunks: ChunkPath[],
_shared: boolean
): URL {
throw new Error('Worker urls are not implemented yet for Node.js')
} }
nodeContextPrototype.b = getWorkerBlobURL nodeContextPrototype.b = getWorkerURL
function instantiateModule( function instantiateModule(
id: ModuleId, id: ModuleId,
......
...@@ -86,7 +86,11 @@ type AsyncModule = ( ...@@ -86,7 +86,11 @@ type AsyncModule = (
) => void ) => void
type ResolveAbsolutePath = (modulePath?: string) => string type ResolveAbsolutePath = (modulePath?: string) => string
type GetWorkerBlobURL = (chunks: ChunkPath[]) => string type GetWorkerURL = (
entrypoint: ChunkPath,
moduleChunks: ChunkPath[],
shared: boolean
) => URL
type ExternalRequire = ( type ExternalRequire = (
id: DependencySpecifier, id: DependencySpecifier,
...@@ -133,7 +137,7 @@ interface TurbopackBaseContext<M> { ...@@ -133,7 +137,7 @@ interface TurbopackBaseContext<M> {
u: LoadWebAssemblyModule u: LoadWebAssemblyModule
P: ResolveAbsolutePath P: ResolveAbsolutePath
U: RelativeURL U: RelativeURL
b: GetWorkerBlobURL b: GetWorkerURL
x: ExternalRequire x: ExternalRequire
y: ExternalImport y: ExternalImport
z: CommonJsRequire z: CommonJsRequire
......
...@@ -205,3 +205,15 @@ pub async fn get_browser_runtime_code( ...@@ -205,3 +205,15 @@ pub async fn get_browser_runtime_code(
Ok(Code::cell(code.build())) Ok(Code::cell(code.build()))
} }
/// Returns the code for the ECMAScript worker entrypoint bootstrap.
pub fn get_worker_runtime_code(
asset_context: Vc<Box<dyn AssetContext>>,
generate_source_map: bool,
) -> Result<Vc<Code>> {
Ok(embed_static_code(
asset_context,
rcstr!("browser/runtime/base/worker-entrypoint.ts"),
generate_source_map,
))
}
...@@ -10,7 +10,7 @@ pub(crate) mod embed_js; ...@@ -10,7 +10,7 @@ pub(crate) mod embed_js;
pub(crate) mod nodejs_runtime; pub(crate) mod nodejs_runtime;
pub(crate) mod runtime_type; pub(crate) mod runtime_type;
pub use browser_runtime::get_browser_runtime_code; pub use browser_runtime::{get_browser_runtime_code, get_worker_runtime_code};
pub use chunk_suffix::ChunkSuffix; pub use chunk_suffix::ChunkSuffix;
#[cfg(feature = "test")] #[cfg(feature = "test")]
pub use dummy_runtime::get_dummy_runtime_code; pub use dummy_runtime::get_dummy_runtime_code;
......
...@@ -1862,6 +1862,10 @@ impl JsValue { ...@@ -1862,6 +1862,10 @@ impl JsValue {
"Worker".to_string(), "Worker".to_string(),
"The standard Worker constructor: https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker" "The standard Worker constructor: https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker"
), ),
WellKnownFunctionKind::SharedWorkerConstructor => (
"SharedWorker".to_string(),
"The standard SharedWorker constructor: https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker/SharedWorker"
),
WellKnownFunctionKind::URLConstructor => ( WellKnownFunctionKind::URLConstructor => (
"URL".to_string(), "URL".to_string(),
"The standard URL constructor: https://developer.mozilla.org/en-US/docs/Web/API/URL/URL" "The standard URL constructor: https://developer.mozilla.org/en-US/docs/Web/API/URL/URL"
...@@ -3527,6 +3531,7 @@ pub enum WellKnownFunctionKind { ...@@ -3527,6 +3531,7 @@ pub enum WellKnownFunctionKind {
NodeResolveFrom, NodeResolveFrom,
NodeProtobufLoad, NodeProtobufLoad,
WorkerConstructor, WorkerConstructor,
SharedWorkerConstructor,
// The worker_threads Worker class // The worker_threads Worker class
NodeWorkerConstructor, NodeWorkerConstructor,
URLConstructor, URLConstructor,
......
...@@ -78,7 +78,7 @@ use turbopack_core::{ ...@@ -78,7 +78,7 @@ use turbopack_core::{
issue::{IssueExt, IssueSeverity, IssueSource, StyledString, analyze::AnalyzeIssue}, issue::{IssueExt, IssueSeverity, IssueSource, StyledString, analyze::AnalyzeIssue},
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
reference::{ModuleReference, ModuleReferences}, reference::{ModuleReference, ModuleReferences},
reference_type::{CommonJsReferenceSubType, ReferenceType}, reference_type::{CommonJsReferenceSubType, ReferenceType, WorkerReferenceSubType},
resolve::{ resolve::{
FindContextFileResult, ImportUsage, ModulePart, find_context_file, FindContextFileResult, ImportUsage, ModulePart, find_context_file,
origin::{PlainResolveOrigin, ResolveOrigin}, origin::{PlainResolveOrigin, ResolveOrigin},
...@@ -1915,15 +1915,25 @@ where ...@@ -1915,15 +1915,25 @@ where
} }
return Ok(()); return Ok(());
} }
WellKnownFunctionKind::WorkerConstructor => { WellKnownFunctionKind::WorkerConstructor
| WellKnownFunctionKind::SharedWorkerConstructor => {
let args = linked_args().await?; let args = linked_args().await?;
if let Some(url @ JsValue::Url(_, JsValueUrlKind::Relative)) = args.first() { if let Some(url @ JsValue::Url(_, JsValueUrlKind::Relative)) = args.first() {
let (name, worker_type) = match func {
WellKnownFunctionKind::WorkerConstructor => {
("Worker", WorkerReferenceSubType::WebWorker)
}
WellKnownFunctionKind::SharedWorkerConstructor => {
("SharedWorker", WorkerReferenceSubType::SharedWorker)
}
_ => unreachable!(),
};
let pat = js_value_to_pattern(url); let pat = js_value_to_pattern(url);
if !pat.has_constant_parts() { if !pat.has_constant_parts() {
let (args, hints) = explain_args(args); let (args, hints) = explain_args(args);
handler.span_warn_with_code( handler.span_warn_with_code(
span, span,
&format!("new Worker({args}) is very dynamic{hints}",), &format!("new {name}({args}) is very dynamic{hints}",),
DiagnosticId::Lint( DiagnosticId::Lint(
errors::failed_to_analyze::ecmascript::NEW_WORKER.to_string(), errors::failed_to_analyze::ecmascript::NEW_WORKER.to_string(),
), ),
...@@ -1940,6 +1950,7 @@ where ...@@ -1940,6 +1950,7 @@ where
Request::parse(pat).to_resolved().await?, Request::parse(pat).to_resolved().await?,
issue_source(source, span), issue_source(source, span),
in_try, in_try,
worker_type,
), ),
ast_path.to_vec().into(), ast_path.to_vec().into(),
); );
...@@ -3339,6 +3350,12 @@ async fn value_visitor_inner( ...@@ -3339,6 +3350,12 @@ async fn value_visitor_inner(
true, true,
"ignored Worker constructor", "ignored Worker constructor",
), ),
"SharedWorker" => JsValue::unknown_if(
ignore,
JsValue::WellKnownFunction(WellKnownFunctionKind::SharedWorkerConstructor),
true,
"ignored SharedWorker constructor",
),
"define" => JsValue::WellKnownFunction(WellKnownFunctionKind::Define), "define" => JsValue::WellKnownFunction(WellKnownFunctionKind::Define),
"URL" => JsValue::WellKnownFunction(WellKnownFunctionKind::URLConstructor), "URL" => JsValue::WellKnownFunction(WellKnownFunctionKind::URLConstructor),
"process" => JsValue::WellKnownObject(WellKnownObjectKind::NodeProcessModule), "process" => JsValue::WellKnownObject(WellKnownObjectKind::NodeProcessModule),
...@@ -4121,8 +4138,8 @@ fn is_invoking_node_process_eval(args: &[JsValue]) -> bool { ...@@ -4121,8 +4138,8 @@ fn is_invoking_node_process_eval(args: &[JsValue]) -> bool {
if let JsValue::Member(_, obj, constant) = &args[0] { if let JsValue::Member(_, obj, constant) = &args[0] {
// Is the first argument to spawn `process.argv[]`? // Is the first argument to spawn `process.argv[]`?
if let ( if let (
box JsValue::WellKnownObject(WellKnownObjectKind::NodeProcessArgv), &box JsValue::WellKnownObject(WellKnownObjectKind::NodeProcessArgv),
box JsValue::Constant(JsConstantValue::Num(ConstantNumber(num))), &box JsValue::Constant(JsConstantValue::Num(ConstantNumber(num))),
) = (obj, constant) ) = (obj, constant)
{ {
// Is it specifically `process.argv[0]`? // Is it specifically `process.argv[0]`?
......
...@@ -34,6 +34,7 @@ pub struct WorkerAssetReference { ...@@ -34,6 +34,7 @@ pub struct WorkerAssetReference {
pub request: ResolvedVc<Request>, pub request: ResolvedVc<Request>,
pub issue_source: IssueSource, pub issue_source: IssueSource,
pub in_try: bool, pub in_try: bool,
pub worker_type: WorkerReferenceSubType,
} }
impl WorkerAssetReference { impl WorkerAssetReference {
...@@ -42,25 +43,24 @@ impl WorkerAssetReference { ...@@ -42,25 +43,24 @@ impl WorkerAssetReference {
request: ResolvedVc<Request>, request: ResolvedVc<Request>,
issue_source: IssueSource, issue_source: IssueSource,
in_try: bool, in_try: bool,
worker_type: WorkerReferenceSubType,
) -> Self { ) -> Self {
WorkerAssetReference { WorkerAssetReference {
origin, origin,
request, request,
issue_source, issue_source,
in_try, in_try,
worker_type,
} }
} }
} }
impl WorkerAssetReference { impl WorkerAssetReference {
async fn worker_loader_module( async fn worker_loader_module(&self) -> Result<Option<Vc<WorkerLoaderModule>>> {
self: &WorkerAssetReference,
) -> Result<Option<Vc<WorkerLoaderModule>>> {
let module = url_resolve( let module = url_resolve(
*self.origin, *self.origin,
*self.request, *self.request,
// TODO support more worker types ReferenceType::Worker(self.worker_type),
ReferenceType::Worker(WorkerReferenceSubType::WebWorker),
Some(self.issue_source), Some(self.issue_source),
self.in_try, self.in_try,
); );
...@@ -81,7 +81,11 @@ impl WorkerAssetReference { ...@@ -81,7 +81,11 @@ impl WorkerAssetReference {
return Ok(None); return Ok(None);
}; };
Ok(Some(WorkerLoaderModule::new(*chunkable))) Ok(Some(WorkerLoaderModule::new(
*chunkable,
self.worker_type,
*self.origin.asset_context().to_resolved().await?,
)))
} }
} }
......
...@@ -82,7 +82,7 @@ pub const TURBOPACK_DYNAMIC: &TurbopackRuntimeFunctionShortcut = make_shortcut!( ...@@ -82,7 +82,7 @@ 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_WORKER_BLOB_URL: &TurbopackRuntimeFunctionShortcut = make_shortcut!("b"); pub const TURBOPACK_WORKER_URL: &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");
...@@ -115,7 +115,7 @@ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctio ...@@ -115,7 +115,7 @@ 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_worker_blob_url__", TURBOPACK_WORKER_BLOB_URL), ("__turbopack_worker_url__", TURBOPACK_WORKER_URL),
("__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),
......
...@@ -7,10 +7,12 @@ use turbopack_core::{ ...@@ -7,10 +7,12 @@ use turbopack_core::{
ChunkData, ChunkItem, ChunkType, ChunkingContext, ChunkingContextExt, ChunksData, ChunkData, ChunkItem, ChunkType, ChunkingContext, ChunkingContextExt, ChunksData,
availability_info::AvailabilityInfo, availability_info::AvailabilityInfo,
}, },
context::AssetContext,
ident::AssetIdent, ident::AssetIdent,
module::Module, module::Module,
module_graph::{ModuleGraph, chunk_group_info::ChunkGroup}, module_graph::{ModuleGraph, chunk_group_info::ChunkGroup},
output::{OutputAssetsReference, OutputAssetsWithReferenced}, output::{OutputAsset, OutputAssetsReference, OutputAssetsWithReferenced},
reference_type::WorkerReferenceSubType,
}; };
use super::module::WorkerLoaderModule; use super::module::WorkerLoaderModule;
...@@ -19,7 +21,7 @@ use crate::{ ...@@ -19,7 +21,7 @@ use crate::{
EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkType, EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkType,
data::EcmascriptChunkData, data::EcmascriptChunkData,
}, },
runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_WORKER_BLOB_URL}, runtime_functions::{TURBOPACK_EXPORT_VALUE, TURBOPACK_WORKER_URL},
utils::StringifyJs, utils::StringifyJs,
}; };
...@@ -28,6 +30,8 @@ pub struct WorkerLoaderChunkItem { ...@@ -28,6 +30,8 @@ pub struct WorkerLoaderChunkItem {
pub module: ResolvedVc<WorkerLoaderModule>, pub module: ResolvedVc<WorkerLoaderModule>,
pub module_graph: ResolvedVc<ModuleGraph>, pub module_graph: ResolvedVc<ModuleGraph>,
pub chunking_context: ResolvedVc<Box<dyn ChunkingContext>>, pub chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
pub asset_context: ResolvedVc<Box<dyn AssetContext>>,
pub worker_type: WorkerReferenceSubType,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
...@@ -35,7 +39,6 @@ impl WorkerLoaderChunkItem { ...@@ -35,7 +39,6 @@ impl WorkerLoaderChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn chunk_group(&self) -> Result<Vc<OutputAssetsWithReferenced>> { async fn chunk_group(&self) -> Result<Vc<OutputAssetsWithReferenced>> {
let module = self.module.await?; let module = self.module.await?;
Ok(self.chunking_context.evaluated_chunk_group_assets( Ok(self.chunking_context.evaluated_chunk_group_assets(
module.inner.ident().with_modifier(rcstr!("worker")), module.inner.ident().with_modifier(rcstr!("worker")),
ChunkGroup::Isolated(ResolvedVc::upcast(module.inner)), ChunkGroup::Isolated(ResolvedVc::upcast(module.inner)),
...@@ -58,6 +61,24 @@ impl WorkerLoaderChunkItem { ...@@ -58,6 +61,24 @@ impl WorkerLoaderChunkItem {
impl EcmascriptChunkItem for WorkerLoaderChunkItem { impl EcmascriptChunkItem for WorkerLoaderChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
async fn content(self: Vc<Self>) -> Result<Vc<EcmascriptChunkItemContent>> { async fn content(self: Vc<Self>) -> Result<Vc<EcmascriptChunkItemContent>> {
let this = self.await?;
// Get the worker entrypoint for this chunking context
let asset_context = *this.asset_context;
let entrypoint_full_path = this
.chunking_context
.worker_entrypoint(asset_context)
.path()
.await?;
// Get the entrypoint path relative to output root
let output_root = this.chunking_context.output_root().owned().await?;
let entrypoint_path = output_root
.get_path_to(&entrypoint_full_path)
.map(|s| s.to_string())
.unwrap_or_else(|| entrypoint_full_path.path.to_string());
// Get the chunk data for the worker module
let chunks_data = self.chunks_data().await?; let chunks_data = self.chunks_data().await?;
let chunks_data = chunks_data.iter().try_join().await?; let chunks_data = chunks_data.iter().try_join().await?;
let chunks_data: Vec<_> = chunks_data let chunks_data: Vec<_> = chunks_data
...@@ -65,11 +86,17 @@ impl EcmascriptChunkItem for WorkerLoaderChunkItem { ...@@ -65,11 +86,17 @@ impl EcmascriptChunkItem for WorkerLoaderChunkItem {
.map(|chunk_data| EcmascriptChunkData::new(chunk_data)) .map(|chunk_data| EcmascriptChunkData::new(chunk_data))
.collect(); .collect();
// Determine if this is a SharedWorker
let is_shared = matches!(this.worker_type, WorkerReferenceSubType::SharedWorker);
// Generate code that creates a worker URL with the entrypoint and chunk paths
let code = formatdoc! { let code = formatdoc! {
r#" r#"
{TURBOPACK_EXPORT_VALUE}({TURBOPACK_WORKER_BLOB_URL}({chunks:#})); {TURBOPACK_EXPORT_VALUE}({TURBOPACK_WORKER_URL}({entrypoint}, {chunks}, {shared}));
"#, "#,
entrypoint = StringifyJs(&entrypoint_path),
chunks = StringifyJs(&chunks_data), chunks = StringifyJs(&chunks_data),
shared = is_shared,
}; };
Ok(EcmascriptChunkItemContent { Ok(EcmascriptChunkItemContent {
...@@ -83,8 +110,12 @@ impl EcmascriptChunkItem for WorkerLoaderChunkItem { ...@@ -83,8 +110,12 @@ impl EcmascriptChunkItem for WorkerLoaderChunkItem {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl OutputAssetsReference for WorkerLoaderChunkItem { impl OutputAssetsReference for WorkerLoaderChunkItem {
#[turbo_tasks::function] #[turbo_tasks::function]
fn references(self: Vc<Self>) -> Vc<OutputAssetsWithReferenced> { async fn references(self: Vc<Self>) -> Result<Vc<OutputAssetsWithReferenced>> {
self.chunk_group() let this = self.await?;
let asset_context = *this.asset_context;
Ok(self
.chunk_group()
.concatenate_asset(this.chunking_context.worker_entrypoint(asset_context)))
} }
} }
......
...@@ -7,10 +7,12 @@ use turbopack_core::{ ...@@ -7,10 +7,12 @@ use turbopack_core::{
ChunkGroupType, ChunkableModule, ChunkableModuleReference, ChunkingContext, ChunkingType, ChunkGroupType, ChunkableModule, ChunkableModuleReference, ChunkingContext, ChunkingType,
ChunkingTypeOption, ChunkingTypeOption,
}, },
context::AssetContext,
ident::AssetIdent, ident::AssetIdent,
module::{Module, ModuleSideEffects}, module::{Module, ModuleSideEffects},
module_graph::ModuleGraph, module_graph::ModuleGraph,
reference::{ModuleReference, ModuleReferences}, reference::{ModuleReference, ModuleReferences},
reference_type::WorkerReferenceSubType,
resolve::ModuleResolveResult, resolve::ModuleResolveResult,
}; };
...@@ -21,13 +23,23 @@ use super::chunk_item::WorkerLoaderChunkItem; ...@@ -21,13 +23,23 @@ use super::chunk_item::WorkerLoaderChunkItem;
#[turbo_tasks::value] #[turbo_tasks::value]
pub struct WorkerLoaderModule { pub struct WorkerLoaderModule {
pub inner: ResolvedVc<Box<dyn ChunkableModule>>, pub inner: ResolvedVc<Box<dyn ChunkableModule>>,
pub worker_type: WorkerReferenceSubType,
pub asset_context: ResolvedVc<Box<dyn AssetContext>>,
} }
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl WorkerLoaderModule { impl WorkerLoaderModule {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn new(module: ResolvedVc<Box<dyn ChunkableModule>>) -> Vc<Self> { pub fn new(
Self::cell(WorkerLoaderModule { inner: module }) module: ResolvedVc<Box<dyn ChunkableModule>>,
worker_type: WorkerReferenceSubType,
asset_context: ResolvedVc<Box<dyn AssetContext>>,
) -> Vc<Self> {
Self::cell(WorkerLoaderModule {
inner: module,
worker_type,
asset_context,
})
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -74,19 +86,22 @@ impl Asset for WorkerLoaderModule { ...@@ -74,19 +86,22 @@ impl Asset for WorkerLoaderModule {
#[turbo_tasks::value_impl] #[turbo_tasks::value_impl]
impl ChunkableModule for WorkerLoaderModule { impl ChunkableModule for WorkerLoaderModule {
#[turbo_tasks::function] #[turbo_tasks::function]
fn as_chunk_item( async fn as_chunk_item(
self: ResolvedVc<Self>, self: ResolvedVc<Self>,
module_graph: ResolvedVc<ModuleGraph>, module_graph: ResolvedVc<ModuleGraph>,
chunking_context: ResolvedVc<Box<dyn ChunkingContext>>, chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
) -> Vc<Box<dyn turbopack_core::chunk::ChunkItem>> { ) -> Result<Vc<Box<dyn turbopack_core::chunk::ChunkItem>>> {
Vc::upcast( let this = self.await?;
Ok(Vc::upcast(
WorkerLoaderChunkItem { WorkerLoaderChunkItem {
module: self, module: self,
module_graph, module_graph,
chunking_context, chunking_context,
worker_type: this.worker_type,
asset_context: this.asset_context,
} }
.cell(), .cell(),
) ))
} }
} }
......
...@@ -48,7 +48,7 @@ use turbopack_core::{ ...@@ -48,7 +48,7 @@ use turbopack_core::{
chunk_group_info::{ChunkGroup, ChunkGroupEntry}, chunk_group_info::{ChunkGroup, ChunkGroupEntry},
}, },
output::{OutputAsset, OutputAssets, OutputAssetsReference, OutputAssetsWithReferenced}, output::{OutputAsset, OutputAssets, OutputAssetsReference, OutputAssetsWithReferenced},
reference_type::{EntryReferenceSubType, ReferenceType}, reference_type::{EntryReferenceSubType, ReferenceType, UrlReferenceSubType},
source::Source, source::Source,
}; };
use turbopack_ecmascript::{ use turbopack_ecmascript::{
...@@ -325,11 +325,16 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> { ...@@ -325,11 +325,16 @@ async fn run_test_operation(resource: RcStr) -> Result<Vc<FileSystemPath>> {
.cell() .cell()
.await?; .await?;
let conditions = RuleCondition::any(vec![ let conditions = RuleCondition::All(vec![
RuleCondition::ResourcePathEndsWith(".js".into()), RuleCondition::not(RuleCondition::ReferenceType(ReferenceType::Url(
RuleCondition::ResourcePathEndsWith(".jsx".into()), UrlReferenceSubType::Undefined,
RuleCondition::ResourcePathEndsWith(".ts".into()), ))),
RuleCondition::ResourcePathEndsWith(".tsx".into()), RuleCondition::any(vec![
RuleCondition::ResourcePathEndsWith(".js".into()),
RuleCondition::ResourcePathEndsWith(".jsx".into()),
RuleCondition::ResourcePathEndsWith(".ts".into()),
RuleCondition::ResourcePathEndsWith(".tsx".into()),
]),
]); ]);
let module_rules = ModuleRule::new( let module_rules = ModuleRule::new(
......
;!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]="3834607a-5e38-b3f2-d7f2-094bfde98e30")}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]="2edabdcd-1a50-190d-01a5-132504146b5c")}catch(e){}}();
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push([ (globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push([
"output/ba425_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js", "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)"]} {"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)"]}
...@@ -521,7 +521,7 @@ function applyModuleFactoryName(factory) { ...@@ -521,7 +521,7 @@ function applyModuleFactoryName(factory) {
* shared runtime utils. * shared runtime utils.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../base/globals.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../base/globals.d.ts" />
/// <reference path="../../../shared/runtime-utils.ts" /> /// <reference path="../../../shared/runtime-utils.ts" />
// Used in WebWorkers to tell the runtime about the chunk base path // Used in WebWorkers to tell the runtime about the chunk suffix
const browserContextPrototype = Context.prototype; const browserContextPrototype = Context.prototype;
var SourceType = /*#__PURE__*/ function(SourceType) { var SourceType = /*#__PURE__*/ function(SourceType) {
/** /**
...@@ -684,24 +684,29 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -684,24 +684,29 @@ browserContextPrototype.R = resolvePathFromModule;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/** /**
* Returns a blob URL for the worker. * Returns a URL for the worker.
* @param chunks list of chunks to load * The entrypoint is a pre-compiled worker runtime file. The params configure
*/ function getWorkerBlobURL(chunks) { * which module chunks to load and which module to run as the entry point.
// It is important to reverse the array so when bootstrapping we can infer what chunk is being *
// evaluated by poping urls off of this array. See `getPathFromScript` * @param entrypoint URL path to the worker entrypoint chunk
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)}; * @param moduleChunks list of module chunk paths to load
self.TURBOPACK_CHUNK_SUFFIX = ${JSON.stringify(CHUNK_SUFFIX)}; * @param shared whether this is a SharedWorker (uses querystring for URL identity)
self.NEXT_DEPLOYMENT_ID = ${JSON.stringify(globalThis.NEXT_DEPLOYMENT_ID)}; */ function getWorkerURL(entrypoint, moduleChunks, shared) {
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)}; const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`; const params = {
let blob = new Blob([ S: CHUNK_SUFFIX,
bootstrap N: globalThis.NEXT_DEPLOYMENT_ID,
], { NC: moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk))
type: 'text/javascript' };
}); const paramsJson = JSON.stringify(params);
return URL.createObjectURL(blob); if (shared) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
return url;
} }
browserContextPrototype.b = getWorkerBlobURL; browserContextPrototype.b = getWorkerURL;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -1699,7 +1704,7 @@ let BACKEND; ...@@ -1699,7 +1704,7 @@ let BACKEND;
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl);
importScripts(TURBOPACK_WORKER_LOCATION + chunkUrl); importScripts(chunkUrl);
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
...@@ -1862,5 +1867,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -1862,5 +1867,5 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# debugId=3834607a-5e38-b3f2-d7f2-094bfde98e30 //# debugId=2edabdcd-1a50-190d-01a5-132504146b5c
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js.map //# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js.map
\ No newline at end of file
...@@ -708,10 +708,10 @@ function loadWebAssemblyModule(chunkPath, _edgeModule) { ...@@ -708,10 +708,10 @@ function loadWebAssemblyModule(chunkPath, _edgeModule) {
return compileWebAssemblyFromPath(resolved); return compileWebAssemblyFromPath(resolved);
} }
contextPrototype.u = loadWebAssemblyModule; contextPrototype.u = loadWebAssemblyModule;
function getWorkerBlobURL(_chunks) { function getWorkerURL(_entrypoint, _moduleChunks, _shared) {
throw new Error('Worker blobs are not implemented yet for Node.js'); throw new Error('Worker urls are not implemented yet for Node.js');
} }
nodeContextPrototype.b = getWorkerBlobURL; nodeContextPrototype.b = getWorkerURL;
function instantiateModule(id, sourceType, sourceData) { function instantiateModule(id, sourceType, sourceData) {
const moduleFactory = moduleFactories.get(id); const moduleFactory = moduleFactories.get(id);
if (typeof moduleFactory !== 'function') { if (typeof moduleFactory !== 'function') {
......
/**
* Worker entrypoint bootstrap.
*/ ;
(()=>{
function abort(message) {
console.error(message);
throw new Error(message);
}
// Security: Ensure this code is running in a worker environment to prevent
// the worker entrypoint being used as an XSS gadget. If this is a worker, we
// know that the origin of the caller is the same as our origin.
if (typeof self['WorkerGlobalScope'] === 'undefined' || !(self instanceof self['WorkerGlobalScope'])) {
abort('Worker entrypoint must be loaded in a worker context');
}
const url = new URL(location.href);
// Try querystring first (SharedWorker), then hash (regular Worker)
let paramsString = url.searchParams.get('params');
if (!paramsString && url.hash.startsWith('#params=')) {
paramsString = decodeURIComponent(url.hash.slice('#params='.length));
}
if (!paramsString) abort('Missing worker bootstrap config');
// Safety: this string requires that a script on the same origin has loaded
// this code as a module. We still don't fully trust it, so we'll validate the
// types and ensure that the next chunk URLs are same-origin.
const config = JSON.parse(paramsString);
const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : '';
const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : '';
// In a normal browser context, the runtime can figure out which chunk is
// currently executing via `document.currentScript`. Workers don't have that
// luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead
// (`reverse()`d below).
//
// Each chunk pops its URL off the front of the array when it runs, so we need
// to store them in reverse order to make sure the first chunk to execute sees
// its own URL at the front.
const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : [];
Object.assign(self, {
TURBOPACK_CHUNK_SUFFIX,
TURBOPACK_NEXT_CHUNK_URLS,
NEXT_DEPLOYMENT_ID
});
if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {
const scriptsToLoad = [];
for (const chunk of TURBOPACK_NEXT_CHUNK_URLS){
// Chunks are relative to the origin.
const chunkUrl = new URL(chunk, location.origin);
// Security: Only load scripts from the same origin. This prevents this
// worker entrypoint from being used as a gadget to load scripts from
// foreign origins if someone happens to find a separate XSS vector
// elsewhere on this origin.
if (chunkUrl.origin !== location.origin) {
abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`);
}
scriptsToLoad.push(chunkUrl.toString());
}
TURBOPACK_NEXT_CHUNK_URLS.reverse();
importScripts(...scriptsToLoad);
}
})();
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_output_2867ca5f._.js.map
\ No newline at end of file
...@@ -8,10 +8,7 @@ module.exports = 'turbopack'; ...@@ -8,10 +8,7 @@ module.exports = 'turbopack';
__turbopack_context__.v("/static/vercel.242d4ff2.cjs");}), __turbopack_context__.v("/static/vercel.242d4ff2.cjs");}),
"[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__) => {
__turbopack_context__.v(__turbopack_context__.b([ __turbopack_context__.v(__turbopack_context__.b("output/6642e_crates_turbopack-tests_tests_snapshot_imports_ignore-comments_output_2867ca5f._.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));
"output/bf321_tests_snapshot_imports_ignore-comments_input_vercel_cjs_422a38f6._.js",
"output/ad3e4_tests_snapshot_imports_ignore-comments_input_vercel_cjs_6f11dd5d._.js"
]));
}), }),
"[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__) => {
......
...@@ -3,5 +3,5 @@ ...@@ -3,5 +3,5 @@
"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": 21, "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": 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"}}]
} }
\ No newline at end of file
{"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/worker-entrypoint.ts"],"sourcesContent":["/**\n * Worker entrypoint bootstrap.\n */\n\ninterface WorkerBootstrapConfig {\n // TURBOPACK_CHUNK_SUFFIX\n S?: string\n // NEXT_DEPLOYMENT_ID\n N?: string\n // TURBOPACK_NEXT_CHUNK_URLS\n NC?: string[]\n}\n\n;(() => {\n function abort(message: string): never {\n console.error(message)\n throw new Error(message)\n }\n\n // Security: Ensure this code is running in a worker environment to prevent\n // the worker entrypoint being used as an XSS gadget. If this is a worker, we\n // know that the origin of the caller is the same as our origin.\n if (\n typeof (self as any)['WorkerGlobalScope'] === 'undefined' ||\n !(self instanceof (self as any)['WorkerGlobalScope'])\n ) {\n abort('Worker entrypoint must be loaded in a worker context')\n }\n\n const url = new URL(location.href)\n\n // Try querystring first (SharedWorker), then hash (regular Worker)\n let paramsString = url.searchParams.get('params')\n if (!paramsString && url.hash.startsWith('#params=')) {\n paramsString = decodeURIComponent(url.hash.slice('#params='.length))\n }\n\n if (!paramsString) abort('Missing worker bootstrap config')\n\n // Safety: this string requires that a script on the same origin has loaded\n // this code as a module. We still don't fully trust it, so we'll validate the\n // types and ensure that the next chunk URLs are same-origin.\n const config: WorkerBootstrapConfig = JSON.parse(paramsString)\n\n const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : ''\n const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''\n // In a normal browser context, the runtime can figure out which chunk is\n // currently executing via `document.currentScript`. Workers don't have that\n // luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead\n // (`reverse()`d below).\n //\n // Each chunk pops its URL off the front of the array when it runs, so we need\n // to store them in reverse order to make sure the first chunk to execute sees\n // its own URL at the front.\n const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []\n\n Object.assign(self, {\n TURBOPACK_CHUNK_SUFFIX,\n TURBOPACK_NEXT_CHUNK_URLS,\n NEXT_DEPLOYMENT_ID,\n })\n\n if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {\n const scriptsToLoad: string[] = []\n for (const chunk of TURBOPACK_NEXT_CHUNK_URLS) {\n // Chunks are relative to the origin.\n const chunkUrl = new URL(chunk, location.origin)\n // Security: Only load scripts from the same origin. This prevents this\n // worker entrypoint from being used as a gadget to load scripts from\n // foreign origins if someone happens to find a separate XSS vector\n // elsewhere on this origin.\n if (chunkUrl.origin !== location.origin) {\n abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`)\n }\n scriptsToLoad.push(chunkUrl.toString())\n }\n\n TURBOPACK_NEXT_CHUNK_URLS.reverse()\n importScripts(...scriptsToLoad)\n }\n})()\n"],"names":["abort","message","console","error","Error","self","url","URL","location","href","paramsString","searchParams","get","hash","startsWith","decodeURIComponent","slice","length","config","JSON","parse","TURBOPACK_CHUNK_SUFFIX","S","NEXT_DEPLOYMENT_ID","N","TURBOPACK_NEXT_CHUNK_URLS","Array","isArray","NC","Object","assign","scriptsToLoad","chunk","chunkUrl","origin","push","toString","reverse","importScripts"],"mappings":"AAAA;;CAEC;AAWA,CAAC;IACA,SAASA,MAAMC,OAAe;QAC5BC,QAAQC,KAAK,CAACF;QACd,MAAM,IAAIG,MAAMH;IAClB;IAEA,2EAA2E;IAC3E,6EAA6E;IAC7E,gEAAgE;IAChE,IACE,OAAO,AAACI,IAAY,CAAC,oBAAoB,KAAK,eAC9C,CAAC,CAACA,gBAAgB,AAACA,IAAY,CAAC,oBAAoB,GACpD;QACAL,MAAM;IACR;IAEA,MAAMM,MAAM,IAAIC,IAAIC,SAASC,IAAI;IAEjC,mEAAmE;IACnE,IAAIC,eAAeJ,IAAIK,YAAY,CAACC,GAAG,CAAC;IACxC,IAAI,CAACF,gBAAgBJ,IAAIO,IAAI,CAACC,UAAU,CAAC,aAAa;QACpDJ,eAAeK,mBAAmBT,IAAIO,IAAI,CAACG,KAAK,CAAC,WAAWC,MAAM;IACpE;IAEA,IAAI,CAACP,cAAcV,MAAM;IAEzB,2EAA2E;IAC3E,8EAA8E;IAC9E,6DAA6D;IAC7D,MAAMkB,SAAgCC,KAAKC,KAAK,CAACV;IAEjD,MAAMW,yBAAyB,OAAOH,OAAOI,CAAC,KAAK,WAAWJ,OAAOI,CAAC,GAAG;IACzE,MAAMC,qBAAqB,OAAOL,OAAOM,CAAC,KAAK,WAAWN,OAAOM,CAAC,GAAG;IACrE,yEAAyE;IACzE,4EAA4E;IAC5E,mEAAmE;IACnE,wBAAwB;IACxB,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,4BAA4B;IAC5B,MAAMC,4BAA4BC,MAAMC,OAAO,CAACT,OAAOU,EAAE,IAAIV,OAAOU,EAAE,GAAG,EAAE;IAE3EC,OAAOC,MAAM,CAACzB,MAAM;QAClBgB;QACAI;QACAF;IACF;IAEA,IAAIE,0BAA0BR,MAAM,GAAG,GAAG;QACxC,MAAMc,gBAA0B,EAAE;QAClC,KAAK,MAAMC,SAASP,0BAA2B;YAC7C,qCAAqC;YACrC,MAAMQ,WAAW,IAAI1B,IAAIyB,OAAOxB,SAAS0B,MAAM;YAC/C,uEAAuE;YACvE,qEAAqE;YACrE,mEAAmE;YACnE,4BAA4B;YAC5B,IAAID,SAASC,MAAM,KAAK1B,SAAS0B,MAAM,EAAE;gBACvClC,MAAM,CAAC,6CAA6C,EAAEiC,SAASC,MAAM,EAAE;YACzE;YACAH,cAAcI,IAAI,CAACF,SAASG,QAAQ;QACtC;QAEAX,0BAA0BY,OAAO;QACjCC,iBAAiBP;IACnB;AACF,CAAC","ignoreList":[0]}
\ No newline at end of file
...@@ -708,10 +708,10 @@ function loadWebAssemblyModule(chunkPath, _edgeModule) { ...@@ -708,10 +708,10 @@ function loadWebAssemblyModule(chunkPath, _edgeModule) {
return compileWebAssemblyFromPath(resolved); return compileWebAssemblyFromPath(resolved);
} }
contextPrototype.u = loadWebAssemblyModule; contextPrototype.u = loadWebAssemblyModule;
function getWorkerBlobURL(_chunks) { function getWorkerURL(_entrypoint, _moduleChunks, _shared) {
throw new Error('Worker blobs are not implemented yet for Node.js'); throw new Error('Worker urls are not implemented yet for Node.js');
} }
nodeContextPrototype.b = getWorkerBlobURL; nodeContextPrototype.b = getWorkerURL;
function instantiateModule(id, sourceType, sourceData) { function instantiateModule(id, sourceType, sourceData) {
const moduleFactory = moduleFactories.get(id); const moduleFactory = moduleFactories.get(id);
if (typeof moduleFactory !== 'function') { if (typeof moduleFactory !== 'function') {
......
...@@ -520,7 +520,7 @@ function applyModuleFactoryName(factory) { ...@@ -520,7 +520,7 @@ function applyModuleFactoryName(factory) {
* shared runtime utils. * shared runtime utils.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../base/globals.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../base/globals.d.ts" />
/// <reference path="../../../shared/runtime-utils.ts" /> /// <reference path="../../../shared/runtime-utils.ts" />
// Used in WebWorkers to tell the runtime about the chunk base path // Used in WebWorkers to tell the runtime about the chunk suffix
const browserContextPrototype = Context.prototype; const browserContextPrototype = Context.prototype;
var SourceType = /*#__PURE__*/ function(SourceType) { var SourceType = /*#__PURE__*/ function(SourceType) {
/** /**
...@@ -683,24 +683,29 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -683,24 +683,29 @@ browserContextPrototype.R = resolvePathFromModule;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/** /**
* Returns a blob URL for the worker. * Returns a URL for the worker.
* @param chunks list of chunks to load * The entrypoint is a pre-compiled worker runtime file. The params configure
*/ function getWorkerBlobURL(chunks) { * which module chunks to load and which module to run as the entry point.
// It is important to reverse the array so when bootstrapping we can infer what chunk is being *
// evaluated by poping urls off of this array. See `getPathFromScript` * @param entrypoint URL path to the worker entrypoint chunk
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)}; * @param moduleChunks list of module chunk paths to load
self.TURBOPACK_CHUNK_SUFFIX = ${JSON.stringify(CHUNK_SUFFIX)}; * @param shared whether this is a SharedWorker (uses querystring for URL identity)
self.NEXT_DEPLOYMENT_ID = ${JSON.stringify(globalThis.NEXT_DEPLOYMENT_ID)}; */ function getWorkerURL(entrypoint, moduleChunks, shared) {
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)}; const url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`; const params = {
let blob = new Blob([ S: CHUNK_SUFFIX,
bootstrap N: globalThis.NEXT_DEPLOYMENT_ID,
], { NC: moduleChunks.map((chunk)=>getChunkRelativeUrl(chunk))
type: 'text/javascript' };
}); const paramsJson = JSON.stringify(params);
return URL.createObjectURL(blob); if (shared) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
return url;
} }
browserContextPrototype.b = getWorkerBlobURL; browserContextPrototype.b = getWorkerURL;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -1698,7 +1703,7 @@ let BACKEND; ...@@ -1698,7 +1703,7 @@ let BACKEND;
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl);
importScripts(TURBOPACK_WORKER_LOCATION + chunkUrl); importScripts(chunkUrl);
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
......
...@@ -768,7 +768,7 @@ function applyModuleFactoryName(factory) { ...@@ -768,7 +768,7 @@ function applyModuleFactoryName(factory) {
* shared runtime utils. * shared runtime utils.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../base/globals.d.ts" /> */ /* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../base/globals.d.ts" />
/// <reference path="../../../shared/runtime-utils.ts" /> /// <reference path="../../../shared/runtime-utils.ts" />
// Used in WebWorkers to tell the runtime about the chunk base path // Used in WebWorkers to tell the runtime about the chunk suffix
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try { try {
var info = gen[key](arg); var info = gen[key](arg);
...@@ -1181,24 +1181,31 @@ browserContextPrototype.R = resolvePathFromModule; ...@@ -1181,24 +1181,31 @@ browserContextPrototype.R = resolvePathFromModule;
} }
browserContextPrototype.P = resolveAbsolutePath; browserContextPrototype.P = resolveAbsolutePath;
/** /**
* Returns a blob URL for the worker. * Returns a URL for the worker.
* @param chunks list of chunks to load * The entrypoint is a pre-compiled worker runtime file. The params configure
*/ function getWorkerBlobURL(chunks) { * which module chunks to load and which module to run as the entry point.
// It is important to reverse the array so when bootstrapping we can infer what chunk is being *
// evaluated by poping urls off of this array. See `getPathFromScript` * @param entrypoint URL path to the worker entrypoint chunk
var bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)}; * @param moduleChunks list of module chunk paths to load
self.TURBOPACK_CHUNK_SUFFIX = ${JSON.stringify(CHUNK_SUFFIX)}; * @param shared whether this is a SharedWorker (uses querystring for URL identity)
self.NEXT_DEPLOYMENT_ID = ${JSON.stringify(globalThis.NEXT_DEPLOYMENT_ID)}; */ function getWorkerURL(entrypoint, moduleChunks, shared) {
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)}; var url = new URL(getChunkRelativeUrl(entrypoint), location.origin);
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`; var params = {
var blob = new Blob([ S: CHUNK_SUFFIX,
bootstrap N: globalThis.NEXT_DEPLOYMENT_ID,
], { NC: moduleChunks.map(function(chunk) {
type: 'text/javascript' return getChunkRelativeUrl(chunk);
}); })
return URL.createObjectURL(blob); };
var paramsJson = JSON.stringify(params);
if (shared) {
url.searchParams.set('params', paramsJson);
} else {
url.hash = '#params=' + encodeURIComponent(paramsJson);
}
return url;
} }
browserContextPrototype.b = getWorkerBlobURL; browserContextPrototype.b = getWorkerURL;
/** /**
* Instantiates a runtime module. * Instantiates a runtime module.
*/ function instantiateRuntimeModule(moduleId, chunkPath) { */ function instantiateRuntimeModule(moduleId, chunkPath) {
...@@ -1631,7 +1638,7 @@ var BACKEND; ...@@ -1631,7 +1638,7 @@ var BACKEND;
// ignore // ignore
} else if (isJs(chunkUrl)) { } else if (isJs(chunkUrl)) {
self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl); self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl);
importScripts(TURBOPACK_WORKER_LOCATION + chunkUrl); importScripts(chunkUrl);
} else { } else {
throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`); throw new Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);
} }
......
console.log('index.js')
const url = new URL('./worker.js', import.meta.url)
new Worker(url)
{
"runtime": "Browser",
"runtimeType": "Development",
"minifyType": "NoMinify",
"environment": "Browser"
}
/**
* Worker entrypoint bootstrap.
*/ ;
(()=>{
function abort(message) {
console.error(message);
throw new Error(message);
}
// Security: Ensure this code is running in a worker environment to prevent
// the worker entrypoint being used as an XSS gadget. If this is a worker, we
// know that the origin of the caller is the same as our origin.
if (typeof self['WorkerGlobalScope'] === 'undefined' || !(self instanceof self['WorkerGlobalScope'])) {
abort('Worker entrypoint must be loaded in a worker context');
}
const url = new URL(location.href);
// Try querystring first (SharedWorker), then hash (regular Worker)
let paramsString = url.searchParams.get('params');
if (!paramsString && url.hash.startsWith('#params=')) {
paramsString = decodeURIComponent(url.hash.slice('#params='.length));
}
if (!paramsString) abort('Missing worker bootstrap config');
// Safety: this string requires that a script on the same origin has loaded
// this code as a module. We still don't fully trust it, so we'll validate the
// types and ensure that the next chunk URLs are same-origin.
const config = JSON.parse(paramsString);
const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : '';
const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : '';
// In a normal browser context, the runtime can figure out which chunk is
// currently executing via `document.currentScript`. Workers don't have that
// luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead
// (`reverse()`d below).
//
// Each chunk pops its URL off the front of the array when it runs, so we need
// to store them in reverse order to make sure the first chunk to execute sees
// its own URL at the front.
const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : [];
Object.assign(self, {
TURBOPACK_CHUNK_SUFFIX,
TURBOPACK_NEXT_CHUNK_URLS,
NEXT_DEPLOYMENT_ID
});
if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {
const scriptsToLoad = [];
for (const chunk of TURBOPACK_NEXT_CHUNK_URLS){
// Chunks are relative to the origin.
const chunkUrl = new URL(chunk, location.origin);
// Security: Only load scripts from the same origin. This prevents this
// worker entrypoint from being used as a gadget to load scripts from
// foreign origins if someone happens to find a separate XSS vector
// elsewhere on this origin.
if (chunkUrl.origin !== location.origin) {
abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`);
}
scriptsToLoad.push(chunkUrl.toString());
}
TURBOPACK_NEXT_CHUNK_URLS.reverse();
importScripts(...scriptsToLoad);
}
})();
//# sourceMappingURL=turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_output_2867ca5f._.js.map
\ No newline at end of file
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push(["output/aaf3a_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_841f9693.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
console.log('worker.js');
self.postMessage('hello');
}),
]);
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_841f9693.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 3, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js"],"sourcesContent":["console.log('worker.js')\nself.postMessage('hello')\n"],"names":["console","log","self","postMessage"],"mappings":"AAAAA,QAAQC,GAAG,CAAC;AACZC,KAAKC,WAAW,CAAC"}}]
}
\ No newline at end of file
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_input_73fc86c5._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.v("/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_2867ca5f._.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));
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
const __TURBOPACK__import$2e$meta__ = {
get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js")}`;
}
};
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)"));
}),
]);
//# sourceMappingURL=turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_input_73fc86c5._.js.map
\ No newline at end of file
{
"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"}}]
}
\ No newline at end of file
{"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/worker-entrypoint.ts"],"sourcesContent":["/**\n * Worker entrypoint bootstrap.\n */\n\ninterface WorkerBootstrapConfig {\n // TURBOPACK_CHUNK_SUFFIX\n S?: string\n // NEXT_DEPLOYMENT_ID\n N?: string\n // TURBOPACK_NEXT_CHUNK_URLS\n NC?: string[]\n}\n\n;(() => {\n function abort(message: string): never {\n console.error(message)\n throw new Error(message)\n }\n\n // Security: Ensure this code is running in a worker environment to prevent\n // the worker entrypoint being used as an XSS gadget. If this is a worker, we\n // know that the origin of the caller is the same as our origin.\n if (\n typeof (self as any)['WorkerGlobalScope'] === 'undefined' ||\n !(self instanceof (self as any)['WorkerGlobalScope'])\n ) {\n abort('Worker entrypoint must be loaded in a worker context')\n }\n\n const url = new URL(location.href)\n\n // Try querystring first (SharedWorker), then hash (regular Worker)\n let paramsString = url.searchParams.get('params')\n if (!paramsString && url.hash.startsWith('#params=')) {\n paramsString = decodeURIComponent(url.hash.slice('#params='.length))\n }\n\n if (!paramsString) abort('Missing worker bootstrap config')\n\n // Safety: this string requires that a script on the same origin has loaded\n // this code as a module. We still don't fully trust it, so we'll validate the\n // types and ensure that the next chunk URLs are same-origin.\n const config: WorkerBootstrapConfig = JSON.parse(paramsString)\n\n const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : ''\n const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''\n // In a normal browser context, the runtime can figure out which chunk is\n // currently executing via `document.currentScript`. Workers don't have that\n // luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead\n // (`reverse()`d below).\n //\n // Each chunk pops its URL off the front of the array when it runs, so we need\n // to store them in reverse order to make sure the first chunk to execute sees\n // its own URL at the front.\n const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []\n\n Object.assign(self, {\n TURBOPACK_CHUNK_SUFFIX,\n TURBOPACK_NEXT_CHUNK_URLS,\n NEXT_DEPLOYMENT_ID,\n })\n\n if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {\n const scriptsToLoad: string[] = []\n for (const chunk of TURBOPACK_NEXT_CHUNK_URLS) {\n // Chunks are relative to the origin.\n const chunkUrl = new URL(chunk, location.origin)\n // Security: Only load scripts from the same origin. This prevents this\n // worker entrypoint from being used as a gadget to load scripts from\n // foreign origins if someone happens to find a separate XSS vector\n // elsewhere on this origin.\n if (chunkUrl.origin !== location.origin) {\n abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`)\n }\n scriptsToLoad.push(chunkUrl.toString())\n }\n\n TURBOPACK_NEXT_CHUNK_URLS.reverse()\n importScripts(...scriptsToLoad)\n }\n})()\n"],"names":["abort","message","console","error","Error","self","url","URL","location","href","paramsString","searchParams","get","hash","startsWith","decodeURIComponent","slice","length","config","JSON","parse","TURBOPACK_CHUNK_SUFFIX","S","NEXT_DEPLOYMENT_ID","N","TURBOPACK_NEXT_CHUNK_URLS","Array","isArray","NC","Object","assign","scriptsToLoad","chunk","chunkUrl","origin","push","toString","reverse","importScripts"],"mappings":"AAAA;;CAEC;AAWA,CAAC;IACA,SAASA,MAAMC,OAAe;QAC5BC,QAAQC,KAAK,CAACF;QACd,MAAM,IAAIG,MAAMH;IAClB;IAEA,2EAA2E;IAC3E,6EAA6E;IAC7E,gEAAgE;IAChE,IACE,OAAO,AAACI,IAAY,CAAC,oBAAoB,KAAK,eAC9C,CAAC,CAACA,gBAAgB,AAACA,IAAY,CAAC,oBAAoB,GACpD;QACAL,MAAM;IACR;IAEA,MAAMM,MAAM,IAAIC,IAAIC,SAASC,IAAI;IAEjC,mEAAmE;IACnE,IAAIC,eAAeJ,IAAIK,YAAY,CAACC,GAAG,CAAC;IACxC,IAAI,CAACF,gBAAgBJ,IAAIO,IAAI,CAACC,UAAU,CAAC,aAAa;QACpDJ,eAAeK,mBAAmBT,IAAIO,IAAI,CAACG,KAAK,CAAC,WAAWC,MAAM;IACpE;IAEA,IAAI,CAACP,cAAcV,MAAM;IAEzB,2EAA2E;IAC3E,8EAA8E;IAC9E,6DAA6D;IAC7D,MAAMkB,SAAgCC,KAAKC,KAAK,CAACV;IAEjD,MAAMW,yBAAyB,OAAOH,OAAOI,CAAC,KAAK,WAAWJ,OAAOI,CAAC,GAAG;IACzE,MAAMC,qBAAqB,OAAOL,OAAOM,CAAC,KAAK,WAAWN,OAAOM,CAAC,GAAG;IACrE,yEAAyE;IACzE,4EAA4E;IAC5E,mEAAmE;IACnE,wBAAwB;IACxB,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,4BAA4B;IAC5B,MAAMC,4BAA4BC,MAAMC,OAAO,CAACT,OAAOU,EAAE,IAAIV,OAAOU,EAAE,GAAG,EAAE;IAE3EC,OAAOC,MAAM,CAACzB,MAAM;QAClBgB;QACAI;QACAF;IACF;IAEA,IAAIE,0BAA0BR,MAAM,GAAG,GAAG;QACxC,MAAMc,gBAA0B,EAAE;QAClC,KAAK,MAAMC,SAASP,0BAA2B;YAC7C,qCAAqC;YACrC,MAAMQ,WAAW,IAAI1B,IAAIyB,OAAOxB,SAAS0B,MAAM;YAC/C,uEAAuE;YACvE,qEAAqE;YACrE,mEAAmE;YACnE,4BAA4B;YAC5B,IAAID,SAASC,MAAM,KAAK1B,SAAS0B,MAAM,EAAE;gBACvClC,MAAM,CAAC,6CAA6C,EAAEiC,SAASC,MAAM,EAAE;YACzE;YACAH,cAAcI,IAAI,CAACF,SAASG,QAAQ;QACtC;QAEAX,0BAA0BY,OAAO;QACjCC,iBAAiBP;IACnB;AACF,CAAC","ignoreList":[0]}
\ No newline at end of file
console.log('worker.js')
self.postMessage('hello')
\ No newline at end of file
const url = new URL('./worker.js', import.meta.url)
new SharedWorker(url)
self.onconnect = (e) => e.ports[0].postMessage('hello')
{
"runtime": "Browser",
"runtimeType": "Development",
"minifyType": "NoMinify",
"environment": "Browser"
}
/**
* Worker entrypoint bootstrap.
*/ ;
(()=>{
function abort(message) {
console.error(message);
throw new Error(message);
}
// Security: Ensure this code is running in a worker environment to prevent
// the worker entrypoint being used as an XSS gadget. If this is a worker, we
// know that the origin of the caller is the same as our origin.
if (typeof self['WorkerGlobalScope'] === 'undefined' || !(self instanceof self['WorkerGlobalScope'])) {
abort('Worker entrypoint must be loaded in a worker context');
}
const url = new URL(location.href);
// Try querystring first (SharedWorker), then hash (regular Worker)
let paramsString = url.searchParams.get('params');
if (!paramsString && url.hash.startsWith('#params=')) {
paramsString = decodeURIComponent(url.hash.slice('#params='.length));
}
if (!paramsString) abort('Missing worker bootstrap config');
// Safety: this string requires that a script on the same origin has loaded
// this code as a module. We still don't fully trust it, so we'll validate the
// types and ensure that the next chunk URLs are same-origin.
const config = JSON.parse(paramsString);
const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : '';
const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : '';
// In a normal browser context, the runtime can figure out which chunk is
// currently executing via `document.currentScript`. Workers don't have that
// luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead
// (`reverse()`d below).
//
// Each chunk pops its URL off the front of the array when it runs, so we need
// to store them in reverse order to make sure the first chunk to execute sees
// its own URL at the front.
const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : [];
Object.assign(self, {
TURBOPACK_CHUNK_SUFFIX,
TURBOPACK_NEXT_CHUNK_URLS,
NEXT_DEPLOYMENT_ID
});
if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {
const scriptsToLoad = [];
for (const chunk of TURBOPACK_NEXT_CHUNK_URLS){
// Chunks are relative to the origin.
const chunkUrl = new URL(chunk, location.origin);
// Security: Only load scripts from the same origin. This prevents this
// worker entrypoint from being used as a gadget to load scripts from
// foreign origins if someone happens to find a separate XSS vector
// elsewhere on this origin.
if (chunkUrl.origin !== location.origin) {
abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`);
}
scriptsToLoad.push(chunkUrl.toString());
}
TURBOPACK_NEXT_CHUNK_URLS.reverse();
importScripts(...scriptsToLoad);
}
})();
//# sourceMappingURL=turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_output_2867ca5f._.js.map
\ No newline at end of file
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push(["output/aaf3a_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_e14430d8.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
self.onconnect = (e)=>e.ports[0].postMessage('hello');
}),
]);
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_e14430d8.js.map
\ No newline at end of file
{
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 3, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js"],"sourcesContent":["self.onconnect = (e) => e.ports[0].postMessage('hello')\n"],"names":["self","onconnect","e","ports","postMessage"],"mappings":"AAAAA,KAAKC,SAAS,GAAG,CAACC,IAAMA,EAAEC,KAAK,CAAC,EAAE,CAACC,WAAW,CAAC"}}]
}
\ No newline at end of file
(globalThis.TURBOPACK || (globalThis.TURBOPACK = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_input_3845375a._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {
__turbopack_context__.v("/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_2867ca5f._.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));
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {
const __TURBOPACK__import$2e$meta__ = {
get url () {
return `file://${__turbopack_context__.P("turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js")}`;
}
};
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)"));
}),
]);
//# sourceMappingURL=turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_input_3845375a._.js.map
\ No newline at end of file
{
"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"}}]
}
\ No newline at end of file
{"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/worker-entrypoint.ts"],"sourcesContent":["/**\n * Worker entrypoint bootstrap.\n */\n\ninterface WorkerBootstrapConfig {\n // TURBOPACK_CHUNK_SUFFIX\n S?: string\n // NEXT_DEPLOYMENT_ID\n N?: string\n // TURBOPACK_NEXT_CHUNK_URLS\n NC?: string[]\n}\n\n;(() => {\n function abort(message: string): never {\n console.error(message)\n throw new Error(message)\n }\n\n // Security: Ensure this code is running in a worker environment to prevent\n // the worker entrypoint being used as an XSS gadget. If this is a worker, we\n // know that the origin of the caller is the same as our origin.\n if (\n typeof (self as any)['WorkerGlobalScope'] === 'undefined' ||\n !(self instanceof (self as any)['WorkerGlobalScope'])\n ) {\n abort('Worker entrypoint must be loaded in a worker context')\n }\n\n const url = new URL(location.href)\n\n // Try querystring first (SharedWorker), then hash (regular Worker)\n let paramsString = url.searchParams.get('params')\n if (!paramsString && url.hash.startsWith('#params=')) {\n paramsString = decodeURIComponent(url.hash.slice('#params='.length))\n }\n\n if (!paramsString) abort('Missing worker bootstrap config')\n\n // Safety: this string requires that a script on the same origin has loaded\n // this code as a module. We still don't fully trust it, so we'll validate the\n // types and ensure that the next chunk URLs are same-origin.\n const config: WorkerBootstrapConfig = JSON.parse(paramsString)\n\n const TURBOPACK_CHUNK_SUFFIX = typeof config.S === 'string' ? config.S : ''\n const NEXT_DEPLOYMENT_ID = typeof config.N === 'string' ? config.N : ''\n // In a normal browser context, the runtime can figure out which chunk is\n // currently executing via `document.currentScript`. Workers don't have that\n // luxury, so we use `TURBOPACK_NEXT_CHUNK_URLS` as a stack instead\n // (`reverse()`d below).\n //\n // Each chunk pops its URL off the front of the array when it runs, so we need\n // to store them in reverse order to make sure the first chunk to execute sees\n // its own URL at the front.\n const TURBOPACK_NEXT_CHUNK_URLS = Array.isArray(config.NC) ? config.NC : []\n\n Object.assign(self, {\n TURBOPACK_CHUNK_SUFFIX,\n TURBOPACK_NEXT_CHUNK_URLS,\n NEXT_DEPLOYMENT_ID,\n })\n\n if (TURBOPACK_NEXT_CHUNK_URLS.length > 0) {\n const scriptsToLoad: string[] = []\n for (const chunk of TURBOPACK_NEXT_CHUNK_URLS) {\n // Chunks are relative to the origin.\n const chunkUrl = new URL(chunk, location.origin)\n // Security: Only load scripts from the same origin. This prevents this\n // worker entrypoint from being used as a gadget to load scripts from\n // foreign origins if someone happens to find a separate XSS vector\n // elsewhere on this origin.\n if (chunkUrl.origin !== location.origin) {\n abort(`Refusing to load script from foreign origin: ${chunkUrl.origin}`)\n }\n scriptsToLoad.push(chunkUrl.toString())\n }\n\n TURBOPACK_NEXT_CHUNK_URLS.reverse()\n importScripts(...scriptsToLoad)\n }\n})()\n"],"names":["abort","message","console","error","Error","self","url","URL","location","href","paramsString","searchParams","get","hash","startsWith","decodeURIComponent","slice","length","config","JSON","parse","TURBOPACK_CHUNK_SUFFIX","S","NEXT_DEPLOYMENT_ID","N","TURBOPACK_NEXT_CHUNK_URLS","Array","isArray","NC","Object","assign","scriptsToLoad","chunk","chunkUrl","origin","push","toString","reverse","importScripts"],"mappings":"AAAA;;CAEC;AAWA,CAAC;IACA,SAASA,MAAMC,OAAe;QAC5BC,QAAQC,KAAK,CAACF;QACd,MAAM,IAAIG,MAAMH;IAClB;IAEA,2EAA2E;IAC3E,6EAA6E;IAC7E,gEAAgE;IAChE,IACE,OAAO,AAACI,IAAY,CAAC,oBAAoB,KAAK,eAC9C,CAAC,CAACA,gBAAgB,AAACA,IAAY,CAAC,oBAAoB,GACpD;QACAL,MAAM;IACR;IAEA,MAAMM,MAAM,IAAIC,IAAIC,SAASC,IAAI;IAEjC,mEAAmE;IACnE,IAAIC,eAAeJ,IAAIK,YAAY,CAACC,GAAG,CAAC;IACxC,IAAI,CAACF,gBAAgBJ,IAAIO,IAAI,CAACC,UAAU,CAAC,aAAa;QACpDJ,eAAeK,mBAAmBT,IAAIO,IAAI,CAACG,KAAK,CAAC,WAAWC,MAAM;IACpE;IAEA,IAAI,CAACP,cAAcV,MAAM;IAEzB,2EAA2E;IAC3E,8EAA8E;IAC9E,6DAA6D;IAC7D,MAAMkB,SAAgCC,KAAKC,KAAK,CAACV;IAEjD,MAAMW,yBAAyB,OAAOH,OAAOI,CAAC,KAAK,WAAWJ,OAAOI,CAAC,GAAG;IACzE,MAAMC,qBAAqB,OAAOL,OAAOM,CAAC,KAAK,WAAWN,OAAOM,CAAC,GAAG;IACrE,yEAAyE;IACzE,4EAA4E;IAC5E,mEAAmE;IACnE,wBAAwB;IACxB,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,4BAA4B;IAC5B,MAAMC,4BAA4BC,MAAMC,OAAO,CAACT,OAAOU,EAAE,IAAIV,OAAOU,EAAE,GAAG,EAAE;IAE3EC,OAAOC,MAAM,CAACzB,MAAM;QAClBgB;QACAI;QACAF;IACF;IAEA,IAAIE,0BAA0BR,MAAM,GAAG,GAAG;QACxC,MAAMc,gBAA0B,EAAE;QAClC,KAAK,MAAMC,SAASP,0BAA2B;YAC7C,qCAAqC;YACrC,MAAMQ,WAAW,IAAI1B,IAAIyB,OAAOxB,SAAS0B,MAAM;YAC/C,uEAAuE;YACvE,qEAAqE;YACrE,mEAAmE;YACnE,4BAA4B;YAC5B,IAAID,SAASC,MAAM,KAAK1B,SAAS0B,MAAM,EAAE;gBACvClC,MAAM,CAAC,6CAA6C,EAAEiC,SAASC,MAAM,EAAE;YACzE;YACAH,cAAcI,IAAI,CAACF,SAASG,QAAQ;QACtC;QAEAX,0BAA0BY,OAAO;QACjCC,iBAAiBP;IACnB;AACF,CAAC","ignoreList":[0]}
\ No newline at end of file
self.onconnect = (e) => e.ports[0].postMessage('hello')
\ 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