code:
# resolve <sup>[![Version Badge][2]][1]</sup>

implements the [node `require.resolve()` algorithm](https://nodejs.org/api/modules.html#modules_all_together) such that you can `require.resolve()` on behalf of a file asynchronously and synchronously

[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][5]][6]
[![dev dependency status][7]][8]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]

[![npm badge][11]][1]

# example

asynchronously resolve:

```js
var resolve = require('resolve/async'); // or, require('resolve')
resolve('tap', { basedir: __dirname }, function (err, res) {
    if (err) console.error(err);
    else console.log(res);
});
```

```
$ node example/async.js
/home/substack/projects/node-resolve/node_modules/tap/lib/main.js
```

synchronously resolve:

```js
var resolve = require('resolve/sync'); // or, `require('resolve').sync
var res = resolve('tap', { basedir: __dirname });
console.log(res);
```

```
$ node example/sync.js
/home/substack/projects/node-resolve/node_modules/tap/lib/main.js
```

# methods

```js
var resolve = require('resolve');
var async = require('resolve/async');
var sync = require('resolve/sync');
```

For both the synchronous and asynchronous methods, errors may have any of the following `err.code` values:

- `MODULE_NOT_FOUND`: the given path string (`id`) could not be resolved to a module
- `INVALID_BASEDIR`: the specified `opts.basedir` doesn't exist, or is not a directory
- `INVALID_PACKAGE_MAIN`: a `package.json` was encountered with an invalid `main` property (eg. not a string)

## resolve(id, opts={}, cb)

Asynchronously resolve the module path string `id` into `cb(err, res [, pkg])`, where `pkg` (if defined) is the data from `package.json`.

options are:

* opts.basedir - directory to begin resolving from

* opts.package - `package.json` data applicable to the module being loaded

* opts.extensions - array of file extensions to search in order

* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search

* opts.readFile - how to read files asynchronously

* opts.isFile - function to asynchronously test whether a file exists

* opts.isDirectory - function to asynchronously test whether a file exists and is a directory

* opts.realpath - function to asynchronously resolve a potential symlink to its real path

* `opts.readPackage(readFile, pkgfile, cb)` - function to asynchronously read and parse a package.json file
  * readFile - the passed `opts.readFile` or `fs.readFile` if not specified
  * pkgfile - path to package.json
  * cb - callback

* `opts.packageFilter(pkg, pkgfile, dir)` - transform the parsed package.json contents before looking at the "main" field
  * pkg - package data
  * pkgfile - path to package.json
  * dir - directory that contains package.json

* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package
  * pkg - package data
  * path - the path being resolved
  * relativePath - the path relative from the package.json location
  * returns - a relative path that will be joined from the package.json location

* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this)

  For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function
    * request - the import specifier being resolved
    * start - lookup path
    * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
    * opts - the resolution options

* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this)
    * request - the import specifier being resolved
    * start - lookup path
    * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
    * opts - the resolution options

* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"`

* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving.
This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag.
**Note:** this property is currently `true` by default but it will be changed to
`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*.

default `opts` values:

```js
{
    paths: [],
    basedir: __dirname,
    extensions: ['.js'],
    includeCoreModules: true,
    readFile: fs.readFile,
    isFile: function isFile(file, cb) {
        fs.stat(file, function (err, stat) {
            if (!err) {
                return cb(null, stat.isFile() || stat.isFIFO());
            }
            if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
            return cb(err);
        });
    },
    isDirectory: function isDirectory(dir, cb) {
        fs.stat(dir, function (err, stat) {
            if (!err) {
                return cb(null, stat.isDirectory());
            }
            if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
            return cb(err);
        });
    },
    realpath: function realpath(file, cb) {
        var realpath = typeof fs.realpath.native === 'function' ? fs.realpath.native : fs.realpath;
        realpath(file, function (realPathErr, realPath) {
            if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr);
            else cb(null, realPathErr ? file : realPath);
        });
    },
    readPackage: function defaultReadPackage(readFile, pkgfile, cb) {
        readFile(pkgfile, function (readFileErr, body) {
            if (readFileErr) cb(readFileErr);
            else {
                try {
                    var pkg = JSON.parse(body);
                    cb(null, pkg);
                } catch (jsonErr) {
                    cb(null);
                }
            }
        });
    },
    moduleDirectory: 'node_modules',
    preserveSymlinks: true
}
```

## resolve.sync(id, opts)

Synchronously resolve the module path string `id`, returning the result and
throwing an error when `id` can't be resolved.

options are:

* opts.basedir - directory to begin resolving from

* opts.extensions - array of file extensions to search in order

* opts.includeCoreModules - set to `false` to exclude node core modules (e.g. `fs`) from the search

* opts.readFileSync - how to read files synchronously

* opts.isFile - function to synchronously test whether a file exists

* opts.isDirectory - function to synchronously test whether a file exists and is a directory

* opts.realpathSync - function to synchronously resolve a potential symlink to its real path

* `opts.readPackageSync(readFileSync, pkgfile)` - function to synchronously read and parse a package.json file
  * readFileSync - the passed `opts.readFileSync` or `fs.readFileSync` if not specified
  * pkgfile - path to package.json

* `opts.packageFilter(pkg, dir)` - transform the parsed package.json contents before looking at the "main" field
  * pkg - package data
  * dir - directory that contains package.json (Note: the second argument will change to "pkgfile" in v2)

* `opts.pathFilter(pkg, path, relativePath)` - transform a path within a package
  * pkg - package data
  * path - the path being resolved
  * relativePath - the path relative from the package.json location
  * returns - a relative path that will be joined from the package.json location

* opts.paths - require.paths array to use if nothing is found on the normal `node_modules` recursive walk (probably don't use this)

  For advanced users, `paths` can also be a `opts.paths(request, start, opts)` function
    * request - the import specifier being resolved
    * start - lookup path
    * getNodeModulesDirs - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
    * opts - the resolution options

* `opts.packageIterator(request, start, opts)` - return the list of candidate paths where the packages sources may be found (probably don't use this)
    * request - the import specifier being resolved
    * start - lookup path
    * getPackageCandidates - a thunk (no-argument function) that returns the paths using standard `node_modules` resolution
    * opts - the resolution options

* opts.moduleDirectory - directory (or directories) in which to recursively look for modules. default: `"node_modules"`

* opts.preserveSymlinks - if true, doesn't resolve `basedir` to real path before resolving.
This is the way Node resolves dependencies when executed with the [--preserve-symlinks](https://nodejs.org/api/all.html#cli_preserve_symlinks) flag.
**Note:** this property is currently `true` by default but it will be changed to
`false` in the next major version because *Node's resolution algorithm does not preserve symlinks by default*.

default `opts` values:

```js
{
    paths: [],
    basedir: __dirname,
    extensions: ['.js'],
    includeCoreModules: true,
    readFileSync: fs.readFileSync,
    isFile: function isFile(file) {
        try {
            var stat = fs.statSync(file);
        } catch (e) {
            if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
            throw e;
        }
        return stat.isFile() || stat.isFIFO();
    },
    isDirectory: function isDirectory(dir) {
        try {
            var stat = fs.statSync(dir);
        } catch (e) {
            if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
            throw e;
        }
        return stat.isDirectory();
    },
    realpathSync: function realpathSync(file) {
        try {
            var realpath = typeof fs.realpathSync.native === 'function' ? fs.realpathSync.native : fs.realpathSync;
            return realpath(file);
        } catch (realPathErr) {
            if (realPathErr.code !== 'ENOENT') {
                throw realPathErr;
            }
        }
        return file;
    },
    readPackageSync: function defaultReadPackageSync(readFileSync, pkgfile) {
        var body = readFileSync(pkgfile);
        try {
            var pkg = JSON.parse(body);
            return pkg;
        } catch (jsonErr) {}
    },
    moduleDirectory: 'node_modules',
    preserveSymlinks: true
}
```

# install

With [npm](https://npmjs.org) do:

```sh
npm install resolve
```

# license

MIT

[1]: https://npmjs.org/package/resolve
[2]: https://versionbadg.es/browserify/resolve.svg
[5]: https://david-dm.org/browserify/resolve.svg
[6]: https://david-dm.org/browserify/resolve
[7]: https://david-dm.org/browserify/resolve/dev-status.svg
[8]: https://david-dm.org/browserify/resolve#info=devDependencies
[11]: https://nodei.co/npm/resolve.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/resolve.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/resolve.svg
[downloads-url]: https://npm-stat.com/charts.html?package=resolve
[codecov-image]: https://codecov.io/gh/browserify/resolve/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/browserify/resolve/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/browserify/resolve
[actions-url]: https://github.com/browserify/resolve/actions


code:
'use strict';

module.exports = require('./lib/sync');

license: mit


code:
var test = require('tape');
var keys = require('object-keys');
var semver = require('semver');

var resolve = require('../');

var brokenNode = semver.satisfies(process.version, '11.11 - 11.13');

test('core modules', function (t) {
    t.test('isCore()', function (st) {
        st.ok(resolve.isCore('fs'));
        st.ok(resolve.isCore('net'));
        st.ok(resolve.isCore('http'));

        st.ok(!resolve.isCore('seq'));
        st.ok(!resolve.isCore('../'));

        st.ok(!resolve.isCore('toString'));

        st.end();
    });

    t.test('core list', function (st) {
        var cores = keys(resolve.core);
        st.plan(cores.length);

        for (var i = 0; i < cores.length; ++i) {
            var mod = cores[i];
            // note: this must be require, not require.resolve, due to https://github.com/nodejs/node/issues/43274
            var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func
            t.comment(mod + ': ' + resolve.core[mod]);
            if (resolve.core[mod]) {
                st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw');
            } else if (brokenNode) {
                st.ok(true, 'this version of node is broken: attempting to require things that fail to resolve breaks "home_paths" tests');
            } else {
                st.throws(requireFunc, mod + ' not supported; requiring throws');
            }
        }

        st.end();
    });

    t.test('core via repl module', { skip: !resolve.core.repl }, function (st) {
        var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle
        if (!libs) {
            st.skip('module.builtinModules does not exist');
            return st.end();
        }
        for (var i = 0; i < libs.length; ++i) {
            var mod = libs[i];
            st.ok(resolve.core[mod], mod + ' is a core module');
            st.doesNotThrow(
                function () { require(mod); }, // eslint-disable-line no-loop-func
                'requiring ' + mod + ' does not throw'
            );
        }
        st.end();
    });

    t.test('core via builtinModules list', { skip: !resolve.core.module }, function (st) {
        var libs = require('module').builtinModules;
        if (!libs) {
            st.skip('module.builtinModules does not exist');
            return st.end();
        }
        var blacklist = [
            '_debug_agent',
            'v8/tools/tickprocessor-driver',
            'v8/tools/SourceMap',
            'v8/tools/tickprocessor',
            'v8/tools/profile'
        ];
        for (var i = 0; i < libs.length; ++i) {
            var mod = libs[i];
            if (blacklist.indexOf(mod) === -1) {
                st.ok(resolve.core[mod], mod + ' is a core module');
                st.doesNotThrow(
                    function () { require(mod); }, // eslint-disable-line no-loop-func
                    'requiring ' + mod + ' does not throw'
                );
            }
        }
        st.end();
    });

    t.end();
});


code:
var path = require('path');
var test = require('tape');
var resolve = require('../');

test('dotdot', function (t) {
    t.plan(4);
    var dir = path.join(__dirname, '/dotdot/abc');

    resolve('..', { basedir: dir }, function (err, res, pkg) {
        t.ifError(err);
        t.equal(res, path.join(__dirname, 'dotdot/index.js'));
    });

    resolve('.', { basedir: dir }, function (err, res, pkg) {
        t.ifError(err);
        t.equal(res, path.join(dir, 'index.js'));
    });
});

test('dotdot sync', function (t) {
    t.plan(2);
    var dir = path.join(__dirname, '/dotdot/abc');

    var a = resolve.sync('..', { basedir: dir });
    t.equal(a, path.join(__dirname, 'dotdot/index.js'));

    var b = resolve.sync('.', { basedir: dir });
    t.equal(b, path.join(dir, 'index.js'));
});


code:
var x = require('..');
console.log(x);


code:
var test = require('tape');
var path = require('path');
var resolve = require('../');

test('faulty basedir must produce error in windows', { skip: process.platform !== 'win32' }, function (t) {
    t.plan(1);

    var resolverDir = 'C:\\a\\b\\c\\d';

    resolve('tape/lib/test.js', { basedir: resolverDir }, function (err, res, pkg) {
        t.equal(!!err, true);
    });
});

test('non-existent basedir should not throw when preserveSymlinks is false', function (t) {
    t.plan(2);

    var opts = {
        basedir: path.join(path.sep, 'unreal', 'path', 'that', 'does', 'not', 'exist'),
        preserveSymlinks: false
    };

    var module = './dotdot/abc';

    resolve(module, opts, function (err, res) {
        t.equal(err.code, 'MODULE_NOT_FOUND');
        t.equal(res, undefined);
    });
});


code:
var path = require('path');
var test = require('tape');
var resolve = require('../');

test('filter', function (t) {
    t.plan(4);
    var dir = path.join(__dirname, 'resolver');
    var packageFilterArgs;
    resolve('./baz', {
        basedir: dir,
        packageFilter: function (pkg, pkgfile) {
            pkg.main = 'doom'; // eslint-disable-line no-param-reassign
            packageFilterArgs = [pkg, pkgfile];
            return pkg;
        }
    }, function (err, res, pkg) {
        if (err) t.fail(err);

        t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works');

        var packageData = packageFilterArgs[0];
        t.equal(pkg, packageData, 'first packageFilter argument is "pkg"');
        t.equal(packageData.main, 'doom', 'package "main" was altered');

        var packageFile = packageFilterArgs[1];
        t.equal(
            packageFile,
            path.join(dir, 'baz/package.json'),
            'second packageFilter argument is "pkgfile"'
        );

        t.end();
    });
});


code:
var path = require('path');
var test = require('tape');
var resolve = require('../');

test('filter', function (t) {
    var dir = path.join(__dirname, 'resolver');
    var packageFilterArgs;
    var res = resolve.sync('./baz', {
        basedir: dir,
        // NOTE: in v2.x, this will be `pkg, pkgfile, dir`, but must remain "broken" here in v1.x for compatibility
        packageFilter: function (pkg, /*pkgfile,*/ dir) { // eslint-disable-line spaced-comment
            pkg.main = 'doom'; // eslint-disable-line no-param-reassign
            packageFilterArgs = 'is 1.x' ? [pkg, dir] : [pkg, pkgfile, dir]; // eslint-disable-line no-constant-condition, no-undef
            return pkg;
        }
    });

    t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works');

    var packageData = packageFilterArgs[0];
    t.equal(packageData.main, 'doom', 'package "main" was altered');

    if (!'is 1.x') { // eslint-disable-line no-constant-condition
        var packageFile = packageFilterArgs[1];
        t.equal(packageFile, path.join(dir, 'baz', 'package.json'), 'package.json path is correct');
    }

    var packageDir = packageFilterArgs['is 1.x' ? 1 : 2]; // eslint-disable-line no-constant-condition
    // eslint-disable-next-line no-constant-condition
    t.equal(packageDir, path.join(dir, 'baz'), ('is 1.x' ? 'second' : 'third') + ' packageFilter argument is "dir"');

    t.end();
});


code:
'use strict';

var fs = require('fs');
var homedir = require('../lib/homedir');
var path = require('path');

var test = require('tape');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');
var mv = require('mv');
var copyDir = require('copy-dir');
var tmp = require('tmp');

var HOME = homedir();

var hnm = path.join(HOME, '.node_modules');
var hnl = path.join(HOME, '.node_libraries');

var resolve = require('../async');

function makeDir(t, dir, cb) {
    mkdirp(dir, function (err) {
        if (err) {
            cb(err);
        } else {
            t.teardown(function cleanup() {
                rimraf.sync(dir);
            });
            cb();
        }
    });
}

function makeTempDir(t, dir, cb) {
    if (fs.existsSync(dir)) {
        var tmpResult = tmp.dirSync();
        t.teardown(tmpResult.removeCallback);
        var backup = path.join(tmpResult.name, path.basename(dir));
        mv(dir, backup, function (err) {
            if (err) {
                cb(err);
            } else {
                t.teardown(function () {
                    mv(backup, dir, cb);
                });
                makeDir(t, dir, cb);
            }
        });
    } else {
        makeDir(t, dir, cb);
    }
}

test('homedir module paths', function (t) {
    t.plan(7);

    makeTempDir(t, hnm, function (err) {
        t.error(err, 'no error with HNM temp dir');
        if (err) {
            return t.end();
        }

        var bazHNMDir = path.join(hnm, 'baz');
        var dotMainDir = path.join(hnm, 'dot_main');
        copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNMDir);
        copyDir.sync(path.join(__dirname, 'resolver/dot_main'), dotMainDir);

        var bazPkg = { name: 'baz', main: 'quux.js' };
        var dotMainPkg = { main: 'index' };

        var bazHNMmain = path.join(bazHNMDir, 'quux.js');
        t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`');
        var dotMainMain = path.join(dotMainDir, 'index.js');
        t.equal(require.resolve('dot_main'), dotMainMain, 'sanity check: require.resolve finds `dot_main`');

        makeTempDir(t, hnl, function (err) {
            t.error(err, 'no error with HNL temp dir');
            if (err) {
                return t.end();
            }
            var bazHNLDir = path.join(hnl, 'baz');
            copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNLDir);

            var dotSlashMainDir = path.join(hnl, 'dot_slash_main');
            var dotSlashMainMain = path.join(dotSlashMainDir, 'index.js');
            var dotSlashMainPkg = { main: 'index' };
            copyDir.sync(path.join(__dirname, 'resolver/dot_slash_main'), dotSlashMainDir);

            t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`');
            t.equal(require.resolve('dot_slash_main'), dotSlashMainMain, 'sanity check: require.resolve finds HNL `dot_slash_main`');

            t.test('with temp dirs', function (st) {
                st.plan(3);

                st.test('just in `$HOME/.node_modules`', function (s2t) {
                    s2t.plan(3);

                    resolve('dot_main', function (err, res, pkg) {
                        s2t.error(err, 'no error resolving `dot_main`');
                        s2t.equal(res, dotMainMain, '`dot_main` resolves in `$HOME/.node_modules`');
                        s2t.deepEqual(pkg, dotMainPkg);
                    });
                });

                st.test('just in `$HOME/.node_libraries`', function (s2t) {
                    s2t.plan(3);

                    resolve('dot_slash_main', function (err, res, pkg) {
                        s2t.error(err, 'no error resolving `dot_slash_main`');
                        s2t.equal(res, dotSlashMainMain, '`dot_slash_main` resolves in `$HOME/.node_libraries`');
                        s2t.deepEqual(pkg, dotSlashMainPkg);
                    });
                });

                st.test('in `$HOME/.node_libraries` and `$HOME/.node_modules`', function (s2t) {
                    s2t.plan(3);

                    resolve('baz', function (err, res, pkg) {
                        s2t.error(err, 'no error resolving `baz`');
                        s2t.equal(res, bazHNMmain, '`baz` resolves in `$HOME/.node_modules` when in both');
                        s2t.deepEqual(pkg, bazPkg);
                    });
                });
            });
        });
    });
});


code:
'use strict';

var fs = require('fs');
var homedir = require('../lib/homedir');
var path = require('path');

var test = require('tape');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');
var mv = require('mv');
var copyDir = require('copy-dir');
var tmp = require('tmp');

var HOME = homedir();

var hnm = path.join(HOME, '.node_modules');
var hnl = path.join(HOME, '.node_libraries');

var resolve = require('../sync');

function makeDir(t, dir, cb) {
    mkdirp(dir, function (err) {
        if (err) {
            cb(err);
        } else {
            t.teardown(function cleanup() {
                rimraf.sync(dir);
            });
            cb();
        }
    });
}

function makeTempDir(t, dir, cb) {
    if (fs.existsSync(dir)) {
        var tmpResult = tmp.dirSync();
        t.teardown(tmpResult.removeCallback);
        var backup = path.join(tmpResult.name, path.basename(dir));
        mv(dir, backup, function (err) {
            if (err) {
                cb(err);
            } else {
                t.teardown(function () {
                    mv(backup, dir, cb);
                });
                makeDir(t, dir, cb);
            }
        });
    } else {
        makeDir(t, dir, cb);
    }
}

test('homedir module paths', function (t) {
    t.plan(7);

    makeTempDir(t, hnm, function (err) {
        t.error(err, 'no error with HNM temp dir');
        if (err) {
            return t.end();
        }

        var bazHNMDir = path.join(hnm, 'baz');
        var dotMainDir = path.join(hnm, 'dot_main');
        copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNMDir);
        copyDir.sync(path.join(__dirname, 'resolver/dot_main'), dotMainDir);

        var bazHNMmain = path.join(bazHNMDir, 'quux.js');
        t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`');
        var dotMainMain = path.join(dotMainDir, 'index.js');
        t.equal(require.resolve('dot_main'), dotMainMain, 'sanity check: require.resolve finds `dot_main`');

        makeTempDir(t, hnl, function (err) {
            t.error(err, 'no error with HNL temp dir');
            if (err) {
                return t.end();
            }
            var bazHNLDir = path.join(hnl, 'baz');
            copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNLDir);

            var dotSlashMainDir = path.join(hnl, 'dot_slash_main');
            var dotSlashMainMain = path.join(dotSlashMainDir, 'index.js');
            copyDir.sync(path.join(__dirname, 'resolver/dot_slash_main'), dotSlashMainDir);

            t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`');
            t.equal(require.resolve('dot_slash_main'), dotSlashMainMain, 'sanity check: require.resolve finds HNL `dot_slash_main`');

            t.test('with temp dirs', function (st) {
                st.plan(3);

                st.test('just in `$HOME/.node_modules`', function (s2t) {
                    s2t.plan(1);

                    var res = resolve('dot_main');
                    s2t.equal(res, dotMainMain, '`dot_main` resolves in `$HOME/.node_modules`');
                });

                st.test('just in `$HOME/.node_libraries`', function (s2t) {
                    s2t.plan(1);

                    var res = resolve('dot_slash_main');
                    s2t.equal(res, dotSlashMainMain, '`dot_slash_main` resolves in `$HOME/.node_libraries`');
                });

                st.test('in `$HOME/.node_libraries` and `$HOME/.node_modules`', function (s2t) {
                    s2t.plan(1);

                    var res = resolve('baz');
                    s2t.equal(res, bazHNMmain, '`baz` resolves in `$HOME/.node_modules` when in both');
                });
            });
        });
    });
});


code:
var path = require('path');
var test = require('tape');
var resolve = require('../');

test('mock', function (t) {
    t.plan(8);

    var files = {};
    files[path.resolve('/foo/bar/baz.js')] = 'beep';

    var dirs = {};
    dirs[path.resolve('/foo/bar')] = true;

    function opts(basedir) {
        return {
            basedir: path.resolve(basedir),
            isFile: function (file, cb) {
                cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file)));
            },
            isDirectory: function (dir, cb) {
                cb(null, !!dirs[path.resolve(dir)]);
            },
            readFile: function (file, cb) {
                cb(null, files[path.resolve(file)]);
            },
            realpath: function (file, cb) {
                cb(null, file);
            }
        };
    }

    resolve('./baz', opts('/foo/bar'), function (err, res, pkg) {
        if (err) return t.fail(err);
        t.equal(res, path.resolve('/foo/bar/baz.js'));
        t.equal(pkg, undefined);
    });

    resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) {
        if (err) return t.fail(err);
        t.equal(res, path.resolve('/foo/bar/baz.js'));
        t.equal(pkg, undefined);
    });

    resolve('baz', opts('/foo/bar'), function (err, res) {
        t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });

    resolve('../baz', opts('/foo/bar'), function (err, res) {
        t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });
});

test('mock from package', function (t) {
    t.plan(8);

    var files = {};
    files[path.resolve('/foo/bar/baz.js')] = 'beep';

    var dirs = {};
    dirs[path.resolve('/foo/bar')] = true;

    function opts(basedir) {
        return {
            basedir: path.resolve(basedir),
            isFile: function (file, cb) {
                cb(null, Object.prototype.hasOwnProperty.call(files, file));
            },
            isDirectory: function (dir, cb) {
                cb(null, !!dirs[path.resolve(dir)]);
            },
            'package': { main: 'bar' },
            readFile: function (file, cb) {
                cb(null, files[file]);
            },
            realpath: function (file, cb) {
                cb(null, file);
            }
        };
    }

    resolve('./baz', opts('/foo/bar'), function (err, res, pkg) {
        if (err) return t.fail(err);
        t.equal(res, path.resolve('/foo/bar/baz.js'));
        t.equal(pkg && pkg.main, 'bar');
    });

    resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) {
        if (err) return t.fail(err);
        t.equal(res, path.resolve('/foo/bar/baz.js'));
        t.equal(pkg && pkg.main, 'bar');
    });

    resolve('baz', opts('/foo/bar'), function (err, res) {
        t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });

    resolve('../baz', opts('/foo/bar'), function (err, res) {
        t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });
});

test('mock package', function (t) {
    t.plan(2);

    var files = {};
    files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep';
    files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({
        main: './baz.js'
    });

    var dirs = {};
    dirs[path.resolve('/foo')] = true;
    dirs[path.resolve('/foo/node_modules')] = true;

    function opts(basedir) {
        return {
            basedir: path.resolve(basedir),
            isFile: function (file, cb) {
                cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file)));
            },
            isDirectory: function (dir, cb) {
                cb(null, !!dirs[path.resolve(dir)]);
            },
            readFile: function (file, cb) {
                cb(null, files[path.resolve(file)]);
            },
            realpath: function (file, cb) {
                cb(null, file);
            }
        };
    }

    resolve('bar', opts('/foo'), function (err, res, pkg) {
        if (err) return t.fail(err);
        t.equal(res, path.resolve('/foo/node_modules/bar/baz.js'));
        t.equal(pkg && pkg.main, './baz.js');
    });
});

test('mock package from package', function (t) {
    t.plan(2);

    var files = {};
    files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep';
    files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({
        main: './baz.js'
    });

    var dirs = {};
    dirs[path.resolve('/foo')] = true;
    dirs[path.resolve('/foo/node_modules')] = true;

    function opts(basedir) {
        return {
            basedir: path.resolve(basedir),
            isFile: function (file, cb) {
                cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file)));
            },
            isDirectory: function (dir, cb) {
                cb(null, !!dirs[path.resolve(dir)]);
            },
            'package': { main: 'bar' },
            readFile: function (file, cb) {
                cb(null, files[path.resolve(file)]);
            },
            realpath: function (file, cb) {
                cb(null, file);
            }
        };
    }

    resolve('bar', opts('/foo'), function (err, res, pkg) {
        if (err) return t.fail(err);
        t.equal(res, path.resolve('/foo/node_modules/bar/baz.js'));
        t.equal(pkg && pkg.main, './baz.js');
    });
});

test('symlinked', function (t) {
    t.plan(4);

    var files = {};
    files[path.resolve('/foo/bar/baz.js')] = 'beep';
    files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep';

    var dirs = {};
    dirs[path.resolve('/foo/bar')] = true;
    dirs[path.resolve('/foo/bar/symlinked')] = true;

    function opts(basedir) {
        return {
            preserveSymlinks: false,
            basedir: path.resolve(basedir),
            isFile: function (file, cb) {
                cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file)));
            },
            isDirectory: function (dir, cb) {
                cb(null, !!dirs[path.resolve(dir)]);
            },
            readFile: function (file, cb) {
                cb(null, files[path.resolve(file)]);
            },
            realpath: function (file, cb) {
                var resolved = path.resolve(file);

                if (resolved.indexOf('symlinked') >= 0) {
                    cb(null, resolved);
                    return;
                }

                var ext = path.extname(resolved);

                if (ext) {
                    var dir = path.dirname(resolved);
                    var base = path.basename(resolved);
                    cb(null, path.join(dir, 'symlinked', base));
                } else {
                    cb(null, path.join(resolved, 'symlinked'));
                }
            }
        };
    }

    resolve('./baz', opts('/foo/bar'), function (err, res, pkg) {
        if (err) return t.fail(err);
        t.equal(res, path.resolve('/foo/bar/symlinked/baz.js'));
        t.equal(pkg, undefined);
    });

    resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) {
        if (err) return t.fail(err);
        t.equal(res, path.resolve('/foo/bar/symlinked/baz.js'));
        t.equal(pkg, undefined);
    });
});

test('readPackage', function (t) {
    t.plan(3);

    var files = {};
    files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep';
    files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({
        main: './baz.js'
    });
    files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop';

    var dirs = {};
    dirs[path.resolve('/foo')] = true;
    dirs[path.resolve('/foo/node_modules')] = true;

    function opts(basedir) {
        return {
            basedir: path.resolve(basedir),
            isFile: function (file, cb) {
                cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file)));
            },
            isDirectory: function (dir, cb) {
                cb(null, !!dirs[path.resolve(dir)]);
            },
            'package': { main: 'bar' },
            readFile: function (file, cb) {
                cb(null, files[path.resolve(file)]);
            },
            realpath: function (file, cb) {
                cb(null, file);
            }
        };
    }

    t.test('with readFile', function (st) {
        st.plan(3);

        resolve('bar', opts('/foo'), function (err, res, pkg) {
            st.error(err);
            st.equal(res, path.resolve('/foo/node_modules/bar/baz.js'));
            st.equal(pkg && pkg.main, './baz.js');
        });
    });

    var readPackage = function (readFile, file, cb) {
        var barPackage = path.join('bar', 'package.json');
        if (file.slice(-barPackage.length) === barPackage) {
            cb(null, { main: './something-else.js' });
        } else {
            cb(null, JSON.parse(files[path.resolve(file)]));
        }
    };

    t.test('with readPackage', function (st) {
        st.plan(3);

        var options = opts('/foo');
        delete options.readFile;
        options.readPackage = readPackage;
        resolve('bar', options, function (err, res, pkg) {
            st.error(err);
            st.equal(res, path.resolve('/foo/node_modules/bar/something-else.js'));
            st.equal(pkg && pkg.main, './something-else.js');
        });
    });

    t.test('with readFile and readPackage', function (st) {
        st.plan(1);

        var options = opts('/foo');
        options.readPackage = readPackage;
        resolve('bar', options, function (err) {
            st.throws(function () { throw err; }, TypeError, 'errors when both readFile and readPackage are provided');
        });
    });
});


code:
var path = require('path');
var test = require('tape');
var resolve = require('../');

test('mock', function (t) {
    t.plan(4);

    var files = {};
    files[path.resolve('/foo/bar/baz.js')] = 'beep';

    var dirs = {};
    dirs[path.resolve('/foo/bar')] = true;

    function opts(basedir) {
        return {
            basedir: path.resolve(basedir),
            isFile: function (file) {
                return Object.prototype.hasOwnProperty.call(files, path.resolve(file));
            },
            isDirectory: function (dir) {
                return !!dirs[path.resolve(dir)];
            },
            readFileSync: function (file) {
                return files[path.resolve(file)];
            },
            realpathSync: function (file) {
                return file;
            }
        };
    }

    t.equal(
        resolve.sync('./baz', opts('/foo/bar')),
        path.resolve('/foo/bar/baz.js')
    );

    t.equal(
        resolve.sync('./baz.js', opts('/foo/bar')),
        path.resolve('/foo/bar/baz.js')
    );

    t.throws(function () {
        resolve.sync('baz', opts('/foo/bar'));
    });

    t.throws(function () {
        resolve.sync('../baz', opts('/foo/bar'));
    });
});

test('mock package', function (t) {
    t.plan(1);

    var files = {};
    files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep';
    files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({
        main: './baz.js'
    });

    var dirs = {};
    dirs[path.resolve('/foo')] = true;
    dirs[path.resolve('/foo/node_modules')] = true;

    function opts(basedir) {
        return {
            basedir: path.resolve(basedir),
            isFile: function (file) {
                return Object.prototype.hasOwnProperty.call(files, path.resolve(file));
            },
            isDirectory: function (dir) {
                return !!dirs[path.resolve(dir)];
            },
            readFileSync: function (file) {
                return files[path.resolve(file)];
            },
            realpathSync: function (file) {
                return file;
            }
        };
    }

    t.equal(
        resolve.sync('bar', opts('/foo')),
        path.resolve('/foo/node_modules/bar/baz.js')
    );
});

test('symlinked', function (t) {
    t.plan(2);

    var files = {};
    files[path.resolve('/foo/bar/baz.js')] = 'beep';
    files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep';

    var dirs = {};
    dirs[path.resolve('/foo/bar')] = true;
    dirs[path.resolve('/foo/bar/symlinked')] = true;

    function opts(basedir) {
        return {
            preserveSymlinks: false,
            basedir: path.resolve(basedir),
            isFile: function (file) {
                return Object.prototype.hasOwnProperty.call(files, path.resolve(file));
            },
            isDirectory: function (dir) {
                return !!dirs[path.resolve(dir)];
            },
            readFileSync: function (file) {
                return files[path.resolve(file)];
            },
            realpathSync: function (file) {
                var resolved = path.resolve(file);

                if (resolved.indexOf('symlinked') >= 0) {
                    return resolved;
                }

                var ext = path.extname(resolved);

                if (ext) {
                    var dir = path.dirname(resolved);
                    var base = path.basename(resolved);
                    return path.join(dir, 'symlinked', base);
                }
                return path.join(resolved, 'symlinked');
            }
        };
    }

    t.equal(
        resolve.sync('./baz', opts('/foo/bar')),
        path.resolve('/foo/bar/symlinked/baz.js')
    );

    t.equal(
        resolve.sync('./baz.js', opts('/foo/bar')),
        path.resolve('/foo/bar/symlinked/baz.js')
    );
});

test('readPackageSync', function (t) {
    t.plan(3);

    var files = {};
    files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep';
    files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({
        main: './baz.js'
    });
    files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop';

    var dirs = {};
    dirs[path.resolve('/foo')] = true;
    dirs[path.resolve('/foo/node_modules')] = true;

    function opts(basedir, useReadPackage) {
        return {
            basedir: path.resolve(basedir),
            isFile: function (file) {
                return Object.prototype.hasOwnProperty.call(files, path.resolve(file));
            },
            isDirectory: function (dir) {
                return !!dirs[path.resolve(dir)];
            },
            readFileSync: useReadPackage ? null : function (file) {
                return files[path.resolve(file)];
            },
            realpathSync: function (file) {
                return file;
            }
        };
    }
    t.test('with readFile', function (st) {
        st.plan(1);

        st.equal(
            resolve.sync('bar', opts('/foo')),
            path.resolve('/foo/node_modules/bar/baz.js')
        );
    });

    var readPackageSync = function (readFileSync, file) {
        if (file.indexOf(path.join('bar', 'package.json')) >= 0) {
            return { main: './something-else.js' };
        }
        return JSON.parse(files[path.resolve(file)]);
    };

    t.test('with readPackage', function (st) {
        st.plan(1);

        var options = opts('/foo');
        delete options.readFileSync;
        options.readPackageSync = readPackageSync;

        st.equal(
            resolve.sync('bar', options),
            path.resolve('/foo/node_modules/bar/something-else.js')
        );
    });

    t.test('with readFile and readPackage', function (st) {
        st.plan(1);

        var options = opts('/foo');
        options.readPackageSync = readPackageSync;
        st.throws(
            function () { resolve.sync('bar', options); },
            TypeError,
            'errors when both readFile and readPackage are provided'
        );
    });
});


code:
var path = require('path');
var test = require('tape');
var resolve = require('../');

test('moduleDirectory strings', function (t) {
    t.plan(4);
    var dir = path.join(__dirname, 'module_dir');
    var xopts = {
        basedir: dir,
        moduleDirectory: 'xmodules'
    };
    resolve('aaa', xopts, function (err, res, pkg) {
        t.ifError(err);
        t.equal(res, path.join(dir, '/xmodules/aaa/index.js'));
    });

    var yopts = {
        basedir: dir,
        moduleDirectory: 'ymodules'
    };
    resolve('aaa', yopts, function (err, res, pkg) {
        t.ifError(err);
        t.equal(res, path.join(dir, '/ymodules/aaa/index.js'));
    });
});

test('moduleDirectory array', function (t) {
    t.plan(6);
    var dir = path.join(__dirname, 'module_dir');
    var aopts = {
        basedir: dir,
        moduleDirectory: ['xmodules', 'ymodules', 'zmodules']
    };
    resolve('aaa', aopts, function (err, res, pkg) {
        t.ifError(err);
        t.equal(res, path.join(dir, '/xmodules/aaa/index.js'));
    });

    var bopts = {
        basedir: dir,
        moduleDirectory: ['zmodules', 'ymodules', 'xmodules']
    };
    resolve('aaa', bopts, function (err, res, pkg) {
        t.ifError(err);
        t.equal(res, path.join(dir, '/ymodules/aaa/index.js'));
    });

    var copts = {
        basedir: dir,
        moduleDirectory: ['xmodules', 'ymodules', 'zmodules']
    };
    resolve('bbb', copts, function (err, res, pkg) {
        t.ifError(err);
        t.equal(res, path.join(dir, '/zmodules/bbb/main.js'));
    });
});


code: module.exports = function (x) { return x * 100; };


code: module.exports = function (x) { return x + 100; };


code: module.exports = function (n) { return n * 111; };


code:
var test = require('tape');
var path = require('path');
var parse = path.parse || require('path-parse');
var keys = require('object-keys');

var nodeModulesPaths = require('../lib/node-modules-paths');

var verifyDirs = function verifyDirs(t, start, dirs, moduleDirectories, paths) {
    var moduleDirs = [].concat(moduleDirectories || 'node_modules');
    if (paths) {
        for (var k = 0; k < paths.length; ++k) {
            moduleDirs.push(path.basename(paths[k]));
        }
    }

    var foundModuleDirs = {};
    var uniqueDirs = {};
    var parsedDirs = {};
    for (var i = 0; i < dirs.length; ++i) {
        var parsed = parse(dirs[i]);
        if (!foundModuleDirs[parsed.base]) { foundModuleDirs[parsed.base] = 0; }
        foundModuleDirs[parsed.base] += 1;
        parsedDirs[parsed.dir] = true;
        uniqueDirs[dirs[i]] = true;
    }
    t.equal(keys(parsedDirs).length >= start.split(path.sep).length, true, 'there are >= dirs than "start" has');
    var foundModuleDirNames = keys(foundModuleDirs);
    t.deepEqual(foundModuleDirNames, moduleDirs, 'all desired module dirs were found');
    t.equal(keys(uniqueDirs).length, dirs.length, 'all dirs provided were unique');

    var counts = {};
    for (var j = 0; j < foundModuleDirNames.length; ++j) {
        counts[foundModuleDirs[j]] = true;
    }
    t.equal(keys(counts).length, 1, 'all found module directories had the same count');
};

test('node-modules-paths', function (t) {
    t.test('no options', function (t) {
        var start = path.join(__dirname, 'resolver');
        var dirs = nodeModulesPaths(start);

        verifyDirs(t, start, dirs);

        t.end();
    });

    t.test('empty options', function (t) {
        var start = path.join(__dirname, 'resolver');
        var dirs = nodeModulesPaths(start, {});

        verifyDirs(t, start, dirs);

        t.end();
    });

    t.test('with paths=array option', function (t) {
        var start = path.join(__dirname, 'resolver');
        var paths = ['a', 'b'];
        var dirs = nodeModulesPaths(start, { paths: paths });

        verifyDirs(t, start, dirs, null, paths);

        t.end();
    });

    t.test('with paths=function option', function (t) {
        var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) {
            return getNodeModulesDirs().concat(path.join(absoluteStart, 'not node modules', request));
        };

        var start = path.join(__dirname, 'resolver');
        var dirs = nodeModulesPaths(start, { paths: paths }, 'pkg');

        verifyDirs(t, start, dirs, null, [path.join(start, 'not node modules', 'pkg')]);

        t.end();
    });

    t.test('with paths=function skipping node modules resolution', function (t) {
        var paths = function paths(request, absoluteStart, getNodeModulesDirs, opts) {
            return [];
        };
        var start = path.join(__dirname, 'resolver');
        var dirs = nodeModulesPaths(start, { paths: paths });
        t.deepEqual(dirs, [], 'no node_modules was computed');
        t.end();
    });

    t.test('with moduleDirectory option', function (t) {
        var start = path.join(__dirname, 'resolver');
        var moduleDirectory = 'not node modules';
        var dirs = nodeModulesPaths(start, { moduleDirectory: moduleDirectory });

        verifyDirs(t, start, dirs, moduleDirectory);

        t.end();
    });

    t.test('with 1 moduleDirectory and paths options', function (t) {
        var start = path.join(__dirname, 'resolver');
        var paths = ['a', 'b'];
        var moduleDirectory = 'not node modules';
        var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectory });

        verifyDirs(t, start, dirs, moduleDirectory, paths);

        t.end();
    });

    t.test('with 1+ moduleDirectory and paths options', function (t) {
        var start = path.join(__dirname, 'resolver');
        var paths = ['a', 'b'];
        var moduleDirectories = ['not node modules', 'other modules'];
        var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories });

        verifyDirs(t, start, dirs, moduleDirectories, paths);

        t.end();
    });

    t.test('combine paths correctly on Windows', function (t) {
        var start = 'C:\\Users\\username\\myProject\\src';
        var paths = [];
        var moduleDirectories = ['node_modules', start];
        var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories });

        t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir');

        t.end();
    });

    t.test('combine paths correctly on non-Windows', { skip: process.platform === 'win32' }, function (t) {
        var start = '/Users/username/git/myProject/src';
        var paths = [];
        var moduleDirectories = ['node_modules', '/Users/username/git/myProject/src'];
        var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories });

        t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir');

        t.end();
    });
});


code:
var fs = require('fs');
var path = require('path');
var test = require('tape');
var resolve = require('../');

test('$NODE_PATH', function (t) {
    t.plan(8);

    var isDir = function (dir, cb) {
        if (dir === '/node_path' || dir === 'node_path/x') {
            return cb(null, true);
        }
        fs.stat(dir, function (err, stat) {
            if (!err) {
                return cb(null, stat.isDirectory());
            }
            if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
            return cb(err);
        });
    };

    resolve('aaa', {
        paths: [
            path.join(__dirname, '/node_path/x'),
            path.join(__dirname, '/node_path/y')
        ],
        basedir: __dirname,
        isDirectory: isDir
    }, function (err, res) {
        t.error(err);
        t.equal(res, path.join(__dirname, '/node_path/x/aaa/index.js'), 'aaa resolves');
    });

    resolve('bbb', {
        paths: [
            path.join(__dirname, '/node_path/x'),
            path.join(__dirname, '/node_path/y')
        ],
        basedir: __dirname,
        isDirectory: isDir
    }, function (err, res) {
        t.error(err);
        t.equal(res, path.join(__dirname, '/node_path/y/bbb/index.js'), 'bbb resolves');
    });

    resolve('ccc', {
        paths: [
            path.join(__dirname, '/node_path/x'),
            path.join(__dirname, '/node_path/y')
        ],
        basedir: __dirname,
        isDirectory: isDir
    }, function (err, res) {
        t.error(err);
        t.equal(res, path.join(__dirname, '/node_path/x/ccc/index.js'), 'ccc resolves');
    });

    // ensure that relative paths still resolve against the regular `node_modules` correctly
    resolve('tap', {
        paths: [
            'node_path'
        ],
        basedir: path.join(__dirname, 'node_path/x'),
        isDirectory: isDir
    }, function (err, res) {
        var root = require('tap/package.json').main; // eslint-disable-line global-require
        t.error(err);
        t.equal(res, path.resolve(__dirname, '..', 'node_modules/tap', root), 'tap resolves');
    });
});


code:
var test = require('tape');
var resolve = require('../');

test('nonstring', function (t) {
    t.plan(1);
    resolve(555, function (err, res, pkg) {
        t.ok(err);
    });
});


code:
var path = require('path');
var test = require('tape');
var resolve = require('../');

var resolverDir = path.join(__dirname, '/pathfilter/deep_ref');

var pathFilterFactory = function (t) {
    return function (pkg, x, remainder) {
        t.equal(pkg.version, '1.2.3');
        t.equal(x, path.join(resolverDir, 'node_modules/deep/ref'));
        t.equal(remainder, 'ref');
        return 'alt';
    };
};

test('#62: deep module references and the pathFilter', function (t) {
    t.test('deep/ref.js', function (st) {
        st.plan(3);

        resolve('deep/ref', { basedir: resolverDir }, function (err, res, pkg) {
            if (err) st.fail(err);

            st.equal(pkg.version, '1.2.3');
            st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js'));
        });

        var res = resolve.sync('deep/ref', { basedir: resolverDir });
        st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js'));
    });

    t.test('deep/deeper/ref', function (st) {
        st.plan(4);

        resolve(
            'deep/deeper/ref',
            { basedir: resolverDir },
            function (err, res, pkg) {
                if (err) t.fail(err);
                st.notEqual(pkg, undefined);
                st.equal(pkg.version, '1.2.3');
                st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js'));
            }
        );

        var res = resolve.sync(
            'deep/deeper/ref',
            { basedir: resolverDir }
        );
        st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js'));
    });

    t.test('deep/ref alt', function (st) {
        st.plan(8);

        var pathFilter = pathFilterFactory(st);

        var res = resolve.sync(
            'deep/ref',
            { basedir: resolverDir, pathFilter: pathFilter }
        );
        st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js'));

        resolve(
            'deep/ref',
            { basedir: resolverDir, pathFilter: pathFilter },
            function (err, res, pkg) {
                if (err) st.fail(err);
                st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js'));
                st.end();
            }
        );
    });

    t.end();
});


code:
var path = require('path');
var test = require('tape');
var resolve = require('../');

test('precedence', function (t) {
    t.plan(3);
    var dir = path.join(__dirname, 'precedence/aaa');

    resolve('./', { basedir: dir }, function (err, res, pkg) {
        t.ifError(err);
        t.equal(res, path.join(dir, 'index.js'));
        t.equal(pkg.name, 'resolve');
    });
});

test('./ should not load ${dir}.js', function (t) { // eslint-disable-line no-template-curly-in-string
    t.plan(1);
    var dir = path.join(__dirname, 'precedence/bbb');

    resolve('./', { basedir: dir }, function (err, res, pkg) {
        t.ok(err);
    });
});


code: console.log(require('./')); // should throw


code:
var path = require('path');
var fs = require('fs');
var test = require('tape');
var resolve = require('../');
var async = require('../async');

test('`./async` entry point', function (t) {
    t.equal(resolve, async, '`./async` entry point is the same as `main`');
    t.end();
});

test('async foo', function (t) {
    t.plan(12);
    var dir = path.join(__dirname, 'resolver');

    resolve('./foo', { basedir: dir }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo.js'));
        t.equal(pkg && pkg.name, 'resolve');
    });

    resolve('./foo.js', { basedir: dir }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo.js'));
        t.equal(pkg && pkg.name, 'resolve');
    });

    resolve('./foo', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo.js'));
        t.equal(pkg && pkg.main, 'resolver');
    });

    resolve('./foo.js', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo.js'));
        t.equal(pkg.main, 'resolver');
    });

    resolve('./foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo.js'));
    });

    resolve('foo', { basedir: dir }, function (err) {
        t.equal(err.message, "Cannot find module 'foo' from '" + path.resolve(dir) + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });

    // Test that filename is reported as the "from" value when passed.
    resolve('foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err) {
        t.equal(err.message, "Cannot find module 'foo' from '" + path.join(dir, 'baz.js') + "'");
    });
});

test('bar', function (t) {
    t.plan(6);
    var dir = path.join(__dirname, 'resolver');

    resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('foo', { basedir: dir + '/bar', 'package': { main: 'bar' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js'));
        t.equal(pkg.main, 'bar');
    });
});

test('baz', function (t) {
    t.plan(4);
    var dir = path.join(__dirname, 'resolver');

    resolve('./baz', { basedir: dir }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'baz/quux.js'));
        t.equal(pkg.main, 'quux.js');
    });

    resolve('./baz', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'baz/quux.js'));
        t.equal(pkg.main, 'quux.js');
    });
});

test('biz', function (t) {
    t.plan(24);
    var dir = path.join(__dirname, 'resolver/biz/node_modules');

    resolve('./grux', { basedir: dir }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'grux/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('./grux', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'grux/index.js'));
        t.equal(pkg.main, 'biz');
    });

    resolve('./garply', { basedir: dir }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'garply/lib/index.js'));
        t.equal(pkg.main, './lib');
    });

    resolve('./garply', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'garply/lib/index.js'));
        t.equal(pkg.main, './lib');
    });

    resolve('tiv', { basedir: dir + '/grux' }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'tiv/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('tiv', { basedir: dir + '/grux', 'package': { main: 'grux' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'tiv/index.js'));
        t.equal(pkg.main, 'grux');
    });

    resolve('tiv', { basedir: dir + '/garply' }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'tiv/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('tiv', { basedir: dir + '/garply', 'package': { main: './lib' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'tiv/index.js'));
        t.equal(pkg.main, './lib');
    });

    resolve('grux', { basedir: dir + '/tiv' }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'grux/index.js'));
        t.equal(pkg, undefined);
    });

    resolve('grux', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'grux/index.js'));
        t.equal(pkg.main, 'tiv');
    });

    resolve('garply', { basedir: dir + '/tiv' }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'garply/lib/index.js'));
        t.equal(pkg.main, './lib');
    });

    resolve('garply', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'garply/lib/index.js'));
        t.equal(pkg.main, './lib');
    });
});

test('quux', function (t) {
    t.plan(2);
    var dir = path.join(__dirname, 'resolver/quux');

    resolve('./foo', { basedir: dir, 'package': { main: 'quux' } }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'foo/index.js'));
        t.equal(pkg.main, 'quux');
    });
});

test('normalize', function (t) {
    t.plan(2);
    var dir = path.join(__dirname, 'resolver/biz/node_modules/grux');

    resolve('../grux', { basedir: dir }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'index.js'));
        t.equal(pkg, undefined);
    });
});

test('cup', function (t) {
    t.plan(5);
    var dir = path.join(__dirname, 'resolver');

    resolve('./cup', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'cup.coffee'));
    });

    resolve('./cup.coffee', { basedir: dir }, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'cup.coffee'));
    });

    resolve('./cup', { basedir: dir, extensions: ['.js'] }, function (err, res) {
        t.equal(err.message, "Cannot find module './cup' from '" + path.resolve(dir) + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });

    // Test that filename is reported as the "from" value when passed.
    resolve('./cup', { basedir: dir, extensions: ['.js'], filename: path.join(dir, 'cupboard.js') }, function (err, res) {
        t.equal(err.message, "Cannot find module './cup' from '" + path.join(dir, 'cupboard.js') + "'");
    });
});

test('mug', function (t) {
    t.plan(3);
    var dir = path.join(__dirname, 'resolver');

    resolve('./mug', { basedir: dir }, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'mug.js'));
    });

    resolve('./mug', { basedir: dir, extensions: ['.coffee', '.js'] }, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, '/mug.coffee'));
    });

    resolve('./mug', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) {
        t.equal(res, path.join(dir, '/mug.js'));
    });
});

test('other path', function (t) {
    t.plan(6);
    var resolverDir = path.join(__dirname, 'resolver');
    var dir = path.join(resolverDir, 'bar');
    var otherDir = path.join(resolverDir, 'other_path');

    resolve('root', { basedir: dir, paths: [otherDir] }, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(resolverDir, 'other_path/root.js'));
    });

    resolve('lib/other-lib', { basedir: dir, paths: [otherDir] }, function (err, res) {
        if (err) t.fail(err);
        t.equal(res, path.join(resolverDir, 'other_path/lib/other-lib.js'));
    });

    resolve('root', { basedir: dir }, function (err, res) {
        t.equal(err.message, "Cannot find module 'root' from '" + path.resolve(dir) + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });

    resolve('zzz', { basedir: dir, paths: [otherDir] }, function (err, res) {
        t.equal(err.message, "Cannot find module 'zzz' from '" + path.resolve(dir) + "'");
        t.equal(err.code, 'MODULE_NOT_FOUND');
    });
});

test('path iterator', function (t) {
    t.plan(2);

    var resolverDir = path.join(__dirname, 'resolver');

    var exactIterator = function (x, start, getPackageCandidates, opts) {
        return [path.join(resolverDir, x)];
    };

    resolve('baz', { packageIterator: exactIterator }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(resolverDir, 'baz/quux.js'));
        t.equal(pkg && pkg.name, 'baz');
    });
});

test('incorrect main', function (t) {
    t.plan(1);

    var resolverDir = path.join(__dirname, 'resolver');
    var dir = path.join(resolverDir, 'incorrect_main');

    resolve('./incorrect_main', { basedir: resolverDir }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'index.js'));
    });
});

test('missing index', function (t) {
    t.plan(2);

    var resolverDir = path.join(__dirname, 'resolver');
    resolve('./missing_index', { basedir: resolverDir }, function (err, res, pkg) {
        t.ok(err instanceof Error);
        t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code');
    });
});

test('missing main', function (t) {
    t.plan(1);

    var resolverDir = path.join(__dirname, 'resolver');

    resolve('./missing_main', { basedir: resolverDir }, function (err, res, pkg) {
        t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code');
    });
});

test('null main', function (t) {
    t.plan(1);

    var resolverDir = path.join(__dirname, 'resolver');

    resolve('./null_main', { basedir: resolverDir }, function (err, res, pkg) {
        t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code');
    });
});

test('main: false', function (t) {
    t.plan(2);

    var basedir = path.join(__dirname, 'resolver');
    var dir = path.join(basedir, 'false_main');
    resolve('./false_main', { basedir: basedir }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(
            res,
            path.join(dir, 'index.js'),
            '`"main": false`: resolves to `index.js`'
        );
        t.deepEqual(pkg, {
            name: 'false_main',
            main: false
        });
    });
});

test('without basedir', function (t) {
    t.plan(1);

    var dir = path.join(__dirname, 'resolver/without_basedir');
    var tester = require(path.join(dir, 'main.js')); // eslint-disable-line global-require

    tester(t, function (err, res, pkg) {
        if (err) {
            t.fail(err);
        } else {
            t.equal(res, path.join(dir, 'node_modules/mymodule.js'));
        }
    });
});

test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) {
    t.plan(2);

    var dir = path.join(__dirname, 'resolver');

    resolve('./foo', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'same_names/foo.js'));
    });

    resolve('./foo/', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'same_names/foo/index.js'));
    });
});

test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) {
    t.plan(2);

    var dir = path.join(__dirname, 'resolver');

    resolve('./', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'same_names/foo/index.js'));
    });

    resolve('.', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) {
        if (err) t.fail(err);
        t.equal(res, path.join(dir, 'same_names/foo/index.js'));
    });
});

test('async: #121 - treating an existing file as a dir when no basedir', function (t) {
    var testFile = path.basename(__filename);

    t.test('sanity check', function (st) {
        st.plan(1);
        resolve('./' + testFile, function (err, res, pkg) {
            if (err) t.fail(err);
            st.equal(res, __filename, 'sanity check');
        });
    });

    t.test('with a fake directory', function (st) {
        st.plan(4);

        resolve('./' + testFile + '/blah', function (err, res, pkg) {
            st.ok(err, 'there is an error');
            st.notOk(res, 'no result');

            st.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve');
            st.equal(
                err && err.message,
                'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'',
                'can not find nonexistent module'
            );
            st.end();
        });
    });

    t.end();
});

test('async dot main', function (t) {
    var start = new Date();
    t.plan(3);
    resolve('./resolver/dot_main', function (err, ret) {
        t.notOk(err);
        t.equal(ret, path.join(__dirname, 'resolver/dot_main/index.js'));
        t.ok(new Date() - start < 50, 'resolve.sync timedout');
        t.end();
    });
});

test('async dot slash main', function (t) {
    var start = new Date();
    t.plan(3);
    resolve('./resolver/dot_slash_main', function (err, ret) {
        t.notOk(err);
        t.equal(ret, path.join(__dirname, 'resolver/dot_slash_main/index.js'));
        t.ok(new Date() - start < 50, 'resolve.sync timedout');
        t.end();
    });
});

test('not a directory', function (t) {
    t.plan(6);
    var path = './foo';
    resolve(path, { basedir: __filename }, function (err, res, pkg) {
        t.ok(err, 'a non-directory errors');
        t.equal(arguments.length, 1);
        t.equal(res, undefined);
        t.equal(pkg, undefined);

        t.equal(err && err.message, 'Cannot find module \'' + path + '\' from \'' + __filename + '\'');
        t.equal(err && err.code, 'MODULE_NOT_FOUND');
    });
});

test('non-string "main" field in package.json', function (t) {
    t.plan(5);

    var dir = path.join(__dirname, 'resolver');
    resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) {
        t.ok(err, 'errors on non-string main');
        t.equal(err.message, 'package “invalid_main” `main` must be a string');
        t.equal(err.code, 'INVALID_PACKAGE_MAIN');
        t.equal(res, undefined, 'res is undefined');
        t.equal(pkg, undefined, 'pkg is undefined');
    });
});

test('non-string "main" field in package.json', function (t) {
    t.plan(5);

    var dir = path.join(__dirname, 'resolver');
    resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) {
        t.ok(err, 'errors on non-string main');
        t.equal(err.message, 'package “invalid_main” `main` must be a string');
        t.equal(err.code, 'INVALID_PACKAGE_MAIN');
        t.equal(res, undefined, 'res is undefined');
        t.equal(pkg, undefined, 'pkg is undefined');
    });
});

test('browser field in package.json', function (t) {
    t.plan(3);

    var dir = path.join(__dirname, 'resolver');
    resolve(
        './browser_field',
        {
            basedir: dir,
            packageFilter: function packageFilter(pkg) {
                if (pkg.browser) {
                    pkg.main = pkg.browser; // eslint-disable-line no-param-reassign
                    delete pkg.browser; // eslint-disable-line no-param-reassign
                }
                return pkg;
            }
        },
        function (err, res, pkg) {
            if (err) t.fail(err);
            t.equal(res, path.join(dir, 'browser_field', 'b.js'));
            t.equal(pkg && pkg.main, 'b');
            t.equal(pkg && pkg.browser, undefined);
        }
    );
});

test('absolute paths', function (t) {
    t.plan(4);

    var extensionless = __filename.slice(0, -path.extname(__filename).length);

    resolve(__filename, function (err, res) {
        t.equal(
            res,
            __filename,
            'absolute path to this file resolves'
        );
    });
    resolve(extensionless, function (err, res) {
        t.equal(
            res,
            __filename,
            'extensionless absolute path to this file resolves'
        );
    });
    resolve(__filename, { basedir: process.cwd() }, function (err, res) {
        t.equal(
            res,
            __filename,
            'absolute path to this file with a basedir resolves'
        );
    });
    resolve(extensionless, { basedir: process.cwd() }, function (err, res) {
        t.equal(
            res,
            __filename,
            'extensionless absolute path to this file with a basedir resolves'
        );
    });
});

var malformedDir = path.join(__dirname, 'resolver/malformed_package_json');
test('malformed package.json', { skip: !fs.existsSync(malformedDir) }, function (t) {
    /* eslint operator-linebreak: ["error", "before"], function-paren-newline: "off" */
    t.plan(
        (3 * 3) // 3 sets of 3 assertions in the final callback
        + 2 // 1 readPackage call with malformed package.json
    );

    var basedir = malformedDir;
    var expected = path.join(basedir, 'index.js');

    resolve('./index.js', { basedir: basedir }, function (err, res, pkg) {
        t.error(err, 'no error');
        t.equal(res, expected, 'malformed package.json is silently ignored');
        t.equal(pkg, undefined, 'malformed package.json gives an undefined `pkg` argument');
    });

    resolve(
        './index.js',
        {
            basedir: basedir,
            packageFilter: function (pkg, pkgfile, dir) {
                t.fail('should not reach here');
            }
        },
        function (err, res, pkg) {
            t.error(err, 'with packageFilter: no error');
            t.equal(res, expected, 'with packageFilter: malformed package.json is silently ignored');
            t.equal(pkg, undefined, 'with packageFilter: malformed package.json gives an undefined `pkg` argument');
        }
    );

    resolve(
        './index.js',
        {
            basedir: basedir,
            readPackage: function (readFile, pkgfile, cb) {
                t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path');
                readFile(pkgfile, function (err, result) {
                    try {
                        cb(null, JSON.parse(result));
                    } catch (e) {
                        t.ok(e instanceof SyntaxError, 'readPackage: malformed package.json parses as a syntax error');
                        cb(null);
                    }
                });
            }
        },
        function (err, res, pkg) {
            t.error(err, 'with readPackage: no error');
            t.equal(res, expected, 'with readPackage: malformed package.json is silently ignored');
            t.equal(pkg, undefined, 'with readPackage: malformed package.json gives an undefined `pkg` argument');
        }
    );
});


code:
// this is the actual main file 'index.js', not 'wrong.js' like the package.json would indicate
module.exports = 1;


ljharb-monorepo-symlink-test

postinstall: lerna bootstrap

test: node packages/package-a

license: MIT


code:
'use strict';

var assert = require('assert');
var path = require('path');
var resolve = require('resolve');

var basedir = __dirname + '/node_modules/@my-scope/package-b';

var expected = path.join(__dirname, '../../node_modules/jquery/dist/jquery.js');

/*
 * preserveSymlinks === false
 * will search NPM package from
 * - packages/package-b/node_modules
 * - packages/node_modules
 * - node_modules
 */
assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: false }), expected);
assert.equal(resolve.sync('../../node_modules/jquery', { basedir: basedir, preserveSymlinks: false }), expected);

/*
 * preserveSymlinks === true
 * will search NPM package from
 * - packages/package-a/node_modules/@my-scope/packages/package-b/node_modules
 * - packages/package-a/node_modules/@my-scope/packages/node_modules
 * - packages/package-a/node_modules/@my-scope/node_modules
 * - packages/package-a/node_modules/node_modules
 * - packages/package-a/node_modules
 * - packages/node_modules
 * - node_modules
 */
assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: true }), expected);
assert.equal(resolve.sync('../../../../../node_modules/jquery', { basedir: basedir, preserveSymlinks: true }), expected);

console.log(' * all monorepo paths successfully resolved through symlinks');


@my-scope/package-a

test: echo "Error: run tests from root" && exit 1


code:
var a = require.resolve('buffer/').replace(process.cwd(), '$CWD');
var b;
var c;

var test = function test() {
    console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false'));
    console.log(b, ': preserveSymlinks true');
    console.log(c, ': preserveSymlinks false');

    if (a !== b && a !== c) {
        throw 'async: no match';
    }
    console.log('async: success! a matched either b or c\n');
};

require('resolve')('buffer/', { preserveSymlinks: true }, function (err, result) {
    if (err) { throw err; }
    b = result.replace(process.cwd(), '$CWD');
    if (b && c) { test(); }
});
require('resolve')('buffer/', { preserveSymlinks: false }, function (err, result) {
    if (err) { throw err; }
    c = result.replace(process.cwd(), '$CWD');
    if (b && c) { test(); }
});


mylib

test: echo "Error: no test specified" && exit 1

license: ISC


code:
var a = require.resolve('buffer/').replace(process.cwd(), '$CWD');
var b = require('resolve').sync('buffer/', { preserveSymlinks: true }).replace(process.cwd(), '$CWD');
var c = require('resolve').sync('buffer/', { preserveSymlinks: false }).replace(process.cwd(), '$CWD');

console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false'));
console.log(b, ': preserveSymlinks true');
console.log(c, ': preserveSymlinks false');

if (a !== b && a !== c) {
    throw 'sync: no match';
}
console.log('sync: success! a matched either b or c\n');


code:
var resolve = require('../../../');

module.exports = function (t, cb) {
    resolve('mymodule', null, cb);
};


code:
var path = require('path');
var fs = require('fs');
var test = require('tape');

var resolve = require('../');
var sync = require('../sync');

var requireResolveSupportsPaths = require.resolve.length > 1
    && !(/^v12\.[012]\./).test(process.version); // broken in v12.0-12.2, see https://github.com/nodejs/node/issues/27794

var requireResolveDefaultPathsBroken = (/^v8\.9\.|^v9\.[01]\.0|^v9\.2\./).test(process.version);
// broken in node v8.9.x, v9.0, v9.1, v9.2.x. see https://github.com/nodejs/node/pull/17113

test('`./sync` entry point', function (t) {
    t.equal(resolve.sync, sync, '`./sync` entry point is the same as `.sync` on `main`');
    t.end();
});

test('foo', function (t) {
    var dir = path.join(__dirname, 'resolver');

    t.equal(
        resolve.sync('./foo', { basedir: dir }),
        path.join(dir, 'foo.js'),
        './foo'
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./foo', { basedir: dir }),
            require.resolve('./foo', { paths: [dir] }),
            './foo: resolve.sync === require.resolve'
        );
    }

    t.equal(
        resolve.sync('./foo.js', { basedir: dir }),
        path.join(dir, 'foo.js'),
        './foo.js'
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./foo.js', { basedir: dir }),
            require.resolve('./foo.js', { paths: [dir] }),
            './foo.js: resolve.sync === require.resolve'
        );
    }

    t.equal(
        resolve.sync('./foo.js', { basedir: dir, filename: path.join(dir, 'bar.js') }),
        path.join(dir, 'foo.js')
    );

    t.throws(function () {
        resolve.sync('foo', { basedir: dir });
    });

    // Test that filename is reported as the "from" value when passed.
    t.throws(
        function () {
            resolve.sync('foo', { basedir: dir, filename: path.join(dir, 'bar.js') });
        },
        {
            name: 'Error',
            message: "Cannot find module 'foo' from '" + path.join(dir, 'bar.js') + "'"
        }
    );

    t.end();
});

test('bar', function (t) {
    var dir = path.join(__dirname, 'resolver');

    var basedir = path.join(dir, 'bar');

    t.equal(
        resolve.sync('foo', { basedir: basedir }),
        path.join(dir, 'bar/node_modules/foo/index.js'),
        'foo in bar'
    );
    if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('foo', { basedir: basedir }),
            require.resolve('foo', { paths: [basedir] }),
            'foo in bar: resolve.sync === require.resolve'
        );
    }

    t.end();
});

test('baz', function (t) {
    var dir = path.join(__dirname, 'resolver');

    t.equal(
        resolve.sync('./baz', { basedir: dir }),
        path.join(dir, 'baz/quux.js'),
        './baz'
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./baz', { basedir: dir }),
            require.resolve('./baz', { paths: [dir] }),
            './baz: resolve.sync === require.resolve'
        );
    }

    t.end();
});

test('biz', function (t) {
    var dir = path.join(__dirname, 'resolver/biz/node_modules');

    t.equal(
        resolve.sync('./grux', { basedir: dir }),
        path.join(dir, 'grux/index.js')
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./grux', { basedir: dir }),
            require.resolve('./grux', { paths: [dir] }),
            './grux: resolve.sync === require.resolve'
        );
    }

    var tivDir = path.join(dir, 'grux');
    t.equal(
        resolve.sync('tiv', { basedir: tivDir }),
        path.join(dir, 'tiv/index.js')
    );
    if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('tiv', { basedir: tivDir }),
            require.resolve('tiv', { paths: [tivDir] }),
            'tiv: resolve.sync === require.resolve'
        );
    }

    var gruxDir = path.join(dir, 'tiv');
    t.equal(
        resolve.sync('grux', { basedir: gruxDir }),
        path.join(dir, 'grux/index.js')
    );
    if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('grux', { basedir: gruxDir }),
            require.resolve('grux', { paths: [gruxDir] }),
            'grux: resolve.sync === require.resolve'
        );
    }

    t.end();
});

test('normalize', function (t) {
    var dir = path.join(__dirname, 'resolver/biz/node_modules/grux');

    t.equal(
        resolve.sync('../grux', { basedir: dir }),
        path.join(dir, 'index.js')
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('../grux', { basedir: dir }),
            require.resolve('../grux', { paths: [dir] }),
            '../grux: resolve.sync === require.resolve'
        );
    }

    t.end();
});

test('cup', function (t) {
    var dir = path.join(__dirname, 'resolver');

    t.equal(
        resolve.sync('./cup', {
            basedir: dir,
            extensions: ['.js', '.coffee']
        }),
        path.join(dir, 'cup.coffee'),
        './cup -> ./cup.coffee'
    );

    t.equal(
        resolve.sync('./cup.coffee', { basedir: dir }),
        path.join(dir, 'cup.coffee'),
        './cup.coffee'
    );

    t.throws(function () {
        resolve.sync('./cup', {
            basedir: dir,
            extensions: ['.js']
        });
    });

    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./cup.coffee', { basedir: dir, extensions: ['.js', '.coffee'] }),
            require.resolve('./cup.coffee', { paths: [dir] }),
            './cup.coffee: resolve.sync === require.resolve'
        );
    }

    t.end();
});

test('mug', function (t) {
    var dir = path.join(__dirname, 'resolver');

    t.equal(
        resolve.sync('./mug', { basedir: dir }),
        path.join(dir, 'mug.js'),
        './mug -> ./mug.js'
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./mug', { basedir: dir }),
            require.resolve('./mug', { paths: [dir] }),
            './mug: resolve.sync === require.resolve'
        );
    }

    t.equal(
        resolve.sync('./mug', {
            basedir: dir,
            extensions: ['.coffee', '.js']
        }),
        path.join(dir, 'mug.coffee'),
        './mug -> ./mug.coffee'
    );

    t.equal(
        resolve.sync('./mug', {
            basedir: dir,
            extensions: ['.js', '.coffee']
        }),
        path.join(dir, 'mug.js'),
        './mug -> ./mug.js'
    );

    t.end();
});

test('other path', function (t) {
    var resolverDir = path.join(__dirname, 'resolver');
    var dir = path.join(resolverDir, 'bar');
    var otherDir = path.join(resolverDir, 'other_path');

    t.equal(
        resolve.sync('root', {
            basedir: dir,
            paths: [otherDir]
        }),
        path.join(resolverDir, 'other_path/root.js')
    );

    t.equal(
        resolve.sync('lib/other-lib', {
            basedir: dir,
            paths: [otherDir]
        }),
        path.join(resolverDir, 'other_path/lib/other-lib.js')
    );

    t.throws(function () {
        resolve.sync('root', { basedir: dir });
    });

    t.throws(function () {
        resolve.sync('zzz', {
            basedir: dir,
            paths: [otherDir]
        });
    });

    t.end();
});

test('path iterator', function (t) {
    var resolverDir = path.join(__dirname, 'resolver');

    var exactIterator = function (x, start, getPackageCandidates, opts) {
        return [path.join(resolverDir, x)];
    };

    t.equal(
        resolve.sync('baz', { packageIterator: exactIterator }),
        path.join(resolverDir, 'baz/quux.js')
    );

    t.end();
});

test('incorrect main', function (t) {
    var resolverDir = path.join(__dirname, 'resolver');
    var dir = path.join(resolverDir, 'incorrect_main');

    t.equal(
        resolve.sync('./incorrect_main', { basedir: resolverDir }),
        path.join(dir, 'index.js')
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./incorrect_main', { basedir: resolverDir }),
            require.resolve('./incorrect_main', { paths: [resolverDir] }),
            './incorrect_main: resolve.sync === require.resolve'
        );
    }

    t.end();
});

test('missing index', function (t) {
    t.plan(requireResolveSupportsPaths ? 2 : 1);

    var resolverDir = path.join(__dirname, 'resolver');
    try {
        resolve.sync('./missing_index', { basedir: resolverDir });
        t.fail('did not fail');
    } catch (err) {
        t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code');
    }
    if (requireResolveSupportsPaths) {
        try {
            require.resolve('./missing_index', { basedir: resolverDir });
            t.fail('require.resolve did not fail');
        } catch (err) {
            t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code');
        }
    }
});

test('missing main', function (t) {
    var resolverDir = path.join(__dirname, 'resolver');

    try {
        resolve.sync('./missing_main', { basedir: resolverDir });
        t.fail('require.resolve did not fail');
    } catch (err) {
        t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code');
    }
    if (requireResolveSupportsPaths) {
        try {
            resolve.sync('./missing_main', { basedir: resolverDir });
            t.fail('require.resolve did not fail');
        } catch (err) {
            t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code');
        }
    }

    t.end();
});

test('null main', function (t) {
    var resolverDir = path.join(__dirname, 'resolver');

    try {
        resolve.sync('./null_main', { basedir: resolverDir });
        t.fail('require.resolve did not fail');
    } catch (err) {
        t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code');
    }
    if (requireResolveSupportsPaths) {
        try {
            resolve.sync('./null_main', { basedir: resolverDir });
            t.fail('require.resolve did not fail');
        } catch (err) {
            t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code');
        }
    }

    t.end();
});

test('main: false', function (t) {
    var basedir = path.join(__dirname, 'resolver');
    var dir = path.join(basedir, 'false_main');
    t.equal(
        resolve.sync('./false_main', { basedir: basedir }),
        path.join(dir, 'index.js'),
        '`"main": false`: resolves to `index.js`'
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./false_main', { basedir: basedir }),
            require.resolve('./false_main', { paths: [basedir] }),
            '`"main": false`: resolve.sync === require.resolve'
        );
    }

    t.end();
});

var stubStatSync = function stubStatSync(fn) {
    var statSync = fs.statSync;
    try {
        fs.statSync = function () {
            throw new EvalError('Unknown Error');
        };
        return fn();
    } finally {
        fs.statSync = statSync;
    }
};

test('#79 - re-throw non ENOENT errors from stat', function (t) {
    var dir = path.join(__dirname, 'resolver');

    stubStatSync(function () {
        t.throws(function () {
            resolve.sync('foo', { basedir: dir });
        }, /Unknown Error/);
    });

    t.end();
});

test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) {
    var dir = path.join(__dirname, 'resolver');
    var basedir = path.join(dir, 'same_names');

    t.equal(
        resolve.sync('./foo', { basedir: basedir }),
        path.join(dir, 'same_names/foo.js')
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./foo', { basedir: basedir }),
            require.resolve('./foo', { paths: [basedir] }),
            './foo: resolve.sync === require.resolve'
        );
    }

    t.equal(
        resolve.sync('./foo/', { basedir: basedir }),
        path.join(dir, 'same_names/foo/index.js')
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./foo/', { basedir: basedir }),
            require.resolve('./foo/', { paths: [basedir] }),
            './foo/: resolve.sync === require.resolve'
        );
    }

    t.end();
});

test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) {
    var dir = path.join(__dirname, 'resolver');
    var basedir = path.join(dir, 'same_names/foo');

    t.equal(
        resolve.sync('./', { basedir: basedir }),
        path.join(dir, 'same_names/foo/index.js'),
        './'
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./', { basedir: basedir }),
            require.resolve('./', { paths: [basedir] }),
            './: resolve.sync === require.resolve'
        );
    }

    t.equal(
        resolve.sync('.', { basedir: basedir }),
        path.join(dir, 'same_names/foo/index.js'),
        '.'
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('.', { basedir: basedir }),
            require.resolve('.', { paths: [basedir] }),
            '.: resolve.sync === require.resolve',
            { todo: true }
        );
    }

    t.end();
});

test('sync: #121 - treating an existing file as a dir when no basedir', function (t) {
    var testFile = path.basename(__filename);

    t.test('sanity check', function (st) {
        st.equal(
            resolve.sync('./' + testFile),
            __filename,
            'sanity check'
        );
        st.equal(
            resolve.sync('./' + testFile),
            require.resolve('./' + testFile),
            'sanity check: resolve.sync === require.resolve'
        );

        st.end();
    });

    t.test('with a fake directory', function (st) {
        function run() { return resolve.sync('./' + testFile + '/blah'); }

        st.throws(run, 'throws an error');

        try {
            run();
        } catch (e) {
            st.equal(e.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve');
            st.equal(
                e.message,
                'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'',
                'can not find nonexistent module'
            );
        }

        st.end();
    });

    t.end();
});

test('sync dot main', function (t) {
    var start = new Date();

    t.equal(
        resolve.sync('./resolver/dot_main'),
        path.join(__dirname, 'resolver/dot_main/index.js'),
        './resolver/dot_main'
    );
    t.equal(
        resolve.sync('./resolver/dot_main'),
        require.resolve('./resolver/dot_main'),
        './resolver/dot_main: resolve.sync === require.resolve'
    );

    t.ok(new Date() - start < 50, 'resolve.sync timedout');

    t.end();
});

test('sync dot slash main', function (t) {
    var start = new Date();

    t.equal(
        resolve.sync('./resolver/dot_slash_main'),
        path.join(__dirname, 'resolver/dot_slash_main/index.js')
    );
    t.equal(
        resolve.sync('./resolver/dot_slash_main'),
        require.resolve('./resolver/dot_slash_main'),
        './resolver/dot_slash_main: resolve.sync === require.resolve'
    );

    t.ok(new Date() - start < 50, 'resolve.sync timedout');

    t.end();
});

test('not a directory', function (t) {
    var path = './foo';
    try {
        resolve.sync(path, { basedir: __filename });
        t.fail();
    } catch (err) {
        t.ok(err, 'a non-directory errors');
        t.equal(err && err.message, 'Cannot find module \'' + path + "' from '" + __filename + "'");
        t.equal(err && err.code, 'MODULE_NOT_FOUND');
    }
    t.end();
});

test('non-string "main" field in package.json', function (t) {
    var dir = path.join(__dirname, 'resolver');
    try {
        var result = resolve.sync('./invalid_main', { basedir: dir });
        t.equal(result, undefined, 'result should not exist');
        t.fail('should not get here');
    } catch (err) {
        t.ok(err, 'errors on non-string main');
        t.equal(err.message, 'package “invalid_main” `main` must be a string');
        t.equal(err.code, 'INVALID_PACKAGE_MAIN');
    }
    t.end();
});

test('non-string "main" field in package.json', function (t) {
    var dir = path.join(__dirname, 'resolver');
    try {
        var result = resolve.sync('./invalid_main', { basedir: dir });
        t.equal(result, undefined, 'result should not exist');
        t.fail('should not get here');
    } catch (err) {
        t.ok(err, 'errors on non-string main');
        t.equal(err.message, 'package “invalid_main” `main` must be a string');
        t.equal(err.code, 'INVALID_PACKAGE_MAIN');
    }
    t.end();
});

test('browser field in package.json', function (t) {
    var dir = path.join(__dirname, 'resolver');
    var res = resolve.sync('./browser_field', {
        basedir: dir,
        packageFilter: function packageFilter(pkg) {
            if (pkg.browser) {
                pkg.main = pkg.browser; // eslint-disable-line no-param-reassign
                delete pkg.browser; // eslint-disable-line no-param-reassign
            }
            return pkg;
        }
    });
    t.equal(res, path.join(dir, 'browser_field', 'b.js'));
    t.end();
});

test('absolute paths', function (t) {
    var extensionless = __filename.slice(0, -path.extname(__filename).length);

    t.equal(
        resolve.sync(__filename),
        __filename,
        'absolute path to this file resolves'
    );
    t.equal(
        resolve.sync(__filename),
        require.resolve(__filename),
        'absolute path to this file: resolve.sync === require.resolve'
    );

    t.equal(
        resolve.sync(extensionless),
        __filename,
        'extensionless absolute path to this file resolves'
    );
    t.equal(
        resolve.sync(__filename),
        require.resolve(__filename),
        'absolute path to this file: resolve.sync === require.resolve'
    );

    t.equal(
        resolve.sync(__filename, { basedir: process.cwd() }),
        __filename,
        'absolute path to this file with a basedir resolves'
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync(__filename, { basedir: process.cwd() }),
            require.resolve(__filename, { paths: [process.cwd()] }),
            'absolute path to this file + basedir: resolve.sync === require.resolve'
        );
    }

    t.equal(
        resolve.sync(extensionless, { basedir: process.cwd() }),
        __filename,
        'extensionless absolute path to this file with a basedir resolves'
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync(extensionless, { basedir: process.cwd() }),
            require.resolve(extensionless, { paths: [process.cwd()] }),
            'extensionless absolute path to this file + basedir: resolve.sync === require.resolve'
        );
    }

    t.end();
});

var malformedDir = path.join(__dirname, 'resolver/malformed_package_json');
test('malformed package.json', { skip: !fs.existsSync(malformedDir) }, function (t) {
    t.plan(5 + (requireResolveSupportsPaths ? 1 : 0));

    var basedir = malformedDir;
    var expected = path.join(basedir, 'index.js');

    t.equal(
        resolve.sync('./index.js', { basedir: basedir }),
        expected,
        'malformed package.json is silently ignored'
    );
    if (requireResolveSupportsPaths) {
        t.equal(
            resolve.sync('./index.js', { basedir: basedir }),
            require.resolve('./index.js', { paths: [basedir] }),
            'malformed package.json: resolve.sync === require.resolve'
        );
    }

    var res1 = resolve.sync(
        './index.js',
        {
            basedir: basedir,
            packageFilter: function (pkg, pkgfile, dir) {
                t.fail('should not reach here');
            }
        }
    );

    t.equal(
        res1,
        expected,
        'with packageFilter: malformed package.json is silently ignored'
    );

    var res2 = resolve.sync(
        './index.js',
        {
            basedir: basedir,
            readPackageSync: function (readFileSync, pkgfile) {
                t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path');
                var result = String(readFileSync(pkgfile));
                try {
                    return JSON.parse(result);
                } catch (e) {
                    t.ok(e instanceof SyntaxError, 'readPackageSync: malformed package.json parses as a syntax error');
                }
            }
        }
    );

    t.equal(
        res2,
        expected,
        'with readPackageSync: malformed package.json is silently ignored'
    );
});