-
Notifications
You must be signed in to change notification settings - Fork 6
/
fix-esm-import-path.js
executable file
·286 lines (263 loc) · 7.37 KB
/
fix-esm-import-path.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/env node
import fs from 'fs'
import path from 'path'
import debug from 'debug'
let processImportType = true
let entryPoints = []
let missingFiles = []
for (let i = 2; i < process.argv.length; i++) {
let arg = process.argv[i]
if (arg === '--preserve-import-type') {
processImportType = false
continue
}
if (arg === '--process-import-type') {
processImportType = true
continue
}
let entryPoint = arg
if (fs.existsSync(entryPoint)) {
entryPoints.push(entryPoint)
} else {
missingFiles.push(entryPoint)
}
}
if (missingFiles.length > 0) {
let name = missingFiles.map(name => JSON.stringify(name)).join(', ')
console.error(`entryPoint ${name} does not exist`)
process.exit(1)
}
if (entryPoints.length === 0) {
console.error('missing entryPoint in argument')
process.exit(1)
}
let log = debug('fix-esm-import-path')
// log.enabled = true
function findNodeModuleDir(srcFile, name) {
let dir = path.dirname(srcFile)
for (;;) {
let files = fs.readdirSync(dir)
if (files.includes('node_modules')) {
let moduleDir = path.join(dir, 'node_modules', name)
if (fs.existsSync(moduleDir)) {
return moduleDir
}
}
dir = path.join(dir, '..')
if (path.resolve(dir) === '/') {
return null
}
}
}
function getModuleEntryFile(dir) {
let entryFile = 'index.js'
let files = fs.readdirSync(dir)
if (files.includes('package.json')) {
let text = fs.readFileSync(path.join(dir, 'package.json')).toString()
let pkg = JSON.parse(text)
entryFile = pkg.module || pkg.main || entryFile
}
return path.join(dir, entryFile)
}
function fixImport({ srcFile, importCode, from, to }) {
let newImportCode = importCode.replace(from, to)
log(`[fixImport]`, { srcFile, importCode, from, to })
let code = fs.readFileSync(srcFile).toString()
code = code.replace(importCode, newImportCode)
fs.writeFileSync(srcFile, code)
return newImportCode
}
function scanModuleMainFile({ file }) {
// no need?
// log(`[scanModuleMainFile] TODO`, { file })
}
function scanModule({ srcFile, importCode, name }) {
if (name.startsWith('node:') || !name.startsWith('/')) {
// e.g. 'node:fs/promises' or 'fs/promises'
return
}
let numOfDirInName = name.split('/').length - 1
if (name.includes('@')) {
numOfDirInName--
}
if (numOfDirInName == 0) {
return
}
let dir = findNodeModuleDir(srcFile, name)
if (dir) {
let mainFile = isFileExists(dir) ? dir : getModuleEntryFile(dir)
return scanModuleMainFile({ file: mainFile })
}
let jsName = name + '.js'
let jsFile = findNodeModuleDir(srcFile, jsName)
if (!jsFile) {
console.error(`Error: cannot resolve module`, {
name,
srcFile,
importCode,
})
process.exit(1)
}
fixImport({ srcFile, importCode, from: name, to: jsName })
scanModuleMainFile({ file: jsFile })
}
function resolveImportName({ srcFile, name }) {
if (name.startsWith('/')) {
return { type: 'absolute', name }
}
if (name.startsWith('./') || name === '.') {
let dir = path.dirname(srcFile)
name = path.join(dir, name)
return { type: 'relative', name }
}
if (name.startsWith('../') || name === '..') {
let dir = path.dirname(srcFile)
name = path.join(dir, name)
return { type: 'relative', name }
}
return { type: 'module', name }
}
let js_ext_list = ['.js', '.jsx']
let ts_ext_list = ['.ts', '.tsx']
let ext_list = [...js_ext_list, ...ts_ext_list]
function scanImport({ srcFile, importCode, name }) {
let { type, name: importName } = resolveImportName({ srcFile, name })
if (type == 'module') {
return scanModule({ srcFile, importCode, name })
}
let importFile = resolveImportFile(importName)
if (!importFile) {
console.error(`[scanImport] File not found:`, {
srcFile,
importName,
importCode,
name,
})
process.exit(1)
}
if (!ext_list.some(ext => importName.endsWith(ext))) {
for (let ext of ext_list) {
if (!importName.endsWith('.js') && importFile.endsWith(ext)) {
log(`[scanImport] fix import:`, {
srcFile,
importCode,
importName,
importFile,
})
importCode = fixImport({
srcFile,
importCode,
from: name,
to: importFile.startsWith(importName + '/index')
? name + '/index.js'
: name + '.js',
})
break
}
}
} else {
ext: for (let js_ext of js_ext_list) {
for (let ts_ext of ts_ext_list) {
if (importName.endsWith(ts_ext) && importFile.endsWith(js_ext)) {
importCode = fixImport({
srcFile,
importCode,
from: name,
to: name.slice(0, name.length - ts_ext.length) + js_ext,
})
break ext
}
}
}
}
return scanFile({ srcFile: importFile })
}
function isFileExists(file) {
return fs.existsSync(file) && fs.statSync(file).isFile()
}
function resolveImportFile(file) {
if (isFileExists(file)) {
return file
}
for (let jsExt of js_ext_list) {
let jsFile = file + jsExt
if (isFileExists(jsFile)) {
return jsFile
}
for (let tsExt of ts_ext_list) {
let tsFile = file + tsExt
if (isFileExists(tsFile)) {
return tsFile
}
if (file.endsWith(jsExt)) {
tsFile = file.slice(0, file.length - jsExt.length) + tsExt
if (isFileExists(tsFile)) {
return tsFile
}
}
}
}
for (let indexFile of ['index.js', 'index.jsx', 'index.ts', 'index.tsx']) {
indexFile = path.join(file, indexFile)
if (isFileExists(indexFile)) {
return indexFile
}
}
for (let tsExt of ts_ext_list) {
if (file.endsWith(tsExt)) {
return resolveImportFile(file.slice(0, file.length - tsExt.length))
}
}
return null
}
let visit_file_set = new Set()
function scanFile({ srcFile }) {
if (visit_file_set.has(srcFile)) return
visit_file_set.add(srcFile)
log('[scanFile]', { srcFile })
let code = fs.readFileSync(srcFile).toString()
for (let regex of [
/.*import .* from '(.*?)'.*/g,
/.*import .* from "(.*?)".*/g,
/.*import "(.*?)".*/g,
/.*import '(.*?)'.*/g,
/.*export .* from '(.*?)'.*/g,
/.*export .* from "(.*?)".*/g,
// handle multi-line import/export with bracket, suggested by fox1t
/.*import\s*(?:type\s*)?{[^}]*}\s*from\s*'(.*?)'.*/g,
/.*import\s*(?:type\s*)?{[^}]*}\s*from\s*"(.*?)".*/g,
/.*export\s*(?:type\s*)?{[^}]*}\s*from\s*'(.*?)'.*/g,
/.*export\s*(?:type\s*)?{[^}]*}\s*from\s*"(.*?)".*/g,
]) {
for (let match of code.matchAll(regex)) {
let [importCode, name] = match
if (importCode.startsWith('//')) continue // skip comment
if (!processImportType && importCode.includes('import type')) continue
scanImport({ srcFile, importCode, name })
}
}
}
function scanEntryPoint(file) {
log('[scanEntryPoint]', { file })
let stat = fs.statSync(file)
if (stat.isFile()) {
if (file.endsWith('.js') || file.endsWith('.ts')) {
scanFile({ srcFile: file })
}
// e.g. package.json, .gitignore
return
}
if (stat.isDirectory()) {
fs.readdirSync(file).forEach(filename => {
if (filename == 'node_modules') return
scanEntryPoint(path.join(file, filename))
})
return
}
// e.g. socket file
console.log('skip unsupported file:', file)
}
for (let entryPoint of entryPoints) {
scanEntryPoint(entryPoint)
}
console.log('done.')