UNPKG

3.03 kBJavaScriptView Raw
1'use strict';
2
3const noop = () => null;
4function matches(pattern, importee) {
5 if (pattern instanceof RegExp) {
6 return pattern.test(importee);
7 }
8 if (importee.length < pattern.length) {
9 return false;
10 }
11 if (importee === pattern) {
12 return true;
13 }
14 const importeeStartsWithKey = importee.indexOf(pattern) === 0;
15 const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/';
16 return importeeStartsWithKey && importeeHasSlashAfterKey;
17}
18function normalizeId(id) {
19 return id;
20}
21function getEntries({ entries }) {
22 if (!entries) {
23 return [];
24 }
25 if (Array.isArray(entries)) {
26 return entries;
27 }
28 return Object.entries(entries).map(([key, value]) => {
29 return { find: key, replacement: value };
30 });
31}
32function getCustomResolver({ customResolver }, options) {
33 if (typeof customResolver === 'function') {
34 return customResolver;
35 }
36 if (customResolver && typeof customResolver.resolveId === 'function') {
37 return customResolver.resolveId;
38 }
39 if (typeof options.customResolver === 'function') {
40 return options.customResolver;
41 }
42 if (options.customResolver && typeof options.customResolver.resolveId === 'function') {
43 return options.customResolver.resolveId;
44 }
45 return null;
46}
47function alias(options = {}) {
48 const entries = getEntries(options);
49 if (entries.length === 0) {
50 return {
51 name: 'alias',
52 resolveId: noop
53 };
54 }
55 return {
56 name: 'alias',
57 buildStart(inputOptions) {
58 return Promise.all([...entries, options].map(({ customResolver }) => customResolver &&
59 typeof customResolver === 'object' &&
60 typeof customResolver.buildStart === 'function' &&
61 customResolver.buildStart.call(this, inputOptions))).then(() => {
62 // enforce void return value
63 });
64 },
65 resolveId(importee, importer) {
66 const importeeId = normalizeId(importee);
67 const importerId = normalizeId(importer);
68 // First match is supposed to be the correct one
69 const matchedEntry = entries.find((entry) => matches(entry.find, importeeId));
70 if (!matchedEntry || !importerId) {
71 return null;
72 }
73 const updatedId = normalizeId(importeeId.replace(matchedEntry.find, matchedEntry.replacement));
74 const customResolver = getCustomResolver(matchedEntry, options);
75 if (customResolver) {
76 return customResolver.call(this, updatedId, importerId, {});
77 }
78 return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => {
79 let finalResult = resolved;
80 if (!finalResult) {
81 finalResult = { id: updatedId };
82 }
83 return finalResult;
84 });
85 }
86 };
87}
88
89module.exports = alias;