UNPKG

@babel/plugin-proposal-import-wasm-source

Version:

Transform source phase imports (`import source ... from '...'`) to work in browsers and Node.js, assuming that the imported source is a WebAssembly module.

74 lines (71 loc) 3.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _helperPluginUtils = require("@babel/helper-plugin-utils"); var _pluginSyntaxImportSource = require("@babel/plugin-syntax-import-source"); var _helperImportToPlatformApi = require("@babel/helper-import-to-platform-api"); var _default = exports.default = (0, _helperPluginUtils.declare)(api => { const { types: t, template } = api; api.assertVersion("^7.23.0 || >8.0.0-alpha <8.0.0-beta"); const targets = api.targets(); let helperESM; let helperCJS; const transformers = { webFetch: fetch => template.expression.ast`WebAssembly.compileStreaming(${fetch})`, nodeFsSync: read => template.expression.ast`new WebAssembly.Module(${read})`, nodeFsAsync: template.expression`WebAssembly.compile` }; const getHelper = file => { const modules = file.get("@babel/plugin-transform-modules-*"); if (modules === "commonjs") { return helperCJS != null ? helperCJS : helperCJS = (0, _helperImportToPlatformApi.importToPlatformApi)(targets, transformers, true); } if (modules == null) { return helperESM != null ? helperESM : helperESM = (0, _helperImportToPlatformApi.importToPlatformApi)(targets, transformers, false); } throw new Error(`@babel/plugin-proposal-import-wasm-source can only be used when not ` + `compiling modules, or when compiling them to CommonJS.`); }; return { name: "proposal-import-wasm-source", inherits: _pluginSyntaxImportSource.default, visitor: { Program(path) { if (path.node.sourceType !== "module") return; const helper = getHelper(this.file); const t2 = t; const data = []; for (const decl of path.get("body")) { var _decl$node$attributes, _decl$node$assertions; if (!decl.isImportDeclaration({ phase: "source" })) continue; if ((_decl$node$attributes = decl.node.attributes) != null && _decl$node$attributes.length || (_decl$node$assertions = decl.node.assertions) != null && _decl$node$assertions.length) { throw path.buildCodeFrameError("`import source` with import attributes cannot be compiled."); } const specifier = decl.node.specifiers[0]; t2.assertImportDefaultSpecifier(specifier); data.push({ id: specifier.local, fetch: helper.buildFetch(decl.node.source, path) }); decl.remove(); } const decl = (0, _helperImportToPlatformApi.buildParallelStaticImports)(data, helper.needsAwait); if (decl) path.unshiftContainer("body", decl); }, ImportExpression(path) { if (path.node.phase !== "source") return; if (path.node.options) { throw path.buildCodeFrameError("`import.source` with an options bag cannot be compiled."); } path.replaceWith(getHelper(this.file).buildFetchAsync(path.node.source, path)); } } }; }); //# sourceMappingURL=index.js.map