AliasUtils.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const forEachBail = require("./forEachBail");
  7. const { PathType, getType } = require("./util/path");
  8. /** @typedef {import("./Resolver")} Resolver */
  9. /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
  10. /** @typedef {import("./Resolver").ResolveContext} ResolveContext */
  11. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  12. /** @typedef {import("./Resolver").ResolveCallback} ResolveCallback */
  13. /** @typedef {string | string[] | false} Alias */
  14. /** @typedef {{ alias: Alias, name: string, onlyModule?: boolean }} AliasOption */
  15. /**
  16. * @typedef {object} CompiledAliasOption
  17. * @property {string} name original alias name
  18. * @property {string} nameWithSlash name + "/" — precomputed to avoid per-resolve concat
  19. * @property {Alias} alias alias target(s)
  20. * @property {boolean} onlyModule normalized onlyModule flag
  21. * @property {string | null} absolutePath absolute form of `name` (with slash ending), null when not absolute
  22. * @property {string | null} wildcardPrefix substring before the single "*" in `name`, null when no wildcard
  23. * @property {string | null} wildcardSuffix substring after the single "*" in `name`, null when no wildcard
  24. * @property {number} firstCharCode first character code of `name` — used as a cheap screen on the hot path. `-1` indicates "matches any first char" (empty wildcard prefix).
  25. * @property {boolean} arrayAlias true when `alias` is an array — precomputed so the hot path skips `Array.isArray`
  26. */
  27. const EMPTY_COMPILED_OPTIONS = /** @type {CompiledAliasOption[]} */ ([]);
  28. /**
  29. * Precompute per-option strings used on every resolve so the hot path in
  30. * `aliasResolveHandler` does no string concatenation / split work per entry.
  31. * Called once per plugin apply — the returned array is stable for the
  32. * lifetime of the resolver.
  33. * @param {Resolver} resolver resolver
  34. * @param {AliasOption[]} options options
  35. * @returns {CompiledAliasOption[]} compiled options
  36. */
  37. function compileAliasOptions(resolver, options) {
  38. if (options.length === 0) return EMPTY_COMPILED_OPTIONS;
  39. const result = Array.from({ length: options.length });
  40. for (let i = 0; i < options.length; i++) {
  41. const item = options[i];
  42. const { name } = item;
  43. let absolutePath = null;
  44. const type = getType(name);
  45. if (type === PathType.AbsolutePosix || type === PathType.AbsoluteWin) {
  46. absolutePath = resolver.join(name, "_").slice(0, -1);
  47. }
  48. const firstStar = name.indexOf("*");
  49. let wildcardPrefix = null;
  50. let wildcardSuffix = null;
  51. if (firstStar !== -1 && !name.includes("*", firstStar + 1)) {
  52. wildcardPrefix = name.slice(0, firstStar);
  53. wildcardSuffix = name.slice(firstStar + 1);
  54. }
  55. // firstCharCode: used by `aliasResolveHandler` to quickly skip aliases
  56. // whose name can't possibly match the current innerRequest. For a plain
  57. // alias (no wildcard) the first char of the name is also the first char
  58. // of `nameWithSlash` and of `absolutePath` (since the latter is derived
  59. // from name via `resolver.join(name, "_")`, which only appends). For a
  60. // wildcard with a non-empty prefix, the first char of that prefix is
  61. // also the first char of name. Only the `name === "*"` case (empty
  62. // wildcard prefix) can match arbitrary first chars — encode that as -1.
  63. let firstCharCode;
  64. if (wildcardPrefix !== null && wildcardPrefix.length === 0) {
  65. firstCharCode = -1;
  66. } else {
  67. firstCharCode = name.length > 0 ? name.charCodeAt(0) : -1;
  68. }
  69. result[i] = {
  70. name,
  71. nameWithSlash: `${name}/`,
  72. alias: item.alias,
  73. onlyModule: Boolean(item.onlyModule),
  74. absolutePath,
  75. wildcardPrefix,
  76. wildcardSuffix,
  77. firstCharCode,
  78. arrayAlias: Array.isArray(item.alias),
  79. };
  80. }
  81. return result;
  82. }
  83. /** @typedef {(err?: null | Error, result?: null | ResolveRequest) => void} InnerCallback */
  84. /**
  85. * @param {Resolver} resolver resolver
  86. * @param {CompiledAliasOption[]} options compiled options
  87. * @param {ResolveStepHook} target target
  88. * @param {ResolveRequest} request request
  89. * @param {ResolveContext} resolveContext resolve context
  90. * @param {InnerCallback} callback callback
  91. * @returns {void}
  92. */
  93. function aliasResolveHandler(
  94. resolver,
  95. options,
  96. target,
  97. request,
  98. resolveContext,
  99. callback,
  100. ) {
  101. if (options.length === 0) return callback();
  102. const innerRequest = request.request || request.path;
  103. if (!innerRequest) return callback();
  104. // Precompute values used in the inner scan loop so we don't recompute
  105. // them per option. This is meaningful when `options` has hundreds of
  106. // entries (e.g. monorepos with generated alias lists) — see the
  107. // `huge-alias-list` / `huge-alias-miss` benchmarks.
  108. const innerFirstCharCode = innerRequest.charCodeAt(0);
  109. const hasRequestString = Boolean(request.request);
  110. forEachBail(
  111. options,
  112. (item, callback) => {
  113. // Cheap char-code screen: when the compiled option's first char
  114. // doesn't match the request's first char (and it isn't an
  115. // "empty-prefix wildcard" — encoded as -1), this option cannot
  116. // possibly match, so skip straight away and avoid the
  117. // `startsWith` / `===` work below.
  118. const { firstCharCode } = item;
  119. if (firstCharCode !== -1 && firstCharCode !== innerFirstCharCode) {
  120. return callback();
  121. }
  122. /** @type {boolean} */
  123. let shouldStop = false;
  124. // For absolute-name aliases, accept the normalized
  125. // `absolutePath` form as well as the raw `nameWithSlash`.
  126. // `nameWithSlash` unconditionally appends `/`, so a raw
  127. // windows request with native backslashes
  128. // (e.g. `C:\\abs\\foo\\baz` against `name: "C:\\abs\\foo"`)
  129. // otherwise fails `startsWith("C:\\abs\\foo/")` and is
  130. // silently skipped. Mirroring the `absolutePath` check in
  131. // both branches closes the gap without changing any
  132. // existing matches.
  133. const { absolutePath } = item;
  134. const matchRequest =
  135. innerRequest === item.name ||
  136. (!item.onlyModule &&
  137. ((hasRequestString && innerRequest.startsWith(item.nameWithSlash)) ||
  138. (absolutePath !== null && innerRequest.startsWith(absolutePath))));
  139. const matchWildcard = !item.onlyModule && item.wildcardPrefix !== null;
  140. if (matchRequest || matchWildcard) {
  141. /**
  142. * @param {Alias} alias alias
  143. * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback
  144. * @returns {void}
  145. */
  146. const resolveWithAlias = (alias, callback) => {
  147. if (alias === false) {
  148. /** @type {ResolveRequest} */
  149. const ignoreObj = {
  150. ...request,
  151. path: false,
  152. };
  153. if (typeof resolveContext.yield === "function") {
  154. resolveContext.yield(ignoreObj);
  155. return callback(null, null);
  156. }
  157. return callback(null, ignoreObj);
  158. }
  159. let newRequestStr;
  160. if (
  161. matchWildcard &&
  162. innerRequest.startsWith(
  163. /** @type {string} */ (item.wildcardPrefix),
  164. ) &&
  165. innerRequest.endsWith(/** @type {string} */ (item.wildcardSuffix))
  166. ) {
  167. const match = innerRequest.slice(
  168. /** @type {string} */ (item.wildcardPrefix).length,
  169. innerRequest.length -
  170. /** @type {string} */ (item.wildcardSuffix).length,
  171. );
  172. newRequestStr = alias.toString().replace("*", match);
  173. }
  174. if (
  175. matchRequest &&
  176. innerRequest !== alias &&
  177. !innerRequest.startsWith(`${alias}/`)
  178. ) {
  179. /** @type {string} */
  180. const remainingRequest = innerRequest.slice(item.name.length);
  181. newRequestStr = alias + remainingRequest;
  182. }
  183. if (newRequestStr !== undefined) {
  184. shouldStop = true;
  185. /** @type {ResolveRequest} */
  186. const obj = {
  187. ...request,
  188. request: newRequestStr,
  189. fullySpecified: false,
  190. };
  191. return resolver.doResolve(
  192. target,
  193. obj,
  194. `aliased with mapping '${item.name}': '${alias}' to '${newRequestStr}'`,
  195. resolveContext,
  196. (err, result) => {
  197. if (err) return callback(err);
  198. if (result) return callback(null, result);
  199. return callback();
  200. },
  201. );
  202. }
  203. return callback();
  204. };
  205. /**
  206. * @param {(null | Error)=} err error
  207. * @param {(null | ResolveRequest)=} result result
  208. * @returns {void}
  209. */
  210. const stoppingCallback = (err, result) => {
  211. if (err) return callback(err);
  212. if (result) return callback(null, result);
  213. // Don't allow other aliasing or raw request
  214. if (shouldStop) return callback(null, null);
  215. return callback();
  216. };
  217. if (item.arrayAlias) {
  218. return forEachBail(
  219. /** @type {string[]} */ (item.alias),
  220. resolveWithAlias,
  221. stoppingCallback,
  222. );
  223. }
  224. return resolveWithAlias(item.alias, stoppingCallback);
  225. }
  226. return callback();
  227. },
  228. callback,
  229. );
  230. }
  231. module.exports.aliasResolveHandler = aliasResolveHandler;
  232. module.exports.compileAliasOptions = compileAliasOptions;