forked from dcousens/typeforce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rename.ts
50 lines (47 loc) · 1.66 KB
/
rename.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import * as fs from 'fs/promises'
import * as path from 'path'
async function * readdirP (dir: string): AsyncGenerator<string> {
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
if (entry.isDirectory()) {
for await (const sub of readdirP(path.join(dir, entry.name))) {
yield sub
}
} else if (entry.isFile()) {
yield path.join(dir, entry.name)
}
}
}
async function main (): Promise<void> {
for await (const entry of readdirP(path.relative(process.cwd(), path.join(__dirname, '..', 'mjs')))) {
const match = /^(.*)(\.(js|js\.map|d\.ts))$/.exec(entry)
if (match == null) {
continue
}
const file = match[1]
const ext = match[2]
if (ext === '.js') {
let data = await fs.readFile(entry, 'utf-8')
data = data.replace(/^((import|export)\s+.+from\s+')(.+)('\s*)/gm, (_, prefix: string, __, file: string, suffix: string) => {
if (file.startsWith('./') && !file.endsWith('.mjs')) {
file += '.mjs'
}
return `${prefix}${file}${suffix}`
})
data = data.replace(`//# sourceMappingURL=${path.basename(file)}.js.map`, `//# sourceMappingURL=${path.basename(file)}.mjs.map`)
await fs.writeFile(entry, data)
await fs.rename(entry, `${file}.mjs`)
} else if (ext === '.js.map') {
const data = JSON.parse(await fs.readFile(entry, 'utf-8'))
data.file = `${file}.mjs`
await fs.writeFile(entry, JSON.stringify(data))
await fs.rename(entry, `${file}.mjs.map`)
} else if (ext === '.d.ts') {
await fs.rename(entry, `${file}.d.mts`)
}
}
}
main()
.catch((e: Error) => {
console.error(e)
process.exit(1)
})