-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathesmockLoader.js
255 lines (222 loc) · 8.3 KB
/
esmockLoader.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
import fs from 'node:fs'
import module from 'node:module'
import process from 'process'
import esmockErr from './esmockErr.js'
const [major, minor] = process.versions.node.split('.').map(it => +it)
const isLT1612 = major < 16 || (major === 16 && minor < 12)
// ex, file:///path/to/esmockLoader.js,
// file:///c:/path/to/esmockLoader.js
const urlDummy = import.meta.url
const esmkgdefsAndAfterRe = /\?esmkgdefs=.*/
const esmkgdefsAndBeforeRe = /.*\?esmkgdefs=/
const esmkdefsRe = /#-#esmkdefs/
const esmkImportStartRe = /^file:\/\/\/import\?/
const esmkImportRe = /file:\/\/\/import\?([^#]*)/
const esmkImportListItemRe = /\bimport,|,import\b|\bimport\b/g
const esmkTreeIdRe = /esmkTreeId=\d*/
const esmkModuleIdRe = /esmkModuleId=([^&]*)/
const esmkIdRe = /\?esmk=\d*/
const exportNamesRe = /.*exportNames=(.*)/
const withHashRe = /.*#-#/
const isesmRe = /isesm=true/
const isnotfoundRe = /isfound=false/
const iscommonjsmoduleRe = /^(commonjs|module)$/
const isstrict3 = /strict=3/
const hashbangRe = /^(#![^\n]*\n)/
// escape '+' char, pnpm generates long pathnames serialized with these
const moduleIdEsc = str =>
str.indexOf('+') >= 0 ? str.replace(/(?!\\)\+/g, '\\+') : str
// returned regexp will match embedded moduleid w/ treeid
const moduleIdReCreate = (moduleid, treeid) => new RegExp(
`.*(${moduleIdEsc(moduleid)}(\\?${treeid}(?:(?!#-#).)*)).*`)
// node v12.0-v18.x, global
const mockKeys = global.mockKeys = (global.mockKeys || {})
const mockKeysSource = global.mockKeysSource = (global.mockKeysSource || {})
// use fs when logging from hooks, console.log async unpredictable
const log = (...args) => (
fs.writeSync(1, JSON.stringify(args, null, ' ').slice(2, -1)))
// node v20.0-v20.6
const globalPreload = !module.register && (({ port }) => (
port.addEventListener('message', ev => (
ev.data.keysource
? mockKeysSource[ev.data.keysource] = ev.data.source
: mockKeys[ev.data.key] = ev.data.keylong)),
port.unref(),
'global.postMessageEsmk = d => port.postMessage(d)'
))
// node v20.6-current
const initialize = module.register && (data => {
if (data && data.port) {
data.port.on('message', msg => {
msg.keysource
? mockKeysSource[msg.keysource] = msg.source
: mockKeys[msg.key] = msg.keylong
})
}
})
const parseImports = defstr => {
const [specifier, imports] = (defstr.match(esmkImportRe) || [])
return [ // return [specifier, importNames]
specifier, exportNamesRe.test(imports) &&
imports.replace(exportNamesRe, '$1').split(',')]
}
// parses local and global mock imports from long-url treeidspec
const parseImportsTree = treeidspec => {
const defs = treeidspec.split(esmkdefsRe)[1] || ''
const defimports = parseImports(defs)
const gdefs = treeidspec.replace(esmkgdefsAndBeforeRe, '')
const gdefimports = parseImports(gdefs)
return [
defimports[0] || gdefimports[0],
[...new Set([defimports[1] || [], gdefimports[1] || []].flat())]
]
}
const treeidspecFromUrl = url => esmkIdRe.test(url)
&& mockKeys[url.match(esmkIdRe)[0].split('=')[1]]
// new versions of node: when multiple loaders are used and context
// is passed to nextResolve, the process crashes in a recursive call
// see: /esmock/issues/#48
//
// old versions of node: if context.parentURL is defined, and context
// is not passed to nextResolve, the tests fail
//
// later versions of node v16 include 'node-addons'
const nextResolveCall = async (nextResolve, specifier, context) => (
context.parentURL &&
(context.conditions.slice(-1)[0] === 'node-addons'
|| context.importAssertions || isLT1612)
? nextResolve(specifier, context)
: nextResolve(specifier))
const resolve = async (specifier, context, nextResolve) => {
const { parentURL } = context
const treeidspec = treeidspecFromUrl(parentURL) || parentURL
if (!esmkTreeIdRe.test(treeidspec))
return nextResolveCall(nextResolve, specifier, context)
const [treeid] = String(treeidspec).match(esmkTreeIdRe)
const [url, defs] = treeidspec.split(esmkdefsRe)
const gdefs = url && url.replace(esmkgdefsAndBeforeRe, '')
// do not call 'nextResolve' for notfound modules
if (treeidspec.includes(`esmkModuleId=${specifier}&isfound=false`)) {
const moduleIdRe = moduleIdReCreate(`file:///${specifier}`, treeid)
const moduleId = (
gdefs.match(moduleIdRe) || defs.match(moduleIdRe) || [])[2]
if (moduleId) {
return {
shortCircuit: true,
url: urlDummy + moduleId
}
}
}
if (esmkImportStartRe.test(specifier)) {
return {
shortCircuit: true,
url: specifier.replace(esmkImportStartRe, urlDummy + '?')
}
}
const resolved = await nextResolveCall(nextResolve, specifier, context)
const moduleIdRe = moduleIdReCreate(resolved.url, treeid)
const moduleId =
moduleIdRe.test(defs) && defs.replace(moduleIdRe, '$1') ||
moduleIdRe.test(gdefs) && gdefs.replace(moduleIdRe, '$1')
if (moduleId) {
resolved.url = isesmRe.test(moduleId)
? moduleId
: urlDummy + '#-#' + moduleId
} else if (gdefs && gdefs !== '0') {
if (!resolved.url.startsWith('node:')) {
resolved.url += '?esmkgdefs=' + gdefs
}
}
if (isstrict3.test(treeidspec) && !moduleId)
throw esmockErr.errModuleIdNotMocked(resolved.url, treeidspec.split('?')[0])
return resolved
}
const loaderVerifyUrl = urlDummy + '?esmock-loader=true'
const loaderIsVerified = (memo => async () => memo = memo || (
(await import(loaderVerifyUrl)).default === true))()
const load = async (url, context, nextLoad) => {
if (url === loaderVerifyUrl) {
return {
format: 'module',
shortCircuit: true,
responseURL: url,
source: 'export default true'
}
}
const treeidspec = treeidspecFromUrl(url) || url
const treeid = treeidspec &&
(treeidspec.match(esmkTreeIdRe) || [])[0]
if (treeid) {
const [specifier, importedNames] = parseImportsTree(treeidspec)
if (importedNames && importedNames.length) {
const nextLoadRes = await nextLoad(url, context)
if (!iscommonjsmoduleRe.test(nextLoadRes.format))
return nextLoadRes
// nextLoadRes.source sometimes 'undefined' and other times 'null' :(
const sourceIsNullLike = (
nextLoadRes.source === null || nextLoadRes.source === undefined)
const source = sourceIsNullLike
? String(fs.readFileSync(new URL(url)))
: String(nextLoadRes.source)
const hbang = (source.match(hashbangRe) || [])[0] || ''
const sourcesafe = hbang ? source.replace(hashbangRe, '') : source
const importexpr = nextLoadRes.format === 'commonjs'
? `const {${importedNames}} = global.esmockCacheGet("${specifier}");`
: `import {${importedNames}} from '${specifier}';`
return {
format: nextLoadRes.format,
shortCircuit: true,
responseURL: encodeURI(url),
source: hbang + importexpr + sourcesafe
}
}
}
if (esmkdefsRe.test(url)) // parent of mocked modules
return nextLoad(url, context)
url = url.replace(esmkgdefsAndAfterRe, '')
if (url.startsWith(urlDummy)) {
url = url.replace(withHashRe, '')
if (isnotfoundRe.test(url))
url = url.replace(urlDummy, `file:///${url.match(esmkModuleIdRe)[1]}`)
}
const exportedNames = exportNamesRe.test(url) && url
.replace(exportNamesRe, '$1')
.replace(esmkImportListItemRe, '')
.split(',')
if (exportedNames && exportedNames[0]) {
if (mockKeysSource[url]) {
return {
// ...await nextLoad(url, context),
format: 'json',
shortCircuit: true,
responseURL: encodeURI(url),
source: mockKeysSource[url]
}
}
return {
format: 'module',
shortCircuit: true,
responseURL: encodeURI(url),
source: exportedNames.map(name => name === 'default'
? `export default global.esmockCacheGet("${url}").default`
: `export const ${name} = global.esmockCacheGet("${url}").${name}`
).join('\n')
}
}
if (treeid && !url.includes(treeid)) {
// long querystring reduces readability of runtime error stacktrace
// smaller querystring `esmk=$id` does not clutter stacktrace
url = url + '?esmk=' + treeid.split('=')[1]
}
return nextLoad(url, context)
}
// node lt 16.12 require getSource, node gte 16.12 warn remove getSource
const getSource = isLT1612 && load
export {
load,
resolve,
getSource,
initialize,
globalPreload,
loaderIsVerified as default
}