-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathesmockModule.js
More file actions
157 lines (124 loc) · 5.43 KB
/
esmockModule.js
File metadata and controls
157 lines (124 loc) · 5.43 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
import fs from 'fs'
import url from 'node:url'
import resolvewith from 'resolvewithplus'
import esmockErr from './esmockErr.js'
import {
esmockTreeIdSet,
esmockTreeIdGet,
esmockCacheSet,
esmockCacheResolvedPathIsESMGet,
esmockCacheResolvedPathIsESMSet
} from './esmockCache.js'
const isObj = o => typeof o === 'object' && o
const isDefaultIn = o => isObj(o) && 'default' in o
const isDirPathRe = /^\.?\.?([a-zA-Z]:)?(\/|\\)/
const isMetaResolve = typeof import.meta.resolve === 'function'
const nextId = ((id = 0) => () => ++id)()
const asFileURL = p => p.startsWith('file://') ? p : url.pathToFileURL(p)
const objProto = Object.getPrototypeOf({})
const isPlainObj = o => Object.getPrototypeOf(o) === objProto
// assigning the object to its own prototypal inheritor can error, eg
// 'Cannot assign to read only property \'F_OK\' of object \'#<Object>\''
//
// if not plain obj, assign enumerable vals only. core modules === plain obj
const esmockModuleMerge = (defLive, def) => isPlainObj(defLive)
? Object.assign({}, defLive, def)
: Object.assign(Object.keys(defLive).reduce(
(prev, k) => (Object.defineProperty(prev, k, {
value: defLive[k],
writable: true
}), prev), Object.create(defLive)), def)
const esmockModuleMergeDefault = (defLive, def) =>
(isObj(defLive) && isObj(def)) ? esmockModuleMerge(defLive, def) : def
const esmockModuleApply = (defLive, def, fileURL) => {
def = Object.assign({}, defLive || {}, {
default: esmockModuleMergeDefault(
isDefaultIn(defLive) && defLive.default,
isDefaultIn(def) ? def.default : def)
}, def)
// if safe, an extra "default.default" is added for compatibility with
// babel-generated dist cjs files which also define "default.default"
if (!resolvewith.iscoremodule(fileURL) && Object.isExtensible(def.default))
def.default.default = def.default
return def
}
// eslint-disable-next-line max-len
const esmockModuleESMRe = /(^\s*|[});\n]\s*)(import\s+(['"]|(\*\s+as\s+)?[^"'()\n;]+\s+from\s+['"]|\{)|export\s+\*\s+from\s+["']|export\s+(\{|default|function|class|var|const|let|async\s+function))/
// returns cached results when available
const esmockModuleIsESM = (fileURL, isesm) => {
isesm = esmockCacheResolvedPathIsESMGet(fileURL)
if (typeof isesm === 'boolean')
return isesm
isesm = !resolvewith.iscoremodule(fileURL)
&& isDirPathRe.test(fileURL)
&& esmockModuleESMRe.test(fs.readFileSync(fileURL, 'utf-8'))
esmockCacheResolvedPathIsESMSet(fileURL, isesm)
return isesm
}
// return the default value directly, so that the esmock caller
// does not need to lookup default as in "esmockedValue.default"
const esmockModuleImportedSanitize = (imported, esmkTreeId) => {
const importedDefault = isDefaultIn(imported) && imported.default
if (/boolean|string|number/.test(typeof importedDefault))
return imported
// ex, non-extensible "[object Module]": import * as fs from 'fs'; export fs;
return Object.isExtensible(importedDefault)
? Object.assign(importedDefault, imported, { esmkTreeId })
: Object.assign({}, importedDefault, imported, { esmkTreeId })
}
const esmockModuleImportedPurge = treeid => {
const purgeKey = key => key === 'null' || esmockCacheSet(key, null)
const longKey = esmockTreeIdGet(treeid.split('esmk=')[1])
const [url, keys] = longKey.split('#-#esmkdefs=')
String(keys).split('#-#').forEach(purgeKey)
String(url.split('esmkgdefs=')[1]).split('#-#').forEach(purgeKey)
}
const esmockModuleCreate = async (treeid, def, id, fileURL, opt) => {
def = esmockModuleApply(
opt.strict || !fileURL || await import(fileURL), def, fileURL)
const mockModuleKey = (fileURL || 'file:///' + id) + '?' + [
'esmkTreeId=' + treeid,
'esmkModuleId=' + id,
'isfound=' + Boolean(fileURL),
'isesm=' + esmockModuleIsESM(fileURL),
'exportNames=' + Object.keys(def).sort().join()
].join('&')
esmockCacheSet(mockModuleKey, def)
return mockModuleKey
}
const esmockModuleId = async (parent, treeid, defs, ids, opt, mocks, id) => {
ids = ids || Object.keys(defs)
id = ids[0]
mocks = mocks || []
if (!id) return mocks
const fileURL = isMetaResolve
? await import.meta.resolve(id, asFileURL(parent)).catch(() => null)
: resolvewith(id, parent)
if (!fileURL && opt.isModuleNotFoundError !== false)
throw esmockErr.errModuleIdNotFound(id, parent)
mocks.push(await esmockModuleCreate(treeid, defs[id], id, fileURL, opt))
return esmockModuleId(parent, treeid, defs, ids.slice(1), opt, mocks)
}
const esmockModule = async (moduleId, parent, defs, gdefs, opt) => {
const moduleFileURL = resolvewith(moduleId, parent)
if (!moduleFileURL)
throw esmockErr.errModuleIdNotFound(moduleId, parent)
const gkeys = gdefs ? Object.keys(gdefs) : []
const dkeys = defs ? Object.keys(defs) : []
if (opt.strict === 3 && !gkeys.length && !dkeys.length) {
throw esmockErr.errModuleIdNoDefs(moduleId, parent)
}
const treeid = typeof opt.id === 'number' ? opt.id : nextId()
const treeidspec = `${moduleFileURL}?key=${treeid}&strict=${opt.strict}?` + [
'esmkgdefs=' + (gkeys.length && (await esmockModuleId(
parent, treeid, gdefs, gkeys, opt)).join('#-#') || 0),
'esmkdefs=', (dkeys.length && (await esmockModuleId(
parent, treeid, defs, dkeys, opt)).join('#-#') || 0)
].join('#-#')
esmockTreeIdSet(String(treeid), treeidspec)
return moduleFileURL + `?esmk=${treeid}`
}
export default Object.assign(esmockModule, {
purge: esmockModuleImportedPurge,
sanitize: esmockModuleImportedSanitize
})