AsyncWasmLoadingRuntimeModule.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RuntimeGlobals = require("../RuntimeGlobals");
  7. const RuntimeModule = require("../RuntimeModule");
  8. const Template = require("../Template");
  9. class AsyncWasmLoadingRuntimeModule extends RuntimeModule {
  10. constructor({ generateLoadBinaryCode, supportsStreaming }) {
  11. super("wasm loading", RuntimeModule.STAGE_NORMAL);
  12. this.generateLoadBinaryCode = generateLoadBinaryCode;
  13. this.supportsStreaming = supportsStreaming;
  14. }
  15. /**
  16. * @returns {string} runtime code
  17. */
  18. generate() {
  19. const { compilation, chunk } = this;
  20. const { outputOptions, runtimeTemplate } = compilation;
  21. const fn = RuntimeGlobals.instantiateWasm;
  22. const wasmModuleSrcPath = compilation.getPath(
  23. JSON.stringify(outputOptions.webassemblyModuleFilename),
  24. {
  25. hash: `" + ${RuntimeGlobals.getFullHash}() + "`,
  26. hashWithLength: length =>
  27. `" + ${RuntimeGlobals.getFullHash}}().slice(0, ${length}) + "`,
  28. module: {
  29. id: '" + wasmModuleId + "',
  30. hash: `" + wasmModuleHash + "`,
  31. hashWithLength(length) {
  32. return `" + wasmModuleHash.slice(0, ${length}) + "`;
  33. }
  34. },
  35. runtime: chunk.runtime
  36. }
  37. );
  38. return `${fn} = ${runtimeTemplate.basicFunction(
  39. "exports, wasmModuleId, wasmModuleHash, importsObj",
  40. [
  41. `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`,
  42. this.supportsStreaming
  43. ? Template.asString([
  44. "if (typeof WebAssembly.instantiateStreaming === 'function') {",
  45. Template.indent([
  46. "return WebAssembly.instantiateStreaming(req, importsObj)",
  47. Template.indent([
  48. `.then(${runtimeTemplate.returningFunction(
  49. "Object.assign(exports, res.instance.exports)",
  50. "res"
  51. )});`
  52. ])
  53. ]),
  54. "}"
  55. ])
  56. : "// no support for streaming compilation",
  57. "return req",
  58. Template.indent([
  59. `.then(${runtimeTemplate.returningFunction("x.arrayBuffer()", "x")})`,
  60. `.then(${runtimeTemplate.returningFunction(
  61. "WebAssembly.instantiate(bytes, importsObj)",
  62. "bytes"
  63. )})`,
  64. `.then(${runtimeTemplate.returningFunction(
  65. "Object.assign(exports, res.instance.exports)",
  66. "res"
  67. )});`
  68. ])
  69. ]
  70. )};`;
  71. }
  72. }
  73. module.exports = AsyncWasmLoadingRuntimeModule;