UNPKG

9.9 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright Google LLC All Rights Reserved.
5 *
6 * Use of this source code is governed by an MIT-style license that can be
7 * found in the LICENSE file at https://angular.io/license
8 */
9var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10 if (k2 === undefined) k2 = k;
11 var desc = Object.getOwnPropertyDescriptor(m, k);
12 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13 desc = { enumerable: true, get: function() { return m[k]; } };
14 }
15 Object.defineProperty(o, k2, desc);
16}) : (function(o, m, k, k2) {
17 if (k2 === undefined) k2 = k;
18 o[k2] = m[k];
19}));
20var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21 Object.defineProperty(o, "default", { enumerable: true, value: v });
22}) : function(o, v) {
23 o["default"] = v;
24});
25var __importStar = (this && this.__importStar) || function (mod) {
26 if (mod && mod.__esModule) return mod;
27 var result = {};
28 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
29 __setModuleDefault(result, mod);
30 return result;
31};
32Object.defineProperty(exports, "__esModule", { value: true });
33exports.TypeScriptPathsPlugin = void 0;
34const path = __importStar(require("path"));
35class TypeScriptPathsPlugin {
36 baseUrl;
37 patterns;
38 constructor(options) {
39 if (options) {
40 this.update(options);
41 }
42 }
43 /**
44 * Update the plugin with new path mapping option values.
45 * The options will also be preprocessed to reduce the overhead of individual resolve actions
46 * during a build.
47 *
48 * @param options The `paths` and `baseUrl` options from TypeScript's `CompilerOptions`.
49 */
50 update(options) {
51 this.baseUrl = options.baseUrl;
52 this.patterns = undefined;
53 if (options.paths) {
54 for (const [pattern, potentials] of Object.entries(options.paths)) {
55 // Ignore any entries that would not result in a new mapping
56 if (potentials.length === 0 || potentials.every((potential) => potential === '*')) {
57 continue;
58 }
59 const starIndex = pattern.indexOf('*');
60 let prefix = pattern;
61 let suffix;
62 if (starIndex > -1) {
63 prefix = pattern.slice(0, starIndex);
64 if (starIndex < pattern.length - 1) {
65 suffix = pattern.slice(starIndex + 1);
66 }
67 }
68 this.patterns ??= [];
69 this.patterns.push({
70 starIndex,
71 prefix,
72 suffix,
73 potentials: potentials.map((potential) => {
74 const potentialStarIndex = potential.indexOf('*');
75 if (potentialStarIndex === -1) {
76 return { hasStar: false, prefix: potential };
77 }
78 return {
79 hasStar: true,
80 prefix: potential.slice(0, potentialStarIndex),
81 suffix: potentialStarIndex < potential.length - 1
82 ? potential.slice(potentialStarIndex + 1)
83 : undefined,
84 };
85 }),
86 });
87 }
88 // Sort patterns so that exact matches take priority then largest prefix match
89 this.patterns?.sort((a, b) => {
90 if (a.starIndex === -1) {
91 return -1;
92 }
93 else if (b.starIndex === -1) {
94 return 1;
95 }
96 else {
97 return b.starIndex - a.starIndex;
98 }
99 });
100 }
101 }
102 apply(resolver) {
103 const target = resolver.ensureHook('resolve');
104 // To support synchronous resolvers this hook cannot be promise based.
105 // Webpack supports synchronous resolution with `tap` and `tapAsync` hooks.
106 resolver
107 .getHook('described-resolve')
108 .tapAsync('TypeScriptPathsPlugin', (request, resolveContext, callback) => {
109 // Preprocessing of the options will ensure that `patterns` is either undefined or has elements to check
110 if (!this.patterns) {
111 callback();
112 return;
113 }
114 if (!request || request.typescriptPathMapped) {
115 callback();
116 return;
117 }
118 const originalRequest = request.request || request.path;
119 if (!originalRequest) {
120 callback();
121 return;
122 }
123 // Only work on Javascript/TypeScript issuers.
124 if (!request?.context?.issuer?.match(/\.[cm]?[jt]sx?$/)) {
125 callback();
126 return;
127 }
128 // Absolute requests are not mapped
129 if (path.isAbsolute(originalRequest)) {
130 callback();
131 return;
132 }
133 switch (originalRequest[0]) {
134 case '.':
135 // Relative requests are not mapped
136 callback();
137 return;
138 case '!':
139 // Ignore all webpack special requests
140 if (originalRequest.length > 1 && originalRequest[1] === '!') {
141 callback();
142 return;
143 }
144 break;
145 }
146 // A generator is used to limit the amount of replacements requests that need to be created.
147 // For example, if the first one resolves, any others are not needed and do not need
148 // to be created.
149 const requests = this.createReplacementRequests(request, originalRequest);
150 const tryResolve = () => {
151 const next = requests.next();
152 if (next.done) {
153 callback();
154 return;
155 }
156 resolver.doResolve(target, next.value, '', resolveContext, (error, result) => {
157 if (error) {
158 callback(error);
159 }
160 else if (result) {
161 callback(undefined, result);
162 }
163 else {
164 tryResolve();
165 }
166 });
167 };
168 tryResolve();
169 });
170 }
171 *findReplacements(originalRequest) {
172 if (!this.patterns) {
173 return;
174 }
175 // check if any path mapping rules are relevant
176 for (const { starIndex, prefix, suffix, potentials } of this.patterns) {
177 let partial;
178 if (starIndex === -1) {
179 // No star means an exact match is required
180 if (prefix === originalRequest) {
181 partial = '';
182 }
183 }
184 else if (starIndex === 0 && !suffix) {
185 // Everything matches a single wildcard pattern ("*")
186 partial = originalRequest;
187 }
188 else if (!suffix) {
189 // No suffix means the star is at the end of the pattern
190 if (originalRequest.startsWith(prefix)) {
191 partial = originalRequest.slice(prefix.length);
192 }
193 }
194 else {
195 // Star was in the middle of the pattern
196 if (originalRequest.startsWith(prefix) && originalRequest.endsWith(suffix)) {
197 partial = originalRequest.substring(prefix.length, originalRequest.length - suffix.length);
198 }
199 }
200 // If request was not matched, move on to the next pattern
201 if (partial === undefined) {
202 continue;
203 }
204 // Create the full replacement values based on the original request and the potentials
205 // for the successfully matched pattern.
206 for (const { hasStar, prefix, suffix } of potentials) {
207 let replacement = prefix;
208 if (hasStar) {
209 replacement += partial;
210 if (suffix) {
211 replacement += suffix;
212 }
213 }
214 yield replacement;
215 }
216 }
217 }
218 *createReplacementRequests(request, originalRequest) {
219 for (const replacement of this.findReplacements(originalRequest)) {
220 const targetPath = path.resolve(this.baseUrl ?? '', replacement);
221 // Resolution in the original callee location, but with the updated request
222 // to point to the mapped target location.
223 yield {
224 ...request,
225 request: targetPath,
226 typescriptPathMapped: true,
227 };
228 // If there is no extension. i.e. the target does not refer to an explicit
229 // file, then this is a candidate for module/package resolution.
230 const canBeModule = path.extname(targetPath) === '';
231 if (canBeModule) {
232 // Resolution in the target location, preserving the original request.
233 // This will work with the `resolve-in-package` resolution hook, supporting
234 // package exports for e.g. locally-built APF libraries.
235 yield {
236 ...request,
237 path: targetPath,
238 typescriptPathMapped: true,
239 };
240 }
241 }
242 }
243}
244exports.TypeScriptPathsPlugin = TypeScriptPathsPlugin;