/
resolve.ts
173 lines (162 loc) · 5.67 KB
/
resolve.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
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
import path from 'node:path'
import glob from 'fast-glob'
import micromatch from 'micromatch'
import type { ResolvedConfig } from '../config'
import { escapeRegex, getNpmPackageName, slash } from '../utils'
import { resolvePackageData } from '../packages'
export function createOptimizeDepsIncludeResolver(
config: ResolvedConfig,
ssr: boolean,
): (id: string) => Promise<string | undefined> {
const resolve = config.createResolver({
asSrc: false,
scan: true,
ssrOptimizeCheck: ssr,
ssrConfig: config.ssr,
packageCache: new Map(),
})
return async (id: string) => {
const lastArrowIndex = id.lastIndexOf('>')
if (lastArrowIndex === -1) {
return await resolve(id, undefined, undefined, ssr)
}
// split nested selected id by last '>', for example:
// 'foo > bar > baz' => 'foo > bar' & 'baz'
const nestedRoot = id.substring(0, lastArrowIndex).trim()
const nestedPath = id.substring(lastArrowIndex + 1).trim()
const basedir = nestedResolveBasedir(
nestedRoot,
config.root,
config.resolve.preserveSymlinks,
)
return await resolve(
nestedPath,
path.resolve(basedir, 'package.json'),
undefined,
ssr,
)
}
}
/**
* Expand the glob syntax in `optimizeDeps.include` to proper import paths
*/
export function expandGlobIds(id: string, config: ResolvedConfig): string[] {
const pkgName = getNpmPackageName(id)
if (!pkgName) return []
const pkgData = resolvePackageData(
pkgName,
config.root,
config.resolve.preserveSymlinks,
config.packageCache,
)
if (!pkgData) return []
const pattern = '.' + id.slice(pkgName.length)
const exports = pkgData.data.exports
// if package has exports field, get all possible export paths and apply
// glob on them with micromatch
if (exports) {
if (typeof exports === 'string' || Array.isArray(exports)) {
return [pkgName]
}
const possibleExportPaths: string[] = []
for (const key in exports) {
if (key.startsWith('.')) {
if (key.includes('*')) {
// "./glob/*": {
// "browser": "./dist/glob/*-browser/*.js", <-- get this one
// "default": "./dist/glob/*/*.js"
// }
// NOTE: theoretically the "default" condition could map to a different
// set of files, but that complicates the resolve logic, so we assume
// all conditions map to the same set of files, and get the first one.
const exportsValue = getFirstExportStringValue(exports[key])
if (!exportsValue) continue
// "./dist/glob/*-browser/*.js" => "./dist/glob/**/*-browser/**/*.js"
// NOTE: in some cases, this could expand to consecutive /**/*/**/* etc
// but it's fine since fast-glob handles it the same.
const exportValuePattern = exportsValue.replace(/\*/g, '**/*')
// "./dist/glob/*-browser/*.js" => /dist\/glob\/(.*)-browser\/(.*)\.js/
const exportsValueGlobRe = new RegExp(
exportsValue.split('*').map(escapeRegex).join('(.*)'),
)
possibleExportPaths.push(
...glob
.sync(exportValuePattern, {
cwd: pkgData.dir,
ignore: ['node_modules'],
})
.map((filePath) => {
// "./glob/*": "./dist/glob/*-browser/*.js"
// `filePath`: "./dist/glob/foo-browser/foo.js"
// we need to revert the file path back to the export key by
// matching value regex and replacing the capture groups to the key
const matched = slash(filePath).match(exportsValueGlobRe)
// `matched`: [..., 'foo', 'foo']
if (matched) {
let allGlobSame = matched.length === 2
// exports key can only have one *, so for >=2 matched groups,
// make sure they have the same value
if (!allGlobSame) {
// assume true, if one group is different, set false and break
allGlobSame = true
for (let i = 2; i < matched.length; i++) {
if (matched[i] !== matched[i - 1]) {
allGlobSame = false
break
}
}
}
if (allGlobSame) {
return key.replace('*', matched[1]).slice(2)
}
}
return ''
})
.filter(Boolean),
)
} else {
possibleExportPaths.push(key.slice(2))
}
}
}
const matched = micromatch(possibleExportPaths, pattern).map((match) =>
path.posix.join(pkgName, match),
)
matched.unshift(pkgName)
return matched
} else {
// for packages without exports, we can do a simple glob
const matched = glob
.sync(pattern, { cwd: pkgData.dir, ignore: ['node_modules'] })
.map((match) => path.posix.join(pkgName, slash(match)))
matched.unshift(pkgName)
return matched
}
}
function getFirstExportStringValue(
obj: string | string[] | Record<string, any>,
): string | undefined {
if (typeof obj === 'string') {
return obj
} else if (Array.isArray(obj)) {
return obj[0]
} else {
for (const key in obj) {
return getFirstExportStringValue(obj[key])
}
}
}
/**
* Continuously resolve the basedir of packages separated by '>'
*/
function nestedResolveBasedir(
id: string,
basedir: string,
preserveSymlinks = false,
) {
const pkgs = id.split('>').map((pkg) => pkg.trim())
for (const pkg of pkgs) {
basedir = resolvePackageData(pkg, basedir, preserveSymlinks)?.dir || basedir
}
return basedir
}