You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

@rollup/plugin-node-resolve

Package Overview
Dependencies
Maintainers
4
Versions
52
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@rollup/plugin-node-resolve - npm Package Compare versions

Comparing version
9.0.0
to
15.0.2
+960
-222
dist/cjs/index.js

@@ -5,19 +5,35 @@ 'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var path = require('path');
var builtinList = _interopDefault(require('builtin-modules'));
var deepMerge = _interopDefault(require('deepmerge'));
var isModule = _interopDefault(require('is-module'));
var isBuiltinModule = require('is-builtin-module');
var deepMerge = require('deepmerge');
var isModule = require('is-module');
var fs = require('fs');
var fs__default = _interopDefault(fs);
var util = require('util');
var url = require('url');
var resolve = require('resolve');
var pluginutils = require('@rollup/pluginutils');
var resolveModule = _interopDefault(require('resolve'));
const exists = util.promisify(fs__default.exists);
const readFile = util.promisify(fs__default.readFile);
const realpath = util.promisify(fs__default.realpath);
const stat = util.promisify(fs__default.stat);
var version = "15.0.2";
var peerDependencies = {
rollup: "^2.78.0||^3.0.0"
};
util.promisify(fs.access);
const readFile$1 = util.promisify(fs.readFile);
const realpath = util.promisify(fs.realpath);
const stat = util.promisify(fs.stat);
async function fileExists(filePath) {
try {
const res = await stat(filePath);
return res.isFile();
} catch {
return false;
}
}
async function resolveSymlink(path) {
return (await fileExists(path)) ? realpath(path) : path;
}
const onError = (error) => {

@@ -75,6 +91,51 @@ if (error.code === 'ENOENT') {

const readCachedFile = makeCache(readFile);
const readCachedFile = makeCache(readFile$1);
const resolveId = util.promisify(resolveModule);
function handleDeprecatedOptions(opts) {
const warnings = [];
if (opts.customResolveOptions) {
const { customResolveOptions } = opts;
if (customResolveOptions.moduleDirectory) {
// eslint-disable-next-line no-param-reassign
opts.moduleDirectories = Array.isArray(customResolveOptions.moduleDirectory)
? customResolveOptions.moduleDirectory
: [customResolveOptions.moduleDirectory];
warnings.push(
'node-resolve: The `customResolveOptions.moduleDirectory` option has been deprecated. Use `moduleDirectories`, which must be an array.'
);
}
if (customResolveOptions.preserveSymlinks) {
throw new Error(
'node-resolve: `customResolveOptions.preserveSymlinks` is no longer an option. We now always use the rollup `preserveSymlinks` option.'
);
}
[
'basedir',
'package',
'extensions',
'includeCoreModules',
'readFile',
'isFile',
'isDirectory',
'realpath',
'packageFilter',
'pathFilter',
'paths',
'packageIterator'
].forEach((resolveOption) => {
if (customResolveOptions[resolveOption]) {
throw new Error(
`node-resolve: \`customResolveOptions.${resolveOption}\` is no longer an option. If you need this, please open an issue.`
);
}
});
}
return { warnings };
}
// returns the imported package name for bare module imports

@@ -116,3 +177,12 @@ function getPackageName(id) {

function getPackageInfo(options) {
const { cache, extensions, pkg, mainFields, preserveSymlinks, useBrowserOverrides } = options;
const {
cache,
extensions,
pkg,
mainFields,
preserveSymlinks,
useBrowserOverrides,
rootDir,
ignoreSideEffectsForRoot
} = options;
let { pkgPath } = options;

@@ -133,3 +203,3 @@

// copy as we are about to munge the `main` field of `pkg`.
packageJson: Object.assign({}, pkg),
packageJson: { ...pkg },

@@ -208,9 +278,21 @@ // path to package.json file

const packageSideEffects = pkg.sideEffects;
if (typeof packageSideEffects === 'boolean') {
internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
} else if (Array.isArray(packageSideEffects)) {
internalPackageInfo.hasModuleSideEffects = pluginutils.createFilter(packageSideEffects, null, {
resolve: pkgRoot
});
if (!ignoreSideEffectsForRoot || rootDir !== pkgRoot) {
const packageSideEffects = pkg.sideEffects;
if (typeof packageSideEffects === 'boolean') {
internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
} else if (Array.isArray(packageSideEffects)) {
const finalPackageSideEffects = packageSideEffects.map((sideEffect) => {
/*
* The array accepts simple glob patterns to the relevant files... Patterns like .css, which do not include a /, will be treated like **\/.css.
* https://webpack.js.org/guides/tree-shaking/
*/
if (sideEffect.includes('/')) {
return sideEffect;
}
return `**/${sideEffect}`;
});
internalPackageInfo.hasModuleSideEffects = pluginutils.createFilter(finalPackageSideEffects, null, {
resolve: pkgRoot
});
}
}

@@ -233,40 +315,654 @@

// Resolve module specifiers in order. Promise resolves to the first module that resolves
// successfully, or the error that resulted from the last attempted module resolution.
function resolveImportSpecifiers(importSpecifierList, resolveOptions) {
let promise = Promise.resolve();
/* eslint-disable no-await-in-loop */
for (let i = 0; i < importSpecifierList.length; i++) {
promise = promise.then((value) => {
// if we've already resolved to something, just return it.
if (value) {
return value;
function isModuleDir(current, moduleDirs) {
return moduleDirs.some((dir) => current.endsWith(dir));
}
async function findPackageJson(base, moduleDirs) {
const { root } = path.parse(base);
let current = base;
while (current !== root && !isModuleDir(current, moduleDirs)) {
const pkgJsonPath = path.join(current, 'package.json');
if (await fileExists(pkgJsonPath)) {
const pkgJsonString = fs.readFileSync(pkgJsonPath, 'utf-8');
return { pkgJson: JSON.parse(pkgJsonString), pkgPath: current, pkgJsonPath };
}
current = path.resolve(current, '..');
}
return null;
}
function isUrl(str) {
try {
return !!new URL(str);
} catch (_) {
return false;
}
}
function isConditions(exports) {
return typeof exports === 'object' && Object.keys(exports).every((k) => !k.startsWith('.'));
}
function isMappings(exports) {
return typeof exports === 'object' && !isConditions(exports);
}
function isMixedExports(exports) {
const keys = Object.keys(exports);
return keys.some((k) => k.startsWith('.')) && keys.some((k) => !k.startsWith('.'));
}
function createBaseErrorMsg(importSpecifier, importer) {
return `Could not resolve import "${importSpecifier}" in ${importer}`;
}
function createErrorMsg(context, reason, internal) {
const { importSpecifier, importer, pkgJsonPath } = context;
const base = createBaseErrorMsg(importSpecifier, importer);
const field = internal ? 'imports' : 'exports';
return `${base} using ${field} defined in ${pkgJsonPath}.${reason ? ` ${reason}` : ''}`;
}
class ResolveError extends Error {}
class InvalidConfigurationError extends ResolveError {
constructor(context, reason) {
super(createErrorMsg(context, `Invalid "exports" field. ${reason}`));
}
}
class InvalidModuleSpecifierError extends ResolveError {
constructor(context, internal, reason) {
super(createErrorMsg(context, reason, internal));
}
}
class InvalidPackageTargetError extends ResolveError {
constructor(context, reason) {
super(createErrorMsg(context, reason));
}
}
/* eslint-disable no-await-in-loop, no-undefined */
function includesInvalidSegments(pathSegments, moduleDirs) {
return pathSegments
.split('/')
.slice(1)
.some((t) => ['.', '..', ...moduleDirs].includes(t));
}
async function resolvePackageTarget(context, { target, subpath, pattern, internal }) {
if (typeof target === 'string') {
if (!pattern && subpath.length > 0 && !target.endsWith('/')) {
throw new InvalidModuleSpecifierError(context);
}
if (!target.startsWith('./')) {
if (internal && !['/', '../'].some((p) => target.startsWith(p)) && !isUrl(target)) {
// this is a bare package import, remap it and resolve it using regular node resolve
if (pattern) {
const result = await context.resolveId(
target.replace(/\*/g, subpath),
context.pkgURL.href
);
return result ? url.pathToFileURL(result.location).href : null;
}
const result = await context.resolveId(`${target}${subpath}`, context.pkgURL.href);
return result ? url.pathToFileURL(result.location).href : null;
}
throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`);
}
return resolveId(importSpecifierList[i], resolveOptions).then((result) => {
if (!resolveOptions.preserveSymlinks) {
result = fs.realpathSync(result);
if (includesInvalidSegments(target, context.moduleDirs)) {
throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`);
}
const resolvedTarget = new URL(target, context.pkgURL);
if (!resolvedTarget.href.startsWith(context.pkgURL.href)) {
throw new InvalidPackageTargetError(
context,
`Resolved to ${resolvedTarget.href} which is outside package ${context.pkgURL.href}`
);
}
if (includesInvalidSegments(subpath, context.moduleDirs)) {
throw new InvalidModuleSpecifierError(context);
}
if (pattern) {
return resolvedTarget.href.replace(/\*/g, subpath);
}
return new URL(subpath, resolvedTarget).href;
}
if (Array.isArray(target)) {
let lastError;
for (const item of target) {
try {
const resolved = await resolvePackageTarget(context, {
target: item,
subpath,
pattern,
internal
});
// return if defined or null, but not undefined
if (resolved !== undefined) {
return resolved;
}
return result;
} catch (error) {
if (!(error instanceof InvalidPackageTargetError)) {
throw error;
} else {
lastError = error;
}
}
}
if (lastError) {
throw lastError;
}
return null;
}
if (target && typeof target === 'object') {
for (const [key, value] of Object.entries(target)) {
if (key === 'default' || context.conditions.includes(key)) {
const resolved = await resolvePackageTarget(context, {
target: value,
subpath,
pattern,
internal
});
// return if defined or null, but not undefined
if (resolved !== undefined) {
return resolved;
}
}
}
return undefined;
}
if (target === null) {
return null;
}
throw new InvalidPackageTargetError(context, `Invalid exports field.`);
}
/* eslint-disable no-await-in-loop */
async function resolvePackageImportsExports(context, { matchKey, matchObj, internal }) {
if (!matchKey.endsWith('*') && matchKey in matchObj) {
const target = matchObj[matchKey];
const resolved = await resolvePackageTarget(context, { target, subpath: '', internal });
return resolved;
}
const expansionKeys = Object.keys(matchObj)
.filter((k) => k.endsWith('/') || k.endsWith('*'))
.sort((a, b) => b.length - a.length);
for (const expansionKey of expansionKeys) {
const prefix = expansionKey.substring(0, expansionKey.length - 1);
if (expansionKey.endsWith('*') && matchKey.startsWith(prefix)) {
const target = matchObj[expansionKey];
const subpath = matchKey.substring(expansionKey.length - 1);
const resolved = await resolvePackageTarget(context, {
target,
subpath,
pattern: true,
internal
});
return resolved;
}
if (matchKey.startsWith(expansionKey)) {
const target = matchObj[expansionKey];
const subpath = matchKey.substring(expansionKey.length);
const resolved = await resolvePackageTarget(context, { target, subpath, internal });
return resolved;
}
}
throw new InvalidModuleSpecifierError(context, internal);
}
async function resolvePackageExports(context, subpath, exports) {
if (isMixedExports(exports)) {
throw new InvalidConfigurationError(
context,
'All keys must either start with ./, or without one.'
);
}
if (subpath === '.') {
let mainExport;
// If exports is a String or Array, or an Object containing no keys starting with ".", then
if (typeof exports === 'string' || Array.isArray(exports) || isConditions(exports)) {
mainExport = exports;
} else if (isMappings(exports)) {
mainExport = exports['.'];
}
if (mainExport) {
const resolved = await resolvePackageTarget(context, { target: mainExport, subpath: '' });
if (resolved) {
return resolved;
}
}
} else if (isMappings(exports)) {
const resolvedMatch = await resolvePackageImportsExports(context, {
matchKey: subpath,
matchObj: exports
});
if (i < importSpecifierList.length - 1) {
// swallow MODULE_NOT_FOUND errors from all but the last resolution
promise = promise.catch((error) => {
if (error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
if (resolvedMatch) {
return resolvedMatch;
}
}
throw new InvalidModuleSpecifierError(context);
}
async function resolvePackageImports({
importSpecifier,
importer,
moduleDirs,
conditions,
resolveId
}) {
const result = await findPackageJson(importer, moduleDirs);
if (!result) {
throw new Error(createBaseErrorMsg('. Could not find a parent package.json.'));
}
const { pkgPath, pkgJsonPath, pkgJson } = result;
const pkgURL = url.pathToFileURL(`${pkgPath}/`);
const context = {
importer,
importSpecifier,
moduleDirs,
pkgURL,
pkgJsonPath,
conditions,
resolveId
};
const { imports } = pkgJson;
if (!imports) {
throw new InvalidModuleSpecifierError(context, true);
}
if (importSpecifier === '#' || importSpecifier.startsWith('#/')) {
throw new InvalidModuleSpecifierError(context, true, 'Invalid import specifier.');
}
return resolvePackageImportsExports(context, {
matchKey: importSpecifier,
matchObj: imports,
internal: true
});
}
const resolveImportPath = util.promisify(resolve);
const readFile = util.promisify(fs.readFile);
async function getPackageJson(importer, pkgName, resolveOptions, moduleDirectories) {
if (importer) {
const selfPackageJsonResult = await findPackageJson(importer, moduleDirectories);
if (selfPackageJsonResult && selfPackageJsonResult.pkgJson.name === pkgName) {
// the referenced package name is the current package
return selfPackageJsonResult;
}
}
try {
const pkgJsonPath = await resolveImportPath(`${pkgName}/package.json`, resolveOptions);
const pkgJson = JSON.parse(await readFile(pkgJsonPath, 'utf-8'));
return { pkgJsonPath, pkgJson, pkgPath: path.dirname(pkgJsonPath) };
} catch (_) {
return null;
}
}
async function resolveIdClassic({
importSpecifier,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
}) {
let hasModuleSideEffects = () => null;
let hasPackageEntry = true;
let packageBrowserField = false;
let packageInfo;
const filter = (pkg, pkgPath) => {
const info = getPackageInfo({
cache: packageInfoCache,
extensions,
pkg,
pkgPath,
mainFields,
preserveSymlinks,
useBrowserOverrides,
rootDir,
ignoreSideEffectsForRoot
});
({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
return info.cachedPkg;
};
const resolveOptions = {
basedir: baseDir,
readFile: readCachedFile,
isFile: isFileCached,
isDirectory: isDirCached,
extensions,
includeCoreModules: false,
moduleDirectory: moduleDirectories,
paths: modulePaths,
preserveSymlinks,
packageFilter: filter
};
let location;
try {
location = await resolveImportPath(importSpecifier, resolveOptions);
} catch (error) {
if (error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
return null;
}
return {
location: preserveSymlinks ? location : await resolveSymlink(location),
hasModuleSideEffects,
hasPackageEntry,
packageBrowserField,
packageInfo
};
}
async function resolveWithExportMap({
importer,
importSpecifier,
exportConditions,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
}) {
if (importSpecifier.startsWith('#')) {
// this is a package internal import, resolve using package imports field
const resolveResult = await resolvePackageImports({
importSpecifier,
importer,
moduleDirs: moduleDirectories,
conditions: exportConditions,
resolveId(id /* , parent*/) {
return resolveIdClassic({
importSpecifier: id,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths
});
}
});
const location = url.fileURLToPath(resolveResult);
return {
location: preserveSymlinks ? location : await resolveSymlink(location),
hasModuleSideEffects: () => null,
hasPackageEntry: true,
packageBrowserField: false,
// eslint-disable-next-line no-undefined
packageInfo: undefined
};
}
const pkgName = getPackageName(importSpecifier);
if (pkgName) {
// it's a bare import, find the package.json and resolve using package exports if available
let hasModuleSideEffects = () => null;
let hasPackageEntry = true;
let packageBrowserField = false;
let packageInfo;
const filter = (pkg, pkgPath) => {
const info = getPackageInfo({
cache: packageInfoCache,
extensions,
pkg,
pkgPath,
mainFields,
preserveSymlinks,
useBrowserOverrides,
rootDir,
ignoreSideEffectsForRoot
});
({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
return info.cachedPkg;
};
const resolveOptions = {
basedir: baseDir,
readFile: readCachedFile,
isFile: isFileCached,
isDirectory: isDirCached,
extensions,
includeCoreModules: false,
moduleDirectory: moduleDirectories,
paths: modulePaths,
preserveSymlinks,
packageFilter: filter
};
const result = await getPackageJson(importer, pkgName, resolveOptions, moduleDirectories);
if (result && result.pkgJson.exports) {
const { pkgJson, pkgJsonPath } = result;
const subpath =
pkgName === importSpecifier ? '.' : `.${importSpecifier.substring(pkgName.length)}`;
const pkgDr = pkgJsonPath.replace('package.json', '');
const pkgURL = url.pathToFileURL(pkgDr);
const context = {
importer,
importSpecifier,
moduleDirs: moduleDirectories,
pkgURL,
pkgJsonPath,
conditions: exportConditions
};
const resolvedPackageExport = await resolvePackageExports(context, subpath, pkgJson.exports);
const location = url.fileURLToPath(resolvedPackageExport);
if (location) {
return {
location: preserveSymlinks ? location : await resolveSymlink(location),
hasModuleSideEffects,
hasPackageEntry,
packageBrowserField,
packageInfo
};
}
}
}
return promise;
return null;
}
async function resolveWithClassic({
importer,
importSpecifierList,
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
}) {
for (let i = 0; i < importSpecifierList.length; i++) {
// eslint-disable-next-line no-await-in-loop
const result = await resolveIdClassic({
importer,
importSpecifier: importSpecifierList[i],
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
});
if (result) {
return result;
}
}
return null;
}
// Resolves to the module if found or `null`.
// The first import specifier will first be attempted with the exports algorithm.
// If this is unsuccessful because export maps are not being used, then all of `importSpecifierList`
// will be tried with the classic resolution algorithm
async function resolveImportSpecifiers({
importer,
importSpecifierList,
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
}) {
try {
const exportMapRes = await resolveWithExportMap({
importer,
importSpecifier: importSpecifierList[0],
exportConditions,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
});
if (exportMapRes) return exportMapRes;
} catch (error) {
if (error instanceof ResolveError) {
warn(error);
return null;
}
throw error;
}
// package has no imports or exports, use classic node resolve
return resolveWithClassic({
importer,
importSpecifierList,
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
});
}
const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
function validateVersion(actualVersion, peerDependencyVersion) {
let minMajor = Infinity;
let minMinor = Infinity;
let minPatch = Infinity;
let foundVersion;
// eslint-disable-next-line no-cond-assign
while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
if (foundMajor < minMajor) {
minMajor = foundMajor;
minMinor = foundMinor;
minPatch = foundPatch;
}
}
if (!actualVersion) {
throw new Error(
`Insufficient Rollup version: "@rollup/plugin-node-resolve" requires at least rollup@${minMajor}.${minMinor}.${minPatch}.`
);
}
const [major, minor, patch] = actualVersion.split('.').map(Number);
if (
major < minMajor ||
(major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
) {
throw new Error(
`Insufficient rollup version: "@rollup/plugin-node-resolve" requires at least rollup@${minMajor}.${minMinor}.${minPatch} but found rollup@${actualVersion}.`
);
}
}
/* eslint-disable no-param-reassign, no-shadow, no-undefined */
const builtins = new Set(builtinList);
const ES6_BROWSER_EMPTY = '\0node-resolve:empty.js';
const nullFn = () => null;
const deepFreeze = (object) => {

@@ -283,4 +979,7 @@ Object.freeze(object);

};
const baseConditions = ['default', 'module'];
const baseConditionsEsm = [...baseConditions, 'import'];
const baseConditionsCjs = [...baseConditions, 'require'];
const defaults = {
customResolveOptions: {},
dedupe: [],

@@ -290,3 +989,5 @@ // It's important that .mjs is listed before .js so that Rollup will interpret npm modules

extensions: ['.mjs', '.js', '.json', '.node'],
resolveOnly: []
resolveOnly: [],
moduleDirectories: ['node_modules'],
ignoreSideEffectsForRoot: false
};

@@ -296,5 +997,8 @@ const DEFAULTS = deepFreeze(deepMerge({}, defaults));

function nodeResolve(opts = {}) {
const options = Object.assign({}, defaults, opts);
const { customResolveOptions, extensions, jail } = options;
const warnings = [];
const { warnings } = handleDeprecatedOptions(opts);
const options = { ...defaults, ...opts };
const { extensions, jail, moduleDirectories, modulePaths, ignoreSideEffectsForRoot } = options;
const conditionsEsm = [...baseConditionsEsm, ...(options.exportConditions || [])];
const conditionsCjs = [...baseConditionsCjs, ...(options.exportConditions || [])];
const packageInfoCache = new Map();

@@ -306,9 +1010,10 @@ const idToPackageInfo = new Map();

const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
const rootDir = options.rootDir || process.cwd();
const rootDir = path.resolve(options.rootDir || process.cwd());
let { dedupe } = options;
let rollupOptions;
if (options.only) {
warnings.push('node-resolve: The `only` options is deprecated, please use `resolveOnly`');
options.resolveOnly = options.only;
if (moduleDirectories.some((name) => name.includes('/'))) {
throw new Error(
'`moduleDirectories` option must only contain directory names. If you want to load modules from somewhere not supported by the default module resolution algorithm, see `modulePaths`.'
);
}

@@ -321,213 +1026,244 @@

const resolveOnly = options.resolveOnly.map((pattern) => {
if (pattern instanceof RegExp) {
return pattern;
}
const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
return new RegExp(`^${normalized}$`);
});
// creates a function from the patterns to test if a particular module should be bundled.
const allowPatterns = (patterns) => {
const regexPatterns = patterns.map((pattern) => {
if (pattern instanceof RegExp) {
return pattern;
}
const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
return new RegExp(`^${normalized}$`);
});
return (id) => !regexPatterns.length || regexPatterns.some((pattern) => pattern.test(id));
};
const resolveOnly =
typeof options.resolveOnly === 'function'
? options.resolveOnly
: allowPatterns(options.resolveOnly);
const browserMapCache = new Map();
let preserveSymlinks;
return {
name: 'node-resolve',
const resolveLikeNode = async (context, importee, importer, custom) => {
// strip query params from import
const [importPath, params] = importee.split('?');
const importSuffix = `${params ? `?${params}` : ''}`;
importee = importPath;
buildStart(options) {
rollupOptions = options;
const baseDir = !importer || dedupe(importee) ? rootDir : path.dirname(importer);
for (const warning of warnings) {
this.warn(warning);
// https://github.com/defunctzombie/package-browser-field-spec
const browser = browserMapCache.get(importer);
if (useBrowserOverrides && browser) {
const resolvedImportee = path.resolve(baseDir, importee);
if (browser[importee] === false || browser[resolvedImportee] === false) {
return { id: ES6_BROWSER_EMPTY };
}
const browserImportee =
(importee[0] !== '.' && browser[importee]) ||
browser[resolvedImportee] ||
browser[`${resolvedImportee}.js`] ||
browser[`${resolvedImportee}.json`];
if (browserImportee) {
importee = browserImportee;
}
}
({ preserveSymlinks } = options);
},
const parts = importee.split(/[/\\]/);
let id = parts.shift();
let isRelativeImport = false;
generateBundle() {
readCachedFile.clear();
isFileCached.clear();
isDirCached.clear();
},
if (id[0] === '@' && parts.length > 0) {
// scoped packages
id += `/${parts.shift()}`;
} else if (id[0] === '.') {
// an import relative to the parent dir of the importer
id = path.resolve(baseDir, importee);
isRelativeImport = true;
}
async resolveId(importee, importer) {
if (importee === ES6_BROWSER_EMPTY) {
return importee;
// if it's not a relative import, and it's not requested, reject it.
if (!isRelativeImport && !resolveOnly(id)) {
if (normalizeInput(rollupOptions.input).includes(importee)) {
return null;
}
// ignore IDs with null character, these belong to other plugins
if (/\0/.test(importee)) return null;
return false;
}
// strip hash and query params from import
const [withoutHash, hash] = importee.split('#');
const [importPath, params] = withoutHash.split('?');
const importSuffix = `${params ? `?${params}` : ''}${hash ? `#${hash}` : ''}`;
importee = importPath;
const importSpecifierList = [importee];
const basedir = !importer || dedupe(importee) ? rootDir : path.dirname(importer);
if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
// For module graph roots (i.e. when importer is undefined), we
// need to handle 'path fragments` like `foo/bar` that are commonly
// found in rollup config files. If importee doesn't look like a
// relative or absolute path, we make it relative and attempt to
// resolve it.
importSpecifierList.push(`./${importee}`);
}
// https://github.com/defunctzombie/package-browser-field-spec
const browser = browserMapCache.get(importer);
if (useBrowserOverrides && browser) {
const resolvedImportee = path.resolve(basedir, importee);
if (browser[importee] === false || browser[resolvedImportee] === false) {
return ES6_BROWSER_EMPTY;
// TypeScript files may import '.js' to refer to either '.ts' or '.tsx'
if (importer && importee.endsWith('.js')) {
for (const ext of ['.ts', '.tsx']) {
if (importer.endsWith(ext) && extensions.includes(ext)) {
importSpecifierList.push(importee.replace(/.js$/, ext));
}
const browserImportee =
browser[importee] ||
browser[resolvedImportee] ||
browser[`${resolvedImportee}.js`] ||
browser[`${resolvedImportee}.json`];
if (browserImportee) {
importee = browserImportee;
}
}
}
const parts = importee.split(/[/\\]/);
let id = parts.shift();
let isRelativeImport = false;
const warn = (...args) => context.warn(...args);
const isRequire = custom && custom['node-resolve'] && custom['node-resolve'].isRequire;
const exportConditions = isRequire ? conditionsCjs : conditionsEsm;
if (id[0] === '@' && parts.length > 0) {
// scoped packages
id += `/${parts.shift()}`;
} else if (id[0] === '.') {
// an import relative to the parent dir of the importer
id = path.resolve(basedir, importee);
isRelativeImport = true;
}
if (useBrowserOverrides && !exportConditions.includes('browser'))
exportConditions.push('browser');
if (
!isRelativeImport &&
resolveOnly.length &&
!resolveOnly.some((pattern) => pattern.test(id))
) {
if (normalizeInput(rollupOptions.input).includes(importee)) {
return null;
const resolvedWithoutBuiltins = await resolveImportSpecifiers({
importer,
importSpecifierList,
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
});
const importeeIsBuiltin = isBuiltinModule(importee);
const resolved =
importeeIsBuiltin && preferBuiltins
? {
packageInfo: undefined,
hasModuleSideEffects: () => null,
hasPackageEntry: true,
packageBrowserField: false
}
: resolvedWithoutBuiltins;
if (!resolved) {
return null;
}
const { packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = resolved;
let { location } = resolved;
if (packageBrowserField) {
if (Object.prototype.hasOwnProperty.call(packageBrowserField, location)) {
if (!packageBrowserField[location]) {
browserMapCache.set(location, packageBrowserField);
return { id: ES6_BROWSER_EMPTY };
}
return false;
location = packageBrowserField[location];
}
browserMapCache.set(location, packageBrowserField);
}
let hasModuleSideEffects = nullFn;
let hasPackageEntry = true;
let packageBrowserField = false;
let packageInfo;
if (hasPackageEntry && !preserveSymlinks) {
const exists = await fileExists(location);
if (exists) {
location = await realpath(location);
}
}
const filter = (pkg, pkgPath) => {
const info = getPackageInfo({
cache: packageInfoCache,
extensions,
pkg,
pkgPath,
mainFields,
preserveSymlinks,
useBrowserOverrides
});
idToPackageInfo.set(location, packageInfo);
({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
if (hasPackageEntry) {
if (importeeIsBuiltin && preferBuiltins) {
if (!isPreferBuiltinsSet && resolvedWithoutBuiltins && resolved !== importee) {
context.warn(
`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`
);
}
return false;
} else if (jail && location.indexOf(path.normalize(jail.trim(path.sep))) !== 0) {
return null;
}
}
return info.cachedPkg;
};
if (options.modulesOnly && (await fileExists(location))) {
const code = await readFile$1(location, 'utf-8');
if (isModule(code)) {
return {
id: `${location}${importSuffix}`,
moduleSideEffects: hasModuleSideEffects(location)
};
}
return null;
}
return {
id: `${location}${importSuffix}`,
moduleSideEffects: hasModuleSideEffects(location)
};
};
let resolveOptions = {
basedir,
packageFilter: filter,
readFile: readCachedFile,
isFile: isFileCached,
isDirectory: isDirCached,
extensions
};
return {
name: 'node-resolve',
if (preserveSymlinks !== undefined) {
resolveOptions.preserveSymlinks = preserveSymlinks;
}
version,
const importSpecifierList = [];
buildStart(buildOptions) {
validateVersion(this.meta.rollupVersion, peerDependencies.rollup);
rollupOptions = buildOptions;
if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
// For module graph roots (i.e. when importer is undefined), we
// need to handle 'path fragments` like `foo/bar` that are commonly
// found in rollup config files. If importee doesn't look like a
// relative or absolute path, we make it relative and attempt to
// resolve it. If we don't find anything, we try resolving it as we
// got it.
importSpecifierList.push(`./${importee}`);
for (const warning of warnings) {
this.warn(warning);
}
const importeeIsBuiltin = builtins.has(importee);
({ preserveSymlinks } = buildOptions);
},
if (importeeIsBuiltin && (!preferBuiltins || !isPreferBuiltinsSet)) {
// The `resolve` library will not resolve packages with the same
// name as a node built-in module. If we're resolving something
// that's a builtin, and we don't prefer to find built-ins, we
// first try to look up a local module with that name. If we don't
// find anything, we resolve the builtin which just returns back
// the built-in's name.
importSpecifierList.push(`${importee}/`);
}
generateBundle() {
readCachedFile.clear();
isFileCached.clear();
isDirCached.clear();
},
// TypeScript files may import '.js' to refer to either '.ts' or '.tsx'
if (importer && importee.endsWith('.js')) {
for (const ext of ['.ts', '.tsx']) {
if (importer.endsWith(ext) && extensions.includes(ext)) {
importSpecifierList.push(importee.replace(/.js$/, ext));
}
resolveId: {
order: 'post',
async handler(importee, importer, resolveOptions) {
if (importee === ES6_BROWSER_EMPTY) {
return importee;
}
}
// ignore IDs with null character, these belong to other plugins
if (/\0/.test(importee)) return null;
importSpecifierList.push(importee);
resolveOptions = Object.assign(resolveOptions, customResolveOptions);
try {
let resolved = await resolveImportSpecifiers(importSpecifierList, resolveOptions);
if (resolved && packageBrowserField) {
if (Object.prototype.hasOwnProperty.call(packageBrowserField, resolved)) {
if (!packageBrowserField[resolved]) {
browserMapCache.set(resolved, packageBrowserField);
return ES6_BROWSER_EMPTY;
}
resolved = packageBrowserField[resolved];
}
browserMapCache.set(resolved, packageBrowserField);
const { custom = {} } = resolveOptions;
const { 'node-resolve': { resolved: alreadyResolved } = {} } = custom;
if (alreadyResolved) {
return alreadyResolved;
}
if (hasPackageEntry && !preserveSymlinks && resolved) {
const fileExists = await exists(resolved);
if (fileExists) {
resolved = await realpath(resolved);
}
if (/\0/.test(importer)) {
importer = undefined;
}
idToPackageInfo.set(resolved, packageInfo);
if (hasPackageEntry) {
if (builtins.has(resolved) && preferBuiltins && isPreferBuiltinsSet) {
return null;
} else if (importeeIsBuiltin && preferBuiltins) {
if (!isPreferBuiltinsSet) {
this.warn(
`preferring built-in module '${importee}' over local alternative at '${resolved}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`
);
const resolved = await resolveLikeNode(this, importee, importer, custom);
if (resolved) {
// This way, plugins may attach additional meta information to the
// resolved id or make it external. We do not skip node-resolve here
// because another plugin might again use `this.resolve` in its
// `resolveId` hook, in which case we want to add the correct
// `moduleSideEffects` information.
const resolvedResolved = await this.resolve(resolved.id, importer, {
...resolveOptions,
custom: { ...custom, 'node-resolve': { ...custom['node-resolve'], resolved } }
});
if (resolvedResolved) {
// Handle plugins that manually make the result external
if (resolvedResolved.external) {
return false;
}
return null;
} else if (jail && resolved.indexOf(path.normalize(jail.trim(path.sep))) !== 0) {
return null;
// Allow other plugins to take over resolution. Rollup core will not
// change the id if it corresponds to an existing file
if (resolvedResolved.id !== resolved.id) {
return resolvedResolved;
}
// Pass on meta information added by other plugins
return { ...resolved, meta: resolvedResolved.meta };
}
}
if (resolved && options.modulesOnly) {
const code = await readFile(resolved, 'utf-8');
if (isModule(code)) {
return {
id: `${resolved}${importSuffix}`,
moduleSideEffects: hasModuleSideEffects(resolved)
};
}
return null;
}
const result = {
id: `${resolved}${importSuffix}`,
moduleSideEffects: hasModuleSideEffects(resolved)
};
return result;
} catch (error) {
return null;
return resolved;
}

@@ -552,1 +1288,3 @@ },

exports.nodeResolve = nodeResolve;
module.exports = Object.assign(exports.default, exports);
//# sourceMappingURL=index.js.map

@@ -1,3 +0,3 @@

import { dirname, resolve, extname, normalize, sep } from 'path';
import builtinList from 'builtin-modules';
import path, { dirname, resolve, extname, normalize, sep } from 'path';
import isBuiltinModule from 'is-builtin-module';
import deepMerge from 'deepmerge';

@@ -7,10 +7,29 @@ import isModule from 'is-module';

import { promisify } from 'util';
import { pathToFileURL, fileURLToPath } from 'url';
import resolve$1 from 'resolve';
import { createFilter } from '@rollup/pluginutils';
import resolveModule from 'resolve';
const exists = promisify(fs.exists);
const readFile = promisify(fs.readFile);
var version = "15.0.2";
var peerDependencies = {
rollup: "^2.78.0||^3.0.0"
};
promisify(fs.access);
const readFile$1 = promisify(fs.readFile);
const realpath = promisify(fs.realpath);
const stat = promisify(fs.stat);
async function fileExists(filePath) {
try {
const res = await stat(filePath);
return res.isFile();
} catch {
return false;
}
}
async function resolveSymlink(path) {
return (await fileExists(path)) ? realpath(path) : path;
}
const onError = (error) => {

@@ -68,6 +87,51 @@ if (error.code === 'ENOENT') {

const readCachedFile = makeCache(readFile);
const readCachedFile = makeCache(readFile$1);
const resolveId = promisify(resolveModule);
function handleDeprecatedOptions(opts) {
const warnings = [];
if (opts.customResolveOptions) {
const { customResolveOptions } = opts;
if (customResolveOptions.moduleDirectory) {
// eslint-disable-next-line no-param-reassign
opts.moduleDirectories = Array.isArray(customResolveOptions.moduleDirectory)
? customResolveOptions.moduleDirectory
: [customResolveOptions.moduleDirectory];
warnings.push(
'node-resolve: The `customResolveOptions.moduleDirectory` option has been deprecated. Use `moduleDirectories`, which must be an array.'
);
}
if (customResolveOptions.preserveSymlinks) {
throw new Error(
'node-resolve: `customResolveOptions.preserveSymlinks` is no longer an option. We now always use the rollup `preserveSymlinks` option.'
);
}
[
'basedir',
'package',
'extensions',
'includeCoreModules',
'readFile',
'isFile',
'isDirectory',
'realpath',
'packageFilter',
'pathFilter',
'paths',
'packageIterator'
].forEach((resolveOption) => {
if (customResolveOptions[resolveOption]) {
throw new Error(
`node-resolve: \`customResolveOptions.${resolveOption}\` is no longer an option. If you need this, please open an issue.`
);
}
});
}
return { warnings };
}
// returns the imported package name for bare module imports

@@ -109,3 +173,12 @@ function getPackageName(id) {

function getPackageInfo(options) {
const { cache, extensions, pkg, mainFields, preserveSymlinks, useBrowserOverrides } = options;
const {
cache,
extensions,
pkg,
mainFields,
preserveSymlinks,
useBrowserOverrides,
rootDir,
ignoreSideEffectsForRoot
} = options;
let { pkgPath } = options;

@@ -126,3 +199,3 @@

// copy as we are about to munge the `main` field of `pkg`.
packageJson: Object.assign({}, pkg),
packageJson: { ...pkg },

@@ -201,9 +274,21 @@ // path to package.json file

const packageSideEffects = pkg.sideEffects;
if (typeof packageSideEffects === 'boolean') {
internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
} else if (Array.isArray(packageSideEffects)) {
internalPackageInfo.hasModuleSideEffects = createFilter(packageSideEffects, null, {
resolve: pkgRoot
});
if (!ignoreSideEffectsForRoot || rootDir !== pkgRoot) {
const packageSideEffects = pkg.sideEffects;
if (typeof packageSideEffects === 'boolean') {
internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
} else if (Array.isArray(packageSideEffects)) {
const finalPackageSideEffects = packageSideEffects.map((sideEffect) => {
/*
* The array accepts simple glob patterns to the relevant files... Patterns like .css, which do not include a /, will be treated like **\/.css.
* https://webpack.js.org/guides/tree-shaking/
*/
if (sideEffect.includes('/')) {
return sideEffect;
}
return `**/${sideEffect}`;
});
internalPackageInfo.hasModuleSideEffects = createFilter(finalPackageSideEffects, null, {
resolve: pkgRoot
});
}
}

@@ -226,40 +311,654 @@

// Resolve module specifiers in order. Promise resolves to the first module that resolves
// successfully, or the error that resulted from the last attempted module resolution.
function resolveImportSpecifiers(importSpecifierList, resolveOptions) {
let promise = Promise.resolve();
/* eslint-disable no-await-in-loop */
for (let i = 0; i < importSpecifierList.length; i++) {
promise = promise.then((value) => {
// if we've already resolved to something, just return it.
if (value) {
return value;
function isModuleDir(current, moduleDirs) {
return moduleDirs.some((dir) => current.endsWith(dir));
}
async function findPackageJson(base, moduleDirs) {
const { root } = path.parse(base);
let current = base;
while (current !== root && !isModuleDir(current, moduleDirs)) {
const pkgJsonPath = path.join(current, 'package.json');
if (await fileExists(pkgJsonPath)) {
const pkgJsonString = fs.readFileSync(pkgJsonPath, 'utf-8');
return { pkgJson: JSON.parse(pkgJsonString), pkgPath: current, pkgJsonPath };
}
current = path.resolve(current, '..');
}
return null;
}
function isUrl(str) {
try {
return !!new URL(str);
} catch (_) {
return false;
}
}
function isConditions(exports) {
return typeof exports === 'object' && Object.keys(exports).every((k) => !k.startsWith('.'));
}
function isMappings(exports) {
return typeof exports === 'object' && !isConditions(exports);
}
function isMixedExports(exports) {
const keys = Object.keys(exports);
return keys.some((k) => k.startsWith('.')) && keys.some((k) => !k.startsWith('.'));
}
function createBaseErrorMsg(importSpecifier, importer) {
return `Could not resolve import "${importSpecifier}" in ${importer}`;
}
function createErrorMsg(context, reason, internal) {
const { importSpecifier, importer, pkgJsonPath } = context;
const base = createBaseErrorMsg(importSpecifier, importer);
const field = internal ? 'imports' : 'exports';
return `${base} using ${field} defined in ${pkgJsonPath}.${reason ? ` ${reason}` : ''}`;
}
class ResolveError extends Error {}
class InvalidConfigurationError extends ResolveError {
constructor(context, reason) {
super(createErrorMsg(context, `Invalid "exports" field. ${reason}`));
}
}
class InvalidModuleSpecifierError extends ResolveError {
constructor(context, internal, reason) {
super(createErrorMsg(context, reason, internal));
}
}
class InvalidPackageTargetError extends ResolveError {
constructor(context, reason) {
super(createErrorMsg(context, reason));
}
}
/* eslint-disable no-await-in-loop, no-undefined */
function includesInvalidSegments(pathSegments, moduleDirs) {
return pathSegments
.split('/')
.slice(1)
.some((t) => ['.', '..', ...moduleDirs].includes(t));
}
async function resolvePackageTarget(context, { target, subpath, pattern, internal }) {
if (typeof target === 'string') {
if (!pattern && subpath.length > 0 && !target.endsWith('/')) {
throw new InvalidModuleSpecifierError(context);
}
if (!target.startsWith('./')) {
if (internal && !['/', '../'].some((p) => target.startsWith(p)) && !isUrl(target)) {
// this is a bare package import, remap it and resolve it using regular node resolve
if (pattern) {
const result = await context.resolveId(
target.replace(/\*/g, subpath),
context.pkgURL.href
);
return result ? pathToFileURL(result.location).href : null;
}
const result = await context.resolveId(`${target}${subpath}`, context.pkgURL.href);
return result ? pathToFileURL(result.location).href : null;
}
throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`);
}
return resolveId(importSpecifierList[i], resolveOptions).then((result) => {
if (!resolveOptions.preserveSymlinks) {
result = realpathSync(result);
if (includesInvalidSegments(target, context.moduleDirs)) {
throw new InvalidPackageTargetError(context, `Invalid mapping: "${target}".`);
}
const resolvedTarget = new URL(target, context.pkgURL);
if (!resolvedTarget.href.startsWith(context.pkgURL.href)) {
throw new InvalidPackageTargetError(
context,
`Resolved to ${resolvedTarget.href} which is outside package ${context.pkgURL.href}`
);
}
if (includesInvalidSegments(subpath, context.moduleDirs)) {
throw new InvalidModuleSpecifierError(context);
}
if (pattern) {
return resolvedTarget.href.replace(/\*/g, subpath);
}
return new URL(subpath, resolvedTarget).href;
}
if (Array.isArray(target)) {
let lastError;
for (const item of target) {
try {
const resolved = await resolvePackageTarget(context, {
target: item,
subpath,
pattern,
internal
});
// return if defined or null, but not undefined
if (resolved !== undefined) {
return resolved;
}
return result;
} catch (error) {
if (!(error instanceof InvalidPackageTargetError)) {
throw error;
} else {
lastError = error;
}
}
}
if (lastError) {
throw lastError;
}
return null;
}
if (target && typeof target === 'object') {
for (const [key, value] of Object.entries(target)) {
if (key === 'default' || context.conditions.includes(key)) {
const resolved = await resolvePackageTarget(context, {
target: value,
subpath,
pattern,
internal
});
// return if defined or null, but not undefined
if (resolved !== undefined) {
return resolved;
}
}
}
return undefined;
}
if (target === null) {
return null;
}
throw new InvalidPackageTargetError(context, `Invalid exports field.`);
}
/* eslint-disable no-await-in-loop */
async function resolvePackageImportsExports(context, { matchKey, matchObj, internal }) {
if (!matchKey.endsWith('*') && matchKey in matchObj) {
const target = matchObj[matchKey];
const resolved = await resolvePackageTarget(context, { target, subpath: '', internal });
return resolved;
}
const expansionKeys = Object.keys(matchObj)
.filter((k) => k.endsWith('/') || k.endsWith('*'))
.sort((a, b) => b.length - a.length);
for (const expansionKey of expansionKeys) {
const prefix = expansionKey.substring(0, expansionKey.length - 1);
if (expansionKey.endsWith('*') && matchKey.startsWith(prefix)) {
const target = matchObj[expansionKey];
const subpath = matchKey.substring(expansionKey.length - 1);
const resolved = await resolvePackageTarget(context, {
target,
subpath,
pattern: true,
internal
});
return resolved;
}
if (matchKey.startsWith(expansionKey)) {
const target = matchObj[expansionKey];
const subpath = matchKey.substring(expansionKey.length);
const resolved = await resolvePackageTarget(context, { target, subpath, internal });
return resolved;
}
}
throw new InvalidModuleSpecifierError(context, internal);
}
async function resolvePackageExports(context, subpath, exports) {
if (isMixedExports(exports)) {
throw new InvalidConfigurationError(
context,
'All keys must either start with ./, or without one.'
);
}
if (subpath === '.') {
let mainExport;
// If exports is a String or Array, or an Object containing no keys starting with ".", then
if (typeof exports === 'string' || Array.isArray(exports) || isConditions(exports)) {
mainExport = exports;
} else if (isMappings(exports)) {
mainExport = exports['.'];
}
if (mainExport) {
const resolved = await resolvePackageTarget(context, { target: mainExport, subpath: '' });
if (resolved) {
return resolved;
}
}
} else if (isMappings(exports)) {
const resolvedMatch = await resolvePackageImportsExports(context, {
matchKey: subpath,
matchObj: exports
});
if (i < importSpecifierList.length - 1) {
// swallow MODULE_NOT_FOUND errors from all but the last resolution
promise = promise.catch((error) => {
if (error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
if (resolvedMatch) {
return resolvedMatch;
}
}
throw new InvalidModuleSpecifierError(context);
}
async function resolvePackageImports({
importSpecifier,
importer,
moduleDirs,
conditions,
resolveId
}) {
const result = await findPackageJson(importer, moduleDirs);
if (!result) {
throw new Error(createBaseErrorMsg('. Could not find a parent package.json.'));
}
const { pkgPath, pkgJsonPath, pkgJson } = result;
const pkgURL = pathToFileURL(`${pkgPath}/`);
const context = {
importer,
importSpecifier,
moduleDirs,
pkgURL,
pkgJsonPath,
conditions,
resolveId
};
const { imports } = pkgJson;
if (!imports) {
throw new InvalidModuleSpecifierError(context, true);
}
if (importSpecifier === '#' || importSpecifier.startsWith('#/')) {
throw new InvalidModuleSpecifierError(context, true, 'Invalid import specifier.');
}
return resolvePackageImportsExports(context, {
matchKey: importSpecifier,
matchObj: imports,
internal: true
});
}
const resolveImportPath = promisify(resolve$1);
const readFile = promisify(fs.readFile);
async function getPackageJson(importer, pkgName, resolveOptions, moduleDirectories) {
if (importer) {
const selfPackageJsonResult = await findPackageJson(importer, moduleDirectories);
if (selfPackageJsonResult && selfPackageJsonResult.pkgJson.name === pkgName) {
// the referenced package name is the current package
return selfPackageJsonResult;
}
}
try {
const pkgJsonPath = await resolveImportPath(`${pkgName}/package.json`, resolveOptions);
const pkgJson = JSON.parse(await readFile(pkgJsonPath, 'utf-8'));
return { pkgJsonPath, pkgJson, pkgPath: dirname(pkgJsonPath) };
} catch (_) {
return null;
}
}
async function resolveIdClassic({
importSpecifier,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
}) {
let hasModuleSideEffects = () => null;
let hasPackageEntry = true;
let packageBrowserField = false;
let packageInfo;
const filter = (pkg, pkgPath) => {
const info = getPackageInfo({
cache: packageInfoCache,
extensions,
pkg,
pkgPath,
mainFields,
preserveSymlinks,
useBrowserOverrides,
rootDir,
ignoreSideEffectsForRoot
});
({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
return info.cachedPkg;
};
const resolveOptions = {
basedir: baseDir,
readFile: readCachedFile,
isFile: isFileCached,
isDirectory: isDirCached,
extensions,
includeCoreModules: false,
moduleDirectory: moduleDirectories,
paths: modulePaths,
preserveSymlinks,
packageFilter: filter
};
let location;
try {
location = await resolveImportPath(importSpecifier, resolveOptions);
} catch (error) {
if (error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
return null;
}
return {
location: preserveSymlinks ? location : await resolveSymlink(location),
hasModuleSideEffects,
hasPackageEntry,
packageBrowserField,
packageInfo
};
}
async function resolveWithExportMap({
importer,
importSpecifier,
exportConditions,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
}) {
if (importSpecifier.startsWith('#')) {
// this is a package internal import, resolve using package imports field
const resolveResult = await resolvePackageImports({
importSpecifier,
importer,
moduleDirs: moduleDirectories,
conditions: exportConditions,
resolveId(id /* , parent*/) {
return resolveIdClassic({
importSpecifier: id,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths
});
}
});
const location = fileURLToPath(resolveResult);
return {
location: preserveSymlinks ? location : await resolveSymlink(location),
hasModuleSideEffects: () => null,
hasPackageEntry: true,
packageBrowserField: false,
// eslint-disable-next-line no-undefined
packageInfo: undefined
};
}
const pkgName = getPackageName(importSpecifier);
if (pkgName) {
// it's a bare import, find the package.json and resolve using package exports if available
let hasModuleSideEffects = () => null;
let hasPackageEntry = true;
let packageBrowserField = false;
let packageInfo;
const filter = (pkg, pkgPath) => {
const info = getPackageInfo({
cache: packageInfoCache,
extensions,
pkg,
pkgPath,
mainFields,
preserveSymlinks,
useBrowserOverrides,
rootDir,
ignoreSideEffectsForRoot
});
({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
return info.cachedPkg;
};
const resolveOptions = {
basedir: baseDir,
readFile: readCachedFile,
isFile: isFileCached,
isDirectory: isDirCached,
extensions,
includeCoreModules: false,
moduleDirectory: moduleDirectories,
paths: modulePaths,
preserveSymlinks,
packageFilter: filter
};
const result = await getPackageJson(importer, pkgName, resolveOptions, moduleDirectories);
if (result && result.pkgJson.exports) {
const { pkgJson, pkgJsonPath } = result;
const subpath =
pkgName === importSpecifier ? '.' : `.${importSpecifier.substring(pkgName.length)}`;
const pkgDr = pkgJsonPath.replace('package.json', '');
const pkgURL = pathToFileURL(pkgDr);
const context = {
importer,
importSpecifier,
moduleDirs: moduleDirectories,
pkgURL,
pkgJsonPath,
conditions: exportConditions
};
const resolvedPackageExport = await resolvePackageExports(context, subpath, pkgJson.exports);
const location = fileURLToPath(resolvedPackageExport);
if (location) {
return {
location: preserveSymlinks ? location : await resolveSymlink(location),
hasModuleSideEffects,
hasPackageEntry,
packageBrowserField,
packageInfo
};
}
}
}
return promise;
return null;
}
async function resolveWithClassic({
importer,
importSpecifierList,
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
}) {
for (let i = 0; i < importSpecifierList.length; i++) {
// eslint-disable-next-line no-await-in-loop
const result = await resolveIdClassic({
importer,
importSpecifier: importSpecifierList[i],
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
});
if (result) {
return result;
}
}
return null;
}
// Resolves to the module if found or `null`.
// The first import specifier will first be attempted with the exports algorithm.
// If this is unsuccessful because export maps are not being used, then all of `importSpecifierList`
// will be tried with the classic resolution algorithm
async function resolveImportSpecifiers({
importer,
importSpecifierList,
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
}) {
try {
const exportMapRes = await resolveWithExportMap({
importer,
importSpecifier: importSpecifierList[0],
exportConditions,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
});
if (exportMapRes) return exportMapRes;
} catch (error) {
if (error instanceof ResolveError) {
warn(error);
return null;
}
throw error;
}
// package has no imports or exports, use classic node resolve
return resolveWithClassic({
importer,
importSpecifierList,
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
});
}
const versionRegexp = /\^(\d+\.\d+\.\d+)/g;
function validateVersion(actualVersion, peerDependencyVersion) {
let minMajor = Infinity;
let minMinor = Infinity;
let minPatch = Infinity;
let foundVersion;
// eslint-disable-next-line no-cond-assign
while ((foundVersion = versionRegexp.exec(peerDependencyVersion))) {
const [foundMajor, foundMinor, foundPatch] = foundVersion[1].split('.').map(Number);
if (foundMajor < minMajor) {
minMajor = foundMajor;
minMinor = foundMinor;
minPatch = foundPatch;
}
}
if (!actualVersion) {
throw new Error(
`Insufficient Rollup version: "@rollup/plugin-node-resolve" requires at least rollup@${minMajor}.${minMinor}.${minPatch}.`
);
}
const [major, minor, patch] = actualVersion.split('.').map(Number);
if (
major < minMajor ||
(major === minMajor && (minor < minMinor || (minor === minMinor && patch < minPatch)))
) {
throw new Error(
`Insufficient rollup version: "@rollup/plugin-node-resolve" requires at least rollup@${minMajor}.${minMinor}.${minPatch} but found rollup@${actualVersion}.`
);
}
}
/* eslint-disable no-param-reassign, no-shadow, no-undefined */
const builtins = new Set(builtinList);
const ES6_BROWSER_EMPTY = '\0node-resolve:empty.js';
const nullFn = () => null;
const deepFreeze = (object) => {

@@ -276,4 +975,7 @@ Object.freeze(object);

};
const baseConditions = ['default', 'module'];
const baseConditionsEsm = [...baseConditions, 'import'];
const baseConditionsCjs = [...baseConditions, 'require'];
const defaults = {
customResolveOptions: {},
dedupe: [],

@@ -283,3 +985,5 @@ // It's important that .mjs is listed before .js so that Rollup will interpret npm modules

extensions: ['.mjs', '.js', '.json', '.node'],
resolveOnly: []
resolveOnly: [],
moduleDirectories: ['node_modules'],
ignoreSideEffectsForRoot: false
};

@@ -289,5 +993,8 @@ const DEFAULTS = deepFreeze(deepMerge({}, defaults));

function nodeResolve(opts = {}) {
const options = Object.assign({}, defaults, opts);
const { customResolveOptions, extensions, jail } = options;
const warnings = [];
const { warnings } = handleDeprecatedOptions(opts);
const options = { ...defaults, ...opts };
const { extensions, jail, moduleDirectories, modulePaths, ignoreSideEffectsForRoot } = options;
const conditionsEsm = [...baseConditionsEsm, ...(options.exportConditions || [])];
const conditionsCjs = [...baseConditionsCjs, ...(options.exportConditions || [])];
const packageInfoCache = new Map();

@@ -299,9 +1006,10 @@ const idToPackageInfo = new Map();

const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
const rootDir = options.rootDir || process.cwd();
const rootDir = resolve(options.rootDir || process.cwd());
let { dedupe } = options;
let rollupOptions;
if (options.only) {
warnings.push('node-resolve: The `only` options is deprecated, please use `resolveOnly`');
options.resolveOnly = options.only;
if (moduleDirectories.some((name) => name.includes('/'))) {
throw new Error(
'`moduleDirectories` option must only contain directory names. If you want to load modules from somewhere not supported by the default module resolution algorithm, see `modulePaths`.'
);
}

@@ -314,213 +1022,244 @@

const resolveOnly = options.resolveOnly.map((pattern) => {
if (pattern instanceof RegExp) {
return pattern;
}
const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
return new RegExp(`^${normalized}$`);
});
// creates a function from the patterns to test if a particular module should be bundled.
const allowPatterns = (patterns) => {
const regexPatterns = patterns.map((pattern) => {
if (pattern instanceof RegExp) {
return pattern;
}
const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
return new RegExp(`^${normalized}$`);
});
return (id) => !regexPatterns.length || regexPatterns.some((pattern) => pattern.test(id));
};
const resolveOnly =
typeof options.resolveOnly === 'function'
? options.resolveOnly
: allowPatterns(options.resolveOnly);
const browserMapCache = new Map();
let preserveSymlinks;
return {
name: 'node-resolve',
const resolveLikeNode = async (context, importee, importer, custom) => {
// strip query params from import
const [importPath, params] = importee.split('?');
const importSuffix = `${params ? `?${params}` : ''}`;
importee = importPath;
buildStart(options) {
rollupOptions = options;
const baseDir = !importer || dedupe(importee) ? rootDir : dirname(importer);
for (const warning of warnings) {
this.warn(warning);
// https://github.com/defunctzombie/package-browser-field-spec
const browser = browserMapCache.get(importer);
if (useBrowserOverrides && browser) {
const resolvedImportee = resolve(baseDir, importee);
if (browser[importee] === false || browser[resolvedImportee] === false) {
return { id: ES6_BROWSER_EMPTY };
}
const browserImportee =
(importee[0] !== '.' && browser[importee]) ||
browser[resolvedImportee] ||
browser[`${resolvedImportee}.js`] ||
browser[`${resolvedImportee}.json`];
if (browserImportee) {
importee = browserImportee;
}
}
({ preserveSymlinks } = options);
},
const parts = importee.split(/[/\\]/);
let id = parts.shift();
let isRelativeImport = false;
generateBundle() {
readCachedFile.clear();
isFileCached.clear();
isDirCached.clear();
},
if (id[0] === '@' && parts.length > 0) {
// scoped packages
id += `/${parts.shift()}`;
} else if (id[0] === '.') {
// an import relative to the parent dir of the importer
id = resolve(baseDir, importee);
isRelativeImport = true;
}
async resolveId(importee, importer) {
if (importee === ES6_BROWSER_EMPTY) {
return importee;
// if it's not a relative import, and it's not requested, reject it.
if (!isRelativeImport && !resolveOnly(id)) {
if (normalizeInput(rollupOptions.input).includes(importee)) {
return null;
}
// ignore IDs with null character, these belong to other plugins
if (/\0/.test(importee)) return null;
return false;
}
// strip hash and query params from import
const [withoutHash, hash] = importee.split('#');
const [importPath, params] = withoutHash.split('?');
const importSuffix = `${params ? `?${params}` : ''}${hash ? `#${hash}` : ''}`;
importee = importPath;
const importSpecifierList = [importee];
const basedir = !importer || dedupe(importee) ? rootDir : dirname(importer);
if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
// For module graph roots (i.e. when importer is undefined), we
// need to handle 'path fragments` like `foo/bar` that are commonly
// found in rollup config files. If importee doesn't look like a
// relative or absolute path, we make it relative and attempt to
// resolve it.
importSpecifierList.push(`./${importee}`);
}
// https://github.com/defunctzombie/package-browser-field-spec
const browser = browserMapCache.get(importer);
if (useBrowserOverrides && browser) {
const resolvedImportee = resolve(basedir, importee);
if (browser[importee] === false || browser[resolvedImportee] === false) {
return ES6_BROWSER_EMPTY;
// TypeScript files may import '.js' to refer to either '.ts' or '.tsx'
if (importer && importee.endsWith('.js')) {
for (const ext of ['.ts', '.tsx']) {
if (importer.endsWith(ext) && extensions.includes(ext)) {
importSpecifierList.push(importee.replace(/.js$/, ext));
}
const browserImportee =
browser[importee] ||
browser[resolvedImportee] ||
browser[`${resolvedImportee}.js`] ||
browser[`${resolvedImportee}.json`];
if (browserImportee) {
importee = browserImportee;
}
}
}
const parts = importee.split(/[/\\]/);
let id = parts.shift();
let isRelativeImport = false;
const warn = (...args) => context.warn(...args);
const isRequire = custom && custom['node-resolve'] && custom['node-resolve'].isRequire;
const exportConditions = isRequire ? conditionsCjs : conditionsEsm;
if (id[0] === '@' && parts.length > 0) {
// scoped packages
id += `/${parts.shift()}`;
} else if (id[0] === '.') {
// an import relative to the parent dir of the importer
id = resolve(basedir, importee);
isRelativeImport = true;
}
if (useBrowserOverrides && !exportConditions.includes('browser'))
exportConditions.push('browser');
if (
!isRelativeImport &&
resolveOnly.length &&
!resolveOnly.some((pattern) => pattern.test(id))
) {
if (normalizeInput(rollupOptions.input).includes(importee)) {
return null;
const resolvedWithoutBuiltins = await resolveImportSpecifiers({
importer,
importSpecifierList,
exportConditions,
warn,
packageInfoCache,
extensions,
mainFields,
preserveSymlinks,
useBrowserOverrides,
baseDir,
moduleDirectories,
modulePaths,
rootDir,
ignoreSideEffectsForRoot
});
const importeeIsBuiltin = isBuiltinModule(importee);
const resolved =
importeeIsBuiltin && preferBuiltins
? {
packageInfo: undefined,
hasModuleSideEffects: () => null,
hasPackageEntry: true,
packageBrowserField: false
}
: resolvedWithoutBuiltins;
if (!resolved) {
return null;
}
const { packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = resolved;
let { location } = resolved;
if (packageBrowserField) {
if (Object.prototype.hasOwnProperty.call(packageBrowserField, location)) {
if (!packageBrowserField[location]) {
browserMapCache.set(location, packageBrowserField);
return { id: ES6_BROWSER_EMPTY };
}
return false;
location = packageBrowserField[location];
}
browserMapCache.set(location, packageBrowserField);
}
let hasModuleSideEffects = nullFn;
let hasPackageEntry = true;
let packageBrowserField = false;
let packageInfo;
if (hasPackageEntry && !preserveSymlinks) {
const exists = await fileExists(location);
if (exists) {
location = await realpath(location);
}
}
const filter = (pkg, pkgPath) => {
const info = getPackageInfo({
cache: packageInfoCache,
extensions,
pkg,
pkgPath,
mainFields,
preserveSymlinks,
useBrowserOverrides
});
idToPackageInfo.set(location, packageInfo);
({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
if (hasPackageEntry) {
if (importeeIsBuiltin && preferBuiltins) {
if (!isPreferBuiltinsSet && resolvedWithoutBuiltins && resolved !== importee) {
context.warn(
`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`
);
}
return false;
} else if (jail && location.indexOf(normalize(jail.trim(sep))) !== 0) {
return null;
}
}
return info.cachedPkg;
};
if (options.modulesOnly && (await fileExists(location))) {
const code = await readFile$1(location, 'utf-8');
if (isModule(code)) {
return {
id: `${location}${importSuffix}`,
moduleSideEffects: hasModuleSideEffects(location)
};
}
return null;
}
return {
id: `${location}${importSuffix}`,
moduleSideEffects: hasModuleSideEffects(location)
};
};
let resolveOptions = {
basedir,
packageFilter: filter,
readFile: readCachedFile,
isFile: isFileCached,
isDirectory: isDirCached,
extensions
};
return {
name: 'node-resolve',
if (preserveSymlinks !== undefined) {
resolveOptions.preserveSymlinks = preserveSymlinks;
}
version,
const importSpecifierList = [];
buildStart(buildOptions) {
validateVersion(this.meta.rollupVersion, peerDependencies.rollup);
rollupOptions = buildOptions;
if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
// For module graph roots (i.e. when importer is undefined), we
// need to handle 'path fragments` like `foo/bar` that are commonly
// found in rollup config files. If importee doesn't look like a
// relative or absolute path, we make it relative and attempt to
// resolve it. If we don't find anything, we try resolving it as we
// got it.
importSpecifierList.push(`./${importee}`);
for (const warning of warnings) {
this.warn(warning);
}
const importeeIsBuiltin = builtins.has(importee);
({ preserveSymlinks } = buildOptions);
},
if (importeeIsBuiltin && (!preferBuiltins || !isPreferBuiltinsSet)) {
// The `resolve` library will not resolve packages with the same
// name as a node built-in module. If we're resolving something
// that's a builtin, and we don't prefer to find built-ins, we
// first try to look up a local module with that name. If we don't
// find anything, we resolve the builtin which just returns back
// the built-in's name.
importSpecifierList.push(`${importee}/`);
}
generateBundle() {
readCachedFile.clear();
isFileCached.clear();
isDirCached.clear();
},
// TypeScript files may import '.js' to refer to either '.ts' or '.tsx'
if (importer && importee.endsWith('.js')) {
for (const ext of ['.ts', '.tsx']) {
if (importer.endsWith(ext) && extensions.includes(ext)) {
importSpecifierList.push(importee.replace(/.js$/, ext));
}
resolveId: {
order: 'post',
async handler(importee, importer, resolveOptions) {
if (importee === ES6_BROWSER_EMPTY) {
return importee;
}
}
// ignore IDs with null character, these belong to other plugins
if (/\0/.test(importee)) return null;
importSpecifierList.push(importee);
resolveOptions = Object.assign(resolveOptions, customResolveOptions);
try {
let resolved = await resolveImportSpecifiers(importSpecifierList, resolveOptions);
if (resolved && packageBrowserField) {
if (Object.prototype.hasOwnProperty.call(packageBrowserField, resolved)) {
if (!packageBrowserField[resolved]) {
browserMapCache.set(resolved, packageBrowserField);
return ES6_BROWSER_EMPTY;
}
resolved = packageBrowserField[resolved];
}
browserMapCache.set(resolved, packageBrowserField);
const { custom = {} } = resolveOptions;
const { 'node-resolve': { resolved: alreadyResolved } = {} } = custom;
if (alreadyResolved) {
return alreadyResolved;
}
if (hasPackageEntry && !preserveSymlinks && resolved) {
const fileExists = await exists(resolved);
if (fileExists) {
resolved = await realpath(resolved);
}
if (/\0/.test(importer)) {
importer = undefined;
}
idToPackageInfo.set(resolved, packageInfo);
if (hasPackageEntry) {
if (builtins.has(resolved) && preferBuiltins && isPreferBuiltinsSet) {
return null;
} else if (importeeIsBuiltin && preferBuiltins) {
if (!isPreferBuiltinsSet) {
this.warn(
`preferring built-in module '${importee}' over local alternative at '${resolved}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`
);
const resolved = await resolveLikeNode(this, importee, importer, custom);
if (resolved) {
// This way, plugins may attach additional meta information to the
// resolved id or make it external. We do not skip node-resolve here
// because another plugin might again use `this.resolve` in its
// `resolveId` hook, in which case we want to add the correct
// `moduleSideEffects` information.
const resolvedResolved = await this.resolve(resolved.id, importer, {
...resolveOptions,
custom: { ...custom, 'node-resolve': { ...custom['node-resolve'], resolved } }
});
if (resolvedResolved) {
// Handle plugins that manually make the result external
if (resolvedResolved.external) {
return false;
}
return null;
} else if (jail && resolved.indexOf(normalize(jail.trim(sep))) !== 0) {
return null;
// Allow other plugins to take over resolution. Rollup core will not
// change the id if it corresponds to an existing file
if (resolvedResolved.id !== resolved.id) {
return resolvedResolved;
}
// Pass on meta information added by other plugins
return { ...resolved, meta: resolvedResolved.meta };
}
}
if (resolved && options.modulesOnly) {
const code = await readFile(resolved, 'utf-8');
if (isModule(code)) {
return {
id: `${resolved}${importSuffix}`,
moduleSideEffects: hasModuleSideEffects(resolved)
};
}
return null;
}
const result = {
id: `${resolved}${importSuffix}`,
moduleSideEffects: hasModuleSideEffects(resolved)
};
return result;
} catch (error) {
return null;
return resolved;
}

@@ -542,3 +1281,3 @@ },

export default nodeResolve;
export { DEFAULTS, nodeResolve };
export { DEFAULTS, nodeResolve as default, nodeResolve };
//# sourceMappingURL=index.js.map
+41
-36
{
"name": "@rollup/plugin-node-resolve",
"version": "9.0.0",
"version": "15.0.2",
"publishConfig": {

@@ -9,3 +9,6 @@ "access": "public"

"license": "MIT",
"repository": "rollup/plugins",
"repository": {
"url": "rollup/plugins",
"directory": "packages/node-resolve"
},
"author": "Rich Harris <richard.a.harris@gmail.com>",

@@ -16,20 +19,23 @@ "homepage": "https://github.com/rollup/plugins/tree/master/packages/node-resolve/#readme",

"module": "./dist/es/index.js",
"exports": {
"types": "./types/index.d.ts",
"import": "./dist/es/index.js",
"default": "./dist/cjs/index.js"
},
"engines": {
"node": ">= 10.0.0"
"node": ">=14.0.0"
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm run test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm run build && pnpm run lint",
"ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm build && pnpm lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm run test -- --verbose && pnpm run test:ts",
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
"lint:docs": "prettier --single-quote --arrow-parens avoid --trailing-comma none --write README.md",
"lint:js": "eslint --fix --cache src test types --ext .js,.ts",
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
"ci:test": "pnpm test -- --verbose",
"prebuild": "del-cli dist",
"prepare": "pnpm run build",
"prepublishOnly": "pnpm run lint && pnpm run test && pnpm run test:ts",
"pretest": "pnpm run build",
"test": "ava",
"prepare": "if [ ! -d 'dist' ]; then pnpm build; fi",
"prepublishOnly": "pnpm build",
"prerelease": "pnpm build",
"pretest": "pnpm build",
"release": "pnpm --workspace-root plugin:release --pkg $npm_package_name",
"test": "pnpm test:ts && ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"

@@ -39,2 +45,3 @@ },

"dist",
"!dist/**/*.map",
"types",

@@ -52,28 +59,31 @@ "README.md",

"peerDependencies": {
"rollup": "^1.20.0||^2.0.0"
"rollup": "^2.78.0||^3.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
},
"dependencies": {
"@rollup/pluginutils": "^3.1.0",
"@types/resolve": "1.17.1",
"builtin-modules": "^3.1.0",
"@rollup/pluginutils": "^5.0.1",
"@types/resolve": "1.20.2",
"deepmerge": "^4.2.2",
"is-builtin-module": "^3.2.1",
"is-module": "^1.0.0",
"resolve": "^1.17.0"
"resolve": "^1.22.1"
},
"devDependencies": {
"@babel/core": "^7.10.5",
"@babel/core": "^7.19.1",
"@babel/plugin-transform-typescript": "^7.10.5",
"@rollup/plugin-babel": "^5.1.0",
"@rollup/plugin-commonjs": "^14.0.0",
"@rollup/plugin-json": "^4.1.0",
"es5-ext": "^0.10.53",
"rollup": "^2.23.0",
"source-map": "^0.7.3",
"@rollup/plugin-babel": "^6.0.0",
"@rollup/plugin-commonjs": "^23.0.0",
"@rollup/plugin-json": "^5.0.0",
"es5-ext": "^0.10.62",
"rollup": "^3.2.3",
"source-map": "^0.7.4",
"string-capitalize": "^1.0.1"
},
"types": "types/index.d.ts",
"types": "./types/index.d.ts",
"ava": {
"babel": {
"compileEnhancements": false
},
"workerThreads": false,
"files": [

@@ -85,8 +95,3 @@ "!**/fixtures/**",

]
},
"exports": {
"require": "./dist/cjs/index.js",
"import": "./dist/es/index.js"
},
"type": "commonjs"
}
}
+73
-26

@@ -16,3 +16,3 @@ [npm]: https://img.shields.io/npm/v/@rollup/plugin-node-resolve

This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v8.0.0+) and Rollup v1.20.0+.
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v2.78.0+.

@@ -46,4 +46,21 @@ ## Install

## Package entrypoints
This plugin supports the package entrypoints feature from node js, specified in the `exports` or `imports` field of a package. Check the [official documentation](https://nodejs.org/api/packages.html#packages_package_entry_points) for more information on how this works. This is the default behavior. In the abscence of these fields, the fields in `mainFields` will be the ones to be used.
## Options
### `exportConditions`
Type: `Array[...String]`<br>
Default: `[]`
Additional conditions of the package.json exports field to match when resolving modules. By default, this plugin looks for the `['default', 'module', 'import']` conditions when resolving imports.
When using `@rollup/plugin-commonjs` v16 or higher, this plugin will use the `['default', 'module', 'require']` conditions when resolving require statements.
Setting this option will add extra conditions on top of the default conditions. See https://nodejs.org/api/packages.html#packages_conditional_exports for more information.
In order to get the [resolution behavior of Node.js](https://nodejs.org/api/packages.html#packages_conditional_exports), set this to `['node']`.
### `browser`

@@ -54,17 +71,20 @@

If `true`, instructs the plugin to use the `"browser"` property in `package.json` files to specify alternative files to load for bundling. This is useful when bundling for a browser environment. Alternatively, a value of `'browser'` can be added to the `mainFields` option. If `false`, any `"browser"` properties in package files will be ignored. This option takes precedence over `mainFields`.
If `true`, instructs the plugin to use the browser module resolutions in `package.json` and adds `'browser'` to `exportConditions` if it is not present so browser conditionals in `exports` are applied. If `false`, any browser properties in package files will be ignored. Alternatively, a value of `'browser'` can be added to both the `mainFields` and `exportConditions` options, however this option takes precedence over `mainFields`.
### `customResolveOptions`
> This option does not work when a package is using [package entrypoints](https://nodejs.org/api/packages.html#packages_package_entry_points)
Type: `Object`<br>
Default: `null`
### `moduleDirectories`
An `Object` that specifies additional options that should be passed through to [`resolve`](https://www.npmjs.com/package/resolve).
Type: `Array[...String]`<br>
Default: `['node_modules']`
```
customResolveOptions: {
moduleDirectory: 'js_modules'
}
```
A list of directory names in which to recursively look for modules.
### `modulePaths`
Type: `Array[...String]`<br>
Default: `[]`
A list of absolute paths to additional locations to search for modules. [This is analogous to setting the `NODE_PATH` environment variable for node](https://nodejs.org/api/modules.html#loading-from-the-global-folders).
### `dedupe`

@@ -107,3 +127,3 @@

Locks the module search within specified path (e.g. chroot). Modules defined outside this path will be marked as external.
Locks the module search within specified path (e.g. chroot). Modules defined outside this path will be ignored by this plugin.

@@ -118,10 +138,6 @@ ### `mainFields`

### `only`
DEPRECATED: use "resolveOnly" instead
### `preferBuiltins`
Type: `Boolean`<br>
Default: `true`
Default: `true` (with warnings if a builtin module is used over a local version. Set to `true` to disable warning.)

@@ -139,3 +155,3 @@ If `true`, the plugin will prefer built-in modules (e.g. `fs`, `path`). If `false`, the plugin will look for locally installed modules of the same name.

Type: `Array[...String|RegExp]`<br>
Type: `Array[...String|RegExp] | (module: string) => boolean`<br>
Default: `null`

@@ -145,4 +161,9 @@

Example: `resolveOnly: ['batman', /^@batcave\/.*$/]`
Alternatively, you may pass in a function that returns a boolean to confirm whether the module should be included or not.
Examples:
- `resolveOnly: ['batman', /^@batcave\/.*$/]`
- `resolveOnly: module => !module.includes('joker')`
### `rootDir`

@@ -160,2 +181,10 @@

### `ignoreSideEffectsForRoot`
If you use the `sideEffects` property in the package.json, by default this is respected for files in the root package. Set to `true` to ignore the `sideEffects` configuration for the root package.
## Preserving symlinks
This plugin honours the rollup [`preserveSymlinks`](https://rollupjs.org/guide/en/#preservesymlinks) option.
## Using with @rollup/plugin-commonjs

@@ -167,3 +196,3 @@

// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';

@@ -178,3 +207,3 @@

},
plugins: [resolve(), commonjs()]
plugins: [nodeResolve(), commonjs()]
};

@@ -185,12 +214,17 @@ ```

This plugin won't resolve any builtins (e.g. `fs`). If you need to resolve builtins you can install local modules and set `preferBuiltins` to `false`, or install a plugin like [rollup-plugin-node-polyfills](https://github.com/ionic-team/rollup-plugin-node-polyfills) which provides stubbed versions of these methods.
By default this plugin will prefer built-ins over local modules, marking them as external.
If you want to silence warnings about builtins, you can add the list of builtins to the `externals` option; like so:
See [`preferBuiltins`](#preferbuiltins).
To provide stubbed versions of Node built-ins, use a plugin like [rollup-plugin-node-polyfills](https://github.com/ionic-team/rollup-plugin-node-polyfills) and set `preferBuiltins` to `false`. e.g.
```js
import resolve from '@rollup/plugin-node-resolve';
import builtins from 'builtin-modules'
import { nodeResolve } from '@rollup/plugin-node-resolve';
import nodePolyfills from 'rollup-plugin-node-polyfills';
export default ({
input: ...,
plugins: [resolve()],
plugins: [
nodePolyfills(),
nodeResolve({ preferBuiltins: false })
],
external: builtins,

@@ -201,2 +235,15 @@ output: ...

## Resolving Require Statements
According to [NodeJS module resolution](https://nodejs.org/api/packages.html#packages_package_entry_points) `require` statements should resolve using the `require` condition in the package exports field, while es modules should use the `import` condition.
The node resolve plugin uses `import` by default, you can opt into using the `require` semantics by passing an extra option to the resolve function:
```js
this.resolve(importee, importer, {
skipSelf: true,
custom: { 'node-resolve': { isRequire: true } }
});
```
## Meta

@@ -203,0 +250,0 @@

@@ -1,3 +0,2 @@

import { Plugin } from 'rollup';
import { AsyncOpts } from 'resolve';
import type { Plugin } from 'rollup';

@@ -13,2 +12,14 @@ export const DEFAULTS: {

/**
* Additional conditions of the package.json exports field to match when resolving modules.
* By default, this plugin looks for the `'default', 'module', 'import']` conditions when resolving imports.
*
* When using `@rollup/plugin-commonjs` v16 or higher, this plugin will use the
* `['default', 'module', 'import']` conditions when resolving require statements.
*
* Setting this option will add extra conditions on top of the default conditions.
* See https://nodejs.org/api/packages.html#packages_conditional_exports for more information.
*/
exportConditions?: string[];
/**
* If `true`, instructs the plugin to use the `"browser"` property in `package.json`

@@ -24,7 +35,15 @@ * files to specify alternative files to load for bundling. This is useful when

/**
* An `Object` that specifies additional options that should be passed through to `node-resolve`.
* A list of directory names in which to recursively look for modules.
* @default ['node_modules']
*/
customResolveOptions?: AsyncOpts;
moduleDirectories?: string[];
/**
* A list of absolute paths to additional locations to search for modules.
* This is analogous to setting the `NODE_PATH` environment variable for node.
* @default []
*/
modulePaths?: string[];
/**
* An `Array` of modules names, which instructs the plugin to force resolving for the

@@ -63,8 +82,2 @@ * specified modules to the root `node_modules`. Helps to prevent bundling the same

/**
* @deprecated use "resolveOnly" instead
* @default null
*/
only?: ReadonlyArray<string | RegExp> | null;
/**
* If `true`, the plugin will prefer built-in modules (e.g. `fs`, `path`). If `false`,

@@ -81,3 +94,3 @@ * the plugin will look for locally installed modules of the same name.

*/
resolveOnly?: ReadonlyArray<string | RegExp> | null;
resolveOnly?: ReadonlyArray<string | RegExp> | null | ((module: string) => boolean);

@@ -84,0 +97,0 @@ /**

# @rollup/plugin-node-resolve ChangeLog
## v9.0.0
_2020-08-13_
### Breaking Changes
- chore: update dependencies (e632469)
### Updates
- refactor: remove deep-freeze from dependencies (#529)
- chore: clean up changelog (84dfddb)
## v8.4.0
_2020-07-12_
### Features
- feat: preserve search params and hashes (#487)
- feat: support .js imports in TypeScript (#480)
### Updates
- docs: fix named export use in readme (#456)
- docs: correct mainFields valid values (#469)
## v8.1.0
_2020-06-22_
### Features
- feat: add native node es modules support (#413)
## v8.0.1
_2020-06-05_
### Bugfixes
- fix: handle nested entry modules with the resolveOnly option (#430)
## v8.0.0
_2020-05-20_
### Breaking Changes
- feat: Add default export (#361)
- feat: export defaults (#301)
### Bugfixes
- fix: resolve local files if `resolveOption` is set (#337)
### Updates
- docs: correct misspelling (#343)
## v7.1.3
_2020-04-12_
### Bugfixes
- fix: resolve symlinked entry point properly (#291)
## v7.1.2
_2020-04-12_
### Updates
- docs: fix url (#289)
## v7.1.1
_2020-02-03_
### Bugfixes
- fix: main fields regression (#196)
## v7.1.0
_2020-02-01_
### Updates
- refactor: clean codebase and fix external warnings (#155)
## v7.0.0
_2020-01-07_
### Breaking Changes
- feat: dedupe by package name (#99)
## v6.1.0
_2020-01-04_
### Bugfixes
- fix: allow deduplicating custom module dirs (#101)
### Features
- feat: add rootDir option (#98)
### Updates
- docs: improve doc related to mainFields (#138)
## 6.0.0
_2019-11-25_
- **Breaking:** Minimum compatible Rollup version is 1.20.0
- **Breaking:** Minimum supported Node version is 8.0.0
- Published as @rollup/plugin-node-resolve
## 5.2.1 (unreleased)
- add missing MIT license file ([#233](https://github.com/rollup/rollup-plugin-node-resolve/pull/233) by @kenjiO)
- Fix incorrect example of config ([#239](https://github.com/rollup/rollup-plugin-node-resolve/pull/240) by @myshov)
- Fix typo in readme ([#240](https://github.com/rollup/rollup-plugin-node-resolve/pull/240) by @LinusU)
## 5.2.0 (2019-06-29)
- dedupe accepts a function ([#225](https://github.com/rollup/rollup-plugin-node-resolve/pull/225) by @manucorporat)
## 5.1.1 (2019-06-29)
- Move Rollup version check to buildStart hook to avoid issues ([#232](https://github.com/rollup/rollup-plugin-node-resolve/pull/232) by @lukastaegert)
## 5.1.0 (2019-06-22)
- Fix path fragment inputs ([#229](https://github.com/rollup/rollup-plugin-node-resolve/pull/229) by @bterlson)
## 5.0.4 (2019-06-22)
- Treat sideEffects array as inclusion list ([#227](https://github.com/rollup/rollup-plugin-node-resolve/pull/227) by @mikeharder)
## 5.0.3 (2019-06-16)
- Make empty.js a virtual module ([#224](https://github.com/rollup/rollup-plugin-node-resolve/pull/224) by @manucorporat)
## 5.0.2 (2019-06-13)
- Support resolve 1.11.1, add built-in test ([#223](https://github.com/rollup/rollup-plugin-node-resolve/pull/223) by @bterlson)
## 5.0.1 (2019-05-31)
- Update to resolve@1.11.0 for better performance ([#220](https://github.com/rollup/rollup-plugin-node-resolve/pull/220) by @keithamus)
## 5.0.0 (2019-05-15)
- Replace bublé with babel, update dependencies ([#216](https://github.com/rollup/rollup-plugin-node-resolve/pull/216) by @mecurc)
- Handle module side-effects ([#219](https://github.com/rollup/rollup-plugin-node-resolve/pull/219) by @lukastaegert)
### Breaking Changes
- Requires at least rollup@1.11.0 to work (v1.12.0 for module side-effects to be respected)
- If used with rollup-plugin-commonjs, it should be at least v10.0.0
## 4.2.4 (2019-05-11)
- Add note on builtins to Readme ([#215](https://github.com/rollup/rollup-plugin-node-resolve/pull/215) by @keithamus)
- Add issue templates ([#217](https://github.com/rollup/rollup-plugin-node-resolve/pull/217) by @mecurc)
- Improve performance by caching `isDir` ([#218](https://github.com/rollup/rollup-plugin-node-resolve/pull/218) by @keithamus)
## 4.2.3 (2019-04-11)
- Fix ordering of jsnext:main when using the jsnext option ([#209](https://github.com/rollup/rollup-plugin-node-resolve/pull/209) by @lukastaegert)
## 4.2.2 (2019-04-10)
- Fix TypeScript typings (rename and export Options interface) ([#206](https://github.com/rollup/rollup-plugin-node-resolve/pull/206) by @Kocal)
- Fix mainfields typing ([#207](https://github.com/rollup/rollup-plugin-node-resolve/pull/207) by @nicolashenry)
## 4.2.1 (2019-04-06)
- Respect setting the deprecated fields "module", "main", and "jsnext" ([#204](https://github.com/rollup/rollup-plugin-node-resolve/pull/204) by @nick-woodward)
## 4.2.0 (2019-04-06)
- Add new mainfields option ([#182](https://github.com/rollup/rollup-plugin-node-resolve/pull/182) by @keithamus)
- Added dedupe option to prevent bundling the same package multiple times ([#201](https://github.com/rollup/rollup-plugin-node-resolve/pull/182) by @sormy)
## 4.1.0 (2019-04-05)
- Add TypeScript typings ([#189](https://github.com/rollup/rollup-plugin-node-resolve/pull/189) by @NotWoods)
- Update dependencies ([#202](https://github.com/rollup/rollup-plugin-node-resolve/pull/202) by @lukastaegert)
## 4.0.1 (2019-02-22)
- Fix issue when external modules are specified in `package.browser` ([#143](https://github.com/rollup/rollup-plugin-node-resolve/pull/143) by @keithamus)
- Fix `package.browser` mapping issue when `false` is specified ([#183](https://github.com/rollup/rollup-plugin-node-resolve/pull/183) by @allex)
## 4.0.0 (2018-12-09)
This release will support rollup@1.0
### Features
- Resolve modules used to define manual chunks ([#185](https://github.com/rollup/rollup-plugin-node-resolve/pull/185) by @mcshaman)
- Update dependencies and plugin hook usage ([#187](https://github.com/rollup/rollup-plugin-node-resolve/pull/187) by @lukastaegert)
## 3.4.0 (2018-09-04)
This release now supports `.mjs` files by default
### Features
- feat: Support .mjs files by default (https://github.com/rollup/rollup-plugin-node-resolve/pull/151, by @leebyron)
## 3.3.0 (2018-03-17)
This release adds the `only` option
### New Features
- feat: add `only` option (#83; @arantes555)
### Docs
- docs: correct description of `jail` option (#120; @GeorgeTaveras1231)
## 3.2.0 (2018-03-07)
This release caches reading/statting of files, to improve speed.
### Performance Improvements
- perf: cache file stats/reads (#126; @keithamus)
## 3.0.4 (unreleased)
- Update lockfile [#137](https://github.com/rollup/rollup-plugin-node-resolve/issues/137)
- Update rollup dependency [#138](https://github.com/rollup/rollup-plugin-node-resolve/issues/138)
- Enable installation from Github [#142](https://github.com/rollup/rollup-plugin-node-resolve/issues/142)
## 3.0.3
- Fix [#130](https://github.com/rollup/rollup-plugin-node-resolve/issues/130) and [#131](https://github.com/rollup/rollup-plugin-node-resolve/issues/131)
## 3.0.2
- Ensure `pkg.browser` is an object if necessary ([#129](https://github.com/rollup/rollup-plugin-node-resolve/pull/129))
## 3.0.1
- Remove `browser-resolve` dependency ([#127](https://github.com/rollup/rollup-plugin-node-resolve/pull/127))
## 3.0.0
- [BREAKING] Remove `options.skip` ([#90](https://github.com/rollup/rollup-plugin-node-resolve/pull/90))
- Add `modulesOnly` option ([#96](https://github.com/rollup/rollup-plugin-node-resolve/pull/96))
## 2.1.1
- Prevent `jail` from breaking builds on Windows ([#93](https://github.com/rollup/rollup-plugin-node-resolve/issues/93))
## 2.1.0
- Add `jail` option ([#53](https://github.com/rollup/rollup-plugin-node-resolve/pull/53))
- Add `customResolveOptions` option ([#79](https://github.com/rollup/rollup-plugin-node-resolve/pull/79))
- Support symlinked packages ([#82](https://github.com/rollup/rollup-plugin-node-resolve/pull/82))
## 2.0.0
- Add support `module` field in package.json as an official alternative to jsnext
## 1.7.3
- Error messages are more descriptive ([#50](https://github.com/rollup/rollup-plugin-node-resolve/issues/50))
## 1.7.2
- Allow entry point paths beginning with ./
## 1.7.1
- Return a `name`
## 1.7.0
- Allow relative IDs to be external ([#32](https://github.com/rollup/rollup-plugin-node-resolve/pull/32))
## 1.6.0
- Skip IDs containing null character
## 1.5.0
- Prefer built-in options, but allow opting out ([#28](https://github.com/rollup/rollup-plugin-node-resolve/pull/28))
## 1.4.0
- Pass `options.extensions` through to `node-resolve`
## 1.3.0
- `skip: true` skips all packages that don't satisfy the `main` or `jsnext` options ([#16](https://github.com/rollup/rollup-plugin-node-resolve/pull/16))
## 1.2.1
- Support scoped packages in `skip` option ([#15](https://github.com/rollup/rollup-plugin-node-resolve/issues/15))
## 1.2.0
- Support `browser` field ([#8](https://github.com/rollup/rollup-plugin-node-resolve/issues/8))
- Get tests to pass on Windows
## 1.1.0
- Use node-resolve to handle various corner cases
## 1.0.0
- Add ES6 build, use Rollup 0.20.0
## 0.1.0
- First release