|
| 1 | +const fs = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | + |
| 4 | +function processDir(dir) { |
| 5 | + if (!fs.existsSync(dir)) return; |
| 6 | + const files = fs.readdirSync(dir); |
| 7 | + for (const file of files) { |
| 8 | + const fullPath = path.join(dir, file); |
| 9 | + if (fs.statSync(fullPath).isDirectory()) { |
| 10 | + processDir(fullPath); |
| 11 | + } else if (fullPath.endsWith('.js') || fullPath.endsWith('.d.ts')) { |
| 12 | + let content = fs.readFileSync(fullPath, 'utf8'); |
| 13 | + // Regex to match import/export statements (including dynamic imports) |
| 14 | + const regex = /(from\s+['"]|import\s*\(?['"]|import\s+['"])([^'"]+)(['"]\)?)/g; |
| 15 | + |
| 16 | + let modifiedContent = content.replace(regex, (match, p1, p2, p3) => { |
| 17 | + // Skip if already has an extension or is a known standard module/bare module that doesn't need it |
| 18 | + if (p2.endsWith('.js') || p2.endsWith('.json') || p2.endsWith('.cjs') || p2.endsWith('.mjs')) { |
| 19 | + return match; |
| 20 | + } |
| 21 | + |
| 22 | + // Handle relative paths |
| 23 | + if (p2.startsWith('.')) { |
| 24 | + // If the path corresponds to a directory, it needs /index.js |
| 25 | + const targetPath = path.join(path.dirname(fullPath), p2); |
| 26 | + if (fs.existsSync(targetPath) && fs.statSync(targetPath).isDirectory()) { |
| 27 | + return `${p1}${p2}/index.js${p3}`; |
| 28 | + } else { |
| 29 | + return `${p1}${p2}.js${p3}`; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + // Handle specific subpath third-party imports mentioned in the bug report |
| 34 | + if (p2.startsWith('bip174/src/')) { |
| 35 | + return `${p1}${p2}.js${p3}`; |
| 36 | + } |
| 37 | + |
| 38 | + return match; |
| 39 | + }); |
| 40 | + |
| 41 | + if (modifiedContent !== content) { |
| 42 | + fs.writeFileSync(fullPath, modifiedContent, 'utf8'); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +const targetDir = process.argv[2]; |
| 49 | +if (!targetDir) { |
| 50 | + console.error("Usage: node fix-esm.js <directory>"); |
| 51 | + process.exit(1); |
| 52 | +} |
| 53 | +processDir(targetDir); |
0 commit comments