UNPKG

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