|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.dev/license |
| 7 | + */ |
| 8 | + |
| 9 | +import type { Plugin, ResolveOptions } from 'esbuild'; |
| 10 | +import assert from 'node:assert'; |
| 11 | +import { createHash } from 'node:crypto'; |
| 12 | +import { readFile } from 'node:fs/promises'; |
| 13 | +import { basename, dirname, join } from 'node:path'; |
| 14 | +import { assertIsError } from '../../utils/error'; |
| 15 | +import { LoadResultCache, createCachedLoad } from './load-result-cache'; |
| 16 | + |
| 17 | +/** |
| 18 | + * Options for the Angular WASM esbuild plugin |
| 19 | + * @see createWasmPlugin |
| 20 | + */ |
| 21 | +export interface WasmPluginOptions { |
| 22 | + /** Allow generation of async (proposal compliant) WASM imports. This requires zoneless to enable async/await. */ |
| 23 | + allowAsync?: boolean; |
| 24 | + /** Load results cache. */ |
| 25 | + cache?: LoadResultCache; |
| 26 | +} |
| 27 | + |
| 28 | +const WASM_INIT_NAMESPACE = 'angular:wasm:init'; |
| 29 | +const WASM_CONTENTS_NAMESPACE = 'angular:wasm:contents'; |
| 30 | +const WASM_RESOLVE_SYMBOL = Symbol('WASM_RESOLVE_SYMBOL'); |
| 31 | + |
| 32 | +// See: https://github.com/tc39/proposal-regexp-unicode-property-escapes/blob/fe6d07fad74cd0192d154966baa1e95e7cda78a1/README.md#other-examples |
| 33 | +const ecmaIdentifierNameRegExp = /^(?:[$_\p{ID_Start}])(?:[$_\u200C\u200D\p{ID_Continue}])*$/u; |
| 34 | + |
| 35 | +/** |
| 36 | + * Creates an esbuild plugin to use WASM files with import statements and expressions. |
| 37 | + * The default behavior follows the WebAssembly/ES mode integration proposal found at |
| 38 | + * https://github.com/WebAssembly/esm-integration/tree/main/proposals/esm-integration. |
| 39 | + * This behavior requires top-level await support which is only available in zoneless |
| 40 | + * Angular applications. |
| 41 | + * @returns An esbuild plugin. |
| 42 | + */ |
| 43 | +export function createWasmPlugin(options: WasmPluginOptions): Plugin { |
| 44 | + const { allowAsync = false, cache } = options; |
| 45 | + |
| 46 | + return { |
| 47 | + name: 'angular-wasm', |
| 48 | + setup(build): void { |
| 49 | + build.onResolve({ filter: /.wasm$/ }, async (args) => { |
| 50 | + // Skip if already resolving the WASM file to avoid infinite resolution |
| 51 | + if (args.pluginData?.[WASM_RESOLVE_SYMBOL]) { |
| 52 | + return; |
| 53 | + } |
| 54 | + // Skip if not an import statement or expression |
| 55 | + if (args.kind !== 'import-statement' && args.kind !== 'dynamic-import') { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + // When in the initialization namespace, the content has already been resolved |
| 60 | + // and only needs to be loaded for use with the initialization code. |
| 61 | + if (args.namespace === WASM_INIT_NAMESPACE) { |
| 62 | + return { |
| 63 | + namespace: WASM_CONTENTS_NAMESPACE, |
| 64 | + path: join(args.resolveDir, args.path), |
| 65 | + pluginData: args.pluginData, |
| 66 | + }; |
| 67 | + } |
| 68 | + |
| 69 | + // Skip if a custom loader is defined |
| 70 | + if (build.initialOptions.loader?.['.wasm'] || args.with['loader']) { |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + // Attempt full resolution of the WASM file |
| 75 | + const resolveOptions: ResolveOptions & { path?: string } = { |
| 76 | + ...args, |
| 77 | + pluginData: { [WASM_RESOLVE_SYMBOL]: true }, |
| 78 | + }; |
| 79 | + // The "path" property will cause an error if used in the resolve call |
| 80 | + delete resolveOptions.path; |
| 81 | + |
| 82 | + const result = await build.resolve(args.path, resolveOptions); |
| 83 | + |
| 84 | + // Skip if there are errors, is external, or another plugin resolves to a custom namespace |
| 85 | + if (result.errors.length > 0 || result.external || result.namespace !== 'file') { |
| 86 | + // Reuse already resolved result |
| 87 | + return result; |
| 88 | + } |
| 89 | + |
| 90 | + return { |
| 91 | + ...result, |
| 92 | + namespace: WASM_INIT_NAMESPACE, |
| 93 | + }; |
| 94 | + }); |
| 95 | + |
| 96 | + build.onLoad( |
| 97 | + { filter: /.wasm$/, namespace: WASM_INIT_NAMESPACE }, |
| 98 | + createCachedLoad(cache, async (args) => { |
| 99 | + // Ensure async mode is supported |
| 100 | + if (!allowAsync) { |
| 101 | + return { |
| 102 | + errors: [ |
| 103 | + { |
| 104 | + text: 'WASM/ES module integration imports are not supported with Zone.js applications', |
| 105 | + notes: [ |
| 106 | + { |
| 107 | + text: 'Information about zoneless Angular applications can be found here: https://angular.dev/guide/experimental/zoneless', |
| 108 | + }, |
| 109 | + ], |
| 110 | + }, |
| 111 | + ], |
| 112 | + }; |
| 113 | + } |
| 114 | + |
| 115 | + const wasmContents = await readFile(args.path); |
| 116 | + // Inline WASM code less than 10kB |
| 117 | + const inlineWasm = wasmContents.byteLength < 10_000; |
| 118 | + |
| 119 | + // Add import of WASM contents |
| 120 | + let initContents = `import ${inlineWasm ? 'wasmData' : 'wasmPath'} from ${JSON.stringify(basename(args.path))}`; |
| 121 | + initContents += inlineWasm ? ' with { loader: "binary" };' : ';\n\n'; |
| 122 | + |
| 123 | + // Read from the file system when on Node.js (SSR) and not inline |
| 124 | + if (!inlineWasm && build.initialOptions.platform === 'node') { |
| 125 | + initContents += 'import { readFile } from "node:fs/promises";\n'; |
| 126 | + initContents += 'const wasmData = await readFile(wasmPath);\n'; |
| 127 | + } |
| 128 | + |
| 129 | + // Create initialization function |
| 130 | + initContents += generateInitHelper( |
| 131 | + !inlineWasm && build.initialOptions.platform !== 'node', |
| 132 | + wasmContents, |
| 133 | + ); |
| 134 | + |
| 135 | + // Analyze WASM for imports and exports |
| 136 | + let importModuleNames, exportNames; |
| 137 | + try { |
| 138 | + const wasm = await WebAssembly.compile(wasmContents); |
| 139 | + importModuleNames = new Set( |
| 140 | + WebAssembly.Module.imports(wasm).map((value) => value.module), |
| 141 | + ); |
| 142 | + exportNames = WebAssembly.Module.exports(wasm).map((value) => value.name); |
| 143 | + } catch (error) { |
| 144 | + assertIsError(error); |
| 145 | + |
| 146 | + return { |
| 147 | + errors: [{ text: 'Unable to analyze WASM file', notes: [{ text: error.message }] }], |
| 148 | + }; |
| 149 | + } |
| 150 | + |
| 151 | + // Ensure export names are valid JavaScript identifiers |
| 152 | + const invalidExportNames = exportNames.filter( |
| 153 | + (name) => !ecmaIdentifierNameRegExp.test(name), |
| 154 | + ); |
| 155 | + if (invalidExportNames.length > 0) { |
| 156 | + return { |
| 157 | + errors: invalidExportNames.map((name) => ({ |
| 158 | + text: 'WASM export names must be valid JavaScript identifiers', |
| 159 | + notes: [ |
| 160 | + { |
| 161 | + text: `The export "${name}" is not valid. The WASM file should be updated to remove this error.`, |
| 162 | + }, |
| 163 | + ], |
| 164 | + })), |
| 165 | + }; |
| 166 | + } |
| 167 | + |
| 168 | + // Add import statements and setup import object |
| 169 | + initContents += 'const importObject = Object.create(null);\n'; |
| 170 | + let importIndex = 0; |
| 171 | + for (const moduleName of importModuleNames) { |
| 172 | + // Add a namespace import for each module name |
| 173 | + initContents += `import * as wasm_import_${++importIndex} from ${JSON.stringify(moduleName)};\n`; |
| 174 | + // Add the namespace object to the import object |
| 175 | + initContents += `importObject[${JSON.stringify(moduleName)}] = wasm_import_${importIndex};\n`; |
| 176 | + } |
| 177 | + |
| 178 | + // Instantiate the module |
| 179 | + initContents += 'const instance = await init(importObject);\n'; |
| 180 | + |
| 181 | + // Add exports |
| 182 | + const exportNameList = exportNames.join(', '); |
| 183 | + initContents += `const { ${exportNameList} } = instance.exports;\n`; |
| 184 | + initContents += `export { ${exportNameList} }\n`; |
| 185 | + |
| 186 | + return { |
| 187 | + contents: initContents, |
| 188 | + loader: 'js', |
| 189 | + resolveDir: dirname(args.path), |
| 190 | + pluginData: { wasmContents }, |
| 191 | + watchFiles: [args.path], |
| 192 | + }; |
| 193 | + }), |
| 194 | + ); |
| 195 | + |
| 196 | + build.onLoad({ filter: /.wasm$/, namespace: WASM_CONTENTS_NAMESPACE }, async (args) => { |
| 197 | + const contents = args.pluginData.wasmContents ?? (await readFile(args.path)); |
| 198 | + |
| 199 | + let loader: 'binary' | 'file' = 'file'; |
| 200 | + if (args.with.loader) { |
| 201 | + assert( |
| 202 | + args.with.loader === 'binary' || args.with.loader === 'file', |
| 203 | + 'WASM loader type should only be binary or file.', |
| 204 | + ); |
| 205 | + loader = args.with.loader; |
| 206 | + } |
| 207 | + |
| 208 | + return { |
| 209 | + contents, |
| 210 | + loader, |
| 211 | + watchFiles: [args.path], |
| 212 | + }; |
| 213 | + }); |
| 214 | + }, |
| 215 | + }; |
| 216 | +} |
| 217 | + |
| 218 | +/** |
| 219 | + * Generates the string content of the WASM initialization helper function. |
| 220 | + * This function supports both file fetching and inline byte data depending on |
| 221 | + * the preferred option for the WASM file. When fetching, an integrity hash is |
| 222 | + * also generated and used with the fetch action. |
| 223 | + * |
| 224 | + * @param streaming Uses fetch and WebAssembly.instantiateStreaming. |
| 225 | + * @param wasmContents The binary contents to generate an integrity hash. |
| 226 | + * @returns A string containing the initialization function. |
| 227 | + */ |
| 228 | +function generateInitHelper(streaming: boolean, wasmContents: Uint8Array) { |
| 229 | + let resultContents; |
| 230 | + if (streaming) { |
| 231 | + const fetchOptions = { |
| 232 | + integrity: 'sha256-' + createHash('sha-256').update(wasmContents).digest('base64'), |
| 233 | + }; |
| 234 | + const fetchContents = `fetch(new URL(wasmPath, import.meta.url), ${JSON.stringify(fetchOptions)})`; |
| 235 | + resultContents = `await WebAssembly.instantiateStreaming(${fetchContents}, imports)`; |
| 236 | + } else { |
| 237 | + resultContents = 'await WebAssembly.instantiate(wasmData, imports)'; |
| 238 | + } |
| 239 | + |
| 240 | + const contents = ` |
| 241 | +let mod; |
| 242 | +async function init(imports) { |
| 243 | + if (mod) { |
| 244 | + return await WebAssembly.instantiate(mod, imports); |
| 245 | + } |
| 246 | +
|
| 247 | + const result = ${resultContents}; |
| 248 | + mod = result.module; |
| 249 | +
|
| 250 | + return result.instance; |
| 251 | +} |
| 252 | +`; |
| 253 | + |
| 254 | + return contents; |
| 255 | +} |
0 commit comments