-
Notifications
You must be signed in to change notification settings - Fork 258
Expand file tree
/
Copy pathnode-exports-resolver.js
More file actions
185 lines (146 loc) · 5.78 KB
/
Copy pathnode-exports-resolver.js
File metadata and controls
185 lines (146 loc) · 5.78 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
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
const fs = require('fs')
const path = require('path')
const packageUp = require('pkg-up')
const defaultConditions = ['require', 'node', 'default']
function findMainPackageJson (entryPath, packageName) {
entryPath = entryPath.replace(/\//g, path.sep)
let directoryName = path.dirname(entryPath)
let suspect = packageUp.sync({ cwd: directoryName })
if (fs.existsSync(suspect)) {
return JSON.parse(fs.readFileSync(suspect).toString())
}
while (directoryName && !directoryName.endsWith(packageName)) {
const parentDirectoryName = path.resolve(directoryName, '..')
if (parentDirectoryName === directoryName) break
directoryName = parentDirectoryName
}
suspect = path.resolve(directoryName, 'package.json')
if (fs.existsSync(suspect)) {
return JSON.parse(fs.readFileSync(suspect).toString())
}
return null
}
function getSelfReferencePath (packageName) {
let parentDirectoryName = __dirname
let directoryName
while (directoryName !== parentDirectoryName) {
directoryName = parentDirectoryName
try {
const { name } = require(path.resolve(directoryName, 'package.json'))
if (name === packageName) return directoryName
} catch {}
parentDirectoryName = path.resolve(directoryName, '..')
}
}
function getPackageJson (packageName) {
// Require `package.json` from the package, both from exported `exports` field
// in ESM packages, or directly from the file itself in CommonJS packages.
try {
return require(`${packageName}/package.json`)
} catch (requireError) {
if (requireError.code === 'MODULE_NOT_FOUND') {
throw requireError
}
if (requireError.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
return console.error(
`Unexpected error while requiring ${packageName}:`, requireError
)
}
}
// modules's `package.json` does not provide the "./package.json" path at it's
// "exports" field. Get package level export or main field and try to resolve
// the package.json from it.
try {
const requestPath = require.resolve(packageName)
return requestPath && findMainPackageJson(requestPath, packageName)
} catch (resolveError) {
if (resolveError.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
console.log(
`Unexpected error while performing require.resolve(${packageName}):`
)
return console.error(resolveError)
}
}
// modules's `package.json` does not provide a package level export nor main
// field. Try to find the package manually from `node_modules` folder.
const suspect = path.resolve(__dirname, '..', packageName, 'package.json')
if (fs.existsSync(suspect)) {
return JSON.parse(fs.readFileSync(suspect).toString())
}
console.warn(
'Could not retrieve package.json neither through require (package.json ' +
'itself is not within "exports" field), nor through require.resolve ' +
'(package.json does not specify "main" field) - falling back to default ' +
'resolver logic'
)
}
module.exports = (request, options) => {
const { conditions = defaultConditions, defaultResolver } = options
// console.log('resovler', request, options)
// NOTE: jest-sequencer is a special prefixed jest request
const isNodeModuleRequest =
!(
request.startsWith('.') ||
path.isAbsolute(request) ||
request.startsWith('jest-sequencer')
)
if (isNodeModuleRequest) {
const pkgPathParts = request.split('/')
const { length } = pkgPathParts
let packageName
let submoduleName
if (!request.startsWith('@')) {
packageName = pkgPathParts.shift()
submoduleName = length > 1 ? `./${pkgPathParts.join('/')}` : '.'
} else if (length >= 2) {
packageName = `${pkgPathParts.shift()}/${pkgPathParts.shift()}`
submoduleName = length > 2 ? `./${pkgPathParts.join('/')}` : '.'
}
if (packageName && submoduleName !== '.') {
const selfReferencePath = getSelfReferencePath(packageName)
if (selfReferencePath) packageName = selfReferencePath
const packageJson = getPackageJson(packageName)
if (!packageJson) {
console.error(`Failed to find package.json for ${packageName}`)
}
const { exports } = packageJson || {}
if (exports) {
let targetFilePath
if (typeof exports === 'string') { targetFilePath = exports } else if (Object.keys(exports).every((k) => k.startsWith('.'))) {
const [exportKey, exportValue] = Object.entries(exports)
.find(([k]) => {
if (k === submoduleName) return true
if (k.endsWith('*')) return submoduleName.startsWith(k.slice(0, -1))
return false
}) || []
if (typeof exportValue === 'string') {
targetFilePath = exportKey.endsWith('*')
? exportValue.replace(
/\*/, submoduleName.slice(exportKey.length - 1)
)
: exportValue
} else if (
conditions && exportValue != null && typeof exportValue === 'object'
) {
function resolveExport (exportValue, prevKeys) {
for (const [key, value] of Object.entries(exportValue)) {
// Duplicated nested conditions are undefined behaviour (and
// probably a format error or spec loop-hole), abort and
// delegate to Jest default resolver
if (prevKeys.includes(key)) return
if (!conditions.includes(key)) continue
if (typeof value === 'string') return value
return resolveExport(value, prevKeys.concat(key))
}
}
targetFilePath = resolveExport(exportValue, [])
}
}
if (targetFilePath) {
request = targetFilePath.replace('./', `${packageName}/`)
}
}
}
}
return defaultResolver(request, options)
}