Website Structure

This commit is contained in:
supalerk-ar66 2026-01-13 10:46:40 +07:00
parent 62812f2090
commit 71f0676a62
22365 changed files with 4265753 additions and 791 deletions

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,178 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-alias
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-alias
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-alias
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-alias
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-alias
🍣 A Rollup plugin for defining aliases when bundling packages.
## Alias 101
Suppose we have the following `import` defined in a hypothetical file:
```javascript
import batman from '../../../batman';
```
This probably doesn't look too bad on its own. But consider that may not be the only instance in your codebase, and that after a refactor this might be incorrect. With this plugin in place, you can alias `../../../batman` with `batman` for readability and maintainability. In the case of a refactor, only the alias would need to be changed, rather than navigating through the codebase and changing all imports.
```javascript
import batman from 'batman';
```
If this seems familiar to Webpack users, it should. This is plugin mimics the `resolve.extensions` and `resolve.alias` functionality in Webpack.
This plugin will work for any file type that Rollup natively supports, or those which are [supported by third-party plugins](https://github.com/rollup/awesome#other-file-imports).
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```console
npm install @rollup/plugin-alias --save-dev
# or
yarn add -D @rollup/plugin-alias
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import alias from '@rollup/plugin-alias';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [
alias({
entries: [
{ find: 'utils', replacement: '../../../utils' },
{ find: 'batman-1.0.0', replacement: './joker-1.5.0' }
]
})
]
};
```
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). If the build produces any errors, the plugin will write a 'alias' character to stderr, which should be audible on most systems.
## Options
### `customResolver`
Type: `Function | Object`<br>
Default: `null`
Instructs the plugin to use an alternative resolving algorithm, rather than the Rollup's resolver. Please refer to the [Rollup documentation](https://rollupjs.org/guide/en/#resolveid) for more information about the `resolveId` hook. For a detailed example, see: [Custom Resolvers](#custom-resolvers).
### `entries`
Type: `Object | Array[...Object]`<br>
Default: `null`
Specifies an `Object`, or an `Array` of `Object`, which defines aliases used to replace values in `import` or `require` statements. With either format, the order of the entries is important, in that the first defined rules are applied first. This option also supports [Regular Expression Alias](#regular-expression-aliases) matching.
_Note: Entry targets (the object key in the Object Format, or the `find` property value in the Array Format below) should not end with a trailing slash in most cases. If strange behavior is observed, double check the entries being passed in options._
#### `Object` Format
The `Object` format allows specifying aliases as a key, and the corresponding value as the actual `import` value. For example:
```js
alias({
entries: {
utils: '../../../utils',
'batman-1.0.0': './joker-1.5.0'
}
});
```
#### `Array[...Object]` Format
The `Array[...Object]` format allows specifying aliases as objects, which can be useful for complex key/value pairs.
```js
entries: [
{ find: 'utils', replacement: '../../../utils' },
{ find: 'batman-1.0.0', replacement: './joker-1.5.0' }
];
```
## Regular Expression Aliases
Regular Expressions can be used to search in a more distinct and complex manner. e.g. To perform partial replacements via sub-pattern matching.
To remove something in front of an import and append an extension, use a pattern such as:
```js
{ find:/^i18n\!(.*)/, replacement: '$1.js' }
```
This would be useful for loaders, and files that were previously transpiled via the AMD module, to properly handle them in rollup as internals.
To replace extensions with another, a pattern like the following might be used:
```js
{ find:/^(.*)\.js$/, replacement: '$1.alias' }
```
This would replace the file extension for all imports ending with `.js` to `.alias`.
## Resolving algorithm
This plugin uses resolver plugins specified for Rollup and eventually Rollup default algorithm. If you rely on Node specific features, you probably want [@rollup/plugin-node-resolve](https://www.npmjs.com/package/@rollup/plugin-node-resolve) in your setup.
## Custom Resolvers
The `customResolver` option can be leveraged to provide separate module resolution for an individual alias.
Example:
```javascript
// rollup.config.js
import alias from '@rollup/plugin-alias';
import resolve from '@rollup/plugin-node-resolve';
const customResolver = resolve({
extensions: ['.mjs', '.js', '.jsx', '.json', '.sass', '.scss']
});
const projectRootDir = path.resolve(__dirname);
export default {
// ...
plugins: [
alias({
entries: [
{
find: 'src',
replacement: path.resolve(projectRootDir, 'src')
// OR place `customResolver` here. See explanation below.
}
],
customResolver
}),
resolve()
]
};
```
In the example above the alias `src` is used, which uses the `node-resolve` algorithm for files _aliased_ with `src`, by passing the `customResolver` option. The `resolve()` plugin is kept separate in the plugins list for other files which are not _aliased_ with `src`. The `customResolver` option can be passed inside each `entries` item for granular control over resolving allowing each alias a preferred resolver.
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View file

@ -0,0 +1,95 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var path = require('path');
function matches(pattern, importee) {
if (pattern instanceof RegExp) {
return pattern.test(importee);
}
if (importee.length < pattern.length) {
return false;
}
if (importee === pattern) {
return true;
}
// eslint-disable-next-line prefer-template
return importee.startsWith(pattern + '/');
}
function getEntries({ entries, customResolver }) {
if (!entries) {
return [];
}
const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
if (Array.isArray(entries)) {
return entries.map((entry) => {
return {
find: entry.find,
replacement: entry.replacement,
resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
};
});
}
return Object.entries(entries).map(([key, value]) => {
return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions };
});
}
function getHookFunction(hook) {
if (typeof hook === 'function') {
return hook;
}
if (hook && 'handler' in hook && typeof hook.handler === 'function') {
return hook.handler;
}
return null;
}
function resolveCustomResolver(customResolver) {
if (typeof customResolver === 'function') {
return customResolver;
}
if (customResolver) {
return getHookFunction(customResolver.resolveId);
}
return null;
}
function alias(options = {}) {
const entries = getEntries(options);
if (entries.length === 0) {
return {
name: 'alias',
resolveId: () => null
};
}
return {
name: 'alias',
async buildStart(inputOptions) {
await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => { var _a; return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions)); }));
},
resolveId(importee, importer, resolveOptions) {
// First match is supposed to be the correct one
const matchedEntry = entries.find((entry) => matches(entry.find, importee));
if (!matchedEntry) {
return null;
}
const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
if (matchedEntry.resolverFunction) {
return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
}
return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => {
if (resolved)
return resolved;
if (!path.isAbsolute(updatedId)) {
this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. ` +
`This will lead to duplicated modules for the same path. ` +
`To avoid duplicating modules, you should resolve to an absolute path.`);
}
return { id: updatedId };
});
}
};
}
exports.default = alias;
module.exports = Object.assign(exports.default, exports);
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1,90 @@
import path from 'path';
function matches(pattern, importee) {
if (pattern instanceof RegExp) {
return pattern.test(importee);
}
if (importee.length < pattern.length) {
return false;
}
if (importee === pattern) {
return true;
}
// eslint-disable-next-line prefer-template
return importee.startsWith(pattern + '/');
}
function getEntries({ entries, customResolver }) {
if (!entries) {
return [];
}
const resolverFunctionFromOptions = resolveCustomResolver(customResolver);
if (Array.isArray(entries)) {
return entries.map((entry) => {
return {
find: entry.find,
replacement: entry.replacement,
resolverFunction: resolveCustomResolver(entry.customResolver) || resolverFunctionFromOptions
};
});
}
return Object.entries(entries).map(([key, value]) => {
return { find: key, replacement: value, resolverFunction: resolverFunctionFromOptions };
});
}
function getHookFunction(hook) {
if (typeof hook === 'function') {
return hook;
}
if (hook && 'handler' in hook && typeof hook.handler === 'function') {
return hook.handler;
}
return null;
}
function resolveCustomResolver(customResolver) {
if (typeof customResolver === 'function') {
return customResolver;
}
if (customResolver) {
return getHookFunction(customResolver.resolveId);
}
return null;
}
function alias(options = {}) {
const entries = getEntries(options);
if (entries.length === 0) {
return {
name: 'alias',
resolveId: () => null
};
}
return {
name: 'alias',
async buildStart(inputOptions) {
await Promise.all([...(Array.isArray(options.entries) ? options.entries : []), options].map(({ customResolver }) => { var _a; return customResolver && ((_a = getHookFunction(customResolver.buildStart)) === null || _a === void 0 ? void 0 : _a.call(this, inputOptions)); }));
},
resolveId(importee, importer, resolveOptions) {
// First match is supposed to be the correct one
const matchedEntry = entries.find((entry) => matches(entry.find, importee));
if (!matchedEntry) {
return null;
}
const updatedId = importee.replace(matchedEntry.find, matchedEntry.replacement);
if (matchedEntry.resolverFunction) {
return matchedEntry.resolverFunction.call(this, updatedId, importer, resolveOptions);
}
return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, resolveOptions)).then((resolved) => {
if (resolved)
return resolved;
if (!path.isAbsolute(updatedId)) {
this.warn(`rewrote ${importee} to ${updatedId} but was not an abolute path and was not handled by other plugins. ` +
`This will lead to duplicated modules for the same path. ` +
`To avoid duplicating modules, you should resolve to an absolute path.`);
}
return { id: updatedId };
});
}
};
}
export { alias as default };
//# sourceMappingURL=index.js.map

View file

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

View file

@ -0,0 +1,77 @@
{
"name": "@rollup/plugin-alias",
"version": "5.1.1",
"publishConfig": {
"access": "public"
},
"description": "Define and resolve aliases for bundle dependencies",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/alias"
},
"author": "Johannes Stein",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/alias#readme",
"bugs": "https://github.com/rollup/plugins/issues",
"main": "./dist/cjs/index.js",
"module": "./dist/es/index.js",
"exports": {
"types": "./types/index.d.ts",
"import": "./dist/es/index.js",
"default": "./dist/cjs/index.js"
},
"engines": {
"node": ">=14.0.0"
},
"files": [
"dist",
"!dist/**/*.map",
"types",
"README.md",
"LICENSE"
],
"keywords": [
"rollup",
"plugin",
"resolve",
"alias"
],
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
},
"devDependencies": {
"@rollup/plugin-node-resolve": "^15.0.0",
"@rollup/plugin-typescript": "^9.0.1",
"del-cli": "^5.0.0",
"rollup": "^4.0.0-24",
"typescript": "^4.8.3"
},
"types": "./types/index.d.ts",
"ava": {
"files": [
"!**/fixtures/**",
"!**/output/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm build && pnpm lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm test -- --verbose",
"prebuild": "del-cli dist",
"prerelease": "pnpm build",
"pretest": "pnpm build",
"release": "pnpm --workspace-root package:release $(pwd)",
"test": "ava",
"test:ts": "tsc --noEmit"
}
}

View file

@ -0,0 +1,44 @@
import type { Plugin, PluginHooks } from 'rollup';
type MapToFunction<T> = T extends Function ? T : never;
export type ResolverFunction = MapToFunction<PluginHooks['resolveId']>;
export interface ResolverObject {
buildStart?: PluginHooks['buildStart'];
resolveId: ResolverFunction;
}
export interface Alias {
find: string | RegExp;
replacement: string;
customResolver?: ResolverFunction | ResolverObject | null;
}
export interface ResolvedAlias {
find: string | RegExp;
replacement: string;
resolverFunction: ResolverFunction | null;
}
export interface RollupAliasOptions {
/**
* Instructs the plugin to use an alternative resolving algorithm,
* rather than the Rollup's resolver.
* @default null
*/
customResolver?: ResolverFunction | ResolverObject | null;
/**
* Specifies an `Object`, or an `Array` of `Object`,
* which defines aliases used to replace values in `import` or `require` statements.
* With either format, the order of the entries is important,
* in that the first defined rules are applied first.
*/
entries?: readonly Alias[] | { [find: string]: string };
}
/**
* 🍣 A Rollup plugin for defining aliases when bundling packages.
*/
export default function alias(options?: RollupAliasOptions): Plugin;

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,479 @@
[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 (v14.0.0+) and Rollup v2.68.0+. If you are using [`@rollup/plugin-node-resolve`](https://github.com/rollup/plugins/tree/master/packages/node-resolve), it should be v13.0.6+.
## 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).
When used together with the node-resolve plugin
## Options
### `strictRequires`
Type: `"auto" | boolean | "debug" | string[]`<br>
Default: `true`
Historically, this plugin tried to hoist `require` statements as imports to the top of each file. While this works well for many code bases and allows for very efficient ESM output, it does not perfectly capture CommonJS semantics as the initialisation order of required modules will be different. The resultant side effects can include log statements being emitted in a different order, and some code that is dependent on the initialisation order of polyfills in require statements may not work. But it is especially problematic when there are circular `require` calls between CommonJS modules as those often rely on the lazy execution of nested `require` calls.
The default value of `true` will wrap all CommonJS files in functions which are executed when they are required for the first time, preserving NodeJS semantics. This is the safest setting and should be used if the generated code does not work correctly with `"auto"`. Note that `strictRequires: true` can have a small impact on the size and performance of generated code, but less so if the code is minified.
Setting this option to `"auto"` will only wrap CommonJS files when they are part of a CommonJS dependency cycle, e.g. an index file that is required by some of its dependencies, or if they are only required in a potentially "conditional" way like from within an if-statement or a function. All other CommonJS files are hoisted. This is the recommended setting for most code bases. Note that the detection of conditional requires can be subject to race conditions if there are both conditional and unconditional requires of the same file, which in edge cases may result in inconsistencies between builds. If you think this is a problem for you, you can avoid this by using any value other than `"auto"` or `"debug"`.
`false` will entirely prevent wrapping and hoist all files. This may still work depending on the nature of cyclic dependencies but will often cause problems.
You can also provide a [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, to only specify a subset of files which should be wrapped in functions for proper `require` semantics.
`"debug"` works like `"auto"` but after bundling, it will display a warning containing a list of ids that have been wrapped which can be used as picomatch pattern for fine-tuning or to avoid the potential race conditions mentioned for `"auto"`.
### `dynamicRequireTargets`
Type: `string | string[]`<br>
Default: `[]`
_Note: In previous versions, this option would spin up a rather comprehensive mock environment that was capable of handling modules that manipulate `require.cache`. This is no longer supported. If you rely on this e.g. when using request-promise-native, use version 21 of this plugin._
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 dependencies. It also enables `strictRequires` for those modules, see above.
_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'
]
});
```
### `dynamicRequireRoot`
Type: `string`<br>
Default: `process.cwd()`
To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/` may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your home directory name. By default it uses the current working directory.
### `exclude`
Type: `string | string[]`<br>
Default: `null`
A [picomatch pattern](https://github.com/micromatch/picomatch), 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 [picomatch pattern](https://github.com/micromatch/picomatch), 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.
### `ignoreTryCatch`
Type: `boolean | 'remove' | string[] | ((id: string) => boolean)`<br>
Default: `true`
In most cases, where `require` calls to external dependencies are inside a `try-catch` clause, they should be left unconverted as it requires an optional dependency that may or may not be installed beside the rolled up package.
Due to the conversion of `require` to a static `import` - the call is hoisted to the top of the file, outside of the `try-catch` clause.
- `true`: All external `require` calls inside a `try` will be left unconverted.
- `false`: All external `require` calls inside a `try` will be converted as if the `try-catch` clause is not there.
- `remove`: Remove all external `require` calls from inside any `try` block.
- `string[]`: Pass an array containing the IDs to left unconverted.
- `((id: string) => boolean|'remove')`: Pass a function that control individual IDs.
Note that non-external requires will not be ignored by this option.
### `ignoreDynamicRequires`
Type: `boolean`
Default: false
Some `require` calls cannot be resolved statically to be translated to imports, e.g.
```js
function wrappedRequire(target) {
return require(target);
}
wrappedRequire('foo');
wrappedRequire('bar');
```
When this option is set to `false`, the generated code will either directly throw an error when such a call is encountered or, when `dynamicRequireTargets` is used, when such a call cannot be resolved with a configured dynamic require target.
Setting this option to `true` will instead leave the `require` call in the code or use it as a fallback for `dynamicRequireTargets`.
### `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.
### `defaultIsModuleExports`
Type: `boolean | "auto"`<br>
Default: `"auto"`
Controls what is the default export when importing a CommonJS file from an ES module.
- `true`: The value of the default export is `module.exports`. This currently matches the behavior of Node.js when importing a CommonJS file.
```js
// mod.cjs
exports.default = 3;
```
```js
import foo from './mod.cjs';
console.log(foo); // { default: 3 }
```
- `false`: The value of the default export is `exports.default`.
```js
// mod.cjs
exports.default = 3;
```
```js
import foo from './mod.cjs';
console.log(foo); // 3
```
- `"auto"`: The value of the default export is `exports.default` if the CommonJS file has an `exports.__esModule === true` property; otherwise it's `module.exports`. This makes it possible to import
the default export of ES modules compiled to CommonJS as if they were not compiled.
```js
// mod.cjs
exports.default = 3;
```
```js
// mod-compiled.cjs
exports.__esModule = true;
exports.default = 3;
```
```js
import foo from './mod.cjs';
import bar from './mod-compiled.cjs';
console.log(foo); // { default: 3 }
console.log(bar); // 3
```
### `requireReturnsDefault`
Type: `boolean | "namespace" | "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) {
if (n.__esModule) return n;
var f = n.default;
if (typeof f == 'function') {
var a = function a() {
var isInstance = false;
try {
isInstance = this instanceof a;
} catch {}
if (isInstance) {
return Reflect.construct(f, arguments, this.constructor);
}
return f.apply(this, arguments);
};
a.prototype = f.prototype;
} else a = {};
Object.defineProperty(a, '__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 CommonJS files as entry points
With this plugin, you can also use CommonJS files as entry points. This means, however, that when you are bundling to an ES module, your bundle will only have a default export. If you want named exports instead, you should use an ES module entry point instead that reexports from your CommonJS entry point, e.g.
```js
// main.cjs, the CommonJS entry
exports.foo = 'foo';
exports.bar = 'bar';
// main.mjs, the ES module entry
export { foo, bar } from './main.cjs';
// rollup.config.mjs
export default {
input: 'main.mjs',
output: {
format: 'es',
file: 'bundle.mjs'
}
};
```
When bundling to CommonJS or IIFE, i.e `output.format === 'cjs'` / `output.format === 'iife'`, make sure that you do not set `output.exports` to `'named'`. The default value of `'auto'` will usually work, but you can also set it explicitly to `'default'`. That makes sure that Rollup assigns the default export that was generated for your CommonJS entry point to `module.exports`, and semantics do not change.
## 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: [commonjs(), resolve()]
};
```
## 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.
## Inter-plugin-communication
This plugin exposes the result of its CommonJS file type detection for other plugins to use. You can access it via `this.getModuleInfo` or the `moduleParsed` hook:
```js
function cjsDetectionPlugin() {
return {
name: 'cjs-detection',
moduleParsed({
id,
meta: {
commonjs: { isCommonJS }
}
}) {
console.log(`File ${id} is CommonJS: ${isCommonJS}`);
}
};
}
```
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

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

View file

@ -0,0 +1,91 @@
{
"name": "@rollup/plugin-commonjs",
"version": "28.0.9",
"publishConfig": {
"access": "public"
},
"description": "Convert CommonJS modules to ES2015",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/commonjs"
},
"author": "Rich Harris <richard.a.harris@gmail.com>",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/commonjs/#readme",
"bugs": "https://github.com/rollup/plugins/issues",
"main": "./dist/cjs/index.js",
"module": "./dist/es/index.js",
"exports": {
"types": "./types/index.d.ts",
"import": "./dist/es/index.js",
"default": "./dist/cjs/index.js"
},
"engines": {
"node": ">=16.0.0 || 14 >= 14.17"
},
"files": [
"dist",
"!dist/**/*.map",
"types",
"README.md",
"LICENSE"
],
"keywords": [
"rollup",
"plugin",
"npm",
"modules",
"commonjs",
"require"
],
"peerDependencies": {
"rollup": "^2.68.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
},
"dependencies": {
"@rollup/pluginutils": "^5.0.1",
"commondir": "^1.0.1",
"estree-walker": "^2.0.2",
"fdir": "^6.2.0",
"is-reference": "1.2.1",
"magic-string": "^0.30.3",
"picomatch": "^4.0.2"
},
"devDependencies": {
"@rollup/plugin-json": "^5.0.0",
"@rollup/plugin-node-resolve": "^15.0.0",
"locate-character": "^2.0.5",
"require-relative": "^0.8.7",
"rollup": "^4.0.0-24",
"source-map": "^0.7.4",
"source-map-support": "^0.5.21",
"typescript": "^4.8.3"
},
"types": "./types/index.d.ts",
"ava": {
"workerThreads": false,
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm build && pnpm lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm test -- --verbose && pnpm test:ts",
"prebuild": "del-cli dist",
"prerelease": "pnpm build",
"pretest": "pnpm build",
"release": "pnpm --workspace-root package:release $(pwd)",
"test": "ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"
}
}

View file

@ -0,0 +1,233 @@
import type { FilterPattern } from '@rollup/pluginutils';
import type { Plugin } from 'rollup';
type RequireReturnsDefaultOption = boolean | 'auto' | 'preferred' | 'namespace';
type DefaultIsModuleExportsOption = boolean | 'auto';
interface RollupCommonJSOptions {
/**
* A picomatch 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 picomatch 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;
/**
* Some `require` calls cannot be resolved statically to be translated to
* imports.
* When this option is set to `false`, the generated code will either
* directly throw an error when such a call is encountered or, when
* `dynamicRequireTargets` is used, when such a call cannot be resolved with a
* configured dynamic require target.
* Setting this option to `true` will instead leave the `require` call in the
* code or use it as a fallback for `dynamicRequireTargets`.
* @default false
*/
ignoreDynamicRequires?: 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;
/**
* By default, this plugin will try to hoist `require` statements as imports
* to the top of each file. While this works well for many code bases and
* allows for very efficient ESM output, it does not perfectly capture
* CommonJS semantics as the order of side effects like log statements may
* change. But it is especially problematic when there are circular `require`
* calls between CommonJS modules as those often rely on the lazy execution of
* nested `require` calls.
*
* Setting this option to `true` will wrap all CommonJS files in functions
* which are executed when they are required for the first time, preserving
* NodeJS semantics. Note that this can have an impact on the size and
* performance of the generated code.
*
* The default value of `"auto"` will only wrap CommonJS files when they are
* part of a CommonJS dependency cycle, e.g. an index file that is required by
* many of its dependencies. All other CommonJS files are hoisted. This is the
* recommended setting for most code bases.
*
* `false` will entirely prevent wrapping and hoist all files. This may still
* work depending on the nature of cyclic dependencies but will often cause
* problems.
*
* You can also provide a picomatch pattern, or array of patterns, to only
* specify a subset of files which should be wrapped in functions for proper
* `require` semantics.
*
* `"debug"` works like `"auto"` but after bundling, it will display a warning
* containing a list of ids that have been wrapped which can be used as
* picomatch pattern for fine-tuning.
* @default "auto"
*/
strictRequires?: boolean | FilterPattern;
/**
* 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);
/**
* In most cases, where `require` calls are inside a `try-catch` clause,
* they should be left unconverted as it requires an optional dependency
* that may or may not be installed beside the rolled up package.
* Due to the conversion of `require` to a static `import` - the call is
* hoisted to the top of the file, outside the `try-catch` clause.
*
* - `true`: Default. All `require` calls inside a `try` will be left unconverted.
* - `false`: All `require` calls inside a `try` will be converted as if the
* `try-catch` clause is not there.
* - `remove`: Remove all `require` calls from inside any `try` block.
* - `string[]`: Pass an array containing the IDs to left unconverted.
* - `((id: string) => boolean|'remove')`: Pass a function that controls
* individual IDs.
*
* @default true
*/
ignoreTryCatch?:
| boolean
| 'remove'
| ReadonlyArray<string>
| ((id: string) => boolean | 'remove');
/**
* 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 plugin 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 whether 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);
/**
* @default "auto"
*/
defaultIsModuleExports?:
| DefaultIsModuleExportsOption
| ((id: string) => DefaultIsModuleExportsOption);
/**
* 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
* dependencies. It also enables `strictRequires` for those modules.
*
* 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>;
/**
* To avoid long paths when using the `dynamicRequireTargets` option, you can use this option to specify a directory
* that is a common parent for all files that use dynamic require statements. Using a directory higher up such as `/`
* may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your
* home directory name. By default, it uses the current working directory.
*/
dynamicRequireRoot?: string;
}
/**
* Convert CommonJS modules to ES6, so they can be included in a Rollup bundle
*/
export default function commonjs(options?: RollupCommonJSOptions): Plugin;

View file

@ -0,0 +1,96 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-inject
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-inject
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-inject
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-inject
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-inject
🍣 A Rollup plugin which scans modules for global variables and injects `import` statements where necessary.
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```console
npm install @rollup/plugin-inject --save-dev
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import inject from '@rollup/plugin-inject';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [
inject({
Promise: ['es6-promise', 'Promise']
})
]
};
```
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).
This configuration above will scan all your files for global Promise usage and plugin will add import to desired module (`import { Promise } from 'es6-promise'` in this case).
Examples:
```js
{
// import { Promise } from 'es6-promise'
Promise: [ 'es6-promise', 'Promise' ],
// import { Promise as P } from 'es6-promise'
P: [ 'es6-promise', 'Promise' ],
// import $ from 'jquery'
$: 'jquery',
// import * as fs from 'fs'
fs: [ 'fs', '*' ],
// use a local module instead of a third-party one
'Object.assign': path.resolve( 'src/helpers/object-assign.js' ),
}
```
Typically, `@rollup/plugin-inject` should be placed in `plugins` _before_ other plugins so that they may apply optimizations, such as dead code removal.
## Options
In addition to the properties and values specified for injecting, users may also specify the options below.
### `exclude`
Type: `String` | `Array[...String]`<br>
Default: `null`
A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default no files are ignored.
### `include`
Type: `String` | `Array[...String]`<br>
Default: `null`
A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default all files are targeted.
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View file

@ -0,0 +1,218 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var path = require('path');
var pluginutils = require('@rollup/pluginutils');
var estreeWalker = require('estree-walker');
var MagicString = require('magic-string');
var escape = function (str) { return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'); };
var isReference = function (node, parent) {
if (node.type === 'MemberExpression') {
return !node.computed && isReference(node.object, node);
}
if (node.type === 'Identifier') {
// TODO is this right?
if (parent.type === 'MemberExpression') { return parent.computed || node === parent.object; }
// disregard the `bar` in { bar: foo }
if (parent.type === 'Property' && node !== parent.value) { return false; }
// disregard the `bar` in `class Foo { bar () {...} }`
if (parent.type === 'MethodDefinition') { return false; }
// disregard the `bar` in `export { foo as bar }`
if (parent.type === 'ExportSpecifier' && node !== parent.local) { return false; }
// disregard the `bar` in `import { bar as foo }`
if (parent.type === 'ImportSpecifier' && node === parent.imported) {
return false;
}
return true;
}
return false;
};
var flatten = function (startNode) {
var parts = [];
var node = startNode;
while (node.type === 'MemberExpression') {
parts.unshift(node.property.name);
node = node.object;
}
var name = node.name;
parts.unshift(name);
return { name: name, keypath: parts.join('.') };
};
function inject(options) {
if (!options) { throw new Error('Missing options'); }
var filter = pluginutils.createFilter(options.include, options.exclude);
var modules = options.modules;
if (!modules) {
modules = Object.assign({}, options);
delete modules.include;
delete modules.exclude;
delete modules.sourceMap;
delete modules.sourcemap;
}
var modulesMap = new Map(Object.entries(modules));
// Fix paths on Windows
if (path.sep !== '/') {
modulesMap.forEach(function (mod, key) {
modulesMap.set(
key,
Array.isArray(mod) ? [mod[0].split(path.sep).join('/'), mod[1]] : mod.split(path.sep).join('/')
);
});
}
var firstpass = new RegExp(("(?:" + (Array.from(modulesMap.keys()).map(escape).join('|')) + ")"), 'g');
var sourceMap = options.sourceMap !== false && options.sourcemap !== false;
return {
name: 'inject',
transform: function transform(code, id) {
if (!filter(id)) { return null; }
if (code.search(firstpass) === -1) { return null; }
if (path.sep !== '/') { id = id.split(path.sep).join('/'); } // eslint-disable-line no-param-reassign
var ast = null;
try {
ast = this.parse(code);
} catch (err) {
this.warn({
code: 'PARSE_ERROR',
message: ("rollup-plugin-inject: failed to parse " + id + ". Consider restricting the plugin to particular files via options.include")
});
}
if (!ast) {
return null;
}
var imports = new Set();
ast.body.forEach(function (node) {
if (node.type === 'ImportDeclaration') {
node.specifiers.forEach(function (specifier) {
imports.add(specifier.local.name);
});
}
});
// analyse scopes
var scope = pluginutils.attachScopes(ast, 'scope');
var magicString = new MagicString(code);
var newImports = new Map();
function handleReference(node, name, keypath) {
var mod = modulesMap.get(keypath);
if (mod && !imports.has(name) && !scope.contains(name)) {
if (typeof mod === 'string') { mod = [mod, 'default']; }
// prevent module from importing itself
if (mod[0] === id) { return false; }
var hash = keypath + ":" + (mod[0]) + ":" + (mod[1]);
var importLocalName =
name === keypath ? name : pluginutils.makeLegalIdentifier(("$inject_" + keypath));
if (!newImports.has(hash)) {
// escape apostrophes and backslashes for use in single-quoted string literal
var modName = mod[0].replace(/[''\\]/g, '\\$&');
if (mod[1] === '*') {
newImports.set(hash, ("import * as " + importLocalName + " from '" + modName + "';"));
} else {
newImports.set(hash, ("import { " + (mod[1]) + " as " + importLocalName + " } from '" + modName + "';"));
}
}
if (name !== keypath) {
magicString.overwrite(node.start, node.end, importLocalName, {
storeName: true
});
}
return true;
}
return false;
}
estreeWalker.walk(ast, {
enter: function enter(node, parent) {
if (sourceMap) {
magicString.addSourcemapLocation(node.start);
magicString.addSourcemapLocation(node.end);
}
if (node.scope) {
scope = node.scope; // eslint-disable-line prefer-destructuring
}
// special case shorthand properties. because node.key === node.value,
// we can't differentiate once we've descended into the node
if (node.type === 'Property' && node.shorthand && node.value.type === 'Identifier') {
var ref = node.key;
var name = ref.name;
handleReference(node, name, name);
this.skip();
return;
}
if (isReference(node, parent)) {
var ref$1 = flatten(node);
var name$1 = ref$1.name;
var keypath = ref$1.keypath;
var handled = handleReference(node, name$1, keypath);
if (handled) {
this.skip();
}
}
},
leave: function leave(node) {
if (node.scope) {
scope = scope.parent;
}
}
});
if (newImports.size === 0) {
return {
code: code,
ast: ast,
map: sourceMap ? magicString.generateMap({ hires: true }) : null
};
}
var importBlock = Array.from(newImports.values()).join('\n\n');
magicString.prepend((importBlock + "\n\n"));
return {
code: magicString.toString(),
map: sourceMap ? magicString.generateMap({ hires: true }) : null
};
}
};
}
exports.default = inject;
module.exports = Object.assign(exports.default, exports);
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1,213 @@
import { sep } from 'path';
import { createFilter, attachScopes, makeLegalIdentifier } from '@rollup/pluginutils';
import { walk } from 'estree-walker';
import MagicString from 'magic-string';
var escape = function (str) { return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&'); };
var isReference = function (node, parent) {
if (node.type === 'MemberExpression') {
return !node.computed && isReference(node.object, node);
}
if (node.type === 'Identifier') {
// TODO is this right?
if (parent.type === 'MemberExpression') { return parent.computed || node === parent.object; }
// disregard the `bar` in { bar: foo }
if (parent.type === 'Property' && node !== parent.value) { return false; }
// disregard the `bar` in `class Foo { bar () {...} }`
if (parent.type === 'MethodDefinition') { return false; }
// disregard the `bar` in `export { foo as bar }`
if (parent.type === 'ExportSpecifier' && node !== parent.local) { return false; }
// disregard the `bar` in `import { bar as foo }`
if (parent.type === 'ImportSpecifier' && node === parent.imported) {
return false;
}
return true;
}
return false;
};
var flatten = function (startNode) {
var parts = [];
var node = startNode;
while (node.type === 'MemberExpression') {
parts.unshift(node.property.name);
node = node.object;
}
var name = node.name;
parts.unshift(name);
return { name: name, keypath: parts.join('.') };
};
function inject(options) {
if (!options) { throw new Error('Missing options'); }
var filter = createFilter(options.include, options.exclude);
var modules = options.modules;
if (!modules) {
modules = Object.assign({}, options);
delete modules.include;
delete modules.exclude;
delete modules.sourceMap;
delete modules.sourcemap;
}
var modulesMap = new Map(Object.entries(modules));
// Fix paths on Windows
if (sep !== '/') {
modulesMap.forEach(function (mod, key) {
modulesMap.set(
key,
Array.isArray(mod) ? [mod[0].split(sep).join('/'), mod[1]] : mod.split(sep).join('/')
);
});
}
var firstpass = new RegExp(("(?:" + (Array.from(modulesMap.keys()).map(escape).join('|')) + ")"), 'g');
var sourceMap = options.sourceMap !== false && options.sourcemap !== false;
return {
name: 'inject',
transform: function transform(code, id) {
if (!filter(id)) { return null; }
if (code.search(firstpass) === -1) { return null; }
if (sep !== '/') { id = id.split(sep).join('/'); } // eslint-disable-line no-param-reassign
var ast = null;
try {
ast = this.parse(code);
} catch (err) {
this.warn({
code: 'PARSE_ERROR',
message: ("rollup-plugin-inject: failed to parse " + id + ". Consider restricting the plugin to particular files via options.include")
});
}
if (!ast) {
return null;
}
var imports = new Set();
ast.body.forEach(function (node) {
if (node.type === 'ImportDeclaration') {
node.specifiers.forEach(function (specifier) {
imports.add(specifier.local.name);
});
}
});
// analyse scopes
var scope = attachScopes(ast, 'scope');
var magicString = new MagicString(code);
var newImports = new Map();
function handleReference(node, name, keypath) {
var mod = modulesMap.get(keypath);
if (mod && !imports.has(name) && !scope.contains(name)) {
if (typeof mod === 'string') { mod = [mod, 'default']; }
// prevent module from importing itself
if (mod[0] === id) { return false; }
var hash = keypath + ":" + (mod[0]) + ":" + (mod[1]);
var importLocalName =
name === keypath ? name : makeLegalIdentifier(("$inject_" + keypath));
if (!newImports.has(hash)) {
// escape apostrophes and backslashes for use in single-quoted string literal
var modName = mod[0].replace(/[''\\]/g, '\\$&');
if (mod[1] === '*') {
newImports.set(hash, ("import * as " + importLocalName + " from '" + modName + "';"));
} else {
newImports.set(hash, ("import { " + (mod[1]) + " as " + importLocalName + " } from '" + modName + "';"));
}
}
if (name !== keypath) {
magicString.overwrite(node.start, node.end, importLocalName, {
storeName: true
});
}
return true;
}
return false;
}
walk(ast, {
enter: function enter(node, parent) {
if (sourceMap) {
magicString.addSourcemapLocation(node.start);
magicString.addSourcemapLocation(node.end);
}
if (node.scope) {
scope = node.scope; // eslint-disable-line prefer-destructuring
}
// special case shorthand properties. because node.key === node.value,
// we can't differentiate once we've descended into the node
if (node.type === 'Property' && node.shorthand && node.value.type === 'Identifier') {
var ref = node.key;
var name = ref.name;
handleReference(node, name, name);
this.skip();
return;
}
if (isReference(node, parent)) {
var ref$1 = flatten(node);
var name$1 = ref$1.name;
var keypath = ref$1.keypath;
var handled = handleReference(node, name$1, keypath);
if (handled) {
this.skip();
}
}
},
leave: function leave(node) {
if (node.scope) {
scope = scope.parent;
}
}
});
if (newImports.size === 0) {
return {
code: code,
ast: ast,
map: sourceMap ? magicString.generateMap({ hires: true }) : null
};
}
var importBlock = Array.from(newImports.values()).join('\n\n');
magicString.prepend((importBlock + "\n\n"));
return {
code: magicString.toString(),
map: sourceMap ? magicString.generateMap({ hires: true }) : null
};
}
};
}
export { inject as default };
//# sourceMappingURL=index.js.map

View file

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

View file

@ -0,0 +1,85 @@
{
"name": "@rollup/plugin-inject",
"version": "5.0.5",
"publishConfig": {
"access": "public"
},
"description": "Scan modules for global variables and injects `import` statements where necessary",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/inject"
},
"author": "Rich Harris <richard.a.harris@gmail.com>",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/inject#readme",
"bugs": "https://github.com/rollup/plugins/issues",
"main": "./dist/cjs/index.js",
"module": "./dist/es/index.js",
"exports": {
"types": "./types/index.d.ts",
"import": "./dist/es/index.js",
"default": "./dist/cjs/index.js"
},
"engines": {
"node": ">=14.0.0"
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm build && pnpm lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm test -- --verbose && pnpm test:ts",
"prebuild": "del-cli dist",
"prepare": "if [ ! -d 'dist' ]; then pnpm build; fi",
"prerelease": "pnpm build",
"pretest": "pnpm build",
"release": "pnpm --workspace-root plugin:release --pkg $npm_package_name",
"test": "ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"
},
"files": [
"dist",
"!dist/**/*.map",
"types",
"README.md",
"LICENSE"
],
"keywords": [
"rollup",
"plugin",
"inject",
"es2015",
"npm",
"modules"
],
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
},
"dependencies": {
"@rollup/pluginutils": "^5.0.1",
"estree-walker": "^2.0.2",
"magic-string": "^0.30.3"
},
"devDependencies": {
"@rollup/plugin-buble": "^1.0.0",
"del-cli": "^5.0.0",
"locate-character": "^2.0.5",
"rollup": "^4.0.0-24",
"source-map": "^0.7.4",
"typescript": "^4.8.3"
},
"types": "./types/index.d.ts",
"ava": {
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
}
}

View file

@ -0,0 +1,42 @@
import type { Plugin } from 'rollup';
type Injectment = string | [string, string];
export interface RollupInjectOptions {
/**
* All other options are treated as `string: injectment` injectrs,
* or `string: (id) => injectment` functions.
*/
[str: string]:
| Injectment
| RollupInjectOptions['include']
| RollupInjectOptions['sourceMap']
| RollupInjectOptions['modules'];
/**
* A picomatch pattern, or array of patterns, of files that should be
* processed by this plugin (if omitted, all files are included by default)
*/
include?: string | RegExp | ReadonlyArray<string | RegExp> | null;
/**
* Files that should be excluded, if `include` is otherwise too permissive.
*/
exclude?: string | RegExp | ReadonlyArray<string | RegExp> | null;
/**
* If false, skips source map generation. This will improve performance.
* @default true
*/
sourceMap?: boolean;
/**
* You can separate values to inject from other options.
*/
modules?: { [str: string]: Injectment };
}
/**
* inject strings in files while bundling them.
*/
export default function inject(options?: RollupInjectOptions): Plugin;

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,110 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-json
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-json
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-json
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-json
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-json
🍣 A Rollup plugin which Converts .json files to ES6 modules.
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```console
npm install @rollup/plugin-json --save-dev
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import json from '@rollup/plugin-json';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [json()]
};
```
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).
With an accompanying file `src/index.js`, the local `package.json` file would now be importable as seen below:
```js
// src/index.js
import { readFileSync } from 'fs';
const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
console.log(`running version ${pkg.version}`);
```
## Options
### `compact`
Type: `Boolean`<br>
Default: `false`
If `true`, instructs the plugin to ignore `indent` and generates the smallest code.
### `exclude`
Type: `String` | `Array[...String]`<br>
Default: `null`
A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default no files are ignored.
### `include`
Type: `String` | `Array[...String]`<br>
Default: `null`
A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default all files are targeted.
### `includeArbitraryNames`
Type: `Boolean`<br>
Default: `false`
If `true` and `namedExports` is `true`, generates a named export for not a valid identifier properties of the JSON object by leveraging the ["Arbitrary Module Namespace Identifier Names" feature](https://github.com/tc39/ecma262/pull/2154).
### `indent`
Type: `String`<br>
Default: `'\t'`
Specifies the indentation for the generated default export.
### `namedExports`
Type: `Boolean`<br>
Default: `true`
If `true`, instructs the plugin to generate a named export for every property of the JSON object.
### `preferConst`
Type: `Boolean`<br>
Default: `false`
If `true`, instructs the plugin to declare properties as variables, using either `var` or `const`. This pertains to tree-shaking.
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View file

@ -0,0 +1,43 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var pluginutils = require('@rollup/pluginutils');
function json(options) {
if ( options === void 0 ) options = {};
var filter = pluginutils.createFilter(options.include, options.exclude);
var indent = 'indent' in options ? options.indent : '\t';
return {
name: 'json',
// eslint-disable-next-line no-shadow
transform: function transform(code, id) {
if (id.slice(-5) !== '.json' || !filter(id)) { return null; }
try {
var parsed = JSON.parse(code);
return {
code: pluginutils.dataToEsm(parsed, {
preferConst: options.preferConst,
compact: options.compact,
namedExports: options.namedExports,
includeArbitraryNames: options.includeArbitraryNames,
indent: indent
}),
map: { mappings: '' }
};
} catch (err) {
var message = 'Could not parse JSON file';
this.error({ message: message, id: id, cause: err });
return null;
}
}
};
}
exports.default = json;
module.exports = Object.assign(exports.default, exports);
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1,38 @@
import { createFilter, dataToEsm } from '@rollup/pluginutils';
function json(options) {
if ( options === void 0 ) options = {};
var filter = createFilter(options.include, options.exclude);
var indent = 'indent' in options ? options.indent : '\t';
return {
name: 'json',
// eslint-disable-next-line no-shadow
transform: function transform(code, id) {
if (id.slice(-5) !== '.json' || !filter(id)) { return null; }
try {
var parsed = JSON.parse(code);
return {
code: dataToEsm(parsed, {
preferConst: options.preferConst,
compact: options.compact,
namedExports: options.namedExports,
includeArbitraryNames: options.includeArbitraryNames,
indent: indent
}),
map: { mappings: '' }
};
} catch (err) {
var message = 'Could not parse JSON file';
this.error({ message: message, id: id, cause: err });
return null;
}
}
};
}
export { json as default };
//# sourceMappingURL=index.js.map

View file

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

View file

@ -0,0 +1,81 @@
{
"name": "@rollup/plugin-json",
"version": "6.1.0",
"publishConfig": {
"access": "public"
},
"description": "Convert .json files to ES6 modules",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/json"
},
"author": "rollup",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/json#readme",
"bugs": "https://github.com/rollup/plugins/issues",
"main": "./dist/cjs/index.js",
"module": "./dist/es/index.js",
"exports": {
"types": "./types/index.d.ts",
"import": "./dist/es/index.js",
"default": "./dist/cjs/index.js"
},
"engines": {
"node": ">=14.0.0"
},
"files": [
"dist",
"!dist/**/*.map",
"types",
"README.md",
"LICENSE"
],
"keywords": [
"rollup",
"plugin",
"json",
"es2015",
"npm",
"modules"
],
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
},
"dependencies": {
"@rollup/pluginutils": "^5.1.0"
},
"devDependencies": {
"@rollup/plugin-buble": "^1.0.0",
"@rollup/plugin-node-resolve": "^15.0.0",
"rollup": "^4.0.0-24",
"source-map-support": "^0.5.21"
},
"types": "./types/index.d.ts",
"ava": {
"workerThreads": false,
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm build && pnpm lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm test -- --verbose && pnpm test:ts",
"prebuild": "del-cli dist",
"prerelease": "pnpm build",
"pretest": "pnpm build",
"release": "pnpm --workspace-root package:release $(pwd)",
"test": "ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"
}
}

View file

@ -0,0 +1,41 @@
import type { FilterPattern } from '@rollup/pluginutils';
import type { Plugin } from 'rollup';
export interface RollupJsonOptions {
/**
* All JSON files will be parsed by default,
* but you can also specifically include files
*/
include?: FilterPattern;
/**
* All JSON files will be parsed by default,
* but you can also specifically exclude files
*/
exclude?: FilterPattern;
/**
* For tree-shaking, properties will be declared as variables, using
* either `var` or `const`.
* @default false
*/
preferConst?: boolean;
/**
* Specify indentation for the generated default export
* @default '\t'
*/
indent?: string;
/**
* Ignores indent and generates the smallest code
* @default false
*/
compact?: boolean;
/**
* Generate a named export for every property of the JSON object
* @default true
*/
namedExports?: boolean;
}
/**
* Convert .json files to ES6 modules
*/
export default function json(options?: RollupJsonOptions): Plugin;

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,296 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-node-resolve
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-node-resolve
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-node-resolve
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-node-resolve
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-node-resolve
🍣 A Rollup plugin which locates modules using the [Node resolution algorithm](https://nodejs.org/api/modules.html#modules_all_together), for using third party modules in `node_modules`
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v2.78.0+.
## Install
Using npm:
```console
npm install @rollup/plugin-node-resolve --save-dev
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import { nodeResolve } from '@rollup/plugin-node-resolve';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [nodeResolve()]
};
```
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).
## Package entrypoints
This plugin supports the package entrypoints feature from node js, specified in the `exports` or `imports` field of a package. Check the [official documentation](https://nodejs.org/api/packages.html#packages_package_entry_points) for more information on how this works. This is the default behavior. In the abscence of these fields, the fields in `mainFields` will be the ones to be used.
## Options
### `exportConditions`
Type: `Array[...String]`<br>
Default: `[]`
Additional conditions of the package.json exports field to match when resolving modules. By default, this plugin looks for the `['default', 'module', 'import', 'development|production']` conditions when resolving imports. If neither the `development` or `production` conditions are provided it will default to `production` - or `development` if `NODE_ENV` is set to a value other than `production`.
When using `@rollup/plugin-commonjs` v16 or higher, this plugin will use the `['default', 'module', 'require']` conditions when resolving require statements.
Setting this option will add extra conditions on top of the default conditions. See https://nodejs.org/api/packages.html#packages_conditional_exports for more information.
In order to get the [resolution behavior of Node.js](https://nodejs.org/api/packages.html#packages_conditional_exports), set this to `['node']`.
### `browser`
Type: `Boolean`<br>
Default: `false`
If `true`, instructs the plugin to use the browser module resolutions in `package.json` and adds `'browser'` to `exportConditions` if it is not present so browser conditionals in `exports` are applied. If `false`, any browser properties in package files will be ignored. Alternatively, a value of `'browser'` can be added to both the `mainFields` and `exportConditions` options, however this option takes precedence over `mainFields`.
> This option does not work when a package is using [package entrypoints](https://nodejs.org/api/packages.html#packages_package_entry_points)
### `moduleDirectories`
Type: `Array[...String]`<br>
Default: `['node_modules']`
A list of directory names in which to recursively look for modules.
### `modulePaths`
Type: `Array[...String]`<br>
Default: `[]`
A list of absolute paths to additional locations to search for modules. [This is analogous to setting the `NODE_PATH` environment variable for node](https://nodejs.org/api/modules.html#loading-from-the-global-folders).
### `dedupe`
Type: `Array[...String]`<br>
Default: `[]`
An `Array` of modules names, which instructs the plugin to force resolving for the specified modules to the root `node_modules`. Helps to prevent bundling the same package multiple times if package is imported from dependencies.
```js
dedupe: ['my-package', '@namespace/my-package'];
```
This will deduplicate bare imports such as:
```js
import 'my-package';
import '@namespace/my-package';
```
And it will deduplicate deep imports such as:
```js
import 'my-package/foo.js';
import '@namespace/my-package/bar.js';
```
### `extensions`
Type: `Array[...String]`<br>
Default: `['.mjs', '.js', '.json', '.node']`
Specifies the extensions of files that the plugin will operate on.
### `jail`
Type: `String`<br>
Default: `'/'`
Locks the module search within specified path (e.g. chroot). Modules defined outside this path will be ignored by this plugin.
### `mainFields`
Type: `Array[...String]`<br>
Default: `['module', 'main']`<br>
Valid values: `['browser', 'jsnext:main', 'module', 'main']`
Specifies the properties to scan within a `package.json`, used to determine the bundle entry point. The order of property names is significant, as the first-found property is used as the resolved entry point. If the array contains `'browser'`, key/values specified in the `package.json` `browser` property will be used.
### `preferBuiltins`
Type: `Boolean | (module: string) => boolean`<br>
Default: `true` (with warnings if a builtin module is used over a local version. Set to `true` to disable warning.)
If `true`, the plugin will prefer built-in modules (e.g. `fs`, `path`). If `false`, the plugin will look for locally installed modules of the same name.
Alternatively, you may pass in a function that returns a boolean to confirm whether the plugin should prefer built-in modules. e.g.
```js
preferBuiltins: (module) => module !== 'punycode';
```
will not treat `punycode` as a built-in module
### `modulesOnly`
Type: `Boolean`<br>
Default: `false`
If `true`, inspect resolved files to assert that they are ES2015 modules.
### `resolveOnly`
Type: `Array[...String|RegExp] | (module: string) => boolean`<br>
Default: `null`
An `Array` which instructs the plugin to limit module resolution to those whose names match patterns in the array. _Note: Modules not matching any patterns will be marked as external._
Alternatively, you may pass in a function that returns a boolean to confirm whether the module should be included or not.
Examples:
- `resolveOnly: ['batman', /^@batcave\/.*$/]`
- `resolveOnly: module => !module.includes('joker')`
### `rootDir`
Type: `String`<br>
Default: `process.cwd()`
Specifies the root directory from which to resolve modules. Typically used when resolving entry-point imports, and when resolving deduplicated modules. Useful when executing rollup in a package of a mono-repository.
```
// Set the root directory to be the parent folder
rootDir: path.join(process.cwd(), '..')
```
### `ignoreSideEffectsForRoot`
Type: `Boolean`<br>
Default: `false`
If you use the `sideEffects` property in the package.json, by default this is respected for files in the root package. Set to `true` to ignore the `sideEffects` configuration for the root package.
### `allowExportsFolderMapping`
Older Node versions supported exports mappings of folders like
```json
{
"exports": {
"./foo/": "./dist/foo/"
}
}
```
This was deprecated with Node 14 and removed in Node 17, instead it is recommended to use exports patterns like
```json
{
"exports": {
"./foo/*": "./dist/foo/*"
}
}
```
But for backwards compatibility this behavior is still supported by enabling the `allowExportsFolderMapping` (defaults to `true`).
The default value might change in a futur major release.
## Preserving symlinks
This plugin honours the rollup [`preserveSymlinks`](https://rollupjs.org/guide/en/#preservesymlinks) option.
## Using with @rollup/plugin-commonjs
Since most packages in your node_modules folder are probably legacy CommonJS rather than JavaScript modules, you may need to use [@rollup/plugin-commonjs](https://github.com/rollup/plugins/tree/master/packages/commonjs):
```js
// rollup.config.js
import { nodeResolve } 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: [nodeResolve(), commonjs()]
};
```
## Resolving Built-Ins (like `fs`)
By default this plugin will prefer built-ins over local modules, marking them as external.
See [`preferBuiltins`](#preferbuiltins).
To provide stubbed versions of Node built-ins, use a plugin like [rollup-plugin-node-polyfills](https://github.com/ionic-team/rollup-plugin-node-polyfills) and set `preferBuiltins` to `false`. e.g.
```js
import { nodeResolve } from '@rollup/plugin-node-resolve';
import nodePolyfills from 'rollup-plugin-node-polyfills';
export default ({
input: ...,
plugins: [
nodePolyfills(),
nodeResolve({ preferBuiltins: false })
],
external: builtins,
output: ...
})
```
## Resolving Require Statements
According to [NodeJS module resolution](https://nodejs.org/api/packages.html#packages_package_entry_points) `require` statements should resolve using the `require` condition in the package exports field, while es modules should use the `import` condition.
The node resolve plugin uses `import` by default, you can opt into using the `require` semantics by passing an extra option to the resolve function:
```js
this.resolve(importee, importer, {
skipSelf: true,
custom: { 'node-resolve': { isRequire: true } }
});
```
## Resolve Options
After this plugin resolved an import id to its target file in `node_modules`, it will invoke `this.resolve` again with the resolved id. It will pass the following information in the resolve options:
```js
this.resolve(resolved.id, importer, {
custom: {
'node-resolve': {
resolved, // the object with information from node.js resolve
importee // the original import id
}
}
});
```
Your plugin can use the `importee` information to map an original import to its resolved file in `node_modules`, in a plugin hook such as `resolveId`.
The `resolved` object contains the resolved id, which is passed as the first parameter. It also has a property `moduleSideEffects`, which may contain the value from the npm `package.json` field `sideEffects` or `null`.
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

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

View file

@ -0,0 +1,89 @@
{
"name": "@rollup/plugin-node-resolve",
"version": "16.0.3",
"publishConfig": {
"access": "public"
},
"description": "Locate and bundle third-party dependencies in node_modules",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/node-resolve"
},
"author": "Rich Harris <richard.a.harris@gmail.com>",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/node-resolve/#readme",
"bugs": "https://github.com/rollup/plugins/issues",
"main": "./dist/cjs/index.js",
"module": "./dist/es/index.js",
"exports": {
"types": "./types/index.d.ts",
"import": "./dist/es/index.js",
"default": "./dist/cjs/index.js"
},
"engines": {
"node": ">=14.0.0"
},
"files": [
"dist",
"!dist/**/*.map",
"types",
"README.md",
"LICENSE"
],
"keywords": [
"rollup",
"plugin",
"es2015",
"npm",
"modules"
],
"peerDependencies": {
"rollup": "^2.78.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
},
"dependencies": {
"@rollup/pluginutils": "^5.0.1",
"@types/resolve": "1.20.2",
"deepmerge": "^4.2.2",
"is-module": "^1.0.0",
"resolve": "^1.22.1"
},
"devDependencies": {
"@babel/core": "^7.19.1",
"@babel/plugin-transform-typescript": "^7.10.5",
"@rollup/plugin-babel": "^6.0.0",
"@rollup/plugin-commonjs": "^23.0.0",
"@rollup/plugin-json": "^5.0.0",
"es5-ext": "^0.10.62",
"rollup": "^4.0.0-24",
"source-map": "^0.7.4",
"string-capitalize": "^1.0.1"
},
"types": "./types/index.d.ts",
"ava": {
"workerThreads": false,
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm build && pnpm lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm test -- --verbose",
"prebuild": "del-cli dist",
"prerelease": "pnpm build",
"pretest": "pnpm build",
"release": "pnpm --workspace-root package:release $(pwd)",
"test": "pnpm test:ts && ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"
}
}

View file

@ -0,0 +1,122 @@
import type { Plugin } from 'rollup';
export const DEFAULTS: {
customResolveOptions: {};
dedupe: [];
extensions: ['.mjs', '.js', '.json', '.node'];
resolveOnly: [];
};
export interface RollupNodeResolveOptions {
/**
* Additional conditions of the package.json exports field to match when resolving modules.
* By default, this plugin looks for the `'default', 'module', 'import']` conditions when resolving imports.
*
* When using `@rollup/plugin-commonjs` v16 or higher, this plugin will use the
* `['default', 'module', 'import']` conditions when resolving require statements.
*
* Setting this option will add extra conditions on top of the default conditions.
* See https://nodejs.org/api/packages.html#packages_conditional_exports for more information.
*/
exportConditions?: string[];
/**
* If `true`, instructs the plugin to use the `"browser"` property in `package.json`
* files to specify alternative files to load for bundling. This is useful when
* bundling for a browser environment. Alternatively, a value of `'browser'` can be
* added to the `mainFields` option. If `false`, any `"browser"` properties in
* package files will be ignored. This option takes precedence over `mainFields`.
* @default false
*/
browser?: boolean;
/**
* A list of directory names in which to recursively look for modules.
* @default ['node_modules']
*/
moduleDirectories?: string[];
/**
* A list of absolute paths to additional locations to search for modules.
* This is analogous to setting the `NODE_PATH` environment variable for node.
* @default []
*/
modulePaths?: string[];
/**
* An `Array` of modules names, which instructs the plugin to force resolving for the
* specified modules to the root `node_modules`. Helps to prevent bundling the same
* package multiple times if package is imported from dependencies.
*/
dedupe?: string[] | ((importee: string) => boolean);
/**
* Specifies the extensions of files that the plugin will operate on.
* @default [ '.mjs', '.js', '.json', '.node' ]
*/
extensions?: readonly string[];
/**
* Locks the module search within specified path (e.g. chroot). Modules defined
* outside this path will be marked as external.
* @default '/'
*/
jail?: string;
/**
* Specifies the properties to scan within a `package.json`, used to determine the
* bundle entry point.
* @default ['module', 'main']
*/
mainFields?: readonly string[];
/**
* If `true`, inspect resolved files to assert that they are ES2015 modules.
* @default false
*/
modulesOnly?: boolean;
/**
* If `true`, the plugin will prefer built-in modules (e.g. `fs`, `path`). If `false`,
* the plugin will look for locally installed modules of the same name.
*
* If a function is provided, it will be called to determine whether to prefer built-ins.
* @default true
*/
preferBuiltins?: boolean | ((module: string) => boolean);
/**
* An `Array` which instructs the plugin to limit module resolution to those whose
* names match patterns in the array.
* @default []
*/
resolveOnly?: ReadonlyArray<string | RegExp> | null | ((module: string) => boolean);
/**
* Specifies the root directory from which to resolve modules. Typically used when
* resolving entry-point imports, and when resolving deduplicated modules.
* @default process.cwd()
*/
rootDir?: string;
/**
* If you use the `sideEffects` property in the package.json, by default this is respected for files in the root package. Set to `true` to ignore the `sideEffects` configuration for the root package.
*
* @default false
*/
ignoreSideEffectsForRoot?: boolean;
/**
* Allow folder mappings in package exports (trailing /)
* This was deprecated in Node 14 and removed with Node 17, see DEP0148.
* So this option might be changed to default to `false` in a future release.
* @default true
*/
allowExportsFolderMapping?: boolean;
}
/**
* Locate modules using the Node resolution algorithm, for using third party modules in node_modules
*/
export function nodeResolve(options?: RollupNodeResolveOptions): Plugin;
export default nodeResolve;

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,240 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-replace
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-replace
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-replace
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-replace
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-replace
🍣 A Rollup plugin which replaces targeted strings in files while bundling.
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```console
npm install @rollup/plugin-replace --save-dev
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import replace from '@rollup/plugin-replace';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify('production'),
__buildDate__: () => JSON.stringify(new Date()),
__buildVersion: 15
})
]
};
```
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).
The configuration above will replace every instance of `process.env.NODE_ENV` with `"production"` and `__buildDate__` with the result of the given function in any file included in the build.
_Note: Values must be either primitives (e.g. string, number) or `function` that returns a string. For complex values, use `JSON.stringify`. To replace a target with a value that will be evaluated as a string, set the value to a quoted string (e.g. `"test"`) or use `JSON.stringify` to preprocess the target string safely._
Typically, `@rollup/plugin-replace` should be placed in `plugins` _before_ other plugins so that they may apply optimizations, such as dead code removal.
## Options
In addition to the properties and values specified for replacement, users may also specify the options below.
### `delimiters`
Type: `Array[String, String]`<br>
Default: `['(?<![_$a-zA-Z0-9\\xA0-\\uFFFF])', '(?![_$a-zA-Z0-9\\xA0-\\uFFFF])(?!\\.)']`
Specifies the boundaries around which strings will be replaced. By default, delimiters match JavaScript identifier boundaries and also prevent replacements of instances with nested access. See [Word Boundaries](#word-boundaries) below for more information.
For example, if you pass `typeof window` in `values` to-be-replaced, then you could expect the following scenarios:
- `typeof window` **will** be replaced
- `typeof window.document` **will not** be replaced due to the `(?!\.)` boundary
- `typeof windowSmth` **will not** be replaced due to identifier boundaries
Delimiters will be used to build a `Regexp`. To match special characters (any of `.*+?^${}()|[]\`), be sure to [escape](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping) them.
### `objectGuards`
Type: `Boolean`<br>
Default: `false`
When replacing dot-separated object properties like `process.env.NODE_ENV`, will also replace `typeof process` object guard
checks against the objects with the string `"object"`.
For example:
```js
replace({
values: {
'process.env.NODE_ENV': '"production"'
}
});
```
```js
// Input
if (typeof process !== 'undefined' && process.env.NODE_ENV === 'production') {
console.log('production');
}
// Without `objectGuards`
if (typeof process !== 'undefined' && 'production' === 'production') {
console.log('production');
}
// With `objectGuards`
if ('object' !== 'undefined' && 'production' === 'production') {
console.log('production');
}
```
### `preventAssignment`
Type: `Boolean`<br>
Default: `false`
Prevents replacing strings where they are followed by a single equals sign. For example, where the plugin is called as follows:
```js
replace({
values: {
'process.env.DEBUG': 'false'
}
});
```
Observe the following code:
```js
// Input
process.env.DEBUG = false;
if (process.env.DEBUG == true) {
//
}
// Without `preventAssignment`
false = false; // this throws an error because false cannot be assigned to
if (false == true) {
//
}
// With `preventAssignment`
process.env.DEBUG = false;
if (false == true) {
//
}
```
### `exclude`
Type: `String` | `Array[...String]`<br>
Default: `null`
A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default no files are ignored.
### `include`
Type: `String` | `Array[...String]`<br>
Default: `null`
A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default all files are targeted.
### `sourceMap` or `sourcemap`
Type: `Boolean`<br>
Default: `false`
Enables generating sourcemaps for the bundled code. For example, where the plugin is called as follows:
```js
replace({
sourcemap: true
});
```
### `values`
Type: `{ [key: String]: Replacement }`, where `Replacement` is either a string or a `function` that returns a string.
Default: `{}`
To avoid mixing replacement strings with the other options, you can specify replacements in the `values` option. For example, the following signature:
```js
replace({
include: ['src/**/*.js'],
changed: 'replaced'
});
```
Can be replaced with:
```js
replace({
include: ['src/**/*.js'],
values: {
changed: 'replaced'
}
});
```
## Word Boundaries
By default, values will only match if they are surrounded by _word boundaries_ that respect JavaScript's rules for valid identifiers (including `$` and `_` as valid identifier characters).
Consider the following options and build file:
```js
module.exports = {
...
plugins: [replace({ changed: 'replaced' })]
};
```
```js
// file.js
console.log('changed');
console.log('unchanged');
```
The result would be:
```js
// file.js
console.log('replaced');
console.log('unchanged');
```
To ignore word boundaries and replace every instance of the string, wherever it may be, specify empty strings as delimiters:
```js
export default {
...
plugins: [
replace({
changed: 'replaced',
delimiters: ['', '']
})
]
};
```
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View file

@ -0,0 +1,139 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var MagicString = require('magic-string');
var pluginutils = require('@rollup/pluginutils');
function escape(str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
}
function ensureFunction(functionOrValue) {
if (typeof functionOrValue === 'function') { return functionOrValue; }
return function () { return functionOrValue; };
}
function longest(a, b) {
return b.length - a.length;
}
function getReplacements(options) {
if (options.values) {
return Object.assign({}, options.values);
}
var values = Object.assign({}, options);
delete values.delimiters;
delete values.include;
delete values.exclude;
delete values.sourcemap;
delete values.sourceMap;
delete values.objectGuards;
delete values.preventAssignment;
return values;
}
function mapToFunctions(object) {
return Object.keys(object).reduce(function (fns, key) {
var functions = Object.assign({}, fns);
functions[key] = ensureFunction(object[key]);
return functions;
}, {});
}
var objKeyRegEx =
/^([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)(\.([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))+$/;
function expandTypeofReplacements(replacements) {
Object.keys(replacements).forEach(function (key) {
var objMatch = key.match(objKeyRegEx);
if (!objMatch) { return; }
var dotIndex = objMatch[1].length;
do {
// eslint-disable-next-line no-param-reassign
replacements[("typeof " + (key.slice(0, dotIndex)))] = '"object"';
dotIndex = key.indexOf('.', dotIndex + 1);
} while (dotIndex !== -1);
});
}
function replace(options) {
if ( options === void 0 ) options = {};
var filter = pluginutils.createFilter(options.include, options.exclude);
var delimiters = options.delimiters; if ( delimiters === void 0 ) delimiters = ['(?<![_$a-zA-Z0-9\\xA0-\\uFFFF])', '(?![_$a-zA-Z0-9\\xA0-\\uFFFF])(?!\\.)'];
var preventAssignment = options.preventAssignment;
var objectGuards = options.objectGuards;
var replacements = getReplacements(options);
if (objectGuards) { expandTypeofReplacements(replacements); }
var functionValues = mapToFunctions(replacements);
var keys = Object.keys(functionValues).sort(longest).map(escape);
var lookbehind = preventAssignment ? '(?<!\\b(?:const|let|var)\\s*)' : '';
var lookahead = preventAssignment ? '(?!\\s*=[^=])' : '';
var pattern = new RegExp(
("" + lookbehind + (delimiters[0]) + "(" + (keys.join('|')) + ")" + (delimiters[1]) + lookahead),
'g'
);
return {
name: 'replace',
buildStart: function buildStart() {
if (![true, false].includes(preventAssignment)) {
this.warn({
message:
"@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to `true`, as the next major version will default this option to `true`."
});
}
},
renderChunk: function renderChunk(code, chunk) {
var id = chunk.fileName;
if (!keys.length) { return null; }
if (!filter(id)) { return null; }
return executeReplacement(code, id);
},
transform: function transform(code, id) {
if (!keys.length) { return null; }
if (!filter(id)) { return null; }
return executeReplacement(code, id);
}
};
function executeReplacement(code, id) {
var magicString = new MagicString(code);
if (!codeHasReplacements(code, id, magicString)) {
return null;
}
var result = { code: magicString.toString() };
if (isSourceMapEnabled()) {
result.map = magicString.generateMap({ hires: true });
}
return result;
}
function codeHasReplacements(code, id, magicString) {
var result = false;
var match;
// eslint-disable-next-line no-cond-assign
while ((match = pattern.exec(code))) {
result = true;
var start = match.index;
var end = start + match[0].length;
var replacement = String(functionValues[match[1]](id));
magicString.overwrite(start, end, replacement);
}
return result;
}
function isSourceMapEnabled() {
return options.sourceMap !== false && options.sourcemap !== false;
}
}
exports.default = replace;
module.exports = Object.assign(exports.default, exports);
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1,134 @@
import MagicString from 'magic-string';
import { createFilter } from '@rollup/pluginutils';
function escape(str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
}
function ensureFunction(functionOrValue) {
if (typeof functionOrValue === 'function') { return functionOrValue; }
return function () { return functionOrValue; };
}
function longest(a, b) {
return b.length - a.length;
}
function getReplacements(options) {
if (options.values) {
return Object.assign({}, options.values);
}
var values = Object.assign({}, options);
delete values.delimiters;
delete values.include;
delete values.exclude;
delete values.sourcemap;
delete values.sourceMap;
delete values.objectGuards;
delete values.preventAssignment;
return values;
}
function mapToFunctions(object) {
return Object.keys(object).reduce(function (fns, key) {
var functions = Object.assign({}, fns);
functions[key] = ensureFunction(object[key]);
return functions;
}, {});
}
var objKeyRegEx =
/^([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)(\.([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))+$/;
function expandTypeofReplacements(replacements) {
Object.keys(replacements).forEach(function (key) {
var objMatch = key.match(objKeyRegEx);
if (!objMatch) { return; }
var dotIndex = objMatch[1].length;
do {
// eslint-disable-next-line no-param-reassign
replacements[("typeof " + (key.slice(0, dotIndex)))] = '"object"';
dotIndex = key.indexOf('.', dotIndex + 1);
} while (dotIndex !== -1);
});
}
function replace(options) {
if ( options === void 0 ) options = {};
var filter = createFilter(options.include, options.exclude);
var delimiters = options.delimiters; if ( delimiters === void 0 ) delimiters = ['(?<![_$a-zA-Z0-9\\xA0-\\uFFFF])', '(?![_$a-zA-Z0-9\\xA0-\\uFFFF])(?!\\.)'];
var preventAssignment = options.preventAssignment;
var objectGuards = options.objectGuards;
var replacements = getReplacements(options);
if (objectGuards) { expandTypeofReplacements(replacements); }
var functionValues = mapToFunctions(replacements);
var keys = Object.keys(functionValues).sort(longest).map(escape);
var lookbehind = preventAssignment ? '(?<!\\b(?:const|let|var)\\s*)' : '';
var lookahead = preventAssignment ? '(?!\\s*=[^=])' : '';
var pattern = new RegExp(
("" + lookbehind + (delimiters[0]) + "(" + (keys.join('|')) + ")" + (delimiters[1]) + lookahead),
'g'
);
return {
name: 'replace',
buildStart: function buildStart() {
if (![true, false].includes(preventAssignment)) {
this.warn({
message:
"@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to `true`, as the next major version will default this option to `true`."
});
}
},
renderChunk: function renderChunk(code, chunk) {
var id = chunk.fileName;
if (!keys.length) { return null; }
if (!filter(id)) { return null; }
return executeReplacement(code, id);
},
transform: function transform(code, id) {
if (!keys.length) { return null; }
if (!filter(id)) { return null; }
return executeReplacement(code, id);
}
};
function executeReplacement(code, id) {
var magicString = new MagicString(code);
if (!codeHasReplacements(code, id, magicString)) {
return null;
}
var result = { code: magicString.toString() };
if (isSourceMapEnabled()) {
result.map = magicString.generateMap({ hires: true });
}
return result;
}
function codeHasReplacements(code, id, magicString) {
var result = false;
var match;
// eslint-disable-next-line no-cond-assign
while ((match = pattern.exec(code))) {
result = true;
var start = match.index;
var end = start + match[0].length;
var replacement = String(functionValues[match[1]](id));
magicString.overwrite(start, end, replacement);
}
return result;
}
function isSourceMapEnabled() {
return options.sourceMap !== false && options.sourcemap !== false;
}
}
export { replace as default };
//# sourceMappingURL=index.js.map

View file

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

View file

@ -0,0 +1,84 @@
{
"name": "@rollup/plugin-replace",
"version": "6.0.3",
"publishConfig": {
"access": "public"
},
"description": "Replace strings in files while bundling",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/replace"
},
"author": "Rich Harris <richard.a.harris@gmail.com>",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/replace#readme",
"bugs": "https://github.com/rollup/plugins/issues",
"main": "dist/cjs/index.js",
"module": "dist/es/index.js",
"exports": {
"types": "./types/index.d.ts",
"import": "./dist/es/index.js",
"default": "./dist/cjs/index.js"
},
"engines": {
"node": ">=14.0.0"
},
"files": [
"dist",
"!dist/**/*.map",
"src",
"types",
"README.md"
],
"keywords": [
"rollup",
"plugin",
"replace",
"es2015",
"npm",
"modules"
],
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
},
"dependencies": {
"@rollup/pluginutils": "^5.0.1",
"magic-string": "^0.30.3"
},
"devDependencies": {
"@rollup/plugin-buble": "^1.0.0",
"del-cli": "^5.0.0",
"locate-character": "^2.0.5",
"rollup": "^4.0.0-24",
"source-map": "^0.7.4",
"typescript": "^4.8.3"
},
"types": "./types/index.d.ts",
"ava": {
"workerThreads": false,
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm build && pnpm lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm test -- --verbose && pnpm test:ts",
"prebuild": "del-cli dist",
"prerelease": "pnpm build",
"pretest": "pnpm build",
"release": "pnpm --workspace-root package:release $(pwd)",
"test": "ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"
}
}

View file

@ -0,0 +1,131 @@
import MagicString from 'magic-string';
import { createFilter } from '@rollup/pluginutils';
function escape(str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
}
function ensureFunction(functionOrValue) {
if (typeof functionOrValue === 'function') return functionOrValue;
return () => functionOrValue;
}
function longest(a, b) {
return b.length - a.length;
}
function getReplacements(options) {
if (options.values) {
return Object.assign({}, options.values);
}
const values = Object.assign({}, options);
delete values.delimiters;
delete values.include;
delete values.exclude;
delete values.sourcemap;
delete values.sourceMap;
delete values.objectGuards;
delete values.preventAssignment;
return values;
}
function mapToFunctions(object) {
return Object.keys(object).reduce((fns, key) => {
const functions = Object.assign({}, fns);
functions[key] = ensureFunction(object[key]);
return functions;
}, {});
}
const objKeyRegEx =
/^([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)(\.([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*))+$/;
function expandTypeofReplacements(replacements) {
Object.keys(replacements).forEach((key) => {
const objMatch = key.match(objKeyRegEx);
if (!objMatch) return;
let dotIndex = objMatch[1].length;
do {
// eslint-disable-next-line no-param-reassign
replacements[`typeof ${key.slice(0, dotIndex)}`] = '"object"';
dotIndex = key.indexOf('.', dotIndex + 1);
} while (dotIndex !== -1);
});
}
export default function replace(options = {}) {
const filter = createFilter(options.include, options.exclude);
const {
delimiters = ['(?<![_$a-zA-Z0-9\\xA0-\\uFFFF])', '(?![_$a-zA-Z0-9\\xA0-\\uFFFF])(?!\\.)'],
preventAssignment,
objectGuards
} = options;
const replacements = getReplacements(options);
if (objectGuards) expandTypeofReplacements(replacements);
const functionValues = mapToFunctions(replacements);
const keys = Object.keys(functionValues).sort(longest).map(escape);
const lookbehind = preventAssignment ? '(?<!\\b(?:const|let|var)\\s*)' : '';
const lookahead = preventAssignment ? '(?!\\s*=[^=])' : '';
const pattern = new RegExp(
`${lookbehind}${delimiters[0]}(${keys.join('|')})${delimiters[1]}${lookahead}`,
'g'
);
return {
name: 'replace',
buildStart() {
if (![true, false].includes(preventAssignment)) {
this.warn({
message:
"@rollup/plugin-replace: 'preventAssignment' currently defaults to false. It is recommended to set this option to `true`, as the next major version will default this option to `true`."
});
}
},
renderChunk(code, chunk) {
const id = chunk.fileName;
if (!keys.length) return null;
if (!filter(id)) return null;
return executeReplacement(code, id);
},
transform(code, id) {
if (!keys.length) return null;
if (!filter(id)) return null;
return executeReplacement(code, id);
}
};
function executeReplacement(code, id) {
const magicString = new MagicString(code);
if (!codeHasReplacements(code, id, magicString)) {
return null;
}
const result = { code: magicString.toString() };
if (isSourceMapEnabled()) {
result.map = magicString.generateMap({ hires: true });
}
return result;
}
function codeHasReplacements(code, id, magicString) {
let result = false;
let match;
// eslint-disable-next-line no-cond-assign
while ((match = pattern.exec(code))) {
result = true;
const start = match.index;
const end = start + match[0].length;
const replacement = String(functionValues[match[1]](id));
magicString.overwrite(start, end, replacement);
}
return result;
}
function isSourceMapEnabled() {
return options.sourceMap !== false && options.sourcemap !== false;
}
}

View file

@ -0,0 +1,57 @@
import type { FilterPattern } from '@rollup/pluginutils';
import type { Plugin } from 'rollup';
type Replacement = string | ((id: string) => string);
export interface RollupReplaceOptions {
/**
* All other options are treated as `string: replacement` replacers,
* or `string: (id) => replacement` functions.
*/
[str: string]:
| Replacement
| RollupReplaceOptions['include']
| RollupReplaceOptions['values']
| RollupReplaceOptions['objectGuards']
| RollupReplaceOptions['preventAssignment'];
/**
* A picomatch pattern, or array of patterns, of files that should be
* processed by this plugin (if omitted, all files are included by default)
*/
include?: FilterPattern;
/**
* Files that should be excluded, if `include` is otherwise too permissive.
*/
exclude?: FilterPattern;
/**
* If false, skips source map generation. This will improve performance.
* @default true
*/
sourceMap?: boolean;
/**
* To replace every occurrence of `<@foo@>` instead of every occurrence
* of `foo`, supply delimiters
*/
delimiters?: [string, string];
/**
* When replacing dot-separated object properties like `process.env.NODE_ENV`,
* will also replace `typeof process` object guard checks against the objects
* with the string `"object"`.
*/
objectGuards?: boolean;
/**
* Prevents replacing strings where they are followed by a single equals
* sign.
*/
preventAssignment?: boolean;
/**
* You can separate values to replace from other options.
*/
values?: { [str: string]: Replacement };
}
/**
* Replace strings in files while bundling them.
*/
export default function replace(options?: RollupReplaceOptions): Plugin;

View file

@ -0,0 +1,80 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-terser
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-terser
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-terser
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-terser
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-terser
🍣 A Rollup plugin to generate a minified bundle with terser.
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v2.0+.
## Install
Using npm:
```console
npm install @rollup/plugin-terser --save-dev
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```typescript
import terser from '@rollup/plugin-terser';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [terser()]
};
```
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
The plugin accepts a terser [Options](https://github.com/terser/terser#minify-options) object as input parameter,
to modify the default behaviour.
In addition to the `terser` options, it is also possible to provide the following options:
### `maxWorkers`
Type: `Number`<br>
Default: `undefined`
Instructs the plugin to use a specific amount of cpu threads.
```typescript
import terser from '@rollup/plugin-terser';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [
terser({
maxWorkers: 4
})
]
};
```
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View file

@ -0,0 +1,232 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var worker_threads = require('worker_threads');
var smob = require('smob');
var terser$1 = require('terser');
var url = require('url');
var async_hooks = require('async_hooks');
var os = require('os');
var events = require('events');
var serializeJavascript = require('serialize-javascript');
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
const taskInfo = Symbol('taskInfo');
const freeWorker = Symbol('freeWorker');
const workerPoolWorkerFlag = 'WorkerPoolWorker';
/**
* Duck typing worker context.
*
* @param input
*/
function isWorkerContextSerialized(input) {
return (smob.isObject(input) &&
smob.hasOwnProperty(input, 'code') &&
typeof input.code === 'string' &&
smob.hasOwnProperty(input, 'options') &&
typeof input.options === 'string');
}
function runWorker() {
if (worker_threads.isMainThread || !worker_threads.parentPort || worker_threads.workerData !== workerPoolWorkerFlag) {
return;
}
// eslint-disable-next-line no-eval
const eval2 = eval;
worker_threads.parentPort.on('message', async (data) => {
if (!isWorkerContextSerialized(data)) {
return;
}
const options = eval2(`(${data.options})`);
const result = await terser$1.minify(data.code, options);
const output = {
code: result.code || data.code,
nameCache: options.nameCache
};
if (typeof result.map === 'string') {
output.sourceMap = JSON.parse(result.map);
}
if (smob.isObject(result.map)) {
output.sourceMap = result.map;
}
worker_threads.parentPort === null || worker_threads.parentPort === void 0 ? void 0 : worker_threads.parentPort.postMessage(output);
});
}
class WorkerPoolTaskInfo extends async_hooks.AsyncResource {
constructor(callback) {
super('WorkerPoolTaskInfo');
this.callback = callback;
}
done(err, result) {
this.runInAsyncScope(this.callback, null, err, result);
this.emitDestroy();
}
}
class WorkerPool extends events.EventEmitter {
constructor(options) {
super();
this.tasks = [];
this.workers = [];
this.freeWorkers = [];
this.maxInstances = options.maxWorkers || os.cpus().length;
this.filePath = options.filePath;
this.on(freeWorker, () => {
if (this.tasks.length > 0) {
const { context, cb } = this.tasks.shift();
this.runTask(context, cb);
}
});
}
get numWorkers() {
return this.workers.length;
}
addAsync(context) {
return new Promise((resolve, reject) => {
this.runTask(context, (err, output) => {
if (err) {
reject(err);
return;
}
if (!output) {
reject(new Error('The output is empty'));
return;
}
resolve(output);
});
});
}
close() {
for (let i = 0; i < this.workers.length; i++) {
const worker = this.workers[i];
worker.terminate();
}
}
addNewWorker() {
const worker = new worker_threads.Worker(this.filePath, {
workerData: workerPoolWorkerFlag
});
worker.on('message', (result) => {
var _a;
(_a = worker[taskInfo]) === null || _a === void 0 ? void 0 : _a.done(null, result);
worker[taskInfo] = null;
this.freeWorkers.push(worker);
this.emit(freeWorker);
});
worker.on('error', (err) => {
if (worker[taskInfo]) {
worker[taskInfo].done(err, null);
}
else {
this.emit('error', err);
}
this.workers.splice(this.workers.indexOf(worker), 1);
this.addNewWorker();
});
this.workers.push(worker);
this.freeWorkers.push(worker);
this.emit(freeWorker);
}
runTask(context, cb) {
if (this.freeWorkers.length === 0) {
this.tasks.push({ context, cb });
if (this.numWorkers < this.maxInstances) {
this.addNewWorker();
}
return;
}
const worker = this.freeWorkers.pop();
if (worker) {
worker[taskInfo] = new WorkerPoolTaskInfo(cb);
worker.postMessage({
code: context.code,
options: serializeJavascript(context.options)
});
}
}
}
function terser(input = {}) {
const { maxWorkers, ...options } = input;
let workerPool;
let numOfChunks = 0;
let numOfWorkersUsed = 0;
return {
name: 'terser',
async renderChunk(code, chunk, outputOptions) {
if (!workerPool) {
workerPool = new WorkerPool({
filePath: url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))),
maxWorkers
});
}
numOfChunks += 1;
const defaultOptions = {
sourceMap: outputOptions.sourcemap === true || typeof outputOptions.sourcemap === 'string'
};
if (outputOptions.format === 'es') {
defaultOptions.module = true;
}
if (outputOptions.format === 'cjs') {
defaultOptions.toplevel = true;
}
try {
const { code: result, nameCache, sourceMap } = await workerPool.addAsync({
code,
options: smob.merge({}, options || {}, defaultOptions)
});
if (options.nameCache && nameCache) {
let vars = {
props: {}
};
if (smob.hasOwnProperty(options.nameCache, 'vars') && smob.isObject(options.nameCache.vars)) {
vars = smob.merge({}, options.nameCache.vars || {}, vars);
}
if (smob.hasOwnProperty(nameCache, 'vars') && smob.isObject(nameCache.vars)) {
vars = smob.merge({}, nameCache.vars, vars);
}
// eslint-disable-next-line no-param-reassign
options.nameCache.vars = vars;
let props = {};
if (smob.hasOwnProperty(options.nameCache, 'props') && smob.isObject(options.nameCache.props)) {
// eslint-disable-next-line prefer-destructuring
props = options.nameCache.props;
}
if (smob.hasOwnProperty(nameCache, 'props') && smob.isObject(nameCache.props)) {
props = smob.merge({}, nameCache.props, props);
}
// eslint-disable-next-line no-param-reassign
options.nameCache.props = props;
}
if ((!!defaultOptions.sourceMap || !!options.sourceMap) && smob.isObject(sourceMap)) {
return {
code: result,
map: sourceMap
};
}
return result;
}
catch (e) {
return Promise.reject(e);
}
finally {
numOfChunks -= 1;
if (numOfChunks === 0) {
numOfWorkersUsed = workerPool.numWorkers;
workerPool.close();
workerPool = null;
}
}
},
get numOfWorkersUsed() {
return numOfWorkersUsed;
}
};
}
runWorker();
exports.default = terser;
module.exports = Object.assign(exports.default, exports);
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1,226 @@
import { isMainThread, parentPort, workerData, Worker } from 'worker_threads';
import { isObject, hasOwnProperty, merge } from 'smob';
import { minify } from 'terser';
import { fileURLToPath } from 'url';
import { AsyncResource } from 'async_hooks';
import { cpus } from 'os';
import { EventEmitter } from 'events';
import serializeJavascript from 'serialize-javascript';
const taskInfo = Symbol('taskInfo');
const freeWorker = Symbol('freeWorker');
const workerPoolWorkerFlag = 'WorkerPoolWorker';
/**
* Duck typing worker context.
*
* @param input
*/
function isWorkerContextSerialized(input) {
return (isObject(input) &&
hasOwnProperty(input, 'code') &&
typeof input.code === 'string' &&
hasOwnProperty(input, 'options') &&
typeof input.options === 'string');
}
function runWorker() {
if (isMainThread || !parentPort || workerData !== workerPoolWorkerFlag) {
return;
}
// eslint-disable-next-line no-eval
const eval2 = eval;
parentPort.on('message', async (data) => {
if (!isWorkerContextSerialized(data)) {
return;
}
const options = eval2(`(${data.options})`);
const result = await minify(data.code, options);
const output = {
code: result.code || data.code,
nameCache: options.nameCache
};
if (typeof result.map === 'string') {
output.sourceMap = JSON.parse(result.map);
}
if (isObject(result.map)) {
output.sourceMap = result.map;
}
parentPort === null || parentPort === void 0 ? void 0 : parentPort.postMessage(output);
});
}
class WorkerPoolTaskInfo extends AsyncResource {
constructor(callback) {
super('WorkerPoolTaskInfo');
this.callback = callback;
}
done(err, result) {
this.runInAsyncScope(this.callback, null, err, result);
this.emitDestroy();
}
}
class WorkerPool extends EventEmitter {
constructor(options) {
super();
this.tasks = [];
this.workers = [];
this.freeWorkers = [];
this.maxInstances = options.maxWorkers || cpus().length;
this.filePath = options.filePath;
this.on(freeWorker, () => {
if (this.tasks.length > 0) {
const { context, cb } = this.tasks.shift();
this.runTask(context, cb);
}
});
}
get numWorkers() {
return this.workers.length;
}
addAsync(context) {
return new Promise((resolve, reject) => {
this.runTask(context, (err, output) => {
if (err) {
reject(err);
return;
}
if (!output) {
reject(new Error('The output is empty'));
return;
}
resolve(output);
});
});
}
close() {
for (let i = 0; i < this.workers.length; i++) {
const worker = this.workers[i];
worker.terminate();
}
}
addNewWorker() {
const worker = new Worker(this.filePath, {
workerData: workerPoolWorkerFlag
});
worker.on('message', (result) => {
var _a;
(_a = worker[taskInfo]) === null || _a === void 0 ? void 0 : _a.done(null, result);
worker[taskInfo] = null;
this.freeWorkers.push(worker);
this.emit(freeWorker);
});
worker.on('error', (err) => {
if (worker[taskInfo]) {
worker[taskInfo].done(err, null);
}
else {
this.emit('error', err);
}
this.workers.splice(this.workers.indexOf(worker), 1);
this.addNewWorker();
});
this.workers.push(worker);
this.freeWorkers.push(worker);
this.emit(freeWorker);
}
runTask(context, cb) {
if (this.freeWorkers.length === 0) {
this.tasks.push({ context, cb });
if (this.numWorkers < this.maxInstances) {
this.addNewWorker();
}
return;
}
const worker = this.freeWorkers.pop();
if (worker) {
worker[taskInfo] = new WorkerPoolTaskInfo(cb);
worker.postMessage({
code: context.code,
options: serializeJavascript(context.options)
});
}
}
}
function terser(input = {}) {
const { maxWorkers, ...options } = input;
let workerPool;
let numOfChunks = 0;
let numOfWorkersUsed = 0;
return {
name: 'terser',
async renderChunk(code, chunk, outputOptions) {
if (!workerPool) {
workerPool = new WorkerPool({
filePath: fileURLToPath(import.meta.url),
maxWorkers
});
}
numOfChunks += 1;
const defaultOptions = {
sourceMap: outputOptions.sourcemap === true || typeof outputOptions.sourcemap === 'string'
};
if (outputOptions.format === 'es') {
defaultOptions.module = true;
}
if (outputOptions.format === 'cjs') {
defaultOptions.toplevel = true;
}
try {
const { code: result, nameCache, sourceMap } = await workerPool.addAsync({
code,
options: merge({}, options || {}, defaultOptions)
});
if (options.nameCache && nameCache) {
let vars = {
props: {}
};
if (hasOwnProperty(options.nameCache, 'vars') && isObject(options.nameCache.vars)) {
vars = merge({}, options.nameCache.vars || {}, vars);
}
if (hasOwnProperty(nameCache, 'vars') && isObject(nameCache.vars)) {
vars = merge({}, nameCache.vars, vars);
}
// eslint-disable-next-line no-param-reassign
options.nameCache.vars = vars;
let props = {};
if (hasOwnProperty(options.nameCache, 'props') && isObject(options.nameCache.props)) {
// eslint-disable-next-line prefer-destructuring
props = options.nameCache.props;
}
if (hasOwnProperty(nameCache, 'props') && isObject(nameCache.props)) {
props = merge({}, nameCache.props, props);
}
// eslint-disable-next-line no-param-reassign
options.nameCache.props = props;
}
if ((!!defaultOptions.sourceMap || !!options.sourceMap) && isObject(sourceMap)) {
return {
code: result,
map: sourceMap
};
}
return result;
}
catch (e) {
return Promise.reject(e);
}
finally {
numOfChunks -= 1;
if (numOfChunks === 0) {
numOfWorkersUsed = workerPool.numWorkers;
workerPool.close();
workerPool = null;
}
}
},
get numOfWorkersUsed() {
return numOfWorkersUsed;
}
};
}
runWorker();
export { terser as default };
//# sourceMappingURL=index.js.map

View file

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

View file

@ -0,0 +1,74 @@
{
"name": "@rollup/plugin-terser",
"version": "0.4.4",
"publishConfig": {
"access": "public"
},
"description": "Generate minified bundle",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/terser"
},
"author": "Peter Placzek <peter.placzek1996@gmail.com>",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/terser#readme",
"bugs": "https://github.com/rollup/plugins/issues",
"main": "dist/cjs/index.js",
"module": "dist/es/index.js",
"exports": {
"types": "./types/index.d.ts",
"import": "./dist/es/index.js",
"default": "./dist/cjs/index.js"
},
"engines": {
"node": ">=14.0.0"
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm build && pnpm lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm test -- --verbose && pnpm test:ts",
"prebuild": "del-cli dist",
"prepare": "if [ ! -d 'dist' ]; then pnpm build; fi",
"prerelease": "pnpm build",
"pretest": "pnpm build",
"release": "pnpm --workspace-root plugin:release --pkg $npm_package_name",
"test": "ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"
},
"files": [
"dist",
"!dist/**/*.map",
"src",
"types",
"README.md"
],
"keywords": [
"rollup",
"plugin",
"terser",
"minify",
"npm",
"modules"
],
"peerDependencies": {
"rollup": "^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
},
"dependencies": {
"serialize-javascript": "^6.0.1",
"smob": "^1.0.0",
"terser": "^5.17.4"
},
"devDependencies": {
"@types/serialize-javascript": "^5.0.2",
"rollup": "^4.0.0-24",
"typescript": "^4.8.3"
},
"types": "./types/index.d.ts"
}

View file

@ -0,0 +1,3 @@
export const taskInfo = Symbol('taskInfo');
export const freeWorker = Symbol('freeWorker');
export const workerPoolWorkerFlag = 'WorkerPoolWorker';

View file

@ -0,0 +1,8 @@
import { runWorker } from './worker';
import terser from './module';
runWorker();
export * from './type';
export default terser;

View file

@ -0,0 +1,105 @@
import { fileURLToPath } from 'url';
import type { NormalizedOutputOptions, RenderedChunk } from 'rollup';
import { hasOwnProperty, isObject, merge } from 'smob';
import type { Options } from './type';
import { WorkerPool } from './worker-pool';
export default function terser(input: Options = {}) {
const { maxWorkers, ...options } = input;
let workerPool: WorkerPool | null | undefined;
let numOfChunks = 0;
let numOfWorkersUsed = 0;
return {
name: 'terser',
async renderChunk(code: string, chunk: RenderedChunk, outputOptions: NormalizedOutputOptions) {
if (!workerPool) {
workerPool = new WorkerPool({
filePath: fileURLToPath(import.meta.url),
maxWorkers
});
}
numOfChunks += 1;
const defaultOptions: Options = {
sourceMap: outputOptions.sourcemap === true || typeof outputOptions.sourcemap === 'string'
};
if (outputOptions.format === 'es') {
defaultOptions.module = true;
}
if (outputOptions.format === 'cjs') {
defaultOptions.toplevel = true;
}
try {
const {
code: result,
nameCache,
sourceMap
} = await workerPool.addAsync({
code,
options: merge({}, options || {}, defaultOptions)
});
if (options.nameCache && nameCache) {
let vars: Record<string, any> = {
props: {}
};
if (hasOwnProperty(options.nameCache, 'vars') && isObject(options.nameCache.vars)) {
vars = merge({}, options.nameCache.vars || {}, vars);
}
if (hasOwnProperty(nameCache, 'vars') && isObject(nameCache.vars)) {
vars = merge({}, nameCache.vars, vars);
}
// eslint-disable-next-line no-param-reassign
options.nameCache.vars = vars;
let props: Record<string, any> = {};
if (hasOwnProperty(options.nameCache, 'props') && isObject(options.nameCache.props)) {
// eslint-disable-next-line prefer-destructuring
props = options.nameCache.props;
}
if (hasOwnProperty(nameCache, 'props') && isObject(nameCache.props)) {
props = merge({}, nameCache.props, props);
}
// eslint-disable-next-line no-param-reassign
options.nameCache.props = props;
}
if ((!!defaultOptions.sourceMap || !!options.sourceMap) && isObject(sourceMap)) {
return {
code: result,
map: sourceMap
};
}
return result;
} catch (e) {
return Promise.reject(e);
} finally {
numOfChunks -= 1;
if (numOfChunks === 0) {
numOfWorkersUsed = workerPool.numWorkers;
workerPool.close();
workerPool = null;
}
}
},
get numOfWorkersUsed() {
return numOfWorkersUsed;
}
};
}

View file

@ -0,0 +1,45 @@
import type { AsyncResource } from 'async_hooks';
import type { Worker } from 'worker_threads';
import type { MinifyOptions } from 'terser';
import type { taskInfo } from './constants';
export interface Options extends MinifyOptions {
nameCache?: Record<string, any>;
maxWorkers?: number;
}
export interface WorkerContext {
code: string;
options: Options;
}
export type WorkerCallback = (err: Error | null, output?: WorkerOutput) => void;
interface WorkerPoolTaskInfo extends AsyncResource {
done(err: Error | null, result: any): void;
}
export type WorkerWithTaskInfo = Worker & { [taskInfo]?: WorkerPoolTaskInfo | null };
export interface WorkerContextSerialized {
code: string;
options: string;
}
export interface WorkerOutput {
code: string;
nameCache?: Options['nameCache'];
sourceMap?: Record<string, any>;
}
export interface WorkerPoolOptions {
filePath: string;
maxWorkers?: number;
}
export interface WorkerPoolTask {
context: WorkerContext;
cb: WorkerCallback;
}

View file

@ -0,0 +1,128 @@
import { AsyncResource } from 'async_hooks';
import { Worker } from 'worker_threads';
import { cpus } from 'os';
import { EventEmitter } from 'events';
import serializeJavascript from 'serialize-javascript';
import { freeWorker, taskInfo, workerPoolWorkerFlag } from './constants';
import type {
WorkerCallback,
WorkerContext,
WorkerOutput,
WorkerPoolOptions,
WorkerPoolTask,
WorkerWithTaskInfo
} from './type';
class WorkerPoolTaskInfo extends AsyncResource {
constructor(private callback: WorkerCallback) {
super('WorkerPoolTaskInfo');
}
done(err: Error | null, result: any) {
this.runInAsyncScope(this.callback, null, err, result);
this.emitDestroy();
}
}
export class WorkerPool extends EventEmitter {
protected maxInstances: number;
protected filePath: string;
protected tasks: WorkerPoolTask[] = [];
protected workers: WorkerWithTaskInfo[] = [];
protected freeWorkers: WorkerWithTaskInfo[] = [];
constructor(options: WorkerPoolOptions) {
super();
this.maxInstances = options.maxWorkers || cpus().length;
this.filePath = options.filePath;
this.on(freeWorker, () => {
if (this.tasks.length > 0) {
const { context, cb } = this.tasks.shift()!;
this.runTask(context, cb);
}
});
}
get numWorkers(): number {
return this.workers.length;
}
addAsync(context: WorkerContext): Promise<WorkerOutput> {
return new Promise((resolve, reject) => {
this.runTask(context, (err, output) => {
if (err) {
reject(err);
return;
}
if (!output) {
reject(new Error('The output is empty'));
return;
}
resolve(output);
});
});
}
close() {
for (let i = 0; i < this.workers.length; i++) {
const worker = this.workers[i];
worker.terminate();
}
}
private addNewWorker() {
const worker: WorkerWithTaskInfo = new Worker(this.filePath, {
workerData: workerPoolWorkerFlag
});
worker.on('message', (result) => {
worker[taskInfo]?.done(null, result);
worker[taskInfo] = null;
this.freeWorkers.push(worker);
this.emit(freeWorker);
});
worker.on('error', (err) => {
if (worker[taskInfo]) {
worker[taskInfo].done(err, null);
} else {
this.emit('error', err);
}
this.workers.splice(this.workers.indexOf(worker), 1);
this.addNewWorker();
});
this.workers.push(worker);
this.freeWorkers.push(worker);
this.emit(freeWorker);
}
private runTask(context: WorkerContext, cb: WorkerCallback) {
if (this.freeWorkers.length === 0) {
this.tasks.push({ context, cb });
if (this.numWorkers < this.maxInstances) {
this.addNewWorker();
}
return;
}
const worker = this.freeWorkers.pop();
if (worker) {
worker[taskInfo] = new WorkerPoolTaskInfo(cb);
worker.postMessage({
code: context.code,
options: serializeJavascript(context.options)
});
}
}
}

View file

@ -0,0 +1,58 @@
import { isMainThread, parentPort, workerData } from 'worker_threads';
import { hasOwnProperty, isObject } from 'smob';
import { minify } from 'terser';
import { workerPoolWorkerFlag } from './constants';
import type { WorkerContextSerialized, WorkerOutput } from './type';
/**
* Duck typing worker context.
*
* @param input
*/
function isWorkerContextSerialized(input: unknown): input is WorkerContextSerialized {
return (
isObject(input) &&
hasOwnProperty(input, 'code') &&
typeof input.code === 'string' &&
hasOwnProperty(input, 'options') &&
typeof input.options === 'string'
);
}
export function runWorker() {
if (isMainThread || !parentPort || workerData !== workerPoolWorkerFlag) {
return;
}
// eslint-disable-next-line no-eval
const eval2 = eval;
parentPort.on('message', async (data: WorkerContextSerialized) => {
if (!isWorkerContextSerialized(data)) {
return;
}
const options = eval2(`(${data.options})`);
const result = await minify(data.code, options);
const output: WorkerOutput = {
code: result.code || data.code,
nameCache: options.nameCache
};
if (typeof result.map === 'string') {
output.sourceMap = JSON.parse(result.map);
}
if (isObject(result.map)) {
output.sourceMap = result.map;
}
parentPort?.postMessage(output);
});
}

View file

@ -0,0 +1,15 @@
import type { Plugin } from 'rollup';
import type { MinifyOptions } from 'terser';
export interface Options extends MinifyOptions {
nameCache?: Record<string, any>;
maxWorkers?: number;
}
/**
* A Rollup plugin to generate a minified output bundle.
*
* @param options - Plugin options.
* @returns Plugin instance.
*/
export default function terser(options?: Options): Plugin;

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,313 @@
[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
The plugin utils require an [LTS](https://github.com/nodejs/Release) Node version (v14.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/plugins/tree/master/packages/inject) or [@rollup/plugin-commonjs](https://github.com/rollup/plugins/tree/master/packages/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?: <picomatch>, exclude?: <picomatch>, options?: Object)`<br>
Returns: `(id: string | unknown) => boolean`
#### `include` and `exclude`
Type: `String | RegExp | Array[...String|RegExp]`<br>
A valid [`picomatch`](https://github.com/micromatch/picomatch#globbing-features) 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 `picomatch` patterns, and must not match any of the `options.exclude` patterns.
Note that `picomatch` patterns are very similar to [`minimatch`](https://github.com/isaacs/minimatch#readme) patterns, and in most use cases, they are interchangeable. If you have more specific pattern matching needs, you can view [this comparison table](https://github.com/micromatch/picomatch#library-comparisons) to learn more about where the libraries differ.
#### `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, options: DataToEsmOptions)`<br>
Returns: `String`
#### `data`
Type: `Object`
An object to transform into an ES module.
#### `options`
Type: `DataToEsmOptions`
_Note: Please see the TypeScript definition for complete documentation of these options_
#### Usage
```js
import { dataToEsm } from '@rollup/pluginutils';
const esModuleSource = dataToEsm(
{
custom: 'data',
to: ['treeshake']
},
{
compact: false,
indent: '\t',
preferConst: true,
objectShorthand: true,
namedExports: true,
includeArbitraryNames: false
}
);
/*
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']
}
}
});
}
};
}
```
### exactRegex
Constructs a RegExp that matches the exact string specified. This is useful for plugin hook filters.
Parameters: `(str: String | Array[...String], flags?: String)`<br>
Returns: `RegExp`
#### Usage
```js
import { exactRegex } from '@rollup/pluginutils';
exactRegex('foobar'); // /^foobar$/
exactRegex(['foo', 'bar']); // /^(?:foo|bar)$/
exactRegex('foo(bar)', 'i'); // /^foo\(bar\)$/i
```
### 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'
```
### normalizePath
Converts path separators to forward slash.
Parameters: `(filename: String)`<br>
Returns: `String`
#### Usage
```js
import { normalizePath } from '@rollup/pluginutils';
normalizePath('foo\\bar'); // 'foo/bar'
normalizePath('foo/bar'); // 'foo/bar'
```
### prefixRegex
Constructs a RegExp that matches a value that has the specified prefix. This is useful for plugin hook filters.
Parameters: `(str: String | Array[...String], flags?: String)`<br>
Returns: `RegExp`
#### Usage
```js
import { prefixRegex } from '@rollup/pluginutils';
prefixRegex('foobar'); // /^foobar/
prefixRegex(['foo', 'bar']); // /^(?:foo|bar)/
prefixRegex('foo(bar)', 'i'); // /^foo\(bar\)/i
```
### suffixRegex
Constructs a RegExp that matches a value that has the specified suffix. This is useful for plugin hook filters.
Parameters: `(str: String | Array[...String], flags?: String)`<br>
Returns: `RegExp`
#### Usage
```js
import { suffixRegex } from '@rollup/pluginutils';
suffixRegex('foobar'); // /foobar$/
suffixRegex(['foo', 'bar']); // /(?:foo|bar)$/
suffixRegex('foo(bar)', 'i'); // /foo\(bar\)$/i
```
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View file

@ -0,0 +1,407 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var path = require('path');
var estreeWalker = require('estree-walker');
var pm = require('picomatch');
const addExtension = function addExtension(filename, ext = '.js') {
let result = `${filename}`;
if (!path.extname(filename))
result += ext;
return result;
};
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();
estreeWalker.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];
node.declarations.forEach((declaration) => {
scope.addDeclaration(declaration, isBlockDeclaration, true);
});
}
let newScope;
// create new function scope
if (node.type.includes('Function')) {
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 for scope
if (/For(?:In|Of)?Statement/.test(node.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
// create new block scope
if (node.type === 'BlockStatement' && !parent.type.includes('Function')) {
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];
}
const normalizePathRegExp = new RegExp(`\\${path.win32.sep}`, 'g');
const normalizePath = function normalizePath(filename) {
return filename.replace(normalizePathRegExp, path.posix.sep);
};
function getMatcherString(id, resolutionBase) {
if (resolutionBase === false || path.isAbsolute(id) || id.startsWith('**')) {
return normalizePath(id);
}
// resolve('') is valid and will default to process.cwd()
const basePath = normalizePath(path.resolve(resolutionBase || ''))
// 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, normalizePath(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);
if (!includeMatchers.length && !excludeMatchers.length)
return (id) => typeof id === 'string' && !id.includes('\0');
return function result(id) {
if (typeof id !== 'string')
return false;
if (id.includes('\0'))
return false;
const pathId = normalizePath(id);
for (let i = 0; i < excludeMatchers.length; ++i) {
const matcher = excludeMatchers[i];
if (matcher instanceof RegExp) {
matcher.lastIndex = 0;
}
if (matcher.test(pathId))
return false;
}
for (let i = 0; i < includeMatchers.length; ++i) {
const matcher = includeMatchers[i];
if (matcher instanceof RegExp) {
matcher.lastIndex = 0;
}
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 (typeof obj === 'object' && obj !== null) {
if (Array.isArray(obj))
return serializeArray(obj, indent, baseIndent);
if (obj instanceof Date)
return `new Date(${obj.getTime()})`;
if (obj instanceof RegExp)
return obj.toString();
return serializeObject(obj, indent, baseIndent);
}
if (typeof obj === 'number') {
if (obj === Infinity)
return 'Infinity';
if (obj === -Infinity)
return '-Infinity';
if (obj === 0)
return 1 / obj === Infinity ? '0' : '-0';
if (obj !== obj)
return 'NaN'; // eslint-disable-line no-self-compare
}
if (typeof obj === 'symbol') {
const key = Symbol.keyFor(obj);
// eslint-disable-next-line no-undefined
if (key !== undefined)
return `Symbol.for(${stringify(key)})`;
}
if (typeof obj === 'bigint')
return `${obj}n`;
return stringify(obj);
}
// isWellFormed exists from Node.js 20
const hasStringIsWellFormed = 'isWellFormed' in String.prototype;
function isWellFormedString(input) {
// @ts-expect-error String::isWellFormed exists from ES2024. tsconfig lib is set to ES6
if (hasStringIsWellFormed)
return input.isWellFormed();
// https://github.com/tc39/proposal-is-usv-string/blob/main/README.md#algorithm
return !/\p{Surrogate}/u.test(input);
}
const dataToEsm = function dataToEsm(data, options = {}) {
var _a, _b;
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 maxUnderbarPrefixLength = 0;
for (const key of Object.keys(data)) {
const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
if (underbarPrefixLength > maxUnderbarPrefixLength) {
maxUnderbarPrefixLength = underbarPrefixLength;
}
}
const arbitraryNamePrefix = `${'_'.repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
let namedExportCode = '';
const defaultExportRows = [];
const arbitraryNameExportRows = [];
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, '')}`);
if (options.includeArbitraryNames && isWellFormedString(key)) {
const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
}
}
}
const arbitraryExportCode = arbitraryNameExportRows.length > 0
? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}`
: '';
const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
};
function exactRegex(str, flags) {
return new RegExp(`^${combineMultipleStrings(str)}$`, flags);
}
function prefixRegex(str, flags) {
return new RegExp(`^${combineMultipleStrings(str)}`, flags);
}
function suffixRegex(str, flags) {
return new RegExp(`${combineMultipleStrings(str)}$`, flags);
}
const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
function escapeRegex(str) {
return str.replace(escapeRegexRE, '\\$&');
}
function combineMultipleStrings(str) {
if (Array.isArray(str)) {
const escapeStr = str.map(escapeRegex).join('|');
if (escapeStr && str.length > 1) {
return `(?:${escapeStr})`;
}
return escapeStr;
}
return escapeRegex(str);
}
// TODO: remove this in next major
var index = {
addExtension,
attachScopes,
createFilter,
dataToEsm,
exactRegex,
extractAssignedNames,
makeLegalIdentifier,
normalizePath,
prefixRegex,
suffixRegex
};
exports.addExtension = addExtension;
exports.attachScopes = attachScopes;
exports.createFilter = createFilter;
exports.dataToEsm = dataToEsm;
exports.default = index;
exports.exactRegex = exactRegex;
exports.extractAssignedNames = extractAssignedNames;
exports.makeLegalIdentifier = makeLegalIdentifier;
exports.normalizePath = normalizePath;
exports.prefixRegex = prefixRegex;
exports.suffixRegex = suffixRegex;
module.exports = Object.assign(exports.default, exports);
//# sourceMappingURL=index.js.map

View file

@ -0,0 +1,392 @@
import { extname, win32, posix, isAbsolute, resolve } from 'path';
import { walk } from 'estree-walker';
import pm from 'picomatch';
const addExtension = function addExtension(filename, ext = '.js') {
let result = `${filename}`;
if (!extname(filename))
result += ext;
return result;
};
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];
node.declarations.forEach((declaration) => {
scope.addDeclaration(declaration, isBlockDeclaration, true);
});
}
let newScope;
// create new function scope
if (node.type.includes('Function')) {
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 for scope
if (/For(?:In|Of)?Statement/.test(node.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
// create new block scope
if (node.type === 'BlockStatement' && !parent.type.includes('Function')) {
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];
}
const normalizePathRegExp = new RegExp(`\\${win32.sep}`, 'g');
const normalizePath = function normalizePath(filename) {
return filename.replace(normalizePathRegExp, posix.sep);
};
function getMatcherString(id, resolutionBase) {
if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) {
return normalizePath(id);
}
// resolve('') is valid and will default to process.cwd()
const basePath = normalizePath(resolve(resolutionBase || ''))
// 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, normalizePath(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);
if (!includeMatchers.length && !excludeMatchers.length)
return (id) => typeof id === 'string' && !id.includes('\0');
return function result(id) {
if (typeof id !== 'string')
return false;
if (id.includes('\0'))
return false;
const pathId = normalizePath(id);
for (let i = 0; i < excludeMatchers.length; ++i) {
const matcher = excludeMatchers[i];
if (matcher instanceof RegExp) {
matcher.lastIndex = 0;
}
if (matcher.test(pathId))
return false;
}
for (let i = 0; i < includeMatchers.length; ++i) {
const matcher = includeMatchers[i];
if (matcher instanceof RegExp) {
matcher.lastIndex = 0;
}
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 (typeof obj === 'object' && obj !== null) {
if (Array.isArray(obj))
return serializeArray(obj, indent, baseIndent);
if (obj instanceof Date)
return `new Date(${obj.getTime()})`;
if (obj instanceof RegExp)
return obj.toString();
return serializeObject(obj, indent, baseIndent);
}
if (typeof obj === 'number') {
if (obj === Infinity)
return 'Infinity';
if (obj === -Infinity)
return '-Infinity';
if (obj === 0)
return 1 / obj === Infinity ? '0' : '-0';
if (obj !== obj)
return 'NaN'; // eslint-disable-line no-self-compare
}
if (typeof obj === 'symbol') {
const key = Symbol.keyFor(obj);
// eslint-disable-next-line no-undefined
if (key !== undefined)
return `Symbol.for(${stringify(key)})`;
}
if (typeof obj === 'bigint')
return `${obj}n`;
return stringify(obj);
}
// isWellFormed exists from Node.js 20
const hasStringIsWellFormed = 'isWellFormed' in String.prototype;
function isWellFormedString(input) {
// @ts-expect-error String::isWellFormed exists from ES2024. tsconfig lib is set to ES6
if (hasStringIsWellFormed)
return input.isWellFormed();
// https://github.com/tc39/proposal-is-usv-string/blob/main/README.md#algorithm
return !/\p{Surrogate}/u.test(input);
}
const dataToEsm = function dataToEsm(data, options = {}) {
var _a, _b;
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 maxUnderbarPrefixLength = 0;
for (const key of Object.keys(data)) {
const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
if (underbarPrefixLength > maxUnderbarPrefixLength) {
maxUnderbarPrefixLength = underbarPrefixLength;
}
}
const arbitraryNamePrefix = `${'_'.repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
let namedExportCode = '';
const defaultExportRows = [];
const arbitraryNameExportRows = [];
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, '')}`);
if (options.includeArbitraryNames && isWellFormedString(key)) {
const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
}
}
}
const arbitraryExportCode = arbitraryNameExportRows.length > 0
? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}`
: '';
const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
};
function exactRegex(str, flags) {
return new RegExp(`^${combineMultipleStrings(str)}$`, flags);
}
function prefixRegex(str, flags) {
return new RegExp(`^${combineMultipleStrings(str)}`, flags);
}
function suffixRegex(str, flags) {
return new RegExp(`${combineMultipleStrings(str)}$`, flags);
}
const escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
function escapeRegex(str) {
return str.replace(escapeRegexRE, '\\$&');
}
function combineMultipleStrings(str) {
if (Array.isArray(str)) {
const escapeStr = str.map(escapeRegex).join('|');
if (escapeStr && str.length > 1) {
return `(?:${escapeStr})`;
}
return escapeStr;
}
return escapeRegex(str);
}
// TODO: remove this in next major
var index = {
addExtension,
attachScopes,
createFilter,
dataToEsm,
exactRegex,
extractAssignedNames,
makeLegalIdentifier,
normalizePath,
prefixRegex,
suffixRegex
};
export { addExtension, attachScopes, createFilter, dataToEsm, index as default, exactRegex, extractAssignedNames, makeLegalIdentifier, normalizePath, prefixRegex, suffixRegex };
//# sourceMappingURL=index.js.map

View file

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

View file

@ -0,0 +1,99 @@
{
"name": "@rollup/pluginutils",
"version": "5.3.0",
"publishConfig": {
"access": "public"
},
"description": "A set of utility functions commonly used by Rollup plugins",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/pluginutils"
},
"author": "Rich Harris <richard.a.harris@gmail.com>",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/pluginutils#readme",
"bugs": {
"url": "https://github.com/rollup/plugins/issues"
},
"main": "./dist/cjs/index.js",
"module": "./dist/es/index.js",
"type": "commonjs",
"exports": {
"types": "./types/index.d.ts",
"import": "./dist/es/index.js",
"default": "./dist/cjs/index.js"
},
"engines": {
"node": ">=14.0.0"
},
"files": [
"dist",
"!dist/**/*.map",
"types",
"README.md",
"LICENSE"
],
"keywords": [
"rollup",
"plugin",
"utils"
],
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
},
"dependencies": {
"@types/estree": "^1.0.0",
"estree-walker": "^2.0.2",
"picomatch": "^4.0.2"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^23.0.0",
"@rollup/plugin-node-resolve": "^15.0.0",
"@rollup/plugin-typescript": "^9.0.1",
"@types/node": "^14.18.30",
"@types/picomatch": "^2.3.0",
"acorn": "^8.8.0",
"rollup": "^4.0.0-24",
"typescript": "^4.8.3"
},
"types": "./types/index.d.ts",
"ava": {
"extensions": [
"ts"
],
"require": [
"ts-node/register"
],
"workerThreads": false,
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"nyc": {
"extension": [
".js",
".ts"
]
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm build && pnpm lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm test -- --verbose",
"prebuild": "del-cli dist",
"prerelease": "pnpm build",
"pretest": "pnpm build --sourcemap",
"release": "pnpm --workspace-root package:release $(pwd)",
"test": "ava",
"test:ts": "tsc --noEmit"
}
}

View file

@ -0,0 +1,125 @@
import type { 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;
/**
* @desc When this option is set, dataToEsm will generate a named export for keys that
* are not a valid identifier, by leveraging the "Arbitrary Module Namespace Identifier
* Names" feature. See: https://github.com/tc39/ecma262/pull/2154
*/
includeArbitraryNames?: boolean;
indent?: string;
namedExports?: boolean;
objectShorthand?: boolean;
preferConst?: boolean;
}
/**
* A valid `picomatch` glob 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;
/**
* Constructs a RegExp that matches the exact string specified.
* @param str the string to match.
* @param flags flags for the RegExp.
*/
export function exactRegex(str: string | string[], flags?: string): RegExp;
/**
* 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;
/**
* Converts path separators to forward slash.
*/
export function normalizePath(filename: string): string;
/**
* Constructs a RegExp that matches a value that has the specified prefix.
* @param str the string to match.
* @param flags flags for the RegExp.
*/
export function prefixRegex(str: string | string[], flags?: string): RegExp;
/**
* Constructs a RegExp that matches a value that has the specified suffix.
* @param str the string to match.
* @param flags flags for the RegExp.
*/
export function suffixRegex(str: string | string[], flags?: string): RegExp;
export type AddExtension = typeof addExtension;
export type AttachScopes = typeof attachScopes;
export type CreateFilter = typeof createFilter;
export type ExactRegex = typeof exactRegex;
export type ExtractAssignedNames = typeof extractAssignedNames;
export type MakeLegalIdentifier = typeof makeLegalIdentifier;
export type NormalizePath = typeof normalizePath;
export type DataToEsm = typeof dataToEsm;
export type PrefixRegex = typeof prefixRegex;
export type SuffixRegex = typeof suffixRegex;
declare const defaultExport: {
addExtension: AddExtension;
attachScopes: AttachScopes;
createFilter: CreateFilter;
dataToEsm: DataToEsm;
exactRegex: ExactRegex;
extractAssignedNames: ExtractAssignedNames;
makeLegalIdentifier: MakeLegalIdentifier;
normalizePath: NormalizePath;
prefixRegex: PrefixRegex;
suffixRegex: SuffixRegex;
};
export default defaultExport;

View file

@ -0,0 +1,3 @@
# `@rollup/rollup-win32-x64-gnu`
This is the **x86_64-pc-windows-gnu** binary for `rollup`

View file

@ -0,0 +1,22 @@
{
"name": "@rollup/rollup-win32-x64-gnu",
"version": "4.54.0",
"os": [
"win32"
],
"cpu": [
"x64"
],
"files": [
"rollup.win32-x64-gnu.node"
],
"description": "Native bindings for Rollup",
"author": "Lukas Taegert-Atkinson",
"homepage": "https://rollupjs.org/",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/rollup/rollup.git"
},
"main": "./rollup.win32-x64-gnu.node"
}

View file

@ -0,0 +1,3 @@
# `@rollup/rollup-win32-x64-msvc`
This is the **x86_64-pc-windows-msvc** binary for `rollup`

View file

@ -0,0 +1,22 @@
{
"name": "@rollup/rollup-win32-x64-msvc",
"version": "4.54.0",
"os": [
"win32"
],
"cpu": [
"x64"
],
"files": [
"rollup.win32-x64-msvc.node"
],
"description": "Native bindings for Rollup",
"author": "Lukas Taegert-Atkinson",
"homepage": "https://rollupjs.org/",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/rollup/rollup.git"
},
"main": "./rollup.win32-x64-msvc.node"
}