Files
openclaw/scripts/patch-tsdown-esm-bug.mjs
T

52 lines
1.7 KiB
JavaScript

#!/usr/bin/env node
/**
* Patch tsdown dist files to fix Node.js 20+ ESM loader bug
* See: https://github.com/nodejs/node/issues/51896
*
* This patches the problematic createRequire(import.meta.url) pattern
* that triggers ERR_INTERNAL_ASSERTION in Node.js 20+
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const workspace = path.resolve(__dirname, "..");
const tsdownDist = path.join(workspace, "node_modules", "tsdown", "dist");
console.log("Patching tsdown dist files...");
// Find all .mjs files in tsdown dist
const files = fs.readdirSync(tsdownDist).filter((f) => f.endsWith(".mjs"));
let patched = 0;
for (const file of files) {
const filePath = path.join(tsdownDist, file);
let content = fs.readFileSync(filePath, "utf8");
// Pattern 1: createRequire(import.meta.url) - the problematic pattern
const pattern1 = /const __cjs_require = __cjs_createRequire\(import\.meta\.url\);/g;
const replacement1 =
"const __cjs_require = __cjs_createRequire(fileURLToPath(process.argv[1] || import.meta.url));";
// Pattern 2: createRequire(__fileURLToPath(import.meta.url)) - already patched but needs process.argv
const pattern2 =
/const __cjs_require = __cjs_createRequire\(__fileURLToPath\(import\.meta\.url\)\);/g;
const replacement2 =
"const __cjs_require = __cjs_createRequire(__fileURLToPath(process.argv[1] || import.meta.url));";
let newContent = content.replace(pattern1, replacement1).replace(pattern2, replacement2);
if (newContent !== content) {
fs.writeFileSync(filePath, newContent);
console.log(`✓ Patched: ${file}`);
patched++;
}
}
console.log(`Patched ${patched} file(s)`);
process.exit(0);