| 1 | import * as path from "path";
|
|---|
| 2 |
|
|---|
| 3 | export interface MappingEntry {
|
|---|
| 4 | readonly pattern: string;
|
|---|
| 5 | readonly paths: ReadonlyArray<string>;
|
|---|
| 6 | }
|
|---|
| 7 |
|
|---|
| 8 | export interface Paths {
|
|---|
| 9 | readonly [key: string]: ReadonlyArray<string>;
|
|---|
| 10 | }
|
|---|
| 11 |
|
|---|
| 12 | /**
|
|---|
| 13 | * Converts an absolute baseUrl and paths to an array of absolute mapping entries.
|
|---|
| 14 | * The array is sorted by longest prefix.
|
|---|
| 15 | * Having an array with entries allows us to keep a sorting order rather than
|
|---|
| 16 | * sort by keys each time we use the mappings.
|
|---|
| 17 | * @param absoluteBaseUrl
|
|---|
| 18 | * @param paths
|
|---|
| 19 | * @param addMatchAll
|
|---|
| 20 | */
|
|---|
| 21 | export function getAbsoluteMappingEntries(
|
|---|
| 22 | absoluteBaseUrl: string,
|
|---|
| 23 | paths: Paths,
|
|---|
| 24 | addMatchAll: boolean
|
|---|
| 25 | ): ReadonlyArray<MappingEntry> {
|
|---|
| 26 | // Resolve all paths to absolute form once here, and sort them by
|
|---|
| 27 | // longest prefix once here, this saves time on each request later.
|
|---|
| 28 | // We need to put them in an array to preserve the sorting order.
|
|---|
| 29 | const sortedKeys = sortByLongestPrefix(Object.keys(paths));
|
|---|
| 30 | const absolutePaths: Array<MappingEntry> = [];
|
|---|
| 31 | for (const key of sortedKeys) {
|
|---|
| 32 | absolutePaths.push({
|
|---|
| 33 | pattern: key,
|
|---|
| 34 | paths: paths[key].map((pathToResolve) =>
|
|---|
| 35 | path.join(absoluteBaseUrl, pathToResolve)
|
|---|
| 36 | ),
|
|---|
| 37 | });
|
|---|
| 38 | }
|
|---|
| 39 | // If there is no match-all path specified in the paths section of tsconfig, then try to match
|
|---|
| 40 | // all paths relative to baseUrl, this is how typescript works.
|
|---|
| 41 | if (!paths["*"] && addMatchAll) {
|
|---|
| 42 | absolutePaths.push({
|
|---|
| 43 | pattern: "*",
|
|---|
| 44 | paths: [`${absoluteBaseUrl.replace(/\/$/, "")}/*`],
|
|---|
| 45 | });
|
|---|
| 46 | }
|
|---|
| 47 |
|
|---|
| 48 | return absolutePaths;
|
|---|
| 49 | }
|
|---|
| 50 |
|
|---|
| 51 | /**
|
|---|
| 52 | * Sort path patterns.
|
|---|
| 53 | * If a module name can be matched with multiple patterns then pattern with the longest prefix will be picked.
|
|---|
| 54 | */
|
|---|
| 55 | function sortByLongestPrefix(arr: Array<string>): Array<string> {
|
|---|
| 56 | return arr
|
|---|
| 57 | .concat()
|
|---|
| 58 | .sort((a: string, b: string) => getPrefixLength(b) - getPrefixLength(a));
|
|---|
| 59 | }
|
|---|
| 60 |
|
|---|
| 61 | function getPrefixLength(pattern: string): number {
|
|---|
| 62 | const prefixLength = pattern.indexOf("*");
|
|---|
| 63 | return pattern.substr(0, prefixLength).length;
|
|---|
| 64 | }
|
|---|