ExportsFieldPlugin.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const DescriptionFileUtils = require("./DescriptionFileUtils");
  7. const forEachBail = require("./forEachBail");
  8. const { processExportsField } = require("./util/entrypoints");
  9. const { parseIdentifier } = require("./util/identifier");
  10. const {
  11. deprecatedInvalidSegmentRegEx,
  12. invalidSegmentRegEx,
  13. } = require("./util/path");
  14. /** @typedef {import("./Resolver")} Resolver */
  15. /** @typedef {import("./Resolver").JsonObject} JsonObject */
  16. /** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */
  17. /** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */
  18. /** @typedef {import("./util/entrypoints").ExportsField} ExportsField */
  19. /** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */
  20. module.exports = class ExportsFieldPlugin {
  21. /**
  22. * @param {string | ResolveStepHook} source source
  23. * @param {Set<string>} conditionNames condition names
  24. * @param {string | string[]} fieldNamePath name path
  25. * @param {string | ResolveStepHook} target target
  26. * @param {boolean=} restrictions whether `restrictions` are configured (enables exports-target fallback when a target is filtered out)
  27. */
  28. constructor(source, conditionNames, fieldNamePath, target, restrictions) {
  29. this.source = source;
  30. this.target = target;
  31. this.conditionNames = conditionNames;
  32. this.fieldName = fieldNamePath;
  33. this.restrictions = Boolean(restrictions);
  34. // `null` is cached for description files that have no exports field,
  35. // so subsequent resolves against the same package.json skip the
  36. // `DescriptionFileUtils.getField` walk entirely.
  37. /** @type {WeakMap<JsonObject, FieldProcessor | null>} */
  38. this._fieldProcessorCache = new WeakMap();
  39. }
  40. /**
  41. * @param {Resolver} resolver the resolver
  42. * @returns {void}
  43. */
  44. apply(resolver) {
  45. const target = resolver.ensureHook(this.target);
  46. resolver
  47. .getHook(this.source)
  48. .tapAsync("ExportsFieldPlugin", (request, resolveContext, callback) => {
  49. // When there is no description file, abort
  50. if (!request.descriptionFileData) return callback();
  51. if (
  52. // When the description file is inherited from parent, abort
  53. // (There is no description file inside of this package)
  54. request.relativePath !== "." ||
  55. request.request === undefined
  56. ) {
  57. return callback();
  58. }
  59. const { descriptionFileData } = request;
  60. const remainingRequest =
  61. request.query || request.fragment
  62. ? (request.request === "." ? "./" : request.request) +
  63. request.query +
  64. request.fragment
  65. : request.request;
  66. /** @type {string[]} */
  67. let paths;
  68. /** @type {string | null} */
  69. let usedField;
  70. try {
  71. // Look up the cached processor first. On a cache hit we
  72. // avoid re-walking the description file for the exports
  73. // field — and `null` is cached for description files that
  74. // have no exports field at all, so those skip the read
  75. // entirely. `processExportsField` can throw on a malformed
  76. // `exports` map (e.g. a key without a leading `.`), so
  77. // building the processor must stay inside this try/catch.
  78. let fieldProcessor =
  79. this._fieldProcessorCache.get(descriptionFileData);
  80. if (
  81. fieldProcessor === undefined &&
  82. !this._fieldProcessorCache.has(descriptionFileData)
  83. ) {
  84. const exportsField =
  85. /** @type {ExportsField | null | undefined} */
  86. (
  87. DescriptionFileUtils.getField(
  88. descriptionFileData,
  89. this.fieldName,
  90. )
  91. );
  92. fieldProcessor = exportsField
  93. ? processExportsField(exportsField)
  94. : null;
  95. this._fieldProcessorCache.set(descriptionFileData, fieldProcessor);
  96. }
  97. if (!fieldProcessor) return callback();
  98. if (request.directory) {
  99. return callback(
  100. new Error(
  101. `Resolving to directories is not possible with the exports field (request was ${remainingRequest}/)`,
  102. ),
  103. );
  104. }
  105. [paths, usedField] = fieldProcessor(
  106. remainingRequest,
  107. this.conditionNames,
  108. );
  109. } catch (/** @type {unknown} */ err) {
  110. if (resolveContext.log) {
  111. resolveContext.log(
  112. `Exports field in ${request.descriptionFilePath} can't be processed: ${err}`,
  113. );
  114. }
  115. return callback(/** @type {Error} */ (err));
  116. }
  117. if (paths.length === 0) {
  118. const conditions = [...this.conditionNames];
  119. const conditionsStr =
  120. conditions.length === 1
  121. ? `the condition "${conditions[0]}"`
  122. : `the conditions ${JSON.stringify(conditions)}`;
  123. return callback(
  124. new Error(
  125. `"${remainingRequest}" is not exported under ${conditionsStr} from package ${request.descriptionFileRoot} (see exports field in ${request.descriptionFilePath})`,
  126. ),
  127. );
  128. }
  129. // When `restrictions` are configured, share a marker down the
  130. // chain so RestrictionsPlugin can tell us it filtered out an
  131. // otherwise-valid target — then we fall back instead of erroring.
  132. const restrictionsMarker = this.restrictions
  133. ? { blocked: false }
  134. : undefined;
  135. forEachBail(
  136. paths,
  137. /**
  138. * @param {string} path path
  139. * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback
  140. * @param {number} i index
  141. * @returns {void}
  142. */
  143. (path, callback, i) => {
  144. const parsedIdentifier = parseIdentifier(path);
  145. if (!parsedIdentifier) return callback();
  146. const [relativePath, query, fragment] = parsedIdentifier;
  147. if (!relativePath.startsWith("./")) {
  148. if (paths.length === i) {
  149. return callback(
  150. new Error(
  151. `Invalid "exports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`,
  152. ),
  153. );
  154. }
  155. return callback();
  156. }
  157. const withoutDotSlash = relativePath.slice(2);
  158. if (
  159. invalidSegmentRegEx.test(withoutDotSlash) &&
  160. deprecatedInvalidSegmentRegEx.test(withoutDotSlash)
  161. ) {
  162. if (paths.length === i) {
  163. return callback(
  164. new Error(
  165. `Invalid "exports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`,
  166. ),
  167. );
  168. }
  169. return callback();
  170. }
  171. /** @type {ResolveRequest} */
  172. const obj = {
  173. ...request,
  174. request: undefined,
  175. path: resolver.join(
  176. /** @type {string} */ (request.descriptionFileRoot),
  177. relativePath,
  178. ),
  179. relativePath,
  180. query,
  181. fragment,
  182. };
  183. // Attach the marker only when restrictions are configured, so
  184. // resolves without restrictions keep their request shape and
  185. // never leak the property onto the result.
  186. if (restrictionsMarker) {
  187. obj.__restrictionsMarker = restrictionsMarker;
  188. }
  189. resolver.doResolve(
  190. target,
  191. obj,
  192. `using exports field: ${path}`,
  193. resolveContext,
  194. (err, result) => {
  195. if (err) return callback(err);
  196. // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400
  197. if (result === undefined) return callback(null, null);
  198. callback(null, result);
  199. },
  200. );
  201. },
  202. /**
  203. * @param {(null | Error)=} err error
  204. * @param {(null | ResolveRequest)=} result result
  205. * @returns {void}
  206. */
  207. (err, result) => {
  208. if (err) return callback(err);
  209. // When an exports field match was found but the target file doesn't exist,
  210. // return an error to prevent fallback to parent node_modules directories.
  211. // Per the Node.js ESM spec, a matched exports entry that fails to resolve
  212. // is a hard error, not a signal to continue searching up the directory tree.
  213. // See: https://github.com/webpack/enhanced-resolve/issues/399
  214. if (!result) {
  215. // Exception: the target existed but `restrictions` filtered it
  216. // out — return no result so the next `modules` entry is tried.
  217. if (restrictionsMarker && restrictionsMarker.blocked) {
  218. return callback(null, null);
  219. }
  220. return callback(
  221. new Error(
  222. `Package path ${remainingRequest} is exported from package ${request.descriptionFileRoot}, but no valid target file was found (see exports field in ${request.descriptionFilePath})`,
  223. ),
  224. );
  225. }
  226. // Drop the internal marker before it reaches the result.
  227. if (restrictionsMarker) delete result.__restrictionsMarker;
  228. callback(null, result);
  229. },
  230. );
  231. });
  232. }
  233. };