// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. const fs = require('node:fs'); const path = require('node:path'); // // Post-process the mjs file. // // // USAGE: node wasm_post_build.js // const mjsFilePath = process.argv[2]; let contents = fs.readFileSync(mjsFilePath).toString(); // STEP.1 - Apply workaround for spawning workers using `import.meta.url`. // This script is a workaround for enabling: // - using onnxruntime-web with Multi-threading enabled when import from CDN // - using onnxruntime-web when consumed in some frameworks like Vite // // In the use case mentioned above, the file name of the script may be changed. So we need to replace the line: // `new Worker(new URL("ort-wasm-*.mjs", import.meta.url),` // with // `new Worker(new URL(import.meta.url),` // // This behavior is introduced in https://github.com/emscripten-core/emscripten/pull/22165. Since it's unlikely to be // reverted, and there is no config to disable this behavior, we have to use a post-build script to workaround it. // This step should only be applied for multithreading builds if (path.basename(mjsFilePath).includes('-threaded')) { const regex = 'new Worker\\(new URL\\(".+?", ?import\\.meta\\.url\\),'; const matches = [...contents.matchAll(new RegExp(regex, 'g'))]; if (matches.length !== 1) { throw new Error( `Unexpected number of matches for "${regex}" in "${mjsFilePath}": ${matches.length}.`, ); } // Replace the only occurrence. contents = contents.replace( new RegExp(regex), `new Worker(new URL(import.meta.url),`, ); } fs.writeFileSync(mjsFilePath, contents);