Project Files
src / fpzip / fpzip_loader.ts
// fpzip_loader.ts - CJS/ESM-compatible loader for fpzip WASM module
//
// IMPORTANT: Do NOT use import.meta anywhere in this file.
// Rollup transforms import.meta into an always-truthy object literal,
// which defeats typeof guards and causes pathToFileURL(undefined) crashes
// on the Hub where __filename is undefined inside the bundled production.js.
import fs from "fs";
import path from "path";
import { createRequire } from "module";
// --- Determine directory containing fpzip_wasm.js ----------------------------
let _dir: string | undefined;
// Strategy 1: CJS __dirname — valid when fpzip_wasm.js is actually next to us
if (typeof __dirname === "string" && fs.existsSync(path.join(__dirname, "fpzip_wasm.js"))) {
_dir = __dirname;
}
// Strategy 2: walk up from process.cwd() looking for fpzip_wasm.js
if (!_dir) {
let d = process.cwd();
for (let i = 0; i < 6; i++) {
for (const sub of ["src/fpzip", "fpzip", "dist/fpzip"]) {
const candidate = path.join(d, sub);
if (fs.existsSync(path.join(candidate, "fpzip_wasm.js"))) { _dir = candidate; break; }
}
if (_dir) break;
d = path.dirname(d);
}
}
if (!_dir) throw new Error("[fpzip_loader] Unable to determine fpzip directory");
// --- Derive a require() function (ESM contexts lack it) ----------------------
let _require: NodeRequire;
try {
_require = createRequire(`file://${path.join(_dir, "fpzip_loader.ts")}`);
} catch {
_require = (typeof globalThis.require === "function" ? globalThis.require : require) as NodeRequire;
}
// Load the Emscripten JS file that defines `fpzipModule` (MODULARIZE)
const wasmJsPath = path.join(_dir, "fpzip_wasm.js");
const wasmJsCode = fs.readFileSync(wasmJsPath, "utf8");
// Evaluate it in a Node context with CommonJS-ish globals.
const loadModule = new Function(
"require",
"__dirname",
"__filename",
`${wasmJsCode}\nreturn fpzipModule;\n`
);
const fpzipModule = loadModule(_require, _dir, path.join(_dir, "fpzip_loader.ts"));
export default fpzipModule;