-
-
Notifications
You must be signed in to change notification settings - Fork 270
/
munge-mocks.ts
44 lines (42 loc) · 1.27 KB
/
munge-mocks.ts
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
import { isBuiltin } from 'module'
import { isAbsolute, resolve } from 'path'
import { isRelativeRequire } from 'resolve-import/is-relative-require'
import { pathToFileURL } from 'url'
// turn all the mocks we get into either the exports provided,
// if it's an object, or { default: <value> } otherwise.
export const mungeMocks = (
mocksInput: Record<string, any>,
dir: string,
): { [k: string]: { [j: string]: any } } => {
const mocks = Object.create(null)
for (const [k, v] of Object.entries(mocksInput)) {
const m =
v && typeof v === 'object' && !Array.isArray(v) ?
v
: { default: v }
if (isBuiltin(k)) {
mocks[k] = m
/* c8 ignore start */
if (k.startsWith('node:')) {
/* c8 ignore stop */
const bare = k.substring('node:'.length)
if (!(bare in mocksInput)) {
mocks[bare] = m
}
} else {
const prefixed = `node:${k}`
if (!(prefixed in mocksInput)) {
mocks[prefixed] = m
}
}
} else if (/^(file:\/\/\/|https?:\/\/)/.test(k)) {
mocks[k] = m
} else if (isRelativeRequire(k) || isAbsolute(k)) {
mocks[String(pathToFileURL(resolve(dir, k)))] = m
} else {
// absolute package name
mocks[k] = m
}
}
return mocks
}