Skip to content

Commit

Permalink
fix: generate safe imports code using knitwork (#24)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Mar 14, 2024
1 parent 06da6be commit 4d7de7d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 11 deletions.
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -48,6 +48,7 @@
"test:types": "tsc --noEmit --skipLibCheck"
},
"dependencies": {
"knitwork": "^1.0.0",
"magic-string": "^0.30.8",
"mlly": "^1.6.1",
"pathe": "^1.1.2",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

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

33 changes: 22 additions & 11 deletions src/plugin/runtime.ts
@@ -1,4 +1,10 @@
import { readPackageJSON } from "pkg-types";
import {
genSafeVariableName,
genObjectFromRaw,
genString,
genImport,
} from "knitwork";
import {
UMWASM_HELPERS_ID,
UNWASM_EXTERNAL_PREFIX,
Expand Down Expand Up @@ -186,30 +192,35 @@ export async function getWasmImports(
// Try to resolve from nearest package.json
const pkgJSON = await readPackageJSON(asset.id);

let code = "const _imports = {";

let resolved = true;

const imports: string[] = [];
const importsObject: Record<string, Record<string, string>> = {};

for (const moduleName of importNames) {
const importNames = asset.imports[moduleName];
const pkgImport =
pkgJSON.imports?.[moduleName] || pkgJSON.imports?.[`#${moduleName}`];

const importName = "_imports_" + genSafeVariableName(moduleName);

if (pkgImport) {
code = `import * as _imports_${moduleName} from "${pkgImport}";\n${code}`;
imports.push(genImport(pkgImport, { name: "*", as: importName }));
} else {
resolved = false;
}
code += `\n ${moduleName}: {`;
for (const name of importNames) {
code += pkgImport
? `\n ${name}: _imports_${moduleName}.${name},\n`
: `\n ${name}: () => { throw new Error("\`${moduleName}.${name}\` is not provided!")},\n`;
}
code += " },\n";

importsObject[moduleName] = Object.fromEntries(
importNames.map((name) => [
name,
pkgImport
? `${importName}[${genString(name)}]`
: `() => { throw new Error(${genString(moduleName + "." + importName)} + " is not provided!")}`,
]),
);
}

code += "};\n";
const code = `${imports.join("\n")}\n\nconst _imports = ${genObjectFromRaw(importsObject)}`;

return {
code,
Expand Down

0 comments on commit 4d7de7d

Please sign in to comment.