1 | function matches(pattern, importee) {
|
2 | if (pattern instanceof RegExp) {
|
3 | return pattern.test(importee);
|
4 | }
|
5 | if (importee.length < pattern.length) {
|
6 | return false;
|
7 | }
|
8 | if (importee === pattern) {
|
9 | return true;
|
10 | }
|
11 |
|
12 | return importee.startsWith(pattern + '/');
|
13 | }
|
14 | function getEntries({ entries, customResolver }) {
|
15 | if (!entries) {
|
16 | return [];
|
17 | }
|
18 | const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
|
19 | if (Array.isArray(entries)) {
|
20 | return entries.map((entry) => {
|
21 | return {
|
22 | find: entry.find,
|
23 | replacement: entry.replacement,
|
24 | resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
|
25 | };
|
26 | });
|
27 | }
|
28 | return Object.entries(entries).map(([key, value]) => {
|
29 | return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions };
|
30 | });
|
31 | }
|
32 | function resolveCustomResolver(customResolver) {
|
33 | if (customResolver) {
|
34 | if (typeof customResolver === 'function') {
|
35 | return customResolver;
|
36 | }
|
37 | if (typeof customResolver.resolveId === 'function') {
|
38 | return customResolver.resolveId;
|
39 | }
|
40 | }
|
41 | return null;
|
42 | }
|
43 | function alias(options = {}) {
|
44 | const entries = getEntries(options);
|
45 | if (entries.length === 0) {
|
46 | return {
|
47 | name: 'alias',
|
48 | resolveId: () => null
|
49 | };
|
50 | }
|
51 | return {
|
52 | name: 'alias',
|
53 | async buildStart(inputOptions) {
|
54 | await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => customResolver &&
|
55 | typeof customResolver === 'object' &&
|
56 | typeof customResolver.buildStart === 'function' &&
|
57 | customResolver.buildStart.call(this, inputOptions)));
|
58 | },
|
59 | resolveId(importee, importer, resolveOptions) {
|
60 | if (!importer) {
|
61 | return null;
|
62 | }
|
63 |
|
64 | const matchedEntry = entries.find((entry) => matches(entry.find, importee));
|
65 | if (!matchedEntry) {
|
66 | return null;
|
67 | }
|
68 | const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
|
69 | if (matchedEntry.resolverFunction) {
|
70 | return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
|
71 | }
|
72 | return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => resolved || { id: updatedId });
|
73 | }
|
74 | };
|
75 | }
|
76 |
|
77 | export { alias as default };
|