-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.ts
More file actions
357 lines (298 loc) · 10.2 KB
/
module.ts
File metadata and controls
357 lines (298 loc) · 10.2 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import { resolve } from 'node:path'
import { readFile, writeFile } from 'node:fs/promises'
import { specifier } from './specifier.js'
import type { Spec } from './specifier.js'
import type { TemplateLiteral } from 'oxc-parser'
import { parse } from './parse.js'
import {
format,
collectDualPackageUsage,
dualPackageHazardDiagnostics,
type PackageUsage,
} from './format.js'
import { getLangFromExt } from './utils/lang.js'
import type { ModuleOptions, Diagnostic } from './types.js'
import { resolve as pathResolve, dirname as pathDirname, extname, join } from 'node:path'
import { readFile as fsReadFile, stat, realpath } from 'node:fs/promises'
import { parse as parseModule } from './parse.js'
import { walk } from './walk.js'
import { collectModuleIdentifiers } from './utils/identifiers.js'
import { builtinSpecifiers } from './utils/builtinSpecifiers.js'
type AppendJsExtensionMode = NonNullable<ModuleOptions['appendJsExtension']>
type DetectCircularRequires = NonNullable<ModuleOptions['detectCircularRequires']>
const collapseSpecifier = (value: string) => value.replace(/['"`+)\s]|new String\(/g, '')
const appendExtensionIfNeeded = (
spec: Spec,
mode: AppendJsExtensionMode,
dirIndex: string | false,
value: string = spec.value,
) => {
if (mode === 'off') return
if (spec.type === 'TemplateLiteral') {
const node = spec.node as TemplateLiteral
if (node.expressions.length > 0) return
} else if (spec.type !== 'StringLiteral') {
return
}
const collapsed = collapseSpecifier(value)
const isRelative = /^(?:\.\.?)\//.test(collapsed)
if (!isRelative) return
const base = collapsed.split(/[?#]/)[0]
if (!base) return
if (base.endsWith('/')) {
if (!dirIndex) return
return `${value}${dirIndex}`
}
const lastSegment = base.split('/').pop() ?? ''
if (lastSegment.includes('.')) return
return `${value}.js`
}
const rewriteSpecifierValue = (
value: string,
rewriteSpecifier: ModuleOptions['rewriteSpecifier'],
) => {
if (!rewriteSpecifier) return
if (typeof rewriteSpecifier === 'function') {
return rewriteSpecifier(value) ?? undefined
}
const collapsed = collapseSpecifier(value)
const relative = /^(?:\.\.?)\//
if (relative.test(collapsed)) {
return value.replace(/(.+)\.(?:m|c)?(?:j|t)sx?([)'"]*)?$/, `$1${rewriteSpecifier}$2`)
}
}
const normalizeBuiltinSpecifier = (value: string) => {
const collapsed = collapseSpecifier(value)
if (!collapsed) return
const specPart = collapsed.split(/[?#]/)[0] ?? ''
// Ignore relative and absolute paths.
if (/^(?:\.\.?\/|\/)/.test(specPart)) return
// Skip other protocols (e.g., http:, data:) but allow node:.
if (/^[a-zA-Z][a-zA-Z+.-]*:/.test(specPart) && !specPart.startsWith('node:')) return
const bare = specPart.startsWith('node:') ? specPart.slice(5) : specPart
const base = bare.split('/')[0] ?? ''
if (!builtinSpecifiers.has(bare) && !builtinSpecifiers.has(base)) return
if (specPart.startsWith('node:')) return
const quote = /^['"`]/.exec(value)?.[0] ?? ''
return quote ? `${quote}node:${value.slice(quote.length)}` : `node:${value}`
}
const fileExists = async (candidate: string) => {
try {
const s = await stat(candidate)
return s.isFile()
} catch {
return false
}
}
const normalizePath = async (p: string) => pathResolve(await realpath(p).catch(() => p))
const resolveRequirePath = async (fromFile: string, spec: string, dirIndex: string) => {
if (!spec.startsWith('./') && !spec.startsWith('../')) return null
const base = pathResolve(pathDirname(fromFile), spec)
const ext = extname(base)
const candidates: string[] = []
if (ext) {
candidates.push(base)
} else {
candidates.push(
`${base}.js`,
`${base}.cjs`,
`${base}.mjs`,
`${base}.ts`,
`${base}.mts`,
`${base}.cts`,
)
candidates.push(join(base, dirIndex))
}
for (const candidate of candidates) {
if (await fileExists(candidate)) return await normalizePath(candidate)
}
return null
}
const collectStaticRequires = async (filePath: string, dirIndex: string) => {
const src = await fsReadFile(filePath, 'utf8')
const ast = parseModule(filePath, src)
const specs: string[] = []
await walk(ast.program, {
enter(node) {
if (
node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === 'require' &&
node.arguments.length === 1 &&
node.arguments[0].type === 'Literal' &&
typeof node.arguments[0].value === 'string'
) {
const spec = node.arguments[0].value
if (spec.startsWith('./') || spec.startsWith('../')) {
specs.push(spec)
}
}
},
})
const resolved: string[] = []
for (const spec of specs) {
const target = await resolveRequirePath(filePath, spec, dirIndex)
if (target) resolved.push(target)
}
return resolved
}
const detectCircularRequireGraph = async (
entryFile: string,
mode: DetectCircularRequires,
dirIndex: string,
) => {
const cache = new Map<string, string[]>()
const visiting = new Set<string>()
const visited = new Set<string>()
const dfs = async (file: string, stack: string[]) => {
const normalized = await normalizePath(file)
if (visiting.has(normalized)) {
const cycle = [...stack, normalized]
const msg = `Circular require detected: ${cycle.join(' -> ')}`
if (mode === 'error') {
throw new Error(msg)
}
// eslint-disable-next-line no-console -- surfaced when cycle detection is warn-only
console.warn(msg)
return
}
if (visited.has(normalized)) return
visiting.add(normalized)
stack.push(normalized)
let deps = cache.get(normalized)
if (!deps) {
deps = await collectStaticRequires(normalized, dirIndex)
cache.set(normalized, deps)
}
for (const dep of deps) {
await dfs(dep, stack)
}
stack.pop()
visiting.delete(normalized)
visited.add(normalized)
}
await dfs(await normalizePath(entryFile), [])
}
const mergeUsageMaps = (
target: Map<string, PackageUsage>,
source: Map<string, PackageUsage>,
) => {
for (const [pkg, usage] of source) {
const existing = target.get(pkg) ?? { imports: [], requires: [] }
existing.imports.push(...usage.imports)
existing.requires.push(...usage.requires)
target.set(pkg, existing)
}
}
const collectProjectDualPackageHazards = async (files: string[], opts: ModuleOptions) => {
const hazardMode = opts.detectDualPackageHazard ?? 'warn'
if (hazardMode === 'off') return new Map<string, Diagnostic[]>()
const hazardLevel = hazardMode === 'error' ? 'error' : 'warning'
const usages = new Map<string, PackageUsage>()
const manifestCache = new Map<string, any | null>()
for (const file of files) {
const code = await readFile(file, 'utf8')
const ast = parseModule(file, code)
const moduleIdentifiers = await collectModuleIdentifiers(ast.program)
const shadowedBindings = new Set(
[...moduleIdentifiers.entries()]
.filter(([, meta]) => meta.declare.length > 0)
.map(([name]) => name),
)
const perFileUsage = await collectDualPackageUsage(
ast.program,
shadowedBindings,
file,
)
mergeUsageMaps(usages, perFileUsage)
}
const diags = await dualPackageHazardDiagnostics({
usages,
hazardLevel,
cwd: opts.cwd,
manifestCache,
})
const byFile = new Map<string, Diagnostic[]>()
for (const diag of diags) {
const key = diag.filePath ?? files[0]
const existing = byFile.get(key) ?? []
existing.push(diag)
byFile.set(key, existing)
}
return byFile
}
const createDefaultOptions = (): ModuleOptions => ({
target: 'commonjs',
sourceType: 'auto',
transformSyntax: true,
liveBindings: 'strict',
rewriteSpecifier: undefined,
rewriteTemplateLiterals: 'allow',
appendJsExtension: undefined,
appendDirectoryIndex: 'index.js',
dirFilename: 'inject',
importMeta: 'shim',
importMetaMain: 'shim',
requireMainStrategy: 'import-meta-main',
detectCircularRequires: 'off',
detectDualPackageHazard: 'warn',
dualPackageHazardScope: 'file',
requireSource: 'builtin',
nestedRequireStrategy: 'create-require',
cjsDefault: 'auto',
idiomaticExports: 'safe',
importMetaPrelude: 'auto',
topLevelAwait: 'error',
cwd: undefined,
out: undefined,
inPlace: false,
})
const transform = async (filename: string, options?: ModuleOptions) => {
const base = createDefaultOptions()
const opts = options
? { ...base, ...options, filePath: filename }
: { ...base, filePath: filename }
const cwdBase = opts.cwd ? resolve(opts.cwd) : process.cwd()
const appendMode: AppendJsExtensionMode =
options?.appendJsExtension ?? (opts.target === 'module' ? 'relative-only' : 'off')
const dirIndex =
opts.appendDirectoryIndex === undefined ? 'index.js' : opts.appendDirectoryIndex
const detectCycles: DetectCircularRequires = opts.detectCircularRequires ?? 'off'
const file = resolve(cwdBase, filename)
const code = (await readFile(file)).toString()
const ast = parse(filename, code)
let source = await format(code, ast, opts)
if (opts.rewriteSpecifier || appendMode !== 'off' || dirIndex) {
const code = await specifier.updateSrc(source, getLangFromExt(filename), spec => {
if (
spec.type === 'TemplateLiteral' &&
opts.rewriteTemplateLiterals === 'static-only'
) {
const node = spec.node as TemplateLiteral
if (node.expressions.length > 0) return
}
const normalized = normalizeBuiltinSpecifier(spec.value)
const rewritten = rewriteSpecifierValue(
normalized ?? spec.value,
opts.rewriteSpecifier,
)
const baseValue = rewritten ?? normalized ?? spec.value
const appended = appendExtensionIfNeeded(spec, appendMode, dirIndex, baseValue)
return appended ?? rewritten ?? normalized ?? undefined
})
source = code
}
if (detectCycles !== 'off' && opts.target === 'module' && opts.transformSyntax) {
await detectCircularRequireGraph(file, detectCycles, dirIndex || 'index.js')
}
const outputPath = opts.inPlace
? file
: opts.out
? resolve(cwdBase, opts.out)
: undefined
if (outputPath) {
await writeFile(outputPath, source)
}
return source
}
export { transform, collectProjectDualPackageHazards }