Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(wasm): universal support with esm import syntax #2017

Merged
merged 6 commits into from
Dec 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-replace": "^5.0.5",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-wasm": "^6.2.2",
"@rollup/pluginutils": "^5.1.0",
"@types/http-proxy": "^1.17.14",
"@vercel/nft": "^0.26.0",
Expand Down
16 changes: 0 additions & 16 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions src/presets/cloudflare-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ export const cloudflareModule = defineNitroPreset({
inlineDynamicImports: false,
},
},
wasm: {
lazy: false,
esmImport: true,
},
hooks: {
async compiled(nitro: Nitro) {
await writeFile(
Expand Down
4 changes: 4 additions & 0 deletions src/presets/cloudflare-pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ export const cloudflarePages = defineNitroPreset({
// https://github.com/unjs/nitro/pull/933
_mime: "mime/index.js",
},
wasm: {
lazy: false,
esmImport: true,
},
rollupConfig: {
output: {
entryFileNames: "index.js",
Expand Down
2 changes: 1 addition & 1 deletion src/presets/cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const cloudflare = defineNitroPreset({
deploy: "npx wrangler deploy",
},
wasm: {
esmImport: true,
lazy: true,
},
hooks: {
async compiled(nitro: Nitro) {
Expand Down
4 changes: 4 additions & 0 deletions src/presets/vercel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ export const vercelEdge = defineNitroPreset({
process: undefined,
},
},
wasm: {
lazy: true,
esmImport: true,
},
hooks: {
"rollup:before": (nitro: Nitro) => {
deprecateSWR(nitro);
Expand Down
37 changes: 22 additions & 15 deletions src/rollup/plugins/wasm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,12 @@ import { createHash } from "node:crypto";
import { promises as fs, existsSync } from "node:fs";
import { basename, normalize } from "pathe";
import type { Plugin } from "rollup";
import wasmBundle from "@rollup/plugin-wasm";
import MagicString from "magic-string";
import { WasmOptions } from "../../types";

export function wasm(options: WasmOptions): Plugin {
return options.esmImport ? wasmImport() : wasmBundle(options.rollup);
}

const WASM_ID_PREFIX = "\0nitro-wasm:";

export function wasmImport(): Plugin {
export function wasm(opts: WasmOptions): Plugin {
type WasmAssetInfo = {
fileName: string;
id: string;
Expand All @@ -22,7 +17,6 @@ export function wasmImport(): Plugin {

const wasmSources = new Map<string /* sourceFile */, WasmAssetInfo>();
const wasmImports = new Map<string /* id */, WasmAssetInfo>();
const wasmGlobals = new Map<string /* global id */, WasmAssetInfo>();

return <Plugin>{
name: "nitro:wasm",
Expand Down Expand Up @@ -80,6 +74,7 @@ export function wasmImport(): Plugin {
return {
code: `export default "${asset.id}";`,
map: null,
syntheticNamedExports: true,
};
},
renderChunk(code, chunk, options) {
Expand All @@ -90,8 +85,6 @@ export function wasmImport(): Plugin {
return;
}

const isIIFE = options.format === "iife" || options.format === "umd";

const s = new MagicString(code);

const resolveImport = (id) => {
Expand All @@ -103,9 +96,12 @@ export function wasmImport(): Plugin {
return null;
}
const nestedLevel = chunk.fileName.split("/").length - 1;
return (
(nestedLevel ? "../".repeat(nestedLevel) : "./") + asset.fileName
);
const relativeId =
(nestedLevel ? "../".repeat(nestedLevel) : "./") + asset.fileName;
return {
relativeId,
asset,
};
};

const ReplaceRE = new RegExp(`"(${WASM_ID_PREFIX}[^"]+)"`, "g");
Expand All @@ -117,10 +113,21 @@ export function wasmImport(): Plugin {
);
continue;
}
let code = `await import("${resolved}").then(r => r?.default || r);`;
if (isIIFE) {
code = `undefined /* not supported */`;

let dataCode: string;
if (opts.esmImport) {
dataCode = `await import("${resolved.relativeId}").then(r => r?.default || r)`;
} else {
const base64Str = resolved.asset.source.toString("base64");
dataCode = `(()=>{const d=atob("${base64Str}");const s=d.length;const b=new Uint8Array(s);for(let i=0;i<s;i++)b[i]=d.charCodeAt(i);return b})()`;
}

let code = `await WebAssembly.instantiate(${dataCode}).then(r => r?.exports||r?.instance?.exports || r);`;

if (opts.lazy) {
code = `(()=>{const e=async()=>{return ${code}};let _p;const p=()=>{if(!_p)_p=e();return _p;};return {then:cb=>p().then(cb),catch:cb=>p().catch(cb)}})()`;
}

s.overwrite(match.index, match.index + match[0].length, code);
}
if (s.hasChanged()) {
Expand Down
8 changes: 5 additions & 3 deletions src/types/nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import type { NestedHooks, Hookable } from "hookable";
import type { ConsolaInstance, LogLevel } from "consola";
import type { WatchOptions } from "chokidar";
import type { RollupCommonJSOptions } from "@rollup/plugin-commonjs";
import type { RollupWasmOptions } from "@rollup/plugin-wasm";
import type { Storage, BuiltinDriverName } from "unstorage";
import type { ProxyServerOptions } from "httpxy";
import type { ProxyOptions, RouterMethod } from "h3";
Expand Down Expand Up @@ -198,9 +197,12 @@ export interface WasmOptions {
esmImport?: boolean;

/**
* Options for `@rollup/plugin-wasm`, only used when `esmImport` is `false`
* Import `.wasm` files using a lazily evaluated promise for compatibility
*/
rollup?: RollupWasmOptions;
lazy?: boolean;

/** @deprecated */
rollup?: unknown;
}

export interface NitroFrameworkInfo {
Expand Down
3 changes: 0 additions & 3 deletions test/fixture/routes/_ignored.ts

This file was deleted.

14 changes: 1 addition & 13 deletions test/fixture/routes/wasm/dynamic.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
export default defineLazyEventHandler(async () => {
const { sum } = await importWasm(import("~/wasm/sum.wasm" as string));
// const { sum } = await importWasm(import("../../wasm/sum.wasm" as string));
const { sum } = await import("~/wasm/sum.wasm");
return eventHandler(() => {
return `2+3=${sum(2, 3)}`;
});
});

// TODO: Extract as reusable utility once stable
async function importWasm(input: any) {
const _input = await input;
const _module = _input.default || _input;
const _instance =
typeof _module === "function"
? await _module({}).then((r) => r.instance || r)
: await WebAssembly.instantiate(_module, {});
return _instance.exports;
}
6 changes: 6 additions & 0 deletions test/fixture/routes/wasm/static.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import _mod from "~/wasm/sum.wasm";

export default eventHandler(async () => {
const { sum } = await _mod;
return `2+3=${sum(2, 3)}`;
});
3 changes: 2 additions & 1 deletion test/fixture/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"paths": {
"nitropack": ["../../src/index"],
"#internal/nitro": ["../../src/runtime/index"],
"#internal/nitro/*": ["../../src/runtime/*"]
"#internal/nitro/*": ["../../src/runtime/*"],
"~/wasm/sum.wasm": ["./wasm/sum.d.ts"]
}
}
}
1 change: 1 addition & 0 deletions test/fixture/wasm/sum.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare function sum(a: number, b: number): number;
1 change: 1 addition & 0 deletions test/presets/cloudflare-pages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ describe("nitro:preset:cloudflare-pages", async () => {
const mf = new Miniflare({
modules: true,
scriptPath: resolve(ctx.outDir, "_worker.js", "index.js"),
modulesRules: [{ type: "CompiledWasm", include: ["**/*.wasm"] }],
globals: { __env__: {} },
compatibilityFlags: ["streams_enable_constructors"],
bindings: {
Expand Down