docs:更新文档

This commit is contained in:
张益铭
2021-03-01 15:06:11 +08:00
parent 1542135ab0
commit 9064b372e8
5835 changed files with 904126 additions and 161722 deletions

474
node_modules/@rollup/plugin-commonjs/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,474 @@
# @rollup/plugin-commonjs ChangeLog
## v15.1.0
_2020-09-21_
### Features
- feat: inject \_\_esModule marker into ES namespaces and add Object prototype (#552)
- feat: add requireReturnsDefault to types (#579)
## v15.0.0
_2020-08-13_
### Breaking Changes
- feat!: return the namespace by default when requiring ESM (#507)
- fix!: fix interop when importing CJS that is transpiled ESM from an actual ESM (#501)
### Bugfixes
- fix: add .cjs to default file extensions. (#524)
### Updates
- chore: update dependencies (fe399e2)
## v14.0.0
_2020-07-13_
### Release Notes
This restores the fixes from v13.0.1, but as a semver compliant major version.
## v13.0.2
_2020-07-13_
### Rollback
Rolls back breaking change in v13.0.1 whereby the exported `unwrapExports` method was removed.
## v13.0.1
_2020-07-12_
### Bugfixes
- fix: prevent rewrite require.resolve (#446)
- fix: Support \_\_esModule packages with a default export (#465)
## v13.0.0
_2020-06-05_
### Breaking Changes
- fix!: remove namedExports from types (#410)
- fix!: do not create fake named exports (#427)
### Bugfixes
- fix: \_\_moduleExports in multi entry + inter dependencies (#415)
## v12.0.0
_2020-05-20_
### Breaking Changes
- feat: add kill-switch for mixed es-cjs modules (#358)
- feat: set syntheticNamedExports for commonjs modules (#149)
### Bugfixes
- fix: expose the virtual `require` function on mock `module`. fixes #307 (#326)
- fix: improved shouldWrap logic. fixes #304 (#355)
### Features
- feat: support for explicit module.require calls. fixes #310 (#325)
## v11.1.0
_2020-04-12_
### Bugfixes
- fix: produce legal variable names from filenames containing hyphens. (#201)
### Features
- feat: support dynamic require (#206)
- feat: export properties defined using Object.defineProperty(exports, ..) (#222)
### Updates
- chore: snapshot mismatch running tests before publish (d6bbfdd)
- test: add snapshots to all "function" tests (#218)
## v11.0.2
_2020-02-01_
### Updates
- docs: fix link for plugin-node-resolve (#170)
- chore: update dependencies (5405eea)
- chore: remove jsnext:main (#152)
## v11.0.1
_2020-01-04_
### Bugfixes
- fix: module.exports object spread (#121)
## 11.0.0
_2019-12-13_
- **Breaking:** Minimum compatible Rollup version is 1.20.0
- **Breaking:** Minimum supported Node version is 8.0.0
- Published as @rollup/plugin-commonjs
## 10.1.0
_2019-08-27_
- Normalize ids before looking up in named export map ([#406](https://github.com/rollup/rollup-plugin-commonjs/issues/406))
- Update README.md with note on symlinks ([#405](https://github.com/rollup/rollup-plugin-commonjs/issues/405))
## 10.0.2
_2019-08-03_
- Support preserveSymlinks: false ([#401](https://github.com/rollup/rollup-plugin-commonjs/issues/401))
## 10.0.1
_2019-06-27_
- Make tests run with Node 6 again and update dependencies ([#389](https://github.com/rollup/rollup-plugin-commonjs/issues/389))
- Handle builtins appropriately for resolve 1.11.0 ([#395](https://github.com/rollup/rollup-plugin-commonjs/issues/395))
## 10.0.0
_2019-05-15_
- Use new Rollup@1.12 context functions, fix issue when resolveId returns an object ([#387](https://github.com/rollup/rollup-plugin-commonjs/issues/387))
## 9.3.4
_2019-04-04_
- Make "extensions" optional ([#384](https://github.com/rollup/rollup-plugin-commonjs/issues/384))
- Use same typing for include and exclude properties ([#385](https://github.com/rollup/rollup-plugin-commonjs/issues/385))
## 9.3.3
_2019-04-04_
- Remove colon from module prefixes ([#371](https://github.com/rollup/rollup-plugin-commonjs/issues/371))
## 9.3.2
_2019-04-04_
- Use shared extractAssignedNames, fix destructuring issue ([#303](https://github.com/rollup/rollup-plugin-commonjs/issues/303))
## 9.3.1
_2019-04-04_
- Include typings in release ([#382](https://github.com/rollup/rollup-plugin-commonjs/issues/382))
## 9.3.0
_2019-04-03_
- Add TypeScript types ([#363](https://github.com/rollup/rollup-plugin-commonjs/issues/363))
## 9.2.3
_2019-04-02_
- Improve support for ES3 browsers ([#364](https://github.com/rollup/rollup-plugin-commonjs/issues/364))
- Add note about monorepo usage to readme ([#372](https://github.com/rollup/rollup-plugin-commonjs/issues/372))
- Add .js extension to generated helper file ([#373](https://github.com/rollup/rollup-plugin-commonjs/issues/373))
## 9.2.2
_2019-03-25_
- Handle array destructuring assignment ([#379](https://github.com/rollup/rollup-plugin-commonjs/issues/379))
## 9.2.1
_2019-02-23_
- Use correct context when manually resolving ids ([#370](https://github.com/rollup/rollup-plugin-commonjs/issues/370))
## 9.2.0
_2018-10-10_
- Fix missing default warning, produce better code when importing known ESM default exports ([#349](https://github.com/rollup/rollup-plugin-commonjs/issues/349))
- Refactor code and add prettier ([#346](https://github.com/rollup/rollup-plugin-commonjs/issues/346))
## 9.1.8
_2018-09-18_
- Ignore virtual modules created by other plugins ([#327](https://github.com/rollup/rollup-plugin-commonjs/issues/327))
- Add "location" and "process" to reserved words ([#330](https://github.com/rollup/rollup-plugin-commonjs/issues/330))
## 9.1.6
_2018-08-24_
- Keep commonJS detection between instantiations ([#338](https://github.com/rollup/rollup-plugin-commonjs/issues/338))
## 9.1.5
_2018-08-09_
- Handle object form of input ([#329](https://github.com/rollup/rollup-plugin-commonjs/issues/329))
## 9.1.4
_2018-07-27_
- Make "from" a reserved word ([#320](https://github.com/rollup/rollup-plugin-commonjs/issues/320))
## 9.1.3
_2018-04-30_
- Fix a caching issue ([#316](https://github.com/rollup/rollup-plugin-commonjs/issues/316))
## 9.1.2
_2018-04-30_
- Re-publication of 9.1.0
## 9.1.1
_2018-04-30_
- Fix ordering of modules when using rollup 0.58 ([#302](https://github.com/rollup/rollup-plugin-commonjs/issues/302))
## 9.1.0
- Do not automatically wrap modules with return statements in top level arrow functions ([#302](https://github.com/rollup/rollup-plugin-commonjs/issues/302))
## 9.0.0
- Make rollup a peer dependency with a version range ([#300](https://github.com/rollup/rollup-plugin-commonjs/issues/300))
## 8.4.1
- Re-release of 8.3.0 as #287 was actually a breaking change
## 8.4.0
- Better handle non-CJS files that contain CJS keywords ([#285](https://github.com/rollup/rollup-plugin-commonjs/issues/285))
- Use rollup's plugin context`parse` function ([#287](https://github.com/rollup/rollup-plugin-commonjs/issues/287))
- Improve error handling ([#288](https://github.com/rollup/rollup-plugin-commonjs/issues/288))
## 8.3.0
- Handle multiple entry points ([#283](https://github.com/rollup/rollup-plugin-commonjs/issues/283))
- Extract named exports from exported object literals ([#272](https://github.com/rollup/rollup-plugin-commonjs/issues/272))
- Fix when `options.external` is modified by other plugins ([#264](https://github.com/rollup/rollup-plugin-commonjs/issues/264))
- Recognize static template strings in require statements ([#271](https://github.com/rollup/rollup-plugin-commonjs/issues/271))
## 8.2.4
- Don't import default from ES modules that don't export default ([#206](https://github.com/rollup/rollup-plugin-commonjs/issues/206))
## 8.2.3
- Prevent duplicate default exports ([#230](https://github.com/rollup/rollup-plugin-commonjs/pull/230))
- Only include default export when it exists ([#226](https://github.com/rollup/rollup-plugin-commonjs/pull/226))
- Deconflict `require` aliases ([#232](https://github.com/rollup/rollup-plugin-commonjs/issues/232))
## 8.2.1
- Fix magic-string deprecation warning
## 8.2.0
- Avoid using `index` as a variable name ([#208](https://github.com/rollup/rollup-plugin-commonjs/pull/208))
## 8.1.1
- Compatibility with 0.48 ([#220](https://github.com/rollup/rollup-plugin-commonjs/issues/220))
## 8.1.0
- Handle `options.external` correctly ([#212](https://github.com/rollup/rollup-plugin-commonjs/pull/212))
- Support top-level return ([#195](https://github.com/rollup/rollup-plugin-commonjs/pull/195))
## 8.0.2
- Fix another `var` rewrite bug ([#181](https://github.com/rollup/rollup-plugin-commonjs/issues/181))
## 8.0.1
- Remove declarators within a var declaration correctly ([#179](https://github.com/rollup/rollup-plugin-commonjs/issues/179))
## 8.0.0
- Prefer the names dependencies are imported by for the common `var foo = require('foo')` pattern ([#176](https://github.com/rollup/rollup-plugin-commonjs/issues/176))
## 7.1.0
- Allow certain `require` statements to pass through unmolested ([#174](https://github.com/rollup/rollup-plugin-commonjs/issues/174))
## 7.0.2
- Handle duplicate default exports ([#158](https://github.com/rollup/rollup-plugin-commonjs/issues/158))
## 7.0.1
- Fix exports with parentheses ([#168](https://github.com/rollup/rollup-plugin-commonjs/issues/168))
## 7.0.0
- Rewrite `typeof module`, `typeof module.exports` and `typeof exports` as `'object'` ([#151](https://github.com/rollup/rollup-plugin-commonjs/issues/151))
## 6.0.1
- Don't overwrite globals ([#127](https://github.com/rollup/rollup-plugin-commonjs/issues/127))
## 6.0.0
- Rewrite top-level `define` as `undefined`, so AMD-first UMD blocks do not cause breakage ([#144](https://github.com/rollup/rollup-plugin-commonjs/issues/144))
- Support ES2017 syntax ([#132](https://github.com/rollup/rollup-plugin-commonjs/issues/132))
- Deconflict exported reserved keywords ([#116](https://github.com/rollup/rollup-plugin-commonjs/issues/116))
## 5.0.5
- Fix parenthesis wrapped exports ([#120](https://github.com/rollup/rollup-plugin-commonjs/issues/120))
## 5.0.4
- Ensure named exports are added to default export in optimised modules ([#112](https://github.com/rollup/rollup-plugin-commonjs/issues/112))
## 5.0.3
- Respect custom `namedExports` in optimised modules ([#35](https://github.com/rollup/rollup-plugin-commonjs/issues/35))
## 5.0.2
- Replace `require` (outside call expressions) with `commonjsRequire` helper ([#77](https://github.com/rollup/rollup-plugin-commonjs/issues/77), [#83](https://github.com/rollup/rollup-plugin-commonjs/issues/83))
## 5.0.1
- Deconflict against globals ([#84](https://github.com/rollup/rollup-plugin-commonjs/issues/84))
## 5.0.0
- Optimise modules that don't need to be wrapped in a function ([#106](https://github.com/rollup/rollup-plugin-commonjs/pull/106))
- Ignore modules containing `import` and `export` statements ([#96](https://github.com/rollup/rollup-plugin-commonjs/pull/96))
## 4.1.0
- Ignore dead branches ([#93](https://github.com/rollup/rollup-plugin-commonjs/issues/93))
## 4.0.1
- Fix `ignoreGlobal` option ([#86](https://github.com/rollup/rollup-plugin-commonjs/pull/86))
## 4.0.0
- Better interop and smaller output ([#92](https://github.com/rollup/rollup-plugin-commonjs/pull/92))
## 3.3.1
- Deconflict export and local module ([rollup/rollup#554](https://github.com/rollup/rollup/issues/554))
## 3.3.0
- Keep the order of execution for require calls ([#43](https://github.com/rollup/rollup-plugin-commonjs/pull/43))
- Use interopDefault as helper ([#42](https://github.com/rollup/rollup-plugin-commonjs/issues/42))
## 3.2.0
- Use named exports as a function when no default export is defined ([#524](https://github.com/rollup/rollup/issues/524))
## 3.1.0
- Replace `typeof require` with `'function'` ([#38](https://github.com/rollup/rollup-plugin-commonjs/issues/38))
- Don't attempt to resolve entry file relative to importer ([#63](https://github.com/rollup/rollup-plugin-commonjs/issues/63))
## 3.0.2
- Handle multiple references to `global`
## 3.0.1
- Return a `name`
## 3.0.0
- Make `transform` stateless ([#71](https://github.com/rollup/rollup-plugin-commonjs/pull/71))
- Support web worker `global` ([#50](https://github.com/rollup/rollup-plugin-commonjs/issues/50))
- Ignore global with `options.ignoreGlobal` ([#48](https://github.com/rollup/rollup-plugin-commonjs/issues/48))
## 2.2.1
- Prevent false positives with `namedExports` ([#36](https://github.com/rollup/rollup-plugin-commonjs/issues/36))
## 2.2.0
- Rewrite top-level `this` expressions to mean the same as `global` ([#31](https://github.com/rollup/rollup-plugin-commonjs/issues/31))
## 2.1.0
- Optimised module wrappers ([#20](https://github.com/rollup/rollup-plugin-commonjs/pull/20))
- Allow control over named exports via `options.namedExports` ([#18](https://github.com/rollup/rollup-plugin-commonjs/issues/18))
- Handle bare imports correctly ([#23](https://github.com/rollup/rollup-plugin-commonjs/issues/23))
- Blacklist all reserved words as export names ([#21](https://github.com/rollup/rollup-plugin-commonjs/issues/21))
- Configure allowed file extensions via `options.extensions` ([#27](https://github.com/rollup/rollup-plugin-commonjs/pull/27))
## 2.0.0
- Support for transpiled modules `exports.default` is used as the default export in place of `module.exports`, if applicable, and `__esModule` is not exported ([#16](https://github.com/rollup/rollup-plugin-commonjs/pull/16))
## 1.4.0
- Generate sourcemaps by default
## 1.3.0
- Handle references to `global` ([#6](https://github.com/rollup/rollup-plugin-commonjs/issues/6))
## 1.2.0
- Generate named exports where possible ([#5](https://github.com/rollup/rollup-plugin-commonjs/issues/5))
- Handle shadowed `require`/`module`/`exports`
## 1.1.0
- Handle dots in filenames ([#3](https://github.com/rollup/rollup-plugin-commonjs/issues/3))
- Wrap modules in IIFE for more readable output
## 1.0.0
- Stable release, now that Rollup supports plugins
## 0.2.1
- Allow mixed CommonJS/ES6 imports/exports
- Use `var` instead of `let`
## 0.2.0
- Sourcemap support
- Support `options.include` and `options.exclude`
- Bail early if module is obviously not a CommonJS module
## 0.1.1
Add dist files to package (whoops!)
## 0.1.0
- First release

21
node_modules/@rollup/plugin-commonjs/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

318
node_modules/@rollup/plugin-commonjs/README.md generated vendored Normal file
View File

@@ -0,0 +1,318 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-commonjs
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-commonjs
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-commonjs
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-commonjs
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-commonjs
🍣 A Rollup plugin to convert CommonJS modules to ES6, so they can be included in a Rollup bundle
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v8.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```bash
npm install @rollup/plugin-commonjs --save-dev
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [commonjs()]
};
```
Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api).
## Options
### `dynamicRequireTargets`
Type: `string | string[]`<br>
Default: `[]`
Some modules contain dynamic `require` calls, or require modules that contain circular dependencies, which are not handled well by static imports.
Including those modules as `dynamicRequireTargets` will simulate a CommonJS (NodeJS-like) environment for them with support for dynamic and circular dependencies.
_Note: In extreme cases, this feature may result in some paths being rendered as absolute in the final bundle. The plugin tries to avoid exposing paths from the local machine, but if you are `dynamicRequirePaths` with paths that are far away from your project's folder, that may require replacing strings like `"/Users/John/Desktop/foo-project/"` -> `"/"`._
Example:
```js
commonjs({
dynamicRequireTargets: [
// include using a glob pattern (either a string or an array of strings)
'node_modules/logform/*.js',
// exclude files that are known to not be required dynamically, this allows for better optimizations
'!node_modules/logform/index.js',
'!node_modules/logform/format.js',
'!node_modules/logform/levels.js',
'!node_modules/logform/browser.js'
]
});
```
### `exclude`
Type: `string | string[]`<br>
Default: `null`
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default, all files with extensions other than those in `extensions` or `".cjs"` are ignored, but you can exclude additional files. See also the `include` option.
### `include`
Type: `string | string[]`<br>
Default: `null`
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default, all files with extension `".cjs"` or those in `extensions` are included, but you can narrow this list by only including specific files. These files will be analyzed and transpiled if either the analysis does not find ES module specific statements or `transformMixedEsModules` is `true`.
### `extensions`
Type: `string[]`<br>
Default: `['.js']`
For extensionless imports, search for extensions other than .js in the order specified. Note that you need to make sure that non-JavaScript files are transpiled by another plugin first.
### `ignoreGlobal`
Type: `boolean`<br>
Default: `false`
If true, uses of `global` won't be dealt with by this plugin.
### `sourceMap`
Type: `boolean`<br>
Default: `true`
If false, skips source map generation for CommonJS modules. This will improve performance.
### `transformMixedEsModules`
Type: `boolean`<br>
Default: `false`
Instructs the plugin whether to enable mixed module transformations. This is useful in scenarios with modules that contain a mix of ES `import` statements and CommonJS `require` expressions. Set to `true` if `require` calls should be transformed to imports in mixed modules, or `false` if the `require` expressions should survive the transformation. The latter can be important if the code contains environment detection, or you are coding for an environment with special treatment for `require` calls such as [ElectronJS](https://www.electronjs.org/). See also the "ignore" option.
### `ignore`
Type: `string[] | ((id: string) => boolean)`<br>
Default: `[]`
Sometimes you have to leave require statements unconverted. Pass an array containing the IDs or an `id => boolean` function.
### `esmExternals`
Type: `boolean | string[] | ((id: string) => boolean)`
Default: `false`
Controls how to render imports from external dependencies. By default, this plugin assumes that all external dependencies are CommonJS. This means they are rendered as default imports to be compatible with e.g. NodeJS where ES modules can only import a default export from a CommonJS dependency:
```js
// input
const foo = require('foo');
// output
import foo from 'foo';
```
This is likely not desired for ES module dependencies: Here `require` should usually return the namespace to be compatible with how bundled modules are handled.
If you set `esmExternals` to `true`, this plugins assumes that all external dependencies are ES modules and will adhere to the `requireReturnsDefault` option. If that option is not set, they will be rendered as namespace imports.
You can also supply an array of ids to be treated as ES modules, or a function that will be passed each external id to determine if it is an ES module.
### `requireReturnsDefault`
Type: `boolean | "auto" | "preferred" | ((id: string) => boolean | "auto" | "preferred")`<br>
Default: `false`
Controls what is returned when requiring an ES module from a CommonJS file. When using the `esmExternals` option, this will also apply to external modules. By default, this plugin will render those imports as namespace imports, i.e.
```js
// input
const foo = require('foo');
// output
import * as foo from 'foo';
```
This is in line with how other bundlers handle this situation and is also the most likely behaviour in case Node should ever support this. However there are some situations where this may not be desired:
- There is code in an external dependency that cannot be changed where a `require` statement expects the default export to be returned from an ES module.
- If the imported module is in the same bundle, Rollup will generate a namespace object for the imported module which can increase bundle size unnecessarily:
```js
// input: main.js
const dep = require('./dep.js');
console.log(dep.default);
// input: dep.js
export default 'foo';
// output
var dep = 'foo';
var dep$1 = /*#__PURE__*/ Object.freeze({
__proto__: null,
default: dep
});
console.log(dep$1.default);
```
For these situations, you can change Rollup's behaviour either globally or per module. To change it globally, set the `requireReturnsDefault` option to one of the following values:
- `false`: This is the default, requiring an ES module returns its namespace. This is the only option that will also add a marker `__esModule: true` to the namespace to support interop patterns in CommonJS modules that are transpiled ES modules.
```js
// input
const dep = require('dep');
console.log(dep);
// output
import * as dep$1 from 'dep';
function getAugmentedNamespace(n) {
var a = Object.defineProperty({}, '__esModule', { value: true });
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(
a,
k,
d.get
? d
: {
enumerable: true,
get: function () {
return n[k];
}
}
);
});
return a;
}
var dep = /*@__PURE__*/ getAugmentedNamespace(dep$1);
console.log(dep);
```
- `"namespace"`: Like `false`, requiring an ES module returns its namespace, but the plugin does not add the `__esModule` marker and thus creates more efficient code. For external dependencies when using `esmExternals: true`, no additional interop code is generated.
```js
// output
import * as dep from 'dep';
console.log(dep);
```
- `"auto"`: This is complementary to how [`output.exports`](https://rollupjs.org/guide/en/#outputexports): `"auto"` works in Rollup: If a module has a default export and no named exports, requiring that module returns the default export. In all other cases, the namespace is returned. For external dependencies when using `esmExternals: true`, a corresponding interop helper is added:
```js
// output
import * as dep$1 from 'dep';
function getDefaultExportFromNamespaceIfNotNamed(n) {
return n &&
Object.prototype.hasOwnProperty.call(n, 'default') &&
Object.keys(n).length === 1
? n['default']
: n;
}
var dep = getDefaultExportFromNamespaceIfNotNamed(dep$1);
console.log(dep);
```
- `"preferred"`: If a module has a default export, requiring that module always returns the default export, no matter whether additional named exports exist. This is similar to how previous versions of this plugin worked. Again for external dependencies when using `esmExternals: true`, an interop helper is added:
```js
// output
import * as dep$1 from 'dep';
function getDefaultExportFromNamespaceIfPresent(n) {
return n && Object.prototype.hasOwnProperty.call(n, 'default')
? n['default']
: n;
}
var dep = getDefaultExportFromNamespaceIfPresent(dep$1);
console.log(dep);
```
- `true`: This will always try to return the default export on require without checking if it actually exists. This can throw at build time if there is no default export. This is how external dependencies are handled when `esmExternals` is not used. The advantage over the other options is that, like `false`, this does not add an interop helper for external dependencies, keeping the code lean:
```js
// output
import dep from 'dep';
console.log(dep);
```
To change this for individual modules, you can supply a function for `requireReturnsDefault` instead. This function will then be called once for each required ES module or external dependency with the corresponding id and allows you to return different values for different modules.
## Using with @rollup/plugin-node-resolve
Since most CommonJS packages you are importing are probably dependencies in `node_modules`, you may need to use [@rollup/plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve):
```js
// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'main.js',
output: {
file: 'bundle.js',
format: 'iife',
name: 'MyModule'
},
plugins: [resolve(), commonjs()]
};
```
## Usage with symlinks
Symlinks are common in monorepos and are also created by the `npm link` command. Rollup with `@rollup/plugin-node-resolve` resolves modules to their real paths by default. So `include` and `exclude` paths should handle real paths rather than symlinked paths (e.g. `../common/node_modules/**` instead of `node_modules/**`). You may also use a regular expression for `include` that works regardless of base path. Try this:
```js
commonjs({
include: /node_modules/
});
```
Whether symlinked module paths are [realpathed](http://man7.org/linux/man-pages/man3/realpath.3.html) or preserved depends on Rollup's `preserveSymlinks` setting, which is false by default, matching Node.js' default behavior. Setting `preserveSymlinks` to true in your Rollup config will cause `import` and `export` to match based on symlinked paths instead.
## Strict mode
ES modules are _always_ parsed in strict mode. That means that certain non-strict constructs (like octal literals) will be treated as syntax errors when Rollup parses modules that use them. Some older CommonJS modules depend on those constructs, and if you depend on them your bundle will blow up. There's basically nothing we can do about that.
Luckily, there is absolutely no good reason _not_ to use strict mode for everything — so the solution to this problem is to lobby the authors of those modules to update them.
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

1406
node_modules/@rollup/plugin-commonjs/dist/index.es.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

1410
node_modules/@rollup/plugin-commonjs/dist/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,315 @@
# @rollup/pluginutils ChangeLog
## v3.1.0
_2020-06-05_
### Bugfixes
- fix: resolve relative paths starting with "./" (#180)
### Features
- feat: add native node es modules support (#419)
### Updates
- refactor: replace micromatch with picomatch. (#306)
- chore: Don't bundle micromatch (#220)
- chore: add missing typescript devDep (238b140)
- chore: Use readonly arrays, add TSDoc (#187)
- chore: Use typechecking (2ae08eb)
## v3.0.10
_2020-05-02_
### Bugfixes
- fix: resolve relative paths starting with "./" (#180)
### Updates
- refactor: replace micromatch with picomatch. (#306)
- chore: Don't bundle micromatch (#220)
- chore: add missing typescript devDep (238b140)
- chore: Use readonly arrays, add TSDoc (#187)
- chore: Use typechecking (2ae08eb)
## v3.0.9
_2020-04-12_
### Updates
- chore: support Rollup v2
## v3.0.8
_2020-02-01_
### Bugfixes
- fix: resolve relative paths starting with "./" (#180)
### Updates
- chore: add missing typescript devDep (238b140)
- chore: Use readonly arrays, add TSDoc (#187)
- chore: Use typechecking (2ae08eb)
## v3.0.7
_2020-02-01_
### Bugfixes
- fix: resolve relative paths starting with "./" (#180)
### Updates
- chore: Use readonly arrays, add TSDoc (#187)
- chore: Use typechecking (2ae08eb)
## v3.0.6
_2020-01-27_
### Bugfixes
- fix: resolve relative paths starting with "./" (#180)
## v3.0.5
_2020-01-25_
### Bugfixes
- fix: bring back named exports (#176)
## v3.0.4
_2020-01-10_
### Bugfixes
- fix: keep for(const..) out of scope (#151)
## v3.0.3
_2020-01-07_
### Bugfixes
- fix: createFilter Windows regression (#141)
### Updates
- test: fix windows path failure (0a0de65)
- chore: fix test script (5eae320)
## v3.0.2
_2020-01-04_
### Bugfixes
- fix: makeLegalIdentifier - potentially unsafe input for blacklisted identifier (#116)
### Updates
- docs: Fix documented type of createFilter's include/exclude (#123)
- chore: update minor linting correction (bcbf9d2)
## 3.0.1
- fix: Escape glob characters in folder (#84)
## 3.0.0
_2019-11-25_
- **Breaking:** Minimum compatible Rollup version is 1.20.0
- **Breaking:** Minimum supported Node version is 8.0.0
- Published as @rollup/plugins-image
## 2.8.2
_2019-09-13_
- Handle optional catch parameter in attachScopes ([#70](https://github.com/rollup/rollup-pluginutils/pulls/70))
## 2.8.1
_2019-06-04_
- Support serialization of many edge cases ([#64](https://github.com/rollup/rollup-pluginutils/issues/64))
## 2.8.0
_2019-05-30_
- Bundle updated micromatch dependency ([#60](https://github.com/rollup/rollup-pluginutils/issues/60))
## 2.7.1
_2019-05-17_
- Do not ignore files with a leading "." in createFilter ([#62](https://github.com/rollup/rollup-pluginutils/issues/62))
## 2.7.0
_2019-05-15_
- Add `resolve` option to createFilter ([#59](https://github.com/rollup/rollup-pluginutils/issues/59))
## 2.6.0
_2019-04-04_
- Add `extractAssignedNames` ([#59](https://github.com/rollup/rollup-pluginutils/issues/59))
- Provide dedicated TypeScript typings file ([#58](https://github.com/rollup/rollup-pluginutils/issues/58))
## 2.5.0
_2019-03-18_
- Generalize dataToEsm type ([#55](https://github.com/rollup/rollup-pluginutils/issues/55))
- Handle empty keys in dataToEsm ([#56](https://github.com/rollup/rollup-pluginutils/issues/56))
## 2.4.1
_2019-02-16_
- Remove unnecessary dependency
## 2.4.0
_2019-02-16_
Update dependencies to solve micromatch vulnerability ([#53](https://github.com/rollup/rollup-pluginutils/issues/53))
## 2.3.3
_2018-09-19_
- Revert micromatch update ([#43](https://github.com/rollup/rollup-pluginutils/issues/43))
## 2.3.2
_2018-09-18_
- Bumb micromatch dependency ([#36](https://github.com/rollup/rollup-pluginutils/issues/36))
- Bumb dependencies ([#41](https://github.com/rollup/rollup-pluginutils/issues/41))
- Split up tests ([#40](https://github.com/rollup/rollup-pluginutils/issues/40))
## 2.3.1
_2018-08-06_
- Fixed ObjectPattern scope in attachScopes to recognise { ...rest } syntax ([#37](https://github.com/rollup/rollup-pluginutils/issues/37))
## 2.3.0
_2018-05-21_
- Add option to not generate named exports ([#32](https://github.com/rollup/rollup-pluginutils/issues/32))
## 2.2.1
_2018-05-21_
- Support `null` serialization ([#34](https://github.com/rollup/rollup-pluginutils/issues/34))
## 2.2.0
_2018-05-11_
- Improve white-space handling in `dataToEsm` and add `prepare` script ([#31](https://github.com/rollup/rollup-pluginutils/issues/31))
## 2.1.1
_2018-05-09_
- Update dependencies
## 2.1.0
_2018-05-08_
- Add `dataToEsm` helper to create named exports from objects ([#29](https://github.com/rollup/rollup-pluginutils/issues/29))
- Support literal keys in object patterns ([#27](https://github.com/rollup/rollup-pluginutils/issues/27))
- Support function declarations without id in `attachScopes` ([#28](https://github.com/rollup/rollup-pluginutils/issues/28))
## 2.0.1
_2017-01-03_
- Don't add extension to file with trailing dot ([#14](https://github.com/rollup/rollup-pluginutils/issues/14))
## 2.0.0
_2017-01-03_
- Use `micromatch` instead of `minimatch` ([#19](https://github.com/rollup/rollup-pluginutils/issues/19))
- Allow `createFilter` to take regexes ([#5](https://github.com/rollup/rollup-pluginutils/issues/5))
## 1.5.2
_2016-08-29_
- Treat `arguments` as a reserved word ([#10](https://github.com/rollup/rollup-pluginutils/issues/10))
## 1.5.1
_2016-06-24_
- Add all declarators in a var declaration to scope, not just the first
## 1.5.0
_2016-06-07_
- Exclude IDs with null character (`\0`)
## 1.4.0
_2016-06-07_
- Workaround minimatch issue ([#6](https://github.com/rollup/rollup-pluginutils/pull/6))
- Exclude non-string IDs in `createFilter`
## 1.3.1
_2015-12-16_
- Build with Rollup directly, rather than via Gobble
## 1.3.0
_2015-12-16_
- Use correct path separator on Windows
## 1.2.0
_2015-11-02_
- Add `attachScopes` and `makeLegalIdentifier`
## 1.1.0
2015-10-24\*
- Add `addExtension` function
## 1.0.1
_2015-10-24_
- Include dist files in package
## 1.0.0
_2015-10-24_
- First release

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,237 @@
[npm]: https://img.shields.io/npm/v/@rollup/pluginutils
[npm-url]: https://www.npmjs.com/package/@rollup/pluginutils
[size]: https://packagephobia.now.sh/badge?p=@rollup/pluginutils
[size-url]: https://packagephobia.now.sh/result?p=@rollup/pluginutils
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/pluginutils
A set of utility functions commonly used by 🍣 Rollup plugins.
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v8.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```console
npm install @rollup/pluginutils --save-dev
```
## Usage
```js
import utils from '@rollup/pluginutils';
//...
```
## API
Available utility functions are listed below:
_Note: Parameter names immediately followed by a `?` indicate that the parameter is optional._
### addExtension
Adds an extension to a module ID if one does not exist.
Parameters: `(filename: String, ext?: String)`<br>
Returns: `String`
```js
import { addExtension } from '@rollup/pluginutils';
export default function myPlugin(options = {}) {
return {
resolveId(code, id) {
// only adds an extension if there isn't one already
id = addExtension(id); // `foo` -> `foo.js`, `foo.js -> foo.js`
id = addExtension(id, '.myext'); // `foo` -> `foo.myext`, `foo.js -> `foo.js`
}
};
}
```
### attachScopes
Attaches `Scope` objects to the relevant nodes of an AST. Each `Scope` object has a `scope.contains(name)` method that returns `true` if a given name is defined in the current scope or a parent scope.
Parameters: `(ast: Node, propertyName?: String)`<br>
Returns: `Object`
See [rollup-plugin-inject](https://github.com/rollup/rollup-plugin-inject) or [rollup-plugin-commonjs](https://github.com/rollup/rollup-plugin-commonjs) for an example of usage.
```js
import { attachScopes } from '@rollup/pluginutils';
import { walk } from 'estree-walker';
export default function myPlugin(options = {}) {
return {
transform(code) {
const ast = this.parse(code);
let scope = attachScopes(ast, 'scope');
walk(ast, {
enter(node) {
if (node.scope) scope = node.scope;
if (!scope.contains('foo')) {
// `foo` is not defined, so if we encounter it,
// we assume it's a global
}
},
leave(node) {
if (node.scope) scope = scope.parent;
}
});
}
};
}
```
### createFilter
Constructs a filter function which can be used to determine whether or not certain modules should be operated upon.
Parameters: `(include?: <minmatch>, exclude?: <minmatch>, options?: Object)`<br>
Returns: `String`
#### `include` and `exclude`
Type: `String | RegExp | Array[...String|RegExp]`<br>
A valid [`minimatch`](https://www.npmjs.com/package/minimatch) pattern, or array of patterns. If `options.include` is omitted or has zero length, filter will return `true` by default. Otherwise, an ID must match one or more of the `minimatch` patterns, and must not match any of the `options.exclude` patterns.
#### `options`
##### `resolve`
Type: `String | Boolean | null`
Optionally resolves the patterns against a directory other than `process.cwd()`. If a `String` is specified, then the value will be used as the base directory. Relative paths will be resolved against `process.cwd()` first. If `false`, then the patterns will not be resolved against any directory. This can be useful if you want to create a filter for virtual module names.
#### Usage
```js
import { createFilter } from '@rollup/pluginutils';
export default function myPlugin(options = {}) {
// assume that the myPlugin accepts options of `options.include` and `options.exclude`
var filter = createFilter(options.include, options.exclude, {
resolve: '/my/base/dir'
});
return {
transform(code, id) {
if (!filter(id)) return;
// proceed with the transformation...
}
};
}
```
### dataToEsm
Transforms objects into tree-shakable ES Module imports.
Parameters: `(data: Object)`<br>
Returns: `String`
#### `data`
Type: `Object`
An object to transform into an ES module.
#### Usage
```js
import { dataToEsm } from '@rollup/pluginutils';
const esModuleSource = dataToEsm(
{
custom: 'data',
to: ['treeshake']
},
{
compact: false,
indent: '\t',
preferConst: false,
objectShorthand: false,
namedExports: true
}
);
/*
Outputs the string ES module source:
export const custom = 'data';
export const to = ['treeshake'];
export default { custom, to };
*/
```
### extractAssignedNames
Extracts the names of all assignment targets based upon specified patterns.
Parameters: `(param: Node)`<br>
Returns: `Array[...String]`
#### `param`
Type: `Node`
An `acorn` AST Node.
#### Usage
```js
import { extractAssignedNames } from '@rollup/pluginutils';
import { walk } from 'estree-walker';
export default function myPlugin(options = {}) {
return {
transform(code) {
const ast = this.parse(code);
walk(ast, {
enter(node) {
if (node.type === 'VariableDeclarator') {
const declaredNames = extractAssignedNames(node.id);
// do something with the declared names
// e.g. for `const {x, y: z} = ... => declaredNames = ['x', 'z']
}
}
});
}
};
}
```
### makeLegalIdentifier
Constructs a bundle-safe identifier from a `String`.
Parameters: `(str: String)`<br>
Returns: `String`
#### Usage
```js
import { makeLegalIdentifier } from '@rollup/pluginutils';
makeLegalIdentifier('foo-bar'); // 'foo_bar'
makeLegalIdentifier('typeof'); // '_typeof'
```
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View File

@@ -0,0 +1,447 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var path = require('path');
var pm = _interopDefault(require('picomatch'));
const addExtension = function addExtension(filename, ext = '.js') {
let result = `${filename}`;
if (!path.extname(filename))
result += ext;
return result;
};
function walk(ast, { enter, leave }) {
return visit(ast, null, enter, leave);
}
let should_skip = false;
let should_remove = false;
let replacement = null;
const context = {
skip: () => should_skip = true,
remove: () => should_remove = true,
replace: (node) => replacement = node
};
function replace(parent, prop, index, node) {
if (parent) {
if (index !== null) {
parent[prop][index] = node;
} else {
parent[prop] = node;
}
}
}
function remove(parent, prop, index) {
if (parent) {
if (index !== null) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
function visit(
node,
parent,
enter,
leave,
prop,
index
) {
if (node) {
if (enter) {
const _should_skip = should_skip;
const _should_remove = should_remove;
const _replacement = replacement;
should_skip = false;
should_remove = false;
replacement = null;
enter.call(context, node, parent, prop, index);
if (replacement) {
node = replacement;
replace(parent, prop, index, node);
}
if (should_remove) {
remove(parent, prop, index);
}
const skipped = should_skip;
const removed = should_remove;
should_skip = _should_skip;
should_remove = _should_remove;
replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
for (const key in node) {
const value = (node )[key];
if (typeof value !== 'object') {
continue;
}
else if (Array.isArray(value)) {
for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
if (value[j] !== null && typeof value[j].type === 'string') {
if (!visit(value[j], node, enter, leave, key, k)) {
// removed
j--;
}
}
}
}
else if (value !== null && typeof value.type === 'string') {
visit(value, node, enter, leave, key, null);
}
}
if (leave) {
const _replacement = replacement;
const _should_remove = should_remove;
replacement = null;
should_remove = false;
leave.call(context, node, parent, prop, index);
if (replacement) {
node = replacement;
replace(parent, prop, index, node);
}
if (should_remove) {
remove(parent, prop, index);
}
const removed = should_remove;
replacement = _replacement;
should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
const extractors = {
ArrayPattern(names, param) {
for (const element of param.elements) {
if (element)
extractors[element.type](names, element);
}
},
AssignmentPattern(names, param) {
extractors[param.left.type](names, param.left);
},
Identifier(names, param) {
names.push(param.name);
},
MemberExpression() { },
ObjectPattern(names, param) {
for (const prop of param.properties) {
// @ts-ignore Typescript reports that this is not a valid type
if (prop.type === 'RestElement') {
extractors.RestElement(names, prop);
}
else {
extractors[prop.value.type](names, prop.value);
}
}
},
RestElement(names, param) {
extractors[param.argument.type](names, param.argument);
}
};
const extractAssignedNames = function extractAssignedNames(param) {
const names = [];
extractors[param.type](names, param);
return names;
};
const blockDeclarations = {
const: true,
let: true
};
class Scope {
constructor(options = {}) {
this.parent = options.parent;
this.isBlockScope = !!options.block;
this.declarations = Object.create(null);
if (options.params) {
options.params.forEach((param) => {
extractAssignedNames(param).forEach((name) => {
this.declarations[name] = true;
});
});
}
}
addDeclaration(node, isBlockDeclaration, isVar) {
if (!isBlockDeclaration && this.isBlockScope) {
// it's a `var` or function node, and this
// is a block scope, so we need to go up
this.parent.addDeclaration(node, isBlockDeclaration, isVar);
}
else if (node.id) {
extractAssignedNames(node.id).forEach((name) => {
this.declarations[name] = true;
});
}
}
contains(name) {
return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
}
}
const attachScopes = function attachScopes(ast, propertyName = 'scope') {
let scope = new Scope();
walk(ast, {
enter(n, parent) {
const node = n;
// function foo () {...}
// class Foo {...}
if (/(Function|Class)Declaration/.test(node.type)) {
scope.addDeclaration(node, false, false);
}
// var foo = 1
if (node.type === 'VariableDeclaration') {
const { kind } = node;
const isBlockDeclaration = blockDeclarations[kind];
// don't add const/let declarations in the body of a for loop #113
const parentType = parent ? parent.type : '';
if (!(isBlockDeclaration && /ForOfStatement/.test(parentType))) {
node.declarations.forEach((declaration) => {
scope.addDeclaration(declaration, isBlockDeclaration, true);
});
}
}
let newScope;
// create new function scope
if (/Function/.test(node.type)) {
const func = node;
newScope = new Scope({
parent: scope,
block: false,
params: func.params
});
// named function expressions - the name is considered
// part of the function's scope
if (func.type === 'FunctionExpression' && func.id) {
newScope.addDeclaration(func, false, false);
}
}
// create new block scope
if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
// catch clause has its own block scope
if (node.type === 'CatchClause') {
newScope = new Scope({
parent: scope,
params: node.param ? [node.param] : [],
block: true
});
}
if (newScope) {
Object.defineProperty(node, propertyName, {
value: newScope,
configurable: true
});
scope = newScope;
}
},
leave(n) {
const node = n;
if (node[propertyName])
scope = scope.parent;
}
});
return scope;
};
// Helper since Typescript can't detect readonly arrays with Array.isArray
function isArray(arg) {
return Array.isArray(arg);
}
function ensureArray(thing) {
if (isArray(thing))
return thing;
if (thing == null)
return [];
return [thing];
}
function getMatcherString(id, resolutionBase) {
if (resolutionBase === false) {
return id;
}
// resolve('') is valid and will default to process.cwd()
const basePath = path.resolve(resolutionBase || '')
.split(path.sep)
.join('/')
// escape all possible (posix + win) path characters that might interfere with regex
.replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
// Note that we use posix.join because:
// 1. the basePath has been normalized to use /
// 2. the incoming glob (id) matcher, also uses /
// otherwise Node will force backslash (\) on windows
return path.posix.join(basePath, id);
}
const createFilter = function createFilter(include, exclude, options) {
const resolutionBase = options && options.resolve;
const getMatcher = (id) => id instanceof RegExp
? id
: {
test: (what) => {
// this refactor is a tad overly verbose but makes for easy debugging
const pattern = getMatcherString(id, resolutionBase);
const fn = pm(pattern, { dot: true });
const result = fn(what);
return result;
}
};
const includeMatchers = ensureArray(include).map(getMatcher);
const excludeMatchers = ensureArray(exclude).map(getMatcher);
return function result(id) {
if (typeof id !== 'string')
return false;
if (/\0/.test(id))
return false;
const pathId = id.split(path.sep).join('/');
for (let i = 0; i < excludeMatchers.length; ++i) {
const matcher = excludeMatchers[i];
if (matcher.test(pathId))
return false;
}
for (let i = 0; i < includeMatchers.length; ++i) {
const matcher = includeMatchers[i];
if (matcher.test(pathId))
return true;
}
return !includeMatchers.length;
};
};
const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
forbiddenIdentifiers.add('');
const makeLegalIdentifier = function makeLegalIdentifier(str) {
let identifier = str
.replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
.replace(/[^$_a-zA-Z0-9]/g, '_');
if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
identifier = `_${identifier}`;
}
return identifier || '_';
};
function stringify(obj) {
return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
}
function serializeArray(arr, indent, baseIndent) {
let output = '[';
const separator = indent ? `\n${baseIndent}${indent}` : '';
for (let i = 0; i < arr.length; i++) {
const key = arr[i];
output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `\n${baseIndent}` : ''}]`;
}
function serializeObject(obj, indent, baseIndent) {
let output = '{';
const separator = indent ? `\n${baseIndent}${indent}` : '';
const entries = Object.entries(obj);
for (let i = 0; i < entries.length; i++) {
const [key, value] = entries[i];
const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `\n${baseIndent}` : ''}}`;
}
function serialize(obj, indent, baseIndent) {
if (obj === Infinity)
return 'Infinity';
if (obj === -Infinity)
return '-Infinity';
if (obj === 0 && 1 / obj === -Infinity)
return '-0';
if (obj instanceof Date)
return `new Date(${obj.getTime()})`;
if (obj instanceof RegExp)
return obj.toString();
if (obj !== obj)
return 'NaN'; // eslint-disable-line no-self-compare
if (Array.isArray(obj))
return serializeArray(obj, indent, baseIndent);
if (obj === null)
return 'null';
if (typeof obj === 'object')
return serializeObject(obj, indent, baseIndent);
return stringify(obj);
}
const dataToEsm = function dataToEsm(data, options = {}) {
const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
const _ = options.compact ? '' : ' ';
const n = options.compact ? '' : '\n';
const declarationType = options.preferConst ? 'const' : 'var';
if (options.namedExports === false ||
typeof data !== 'object' ||
Array.isArray(data) ||
data instanceof Date ||
data instanceof RegExp ||
data === null) {
const code = serialize(data, options.compact ? null : t, '');
const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
return `export default${magic}${code};`;
}
let namedExportCode = '';
const defaultExportRows = [];
for (const [key, value] of Object.entries(data)) {
if (key === makeLegalIdentifier(key)) {
if (options.objectShorthand)
defaultExportRows.push(key);
else
defaultExportRows.push(`${key}:${_}${key}`);
namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
}
else {
defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
}
}
return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
};
// TODO: remove this in next major
var index = {
addExtension,
attachScopes,
createFilter,
dataToEsm,
extractAssignedNames,
makeLegalIdentifier
};
exports.addExtension = addExtension;
exports.attachScopes = attachScopes;
exports.createFilter = createFilter;
exports.dataToEsm = dataToEsm;
exports.default = index;
exports.extractAssignedNames = extractAssignedNames;
exports.makeLegalIdentifier = makeLegalIdentifier;

View File

@@ -0,0 +1,436 @@
import { extname, sep, resolve, posix } from 'path';
import pm from 'picomatch';
const addExtension = function addExtension(filename, ext = '.js') {
let result = `${filename}`;
if (!extname(filename))
result += ext;
return result;
};
function walk(ast, { enter, leave }) {
return visit(ast, null, enter, leave);
}
let should_skip = false;
let should_remove = false;
let replacement = null;
const context = {
skip: () => should_skip = true,
remove: () => should_remove = true,
replace: (node) => replacement = node
};
function replace(parent, prop, index, node) {
if (parent) {
if (index !== null) {
parent[prop][index] = node;
} else {
parent[prop] = node;
}
}
}
function remove(parent, prop, index) {
if (parent) {
if (index !== null) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
function visit(
node,
parent,
enter,
leave,
prop,
index
) {
if (node) {
if (enter) {
const _should_skip = should_skip;
const _should_remove = should_remove;
const _replacement = replacement;
should_skip = false;
should_remove = false;
replacement = null;
enter.call(context, node, parent, prop, index);
if (replacement) {
node = replacement;
replace(parent, prop, index, node);
}
if (should_remove) {
remove(parent, prop, index);
}
const skipped = should_skip;
const removed = should_remove;
should_skip = _should_skip;
should_remove = _should_remove;
replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
for (const key in node) {
const value = (node )[key];
if (typeof value !== 'object') {
continue;
}
else if (Array.isArray(value)) {
for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
if (value[j] !== null && typeof value[j].type === 'string') {
if (!visit(value[j], node, enter, leave, key, k)) {
// removed
j--;
}
}
}
}
else if (value !== null && typeof value.type === 'string') {
visit(value, node, enter, leave, key, null);
}
}
if (leave) {
const _replacement = replacement;
const _should_remove = should_remove;
replacement = null;
should_remove = false;
leave.call(context, node, parent, prop, index);
if (replacement) {
node = replacement;
replace(parent, prop, index, node);
}
if (should_remove) {
remove(parent, prop, index);
}
const removed = should_remove;
replacement = _replacement;
should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
const extractors = {
ArrayPattern(names, param) {
for (const element of param.elements) {
if (element)
extractors[element.type](names, element);
}
},
AssignmentPattern(names, param) {
extractors[param.left.type](names, param.left);
},
Identifier(names, param) {
names.push(param.name);
},
MemberExpression() { },
ObjectPattern(names, param) {
for (const prop of param.properties) {
// @ts-ignore Typescript reports that this is not a valid type
if (prop.type === 'RestElement') {
extractors.RestElement(names, prop);
}
else {
extractors[prop.value.type](names, prop.value);
}
}
},
RestElement(names, param) {
extractors[param.argument.type](names, param.argument);
}
};
const extractAssignedNames = function extractAssignedNames(param) {
const names = [];
extractors[param.type](names, param);
return names;
};
const blockDeclarations = {
const: true,
let: true
};
class Scope {
constructor(options = {}) {
this.parent = options.parent;
this.isBlockScope = !!options.block;
this.declarations = Object.create(null);
if (options.params) {
options.params.forEach((param) => {
extractAssignedNames(param).forEach((name) => {
this.declarations[name] = true;
});
});
}
}
addDeclaration(node, isBlockDeclaration, isVar) {
if (!isBlockDeclaration && this.isBlockScope) {
// it's a `var` or function node, and this
// is a block scope, so we need to go up
this.parent.addDeclaration(node, isBlockDeclaration, isVar);
}
else if (node.id) {
extractAssignedNames(node.id).forEach((name) => {
this.declarations[name] = true;
});
}
}
contains(name) {
return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
}
}
const attachScopes = function attachScopes(ast, propertyName = 'scope') {
let scope = new Scope();
walk(ast, {
enter(n, parent) {
const node = n;
// function foo () {...}
// class Foo {...}
if (/(Function|Class)Declaration/.test(node.type)) {
scope.addDeclaration(node, false, false);
}
// var foo = 1
if (node.type === 'VariableDeclaration') {
const { kind } = node;
const isBlockDeclaration = blockDeclarations[kind];
// don't add const/let declarations in the body of a for loop #113
const parentType = parent ? parent.type : '';
if (!(isBlockDeclaration && /ForOfStatement/.test(parentType))) {
node.declarations.forEach((declaration) => {
scope.addDeclaration(declaration, isBlockDeclaration, true);
});
}
}
let newScope;
// create new function scope
if (/Function/.test(node.type)) {
const func = node;
newScope = new Scope({
parent: scope,
block: false,
params: func.params
});
// named function expressions - the name is considered
// part of the function's scope
if (func.type === 'FunctionExpression' && func.id) {
newScope.addDeclaration(func, false, false);
}
}
// create new block scope
if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
// catch clause has its own block scope
if (node.type === 'CatchClause') {
newScope = new Scope({
parent: scope,
params: node.param ? [node.param] : [],
block: true
});
}
if (newScope) {
Object.defineProperty(node, propertyName, {
value: newScope,
configurable: true
});
scope = newScope;
}
},
leave(n) {
const node = n;
if (node[propertyName])
scope = scope.parent;
}
});
return scope;
};
// Helper since Typescript can't detect readonly arrays with Array.isArray
function isArray(arg) {
return Array.isArray(arg);
}
function ensureArray(thing) {
if (isArray(thing))
return thing;
if (thing == null)
return [];
return [thing];
}
function getMatcherString(id, resolutionBase) {
if (resolutionBase === false) {
return id;
}
// resolve('') is valid and will default to process.cwd()
const basePath = resolve(resolutionBase || '')
.split(sep)
.join('/')
// escape all possible (posix + win) path characters that might interfere with regex
.replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
// Note that we use posix.join because:
// 1. the basePath has been normalized to use /
// 2. the incoming glob (id) matcher, also uses /
// otherwise Node will force backslash (\) on windows
return posix.join(basePath, id);
}
const createFilter = function createFilter(include, exclude, options) {
const resolutionBase = options && options.resolve;
const getMatcher = (id) => id instanceof RegExp
? id
: {
test: (what) => {
// this refactor is a tad overly verbose but makes for easy debugging
const pattern = getMatcherString(id, resolutionBase);
const fn = pm(pattern, { dot: true });
const result = fn(what);
return result;
}
};
const includeMatchers = ensureArray(include).map(getMatcher);
const excludeMatchers = ensureArray(exclude).map(getMatcher);
return function result(id) {
if (typeof id !== 'string')
return false;
if (/\0/.test(id))
return false;
const pathId = id.split(sep).join('/');
for (let i = 0; i < excludeMatchers.length; ++i) {
const matcher = excludeMatchers[i];
if (matcher.test(pathId))
return false;
}
for (let i = 0; i < includeMatchers.length; ++i) {
const matcher = includeMatchers[i];
if (matcher.test(pathId))
return true;
}
return !includeMatchers.length;
};
};
const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
forbiddenIdentifiers.add('');
const makeLegalIdentifier = function makeLegalIdentifier(str) {
let identifier = str
.replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
.replace(/[^$_a-zA-Z0-9]/g, '_');
if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
identifier = `_${identifier}`;
}
return identifier || '_';
};
function stringify(obj) {
return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
}
function serializeArray(arr, indent, baseIndent) {
let output = '[';
const separator = indent ? `\n${baseIndent}${indent}` : '';
for (let i = 0; i < arr.length; i++) {
const key = arr[i];
output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `\n${baseIndent}` : ''}]`;
}
function serializeObject(obj, indent, baseIndent) {
let output = '{';
const separator = indent ? `\n${baseIndent}${indent}` : '';
const entries = Object.entries(obj);
for (let i = 0; i < entries.length; i++) {
const [key, value] = entries[i];
const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `\n${baseIndent}` : ''}}`;
}
function serialize(obj, indent, baseIndent) {
if (obj === Infinity)
return 'Infinity';
if (obj === -Infinity)
return '-Infinity';
if (obj === 0 && 1 / obj === -Infinity)
return '-0';
if (obj instanceof Date)
return `new Date(${obj.getTime()})`;
if (obj instanceof RegExp)
return obj.toString();
if (obj !== obj)
return 'NaN'; // eslint-disable-line no-self-compare
if (Array.isArray(obj))
return serializeArray(obj, indent, baseIndent);
if (obj === null)
return 'null';
if (typeof obj === 'object')
return serializeObject(obj, indent, baseIndent);
return stringify(obj);
}
const dataToEsm = function dataToEsm(data, options = {}) {
const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
const _ = options.compact ? '' : ' ';
const n = options.compact ? '' : '\n';
const declarationType = options.preferConst ? 'const' : 'var';
if (options.namedExports === false ||
typeof data !== 'object' ||
Array.isArray(data) ||
data instanceof Date ||
data instanceof RegExp ||
data === null) {
const code = serialize(data, options.compact ? null : t, '');
const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
return `export default${magic}${code};`;
}
let namedExportCode = '';
const defaultExportRows = [];
for (const [key, value] of Object.entries(data)) {
if (key === makeLegalIdentifier(key)) {
if (options.objectShorthand)
defaultExportRows.push(key);
else
defaultExportRows.push(`${key}:${_}${key}`);
namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
}
else {
defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
}
}
return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
};
// TODO: remove this in next major
var index = {
addExtension,
attachScopes,
createFilter,
dataToEsm,
extractAssignedNames,
makeLegalIdentifier
};
export default index;
export { addExtension, attachScopes, createFilter, dataToEsm, extractAssignedNames, makeLegalIdentifier };

View File

@@ -0,0 +1 @@
{"type":"module"}

View File

@@ -0,0 +1,79 @@
# changelog
## 1.0.1
* Relax node type to `BaseNode` ([#17](https://github.com/Rich-Harris/estree-walker/pull/17))
## 1.0.0
* Don't cache child keys
## 0.9.0
* Add `this.remove()` method
## 0.8.1
* Fix pkg.files
## 0.8.0
* Adopt `estree` types
## 0.7.0
* Add a `this.replace(node)` method
## 0.6.1
* Only traverse nodes that exist and have a type ([#9](https://github.com/Rich-Harris/estree-walker/pull/9))
* Only cache keys for nodes with a type ([#8](https://github.com/Rich-Harris/estree-walker/pull/8))
## 0.6.0
* Fix walker context type
* Update deps, remove unncessary Bublé transformation
## 0.5.2
* Add types to package
## 0.5.1
* Prevent context corruption when `walk()` is called during a walk
## 0.5.0
* Export `childKeys`, for manually fixing in case of malformed ASTs
## 0.4.0
* Add TypeScript typings ([#3](https://github.com/Rich-Harris/estree-walker/pull/3))
## 0.3.1
* Include `pkg.repository` ([#2](https://github.com/Rich-Harris/estree-walker/pull/2))
## 0.3.0
* More predictable ordering
## 0.2.1
* Keep `context` shape
## 0.2.0
* Add ES6 build
## 0.1.3
* npm snafu
## 0.1.2
* Pass current prop and index to `enter`/`leave` callbacks
## 0.1.1
* First release

View File

@@ -0,0 +1,48 @@
# estree-walker
Simple utility for walking an [ESTree](https://github.com/estree/estree)-compliant AST, such as one generated by [acorn](https://github.com/marijnh/acorn).
## Installation
```bash
npm i estree-walker
```
## Usage
```js
var walk = require( 'estree-walker' ).walk;
var acorn = require( 'acorn' );
ast = acorn.parse( sourceCode, options ); // https://github.com/acornjs/acorn
walk( ast, {
enter: function ( node, parent, prop, index ) {
// some code happens
},
leave: function ( node, parent, prop, index ) {
// some code happens
}
});
```
Inside the `enter` function, calling `this.skip()` will prevent the node's children being walked, or the `leave` function (which is optional) being called.
Call `this.replace(new_node)` in either `enter` or `leave` to replace the current node with a new one.
Call `this.remove()` in either `enter` or `leave` to remove the current node.
## Why not use estraverse?
The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where [estraverse](https://github.com/estools/estraverse) was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys.
estree-walker, by contrast, simply enumerates a node's properties to find child nodes (and child lists of nodes), and is therefore resistant to spec changes. It's also much smaller. (The performance, if you're wondering, is basically identical.)
None of which should be taken as criticism of estraverse, which has more features and has been battle-tested in many more situations, and for which I'm very grateful.
## License
MIT

View File

@@ -0,0 +1,135 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.estreeWalker = {})));
}(this, (function (exports) { 'use strict';
function walk(ast, { enter, leave }) {
return visit(ast, null, enter, leave);
}
let should_skip = false;
let should_remove = false;
let replacement = null;
const context = {
skip: () => should_skip = true,
remove: () => should_remove = true,
replace: (node) => replacement = node
};
function replace(parent, prop, index, node) {
if (parent) {
if (index !== null) {
parent[prop][index] = node;
} else {
parent[prop] = node;
}
}
}
function remove(parent, prop, index) {
if (parent) {
if (index !== null) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
function visit(
node,
parent,
enter,
leave,
prop,
index
) {
if (node) {
if (enter) {
const _should_skip = should_skip;
const _should_remove = should_remove;
const _replacement = replacement;
should_skip = false;
should_remove = false;
replacement = null;
enter.call(context, node, parent, prop, index);
if (replacement) {
node = replacement;
replace(parent, prop, index, node);
}
if (should_remove) {
remove(parent, prop, index);
}
const skipped = should_skip;
const removed = should_remove;
should_skip = _should_skip;
should_remove = _should_remove;
replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
for (const key in node) {
const value = (node )[key];
if (typeof value !== 'object') {
continue;
}
else if (Array.isArray(value)) {
for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
if (value[j] !== null && typeof value[j].type === 'string') {
if (!visit(value[j], node, enter, leave, key, k)) {
// removed
j--;
}
}
}
}
else if (value !== null && typeof value.type === 'string') {
visit(value, node, enter, leave, key, null);
}
}
if (leave) {
const _replacement = replacement;
const _should_remove = should_remove;
replacement = null;
should_remove = false;
leave.call(context, node, parent, prop, index);
if (replacement) {
node = replacement;
replace(parent, prop, index, node);
}
if (should_remove) {
remove(parent, prop, index);
}
const removed = should_remove;
replacement = _replacement;
should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
exports.walk = walk;
Object.defineProperty(exports, '__esModule', { value: true });
})));

View File

@@ -0,0 +1 @@
{"version":3,"file":"estree-walker.umd.js","sources":["../src/estree-walker.js"],"sourcesContent":["export function walk(ast, { enter, leave }) {\n\tvisit(ast, null, enter, leave);\n}\n\nlet shouldSkip = false;\nconst context = { skip: () => shouldSkip = true };\n\nexport const childKeys = {};\n\nconst toString = Object.prototype.toString;\n\nfunction isArray(thing) {\n\treturn toString.call(thing) === '[object Array]';\n}\n\nfunction visit(node, parent, enter, leave, prop, index) {\n\tif (!node) return;\n\n\tif (enter) {\n\t\tconst _shouldSkip = shouldSkip;\n\t\tshouldSkip = false;\n\t\tenter.call(context, node, parent, prop, index);\n\t\tconst skipped = shouldSkip;\n\t\tshouldSkip = _shouldSkip;\n\n\t\tif (skipped) return;\n\t}\n\n\tconst keys = childKeys[node.type] || (\n\t\tchildKeys[node.type] = Object.keys(node).filter(key => typeof node[key] === 'object')\n\t);\n\n\tfor (let i = 0; i < keys.length; i += 1) {\n\t\tconst key = keys[i];\n\t\tconst value = node[key];\n\n\t\tif (isArray(value)) {\n\t\t\tfor (let j = 0; j < value.length; j += 1) {\n\t\t\t\tvisit(value[j], node, enter, leave, key, j);\n\t\t\t}\n\t\t}\n\n\t\telse if (value && value.type) {\n\t\t\tvisit(value, node, enter, leave, key, null);\n\t\t}\n\t}\n\n\tif (leave) {\n\t\tleave(node, parent, prop, index);\n\t}\n}\n"],"names":[],"mappings":";;;;;;CAAO,SAAS,IAAI,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE;CAC5C,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;CAChC,CAAC;;CAED,IAAI,UAAU,GAAG,KAAK,CAAC;CACvB,MAAM,OAAO,GAAG,EAAE,IAAI,EAAE,MAAM,UAAU,GAAG,IAAI,EAAE,CAAC;;AAElD,AAAY,OAAC,SAAS,GAAG,EAAE,CAAC;;CAE5B,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC;;CAE3C,SAAS,OAAO,CAAC,KAAK,EAAE;CACxB,CAAC,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,gBAAgB,CAAC;CAClD,CAAC;;CAED,SAAS,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE;CACxD,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO;;CAEnB,CAAC,IAAI,KAAK,EAAE;CACZ,EAAE,MAAM,WAAW,GAAG,UAAU,CAAC;CACjC,EAAE,UAAU,GAAG,KAAK,CAAC;CACrB,EAAE,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;CACjD,EAAE,MAAM,OAAO,GAAG,UAAU,CAAC;CAC7B,EAAE,UAAU,GAAG,WAAW,CAAC;;CAE3B,EAAE,IAAI,OAAO,EAAE,OAAO;CACtB,EAAE;;CAEF,CAAC,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC;CAClC,EAAE,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,QAAQ,CAAC;CACvF,EAAE,CAAC;;CAEH,CAAC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;CAC1C,EAAE,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;CACtB,EAAE,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;;CAE1B,EAAE,IAAI,OAAO,CAAC,KAAK,CAAC,EAAE;CACtB,GAAG,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;CAC7C,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;CAChD,IAAI;CACJ,GAAG;;CAEH,OAAO,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE;CAChC,GAAG,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;CAC/C,GAAG;CACH,EAAE;;CAEF,CAAC,IAAI,KAAK,EAAE;CACZ,EAAE,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;CACnC,EAAE;CACF,CAAC;;;;;;;;;;;;;"}

View File

@@ -0,0 +1,67 @@
{
"_args": [
[
"estree-walker@1.0.1",
"J:\\Github\\CURD-TS"
]
],
"_development": true,
"_from": "estree-walker@1.0.1",
"_id": "estree-walker@1.0.1",
"_inBundle": false,
"_integrity": "sha1-MbxdYSyWtwQQa0d+bdXYqhOMtwA=",
"_location": "/@rollup/plugin-commonjs/@rollup/pluginutils/estree-walker",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "estree-walker@1.0.1",
"name": "estree-walker",
"escapedName": "estree-walker",
"rawSpec": "1.0.1",
"saveSpec": null,
"fetchSpec": "1.0.1"
},
"_requiredBy": [
"/@rollup/plugin-commonjs/@rollup/pluginutils"
],
"_resolved": "http://192.168.250.101:4873/estree-walker/-/estree-walker-1.0.1.tgz",
"_spec": "1.0.1",
"_where": "J:\\Github\\CURD-TS",
"author": {
"name": "Rich Harris"
},
"bugs": {
"url": "https://github.com/Rich-Harris/estree-walker/issues"
},
"description": "Traverse an ESTree-compliant AST",
"devDependencies": {
"@types/estree": "0.0.39",
"mocha": "^5.2.0",
"rollup": "^0.67.3",
"rollup-plugin-sucrase": "^2.1.0",
"typescript": "^3.6.3"
},
"files": [
"src",
"dist",
"types",
"README.md"
],
"homepage": "https://github.com/Rich-Harris/estree-walker#readme",
"license": "MIT",
"main": "dist/estree-walker.umd.js",
"module": "src/estree-walker.js",
"name": "estree-walker",
"repository": {
"type": "git",
"url": "git+https://github.com/Rich-Harris/estree-walker.git"
},
"scripts": {
"build": "tsc && rollup -c",
"prepublishOnly": "npm run build && npm test",
"test": "mocha --opts mocha.opts"
},
"types": "types/index.d.ts",
"version": "1.0.1"
}

View File

@@ -0,0 +1,125 @@
function walk(ast, { enter, leave }) {
return visit(ast, null, enter, leave);
}
let should_skip = false;
let should_remove = false;
let replacement = null;
const context = {
skip: () => should_skip = true,
remove: () => should_remove = true,
replace: (node) => replacement = node
};
function replace(parent, prop, index, node) {
if (parent) {
if (index !== null) {
parent[prop][index] = node;
} else {
parent[prop] = node;
}
}
}
function remove(parent, prop, index) {
if (parent) {
if (index !== null) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
function visit(
node,
parent,
enter,
leave,
prop,
index
) {
if (node) {
if (enter) {
const _should_skip = should_skip;
const _should_remove = should_remove;
const _replacement = replacement;
should_skip = false;
should_remove = false;
replacement = null;
enter.call(context, node, parent, prop, index);
if (replacement) {
node = replacement;
replace(parent, prop, index, node);
}
if (should_remove) {
remove(parent, prop, index);
}
const skipped = should_skip;
const removed = should_remove;
should_skip = _should_skip;
should_remove = _should_remove;
replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
for (const key in node) {
const value = (node )[key];
if (typeof value !== 'object') {
continue;
}
else if (Array.isArray(value)) {
for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
if (value[j] !== null && typeof value[j].type === 'string') {
if (!visit(value[j], node, enter, leave, key, k)) {
// removed
j--;
}
}
}
}
else if (value !== null && typeof value.type === 'string') {
visit(value, node, enter, leave, key, null);
}
}
if (leave) {
const _replacement = replacement;
const _should_remove = should_remove;
replacement = null;
should_remove = false;
leave.call(context, node, parent, prop, index);
if (replacement) {
node = replacement;
replace(parent, prop, index, node);
}
if (should_remove) {
remove(parent, prop, index);
}
const removed = should_remove;
replacement = _replacement;
should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}
export { walk };

View File

@@ -0,0 +1,144 @@
import { BaseNode } from "estree";
type WalkerContext = {
skip: () => void;
remove: () => void;
replace: (node: BaseNode) => void;
};
type WalkerHandler = (
this: WalkerContext,
node: BaseNode,
parent: BaseNode,
key: string,
index: number
) => void
type Walker = {
enter?: WalkerHandler;
leave?: WalkerHandler;
}
export function walk(ast: BaseNode, { enter, leave }: Walker) {
return visit(ast, null, enter, leave);
}
let should_skip = false;
let should_remove = false;
let replacement: BaseNode = null;
const context: WalkerContext = {
skip: () => should_skip = true,
remove: () => should_remove = true,
replace: (node: BaseNode) => replacement = node
};
function replace(parent: any, prop: string, index: number, node: BaseNode) {
if (parent) {
if (index !== null) {
parent[prop][index] = node;
} else {
parent[prop] = node;
}
}
}
function remove(parent: any, prop: string, index: number) {
if (parent) {
if (index !== null) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
function visit(
node: BaseNode,
parent: BaseNode,
enter: WalkerHandler,
leave: WalkerHandler,
prop?: string,
index?: number
) {
if (node) {
if (enter) {
const _should_skip = should_skip;
const _should_remove = should_remove;
const _replacement = replacement;
should_skip = false;
should_remove = false;
replacement = null;
enter.call(context, node, parent, prop, index);
if (replacement) {
node = replacement;
replace(parent, prop, index, node);
}
if (should_remove) {
remove(parent, prop, index);
}
const skipped = should_skip;
const removed = should_remove;
should_skip = _should_skip;
should_remove = _should_remove;
replacement = _replacement;
if (skipped) return node;
if (removed) return null;
}
for (const key in node) {
const value = (node as any)[key];
if (typeof value !== 'object') {
continue;
}
else if (Array.isArray(value)) {
for (let j = 0, k = 0; j < value.length; j += 1, k += 1) {
if (value[j] !== null && typeof value[j].type === 'string') {
if (!visit(value[j], node, enter, leave, key, k)) {
// removed
j--;
}
}
}
}
else if (value !== null && typeof value.type === 'string') {
visit(value, node, enter, leave, key, null);
}
}
if (leave) {
const _replacement = replacement;
const _should_remove = should_remove;
replacement = null;
should_remove = false;
leave.call(context, node, parent, prop, index);
if (replacement) {
node = replacement;
replace(parent, prop, index, node);
}
if (should_remove) {
remove(parent, prop, index);
}
const removed = should_remove;
replacement = _replacement;
should_remove = _should_remove;
if (removed) return null;
}
}
return node;
}

View File

@@ -0,0 +1,13 @@
import { BaseNode } from "estree";
declare type WalkerContext = {
skip: () => void;
remove: () => void;
replace: (node: BaseNode) => void;
};
declare type WalkerHandler = (this: WalkerContext, node: BaseNode, parent: BaseNode, key: string, index: number) => void;
declare type Walker = {
enter?: WalkerHandler;
leave?: WalkerHandler;
};
export declare function walk(ast: BaseNode, { enter, leave }: Walker): BaseNode;
export {};

View File

@@ -0,0 +1,127 @@
{
"_args": [
[
"@rollup/pluginutils@3.1.0",
"J:\\Github\\CURD-TS"
]
],
"_development": true,
"_from": "@rollup/pluginutils@3.1.0",
"_id": "@rollup/pluginutils@3.1.0",
"_inBundle": false,
"_integrity": "sha1-cGtFJO5tyLEDs8mVUz5a1oDAK5s=",
"_location": "/@rollup/plugin-commonjs/@rollup/pluginutils",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "@rollup/pluginutils@3.1.0",
"name": "@rollup/pluginutils",
"escapedName": "@rollup%2fpluginutils",
"scope": "@rollup",
"rawSpec": "3.1.0",
"saveSpec": null,
"fetchSpec": "3.1.0"
},
"_requiredBy": [
"/@rollup/plugin-commonjs"
],
"_resolved": "http://192.168.250.101:4873/@rollup%2fpluginutils/-/pluginutils-3.1.0.tgz",
"_spec": "3.1.0",
"_where": "J:\\Github\\CURD-TS",
"author": {
"name": "Rich Harris",
"email": "richard.a.harris@gmail.com"
},
"ava": {
"compileEnhancements": false,
"extensions": [
"ts"
],
"require": [
"ts-node/register"
],
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"bugs": {
"url": "https://github.com/rollup/plugins/issues"
},
"dependencies": {
"@types/estree": "0.0.39",
"estree-walker": "^1.0.1",
"picomatch": "^2.2.2"
},
"description": "A set of utility functions commonly used by Rollup plugins",
"devDependencies": {
"@rollup/plugin-commonjs": "^11.0.2",
"@rollup/plugin-node-resolve": "^7.1.1",
"@rollup/plugin-typescript": "^3.0.0",
"@types/jest": "^24.9.0",
"@types/node": "^12.12.25",
"@types/picomatch": "^2.2.1",
"typescript": "^3.7.5"
},
"engines": {
"node": ">= 8.0.0"
},
"exports": {
"require": "./dist/cjs/index.js",
"import": "./dist/es/index.js"
},
"files": [
"dist",
"types",
"README.md",
"LICENSE"
],
"homepage": "https://github.com/rollup/plugins/tree/master/packages/pluginutils#readme",
"keywords": [
"rollup",
"plugin",
"utils"
],
"license": "MIT",
"main": "./dist/cjs/index.js",
"module": "./dist/es/index.js",
"name": "@rollup/pluginutils",
"nyc": {
"extension": [
".js",
".ts"
]
},
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rollup/plugins.git"
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm run test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm run build && pnpm run lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm run test -- --verbose",
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
"lint:docs": "prettier --single-quote --write README.md",
"lint:js": "eslint --fix --cache src test types --ext .js,.ts",
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
"prebuild": "del-cli dist",
"prepare": "pnpm run build",
"prepublishOnly": "pnpm run lint && pnpm run build",
"pretest": "pnpm run build -- --sourcemap",
"test": "ava"
},
"type": "commonjs",
"types": "types/index.d.ts",
"version": "3.1.0"
}

View File

@@ -0,0 +1,86 @@
// eslint-disable-next-line import/no-unresolved
import { BaseNode } from 'estree';
export interface AttachedScope {
parent?: AttachedScope;
isBlockScope: boolean;
declarations: { [key: string]: boolean };
addDeclaration(node: BaseNode, isBlockDeclaration: boolean, isVar: boolean): void;
contains(name: string): boolean;
}
export interface DataToEsmOptions {
compact?: boolean;
indent?: string;
namedExports?: boolean;
objectShorthand?: boolean;
preferConst?: boolean;
}
/**
* A valid `minimatch` pattern, or array of patterns.
*/
export type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null;
/**
* Adds an extension to a module ID if one does not exist.
*/
export function addExtension(filename: string, ext?: string): string;
/**
* Attaches `Scope` objects to the relevant nodes of an AST.
* Each `Scope` object has a `scope.contains(name)` method that returns `true`
* if a given name is defined in the current scope or a parent scope.
*/
export function attachScopes(ast: BaseNode, propertyName?: string): AttachedScope;
/**
* Constructs a filter function which can be used to determine whether or not
* certain modules should be operated upon.
* @param include If `include` is omitted or has zero length, filter will return `true` by default.
* @param exclude ID must not match any of the `exclude` patterns.
* @param options Optionally resolves the patterns against a directory other than `process.cwd()`.
* If a `string` is specified, then the value will be used as the base directory.
* Relative paths will be resolved against `process.cwd()` first.
* If `false`, then the patterns will not be resolved against any directory.
* This can be useful if you want to create a filter for virtual module names.
*/
export function createFilter(
include?: FilterPattern,
exclude?: FilterPattern,
options?: { resolve?: string | false | null }
): (id: string | unknown) => boolean;
/**
* Transforms objects into tree-shakable ES Module imports.
* @param data An object to transform into an ES module.
*/
export function dataToEsm(data: unknown, options?: DataToEsmOptions): string;
/**
* Extracts the names of all assignment targets based upon specified patterns.
* @param param An `acorn` AST Node.
*/
export function extractAssignedNames(param: BaseNode): string[];
/**
* Constructs a bundle-safe identifier from a `string`.
*/
export function makeLegalIdentifier(str: string): string;
export type AddExtension = typeof addExtension;
export type AttachScopes = typeof attachScopes;
export type CreateFilter = typeof createFilter;
export type ExtractAssignedNames = typeof extractAssignedNames;
export type MakeLegalIdentifier = typeof makeLegalIdentifier;
export type DataToEsm = typeof dataToEsm;
declare const defaultExport: {
addExtension: AddExtension;
attachScopes: AttachScopes;
createFilter: CreateFilter;
dataToEsm: DataToEsm;
extractAssignedNames: ExtractAssignedNames;
makeLegalIdentifier: MakeLegalIdentifier;
};
export default defaultExport;

125
node_modules/@rollup/plugin-commonjs/package.json generated vendored Normal file
View File

@@ -0,0 +1,125 @@
{
"_args": [
[
"@rollup/plugin-commonjs@15.1.0",
"J:\\Github\\CURD-TS"
]
],
"_development": true,
"_from": "@rollup/plugin-commonjs@15.1.0",
"_id": "@rollup/plugin-commonjs@15.1.0",
"_inBundle": false,
"_integrity": "sha1-Hn0HbE8bKr9+ZSSFcOVV3vw3wjg=",
"_location": "/@rollup/plugin-commonjs",
"_phantomChildren": {
"@types/estree": "0.0.39",
"picomatch": "2.2.2"
},
"_requested": {
"type": "version",
"registry": true,
"raw": "@rollup/plugin-commonjs@15.1.0",
"name": "@rollup/plugin-commonjs",
"escapedName": "@rollup%2fplugin-commonjs",
"scope": "@rollup",
"rawSpec": "15.1.0",
"saveSpec": null,
"fetchSpec": "15.1.0"
},
"_requiredBy": [
"/vite"
],
"_resolved": "http://192.168.250.101:4873/@rollup%2fplugin-commonjs/-/plugin-commonjs-15.1.0.tgz",
"_spec": "15.1.0",
"_where": "J:\\Github\\CURD-TS",
"author": {
"name": "Rich Harris",
"email": "richard.a.harris@gmail.com"
},
"ava": {
"babel": {
"compileEnhancements": false
},
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"bugs": {
"url": "https://github.com/rollup/plugins/issues"
},
"dependencies": {
"@rollup/pluginutils": "^3.1.0",
"commondir": "^1.0.1",
"estree-walker": "^2.0.1",
"glob": "^7.1.6",
"is-reference": "^1.2.1",
"magic-string": "^0.25.7",
"resolve": "^1.17.0"
},
"description": "Convert CommonJS modules to ES2015",
"devDependencies": {
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^8.4.0",
"locate-character": "^2.0.5",
"require-relative": "^0.8.7",
"rollup": "^2.23.0",
"shx": "^0.3.2",
"source-map": "^0.7.3",
"source-map-support": "^0.5.19",
"typescript": "^3.9.7"
},
"engines": {
"node": ">= 8.0.0"
},
"files": [
"dist",
"types",
"README.md",
"LICENSE"
],
"homepage": "https://github.com/rollup/plugins/tree/master/packages/commonjs/#readme",
"keywords": [
"rollup",
"plugin",
"npm",
"modules",
"commonjs",
"require"
],
"license": "MIT",
"main": "dist/index.js",
"module": "dist/index.es.js",
"name": "@rollup/plugin-commonjs",
"peerDependencies": {
"rollup": "^2.22.0"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rollup/plugins.git"
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm run test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm run build && pnpm run lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm run test -- --verbose && pnpm run test:ts",
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
"lint:docs": "prettier --single-quote --arrow-parens avoid --trailing-comma none --write README.md",
"lint:js": "eslint --fix --cache src test types --ext .js,.ts",
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
"prebuild": "del-cli dist",
"prepare": "pnpm run build",
"prepublishOnly": "pnpm run lint && pnpm run test:ts",
"pretest": "pnpm run build",
"test": "ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"
},
"types": "types/index.d.ts",
"version": "15.1.0"
}

150
node_modules/@rollup/plugin-commonjs/types/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,150 @@
import { FilterPattern } from '@rollup/pluginutils';
import { Plugin } from 'rollup';
type RequireReturnsDefaultOption = boolean | 'auto' | 'preferred' | 'namespace';
interface RollupCommonJSOptions {
/**
* A minimatch pattern, or array of patterns, which specifies the files in
* the build the plugin should operate on. By default, all files with
* extension `".cjs"` or those in `extensions` are included, but you can narrow
* this list by only including specific files. These files will be analyzed
* and transpiled if either the analysis does not find ES module specific
* statements or `transformMixedEsModules` is `true`.
* @default undefined
*/
include?: FilterPattern;
/**
* A minimatch pattern, or array of patterns, which specifies the files in
* the build the plugin should _ignore_. By default, all files with
* extensions other than those in `extensions` or `".cjs"` are ignored, but you
* can exclude additional files. See also the `include` option.
* @default undefined
*/
exclude?: FilterPattern;
/**
* For extensionless imports, search for extensions other than .js in the
* order specified. Note that you need to make sure that non-JavaScript files
* are transpiled by another plugin first.
* @default [ '.js' ]
*/
extensions?: ReadonlyArray<string>;
/**
* If true then uses of `global` won't be dealt with by this plugin
* @default false
*/
ignoreGlobal?: boolean;
/**
* If false, skips source map generation for CommonJS modules. This will improve performance.
* @default true
*/
sourceMap?: boolean;
/**
* Instructs the plugin whether to enable mixed module transformations. This
* is useful in scenarios with modules that contain a mix of ES `import`
* statements and CommonJS `require` expressions. Set to `true` if `require`
* calls should be transformed to imports in mixed modules, or `false` if the
* `require` expressions should survive the transformation. The latter can be
* important if the code contains environment detection, or you are coding
* for an environment with special treatment for `require` calls such as
* ElectronJS. See also the `ignore` option.
* @default false
*/
transformMixedEsModules?: boolean;
/**
* Sometimes you have to leave require statements unconverted. Pass an array
* containing the IDs or a `id => boolean` function.
* @default []
*/
ignore?: ReadonlyArray<string> | ((id: string) => boolean);
/**
* Controls how to render imports from external dependencies. By default,
* this plugin assumes that all external dependencies are CommonJS. This
* means they are rendered as default imports to be compatible with e.g.
* NodeJS where ES modules can only import a default export from a CommonJS
* dependency.
*
* If you set `esmExternals` to `true`, this plugins assumes that all
* external dependencies are ES modules and respect the
* `requireReturnsDefault` option. If that option is not set, they will be
* rendered as namespace imports.
*
* You can also supply an array of ids to be treated as ES modules, or a
* function that will be passed each external id to determine if it is an ES
* module.
* @default false
*/
esmExternals?: boolean | ReadonlyArray<string> | ((id: string) => boolean);
/**
* Controls what is returned when requiring an ES module from a CommonJS file.
* When using the `esmExternals` option, this will also apply to external
* modules. By default, this plugin will render those imports as namespace
* imports i.e.
*
* ```js
* // input
* const foo = require('foo');
*
* // output
* import * as foo from 'foo';
* ```
*
* However there are some situations where this may not be desired.
* For these situations, you can change Rollup's behaviour either globally or
* per module. To change it globally, set the `requireReturnsDefault` option
* to one of the following values:
*
* - `false`: This is the default, requiring an ES module returns its
* namespace. This is the only option that will also add a marker
* `__esModule: true` to the namespace to support interop patterns in
* CommonJS modules that are transpiled ES modules.
* - `"namespace"`: Like `false`, requiring an ES module returns its
* namespace, but the plugin does not add the `__esModule` marker and thus
* creates more efficient code. For external dependencies when using
* `esmExternals: true`, no additional interop code is generated.
* - `"auto"`: This is complementary to how `output.exports: "auto"` works in
* Rollup: If a module has a default export and no named exports, requiring
* that module returns the default export. In all other cases, the namespace
* is returned. For external dependencies when using `esmExternals: true`, a
* corresponding interop helper is added.
* - `"preferred"`: If a module has a default export, requiring that module
* always returns the default export, no matter whether additional named
* exports exist. This is similar to how previous versions of this plugin
* worked. Again for external dependencies when using `esmExternals: true`,
* an interop helper is added.
* - `true`: This will always try to return the default export on require
* without checking if it actually exists. This can throw at build time if
* there is no default export. This is how external dependencies are handled
* when `esmExternals` is not used. The advantage over the other options is
* that, like `false`, this does not add an interop helper for external
* dependencies, keeping the code lean.
*
* To change this for individual modules, you can supply a function for
* `requireReturnsDefault` instead. This function will then be called once for
* each required ES module or external dependency with the corresponding id
* and allows you to return different values for different modules.
* @default false
*/
requireReturnsDefault?:
| RequireReturnsDefaultOption
| ((id: string) => RequireReturnsDefaultOption);
/**
* Some modules contain dynamic `require` calls, or require modules that
* contain circular dependencies, which are not handled well by static
* imports. Including those modules as `dynamicRequireTargets` will simulate a
* CommonJS (NodeJS-like) environment for them with support for dynamic and
* circular dependencies.
*
* Note: In extreme cases, this feature may result in some paths being
* rendered as absolute in the final bundle. The plugin tries to avoid
* exposing paths from the local machine, but if you are `dynamicRequirePaths`
* with paths that are far away from your project's folder, that may require
* replacing strings like `"/Users/John/Desktop/foo-project/"` -> `"/"`.
*/
dynamicRequireTargets?: string | ReadonlyArray<string>;
}
/**
* Convert CommonJS modules to ES6, so they can be included in a Rollup bundle
*/
export default function commonjs(options?: RollupCommonJSOptions): Plugin;