source: frontend/node_modules/@rollup/plugin-node-resolve/dist/es/index.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 29.8 KB
Line 
1import path, { dirname, resolve, extname, normalize, sep } from 'path';
2import builtinList from 'builtin-modules';
3import deepMerge from 'deepmerge';
4import isModule from 'is-module';
5import fs, { realpathSync } from 'fs';
6import { promisify } from 'util';
7import { pathToFileURL, fileURLToPath } from 'url';
8import resolve$1 from 'resolve';
9import { createFilter } from '@rollup/pluginutils';
10
11const access = promisify(fs.access);
12const readFile = promisify(fs.readFile);
13const realpath = promisify(fs.realpath);
14const stat = promisify(fs.stat);
15async function exists(filePath) {
16 try {
17 await access(filePath);
18 return true;
19 } catch {
20 return false;
21 }
22}
23
24const onError = (error) => {
25 if (error.code === 'ENOENT') {
26 return false;
27 }
28 throw error;
29};
30
31const makeCache = (fn) => {
32 const cache = new Map();
33 const wrapped = async (param, done) => {
34 if (cache.has(param) === false) {
35 cache.set(
36 param,
37 fn(param).catch((err) => {
38 cache.delete(param);
39 throw err;
40 })
41 );
42 }
43
44 try {
45 const result = cache.get(param);
46 const value = await result;
47 return done(null, value);
48 } catch (error) {
49 return done(error);
50 }
51 };
52
53 wrapped.clear = () => cache.clear();
54
55 return wrapped;
56};
57
58const isDirCached = makeCache(async (file) => {
59 try {
60 const stats = await stat(file);
61 return stats.isDirectory();
62 } catch (error) {
63 return onError(error);
64 }
65});
66
67const isFileCached = makeCache(async (file) => {
68 try {
69 const stats = await stat(file);
70 return stats.isFile();
71 } catch (error) {
72 return onError(error);
73 }
74});
75
76const readCachedFile = makeCache(readFile);
77
78// returns the imported package name for bare module imports
79function getPackageName(id) {
80 if (id.startsWith('.') || id.startsWith('/')) {
81 return null;
82 }
83
84 const split = id.split('/');
85
86 // @my-scope/my-package/foo.js -> @my-scope/my-package
87 // @my-scope/my-package -> @my-scope/my-package
88 if (split[0][0] === '@') {
89 return `${split[0]}/${split[1]}`;
90 }
91
92 // my-package/foo.js -> my-package
93 // my-package -> my-package
94 return split[0];
95}
96
97function getMainFields(options) {
98 let mainFields;
99 if (options.mainFields) {
100 ({ mainFields } = options);
101 } else {
102 mainFields = ['module', 'main'];
103 }
104 if (options.browser && mainFields.indexOf('browser') === -1) {
105 return ['browser'].concat(mainFields);
106 }
107 if (!mainFields.length) {
108 throw new Error('Please ensure at least one `mainFields` value is specified');
109 }
110 return mainFields;
111}
112
113function getPackageInfo(options) {
114 const {
115 cache,
116 extensions,
117 pkg,
118 mainFields,
119 preserveSymlinks,
120 useBrowserOverrides,
121 rootDir,
122 ignoreSideEffectsForRoot
123 } = options;
124 let { pkgPath } = options;
125
126 if (cache.has(pkgPath)) {
127 return cache.get(pkgPath);
128 }
129
130 // browserify/resolve doesn't realpath paths returned in its packageFilter callback
131 if (!preserveSymlinks) {
132 pkgPath = realpathSync(pkgPath);
133 }
134
135 const pkgRoot = dirname(pkgPath);
136
137 const packageInfo = {
138 // copy as we are about to munge the `main` field of `pkg`.
139 packageJson: { ...pkg },
140
141 // path to package.json file
142 packageJsonPath: pkgPath,
143
144 // directory containing the package.json
145 root: pkgRoot,
146
147 // which main field was used during resolution of this module (main, module, or browser)
148 resolvedMainField: 'main',
149
150 // whether the browser map was used to resolve the entry point to this module
151 browserMappedMain: false,
152
153 // the entry point of the module with respect to the selected main field and any
154 // relevant browser mappings.
155 resolvedEntryPoint: ''
156 };
157
158 let overriddenMain = false;
159 for (let i = 0; i < mainFields.length; i++) {
160 const field = mainFields[i];
161 if (typeof pkg[field] === 'string') {
162 pkg.main = pkg[field];
163 packageInfo.resolvedMainField = field;
164 overriddenMain = true;
165 break;
166 }
167 }
168
169 const internalPackageInfo = {
170 cachedPkg: pkg,
171 hasModuleSideEffects: () => null,
172 hasPackageEntry: overriddenMain !== false || mainFields.indexOf('main') !== -1,
173 packageBrowserField:
174 useBrowserOverrides &&
175 typeof pkg.browser === 'object' &&
176 Object.keys(pkg.browser).reduce((browser, key) => {
177 let resolved = pkg.browser[key];
178 if (resolved && resolved[0] === '.') {
179 resolved = resolve(pkgRoot, resolved);
180 }
181 /* eslint-disable no-param-reassign */
182 browser[key] = resolved;
183 if (key[0] === '.') {
184 const absoluteKey = resolve(pkgRoot, key);
185 browser[absoluteKey] = resolved;
186 if (!extname(key)) {
187 extensions.reduce((subBrowser, ext) => {
188 subBrowser[absoluteKey + ext] = subBrowser[key];
189 return subBrowser;
190 }, browser);
191 }
192 }
193 return browser;
194 }, {}),
195 packageInfo
196 };
197
198 const browserMap = internalPackageInfo.packageBrowserField;
199 if (
200 useBrowserOverrides &&
201 typeof pkg.browser === 'object' &&
202 // eslint-disable-next-line no-prototype-builtins
203 browserMap.hasOwnProperty(pkg.main)
204 ) {
205 packageInfo.resolvedEntryPoint = browserMap[pkg.main];
206 packageInfo.browserMappedMain = true;
207 } else {
208 // index.node is technically a valid default entrypoint as well...
209 packageInfo.resolvedEntryPoint = resolve(pkgRoot, pkg.main || 'index.js');
210 packageInfo.browserMappedMain = false;
211 }
212
213 if (!ignoreSideEffectsForRoot || rootDir !== pkgRoot) {
214 const packageSideEffects = pkg.sideEffects;
215 if (typeof packageSideEffects === 'boolean') {
216 internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
217 } else if (Array.isArray(packageSideEffects)) {
218 internalPackageInfo.hasModuleSideEffects = createFilter(packageSideEffects, null, {
219 resolve: pkgRoot
220 });
221 }
222 }
223
224 cache.set(pkgPath, internalPackageInfo);
225 return internalPackageInfo;
226}
227
228function normalizeInput(input) {
229 if (Array.isArray(input)) {
230 return input;
231 } else if (typeof input === 'object') {
232 return Object.values(input);
233 }
234
235 // otherwise it's a string
236 return [input];
237}
238
239/* eslint-disable no-await-in-loop */
240
241const fileExists = promisify(fs.exists);
242
243function isModuleDir(current, moduleDirs) {
244 return moduleDirs.some((dir) => current.endsWith(dir));
245}
246
247async function findPackageJson(base, moduleDirs) {
248 const { root } = path.parse(base);
249 let current = base;
250
251 while (current !== root && !isModuleDir(current, moduleDirs)) {
252 const pkgJsonPath = path.join(current, 'package.json');
253 if (await fileExists(pkgJsonPath)) {
254 const pkgJsonString = fs.readFileSync(pkgJsonPath, 'utf-8');
255 return { pkgJson: JSON.parse(pkgJsonString), pkgPath: current, pkgJsonPath };
256 }
257 current = path.resolve(current, '..');
258 }
259 return null;
260}
261
262function isUrl(str) {
263 try {
264 return !!new URL(str);
265 } catch (_) {
266 return false;
267 }
268}
269
270function isConditions(exports) {
271 return typeof exports === 'object' && Object.keys(exports).every((k) => !k.startsWith('.'));
272}
273
274function isMappings(exports) {
275 return typeof exports === 'object' && !isConditions(exports);
276}
277
278function isMixedExports(exports) {
279 const keys = Object.keys(exports);
280 return keys.some((k) => k.startsWith('.')) && keys.some((k) => !k.startsWith('.'));
281}
282
283function createBaseErrorMsg(importSpecifier, importer) {
284 return `Could not resolve import "${importSpecifier}" in ${importer}`;
285}
286
287function createErrorMsg(context, reason, internal) {
288 const { importSpecifier, importer, pkgJsonPath } = context;
289 const base = createBaseErrorMsg(importSpecifier, importer);
290 const field = internal ? 'imports' : 'exports';
291 return `${base} using ${field} defined in ${pkgJsonPath}.${reason ? ` ${reason}` : ''}`;
292}
293
294class ResolveError extends Error {}
295
296class InvalidConfigurationError extends ResolveError {
297 constructor(context, reason) {
298 super(createErrorMsg(context, `Invalid "exports" field. ${reason}`));
299 }
300}
301
302class InvalidModuleSpecifierError extends ResolveError {
303 constructor(context, internal) {
304 super(createErrorMsg(context, internal));
305 }
306}
307
308class InvalidPackageTargetError extends ResolveError {
309 constructor(context, reason) {
310 super(createErrorMsg(context, reason));
311 }
312}
313
314/* eslint-disable no-await-in-loop, no-undefined */
315
316function includesInvalidSegments(pathSegments, moduleDirs) {
317 return pathSegments
318 .split('/')
319 .slice(1)
320 .some((t) => ['.', '..', ...moduleDirs].includes(t));
321}
322
323async function resolvePackageTarget(context, { target, subpath, pattern, internal }) {
324 if (typeof target === 'string') {
325 if (!pattern && subpath.length > 0 && !target.endsWith('/')) {
326 throw new InvalidModuleSpecifierError(context);
327 }
328
329 if (!target.startsWith('./')) {
330 if (internal && !['/', '../'].some((p) => target.startsWith(p)) && !isUrl(target)) {
331 // this is a bare package import, remap it and resolve it using regular node resolve
332 if (pattern) {
333 const result = await context.resolveId(
334 target.replace(/\*/g, subpath),
335 context.pkgURL.href
336 );
337 return result ? pathToFileURL(result.location) : null;
338 }
339
340 const result = await context.resolveId(`${target}${subpath}`, context.pkgURL.href);
341 return result ? pathToFileURL(result.location) : null;
342 }
343 throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`);
344 }
345
346 if (includesInvalidSegments(target, context.moduleDirs)) {
347 throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`);
348 }
349
350 const resolvedTarget = new URL(target, context.pkgURL);
351 if (!resolvedTarget.href.startsWith(context.pkgURL.href)) {
352 throw new InvalidPackageTargetError(
353 context,
354 `Resolved to ${resolvedTarget.href} which is outside package ${context.pkgURL.href}`
355 );
356 }
357
358 if (includesInvalidSegments(subpath, context.moduleDirs)) {
359 throw new InvalidModuleSpecifierError(context);
360 }
361
362 if (pattern) {
363 return resolvedTarget.href.replace(/\*/g, subpath);
364 }
365 return new URL(subpath, resolvedTarget).href;
366 }
367
368 if (Array.isArray(target)) {
369 let lastError;
370 for (const item of target) {
371 try {
372 const resolved = await resolvePackageTarget(context, {
373 target: item,
374 subpath,
375 pattern,
376 internal
377 });
378
379 // return if defined or null, but not undefined
380 if (resolved !== undefined) {
381 return resolved;
382 }
383 } catch (error) {
384 if (!(error instanceof InvalidPackageTargetError)) {
385 throw error;
386 } else {
387 lastError = error;
388 }
389 }
390 }
391
392 if (lastError) {
393 throw lastError;
394 }
395 return null;
396 }
397
398 if (target && typeof target === 'object') {
399 for (const [key, value] of Object.entries(target)) {
400 if (key === 'default' || context.conditions.includes(key)) {
401 const resolved = await resolvePackageTarget(context, {
402 target: value,
403 subpath,
404 pattern,
405 internal
406 });
407
408 // return if defined or null, but not undefined
409 if (resolved !== undefined) {
410 return resolved;
411 }
412 }
413 }
414 return undefined;
415 }
416
417 if (target === null) {
418 return null;
419 }
420
421 throw new InvalidPackageTargetError(context, `Invalid exports field.`);
422}
423
424/* eslint-disable no-await-in-loop */
425
426async function resolvePackageImportsExports(context, { matchKey, matchObj, internal }) {
427 if (!matchKey.endsWith('*') && matchKey in matchObj) {
428 const target = matchObj[matchKey];
429 const resolved = await resolvePackageTarget(context, { target, subpath: '', internal });
430 return resolved;
431 }
432
433 const expansionKeys = Object.keys(matchObj)
434 .filter((k) => k.endsWith('/') || k.endsWith('*'))
435 .sort((a, b) => b.length - a.length);
436
437 for (const expansionKey of expansionKeys) {
438 const prefix = expansionKey.substring(0, expansionKey.length - 1);
439
440 if (expansionKey.endsWith('*') && matchKey.startsWith(prefix)) {
441 const target = matchObj[expansionKey];
442 const subpath = matchKey.substring(expansionKey.length - 1);
443 const resolved = await resolvePackageTarget(context, {
444 target,
445 subpath,
446 pattern: true,
447 internal
448 });
449 return resolved;
450 }
451
452 if (matchKey.startsWith(expansionKey)) {
453 const target = matchObj[expansionKey];
454 const subpath = matchKey.substring(expansionKey.length);
455
456 const resolved = await resolvePackageTarget(context, { target, subpath, internal });
457 return resolved;
458 }
459 }
460
461 throw new InvalidModuleSpecifierError(context, internal);
462}
463
464async function resolvePackageExports(context, subpath, exports) {
465 if (isMixedExports(exports)) {
466 throw new InvalidConfigurationError(
467 context,
468 'All keys must either start with ./, or without one.'
469 );
470 }
471
472 if (subpath === '.') {
473 let mainExport;
474 // If exports is a String or Array, or an Object containing no keys starting with ".", then
475 if (typeof exports === 'string' || Array.isArray(exports) || isConditions(exports)) {
476 mainExport = exports;
477 } else if (isMappings(exports)) {
478 mainExport = exports['.'];
479 }
480
481 if (mainExport) {
482 const resolved = await resolvePackageTarget(context, { target: mainExport, subpath: '' });
483 if (resolved) {
484 return resolved;
485 }
486 }
487 } else if (isMappings(exports)) {
488 const resolvedMatch = await resolvePackageImportsExports(context, {
489 matchKey: subpath,
490 matchObj: exports
491 });
492
493 if (resolvedMatch) {
494 return resolvedMatch;
495 }
496 }
497
498 throw new InvalidModuleSpecifierError(context);
499}
500
501async function resolvePackageImports({
502 importSpecifier,
503 importer,
504 moduleDirs,
505 conditions,
506 resolveId
507}) {
508 const result = await findPackageJson(importer, moduleDirs);
509 if (!result) {
510 throw new Error(createBaseErrorMsg('. Could not find a parent package.json.'));
511 }
512
513 const { pkgPath, pkgJsonPath, pkgJson } = result;
514 const pkgURL = pathToFileURL(`${pkgPath}/`);
515 const context = {
516 importer,
517 importSpecifier,
518 moduleDirs,
519 pkgURL,
520 pkgJsonPath,
521 conditions,
522 resolveId
523 };
524
525 const { imports } = pkgJson;
526 if (!imports) {
527 throw new InvalidModuleSpecifierError(context, true);
528 }
529
530 if (importSpecifier === '#' || importSpecifier.startsWith('#/')) {
531 throw new InvalidModuleSpecifierError(context, 'Invalid import specifier.');
532 }
533
534 return resolvePackageImportsExports(context, {
535 matchKey: importSpecifier,
536 matchObj: imports,
537 internal: true
538 });
539}
540
541const resolveImportPath = promisify(resolve$1);
542const readFile$1 = promisify(fs.readFile);
543
544async function getPackageJson(importer, pkgName, resolveOptions, moduleDirectories) {
545 if (importer) {
546 const selfPackageJsonResult = await findPackageJson(importer, moduleDirectories);
547 if (selfPackageJsonResult && selfPackageJsonResult.pkgJson.name === pkgName) {
548 // the referenced package name is the current package
549 return selfPackageJsonResult;
550 }
551 }
552
553 try {
554 const pkgJsonPath = await resolveImportPath(`${pkgName}/package.json`, resolveOptions);
555 const pkgJson = JSON.parse(await readFile$1(pkgJsonPath, 'utf-8'));
556 return { pkgJsonPath, pkgJson };
557 } catch (_) {
558 return null;
559 }
560}
561
562async function resolveId({
563 importer,
564 importSpecifier,
565 exportConditions,
566 warn,
567 packageInfoCache,
568 extensions,
569 mainFields,
570 preserveSymlinks,
571 useBrowserOverrides,
572 baseDir,
573 moduleDirectories,
574 rootDir,
575 ignoreSideEffectsForRoot
576}) {
577 let hasModuleSideEffects = () => null;
578 let hasPackageEntry = true;
579 let packageBrowserField = false;
580 let packageInfo;
581
582 const filter = (pkg, pkgPath) => {
583 const info = getPackageInfo({
584 cache: packageInfoCache,
585 extensions,
586 pkg,
587 pkgPath,
588 mainFields,
589 preserveSymlinks,
590 useBrowserOverrides,
591 rootDir,
592 ignoreSideEffectsForRoot
593 });
594
595 ({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
596
597 return info.cachedPkg;
598 };
599
600 const resolveOptions = {
601 basedir: baseDir,
602 readFile: readCachedFile,
603 isFile: isFileCached,
604 isDirectory: isDirCached,
605 extensions,
606 includeCoreModules: false,
607 moduleDirectory: moduleDirectories,
608 preserveSymlinks,
609 packageFilter: filter
610 };
611
612 let location;
613
614 const pkgName = getPackageName(importSpecifier);
615 if (importSpecifier.startsWith('#')) {
616 // this is a package internal import, resolve using package imports field
617 const resolveResult = await resolvePackageImports({
618 importSpecifier,
619 importer,
620 moduleDirs: moduleDirectories,
621 conditions: exportConditions,
622 resolveId(id, parent) {
623 return resolveId({
624 importSpecifier: id,
625 importer: parent,
626 exportConditions,
627 warn,
628 packageInfoCache,
629 extensions,
630 mainFields,
631 preserveSymlinks,
632 useBrowserOverrides,
633 baseDir,
634 moduleDirectories
635 });
636 }
637 });
638 location = fileURLToPath(resolveResult);
639 } else if (pkgName) {
640 // it's a bare import, find the package.json and resolve using package exports if available
641 const result = await getPackageJson(importer, pkgName, resolveOptions, moduleDirectories);
642
643 if (result && result.pkgJson.exports) {
644 const { pkgJson, pkgJsonPath } = result;
645 try {
646 const subpath =
647 pkgName === importSpecifier ? '.' : `.${importSpecifier.substring(pkgName.length)}`;
648 const pkgDr = pkgJsonPath.replace('package.json', '');
649 const pkgURL = pathToFileURL(pkgDr);
650
651 const context = {
652 importer,
653 importSpecifier,
654 moduleDirs: moduleDirectories,
655 pkgURL,
656 pkgJsonPath,
657 conditions: exportConditions
658 };
659 const resolvedPackageExport = await resolvePackageExports(
660 context,
661 subpath,
662 pkgJson.exports
663 );
664 location = fileURLToPath(resolvedPackageExport);
665 } catch (error) {
666 if (error instanceof ResolveError) {
667 return error;
668 }
669 throw error;
670 }
671 }
672 }
673
674 if (!location) {
675 // package has no imports or exports, use classic node resolve
676 try {
677 location = await resolveImportPath(importSpecifier, resolveOptions);
678 } catch (error) {
679 if (error.code !== 'MODULE_NOT_FOUND') {
680 throw error;
681 }
682 return null;
683 }
684 }
685
686 if (!preserveSymlinks) {
687 if (await exists(location)) {
688 location = await realpath(location);
689 }
690 }
691
692 return {
693 location,
694 hasModuleSideEffects,
695 hasPackageEntry,
696 packageBrowserField,
697 packageInfo
698 };
699}
700
701// Resolve module specifiers in order. Promise resolves to the first module that resolves
702// successfully, or the error that resulted from the last attempted module resolution.
703async function resolveImportSpecifiers({
704 importer,
705 importSpecifierList,
706 exportConditions,
707 warn,
708 packageInfoCache,
709 extensions,
710 mainFields,
711 preserveSymlinks,
712 useBrowserOverrides,
713 baseDir,
714 moduleDirectories,
715 rootDir,
716 ignoreSideEffectsForRoot
717}) {
718 let lastResolveError;
719
720 for (let i = 0; i < importSpecifierList.length; i++) {
721 // eslint-disable-next-line no-await-in-loop
722 const result = await resolveId({
723 importer,
724 importSpecifier: importSpecifierList[i],
725 exportConditions,
726 warn,
727 packageInfoCache,
728 extensions,
729 mainFields,
730 preserveSymlinks,
731 useBrowserOverrides,
732 baseDir,
733 moduleDirectories,
734 rootDir,
735 ignoreSideEffectsForRoot
736 });
737
738 if (result instanceof ResolveError) {
739 lastResolveError = result;
740 } else if (result) {
741 return result;
742 }
743 }
744
745 if (lastResolveError) {
746 // only log the last failed resolve error
747 warn(lastResolveError);
748 }
749 return null;
750}
751
752function handleDeprecatedOptions(opts) {
753 const warnings = [];
754
755 if (opts.customResolveOptions) {
756 const { customResolveOptions } = opts;
757 if (customResolveOptions.moduleDirectory) {
758 // eslint-disable-next-line no-param-reassign
759 opts.moduleDirectories = Array.isArray(customResolveOptions.moduleDirectory)
760 ? customResolveOptions.moduleDirectory
761 : [customResolveOptions.moduleDirectory];
762
763 warnings.push(
764 'node-resolve: The `customResolveOptions.moduleDirectory` option has been deprecated. Use `moduleDirectories`, which must be an array.'
765 );
766 }
767
768 if (customResolveOptions.preserveSymlinks) {
769 throw new Error(
770 'node-resolve: `customResolveOptions.preserveSymlinks` is no longer an option. We now always use the rollup `preserveSymlinks` option.'
771 );
772 }
773
774 [
775 'basedir',
776 'package',
777 'extensions',
778 'includeCoreModules',
779 'readFile',
780 'isFile',
781 'isDirectory',
782 'realpath',
783 'packageFilter',
784 'pathFilter',
785 'paths',
786 'packageIterator'
787 ].forEach((resolveOption) => {
788 if (customResolveOptions[resolveOption]) {
789 throw new Error(
790 `node-resolve: \`customResolveOptions.${resolveOption}\` is no longer an option. If you need this, please open an issue.`
791 );
792 }
793 });
794 }
795
796 return { warnings };
797}
798
799/* eslint-disable no-param-reassign, no-shadow, no-undefined */
800
801const builtins = new Set(builtinList);
802const ES6_BROWSER_EMPTY = '\0node-resolve:empty.js';
803const deepFreeze = (object) => {
804 Object.freeze(object);
805
806 for (const value of Object.values(object)) {
807 if (typeof value === 'object' && !Object.isFrozen(value)) {
808 deepFreeze(value);
809 }
810 }
811
812 return object;
813};
814
815const baseConditions = ['default', 'module'];
816const baseConditionsEsm = [...baseConditions, 'import'];
817const baseConditionsCjs = [...baseConditions, 'require'];
818const defaults = {
819 dedupe: [],
820 // It's important that .mjs is listed before .js so that Rollup will interpret npm modules
821 // which deploy both ESM .mjs and CommonJS .js files as ESM.
822 extensions: ['.mjs', '.js', '.json', '.node'],
823 resolveOnly: [],
824 moduleDirectories: ['node_modules'],
825 ignoreSideEffectsForRoot: false
826};
827const DEFAULTS = deepFreeze(deepMerge({}, defaults));
828
829function nodeResolve(opts = {}) {
830 const { warnings } = handleDeprecatedOptions(opts);
831
832 const options = { ...defaults, ...opts };
833 const { extensions, jail, moduleDirectories, ignoreSideEffectsForRoot } = options;
834 const conditionsEsm = [...baseConditionsEsm, ...(options.exportConditions || [])];
835 const conditionsCjs = [...baseConditionsCjs, ...(options.exportConditions || [])];
836 const packageInfoCache = new Map();
837 const idToPackageInfo = new Map();
838 const mainFields = getMainFields(options);
839 const useBrowserOverrides = mainFields.indexOf('browser') !== -1;
840 const isPreferBuiltinsSet = options.preferBuiltins === true || options.preferBuiltins === false;
841 const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
842 const rootDir = resolve(options.rootDir || process.cwd());
843 let { dedupe } = options;
844 let rollupOptions;
845
846 if (typeof dedupe !== 'function') {
847 dedupe = (importee) =>
848 options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
849 }
850
851 const resolveOnly = options.resolveOnly.map((pattern) => {
852 if (pattern instanceof RegExp) {
853 return pattern;
854 }
855 const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
856 return new RegExp(`^${normalized}$`);
857 });
858
859 const browserMapCache = new Map();
860 let preserveSymlinks;
861
862 return {
863 name: 'node-resolve',
864
865 buildStart(options) {
866 rollupOptions = options;
867
868 for (const warning of warnings) {
869 this.warn(warning);
870 }
871
872 ({ preserveSymlinks } = options);
873 },
874
875 generateBundle() {
876 readCachedFile.clear();
877 isFileCached.clear();
878 isDirCached.clear();
879 },
880
881 async resolveId(importee, importer, opts) {
882 if (importee === ES6_BROWSER_EMPTY) {
883 return importee;
884 }
885 // ignore IDs with null character, these belong to other plugins
886 if (/\0/.test(importee)) return null;
887
888 if (/\0/.test(importer)) {
889 importer = undefined;
890 }
891
892 // strip query params from import
893 const [importPath, params] = importee.split('?');
894 const importSuffix = `${params ? `?${params}` : ''}`;
895 importee = importPath;
896
897 const baseDir = !importer || dedupe(importee) ? rootDir : dirname(importer);
898
899 // https://github.com/defunctzombie/package-browser-field-spec
900 const browser = browserMapCache.get(importer);
901 if (useBrowserOverrides && browser) {
902 const resolvedImportee = resolve(baseDir, importee);
903 if (browser[importee] === false || browser[resolvedImportee] === false) {
904 return ES6_BROWSER_EMPTY;
905 }
906 const browserImportee =
907 browser[importee] ||
908 browser[resolvedImportee] ||
909 browser[`${resolvedImportee}.js`] ||
910 browser[`${resolvedImportee}.json`];
911 if (browserImportee) {
912 importee = browserImportee;
913 }
914 }
915
916 const parts = importee.split(/[/\\]/);
917 let id = parts.shift();
918 let isRelativeImport = false;
919
920 if (id[0] === '@' && parts.length > 0) {
921 // scoped packages
922 id += `/${parts.shift()}`;
923 } else if (id[0] === '.') {
924 // an import relative to the parent dir of the importer
925 id = resolve(baseDir, importee);
926 isRelativeImport = true;
927 }
928
929 if (
930 !isRelativeImport &&
931 resolveOnly.length &&
932 !resolveOnly.some((pattern) => pattern.test(id))
933 ) {
934 if (normalizeInput(rollupOptions.input).includes(importee)) {
935 return null;
936 }
937 return false;
938 }
939
940 const importSpecifierList = [];
941
942 if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
943 // For module graph roots (i.e. when importer is undefined), we
944 // need to handle 'path fragments` like `foo/bar` that are commonly
945 // found in rollup config files. If importee doesn't look like a
946 // relative or absolute path, we make it relative and attempt to
947 // resolve it. If we don't find anything, we try resolving it as we
948 // got it.
949 importSpecifierList.push(`./${importee}`);
950 }
951
952 const importeeIsBuiltin = builtins.has(importee);
953
954 if (importeeIsBuiltin) {
955 // The `resolve` library will not resolve packages with the same
956 // name as a node built-in module. If we're resolving something
957 // that's a builtin, and we don't prefer to find built-ins, we
958 // first try to look up a local module with that name. If we don't
959 // find anything, we resolve the builtin which just returns back
960 // the built-in's name.
961 importSpecifierList.push(`${importee}/`);
962 }
963
964 // TypeScript files may import '.js' to refer to either '.ts' or '.tsx'
965 if (importer && importee.endsWith('.js')) {
966 for (const ext of ['.ts', '.tsx']) {
967 if (importer.endsWith(ext) && extensions.includes(ext)) {
968 importSpecifierList.push(importee.replace(/.js$/, ext));
969 }
970 }
971 }
972
973 importSpecifierList.push(importee);
974
975 const warn = (...args) => this.warn(...args);
976 const isRequire =
977 opts && opts.custom && opts.custom['node-resolve'] && opts.custom['node-resolve'].isRequire;
978 const exportConditions = isRequire ? conditionsCjs : conditionsEsm;
979
980 const resolvedWithoutBuiltins = await resolveImportSpecifiers({
981 importer,
982 importSpecifierList,
983 exportConditions,
984 warn,
985 packageInfoCache,
986 extensions,
987 mainFields,
988 preserveSymlinks,
989 useBrowserOverrides,
990 baseDir,
991 moduleDirectories,
992 rootDir,
993 ignoreSideEffectsForRoot
994 });
995
996 const resolved =
997 importeeIsBuiltin && preferBuiltins
998 ? {
999 packageInfo: undefined,
1000 hasModuleSideEffects: () => null,
1001 hasPackageEntry: true,
1002 packageBrowserField: false
1003 }
1004 : resolvedWithoutBuiltins;
1005 if (!resolved) {
1006 return null;
1007 }
1008
1009 const { packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = resolved;
1010 let { location } = resolved;
1011 if (packageBrowserField) {
1012 if (Object.prototype.hasOwnProperty.call(packageBrowserField, location)) {
1013 if (!packageBrowserField[location]) {
1014 browserMapCache.set(location, packageBrowserField);
1015 return ES6_BROWSER_EMPTY;
1016 }
1017 location = packageBrowserField[location];
1018 }
1019 browserMapCache.set(location, packageBrowserField);
1020 }
1021
1022 if (hasPackageEntry && !preserveSymlinks) {
1023 const fileExists = await exists(location);
1024 if (fileExists) {
1025 location = await realpath(location);
1026 }
1027 }
1028
1029 idToPackageInfo.set(location, packageInfo);
1030
1031 if (hasPackageEntry) {
1032 if (importeeIsBuiltin && preferBuiltins) {
1033 if (!isPreferBuiltinsSet && resolvedWithoutBuiltins && resolved !== importee) {
1034 this.warn(
1035 `preferring built-in module '${importee}' over local alternative at '${resolvedWithoutBuiltins.location}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`
1036 );
1037 }
1038 return false;
1039 } else if (jail && location.indexOf(normalize(jail.trim(sep))) !== 0) {
1040 return null;
1041 }
1042 }
1043
1044 if (options.modulesOnly && (await exists(location))) {
1045 const code = await readFile(location, 'utf-8');
1046 if (isModule(code)) {
1047 return {
1048 id: `${location}${importSuffix}`,
1049 moduleSideEffects: hasModuleSideEffects(location)
1050 };
1051 }
1052 return null;
1053 }
1054 const result = {
1055 id: `${location}${importSuffix}`,
1056 moduleSideEffects: hasModuleSideEffects(location)
1057 };
1058 return result;
1059 },
1060
1061 load(importee) {
1062 if (importee === ES6_BROWSER_EMPTY) {
1063 return 'export default {};';
1064 }
1065 return null;
1066 },
1067
1068 getPackageInfoForId(id) {
1069 return idToPackageInfo.get(id);
1070 }
1071 };
1072}
1073
1074export default nodeResolve;
1075export { DEFAULTS, nodeResolve };
Note: See TracBrowser for help on using the repository browser.