Unverified Commit a4fff794 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Turbopack: correctly reference injected variable for Wasm on Edge (#78771)

Closes PACK-4511

Concerning that we have test coverage for this never the deployment test never ran with Turbopack: https://github.com/vercel/next.js/pull/78768

This never (?) worked: 

```js
const wasm_vercel_og__resvg = require("...");
function loadWebAssemblyModule() {
	console.log(globalThis["wasm_vercel_og__resvg"]); // undefined
}
loadWebAssemblyModule();
```



Webpack generates the following, so let's do that as well
```js
const wasm_77d9faebf7af9e421806970ce10a58e9d83116d7 = require("/wasm/wasm_77d9faebf7af9e421806970ce10a58e9d83116d7.wasm");
.....
/***/ "(rsc)/../../node_modules/.pnpm/next@15.4.0-canary.12_react-dom@19.0.0_react@19.0.0/node_modules/next/dist/compiled/@vercel/og/resvg.wasm?module":
/***/ ((module) => {
module.exports = wasm_77d9faebf7af9e421806970ce10a58e9d83116d7;
/***/ }),
```
parent ec6c7108
......@@ -4508,6 +4508,7 @@ dependencies = [
"turbopack-env",
"turbopack-node",
"turbopack-nodejs",
"turbopack-wasm",
"vergen 9.0.5",
]
......@@ -10315,6 +10316,7 @@ dependencies = [
"turbo-tasks",
"turbo-tasks-build",
"turbo-tasks-fs",
"turbo-tasks-hash",
"turbopack-core",
"turbopack-ecmascript",
"wasmparser 0.110.0",
......
......@@ -40,6 +40,7 @@ turbopack-ecmascript = { workspace = true }
turbopack-env = { workspace = true }
turbopack-node = { workspace = true }
turbopack-nodejs = { workspace = true }
turbopack-wasm = { workspace = true }
[build-dependencies]
anyhow = { workspace = true }
......
......@@ -1556,7 +1556,7 @@ impl AppEndpoint {
};
let edge_function_definition = EdgeFunctionDefinition {
files: file_paths_from_root.into_iter().collect(),
wasm: wasm_paths_to_bindings(wasm_paths_from_root.into_iter().collect()),
wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?,
assets: paths_to_bindings(all_assets),
name: app_entry.pathname.clone(),
page: app_entry.original_name.clone(),
......
......@@ -187,7 +187,7 @@ impl InstrumentationEndpoint {
let instrumentation_definition = InstrumentationDefinition {
files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root),
wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?,
name: "instrumentation".into(),
..Default::default()
};
......
......@@ -304,7 +304,7 @@ impl MiddlewareEndpoint {
let edge_function_definition = EdgeFunctionDefinition {
files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root),
wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?,
assets: paths_to_bindings(all_assets),
name: "middleware".into(),
page: "/".into(),
......
......@@ -30,8 +30,8 @@ use serde::{Deserialize, Serialize};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{
fxindexmap, trace::TraceRawVcs, Completion, FxIndexMap, NonLocalValue, ResolvedVc, TaskInput,
Value, ValueToString, Vc,
fxindexmap, fxindexset, trace::TraceRawVcs, Completion, FxIndexMap, NonLocalValue, ResolvedVc,
TaskInput, Value, ValueToString, Vc,
};
use turbo_tasks_fs::{
self, File, FileContent, FileSystem, FileSystemPath, FileSystemPathOption, VirtualFileSystem,
......@@ -1375,7 +1375,7 @@ impl PageEndpoint {
"server/middleware-build-manifest.js".into(),
"server/next-font-manifest.js".into(),
];
let mut wasm_paths_from_root = vec![];
let mut wasm_paths_from_root = fxindexset![];
let node_root_value = node_root.await?;
......@@ -1404,7 +1404,7 @@ impl PageEndpoint {
let original_name = this.original_name.owned().await?;
let edge_function_definition = EdgeFunctionDefinition {
files: file_paths_from_root,
wasm: wasm_paths_to_bindings(wasm_paths_from_root),
wasm: wasm_paths_to_bindings(wasm_paths_from_root).await?,
assets: paths_to_bindings(all_assets),
name: pathname.clone(),
page: original_name.clone(),
......
......@@ -3,12 +3,15 @@ use next_core::{all_assets_from_entries, next_manifests::AssetBinding};
use serde::{Deserialize, Serialize};
use tracing::Instrument;
use turbo_rcstr::RcStr;
use turbo_tasks::{trace::TraceRawVcs, NonLocalValue, ResolvedVc, TryFlatJoinIterExt, Vc};
use turbo_tasks::{
trace::TraceRawVcs, NonLocalValue, ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc,
};
use turbo_tasks_fs::FileSystemPath;
use turbopack_core::{
asset::{Asset, AssetContent},
output::{OutputAsset, OutputAssets},
};
use turbopack_wasm::wasm_edge_var_name;
/// A reference to a server file with content hash for change detection
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, TraceRawVcs, NonLocalValue)]
......@@ -109,8 +112,23 @@ pub(crate) async fn get_js_paths_from_root(
pub(crate) async fn get_wasm_paths_from_root(
root: &FileSystemPath,
output_assets: impl IntoIterator<Item = &ResolvedVc<Box<dyn OutputAsset>>>,
) -> Result<Vec<RcStr>> {
get_paths_from_root(root, output_assets, |path| path.ends_with(".wasm")).await
) -> Result<Vec<(RcStr, ResolvedVc<Box<dyn OutputAsset>>)>> {
output_assets
.into_iter()
.map(move |&file| async move {
let path = &*file.path().await?;
let Some(relative) = root.get_path_to(path) else {
return Ok(None);
};
Ok(if relative.ends_with(".wasm") {
Some((relative.into(), file))
} else {
None
})
})
.try_flat_join()
.await
}
pub(crate) async fn get_asset_paths_from_root(
......@@ -137,42 +155,19 @@ pub(crate) async fn get_font_paths_from_root(
.await
}
fn get_file_stem(path: &str) -> &str {
let file_name = if let Some((_, file_name)) = path.rsplit_once('/') {
file_name
} else {
path
};
if let Some((stem, _)) = file_name.split_once('.') {
if stem.is_empty() {
file_name
} else {
stem
}
} else {
file_name
}
}
pub(crate) fn wasm_paths_to_bindings(paths: Vec<RcStr>) -> Vec<AssetBinding> {
pub(crate) async fn wasm_paths_to_bindings(
paths: impl IntoIterator<Item = (RcStr, ResolvedVc<Box<dyn OutputAsset>>)>,
) -> Result<Vec<AssetBinding>> {
paths
.into_iter()
.map(|path| {
let stem = get_file_stem(&path);
// very simple escaping just replacing unsupported characters with `_`
let escaped = stem.replace(
|c: char| !c.is_ascii_alphanumeric() && c != '$' && c != '_',
"_",
);
AssetBinding {
name: format!("wasm_{}", escaped).into(),
.map(async |(path, asset)| {
Ok(AssetBinding {
name: wasm_edge_var_name(Vc::upcast(*asset)).owned().await?,
file_path: path,
}
})
})
.collect()
.try_join()
.await
}
pub(crate) fn paths_to_bindings(paths: Vec<RcStr>) -> Vec<AssetBinding> {
......
......@@ -14,10 +14,12 @@ declare var BACKEND: RuntimeBackend
declare var loadWebAssembly: (
source: SourceInfo,
wasmChunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module,
imports: WebAssembly.Imports
) => Exports
declare var loadWebAssemblyModule: (
source: SourceInfo,
wasmChunkPath: ChunkPath
wasmChunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module
) => WebAssembly.Module
declare var relativeURL: (inputUrl: string) => void
......@@ -31,6 +31,7 @@ function fetchWebAssembly(wasmChunkPath: ChunkPath) {
async function loadWebAssembly(
_source: unknown,
wasmChunkPath: ChunkPath,
_edgeModule: () => WebAssembly.Module,
importsObj: WebAssembly.Imports
): Promise<Exports> {
const req = fetchWebAssembly(wasmChunkPath)
......@@ -42,7 +43,8 @@ async function loadWebAssembly(
async function loadWebAssemblyModule(
_source: unknown,
wasmChunkPath: ChunkPath
wasmChunkPath: ChunkPath,
_edgeModule: () => WebAssembly.Module
): Promise<WebAssembly.Module> {
const req = fetchWebAssembly(wasmChunkPath)
......
......@@ -43,9 +43,10 @@ function augmentContext(
async function loadWebAssembly(
source: SourceInfo,
chunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module,
imports: WebAssembly.Imports
): Promise<Exports> {
const module = await loadWebAssemblyModule(source, chunkPath)
const module = await loadWebAssemblyModule(source, chunkPath, edgeModule)
return await WebAssembly.instantiate(module, imports)
}
......@@ -62,26 +63,19 @@ function getFileStem(path: string): string {
return stem
}
type GlobalWithInjectedWebAssembly = typeof globalThis & {
[key: `wasm_${string}`]: WebAssembly.Module
}
async function loadWebAssemblyModule(
_source: SourceInfo,
chunkPath: ChunkPath
chunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module
): Promise<WebAssembly.Module> {
const stem = getFileStem(chunkPath)
// very simple escaping just replacing unsupported characters with `_`
const escaped = stem.replace(/[^a-zA-Z0-9$_]/gi, '_')
const identifier: `wasm_${string}` = `wasm_${escaped}`
const module = (globalThis as GlobalWithInjectedWebAssembly)[identifier]
let module
try {
module = edgeModule()
} catch (_e) {}
if (!module) {
throw new Error(
`dynamically loading WebAssembly is not supported in this runtime and global \`${identifier}\` was not injected`
`dynamically loading WebAssembly is not supported in this runtime as global was not injected for chunk '${chunkPath}'`
)
}
......
......@@ -190,13 +190,20 @@ async function loadChunkAsyncByUrl(source: SourceInfo, chunkUrl: string) {
return loadChunkAsync(source, path)
}
function loadWebAssembly(chunkPath: ChunkPath, imports: WebAssembly.Imports) {
function loadWebAssembly(
chunkPath: ChunkPath,
_edgeModule: () => WebAssembly.Module,
imports: WebAssembly.Imports
) {
const resolved = path.resolve(RUNTIME_ROOT, chunkPath)
return instantiateWebAssemblyFromPath(resolved, imports)
}
function loadWebAssemblyModule(chunkPath: ChunkPath) {
function loadWebAssemblyModule(
chunkPath: ChunkPath,
_edgeModule: () => WebAssembly.Module
) {
const resolved = path.resolve(RUNTIME_ROOT, chunkPath)
return compileWebAssemblyFromPath(resolved)
......
......@@ -45,9 +45,13 @@ type LoadChunk = (chunkPath: ChunkPath) => Promise<any> | undefined
type LoadChunkByUrl = (chunkUrl: ChunkUrl) => Promise<any> | undefined
type LoadWebAssembly = (
wasmChunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module,
imports: WebAssembly.Imports
) => Exports
type LoadWebAssemblyModule = (wasmChunkPath: ChunkPath) => WebAssembly.Module
type LoadWebAssemblyModule = (
wasmChunkPath: ChunkPath,
edgeModule: () => WebAssembly.Module
) => WebAssembly.Module
type ModuleCache<M> = Record<ModuleId, M>
type ModuleFactories = Record<ModuleId, unknown>
......
......@@ -540,11 +540,11 @@ async function loadChunkAsyncByUrl(source, chunkUrl) {
const path1 = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT));
return loadChunkAsync(source, path1);
}
function loadWebAssembly(chunkPath, imports) {
function loadWebAssembly(chunkPath, _edgeModule, imports) {
const resolved = path.resolve(RUNTIME_ROOT, chunkPath);
return instantiateWebAssemblyFromPath(resolved, imports);
}
function loadWebAssemblyModule(chunkPath) {
function loadWebAssemblyModule(chunkPath, _edgeModule) {
const resolved = path.resolve(RUNTIME_ROOT, chunkPath);
return compileWebAssemblyFromPath(resolved);
}
......
......@@ -6,5 +6,5 @@
{"offset": {"line": 337, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/base-externals-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../shared/runtime-utils.ts\" />\n\n/// A 'base' utilities to support runtime can have externals.\n/// Currently this is for node.js / edge runtime both.\n/// If a fn requires node.js specific behavior, it should be placed in `node-external-utils` instead.\n\nasync function externalImport(id: ModuleId) {\n let raw\n try {\n raw = await import(id)\n } catch (err) {\n // TODO(alexkirsz) This can happen when a client-side module tries to load\n // an external module we don't provide a shim for (e.g. querystring, url).\n // For now, we fail semi-silently, but in the future this should be a\n // compilation error.\n throw new Error(`Failed to load external module ${id}: ${err}`)\n }\n\n if (raw && raw.__esModule && raw.default && 'default' in raw.default) {\n return interopEsm(raw.default, createNS(raw), true)\n }\n\n return raw\n}\n\nfunction externalRequire(\n id: ModuleId,\n thunk: () => any,\n esm: boolean = false\n): Exports | EsmNamespaceObject {\n let raw\n try {\n raw = thunk()\n } catch (err) {\n // TODO(alexkirsz) This can happen when a client-side module tries to load\n // an external module we don't provide a shim for (e.g. querystring, url).\n // For now, we fail semi-silently, but in the future this should be a\n // compilation error.\n throw new Error(`Failed to load external module ${id}: ${err}`)\n }\n\n if (!esm || raw.__esModule) {\n return raw\n }\n\n return interopEsm(raw, createNS(raw), true)\n}\n\nexternalRequire.resolve = (\n id: string,\n options?: {\n paths?: string[]\n }\n) => {\n return require.resolve(id, options)\n}\n"],"names":[],"mappings":"AAAA,oDAAoD,GAEpD,mDAAmD;AAEnD,6DAA6D;AAC7D,sDAAsD;AACtD,qGAAqG;AAErG,eAAe,eAAe,EAAY;IACxC,IAAI;IACJ,IAAI;QACF,MAAM,MAAM,MAAM,CAAC;IACrB,EAAE,OAAO,KAAK;QACZ,0EAA0E;QAC1E,0EAA0E;QAC1E,qEAAqE;QACrE,qBAAqB;QACrB,MAAM,IAAI,MAAM,CAAC,+BAA+B,EAAE,GAAG,EAAE,EAAE,KAAK;IAChE;IAEA,IAAI,OAAO,IAAI,UAAU,IAAI,IAAI,OAAO,IAAI,aAAa,IAAI,OAAO,EAAE;QACpE,OAAO,WAAW,IAAI,OAAO,EAAE,SAAS,MAAM;IAChD;IAEA,OAAO;AACT;AAEA,SAAS,gBACP,EAAY,EACZ,KAAgB,EAChB,MAAe,KAAK;IAEpB,IAAI;IACJ,IAAI;QACF,MAAM;IACR,EAAE,OAAO,KAAK;QACZ,0EAA0E;QAC1E,0EAA0E;QAC1E,qEAAqE;QACrE,qBAAqB;QACrB,MAAM,IAAI,MAAM,CAAC,+BAA+B,EAAE,GAAG,EAAE,EAAE,KAAK;IAChE;IAEA,IAAI,CAAC,OAAO,IAAI,UAAU,EAAE;QAC1B,OAAO;IACT;IAEA,OAAO,WAAW,KAAK,SAAS,MAAM;AACxC;AAEA,gBAAgB,OAAO,GAAG,CACxB,IACA;IAIA,OAAO,QAAQ,OAAO,CAAC,IAAI;AAC7B","ignoreList":[0]}},
{"offset": {"line": 376, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/node-externals-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\ndeclare var RUNTIME_PUBLIC_PATH: string\ndeclare var RELATIVE_ROOT_PATH: string\ndeclare var ASSET_PREFIX: string\n\nconst path = require('path')\n\nconst relativePathToRuntimeRoot = path.relative(RUNTIME_PUBLIC_PATH, '.')\n// Compute the relative path to the `distDir`.\nconst relativePathToDistRoot = path.join(\n relativePathToRuntimeRoot,\n RELATIVE_ROOT_PATH\n)\nconst RUNTIME_ROOT = path.resolve(__filename, relativePathToRuntimeRoot)\n// Compute the absolute path to the root, by stripping distDir from the absolute path to this file.\nconst ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot)\n\n/**\n * Returns an absolute path to the given module path.\n * Module path should be relative, either path to a file or a directory.\n *\n * This fn allows to calculate an absolute path for some global static values, such as\n * `__dirname` or `import.meta.url` that Turbopack will not embeds in compile time.\n * See ImportMetaBinding::code_generation for the usage.\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n if (modulePath) {\n return path.join(ABSOLUTE_ROOT, modulePath)\n }\n return ABSOLUTE_ROOT\n}\n"],"names":[],"mappings":"AAAA,oDAAoD,GAMpD,MAAM,OAAO,QAAQ;AAErB,MAAM,4BAA4B,KAAK,QAAQ,CAAC,qBAAqB;AACrE,8CAA8C;AAC9C,MAAM,yBAAyB,KAAK,IAAI,CACtC,2BACA;AAEF,MAAM,eAAe,KAAK,OAAO,CAAC,YAAY;AAC9C,mGAAmG;AACnG,MAAM,gBAAgB,KAAK,OAAO,CAAC,YAAY;AAE/C;;;;;;;CAOC,GACD,SAAS,oBAAoB,UAAmB;IAC9C,IAAI,YAAY;QACd,OAAO,KAAK,IAAI,CAAC,eAAe;IAClC;IACA,OAAO;AACT","ignoreList":[0]}},
{"offset": {"line": 396, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/node-wasm-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../shared/runtime-utils.ts\" />\n\nfunction readWebAssemblyAsResponse(path: string) {\n const { createReadStream } = require('fs') as typeof import('fs')\n const { Readable } = require('stream') as typeof import('stream')\n\n const stream = createReadStream(path)\n\n // @ts-ignore unfortunately there's a slight type mismatch with the stream.\n return new Response(Readable.toWeb(stream), {\n headers: {\n 'content-type': 'application/wasm',\n },\n })\n}\n\nasync function compileWebAssemblyFromPath(\n path: string\n): Promise<WebAssembly.Module> {\n const response = readWebAssemblyAsResponse(path)\n\n return await WebAssembly.compileStreaming(response)\n}\n\nasync function instantiateWebAssemblyFromPath(\n path: string,\n importsObj: WebAssembly.Imports\n): Promise<Exports> {\n const response = readWebAssemblyAsResponse(path)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n response,\n importsObj\n )\n\n return instance.exports\n}\n"],"names":[],"mappings":"AAAA,oDAAoD,GAEpD,mDAAmD;AAEnD,SAAS,0BAA0B,IAAY;IAC7C,MAAM,EAAE,gBAAgB,EAAE,GAAG,QAAQ;IACrC,MAAM,EAAE,QAAQ,EAAE,GAAG,QAAQ;IAE7B,MAAM,SAAS,iBAAiB;IAEhC,2EAA2E;IAC3E,OAAO,IAAI,SAAS,SAAS,KAAK,CAAC,SAAS;QAC1C,SAAS;YACP,gBAAgB;QAClB;IACF;AACF;AAEA,eAAe,2BACb,IAAY;IAEZ,MAAM,WAAW,0BAA0B;IAE3C,OAAO,MAAM,YAAY,gBAAgB,CAAC;AAC5C;AAEA,eAAe,+BACb,IAAY,EACZ,UAA+B;IAE/B,MAAM,WAAW,0BAA0B;IAE3C,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,YAAY,oBAAoB,CACzD,UACA;IAGF,OAAO,SAAS,OAAO;AACzB","ignoreList":[0]}},
{"offset": {"line": 417, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/runtime.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../shared/runtime-utils.ts\" />\n/// <reference path=\"../shared-node/base-externals-utils.ts\" />\n/// <reference path=\"../shared-node/node-externals-utils.ts\" />\n/// <reference path=\"../shared-node/node-wasm-utils.ts\" />\n\nenum SourceType {\n /**\n * The module was instantiated because it was included in an evaluated chunk's\n * runtime.\n */\n Runtime = 0,\n /**\n * The module was instantiated because a parent module imported it.\n */\n Parent = 1,\n}\n\ntype SourceInfo =\n | {\n type: SourceType.Runtime\n chunkPath: ChunkPath\n }\n | {\n type: SourceType.Parent\n parentId: ModuleId\n }\n\nprocess.env.TURBOPACK = '1'\n\nfunction stringifySourceInfo(source: SourceInfo): string {\n switch (source.type) {\n case SourceType.Runtime:\n return `runtime for chunk ${source.chunkPath}`\n case SourceType.Parent:\n return `parent module ${source.parentId}`\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`)\n }\n}\n\ntype ExternalRequire = (\n id: ModuleId,\n thunk: () => any,\n esm?: boolean\n) => Exports | EsmNamespaceObject\ntype ExternalImport = (id: ModuleId) => Promise<Exports | EsmNamespaceObject>\n\ninterface TurbopackNodeBuildContext extends TurbopackBaseContext<Module> {\n R: ResolvePathFromModule\n x: ExternalRequire\n y: ExternalImport\n}\n\ntype ModuleFactory = (\n this: Module['exports'],\n context: TurbopackNodeBuildContext\n) => undefined\n\nconst url = require('url') as typeof import('url')\nconst fs = require('fs/promises') as typeof import('fs/promises')\n\nconst moduleFactories: ModuleFactories = Object.create(null)\nconst moduleCache: ModuleCache<ModuleWithDirection> = Object.create(null)\n\n/**\n * Returns an absolute path to the given module's id.\n */\nfunction createResolvePathFromModule(\n resolver: (moduleId: string) => Exports\n): (moduleId: string) => string {\n return function resolvePathFromModule(moduleId: string): string {\n const exported = resolver(moduleId)\n const exportedPath = exported?.default ?? exported\n if (typeof exportedPath !== 'string') {\n return exported as any\n }\n\n const strippedAssetPrefix = exportedPath.slice(ASSET_PREFIX.length)\n const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix)\n\n return url.pathToFileURL(resolved).href\n }\n}\n\nfunction loadChunk(chunkData: ChunkData, source?: SourceInfo): void {\n if (typeof chunkData === 'string') {\n return loadChunkPath(chunkData, source)\n } else {\n return loadChunkPath(chunkData.path, source)\n }\n}\n\nconst loadedChunks = new Set<ChunkPath>()\n\nfunction loadChunkPath(chunkPath: ChunkPath, source?: SourceInfo): void {\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return\n }\n\n if (loadedChunks.has(chunkPath)) {\n return\n }\n\n try {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n const chunkModules: ModuleFactories = require(resolved)\n\n for (const [moduleId, moduleFactory] of Object.entries(chunkModules)) {\n if (!moduleFactories[moduleId]) {\n moduleFactories[moduleId] = moduleFactory\n }\n }\n loadedChunks.add(chunkPath)\n } catch (e) {\n let errorMessage = `Failed to load chunk ${chunkPath}`\n\n if (source) {\n errorMessage += ` from ${stringifySourceInfo(source)}`\n }\n\n throw new Error(errorMessage, {\n cause: e,\n })\n }\n}\n\nasync function loadChunkAsync(\n source: SourceInfo,\n chunkData: ChunkData\n): Promise<any> {\n const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return\n }\n\n if (loadedChunks.has(chunkPath)) {\n return\n }\n\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n try {\n const contents = await fs.readFile(resolved, 'utf-8')\n\n const localRequire = (id: string) => {\n let resolvedId = require.resolve(id, { paths: [path.dirname(resolved)] })\n return require(resolvedId)\n }\n const module = {\n exports: {},\n }\n // TODO: Use vm.runInThisContext once our minimal supported Node.js version includes https://github.com/nodejs/node/pull/52153\n // eslint-disable-next-line no-eval -- Can't use vm.runInThisContext due to https://github.com/nodejs/node/issues/52102\n ;(0, eval)(\n '(function(module, exports, require, __dirname, __filename) {' +\n contents +\n '\\n})' +\n '\\n//# sourceURL=' +\n url.pathToFileURL(resolved)\n )(module, module.exports, localRequire, path.dirname(resolved), resolved)\n\n const chunkModules: ModuleFactories = module.exports\n for (const [moduleId, moduleFactory] of Object.entries(chunkModules)) {\n if (!moduleFactories[moduleId]) {\n moduleFactories[moduleId] = moduleFactory\n }\n }\n loadedChunks.add(chunkPath)\n } catch (e) {\n let errorMessage = `Failed to load chunk ${chunkPath}`\n\n if (source) {\n errorMessage += ` from ${stringifySourceInfo(source)}`\n }\n\n throw new Error(errorMessage, {\n cause: e,\n })\n }\n}\n\nasync function loadChunkAsyncByUrl(source: SourceInfo, chunkUrl: string) {\n const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath\n return loadChunkAsync(source, path)\n}\n\nfunction loadWebAssembly(chunkPath: ChunkPath, imports: WebAssembly.Imports) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return instantiateWebAssemblyFromPath(resolved, imports)\n}\n\nfunction loadWebAssemblyModule(chunkPath: ChunkPath) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return compileWebAssemblyFromPath(resolved)\n}\n\nfunction getWorkerBlobURL(_chunks: ChunkPath[]): string {\n throw new Error('Worker blobs are not implemented yet for Node.js')\n}\n\nfunction instantiateModule(\n id: ModuleId,\n source: SourceInfo\n): ModuleWithDirection {\n const moduleFactory = moduleFactories[id]\n if (typeof moduleFactory !== 'function') {\n // This can happen if modules incorrectly handle HMR disposes/updates,\n // e.g. when they keep a `setTimeout` around which still executes old code\n // and contains e.g. a `require(\"something\")` call.\n let instantiationReason\n switch (source.type) {\n case SourceType.Runtime:\n instantiationReason = `as a runtime entry of chunk ${source.chunkPath}`\n break\n case SourceType.Parent:\n instantiationReason = `because it was required from module ${source.parentId}`\n break\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`)\n }\n throw new Error(\n `Module ${id} was instantiated ${instantiationReason}, but the module factory is not available. It might have been deleted in an HMR update.`\n )\n }\n\n let parents: ModuleId[]\n switch (source.type) {\n case SourceType.Runtime:\n parents = []\n break\n case SourceType.Parent:\n // No need to add this module as a child of the parent module here, this\n // has already been taken care of in `getOrInstantiateModuleFromParent`.\n parents = [source.parentId]\n break\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`)\n }\n\n const module: ModuleWithDirection = {\n exports: {},\n error: undefined,\n loaded: false,\n id,\n parents,\n children: [],\n namespaceObject: undefined,\n }\n moduleCache[id] = module\n\n // NOTE(alexkirsz) This can fail when the module encounters a runtime error.\n try {\n const r = commonJsRequire.bind(null, module)\n moduleFactory.call(module.exports, {\n a: asyncModule.bind(null, module),\n e: module.exports,\n r,\n t: runtimeRequire,\n x: externalRequire,\n y: externalImport,\n f: moduleContext,\n i: esmImport.bind(null, module),\n s: esmExport.bind(null, module, module.exports),\n j: dynamicExport.bind(null, module, module.exports),\n v: exportValue.bind(null, module),\n n: exportNamespace.bind(null, module),\n m: module,\n c: moduleCache,\n M: moduleFactories,\n l: loadChunkAsync.bind(null, { type: SourceType.Parent, parentId: id }),\n L: loadChunkAsyncByUrl.bind(null, {\n type: SourceType.Parent,\n parentId: id,\n }),\n w: loadWebAssembly,\n u: loadWebAssemblyModule,\n g: globalThis,\n P: resolveAbsolutePath,\n U: relativeURL,\n R: createResolvePathFromModule(r),\n b: getWorkerBlobURL,\n z: requireStub,\n __dirname:\n typeof module.id === 'string'\n ? module.id.replace(/(^|\\/)\\/+$/, '')\n : module.id,\n })\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n module.loaded = true\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore\nfunction getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: ModuleWithDirection\n): ModuleWithDirection {\n const module = moduleCache[id]\n\n if (sourceModule.children.indexOf(id) === -1) {\n sourceModule.children.push(id)\n }\n\n if (module) {\n if (module.parents.indexOf(sourceModule.id) === -1) {\n module.parents.push(sourceModule.id)\n }\n\n return module\n }\n\n return instantiateModule(id, {\n type: SourceType.Parent,\n parentId: sourceModule.id,\n })\n}\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, { type: SourceType.Runtime, chunkPath })\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.\n */\n// @ts-ignore TypeScript doesn't separate this module space from the browser runtime\nfunction getOrInstantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n const module = moduleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n return instantiateRuntimeModule(moduleId, chunkPath)\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nmodule.exports = {\n getOrInstantiateRuntimeModule,\n loadChunk,\n}\n"],"names":[],"mappings":"AAAA,oDAAoD,GAEpD,mDAAmD;AACnD,+DAA+D;AAC/D,+DAA+D;AAC/D,0DAA0D;AAE1D,IAAA,AAAK,oCAAA;IACH;;;GAGC;IAED;;GAEC;WARE;EAAA;AAsBL,QAAQ,GAAG,CAAC,SAAS,GAAG;AAExB,SAAS,oBAAoB,MAAkB;IAC7C,OAAQ,OAAO,IAAI;QACjB;YACE,OAAO,CAAC,kBAAkB,EAAE,OAAO,SAAS,EAAE;QAChD;YACE,OAAO,CAAC,cAAc,EAAE,OAAO,QAAQ,EAAE;QAC3C;YACE,UAAU,QAAQ,CAAC,SAAW,CAAC,qBAAqB,EAAE,QAAQ,MAAM;IACxE;AACF;AAoBA,MAAM,MAAM,QAAQ;AACpB,MAAM,KAAK,QAAQ;AAEnB,MAAM,kBAAmC,OAAO,MAAM,CAAC;AACvD,MAAM,cAAgD,OAAO,MAAM,CAAC;AAEpE;;CAEC,GACD,SAAS,4BACP,QAAuC;IAEvC,OAAO,SAAS,sBAAsB,QAAgB;QACpD,MAAM,WAAW,SAAS;QAC1B,MAAM,eAAe,UAAU,WAAW;QAC1C,IAAI,OAAO,iBAAiB,UAAU;YACpC,OAAO;QACT;QAEA,MAAM,sBAAsB,aA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AAI,QAAO,KAAK,EAAE;YAChB,MAAM,QAAO,KAAK;QACpB;QACA,OAAO;IACT;IAEA,OAAO,yBAAyB,UAAU;AAC5C;AAEA,MAAM,aAAa;AACnB;;CAEC,GACD,SAAS,KAAK,cAAoC;IAChD,OAAO,WAAW,IAAI,CAAC;AACzB;AAEA,OAAO,OAAO,GAAG;IACf;IACA;AACF","ignoreList":[0]}}]
{"offset": {"line": 417, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/runtime.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../shared/runtime-utils.ts\" />\n/// <reference path=\"../shared-node/base-externals-utils.ts\" />\n/// <reference path=\"../shared-node/node-externals-utils.ts\" />\n/// <reference path=\"../shared-node/node-wasm-utils.ts\" />\n\nenum SourceType {\n /**\n * The module was instantiated because it was included in an evaluated chunk's\n * runtime.\n */\n Runtime = 0,\n /**\n * The module was instantiated because a parent module imported it.\n */\n Parent = 1,\n}\n\ntype SourceInfo =\n | {\n type: SourceType.Runtime\n chunkPath: ChunkPath\n }\n | {\n type: SourceType.Parent\n parentId: ModuleId\n }\n\nprocess.env.TURBOPACK = '1'\n\nfunction stringifySourceInfo(source: SourceInfo): string {\n switch (source.type) {\n case SourceType.Runtime:\n return `runtime for chunk ${source.chunkPath}`\n case SourceType.Parent:\n return `parent module ${source.parentId}`\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`)\n }\n}\n\ntype ExternalRequire = (\n id: ModuleId,\n thunk: () => any,\n esm?: boolean\n) => Exports | EsmNamespaceObject\ntype ExternalImport = (id: ModuleId) => Promise<Exports | EsmNamespaceObject>\n\ninterface TurbopackNodeBuildContext extends TurbopackBaseContext<Module> {\n R: ResolvePathFromModule\n x: ExternalRequire\n y: ExternalImport\n}\n\ntype ModuleFactory = (\n this: Module['exports'],\n context: TurbopackNodeBuildContext\n) => undefined\n\nconst url = require('url') as typeof import('url')\nconst fs = require('fs/promises') as typeof import('fs/promises')\n\nconst moduleFactories: ModuleFactories = Object.create(null)\nconst moduleCache: ModuleCache<ModuleWithDirection> = Object.create(null)\n\n/**\n * Returns an absolute path to the given module's id.\n */\nfunction createResolvePathFromModule(\n resolver: (moduleId: string) => Exports\n): (moduleId: string) => string {\n return function resolvePathFromModule(moduleId: string): string {\n const exported = resolver(moduleId)\n const exportedPath = exported?.default ?? exported\n if (typeof exportedPath !== 'string') {\n return exported as any\n }\n\n const strippedAssetPrefix = exportedPath.slice(ASSET_PREFIX.length)\n const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix)\n\n return url.pathToFileURL(resolved).href\n }\n}\n\nfunction loadChunk(chunkData: ChunkData, source?: SourceInfo): void {\n if (typeof chunkData === 'string') {\n return loadChunkPath(chunkData, source)\n } else {\n return loadChunkPath(chunkData.path, source)\n }\n}\n\nconst loadedChunks = new Set<ChunkPath>()\n\nfunction loadChunkPath(chunkPath: ChunkPath, source?: SourceInfo): void {\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return\n }\n\n if (loadedChunks.has(chunkPath)) {\n return\n }\n\n try {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n const chunkModules: ModuleFactories = require(resolved)\n\n for (const [moduleId, moduleFactory] of Object.entries(chunkModules)) {\n if (!moduleFactories[moduleId]) {\n moduleFactories[moduleId] = moduleFactory\n }\n }\n loadedChunks.add(chunkPath)\n } catch (e) {\n let errorMessage = `Failed to load chunk ${chunkPath}`\n\n if (source) {\n errorMessage += ` from ${stringifySourceInfo(source)}`\n }\n\n throw new Error(errorMessage, {\n cause: e,\n })\n }\n}\n\nasync function loadChunkAsync(\n source: SourceInfo,\n chunkData: ChunkData\n): Promise<any> {\n const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return\n }\n\n if (loadedChunks.has(chunkPath)) {\n return\n }\n\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n try {\n const contents = await fs.readFile(resolved, 'utf-8')\n\n const localRequire = (id: string) => {\n let resolvedId = require.resolve(id, { paths: [path.dirname(resolved)] })\n return require(resolvedId)\n }\n const module = {\n exports: {},\n }\n // TODO: Use vm.runInThisContext once our minimal supported Node.js version includes https://github.com/nodejs/node/pull/52153\n // eslint-disable-next-line no-eval -- Can't use vm.runInThisContext due to https://github.com/nodejs/node/issues/52102\n ;(0, eval)(\n '(function(module, exports, require, __dirname, __filename) {' +\n contents +\n '\\n})' +\n '\\n//# sourceURL=' +\n url.pathToFileURL(resolved)\n )(module, module.exports, localRequire, path.dirname(resolved), resolved)\n\n const chunkModules: ModuleFactories = module.exports\n for (const [moduleId, moduleFactory] of Object.entries(chunkModules)) {\n if (!moduleFactories[moduleId]) {\n moduleFactories[moduleId] = moduleFactory\n }\n }\n loadedChunks.add(chunkPath)\n } catch (e) {\n let errorMessage = `Failed to load chunk ${chunkPath}`\n\n if (source) {\n errorMessage += ` from ${stringifySourceInfo(source)}`\n }\n\n throw new Error(errorMessage, {\n cause: e,\n })\n }\n}\n\nasync function loadChunkAsyncByUrl(source: SourceInfo, chunkUrl: string) {\n const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath\n return loadChunkAsync(source, path)\n}\n\nfunction loadWebAssembly(\n chunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n imports: WebAssembly.Imports\n) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return instantiateWebAssemblyFromPath(resolved, imports)\n}\n\nfunction loadWebAssemblyModule(\n chunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return compileWebAssemblyFromPath(resolved)\n}\n\nfunction getWorkerBlobURL(_chunks: ChunkPath[]): string {\n throw new Error('Worker blobs are not implemented yet for Node.js')\n}\n\nfunction instantiateModule(\n id: ModuleId,\n source: SourceInfo\n): ModuleWithDirection {\n const moduleFactory = moduleFactories[id]\n if (typeof moduleFactory !== 'function') {\n // This can happen if modules incorrectly handle HMR disposes/updates,\n // e.g. when they keep a `setTimeout` around which still executes old code\n // and contains e.g. a `require(\"something\")` call.\n let instantiationReason\n switch (source.type) {\n case SourceType.Runtime:\n instantiationReason = `as a runtime entry of chunk ${source.chunkPath}`\n break\n case SourceType.Parent:\n instantiationReason = `because it was required from module ${source.parentId}`\n break\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`)\n }\n throw new Error(\n `Module ${id} was instantiated ${instantiationReason}, but the module factory is not available. It might have been deleted in an HMR update.`\n )\n }\n\n let parents: ModuleId[]\n switch (source.type) {\n case SourceType.Runtime:\n parents = []\n break\n case SourceType.Parent:\n // No need to add this module as a child of the parent module here, this\n // has already been taken care of in `getOrInstantiateModuleFromParent`.\n parents = [source.parentId]\n break\n default:\n invariant(source, (source) => `Unknown source type: ${source?.type}`)\n }\n\n const module: ModuleWithDirection = {\n exports: {},\n error: undefined,\n loaded: false,\n id,\n parents,\n children: [],\n namespaceObject: undefined,\n }\n moduleCache[id] = module\n\n // NOTE(alexkirsz) This can fail when the module encounters a runtime error.\n try {\n const r = commonJsRequire.bind(null, module)\n moduleFactory.call(module.exports, {\n a: asyncModule.bind(null, module),\n e: module.exports,\n r,\n t: runtimeRequire,\n x: externalRequire,\n y: externalImport,\n f: moduleContext,\n i: esmImport.bind(null, module),\n s: esmExport.bind(null, module, module.exports),\n j: dynamicExport.bind(null, module, module.exports),\n v: exportValue.bind(null, module),\n n: exportNamespace.bind(null, module),\n m: module,\n c: moduleCache,\n M: moduleFactories,\n l: loadChunkAsync.bind(null, { type: SourceType.Parent, parentId: id }),\n L: loadChunkAsyncByUrl.bind(null, {\n type: SourceType.Parent,\n parentId: id,\n }),\n w: loadWebAssembly,\n u: loadWebAssemblyModule,\n g: globalThis,\n P: resolveAbsolutePath,\n U: relativeURL,\n R: createResolvePathFromModule(r),\n b: getWorkerBlobURL,\n z: requireStub,\n __dirname:\n typeof module.id === 'string'\n ? module.id.replace(/(^|\\/)\\/+$/, '')\n : module.id,\n })\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n module.loaded = true\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore\nfunction getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: ModuleWithDirection\n): ModuleWithDirection {\n const module = moduleCache[id]\n\n if (sourceModule.children.indexOf(id) === -1) {\n sourceModule.children.push(id)\n }\n\n if (module) {\n if (module.parents.indexOf(sourceModule.id) === -1) {\n module.parents.push(sourceModule.id)\n }\n\n return module\n }\n\n return instantiateModule(id, {\n type: SourceType.Parent,\n parentId: sourceModule.id,\n })\n}\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n return instantiateModule(moduleId, { type: SourceType.Runtime, chunkPath })\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.\n */\n// @ts-ignore TypeScript doesn't separate this module space from the browser runtime\nfunction getOrInstantiateRuntimeModule(\n moduleId: ModuleId,\n chunkPath: ChunkPath\n): Module {\n const module = moduleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n return instantiateRuntimeModule(moduleId, chunkPath)\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nmodule.exports = {\n getOrInstantiateRuntimeModule,\n loadChunk,\n}\n"],"names":[],"mappings":"AAAA,oDA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AAE;QACvE,yDAAyD;QACzD,WAAW,QAAO,OAAO,EAAE,QAAO,eAAe;IACnD;IAEA,OAAO;AACT;AAEA;;CAEC,GACD,aAAa;AACb,SAAS,iCACP,EAAY,EACZ,YAAiC;IAEjC,MAAM,UAAS,WAAW,CAAC,GAAG;IAE9B,IAAI,aAAa,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG;QAC5C,aAAa,QAAQ,CAAC,IAAI,CAAC;IAC7B;IAEA,IAAI,SAAQ;QACV,IAAI,QAAO,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,MAAM,CAAC,GAAG;YAClD,QAAO,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE;QACrC;QAEA,OAAO;IACT;IAEA,OAAO,kBAAkB,IAAI;QAC3B,IAAI;QACJ,UAAU,aAAa,EAAE;IAC3B;AACF;AAEA;;CAEC,GACD,SAAS,yBACP,QAAkB,EAClB,SAAoB;IAEpB,OAAO,kBAAkB,UAAU;QAAE,IAAI;QAAsB;IAAU;AAC3E;AAEA;;CAEC,GACD,oFAAoF;AACpF,SAAS,8BACP,QAAkB,EAClB,SAAoB;IAEpB,MAAM,UAAS,WAAW,CAAC,SAAS;IACpC,IAAI,SAAQ;QACV,IAAI,QAAO,KAAK,EAAE;YAChB,MAAM,QAAO,KAAK;QACpB;QACA,OAAO;IACT;IAEA,OAAO,yBAAyB,UAAU;AAC5C;AAEA,MAAM,aAAa;AACnB;;CAEC,GACD,SAAS,KAAK,cAAoC;IAChD,OAAO,WAAW,IAAI,CAAC;AACzB;AAEA,OAAO,OAAO,GAAG;IACf;IACA;AACF","ignoreList":[0]}}]
}
\ No newline at end of file
......@@ -1440,12 +1440,12 @@ function augmentContext(context) {
function fetchWebAssembly(wasmChunkPath) {
return fetch(getChunkRelativeUrl(wasmChunkPath));
}
async function loadWebAssembly(_source, wasmChunkPath, importsObj) {
async function loadWebAssembly(_source, wasmChunkPath, _edgeModule, importsObj) {
const req = fetchWebAssembly(wasmChunkPath);
const { instance } = await WebAssembly.instantiateStreaming(req, importsObj);
return instance.exports;
}
async function loadWebAssemblyModule(_source, wasmChunkPath) {
async function loadWebAssemblyModule(_source, wasmChunkPath, _edgeModule) {
const req = fetchWebAssembly(wasmChunkPath);
return await WebAssembly.compileStreaming(req);
}
......
......@@ -20,6 +20,7 @@ serde = { workspace = true }
turbo-rcstr = { workspace = true }
turbo-tasks = { workspace = true }
turbo-tasks-fs = { workspace = true }
turbo-tasks-hash = { workspace = true }
turbopack-core = { workspace = true }
turbopack-ecmascript = { workspace = true }
wasmparser = "0.110.0"
......
......@@ -9,6 +9,12 @@
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
use anyhow::Result;
use turbo_rcstr::RcStr;
use turbo_tasks::Vc;
use turbo_tasks_hash::hash_xxh3_hash64;
use turbopack_core::asset::Asset;
pub(crate) mod analysis;
pub(crate) mod loader;
pub mod module_asset;
......@@ -16,6 +22,14 @@ pub(crate) mod output_asset;
pub mod raw;
pub mod source;
#[turbo_tasks::function]
pub async fn wasm_edge_var_name(asset: Vc<Box<dyn Asset>>) -> Result<Vc<RcStr>> {
let content = asset.content().file_content().await?;
Ok(Vc::cell(
format!("wasm_{:08x}", hash_xxh3_hash64(content)).into(),
))
}
pub fn register() {
turbo_tasks::register();
turbo_tasks_fs::register();
......
......@@ -8,7 +8,7 @@ use turbo_tasks_fs::File;
use turbopack_core::{asset::AssetContent, source::Source, virtual_source::VirtualSource};
use turbopack_ecmascript::utils::StringifyJs;
use crate::{analysis::analyze, source::WebAssemblySource};
use crate::{analysis::analyze, source::WebAssemblySource, wasm_edge_var_name};
/// Create a javascript loader to instantiate the WebAssembly module with the
/// necessary imports and exports to be processed by [turbopack_ecmascript].
......@@ -44,10 +44,11 @@ pub(crate) async fn instantiating_loader_source(
writedoc!(
code,
r#"
const {{ {exports} }} = await __turbopack_wasm__(wasmPath, {imports});
const {{ {exports} }} = await __turbopack_wasm__(wasmPath, () => {edgeVariable}, {imports});
export {{ {exports} }};
"#,
edgeVariable = wasm_edge_var_name(Vc::upcast(source)).await?,
imports = imports_obj,
exports = analysis.exports.join(", "),
)?;
......@@ -63,20 +64,23 @@ pub(crate) async fn instantiating_loader_source(
/// Create a javascript loader to compile the WebAssembly module and export it
/// without instantiating.
#[turbo_tasks::function]
pub(crate) fn compiling_loader_source(source: Vc<WebAssemblySource>) -> Vc<Box<dyn Source>> {
pub(crate) async fn compiling_loader_source(
source: Vc<WebAssemblySource>,
) -> Result<Vc<Box<dyn Source>>> {
let code: RcStr = formatdoc! {
r#"
import wasmPath from "WASM_PATH";
const mod = await __turbopack_wasm_module__(wasmPath);
const mod = await __turbopack_wasm_module__(wasmPath, () => {edgeVariable});
export default mod;
"#
"#,
edgeVariable = wasm_edge_var_name(Vc::upcast(source)).await?
}
.into();
Vc::upcast(VirtualSource::new(
Ok(Vc::upcast(VirtualSource::new(
source.ident().path().append("_.loader.mjs".into()),
AssetContent::file(File::from(code).into()),
))
)))
}
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