2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Ivan Kopeykin @vankop
8 /** @typedef {string|(string|ConditionalMapping)[]} DirectMapping */
9 /** @typedef {{[k: string]: MappingValue}} ConditionalMapping */
10 /** @typedef {ConditionalMapping|DirectMapping|null} MappingValue */
11 /** @typedef {Record<string, MappingValue>|ConditionalMapping|DirectMapping} ExportsField */
12 /** @typedef {Record<string, MappingValue>} ImportsField */
15 * @typedef {Object} PathTreeNode
16 * @property {Map<string, PathTreeNode>|null} children
17 * @property {MappingValue} folder
18 * @property {Map<string, MappingValue>|null} wildcards
19 * @property {Map<string, MappingValue>} files
23 * Processing exports/imports field
24 * @callback FieldProcessor
25 * @param {string} request request
26 * @param {Set<string>} conditionNames condition names
27 * @returns {string[]} resolved paths
31 Example exports field:
35 "browser": "./feature-browser.js",
36 "default": "./feature.js"
41 Enhanced-resolve name keys ("." and "./feature") as exports field keys.
43 If value is string or string[], mapping is called as a direct mapping
44 and value called as a direct export.
46 If value is key-value object, mapping is called as a conditional mapping
47 and value called as a conditional export.
49 Key in conditional mapping is called condition name.
51 Conditional mapping nested in another conditional mapping is called nested mapping.
55 Example imports field:
59 "browser": "./moment/index.js",
63 "browser": "./moment/",
69 Enhanced-resolve name keys ("#a" and "#moment/", "#moment") as imports field keys.
71 If value is string or string[], mapping is called as a direct mapping
72 and value called as a direct export.
74 If value is key-value object, mapping is called as a conditional mapping
75 and value called as a conditional export.
77 Key in conditional mapping is called condition name.
79 Conditional mapping nested in another conditional mapping is called nested mapping.
83 const slashCode = "/".charCodeAt(0);
84 const dotCode = ".".charCodeAt(0);
85 const hashCode = "#".charCodeAt(0);
88 * @param {ExportsField} exportsField the exports field
89 * @returns {FieldProcessor} process callback
91 module.exports.processExportsField = function processExportsField(
94 return createFieldProcessor(
95 buildExportsFieldPathTree(exportsField),
96 assertExportsFieldRequest,
102 * @param {ImportsField} importsField the exports field
103 * @returns {FieldProcessor} process callback
105 module.exports.processImportsField = function processImportsField(
108 return createFieldProcessor(
109 buildImportsFieldPathTree(importsField),
110 assertImportsFieldRequest,
116 * @param {PathTreeNode} treeRoot root
117 * @param {(s: string) => string} assertRequest assertRequest
118 * @param {(s: string, f: boolean) => void} assertTarget assertTarget
119 * @returns {FieldProcessor} field processor
121 function createFieldProcessor(treeRoot, assertRequest, assertTarget) {
122 return function fieldProcessor(request, conditionNames) {
123 request = assertRequest(request);
125 const match = findMatch(request, treeRoot);
127 if (match === null) return [];
129 const [mapping, remainRequestIndex] = match;
131 /** @type {DirectMapping|null} */
134 if (isConditionalMapping(mapping)) {
135 direct = conditionalMapping(
136 /** @type {ConditionalMapping} */ (mapping),
140 // matching not found
141 if (direct === null) return [];
143 direct = /** @type {DirectMapping} */ (mapping);
146 const remainingRequest =
147 remainRequestIndex === request.length + 1
149 : remainRequestIndex < 0
150 ? request.slice(-remainRequestIndex - 1)
151 : request.slice(remainRequestIndex);
153 return directMapping(
155 remainRequestIndex < 0,
164 * @param {string} request request
165 * @returns {string} updated request
167 function assertExportsFieldRequest(request) {
168 if (request.charCodeAt(0) !== dotCode) {
169 throw new Error('Request should be relative path and start with "."');
171 if (request.length === 1) return "";
172 if (request.charCodeAt(1) !== slashCode) {
173 throw new Error('Request should be relative path and start with "./"');
175 if (request.charCodeAt(request.length - 1) === slashCode) {
176 throw new Error("Only requesting file allowed");
179 return request.slice(2);
183 * @param {string} request request
184 * @returns {string} updated request
186 function assertImportsFieldRequest(request) {
187 if (request.charCodeAt(0) !== hashCode) {
188 throw new Error('Request should start with "#"');
190 if (request.length === 1) {
191 throw new Error("Request should have at least 2 characters");
193 if (request.charCodeAt(1) === slashCode) {
194 throw new Error('Request should not start with "#/"');
196 if (request.charCodeAt(request.length - 1) === slashCode) {
197 throw new Error("Only requesting file allowed");
200 return request.slice(1);
204 * @param {string} exp export target
205 * @param {boolean} expectFolder is folder expected
207 function assertExportTarget(exp, expectFolder) {
209 exp.charCodeAt(0) === slashCode ||
210 (exp.charCodeAt(0) === dotCode && exp.charCodeAt(1) !== slashCode)
213 `Export should be relative path and start with "./", got ${JSON.stringify(
219 const isFolder = exp.charCodeAt(exp.length - 1) === slashCode;
221 if (isFolder !== expectFolder) {
224 ? `Expecting folder to folder mapping. ${JSON.stringify(
226 )} should end with "/"`
227 : `Expecting file to file mapping. ${JSON.stringify(
229 )} should not end with "/"`
235 * @param {string} imp import target
236 * @param {boolean} expectFolder is folder expected
238 function assertImportTarget(imp, expectFolder) {
239 const isFolder = imp.charCodeAt(imp.length - 1) === slashCode;
241 if (isFolder !== expectFolder) {
244 ? `Expecting folder to folder mapping. ${JSON.stringify(
246 )} should end with "/"`
247 : `Expecting file to file mapping. ${JSON.stringify(
249 )} should not end with "/"`
255 * Trying to match request to field
256 * @param {string} request request
257 * @param {PathTreeNode} treeRoot path tree root
258 * @returns {[MappingValue, number]|null} match or null, number is negative and one less when it's a folder mapping, number is request.length + 1 for direct mappings
260 function findMatch(request, treeRoot) {
261 if (request.length === 0) {
262 const value = treeRoot.files.get("");
264 return value ? [value, 1] : null;
268 treeRoot.children === null &&
269 treeRoot.folder === null &&
270 treeRoot.wildcards === null
272 const value = treeRoot.files.get(request);
274 return value ? [value, request.length + 1] : null;
278 let lastNonSlashIndex = 0;
279 let slashIndex = request.indexOf("/", 0);
281 /** @type {[MappingValue, number]|null} */
282 let lastFolderMatch = null;
284 const applyFolderMapping = () => {
285 const folderMapping = node.folder;
287 if (lastFolderMatch) {
288 lastFolderMatch[0] = folderMapping;
289 lastFolderMatch[1] = -lastNonSlashIndex - 1;
291 lastFolderMatch = [folderMapping, -lastNonSlashIndex - 1];
296 const applyWildcardMappings = (wildcardMappings, remainingRequest) => {
297 if (wildcardMappings) {
298 for (const [key, target] of wildcardMappings) {
299 if (remainingRequest.startsWith(key)) {
300 if (!lastFolderMatch) {
301 lastFolderMatch = [target, lastNonSlashIndex + key.length];
302 } else if (lastFolderMatch[1] < lastNonSlashIndex + key.length) {
303 lastFolderMatch[0] = target;
304 lastFolderMatch[1] = lastNonSlashIndex + key.length;
311 while (slashIndex !== -1) {
312 applyFolderMapping();
314 const wildcardMappings = node.wildcards;
316 if (!wildcardMappings && node.children === null) return lastFolderMatch;
318 const folder = request.slice(lastNonSlashIndex, slashIndex);
320 applyWildcardMappings(wildcardMappings, folder);
322 if (node.children === null) return lastFolderMatch;
324 const newNode = node.children.get(folder);
327 return lastFolderMatch;
331 lastNonSlashIndex = slashIndex + 1;
332 slashIndex = request.indexOf("/", lastNonSlashIndex);
335 const remainingRequest =
336 lastNonSlashIndex > 0 ? request.slice(lastNonSlashIndex) : request;
338 const value = node.files.get(remainingRequest);
341 return [value, request.length + 1];
344 applyFolderMapping();
346 applyWildcardMappings(node.wildcards, remainingRequest);
348 return lastFolderMatch;
352 * @param {ConditionalMapping|DirectMapping|null} mapping mapping
353 * @returns {boolean} is conditional mapping
355 function isConditionalMapping(mapping) {
357 mapping !== null && typeof mapping === "object" && !Array.isArray(mapping)
362 * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings
363 * @param {boolean} subpathMapping true, for subpath mappings
364 * @param {DirectMapping|null} mappingTarget direct export
365 * @param {Set<string>} conditionNames condition names
366 * @param {(d: string, f: boolean) => void} assert asserting direct value
367 * @returns {string[]} mapping result
369 function directMapping(
376 if (mappingTarget === null) return [];
378 if (typeof mappingTarget === "string") {
380 targetMapping(remainingRequest, subpathMapping, mappingTarget, assert)
386 for (const exp of mappingTarget) {
387 if (typeof exp === "string") {
389 targetMapping(remainingRequest, subpathMapping, exp, assert)
394 const mapping = conditionalMapping(exp, conditionNames);
395 if (!mapping) continue;
396 const innerExports = directMapping(
403 for (const innerExport of innerExports) {
404 targets.push(innerExport);
412 * @param {string|undefined} remainingRequest remaining request when folder mapping, undefined for file mappings
413 * @param {boolean} subpathMapping true, for subpath mappings
414 * @param {string} mappingTarget direct export
415 * @param {(d: string, f: boolean) => void} assert asserting direct value
416 * @returns {string} mapping result
418 function targetMapping(
424 if (remainingRequest === undefined) {
425 assert(mappingTarget, false);
426 return mappingTarget;
428 if (subpathMapping) {
429 assert(mappingTarget, true);
430 return mappingTarget + remainingRequest;
432 assert(mappingTarget, false);
433 return mappingTarget.replace(/\*/g, remainingRequest.replace(/\$/g, "$$"));
437 * @param {ConditionalMapping} conditionalMapping_ conditional mapping
438 * @param {Set<string>} conditionNames condition names
439 * @returns {DirectMapping|null} direct mapping if found
441 function conditionalMapping(conditionalMapping_, conditionNames) {
442 /** @type {[ConditionalMapping, string[], number][]} */
443 let lookup = [[conditionalMapping_, Object.keys(conditionalMapping_), 0]];
445 loop: while (lookup.length > 0) {
446 const [mapping, conditions, j] = lookup[lookup.length - 1];
447 const last = conditions.length - 1;
449 for (let i = j; i < conditions.length; i++) {
450 const condition = conditions[i];
452 // assert default. Could be last only
454 if (condition === "default") {
455 throw new Error("Default condition should be last one");
457 } else if (condition === "default") {
458 const innerMapping = mapping[condition];
460 if (isConditionalMapping(innerMapping)) {
461 const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping);
462 lookup[lookup.length - 1][2] = i + 1;
463 lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]);
467 return /** @type {DirectMapping} */ (innerMapping);
470 if (conditionNames.has(condition)) {
471 const innerMapping = mapping[condition];
473 if (isConditionalMapping(innerMapping)) {
474 const conditionalMapping = /** @type {ConditionalMapping} */ (innerMapping);
475 lookup[lookup.length - 1][2] = i + 1;
476 lookup.push([conditionalMapping, Object.keys(conditionalMapping), 0]);
480 return /** @type {DirectMapping} */ (innerMapping);
491 * Internal helper to create path tree node
492 * to ensure that each node gets the same hidden class
493 * @returns {PathTreeNode} node
495 function createNode() {
505 * Internal helper for building path tree
506 * @param {PathTreeNode} root root
507 * @param {string} path path
508 * @param {MappingValue} target target
510 function walkPath(root, path, target) {
511 if (path.length === 0) {
512 root.folder = target;
517 // Typical path tree can looks like
519 // - files: ["a.js", "b.js"]
522 // - files: ["a.js", "b.js"]
523 let lastNonSlashIndex = 0;
524 let slashIndex = path.indexOf("/", 0);
526 while (slashIndex !== -1) {
527 const folder = path.slice(lastNonSlashIndex, slashIndex);
530 if (node.children === null) {
531 newNode = createNode();
532 node.children = new Map();
533 node.children.set(folder, newNode);
535 newNode = node.children.get(folder);
538 newNode = createNode();
539 node.children.set(folder, newNode);
544 lastNonSlashIndex = slashIndex + 1;
545 slashIndex = path.indexOf("/", lastNonSlashIndex);
548 if (lastNonSlashIndex >= path.length) {
549 node.folder = target;
551 const file = lastNonSlashIndex > 0 ? path.slice(lastNonSlashIndex) : path;
552 if (file.endsWith("*")) {
553 if (node.wildcards === null) node.wildcards = new Map();
554 node.wildcards.set(file.slice(0, -1), target);
556 node.files.set(file, target);
562 * @param {ExportsField} field exports field
563 * @returns {PathTreeNode} tree root
565 function buildExportsFieldPathTree(field) {
566 const root = createNode();
568 // handle syntax sugar, if exports field is direct mapping for "."
569 if (typeof field === "string") {
570 root.files.set("", field);
573 } else if (Array.isArray(field)) {
574 root.files.set("", field.slice());
579 const keys = Object.keys(field);
581 for (let i = 0; i < keys.length; i++) {
584 if (key.charCodeAt(0) !== dotCode) {
585 // handle syntax sugar, if exports field is conditional mapping for "."
587 while (i < keys.length) {
588 const charCode = keys[i].charCodeAt(0);
589 if (charCode === dotCode || charCode === slashCode) {
591 `Exports field key should be relative path and start with "." (key: ${JSON.stringify(
599 root.files.set("", field);
604 `Exports field key should be relative path and start with "." (key: ${JSON.stringify(
610 if (key.length === 1) {
611 root.files.set("", field[key]);
615 if (key.charCodeAt(1) !== slashCode) {
617 `Exports field key should be relative path and start with "./" (key: ${JSON.stringify(
623 walkPath(root, key.slice(2), field[key]);
630 * @param {ImportsField} field imports field
631 * @returns {PathTreeNode} root
633 function buildImportsFieldPathTree(field) {
634 const root = createNode();
636 const keys = Object.keys(field);
638 for (let i = 0; i < keys.length; i++) {
641 if (key.charCodeAt(0) !== hashCode) {
643 `Imports field key should start with "#" (key: ${JSON.stringify(key)})`
647 if (key.length === 1) {
649 `Imports field key should have at least 2 characters (key: ${JSON.stringify(
655 if (key.charCodeAt(1) === slashCode) {
657 `Imports field key should not start with "#/" (key: ${JSON.stringify(
663 walkPath(root, key.slice(1), field[key]);