@rollup/plugin-node-resolve 8.0.0 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
1
1
  # @rollup/plugin-node-resolve ChangeLog
2
2
 
3
+ ## v9.0.0
4
+
5
+ _2020-08-13_
6
+
7
+ ### Breaking Changes
8
+
9
+ - chore: update dependencies (e632469)
10
+
11
+ ### Updates
12
+
13
+ - refactor: remove deep-freeze from dependencies (#529)
14
+ - chore: clean up changelog (84dfddb)
15
+
16
+ ## v8.4.0
17
+
18
+ _2020-07-12_
19
+
20
+ ### Features
21
+
22
+ - feat: preserve search params and hashes (#487)
23
+ - feat: support .js imports in TypeScript (#480)
24
+
25
+ ### Updates
26
+
27
+ - docs: fix named export use in readme (#456)
28
+ - docs: correct mainFields valid values (#469)
29
+
30
+ ## v8.1.0
31
+
32
+ _2020-06-22_
33
+
34
+ ### Features
35
+
36
+ - feat: add native node es modules support (#413)
37
+
38
+ ## v8.0.1
39
+
40
+ _2020-06-05_
41
+
42
+ ### Bugfixes
43
+
44
+ - fix: handle nested entry modules with the resolveOnly option (#430)
45
+
3
46
  ## v8.0.0
4
47
 
5
48
  _2020-05-20_
package/README.md CHANGED
@@ -28,7 +28,7 @@ npm install @rollup/plugin-node-resolve --save-dev
28
28
  Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
29
29
 
30
30
  ```js
31
- import resolve from '@rollup/plugin-node-resolve';
31
+ import { nodeResolve } from '@rollup/plugin-node-resolve';
32
32
 
33
33
  export default {
34
34
  input: 'src/index.js',
@@ -36,7 +36,7 @@ export default {
36
36
  dir: 'output',
37
37
  format: 'cjs'
38
38
  },
39
- plugins: [resolve()]
39
+ plugins: [nodeResolve()]
40
40
  };
41
41
  ```
42
42
 
@@ -107,7 +107,7 @@ Locks the module search within specified path (e.g. chroot). Modules defined out
107
107
 
108
108
  Type: `Array[...String]`<br>
109
109
  Default: `['module', 'main']`<br>
110
- Valid values: `['browser', 'jsnext', 'module', 'main']`
110
+ Valid values: `['browser', 'jsnext:main', 'module', 'main']`
111
111
 
112
112
  Specifies the properties to scan within a `package.json`, used to determine the bundle entry point. The order of property names is significant, as the first-found property is used as the resolved entry point. If the array contains `'browser'`, key/values specified in the `package.json` `browser` property will be used.
113
113
 
@@ -0,0 +1,540 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
+
7
+ var path = require('path');
8
+ var builtinList = _interopDefault(require('builtin-modules'));
9
+ var deepMerge = _interopDefault(require('deepmerge'));
10
+ var isModule = _interopDefault(require('is-module'));
11
+ var fs = require('fs');
12
+ var fs__default = _interopDefault(fs);
13
+ var util = require('util');
14
+ var pluginutils = require('@rollup/pluginutils');
15
+ var resolveModule = _interopDefault(require('resolve'));
16
+
17
+ const exists = util.promisify(fs__default.exists);
18
+ const readFile = util.promisify(fs__default.readFile);
19
+ const realpath = util.promisify(fs__default.realpath);
20
+ const stat = util.promisify(fs__default.stat);
21
+
22
+ const onError = (error) => {
23
+ if (error.code === 'ENOENT') {
24
+ return false;
25
+ }
26
+ throw error;
27
+ };
28
+
29
+ const makeCache = (fn) => {
30
+ const cache = new Map();
31
+ const wrapped = async (param, done) => {
32
+ if (cache.has(param) === false) {
33
+ cache.set(
34
+ param,
35
+ fn(param).catch((err) => {
36
+ cache.delete(param);
37
+ throw err;
38
+ })
39
+ );
40
+ }
41
+
42
+ try {
43
+ const result = cache.get(param);
44
+ const value = await result;
45
+ return done(null, value);
46
+ } catch (error) {
47
+ return done(error);
48
+ }
49
+ };
50
+
51
+ wrapped.clear = () => cache.clear();
52
+
53
+ return wrapped;
54
+ };
55
+
56
+ const isDirCached = makeCache(async (file) => {
57
+ try {
58
+ const stats = await stat(file);
59
+ return stats.isDirectory();
60
+ } catch (error) {
61
+ return onError(error);
62
+ }
63
+ });
64
+
65
+ const isFileCached = makeCache(async (file) => {
66
+ try {
67
+ const stats = await stat(file);
68
+ return stats.isFile();
69
+ } catch (error) {
70
+ return onError(error);
71
+ }
72
+ });
73
+
74
+ const readCachedFile = makeCache(readFile);
75
+
76
+ const resolveId = util.promisify(resolveModule);
77
+
78
+ // returns the imported package name for bare module imports
79
+ function getPackageName(id) {
80
+ if (id.startsWith('.') || id.startsWith('/')) {
81
+ return null;
82
+ }
83
+
84
+ const split = id.split('/');
85
+
86
+ // @my-scope/my-package/foo.js -> @my-scope/my-package
87
+ // @my-scope/my-package -> @my-scope/my-package
88
+ if (split[0][0] === '@') {
89
+ return `${split[0]}/${split[1]}`;
90
+ }
91
+
92
+ // my-package/foo.js -> my-package
93
+ // my-package -> my-package
94
+ return split[0];
95
+ }
96
+
97
+ function getMainFields(options) {
98
+ let mainFields;
99
+ if (options.mainFields) {
100
+ ({ mainFields } = options);
101
+ } else {
102
+ mainFields = ['module', 'main'];
103
+ }
104
+ if (options.browser && mainFields.indexOf('browser') === -1) {
105
+ return ['browser'].concat(mainFields);
106
+ }
107
+ if (!mainFields.length) {
108
+ throw new Error('Please ensure at least one `mainFields` value is specified');
109
+ }
110
+ return mainFields;
111
+ }
112
+
113
+ function getPackageInfo(options) {
114
+ const { cache, extensions, pkg, mainFields, preserveSymlinks, useBrowserOverrides } = options;
115
+ let { pkgPath } = options;
116
+
117
+ if (cache.has(pkgPath)) {
118
+ return cache.get(pkgPath);
119
+ }
120
+
121
+ // browserify/resolve doesn't realpath paths returned in its packageFilter callback
122
+ if (!preserveSymlinks) {
123
+ pkgPath = fs.realpathSync(pkgPath);
124
+ }
125
+
126
+ const pkgRoot = path.dirname(pkgPath);
127
+
128
+ const packageInfo = {
129
+ // copy as we are about to munge the `main` field of `pkg`.
130
+ packageJson: Object.assign({}, pkg),
131
+
132
+ // path to package.json file
133
+ packageJsonPath: pkgPath,
134
+
135
+ // directory containing the package.json
136
+ root: pkgRoot,
137
+
138
+ // which main field was used during resolution of this module (main, module, or browser)
139
+ resolvedMainField: 'main',
140
+
141
+ // whether the browser map was used to resolve the entry point to this module
142
+ browserMappedMain: false,
143
+
144
+ // the entry point of the module with respect to the selected main field and any
145
+ // relevant browser mappings.
146
+ resolvedEntryPoint: ''
147
+ };
148
+
149
+ let overriddenMain = false;
150
+ for (let i = 0; i < mainFields.length; i++) {
151
+ const field = mainFields[i];
152
+ if (typeof pkg[field] === 'string') {
153
+ pkg.main = pkg[field];
154
+ packageInfo.resolvedMainField = field;
155
+ overriddenMain = true;
156
+ break;
157
+ }
158
+ }
159
+
160
+ const internalPackageInfo = {
161
+ cachedPkg: pkg,
162
+ hasModuleSideEffects: () => null,
163
+ hasPackageEntry: overriddenMain !== false || mainFields.indexOf('main') !== -1,
164
+ packageBrowserField:
165
+ useBrowserOverrides &&
166
+ typeof pkg.browser === 'object' &&
167
+ Object.keys(pkg.browser).reduce((browser, key) => {
168
+ let resolved = pkg.browser[key];
169
+ if (resolved && resolved[0] === '.') {
170
+ resolved = path.resolve(pkgRoot, resolved);
171
+ }
172
+ /* eslint-disable no-param-reassign */
173
+ browser[key] = resolved;
174
+ if (key[0] === '.') {
175
+ const absoluteKey = path.resolve(pkgRoot, key);
176
+ browser[absoluteKey] = resolved;
177
+ if (!path.extname(key)) {
178
+ extensions.reduce((subBrowser, ext) => {
179
+ subBrowser[absoluteKey + ext] = subBrowser[key];
180
+ return subBrowser;
181
+ }, browser);
182
+ }
183
+ }
184
+ return browser;
185
+ }, {}),
186
+ packageInfo
187
+ };
188
+
189
+ const browserMap = internalPackageInfo.packageBrowserField;
190
+ if (
191
+ useBrowserOverrides &&
192
+ typeof pkg.browser === 'object' &&
193
+ // eslint-disable-next-line no-prototype-builtins
194
+ browserMap.hasOwnProperty(pkg.main)
195
+ ) {
196
+ packageInfo.resolvedEntryPoint = browserMap[pkg.main];
197
+ packageInfo.browserMappedMain = true;
198
+ } else {
199
+ // index.node is technically a valid default entrypoint as well...
200
+ packageInfo.resolvedEntryPoint = path.resolve(pkgRoot, pkg.main || 'index.js');
201
+ packageInfo.browserMappedMain = false;
202
+ }
203
+
204
+ const packageSideEffects = pkg.sideEffects;
205
+ if (typeof packageSideEffects === 'boolean') {
206
+ internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
207
+ } else if (Array.isArray(packageSideEffects)) {
208
+ internalPackageInfo.hasModuleSideEffects = pluginutils.createFilter(packageSideEffects, null, {
209
+ resolve: pkgRoot
210
+ });
211
+ }
212
+
213
+ cache.set(pkgPath, internalPackageInfo);
214
+ return internalPackageInfo;
215
+ }
216
+
217
+ function normalizeInput(input) {
218
+ if (Array.isArray(input)) {
219
+ return input;
220
+ } else if (typeof input === 'object') {
221
+ return Object.values(input);
222
+ }
223
+
224
+ // otherwise it's a string
225
+ return [input];
226
+ }
227
+
228
+ // Resolve module specifiers in order. Promise resolves to the first module that resolves
229
+ // successfully, or the error that resulted from the last attempted module resolution.
230
+ function resolveImportSpecifiers(importSpecifierList, resolveOptions) {
231
+ let promise = Promise.resolve();
232
+
233
+ for (let i = 0; i < importSpecifierList.length; i++) {
234
+ promise = promise.then((value) => {
235
+ // if we've already resolved to something, just return it.
236
+ if (value) {
237
+ return value;
238
+ }
239
+
240
+ return resolveId(importSpecifierList[i], resolveOptions).then((result) => {
241
+ if (!resolveOptions.preserveSymlinks) {
242
+ result = fs.realpathSync(result);
243
+ }
244
+ return result;
245
+ });
246
+ });
247
+
248
+ if (i < importSpecifierList.length - 1) {
249
+ // swallow MODULE_NOT_FOUND errors from all but the last resolution
250
+ promise = promise.catch((error) => {
251
+ if (error.code !== 'MODULE_NOT_FOUND') {
252
+ throw error;
253
+ }
254
+ });
255
+ }
256
+ }
257
+
258
+ return promise;
259
+ }
260
+
261
+ /* eslint-disable no-param-reassign, no-shadow, no-undefined */
262
+
263
+ const builtins = new Set(builtinList);
264
+ const ES6_BROWSER_EMPTY = '\0node-resolve:empty.js';
265
+ const nullFn = () => null;
266
+ const deepFreeze = (object) => {
267
+ Object.freeze(object);
268
+
269
+ for (const value of Object.values(object)) {
270
+ if (typeof value === 'object' && !Object.isFrozen(value)) {
271
+ deepFreeze(value);
272
+ }
273
+ }
274
+
275
+ return object;
276
+ };
277
+ const defaults = {
278
+ customResolveOptions: {},
279
+ dedupe: [],
280
+ // It's important that .mjs is listed before .js so that Rollup will interpret npm modules
281
+ // which deploy both ESM .mjs and CommonJS .js files as ESM.
282
+ extensions: ['.mjs', '.js', '.json', '.node'],
283
+ resolveOnly: []
284
+ };
285
+ const DEFAULTS = deepFreeze(deepMerge({}, defaults));
286
+
287
+ function nodeResolve(opts = {}) {
288
+ const options = Object.assign({}, defaults, opts);
289
+ const { customResolveOptions, extensions, jail } = options;
290
+ const warnings = [];
291
+ const packageInfoCache = new Map();
292
+ const idToPackageInfo = new Map();
293
+ const mainFields = getMainFields(options);
294
+ const useBrowserOverrides = mainFields.indexOf('browser') !== -1;
295
+ const isPreferBuiltinsSet = options.preferBuiltins === true || options.preferBuiltins === false;
296
+ const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
297
+ const rootDir = options.rootDir || process.cwd();
298
+ let { dedupe } = options;
299
+ let rollupOptions;
300
+
301
+ if (options.only) {
302
+ warnings.push('node-resolve: The `only` options is deprecated, please use `resolveOnly`');
303
+ options.resolveOnly = options.only;
304
+ }
305
+
306
+ if (typeof dedupe !== 'function') {
307
+ dedupe = (importee) =>
308
+ options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
309
+ }
310
+
311
+ const resolveOnly = options.resolveOnly.map((pattern) => {
312
+ if (pattern instanceof RegExp) {
313
+ return pattern;
314
+ }
315
+ const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
316
+ return new RegExp(`^${normalized}$`);
317
+ });
318
+
319
+ const browserMapCache = new Map();
320
+ let preserveSymlinks;
321
+
322
+ return {
323
+ name: 'node-resolve',
324
+
325
+ buildStart(options) {
326
+ rollupOptions = options;
327
+
328
+ for (const warning of warnings) {
329
+ this.warn(warning);
330
+ }
331
+
332
+ ({ preserveSymlinks } = options);
333
+ },
334
+
335
+ generateBundle() {
336
+ readCachedFile.clear();
337
+ isFileCached.clear();
338
+ isDirCached.clear();
339
+ },
340
+
341
+ async resolveId(importee, importer) {
342
+ if (importee === ES6_BROWSER_EMPTY) {
343
+ return importee;
344
+ }
345
+ // ignore IDs with null character, these belong to other plugins
346
+ if (/\0/.test(importee)) return null;
347
+
348
+ // strip hash and query params from import
349
+ const [withoutHash, hash] = importee.split('#');
350
+ const [importPath, params] = withoutHash.split('?');
351
+ const importSuffix = `${params ? `?${params}` : ''}${hash ? `#${hash}` : ''}`;
352
+ importee = importPath;
353
+
354
+ const basedir = !importer || dedupe(importee) ? rootDir : path.dirname(importer);
355
+
356
+ // https://github.com/defunctzombie/package-browser-field-spec
357
+ const browser = browserMapCache.get(importer);
358
+ if (useBrowserOverrides && browser) {
359
+ const resolvedImportee = path.resolve(basedir, importee);
360
+ if (browser[importee] === false || browser[resolvedImportee] === false) {
361
+ return ES6_BROWSER_EMPTY;
362
+ }
363
+ const browserImportee =
364
+ browser[importee] ||
365
+ browser[resolvedImportee] ||
366
+ browser[`${resolvedImportee}.js`] ||
367
+ browser[`${resolvedImportee}.json`];
368
+ if (browserImportee) {
369
+ importee = browserImportee;
370
+ }
371
+ }
372
+
373
+ const parts = importee.split(/[/\\]/);
374
+ let id = parts.shift();
375
+ let isRelativeImport = false;
376
+
377
+ if (id[0] === '@' && parts.length > 0) {
378
+ // scoped packages
379
+ id += `/${parts.shift()}`;
380
+ } else if (id[0] === '.') {
381
+ // an import relative to the parent dir of the importer
382
+ id = path.resolve(basedir, importee);
383
+ isRelativeImport = true;
384
+ }
385
+
386
+ if (
387
+ !isRelativeImport &&
388
+ resolveOnly.length &&
389
+ !resolveOnly.some((pattern) => pattern.test(id))
390
+ ) {
391
+ if (normalizeInput(rollupOptions.input).includes(importee)) {
392
+ return null;
393
+ }
394
+ return false;
395
+ }
396
+
397
+ let hasModuleSideEffects = nullFn;
398
+ let hasPackageEntry = true;
399
+ let packageBrowserField = false;
400
+ let packageInfo;
401
+
402
+ const filter = (pkg, pkgPath) => {
403
+ const info = getPackageInfo({
404
+ cache: packageInfoCache,
405
+ extensions,
406
+ pkg,
407
+ pkgPath,
408
+ mainFields,
409
+ preserveSymlinks,
410
+ useBrowserOverrides
411
+ });
412
+
413
+ ({ packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = info);
414
+
415
+ return info.cachedPkg;
416
+ };
417
+
418
+ let resolveOptions = {
419
+ basedir,
420
+ packageFilter: filter,
421
+ readFile: readCachedFile,
422
+ isFile: isFileCached,
423
+ isDirectory: isDirCached,
424
+ extensions
425
+ };
426
+
427
+ if (preserveSymlinks !== undefined) {
428
+ resolveOptions.preserveSymlinks = preserveSymlinks;
429
+ }
430
+
431
+ const importSpecifierList = [];
432
+
433
+ if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
434
+ // For module graph roots (i.e. when importer is undefined), we
435
+ // need to handle 'path fragments` like `foo/bar` that are commonly
436
+ // found in rollup config files. If importee doesn't look like a
437
+ // relative or absolute path, we make it relative and attempt to
438
+ // resolve it. If we don't find anything, we try resolving it as we
439
+ // got it.
440
+ importSpecifierList.push(`./${importee}`);
441
+ }
442
+
443
+ const importeeIsBuiltin = builtins.has(importee);
444
+
445
+ if (importeeIsBuiltin && (!preferBuiltins || !isPreferBuiltinsSet)) {
446
+ // The `resolve` library will not resolve packages with the same
447
+ // name as a node built-in module. If we're resolving something
448
+ // that's a builtin, and we don't prefer to find built-ins, we
449
+ // first try to look up a local module with that name. If we don't
450
+ // find anything, we resolve the builtin which just returns back
451
+ // the built-in's name.
452
+ importSpecifierList.push(`${importee}/`);
453
+ }
454
+
455
+ // TypeScript files may import '.js' to refer to either '.ts' or '.tsx'
456
+ if (importer && importee.endsWith('.js')) {
457
+ for (const ext of ['.ts', '.tsx']) {
458
+ if (importer.endsWith(ext) && extensions.includes(ext)) {
459
+ importSpecifierList.push(importee.replace(/.js$/, ext));
460
+ }
461
+ }
462
+ }
463
+
464
+ importSpecifierList.push(importee);
465
+ resolveOptions = Object.assign(resolveOptions, customResolveOptions);
466
+
467
+ try {
468
+ let resolved = await resolveImportSpecifiers(importSpecifierList, resolveOptions);
469
+
470
+ if (resolved && packageBrowserField) {
471
+ if (Object.prototype.hasOwnProperty.call(packageBrowserField, resolved)) {
472
+ if (!packageBrowserField[resolved]) {
473
+ browserMapCache.set(resolved, packageBrowserField);
474
+ return ES6_BROWSER_EMPTY;
475
+ }
476
+ resolved = packageBrowserField[resolved];
477
+ }
478
+ browserMapCache.set(resolved, packageBrowserField);
479
+ }
480
+
481
+ if (hasPackageEntry && !preserveSymlinks && resolved) {
482
+ const fileExists = await exists(resolved);
483
+ if (fileExists) {
484
+ resolved = await realpath(resolved);
485
+ }
486
+ }
487
+
488
+ idToPackageInfo.set(resolved, packageInfo);
489
+
490
+ if (hasPackageEntry) {
491
+ if (builtins.has(resolved) && preferBuiltins && isPreferBuiltinsSet) {
492
+ return null;
493
+ } else if (importeeIsBuiltin && preferBuiltins) {
494
+ if (!isPreferBuiltinsSet) {
495
+ this.warn(
496
+ `preferring built-in module '${importee}' over local alternative at '${resolved}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`
497
+ );
498
+ }
499
+ return null;
500
+ } else if (jail && resolved.indexOf(path.normalize(jail.trim(path.sep))) !== 0) {
501
+ return null;
502
+ }
503
+ }
504
+
505
+ if (resolved && options.modulesOnly) {
506
+ const code = await readFile(resolved, 'utf-8');
507
+ if (isModule(code)) {
508
+ return {
509
+ id: `${resolved}${importSuffix}`,
510
+ moduleSideEffects: hasModuleSideEffects(resolved)
511
+ };
512
+ }
513
+ return null;
514
+ }
515
+ const result = {
516
+ id: `${resolved}${importSuffix}`,
517
+ moduleSideEffects: hasModuleSideEffects(resolved)
518
+ };
519
+ return result;
520
+ } catch (error) {
521
+ return null;
522
+ }
523
+ },
524
+
525
+ load(importee) {
526
+ if (importee === ES6_BROWSER_EMPTY) {
527
+ return 'export default {};';
528
+ }
529
+ return null;
530
+ },
531
+
532
+ getPackageInfoForId(id) {
533
+ return idToPackageInfo.get(id);
534
+ }
535
+ };
536
+ }
537
+
538
+ exports.DEFAULTS = DEFAULTS;
539
+ exports.default = nodeResolve;
540
+ exports.nodeResolve = nodeResolve;