/
GlobResolver.js
224 lines (195 loc) Β· 6.06 KB
/
GlobResolver.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
// @flow
import {Resolver} from '@parcel/plugin';
import {
isGlob,
glob,
globToRegex,
relativePath,
normalizeSeparators,
} from '@parcel/utils';
import path from 'path';
import nullthrows from 'nullthrows';
import ThrowableDiagnostic from '@parcel/diagnostic';
import NodeResolver from '@parcel/node-resolver-core';
import invariant from 'assert';
function errorToThrowableDiagnostic(error, dependency): ThrowableDiagnostic {
return new ThrowableDiagnostic({
diagnostic: {
message: error,
codeFrames: dependency.loc
? [
{
codeHighlights: [
{
start: dependency.loc.start,
end: dependency.loc.end,
},
],
},
]
: undefined,
},
});
}
export default (new Resolver({
async resolve({dependency, options, specifier, pipeline, logger}) {
if (!isGlob(specifier)) {
return;
}
let sourceAssetType = nullthrows(dependency.sourceAssetType);
let sourceFile = nullthrows(
dependency.resolveFrom ?? dependency.sourcePath,
);
let error;
if (sourceAssetType !== 'js' && sourceAssetType !== 'css') {
error = `Glob imports are not supported in ${sourceAssetType} files.`;
} else if (
dependency.specifierType === 'url' &&
!dependency.meta?.isCSSImport
) {
error = 'Glob imports are not supported in URL dependencies.';
}
if (error) {
throw errorToThrowableDiagnostic(error, dependency);
}
// if the specifier does not start with /, ~, or . then it's not a path but package-ish - we resolve
// the package first, and then append the rest of the path
if (!/^[/~.]/.test(specifier)) {
// Globs are not paths - so they always use / (see https://github.com/micromatch/micromatch#backslashes)
let splitOn = specifier.indexOf('/');
if (specifier.charAt(0) === '@') {
splitOn = specifier.indexOf('/', splitOn + 1);
}
// Since we've already asserted earlier that there is a glob present, it shouldn't be
// possible for there to be only a package here without any other path parts (e.g. `import('pkg')`)
invariant(splitOn !== -1);
let pkg = specifier.substring(0, splitOn);
let rest = specifier.substring(splitOn + 1);
// This initialisation code is copied from the DefaultResolver
const resolver = new NodeResolver({
fs: options.inputFS,
projectRoot: options.projectRoot,
// Extensions are always required in URL dependencies.
extensions:
dependency.specifierType === 'commonjs' ||
dependency.specifierType === 'esm'
? ['ts', 'tsx', 'js', 'jsx', 'json']
: [],
mainFields: ['source', 'browser', 'module', 'main'],
packageManager: options.shouldAutoInstall
? options.packageManager
: undefined,
logger,
});
const result = await resolver.resolve({
filename: pkg,
specifierType: dependency.specifierType,
parent: dependency.resolveFrom,
env: dependency.env,
sourcePath: dependency.sourcePath,
loc: dependency.loc,
});
if (!result || !result.filePath) {
throw errorToThrowableDiagnostic(
`Unable to resolve ${pkg} from ${sourceFile} when evaluating specifier ${specifier}`,
dependency,
);
} else if (result.diagnostics) {
throw new ThrowableDiagnostic({diagnostic: result.diagnostics});
}
specifier = path.resolve(path.dirname(result.filePath), rest);
} else {
specifier = path.resolve(path.dirname(sourceFile), specifier);
}
let normalized = normalizeSeparators(specifier);
let files = await glob(normalized, options.inputFS, {
onlyFiles: true,
});
let dir = path.dirname(specifier);
let results = files.map(file => {
let relative = relativePath(dir, file);
if (pipeline) {
relative = `${pipeline}:${relative}`;
}
return [file, relative];
});
let code = '';
if (sourceAssetType === 'js') {
let re = globToRegex(normalized, {capture: true});
let matches = {};
for (let [file, relative] of results) {
let match = file.match(re);
if (!match) continue;
let parts = match
.slice(1)
.filter(Boolean)
.reduce((a, p) => a.concat(p.split('/')), []);
set(matches, parts, relative);
}
let {value, imports} = generate(matches, dependency.priority === 'lazy');
code = imports + 'module.exports = ' + value;
} else if (sourceAssetType === 'css') {
for (let [, relative] of results) {
code += `@import "${relative}";\n`;
}
}
return {
filePath: path.join(
dir,
path.basename(specifier, path.extname(specifier)) +
'.' +
sourceAssetType,
),
code,
invalidateOnFileCreate: [{glob: normalized}],
pipeline: null,
priority: 'sync',
};
},
}): Resolver);
function set(obj, path, value) {
for (let i = 0; i < path.length - 1; i++) {
let part = path[i];
if (obj[part] == null) {
obj[part] = {};
}
obj = obj[part];
}
obj[path[path.length - 1]] = value;
}
function generate(matches, isAsync, indent = '', count = 0) {
if (typeof matches === 'string') {
if (isAsync) {
return {
imports: '',
value: `() => import(${JSON.stringify(matches)})`,
count,
};
}
let key = `_temp${count++}`;
return {
imports: `const ${key} = require(${JSON.stringify(matches)});`,
value: key,
count,
};
}
let imports = '';
let res = indent + '{';
let first = true;
for (let key in matches) {
if (!first) {
res += ',';
}
let {
imports: i,
value,
count: c,
} = generate(matches[key], isAsync, indent + ' ', count);
imports += `${i}\n`;
count = c;
res += `\n${indent} ${JSON.stringify(key)}: ${value}`;
first = false;
}
res += '\n' + indent + '}';
return {imports, value: res, count};
}