Skip to content

Commit

Permalink
feat(turbopack): support "loading" WebAssembly injected as global var…
Browse files Browse the repository at this point in the history
…ables in edge runtime (#6616)
  • Loading branch information
ForsakenHarmony committed Dec 5, 2023
1 parent 94bb9b9 commit 8cb1c34
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,51 @@ function augmentContext(context: TurbopackDevBaseContext): TurbopackDevContext {
}

async function loadWebAssembly(
_source: SourceInfo,
_id: ModuleId,
_importsObj: any
source: SourceInfo,
chunkPath: ChunkPath,
imports: WebAssembly.Imports
): Promise<Exports> {
throw new Error("loading WebAssembly is not supported");
const module = await loadWebAssemblyModule(source, chunkPath);

return await WebAssembly.instantiate(module, imports);
}

function getFileStem(path: string): string {
const fileName = path.split("/").pop()!;

const stem = fileName.split(".").shift()!;

if (stem == "") {
return fileName;
}

return stem;
}

type GlobalWithInjectedWebAssembly = typeof globalThis & {
[key: `wasm_${string}`]: WebAssembly.Module;
};

async function loadWebAssemblyModule(
_source: SourceInfo,
_id: ModuleId
): Promise<any> {
throw new Error("loading WebAssembly is not supported");
chunkPath: ChunkPath
): 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];

if (!module) {
throw new Error(
`dynamically loading WebAssembly is not supported in this runtime and global \`${identifier}\` was not injected`
);
}

return module;
}

(() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
// environment
"lib": ["ESNext"]
// environment, we need WebWorker for WebAssembly types
"lib": ["ESNext", "WebWorker"]
},
"include": ["*.ts"]
}

1 comment on commit 8cb1c34

@vercel
Copy link

@vercel vercel bot commented on 8cb1c34 Dec 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

rust-docs – ./

turbo-xi.vercel.sh
rustdoc.turbo.build
rust-docs-git-main.vercel.sh
rust-docs.vercel.sh

Please sign in to comment.