import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const distDir = path.resolve(__dirname, "..", "dist");
function rewriteDtsImports(dir) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
rewriteDtsImports(full);
continue;
}
if (!entry.name.endsWith(".d.ts")) continue;
const original = fs.readFileSync(full, "utf8");
const rewriteSpec = (match, prefix, spec, suffix) => {
if (/\.[a-zA-Z0-9]+$/.test(spec)) return match; if (spec.endsWith("/")) return match; return `${prefix}${spec}.js${suffix}`;
};
const updated = original
.replace(/(from\s+["'])(\.\.?\/[^"']+?)(["'])/g, rewriteSpec)
.replace(/(import\s*\(\s*["'])(\.\.?\/[^"']+?)(["']\s*\))/g, rewriteSpec);
if (updated !== original) {
fs.writeFileSync(full, updated);
console.log(
`[post-build] Rewrote relative imports in ${path.relative(distDir, full)}`
);
}
}
}
if (!fs.existsSync(distDir)) {
console.error(`[post-build] dist directory not found at ${distDir}`);
process.exit(1);
}
rewriteDtsImports(distDir);