-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.ts
More file actions
67 lines (56 loc) · 1.86 KB
/
module.ts
File metadata and controls
67 lines (56 loc) · 1.86 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
import { resolve } from 'node:path'
import { readFile, writeFile } from 'node:fs/promises'
import { specifier } from '@knighted/specifier'
import { parse } from '#parse'
import { format } from '#format'
import { getLangFromExt } from '#utils/lang.js'
import type { ModuleOptions } from './types.js'
const defaultOptions = {
target: 'commonjs',
sourceType: 'auto',
transformSyntax: true,
liveBindings: 'strict',
rewriteSpecifier: undefined,
dirFilename: 'inject',
importMeta: 'shim',
requireSource: 'builtin',
cjsDefault: 'auto',
topLevelAwait: 'error',
out: undefined,
inPlace: false,
} satisfies ModuleOptions
const transform = async (filename: string, options: ModuleOptions = defaultOptions) => {
const opts = { ...defaultOptions, ...options }
const file = resolve(filename)
const code = (await readFile(file)).toString()
const ast = parse(filename, code)
let source = await format(code, ast, opts)
if (opts.rewriteSpecifier) {
const code = await specifier.updateSrc(
source,
getLangFromExt(filename),
({ value }) => {
if (typeof opts.rewriteSpecifier === 'function') {
return opts.rewriteSpecifier(value) ?? undefined
}
// Collapse any BinaryExpression or NewExpression to test for a relative specifier
const collapsed = value.replace(/['"`+)\s]|new String\(/g, '')
const relative = /^(?:\.|\.\.)\//
if (relative.test(collapsed)) {
// $2 is for any closing quotation/parens around BE or NE
return value.replace(
/(.+)\.(?:m|c)?(?:j|t)s([)'"]*)?$/,
`$1${opts.rewriteSpecifier}$2`,
)
}
},
)
source = code
}
const outputPath = opts.inPlace ? file : opts.out ? resolve(opts.out) : undefined
if (outputPath) {
await writeFile(outputPath, source)
}
return source
}
export { transform }