-
Notifications
You must be signed in to change notification settings - Fork 31
/
index.mjs
131 lines (107 loc) · 3.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
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())
function _resolve (id, opts = {}) {
// console.log('> resolve ', id, 'from', opts.from)
if (/(node|data|http|https):/.test(id)) {
return id
}
if (BUILُTIN_MODULES.has(id)) {
return 'node:' + id
}
const conditionsSet = opts.conditions ? new Set(opts.conditions) : DEFAULT_CONDITIONS_SET
const resolved = moduleResolve(id, opts.from ? normalizeid(opts.from) : DEFAULT_FROM, conditionsSet)
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 code = await readModule(id, opts)
return evalModule(code, opts)
}
export async function evalModule (code, opts = {}) {
return import(await toDataURL(code, opts))
}
export async function readModule (id, opts) {
const resolved = await resolve(id, opts)
const code = await fsp.readFile(fileURLToPath(resolved), 'utf-8')
return code
}
export async function toDataURL (code, opts) {
code = await resolveImports(code, opts)
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) {
Error.captureStackTrace(_pcall, err)
return Promise.reject(err)
}
}