-
Notifications
You must be signed in to change notification settings - Fork 31
/
index.mjs
197 lines (161 loc) · 5 KB
/
index.mjs
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
import { fileURLToPath as _fileURLToPath, pathToFileURL } from 'url'
import { dirname } from 'path'
import { realpathSync, promises as fsp } from 'fs'
import { createRequire, builtinModules } from 'module'
import { moduleResolve } from 'import-meta-resolve'
// CommonJS
export function createCommonJS (importMeta) {
const __filename = fileURLToPath(importMeta.url)
const __dirname = dirname(__filename)
// Lazy require
let _nativeRequire
const getNativeRequire = () => _nativeRequire || (_nativeRequire = createRequire(importMeta.url))
function require (id) { return getNativeRequire()(id) }
require.resolve = (id, options) => getNativeRequire().resolve(id, options)
return {
__filename,
__dirname,
require
}
}
// Resolve
const DEFAULT_CONDITIONS_SET = new Set(['node', 'import'])
const BUILُTIN_MODULES = new Set(builtinModules)
const DEFAULT_FROM = pathToFileURL(process.cwd())
const DEFAULT_EXTENSIONS = ['.mjs', '.cjs', '.js', '.json']
const NOT_FOUND_ERRORS = new Set(['ERR_MODULE_NOT_FOUND', 'ERR_UNSUPPORTED_DIR_IMPORT', 'MODULE_NOT_FOUND'])
function _tryModuleResolve (id, from, conditions) {
try {
return moduleResolve(id, from, conditions)
} catch (err) {
if (!NOT_FOUND_ERRORS.has(err.code)) {
throw err
}
return null
}
}
function _resolve (id, opts = {}) {
// console.log('> resolve ', id, 'from', opts.from)
// Skip if already has a protocol
if (/(node|data|http|https):/.test(id)) {
return id
}
// Skip builtins
if (BUILُTIN_MODULES.has(id)) {
return 'node:' + id
}
// Defaults
const conditionsSet = opts.conditions ? new Set(opts.conditions) : DEFAULT_CONDITIONS_SET
const from = opts.from ? normalizeid(opts.from) : DEFAULT_FROM
// Try simple resolve
let resolved = _tryModuleResolve(id, from, conditionsSet)
// Try other extensions if not found
if (!resolved) {
for (const prefix of ['', '/index']) {
for (const ext of opts.extensions || DEFAULT_EXTENSIONS) {
resolved = _tryModuleResolve(id + prefix + ext, from, conditionsSet)
if (resolved) { break }
}
if (resolved) { break }
}
}
// Throw error if not found
if (!resolved) {
const err = new Error(`Cannot find module ${id} imported from ${from}`)
err.code = 'MODULE_NOT_FOUND'
throw err
}
// Resolve realPath and normalize slash
const realPath = realpathSync(fileURLToPath(resolved))
return pathToFileURL(realPath).toString()
}
export function resolveSync (id, opts) {
return _resolve(id, opts)
}
export function resolve (id, opts) {
return _pcall(resolveSync, id, opts)
}
export function resolvePathSync (id, opts) {
return fileURLToPath(resolveSync(id, opts))
}
export function resolvePath (id, opts) {
return _pcall(resolvePathSync, id, opts)
}
export function createResolve (defaults) {
return (id, from) => {
return resolve(id, { ...defaults, from: from || defaults.from })
}
}
// Evaluate
const ESM_IMPORT_RE = /(?<=import .* from ['"])([^'"]+)(?=['"])|(?<=export .* from ['"])([^'"]+)(?=['"])|(?<=import\s*['"])([^'"]+)(?=['"])|(?<=import\s*\(['"])([^'"]+)(?=['"]\))/g
export async function loadModule (id, opts = {}) {
const { url, code } = await readModule(id, opts)
return evalModule(code, {
url,
...opts
})
}
export async function evalModule (code, opts = {}) {
return import(await toDataURL(code, opts))
}
export async function readModule (id, opts) {
const url = await resolve(id, opts)
const code = await fsp.readFile(fileURLToPath(url), 'utf-8')
return { url, code }
}
export async function toDataURL (code, opts) {
// Use url <> from as defaults of each other
if (!opts.url && opts.from) {
opts.url = opts.from
} else if (opts.url && !opts.from) {
opts.from = opts.url
}
// Resolve relative imports
code = await resolveImports(code, opts)
// Rewrite import.meta.url
if (opts.url) {
code = code.replace(/import\.meta\.url/g, `'${opts.url}'`)
}
// Convert to base64
const base64 = Buffer.from(code).toString('base64')
return `data:text/javascript;base64,${base64}`
}
export function resolveImports (code, opts) {
// TODO: Reimplement with resolve (async replace)
return _pcall(() => code.replace(ESM_IMPORT_RE, id => resolveSync(id, opts)))
}
// Utils
export function fileURLToPath (id) {
if (typeof id === 'string' && !id.startsWith('file://')) {
return normalizeSlash(id)
}
return normalizeSlash(_fileURLToPath(id))
}
export function normalizeid (id) {
if (typeof id !== 'string') {
id = id.toString()
}
if (/(node|data|http|https|file):/.test(id)) {
return id
}
if (BUILُTIN_MODULES.has(id)) {
return 'node:' + id
}
return 'file://' + normalizeSlash(id)
}
function normalizeSlash (str) {
return str.replace(/\\/g, '/')
}
function _pcall (fn, ...args) {
try {
return Promise.resolve(fn(...args)).catch(err => _perr(err))
} catch (err) {
return _perr(err)
}
}
function _perr (_err) {
const err = new Error(_err)
err.code = _err.code
Error.captureStackTrace(err, _pcall)
return Promise.reject(err)
}