ReadFileCompileWasmPlugin.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { WEBASSEMBLY_MODULE_TYPE_SYNC } = require("../ModuleTypeConstants");
  7. const RuntimeGlobals = require("../RuntimeGlobals");
  8. const Template = require("../Template");
  9. const { usesFullHashDigest } = require("../TemplatedPathPlugin");
  10. const { needsRuntimeFullHash } = require("../wasm/wasmModuleFilename");
  11. const WasmChunkLoadingRuntimeModule = require("../wasm-sync/WasmChunkLoadingRuntimeModule");
  12. /** @import Chunk from "../Chunk" */
  13. /** @import Compiler from "../Compiler" */
  14. /**
  15. * Defines the read file compile wasm plugin options type used by this module.
  16. * @typedef {object} ReadFileCompileWasmPluginOptions
  17. * @property {boolean=} mangleImports mangle imports
  18. * @property {boolean=} import use import?
  19. */
  20. const PLUGIN_NAME = "ReadFileCompileWasmPlugin";
  21. class ReadFileCompileWasmPlugin {
  22. /**
  23. * Creates an instance of ReadFileCompileWasmPlugin.
  24. * @param {ReadFileCompileWasmPluginOptions=} options options object
  25. */
  26. constructor(options = {}) {
  27. /** @type {ReadFileCompileWasmPluginOptions} */
  28. this.options = options;
  29. }
  30. /**
  31. * Applies the plugin by registering its hooks on the compiler.
  32. * @param {Compiler} compiler the compiler instance
  33. * @returns {void}
  34. */
  35. apply(compiler) {
  36. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
  37. const globalWasmLoading = compilation.outputOptions.wasmLoading;
  38. /**
  39. * Checks whether this read file compile wasm plugin is enabled for chunk.
  40. * @param {Chunk} chunk chunk
  41. * @returns {boolean} true, when wasm loading is enabled for the chunk
  42. */
  43. const isEnabledForChunk = (chunk) => {
  44. const options = chunk.getEntryOptions();
  45. const wasmLoading =
  46. options && options.wasmLoading !== undefined
  47. ? options.wasmLoading
  48. : globalWasmLoading;
  49. return wasmLoading === "async-node";
  50. };
  51. /**
  52. * @type {(path: string) => string} callback to generate code to load the wasm file
  53. */
  54. const generateLoadBinaryCode = this.options.import
  55. ? (path) =>
  56. Template.asString([
  57. "Promise.all([import('fs'), import('url')]).then(([{ readFile }, { URL }]) => new Promise((resolve, reject) => {",
  58. Template.indent([
  59. `readFile(${compilation.runtimeTemplate.importMetaUrl(path)}, (err, buffer) => {`,
  60. Template.indent([
  61. "if (err) return reject(err);",
  62. "",
  63. "// Fake fetch response",
  64. "resolve({",
  65. Template.indent([
  66. // Return a real ArrayBuffer: some runtimes (e.g. Deno)
  67. // reject a Node Buffer view here as "not a buffer source".
  68. "arrayBuffer() { return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); }"
  69. ]),
  70. "});"
  71. ]),
  72. "});"
  73. ]),
  74. "}))"
  75. ])
  76. : (path) =>
  77. Template.asString([
  78. "new Promise(function (resolve, reject) {",
  79. Template.indent([
  80. compilation.runtimeTemplate.destructureObject(
  81. ["readFile"],
  82. `require(${compilation.runtimeTemplate.renderNodePrefixForCoreModule("fs")})`
  83. ),
  84. compilation.runtimeTemplate.destructureObject(
  85. ["join"],
  86. `require(${compilation.runtimeTemplate.renderNodePrefixForCoreModule("path")})`
  87. ),
  88. "",
  89. "try {",
  90. Template.indent([
  91. `readFile(join(__dirname, ${path}), function(err, buffer){`,
  92. Template.indent([
  93. "if (err) return reject(err);",
  94. "",
  95. "// Fake fetch response",
  96. "resolve({",
  97. Template.indent([
  98. // Return a real ArrayBuffer: some runtimes (e.g. Deno)
  99. // reject a Node Buffer view here as "not a buffer source".
  100. compilation.runtimeTemplate.method(
  101. "arrayBuffer",
  102. "",
  103. "return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);"
  104. )
  105. ]),
  106. "});"
  107. ]),
  108. "});"
  109. ]),
  110. "} catch (err) { reject(err); }"
  111. ]),
  112. "})"
  113. ]);
  114. compilation.hooks.runtimeRequirementInTree
  115. .for(RuntimeGlobals.ensureChunkHandlers)
  116. .tap(PLUGIN_NAME, (chunk, set, { chunkGraph }) => {
  117. if (!isEnabledForChunk(chunk)) return;
  118. if (
  119. !chunkGraph.hasModuleInGraph(
  120. chunk,
  121. (m) => m.type === WEBASSEMBLY_MODULE_TYPE_SYNC
  122. )
  123. ) {
  124. return;
  125. }
  126. set.add(RuntimeGlobals.moduleCache);
  127. if (
  128. needsRuntimeFullHash(
  129. /** @type {string} */ (
  130. compilation.outputOptions.webassemblyModuleFilename
  131. )
  132. )
  133. ) {
  134. set.add(RuntimeGlobals.getFullHash);
  135. }
  136. compilation.addRuntimeModule(
  137. chunk,
  138. new WasmChunkLoadingRuntimeModule({
  139. fullHashDigest: usesFullHashDigest(
  140. /** @type {string} */ (
  141. compilation.outputOptions.webassemblyModuleFilename
  142. )
  143. ),
  144. generateLoadBinaryCode,
  145. supportsStreaming: false,
  146. mangleImports: this.options.mangleImports,
  147. runtimeRequirements: set
  148. })
  149. );
  150. });
  151. });
  152. }
  153. }
  154. module.exports = ReadFileCompileWasmPlugin;