Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(parakeet): ship ONNX Runtime under a private DLL name on Windows (#2074)
Chad Piha4d6077ded8be
diff --git a/CLAUDE.md b/CLAUDE.mdindex e2f804f85..b87f7b98c 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -214,6 +214,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.- **parakeet.js**: Model management for NVIDIA Parakeet ASR models- Uses sherpa-onnx runtime for cross-platform ONNX inference- Bundled binaries in `resources/bin/sherpa-onnx-{platform}-{arch}`+ - Windows: the bundled ONNX Runtime ships as `ow-onnxrt.dll`, not `onnxruntime.dll`. `scripts/download-sherpa-onnx.js` renames it and rewrites the import tables of every sherpa image (`scripts/lib/pe-imports.js`) because Windows 11 ships an older `onnxruntime.dll` in System32 and some loader configurations resolve the bare name to that copy (#2054). `afterPack.js` fails the Windows build if `onnxruntime.dll` is present or `ow-onnxrt.dll` is missing- INT8 quantized models for efficient CPU inference- Models stored in `~/.cache/openwhispr/parakeet-models/`- Server pre-warming on startup when `LOCAL_TRANSCRIPTION_PROVIDER=nvidia` is setdiff --git a/scripts/afterPack.js b/scripts/afterPack.jsindex 295ab9df5..f5aace49d 100644--- a/scripts/afterPack.js+++ b/scripts/afterPack.js@@ -18,6 +18,10 @@ const path = require("path");const { execFileSync } = require("child_process");const { Arch } = require("app-builder-lib");const { buildLinuxWrapperScript } = require("./lib/linux-launcher");+const {+ WINDOWS_ONNXRUNTIME_PRIVATE_NAME,+ WINDOWS_ONNXRUNTIME_UPSTREAM_NAME,+} = require("./download-sherpa-onnx");// ---------------------------------------------------------------------------// macOS resource binary signing@@ -231,6 +235,25 @@ function verifyMeetingAecHelper(context) {}}+// download-sherpa-onnx.js renames the bundled ONNX Runtime so the Windows+// loader can never resolve it to C:\Windows\System32\onnxruntime.dll (#2054).+// A stray onnxruntime.dll or a missing private DLL means that step was skipped+// (stale cache, older marker) and Parakeet would die at startup for the user.+function verifyWindowsOnnxRuntimePrivatized(binDir) {+ const strayPath = path.join(binDir, WINDOWS_ONNXRUNTIME_UPSTREAM_NAME);+ if (fs.existsSync(strayPath)) {+ throw new Error(+ `afterPack: ${WINDOWS_ONNXRUNTIME_UPSTREAM_NAME} must not ship (${strayPath}) — download-sherpa-onnx.js renames it to ${WINDOWS_ONNXRUNTIME_PRIVATE_NAME}; re-run the sherpa download with --force`+ );+ }+ const privatePath = path.join(binDir, WINDOWS_ONNXRUNTIME_PRIVATE_NAME);+ if (!fs.existsSync(privatePath)) {+ throw new Error(+ `afterPack: missing ${privatePath} — the bundled ONNX Runtime was not extracted and renamed; Parakeet would die at startup on Windows`+ );+ }+}+function verifyUnpackedBinaries(context) {const unpackedDir = path.join(resolveResourcesDir(context), "app.asar.unpacked");const unpackedModulesDir = path.join(unpackedDir, "node_modules");@@ -267,6 +290,7 @@ function verifyUnpackedBinaries(context) {`afterPack: no fastlist-*.exe in ${psListVendorDir} — ps-list vendor executable was not unpacked from app.asar (asarUnpack/packaging failure); Windows process detection would break`);}+ verifyWindowsOnnxRuntimePrivatized(path.join(resolveResourcesDir(context), "bin"));}console.log(" afterPack: verified unpacked bundled binaries");@@ -283,3 +307,5 @@ exports.default = async function (context) {verifyUnpackedBinaries(context);registerMacResourceBinariesForSigning(context);};++exports.verifyWindowsOnnxRuntimePrivatized = verifyWindowsOnnxRuntimePrivatized;diff --git a/scripts/download-sherpa-onnx.js b/scripts/download-sherpa-onnx.jsindex b0963f235..0be38999a 100644--- a/scripts/download-sherpa-onnx.js+++ b/scripts/download-sherpa-onnx.js@@ -14,10 +14,22 @@ const {PARAKEET_MINIMUM_MACOS_VERSION,compareVersions,} = require("../src/helpers/parakeetCapability");+const { renameImportedModule } = require("./lib/pe-imports");const SHERPA_ONNX_VERSION = "1.13.4";const GITHUB_RELEASE_URL = `https://github.com/k2-fsa/sherpa-onnx/releases/download/v${SHERPA_ONNX_VERSION}`;+// Windows 11 ships an older onnxruntime.dll in System32, and on some machines+// the loader resolves the bare import name to that copy instead of the one+// beside the exe (#2054: "requested API version [27] is not available").+// So the bundled runtime ships under a private name and every sherpa image+// gets its import table rewritten to match. The replacement must not be+// longer than the upstream name because the string is patched in place.+// Drop this once ORT ships version-suffixed DLLs (microsoft/onnxruntime#27893)+// and sherpa-onnx picks them up.+const WINDOWS_ONNXRUNTIME_UPSTREAM_NAME = "onnxruntime.dll";+const WINDOWS_ONNXRUNTIME_PRIVATE_NAME = "ow-onnxrt.dll";+// Binary configurations for each platform// Note: macOS uses universal2 builds that work on both arm64 and x64const BINARIES = {@@ -180,15 +192,57 @@ function copyBinary(extractDir, binaryName, outputPath, platformArch) {return true;}-function isCompleteInstall(markerPath, binaryPaths) {+function privatizeWindowsOnnxRuntime({ binDir, binaryPaths, libraryNames }) {+ const isUpstreamRuntime = (name) => name.toLowerCase() === WINDOWS_ONNXRUNTIME_UPSTREAM_NAME;+ const upstreamName = libraryNames.find(isUpstreamRuntime);+ if (!upstreamName) {+ throw new Error(+ `${WINDOWS_ONNXRUNTIME_UPSTREAM_NAME} not found among extracted libraries (${libraryNames.join(", ")}); the upstream archive layout changed`+ );+ }++ // Upstream's Windows CI copies every DLL into both bin/ and lib/ of the+ // archive, so the extracted list carries each name twice for one file.+ const shippedLibraries = [+ ...new Set(+ libraryNames.map((name) =>+ isUpstreamRuntime(name) ? WINDOWS_ONNXRUNTIME_PRIVATE_NAME : name+ )+ ),+ ];+ const privatePath = path.join(binDir, WINDOWS_ONNXRUNTIME_PRIVATE_NAME);+ fs.rmSync(privatePath, { force: true });+ fs.renameSync(path.join(binDir, upstreamName), privatePath);++ const imagePaths = [...binaryPaths, ...shippedLibraries.map((name) => path.join(binDir, name))];+ for (const imagePath of imagePaths) {+ const image = fs.readFileSync(imagePath);+ const patched = renameImportedModule(+ image,+ WINDOWS_ONNXRUNTIME_UPSTREAM_NAME,+ WINDOWS_ONNXRUNTIME_PRIVATE_NAME+ );+ if (patched === 0) continue;+ fs.writeFileSync(imagePath, image);+ console.log(+ ` win32: ${path.basename(imagePath)} now imports ${WINDOWS_ONNXRUNTIME_PRIVATE_NAME}`+ );+ }++ return shippedLibraries;+}++function isCompleteInstall(markerPath, binaryPaths, { platformArch, binDir = BIN_DIR }) {if (binaryPaths.some((binaryPath) => !fs.existsSync(binaryPath))) return false;try {const marker = JSON.parse(fs.readFileSync(markerPath, "utf8"));+ if (marker.version !== SHERPA_ONNX_VERSION || !Array.isArray(marker.libraries)) return false;+ if (marker.libraries.some((lib) => !fs.existsSync(path.join(binDir, lib)))) return false;+ // A win32 marker without this field predates the rename: the exes on disk+ // still import onnxruntime.dll and must be re-extracted.return (- marker.version === SHERPA_ONNX_VERSION &&- Array.isArray(marker.libraries) &&- marker.libraries.every((lib) => fs.existsSync(path.join(BIN_DIR, lib)))+ !platformArch.startsWith("win32") || marker.onnxRuntime === WINDOWS_ONNXRUNTIME_PRIVATE_NAME);} catch {return false;@@ -208,12 +262,15 @@ async function downloadBinary(platformArch, config, isForce = false) {if (!isForce &&- isCompleteInstall(installMarkerPath, [outputPath, onlineOutputPath, diarizeOutputPath])+ isCompleteInstall(installMarkerPath, [outputPath, onlineOutputPath, diarizeOutputPath], {+ platformArch,+ })) {console.log(` ${platformArch}: Already exists (use --force to re-download)`);return true;}- if (isForce && fs.existsSync(installMarkerPath)) fs.unlinkSync(installMarkerPath);+ // A failed repair must not leave a previous marker certifying partially patched binaries.+ if (fs.existsSync(installMarkerPath)) fs.unlinkSync(installMarkerPath);const url = getDownloadUrl(config.archiveName);console.log(` ${platformArch}: Downloading from ${url}`);@@ -283,9 +340,22 @@ async function downloadBinary(platformArch, config, isForce = false) {}}+ const isWindowsTarget = platformArch.startsWith("win32");+ const shippedLibraries = isWindowsTarget+ ? privatizeWindowsOnnxRuntime({+ binDir: BIN_DIR,+ binaryPaths: [outputPath, onlineOutputPath, diarizeOutputPath],+ libraryNames: copiedLibraries,+ })+ : copiedLibraries;+fs.writeFileSync(installMarkerPath,- JSON.stringify({ version: SHERPA_ONNX_VERSION, libraries: copiedLibraries })+ JSON.stringify({+ version: SHERPA_ONNX_VERSION,+ libraries: shippedLibraries,+ ...(isWindowsTarget ? { onnxRuntime: WINDOWS_ONNXRUNTIME_PRIVATE_NAME } : {}),+ }));return true;} catch (error) {@@ -366,8 +436,12 @@ module.exports = {SHERPA_ONNX_VERSION,BINARIES,BIN_DIR,+ WINDOWS_ONNXRUNTIME_PRIVATE_NAME,+ WINDOWS_ONNXRUNTIME_UPSTREAM_NAME,getDownloadUrl,+ isCompleteInstall,parseMacosDeploymentTargets,+ privatizeWindowsOnnxRuntime,validateMacosDeploymentTargets,verifyPackagedMacosParakeet,};diff --git a/scripts/lib/pe-imports.js b/scripts/lib/pe-imports.jsnew file mode 100644index 000000000..c0516ab60--- /dev/null+++ b/scripts/lib/pe-imports.js@@ -0,0 +1,142 @@+// Reads and rewrites DLL module names in a PE image's import and delay-load+// directories. Used by download-sherpa-onnx.js to point the bundled sherpa+// binaries at a privately named ONNX Runtime, because Windows 11 ships an+// older onnxruntime.dll in System32 and some loader configurations pick it+// over the application directory (#2054). Names are patched in place, so a+// replacement can never be longer than the original.+const DOS_MAGIC = 0x5a4d; // "MZ"+const PE_SIGNATURE = 0x00004550; // "PE\0\0"+const OPTIONAL_HEADER_PE32 = 0x10b;+const OPTIONAL_HEADER_PE32_PLUS = 0x20b;+const IMPORT_DIRECTORY_INDEX = 1;+const DELAY_IMPORT_DIRECTORY_INDEX = 13;+const IMPORT_DESCRIPTOR_SIZE = 20;+const DELAY_DESCRIPTOR_SIZE = 32;+const SECTION_HEADER_SIZE = 40;+const MAX_MODULE_NAME_LENGTH = 256;++function parseHeaders(image) {+ if (image.length < 0x40 || image.readUInt16LE(0) !== DOS_MAGIC) {+ throw new Error("not a PE image: missing MZ header");+ }+ const peOffset = image.readUInt32LE(0x3c);+ if (peOffset + 24 > image.length || image.readUInt32LE(peOffset) !== PE_SIGNATURE) {+ throw new Error("not a PE image: missing PE signature");+ }++ const numberOfSections = image.readUInt16LE(peOffset + 6);+ const sizeOfOptionalHeader = image.readUInt16LE(peOffset + 20);+ const optionalOffset = peOffset + 24;+ const magic = image.readUInt16LE(optionalOffset);++ let numberOfRvaAndSizes;+ let dataDirectoryOffset;+ if (magic === OPTIONAL_HEADER_PE32) {+ numberOfRvaAndSizes = image.readUInt32LE(optionalOffset + 92);+ dataDirectoryOffset = optionalOffset + 96;+ } else if (magic === OPTIONAL_HEADER_PE32_PLUS) {+ numberOfRvaAndSizes = image.readUInt32LE(optionalOffset + 108);+ dataDirectoryOffset = optionalOffset + 112;+ } else {+ throw new Error(`unsupported optional header magic 0x${magic.toString(16)}`);+ }++ const sectionTableOffset = optionalOffset + sizeOfOptionalHeader;+ const sections = [];+ for (let index = 0; index < numberOfSections; index += 1) {+ const header = sectionTableOffset + index * SECTION_HEADER_SIZE;+ sections.push({+ virtualSize: image.readUInt32LE(header + 8),+ virtualAddress: image.readUInt32LE(header + 12),+ sizeOfRawData: image.readUInt32LE(header + 16),+ pointerToRawData: image.readUInt32LE(header + 20),+ });+ }++ const directory = (index) => {+ if (index >= numberOfRvaAndSizes) return null;+ const entry = dataDirectoryOffset + index * 8;+ const virtualAddress = image.readUInt32LE(entry);+ return virtualAddress === 0 ? null : { virtualAddress, size: image.readUInt32LE(entry + 4) };+ };++ return { sections, directory };+}++function rvaToOffset(rva, sections) {+ for (const section of sections) {+ const span = Math.max(section.virtualSize, section.sizeOfRawData);+ if (rva >= section.virtualAddress && rva < section.virtualAddress + span) {+ return rva - section.virtualAddress + section.pointerToRawData;+ }+ }+ throw new Error(`RVA 0x${rva.toString(16)} is outside every section`);+}++function readModuleName(image, offset) {+ const end = image.indexOf(0, offset);+ if (end === -1 || end - offset > MAX_MODULE_NAME_LENGTH) {+ throw new Error(`unterminated module name at offset 0x${offset.toString(16)}`);+ }+ return image.toString("ascii", offset, end);+}++// Yields { offset, name } for every module-name string referenced from the+// import directory, then from the delay-load directory.+function* moduleNameEntries(image) {+ const { sections, directory } = parseHeaders(image);++ const imports = directory(IMPORT_DIRECTORY_INDEX);+ if (imports) {+ let descriptor = rvaToOffset(imports.virtualAddress, sections);+ for (;;) {+ const originalFirstThunk = image.readUInt32LE(descriptor);+ const nameRva = image.readUInt32LE(descriptor + 12);+ const firstThunk = image.readUInt32LE(descriptor + 16);+ if (originalFirstThunk === 0 && nameRva === 0 && firstThunk === 0) break;+ const offset = rvaToOffset(nameRva, sections);+ yield { offset, name: readModuleName(image, offset) };+ descriptor += IMPORT_DESCRIPTOR_SIZE;+ }+ }++ const delayed = directory(DELAY_IMPORT_DIRECTORY_INDEX);+ if (delayed) {+ let descriptor = rvaToOffset(delayed.virtualAddress, sections);+ for (;;) {+ const attributes = image.readUInt32LE(descriptor);+ const nameRva = image.readUInt32LE(descriptor + 4);+ if (attributes === 0 && nameRva === 0) break;+ if ((attributes & 1) === 0) {+ // Pre-VS2010 descriptors store virtual addresses; nothing we ship uses them.+ throw new Error("delay-load descriptor is not RVA-based; refusing to patch");+ }+ const offset = rvaToOffset(nameRva, sections);+ yield { offset, name: readModuleName(image, offset) };+ descriptor += DELAY_DESCRIPTOR_SIZE;+ }+ }+}++function listImportedModules(image) {+ return [...moduleNameEntries(image)].map((entry) => entry.name);+}++function renameImportedModule(image, fromName, toName) {+ if (Buffer.byteLength(toName, "ascii") > Buffer.byteLength(fromName, "ascii")) {+ throw new Error(+ `replacement "${toName}" is longer than "${fromName}"; import names are patched in place and cannot grow`+ );+ }+ const target = fromName.toLowerCase();+ const patchedOffsets = new Set();+ for (const { offset, name } of moduleNameEntries(image)) {+ if (name.toLowerCase() !== target || patchedOffsets.has(offset)) continue;+ image.fill(0, offset, offset + name.length);+ image.write(toName, offset, "ascii");+ patchedOffsets.add(offset);+ }+ return patchedOffsets.size;+}++module.exports = { listImportedModules, renameImportedModule };diff --git a/test/helpers/harness/peFixture.js b/test/helpers/harness/peFixture.jsnew file mode 100644index 000000000..3db4c5462--- /dev/null+++ b/test/helpers/harness/peFixture.js@@ -0,0 +1,78 @@+// Minimal PE32+ images for exercising scripts/lib/pe-imports.js without real+// Windows binaries. One .rdata section holds the import descriptors, the+// delay-load descriptors and the module name strings, which is all the+// reader looks at.+const IMPORT_DESCRIPTOR_SIZE = 20;+const DELAY_DESCRIPTOR_SIZE = 32;+const PE_HEADER_OFFSET = 0x80;+const OPTIONAL_HEADER_SIZE = 240; // PE32++const SECTION_RVA = 0x1000;+const SECTION_FILE_OFFSET = 0x400;+const FILE_ALIGNMENT = 0x200;++function buildPeImage({ imports = [], delayImports = [] } = {}) {+ const importTableSize = (imports.length + 1) * IMPORT_DESCRIPTOR_SIZE;+ const delayTableSize =+ delayImports.length > 0 ? (delayImports.length + 1) * DELAY_DESCRIPTOR_SIZE : 0;++ // Name strings follow the two tables inside the section.+ const nameOffsets = new Map();+ let cursor = importTableSize + delayTableSize;+ const nameBlobs = [];+ for (const name of [...imports, ...delayImports]) {+ nameOffsets.set(name, cursor);+ nameBlobs.push(Buffer.from(`${name}\0`, "ascii"));+ cursor += name.length + 1;+ }+ const sectionSize = Math.max(FILE_ALIGNMENT, Math.ceil(cursor / FILE_ALIGNMENT) * FILE_ALIGNMENT);+ const image = Buffer.alloc(SECTION_FILE_OFFSET + sectionSize);++ // DOS header+ image.write("MZ", 0, "ascii");+ image.writeUInt32LE(PE_HEADER_OFFSET, 0x3c); // e_lfanew++ // PE signature + COFF file header+ image.writeUInt32LE(0x00004550, PE_HEADER_OFFSET); // "PE\0\0"+ image.writeUInt16LE(0x8664, PE_HEADER_OFFSET + 4); // Machine: x64+ image.writeUInt16LE(1, PE_HEADER_OFFSET + 6); // NumberOfSections+ image.writeUInt16LE(OPTIONAL_HEADER_SIZE, PE_HEADER_OFFSET + 20);++ // Optional header (PE32+)+ const optional = PE_HEADER_OFFSET + 24;+ image.writeUInt16LE(0x20b, optional); // Magic+ image.writeUInt32LE(16, optional + 108); // NumberOfRvaAndSizes+ const dataDirectory = (index) => optional + 112 + index * 8;+ image.writeUInt32LE(SECTION_RVA, dataDirectory(1));+ image.writeUInt32LE(importTableSize, dataDirectory(1) + 4);+ if (delayTableSize > 0) {+ image.writeUInt32LE(SECTION_RVA + importTableSize, dataDirectory(13));+ image.writeUInt32LE(delayTableSize, dataDirectory(13) + 4);+ }++ // Section header+ const section = optional + OPTIONAL_HEADER_SIZE;+ image.write(".rdata", section, "ascii");+ image.writeUInt32LE(cursor, section + 8); // VirtualSize+ image.writeUInt32LE(SECTION_RVA, section + 12); // VirtualAddress+ image.writeUInt32LE(sectionSize, section + 16); // SizeOfRawData+ image.writeUInt32LE(SECTION_FILE_OFFSET, section + 20); // PointerToRawData++ // IMAGE_IMPORT_DESCRIPTOR entries (terminated by an all-zero entry)+ imports.forEach((name, index) => {+ const descriptor = SECTION_FILE_OFFSET + index * IMPORT_DESCRIPTOR_SIZE;+ image.writeUInt32LE(SECTION_RVA + nameOffsets.get(name), descriptor + 12); // Name+ image.writeUInt32LE(0x2000, descriptor + 16); // FirstThunk (unused by the reader)+ });++ // IMAGE_DELAYLOAD_DESCRIPTOR entries (RVA-based, terminated by an all-zero entry)+ delayImports.forEach((name, index) => {+ const descriptor = SECTION_FILE_OFFSET + importTableSize + index * DELAY_DESCRIPTOR_SIZE;+ image.writeUInt32LE(1, descriptor); // Attributes: RvaBased+ image.writeUInt32LE(SECTION_RVA + nameOffsets.get(name), descriptor + 4); // DllNameRVA+ });++ Buffer.concat(nameBlobs).copy(image, SECTION_FILE_OFFSET + importTableSize + delayTableSize);+ return image;+}++module.exports = { buildPeImage };diff --git a/test/scripts/afterPackWindowsOnnxRuntime.test.js b/test/scripts/afterPackWindowsOnnxRuntime.test.jsnew file mode 100644index 000000000..70cb7d3a1--- /dev/null+++ b/test/scripts/afterPackWindowsOnnxRuntime.test.js@@ -0,0 +1,31 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("fs");+const os = require("os");+const path = require("path");++const { verifyWindowsOnnxRuntimePrivatized } = require("../../scripts/afterPack");++function makeBinDir(t) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "afterpack-bin-"));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ return dir;+}++test("passes when only the private ONNX Runtime is present", (t) => {+ const dir = makeBinDir(t);+ fs.writeFileSync(path.join(dir, "ow-onnxrt.dll"), "");+ assert.doesNotThrow(() => verifyWindowsOnnxRuntimePrivatized(dir));+});++test("fails when a stray onnxruntime.dll would ship", (t) => {+ const dir = makeBinDir(t);+ fs.writeFileSync(path.join(dir, "ow-onnxrt.dll"), "");+ fs.writeFileSync(path.join(dir, "onnxruntime.dll"), "");+ assert.throws(() => verifyWindowsOnnxRuntimePrivatized(dir), /onnxruntime\.dll must not ship/);+});++test("fails when the private ONNX Runtime is missing", (t) => {+ const dir = makeBinDir(t);+ assert.throws(() => verifyWindowsOnnxRuntimePrivatized(dir), /missing .*ow-onnxrt\.dll/);+});diff --git a/test/scripts/downloadSherpaOnnx.test.js b/test/scripts/downloadSherpaOnnx.test.jsnew file mode 100644index 000000000..c834a6f42--- /dev/null+++ b/test/scripts/downloadSherpaOnnx.test.js@@ -0,0 +1,259 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("fs");+const os = require("os");+const path = require("path");+const vm = require("node:vm");+const { createRequire } = require("node:module");++const { listImportedModules } = require("../../scripts/lib/pe-imports");+const { buildPeImage } = require("../helpers/harness/peFixture");+const {+ BINARIES,+ SHERPA_ONNX_VERSION,+ WINDOWS_ONNXRUNTIME_PRIVATE_NAME,+ WINDOWS_ONNXRUNTIME_UPSTREAM_NAME,+ isCompleteInstall,+ privatizeWindowsOnnxRuntime,+} = require("../../scripts/download-sherpa-onnx");++const EXE_NAMES = [+ "sherpa-onnx-ws-win32-x64.exe",+ "sherpa-onnx-online-ws-win32-x64.exe",+ "sherpa-onnx-diarize-win32-x64.exe",+];++function makeBinDir(t) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "sherpa-win32-"));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ return dir;+}++// Mirrors what the 1.13.4 win-x64-shared-MD-Release archive yields after copying:+// three exes that import onnxruntime.dll, the C API DLL that imports it too+// (upstream spells it in mixed case in some builds), the runtime itself, and+// the providers DLL that does not reference it.+function writeFakeBundle(dir) {+ for (const exe of EXE_NAMES) {+ fs.writeFileSync(+ path.join(dir, exe),+ buildPeImage({ imports: ["KERNEL32.dll", "onnxruntime.dll"] })+ );+ }+ fs.writeFileSync(+ path.join(dir, "sherpa-onnx-c-api.dll"),+ buildPeImage({ imports: ["ONNXRUNTIME.dll", "KERNEL32.dll"] })+ );+ fs.writeFileSync(path.join(dir, "onnxruntime.dll"), buildPeImage({ imports: ["KERNEL32.dll"] }));+ fs.writeFileSync(+ path.join(dir, "onnxruntime_providers_shared.dll"),+ buildPeImage({ imports: ["KERNEL32.dll"] })+ );+ return {+ binaryPaths: EXE_NAMES.map((exe) => path.join(dir, exe)),+ libraryNames: ["sherpa-onnx-c-api.dll", "onnxruntime.dll", "onnxruntime_providers_shared.dll"],+ };+}++test("the private DLL name fits in place of the upstream import string and differs from it", () => {+ assert.ok(+ Buffer.byteLength(WINDOWS_ONNXRUNTIME_PRIVATE_NAME) <=+ Buffer.byteLength(WINDOWS_ONNXRUNTIME_UPSTREAM_NAME)+ );+ assert.notEqual(+ WINDOWS_ONNXRUNTIME_PRIVATE_NAME.toLowerCase(),+ WINDOWS_ONNXRUNTIME_UPSTREAM_NAME.toLowerCase()+ );+});++test("privatizeWindowsOnnxRuntime renames the runtime and repoints every importer", (t) => {+ const dir = makeBinDir(t);+ const { binaryPaths, libraryNames } = writeFakeBundle(dir);+ const providersBefore = fs.readFileSync(path.join(dir, "onnxruntime_providers_shared.dll"));++ const shipped = privatizeWindowsOnnxRuntime({ binDir: dir, binaryPaths, libraryNames });++ assert.deepEqual(shipped, [+ "sherpa-onnx-c-api.dll",+ WINDOWS_ONNXRUNTIME_PRIVATE_NAME,+ "onnxruntime_providers_shared.dll",+ ]);+ assert.equal(fs.existsSync(path.join(dir, "onnxruntime.dll")), false);+ assert.equal(fs.existsSync(path.join(dir, WINDOWS_ONNXRUNTIME_PRIVATE_NAME)), true);+ for (const file of [...binaryPaths, path.join(dir, "sherpa-onnx-c-api.dll")]) {+ const imports = listImportedModules(fs.readFileSync(file));+ assert.ok(+ imports.includes(WINDOWS_ONNXRUNTIME_PRIVATE_NAME),+ `${path.basename(file)}: ${imports}`+ );+ assert.ok(!imports.some((name) => name.toLowerCase() === "onnxruntime.dll"));+ }+ assert.deepEqual(+ fs.readFileSync(path.join(dir, "onnxruntime_providers_shared.dll")),+ providersBefore+ );+});++// sherpa's Windows CI copies every DLL into both bin/ and lib/ of the archive,+// so findLibrariesInDir reports each one twice while they land on one file each.+test("privatizeWindowsOnnxRuntime tolerates the archive shipping each DLL twice", (t) => {+ const dir = makeBinDir(t);+ const { binaryPaths, libraryNames } = writeFakeBundle(dir);++ const shipped = privatizeWindowsOnnxRuntime({+ binDir: dir,+ binaryPaths,+ libraryNames: [...libraryNames, ...libraryNames],+ });++ assert.deepEqual(shipped, [+ "sherpa-onnx-c-api.dll",+ WINDOWS_ONNXRUNTIME_PRIVATE_NAME,+ "onnxruntime_providers_shared.dll",+ ]);+ for (const name of shipped) {+ assert.ok(fs.existsSync(path.join(dir, name)), `${name} missing`);+ }+});++test("privatizeWindowsOnnxRuntime fails loudly when the archive no longer ships onnxruntime.dll", (t) => {+ const dir = makeBinDir(t);+ const { binaryPaths } = writeFakeBundle(dir);+ assert.throws(+ () =>+ privatizeWindowsOnnxRuntime({+ binDir: dir,+ binaryPaths,+ libraryNames: ["sherpa-onnx-c-api.dll"],+ }),+ /onnxruntime\.dll not found/+ );+});++test("a win32 marker written before the rename is not a complete install", (t) => {+ const dir = makeBinDir(t);+ const exe = path.join(dir, "sherpa-onnx-ws-win32-x64.exe");+ fs.writeFileSync(exe, buildPeImage({ imports: [WINDOWS_ONNXRUNTIME_PRIVATE_NAME] }));+ fs.writeFileSync(path.join(dir, WINDOWS_ONNXRUNTIME_PRIVATE_NAME), buildPeImage());+ const marker = path.join(dir, ".sherpa-onnx-win32-x64.json");+ const options = { platformArch: "win32-x64", binDir: dir };++ fs.writeFileSync(+ marker,+ JSON.stringify({ version: SHERPA_ONNX_VERSION, libraries: [WINDOWS_ONNXRUNTIME_PRIVATE_NAME] })+ );+ assert.equal(isCompleteInstall(marker, [exe], options), false);++ fs.writeFileSync(+ marker,+ JSON.stringify({+ version: SHERPA_ONNX_VERSION,+ libraries: [WINDOWS_ONNXRUNTIME_PRIVATE_NAME],+ onnxRuntime: WINDOWS_ONNXRUNTIME_PRIVATE_NAME,+ })+ );+ assert.equal(isCompleteInstall(marker, [exe], options), true);+});++test("non-Windows markers do not need the onnxRuntime field", (t) => {+ const dir = makeBinDir(t);+ const binary = path.join(dir, "sherpa-onnx-ws-darwin-arm64");+ fs.writeFileSync(binary, "");+ const marker = path.join(dir, ".sherpa-onnx-darwin-arm64.json");+ fs.writeFileSync(marker, JSON.stringify({ version: SHERPA_ONNX_VERSION, libraries: [] }));+ assert.equal(+ isCompleteInstall(marker, [binary], { platformArch: "darwin-arm64", binDir: dir }),+ true+ );+});++test("a failed automatic Windows repair stays incomplete and retries DLL patching", async (t) => {+ const root = makeBinDir(t);+ const binDir = path.join(root, "resources", "bin");+ fs.mkdirSync(binDir, { recursive: true });+ const config = BINARIES["win32-x64"];+ const binaryPaths = EXE_NAMES.map((name) => path.join(binDir, name));+ const markerPath = path.join(binDir, ".sherpa-onnx-win32-x64.json");+ const options = { platformArch: "win32-x64", binDir };+ const sourcePath = require.resolve("../../scripts/download-sherpa-onnx");+ const requireFromDownloader = createRequire(sourcePath);+ let downloads = 0;+ let failPatch = false;+ let patchFailureInjected = false;++ const downloadBinary = vm.runInNewContext(+ `${fs.readFileSync(sourcePath, "utf8")}\ndownloadBinary;`,+ {+ __dirname: path.join(root, "scripts"),+ module: { exports: {} },+ process,+ console,+ require(name) {+ if (name === "fs") {+ return {+ ...fs,+ writeFileSync(filePath, ...args) {+ if (failPatch && filePath === binaryPaths[1]) {+ patchFailureInjected = true;+ throw Object.assign(new Error("simulated patch write failure"), { code: "EBUSY" });+ }+ return fs.writeFileSync(filePath, ...args);+ },+ };+ }+ if (name === "./lib/download-utils") {+ return {+ ...requireFromDownloader(name),+ async downloadFile(_url, destination) {+ downloads += 1;+ fs.writeFileSync(destination, "fixture archive");+ },+ };+ }+ if (name === "child_process") {+ return {+ execFileSync(command, args, { cwd }) {+ assert.equal(command, "tar");+ const extractDir = path.resolve(cwd, args[args.indexOf("-C") + 1]);+ writeFakeBundle(extractDir);+ [config.binaryPath, config.onlineBinaryPath, config.diarizeBinaryPath].forEach(+ (name, index) => {+ fs.renameSync(+ path.join(extractDir, EXE_NAMES[index]),+ path.join(extractDir, name)+ );+ }+ );+ },+ };+ }+ return requireFromDownloader(name);+ },+ },+ { filename: sourcePath }+ );++ assert.equal(await downloadBinary("win32-x64", config), true);+ assert.equal(isCompleteInstall(markerPath, binaryPaths, options), true);+ assert.equal(await downloadBinary("win32-x64", config), true);+ assert.equal(downloads, 1);++ fs.unlinkSync(binaryPaths[1]);+ failPatch = true;+ assert.equal(await downloadBinary("win32-x64", config), false);+ assert.equal(patchFailureInjected, true);+ assert.ok(listImportedModules(fs.readFileSync(binaryPaths[1])).includes("onnxruntime.dll"));+ assert.equal(fs.existsSync(path.join(binDir, "onnxruntime.dll")), false);+ assert.equal(fs.existsSync(markerPath), false);+ assert.equal(isCompleteInstall(markerPath, binaryPaths, options), false);++ failPatch = false;+ assert.equal(await downloadBinary("win32-x64", config), true);+ assert.equal(downloads, 3);+ assert.equal(isCompleteInstall(markerPath, binaryPaths, options), true);+ for (const imagePath of [...binaryPaths, path.join(binDir, "sherpa-onnx-c-api.dll")]) {+ const imports = listImportedModules(fs.readFileSync(imagePath));+ assert.ok(imports.includes("ow-onnxrt.dll"), imagePath);+ assert.ok(!imports.some((name) => name.toLowerCase() === "onnxruntime.dll"), imagePath);+ }+});diff --git a/test/scripts/peImports.test.js b/test/scripts/peImports.test.jsnew file mode 100644index 000000000..c9808db25--- /dev/null+++ b/test/scripts/peImports.test.js@@ -0,0 +1,66 @@+const test = require("node:test");+const assert = require("node:assert/strict");++const { buildPeImage } = require("../helpers/harness/peFixture");+const { listImportedModules, renameImportedModule } = require("../../scripts/lib/pe-imports");++test("lists module names from the import directory in table order", () => {+ const image = buildPeImage({ imports: ["KERNEL32.dll", "onnxruntime.dll", "MSVCP140.dll"] });+ assert.deepEqual(listImportedModules(image), ["KERNEL32.dll", "onnxruntime.dll", "MSVCP140.dll"]);+});++test("lists delay-load module names after the static imports", () => {+ const image = buildPeImage({ imports: ["KERNEL32.dll"], delayImports: ["onnxruntime.dll"] });+ assert.deepEqual(listImportedModules(image), ["KERNEL32.dll", "onnxruntime.dll"]);+});++test("an image with no imports lists nothing", () => {+ assert.deepEqual(listImportedModules(buildPeImage()), []);+});++test("rejects a buffer that is not a PE image", () => {+ assert.throws(() => listImportedModules(Buffer.from("not a pe file at all")), /MZ/);+});++test("renames a module in place, NUL-pads the old length and leaves other names alone", () => {+ const image = buildPeImage({ imports: ["KERNEL32.dll", "onnxruntime.dll"] });+ const before = Buffer.from(image);++ const patched = renameImportedModule(image, "onnxruntime.dll", "ow-onnxrt.dll");++ assert.equal(patched, 1);+ assert.deepEqual(listImportedModules(image), ["KERNEL32.dll", "ow-onnxrt.dll"]);+ const nameOffset = before.indexOf(Buffer.from("onnxruntime.dll\0", "ascii"));+ assert.equal(image.toString("ascii", nameOffset, nameOffset + 13), "ow-onnxrt.dll");+ assert.deepEqual([...image.subarray(nameOffset + 13, nameOffset + 16)], [0, 0, 0]);+ // Only the 15 name bytes changed.+ assert.deepEqual(image.subarray(0, nameOffset), before.subarray(0, nameOffset));+ assert.deepEqual(image.subarray(nameOffset + 16), before.subarray(nameOffset + 16));+});++test("matches the module name case-insensitively, as the Windows loader does", () => {+ const image = buildPeImage({ imports: ["ONNXRUNTIME.DLL"] });+ assert.equal(renameImportedModule(image, "onnxruntime.dll", "ow-onnxrt.dll"), 1);+ assert.deepEqual(listImportedModules(image), ["ow-onnxrt.dll"]);+});++test("also renames delay-load references", () => {+ const image = buildPeImage({ delayImports: ["onnxruntime.dll"] });+ assert.equal(renameImportedModule(image, "onnxruntime.dll", "ow-onnxrt.dll"), 1);+ assert.deepEqual(listImportedModules(image), ["ow-onnxrt.dll"]);+});++test("returns 0 and leaves the image untouched when the module is not imported", () => {+ const image = buildPeImage({ imports: ["KERNEL32.dll"] });+ const before = Buffer.from(image);+ assert.equal(renameImportedModule(image, "onnxruntime.dll", "ow-onnxrt.dll"), 0);+ assert.deepEqual(image, before);+});++test("refuses a replacement name longer than the original", () => {+ const image = buildPeImage({ imports: ["onnxruntime.dll"] });+ assert.throws(+ () => renameImportedModule(image, "onnxruntime.dll", "openwhispr-onnxruntime.dll"),+ /longer/+ );+});