This commit is contained in:
Iliyan Angelov
2025-09-14 23:24:25 +03:00
commit c67067a2a4
71311 changed files with 6800714 additions and 0 deletions

292
frontend/node_modules/@rollup/plugin-babel/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,292 @@
# @rollup/plugin-babel ChangeLog
## v5.3.1
_2022-02-22_
### Bugfixes
- fix: consider path delimeter on windows (#1090)
## v5.3.0
_2021-02-14_
### Features
- feat: add custom filter option (#767)
- feat: pass rollup context as this context into override config function (#784)
### Updates
- docs: typo in README.md (#800)
- chore: commit updated readme format (bfda6d8)
## v5.2.3
_2021-01-29_
### Updates
- docs: add usage with commonjs. fixes #622 (6b4b7b6)
- docs: update export in README (#690)
## v5.2.2
_2020-11-30_
### Bugfixes
- fix: clone cached helper identifier before returning it (#584)
- fix: strip hash and query param in extension filter (#533)
## v5.2.1
_2020-09-09_
### Updates
- chore: add deprecation/migration warnings for the runtime (#534)
## v5.2.0
_2020-08-13_
### Features
- feat: `export * as ns` support (#511)
### Updates
- chore: update dependencies (13526d6)
## v5.1.0
_2020-07-12_
### Features
- feat: add typings (#462)
### Updates
- docs: add note about excluding @babel/runtime helpers via regex (#483)
## v5.0.4
_2020-06-22_
### Updates
- docs: remove unused import in "Usage" example (#460)
- docs: update node requirement in readme (#443)
- docs: fix typo in readme (#447)
## v5.0.3
_2020-06-05_
### Updates
- docs: update `babelHelpers` description (#397)
## v5.0.2
_2020-05-20_
### Bugfixes
- fix: use loadPartialConfigAsync when it is available (#359)
### Updates
- docs: Cleanup misleading leftovers in the README (#377)
- docs: correct breaking change note in v5 CHANGELOG (#368)
## v5.0.1
_2020-05-20_
### Bugfixes
- fix: use loadPartialConfigAsync when it is available (#359)
### Updates
- docs: Cleanup misleading leftovers in the README (#377)
- docs: correct breaking change note in v5 CHANGELOG (#368)
# @rollup/plugin-babel changelog
## 5.0.0
_2020-04-27_
### Features
- Added `getBabelOutputPlugin` and `createBabelOutputPluginFactory` exports which can be used to transform generated code
- Added `skipPreflightCheck` option. The plugin performs some extra checks to see if the passed configuration is correct and matching its expectations. This comes with some runtime overhead and can slow down builds. If you know what you are doing and you are confident that you have configured things correctly you can disable those checks with this option.
- Published as `@rollup/plugin-babel`
### Updates
- Default export exported as `getBabelInputPlugin` for symmetry with `getBabelOutputPlugin`
### Breaking Changes
- Minimum compatible Rollup version is 1.2.0
- Minimum supported Node version is 10.0.0
- `.custom` factory is now available as separate `createBabelInputPluginFactory` export
- Removed `externalHelpers` & `runtimeHelpers` options. There is now a single `babelHelpers` option which can take one of `'bundled'`, `'inline'`, `'runtime'` and `'external'` as a value. The default is `'bundled'` which matches 4.x behavior, but it is recommended to configure this option explicitly.
## 4.3.2
- Fixed usage with `externalHelpers: true` option
## 4.3.1
- Add `.js` extension to the virtual babel helpers file (only matters when using `preserveModules` option in rollup)
## 4.3.0
- Added `.custom` builder.
- Fail build when a plugin tries to add non existent babel helper
## 4.2.0
Allow `rollup@1` as peer dependency.
## 4.1.0
- Fixed "preflight check" for ignored files.
- Return `null` when no transformation has been done (fixing source maps for this case)
## 4.0.3
Fixed fallback class transform in "preflight check".
## 4.0.2
Fixed `rollup` peer dependency.
## 4.0.0
Babel 7 compatible! (dropped Babel 6 compatibility though).
Additionally:
- Internal preflight checks are created now per plugin instance, so using 2 instances of rollup-plugin-babel (i.e. targeting 2 different set of files with include/exclude options) shouldn't conflict with each other
- Transpiling by default only what Babel transpiles - files with those extensions: .js, .jsx, .es6, .es, .mjs. You can customize this with new `extensions` option. This also fixes long standing issue with rollup-plugin-babel trying to transform JSON files.
## 3.0.3
- Drop babel7 support. Use 4.0.0-beta if you use babel 7
- Use "module" in addition to "jsnext:main" ([#150](https://github.com/rollup/rollup-plugin-babel/issues/150))
- Remove unused babel helpers namespace declaration & expression ([#164](https://github.com/rollup/rollup-plugin-babel/issues/164))
## 3.0.2
- Fix regression with Babel 6 ([#158](https://github.com/rollup/rollup-plugin-babel/issues/158))
## 3.0.1
- Wasn't working, fix bug with transform (not using es2015-classes for preflight check)
## 3.0.0
- Drop Node 0.10/0.12 (Use native `Object.assign`)
- Change `babel-core` to be a peerDependency
- Support `babel-core` v7 as well as a peerDep (no changes necessary)
## 2.7.1
- Prevent erroneous warnings about duplicated runtime helpers ([#105](https://github.com/rollup/rollup-plugin-babel/issues/105))
- Ignore `ignore` option in preflight check ([#102](https://github.com/rollup/rollup-plugin-babel/issues/102))
- Allow custom `moduleName` with `runtime-helpers` ([#95](https://github.com/rollup/rollup-plugin-babel/issues/95))
## 2.7.0
- Add `externalHelpersWhitelist` option ([#92](https://github.com/rollup/rollup-plugin-babel/pull/92))
- Ignore `only` option during preflight checks ([#98](https://github.com/rollup/rollup-plugin-babel/issues/98))
- Use `options.onwarn` if available ([#84](https://github.com/rollup/rollup-plugin-babel/issues/84))
- Update documentation and dependencies
## 2.6.1
- Return a `name`
## 2.6.0
- Use `\0` convention for helper module ID ([#64](https://github.com/rollup/rollup-plugin-babel/issues/64))
## 2.5.1
- Don't mutate `options.plugins` ([#47](https://github.com/rollup/rollup-plugin-babel/issues/47))
## 2.5.0
- Import `babelHelpers` rather than injecting them allows `transform` function to be pure ([#rollup/658](https://github.com/rollup/rollup/pull/658#issuecomment-223876824))
## 2.4.0
- Add `externalHelpers` option ([#41](https://github.com/rollup/rollup-plugin-babel/pull/41))
## 2.3.9
- Do not rename Babel helpers ([#34](https://github.com/rollup/rollup-plugin-babel/pull/34))
## 2.3.8
- Create new version to (hopefully) solve bizarre CI issue
## 2.3.7
- Be less clever about renaming Babel helpers ([#19](https://github.com/rollup/rollup-plugin-babel/issues/19))
## 2.3.6
- Fix cache misses in preflight check ([#29](https://github.com/rollup/rollup-plugin-babel/pull/29))
## 2.3.5
- Use class transformer local to plugin, not project being built
## 2.3.4
- Ensure class transformer is present for preflight check, and only run check once per directory ([#23](https://github.com/rollup/rollup-plugin-babel/issues/23))
## 2.3.3
- Fix helper renaming ([#22](https://github.com/rollup/rollup-plugin-babel/issues/22))
## 2.3.1-2
- Include correct files in npm package
## 2.3.0
- Allow `transform-runtime` Babel plugin, if combined with `runtimeHelpers: true` option ([#17](https://github.com/rollup/rollup-plugin-babel/issues/17))
- More permissive handling of helpers only warn if inline helpers are duplicated
- Handle plugins that change export patterns ([#18](https://github.com/rollup/rollup-plugin-babel/issues/18))
## 2.2.0
- Preflight checks are run per-file, to avoid configuration snafus ([#16](https://github.com/rollup/rollup-plugin-babel/issues/16))
## 2.1.0
- Generate sourcemaps by default
## 2.0.1
- Use object-assign ponyfill
- Add travis support
- Fix test
## 2.0.0
- Babel 6 compatible
## 1.0.0
- First release

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

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

380
frontend/node_modules/@rollup/plugin-babel/README.md generated vendored Normal file
View File

@@ -0,0 +1,380 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-babel
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-babel
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-babel
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-babel
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-babel
🍣 A Rollup plugin for seamless integration between Rollup and Babel.
## Why?
If you're using Babel to transpile your ES6/7 code and Rollup to generate a standalone bundle, you have a couple of options:
- run the code through Babel first, being careful to exclude the module transformer, or
- run the code through Rollup first, and _then_ pass it to Babel.
Both approaches have disadvantages in the first case, on top of the additional configuration complexity, you may end up with Babel's helpers (like `classCallCheck`) repeated throughout your code (once for each module where the helpers are used). In the second case, transpiling is likely to be slower, because transpiling a large bundle is much more work for Babel than transpiling a set of small files.
Either way, you have to worry about a place to put the intermediate files, and getting sourcemaps to behave becomes a royal pain.
Using Rollup with `@rollup/plugin-babel` makes the process far easier.
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v10.0.0+) and Rollup v1.20.0+.
## Install
```bash
npm install @rollup/plugin-babel --save-dev
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import { babel } from '@rollup/plugin-babel';
const config = {
input: 'src/index.js',
output: {
dir: 'output',
format: 'esm'
},
plugins: [babel({ babelHelpers: 'bundled' })]
};
export default config;
```
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).
### Using With `@rollup/plugin-commonjs`
When using `@rollup/plugin-babel` with `@rollup/plugin-commonjs` in the same Rollup configuration, it's important to note that `@rollup/plugin-commonjs` _must_ be placed before this plugin in the `plugins` array for the two to work together properly. e.g.
```js
import { babel } from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
const config = {
...
plugins: [
commonjs(),
babel({ babelHelpers: 'bundled' })
],
};
```
## Options
This plugin respects Babel [configuration files](https://babeljs.io/docs/en/configuration) by default and they are generally the best place to put your configuration.
You can also run Babel on the generated chunks instead of the input files. Even though this is slower, it is the only way to transpile Rollup's auto-generated wrapper code to lower compatibility targets than ES5, see [Running Babel on the generated code](#running-babel-on-the-generated-code) for details.
All options are as per the [Babel documentation](https://babeljs.io/docs/en/options), plus the following:
### `exclude`
Type: `String | RegExp | Array[...String|RegExp]`<br>
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. When relying on Babel configuration files you can only exclude additional files with this option, you cannot override what you have configured for Babel itself.
### `include`
Type: `String | RegExp | Array[...String|RegExp]`<br>
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should operate on. When relying on Babel configuration files you cannot include files already excluded there.
### `filter`
Type: (id: string) => boolean<br>
Custom [filter function](https://github.com/rollup/plugins/tree/master/packages/pluginutils#createfilter) can be used to determine whether or not certain modules should be operated upon.
Usage:
```js
import { createFilter } from '@rollup/pluginutils';
const include = 'include/**.js';
const exclude = 'exclude/**.js';
const filter = createFilter(include, exclude, {});
```
### `extensions`
Type: `Array[...String]`<br>
Default: `['.js', '.jsx', '.es6', '.es', '.mjs']`
An array of file extensions that Babel should transpile. If you want to transpile TypeScript files with this plugin it's essential to include `.ts` and `.tsx` in this option.
### `babelHelpers`
Type: `'bundled' | 'runtime' | 'inline' | 'external'`<br>
Default: `'bundled'`
It is recommended to configure this option explicitly (even if with its default value) so an informed decision is taken on how those babel helpers are inserted into the code.
We recommend to follow these guidelines to determine the most appropriate value for your project:
- `'runtime'` - you should use this especially when building libraries with Rollup. It has to be used in combination with `@babel/plugin-transform-runtime` and you should also specify `@babel/runtime` as dependency of your package. Don't forget to tell Rollup to treat the helpers imported from within the `@babel/runtime` module as external dependencies when bundling for `cjs` & `es` formats. This can be accomplished via regex (`external: [/@babel\/runtime/]`) or a function (`external: id => id.includes('@babel/runtime')`). It's important to not only specify `external: ['@babel/runtime']` since the helpers are imported from nested paths (e.g `@babel/runtime/helpers/get`) and [Rollup will only exclude modules that match strings exactly](https://rollupjs.org/guide/en/#peer-dependencies).
- `'bundled'` - you should use this if you want your resulting bundle to contain those helpers (at most one copy of each). Useful especially if you bundle an application code.
- `'external'` - use this only if you know what you are doing. It will reference helpers on **global** `babelHelpers` object. Used in combination with `@babel/plugin-external-helpers`.
- `'inline'` - this is not recommended. Helpers will be inserted in each file using this option. This can cause serious code duplication. This is the default Babel behavior as Babel operates on isolated files - however, as Rollup is a bundler and is project-aware (and therefore likely operating across multiple input files), the default of this plugin is `"bundled"`.
### `skipPreflightCheck`
Type: `Boolean`<br>
Default: `false`
Before transpiling your input files this plugin also transpile a short piece of code **for each** input file. This is used to validate some misconfiguration errors, but for sufficiently big projects it can slow your build times so if you are confident about your configuration then you might disable those checks with this option.
### External dependencies
Ideally, you should only be transforming your source code, rather than running all of your external dependencies through Babel (to ignore external dependencies from being handled by this plugin you might use `exclude: 'node_modules/**'` option). If you have a dependency that exposes untranspiled ES6 source code that doesn't run in your target environment, then you may need to break this rule, but it often causes problems with unusual `.babelrc` files or mismatched versions of Babel.
We encourage library authors not to distribute code that uses untranspiled ES6 features (other than modules) for this reason. Consumers of your library should _not_ have to transpile your ES6 code, any more than they should have to transpile your CoffeeScript, ClojureScript or TypeScript.
Use `babelrc: false` to prevent Babel from using local (i.e. to your external dependencies) `.babelrc` files, relying instead on the configuration you pass in.
### Helpers
In some cases Babel uses _helpers_ to avoid repeating chunks of code  for example, if you use the `class` keyword, it will use a `classCallCheck` function to ensure that the class is instantiated correctly.
By default, those helpers will be inserted at the top of the file being transformed, which can lead to duplication. This rollup plugin automatically deduplicates those helpers, keeping only one copy of each one used in the output bundle. Rollup will combine the helpers in a single block at the top of your bundle.
You can customize how those helpers are being inserted into the transformed file with [`babelHelpers`](#babelhelpers) option.
### Modules
This is not needed since Babel 7 - it knows automatically that Rollup understands ES modules & that it shouldn't use any module transform with it. Unless you forcefully include a module transform in your Babel configuration.
If you have been pointed to this section by an error thrown by this plugin, please check your Babel configuration files and disable any module transforms when running Rollup builds.
## Running Babel on the generated code
You can run `@rollup/plugin-babel` on the output files instead of the input files by using `getBabelOutputPlugin(...)`. This can be used to perform code transformations on the resulting chunks and is the only way to transform Rollup's auto-generated code. By default, the plugin will be applied to all outputs:
```js
// rollup.config.js
import { getBabelOutputPlugin } from '@rollup/plugin-babel';
export default {
input: 'main.js',
plugins: [
getBabelOutputPlugin({
presets: ['@babel/preset-env']
})
],
output: [
{ file: 'bundle.cjs.js', format: 'cjs' },
{ file: 'bundle.esm.js', format: 'esm' }
]
};
```
If you only want to apply it to specific outputs, you can use it as an output plugin (requires at least Rollup v1.27.0):
```js
// rollup.config.js
import { getBabelOutputPlugin } from '@rollup/plugin-babel';
export default {
input: 'main.js',
output: [
{ file: 'bundle.js', format: 'esm' },
{
file: 'bundle.es5.js',
format: 'esm',
plugins: [getBabelOutputPlugin({ presets: ['@babel/preset-env'] })]
}
]
};
```
The `include`, `exclude` and `extensions` options are ignored when the when using `getBabelOutputPlugin` and `createBabelOutputPluginFactory` will produce warnings, and there are a few more points to note that users should be aware of.
You can also run the plugin twice on the code, once when processing the input files to transpile special syntax to JavaScript and once on the output to transpile to a lower compatibility target:
```js
// rollup.config.js
import babel, { getBabelOutputPlugin } from '@rollup/plugin-babel';
export default {
input: 'main.js',
plugins: [babel({ presets: ['@babel/preset-react'] })],
output: [
{
file: 'bundle.js',
format: 'esm',
plugins: [getBabelOutputPlugin({ presets: ['@babel/preset-env'] })]
}
]
};
```
### Babel configuration files
Unlike the regular `babel` plugin, `getBabelOutputPlugin(...)` will **not** automatically search for [Babel configuration files](https://babeljs.io/docs/en/config-files). Besides passing in Babel options directly, however, you can specify a configuration file manually via Babel's [`configFile`](https://babeljs.io/docs/en/options#configfile) option:
```js
getBabelOutputPlugin({
configFile: path.resolve(__dirname, 'babel.config.js')
});
```
### Using formats other than ES modules or CommonJS
As `getBabelOutputPlugin(...)` will run _after_ Rollup has done all its transformations, it needs to make sure it preserves the semantics of Rollup's output format. This is especially important for Babel plugins that add, modify or remove imports or exports, but also for other transformations that add new variables as they can accidentally become global variables depending on the format. Therefore it is recommended that for formats other than `esm` or `cjs`, you set Rollup to use the `esm` output format and let Babel handle the transformation to another format, e.g. via
```
presets: [['@babel/preset-env', { modules: 'umd' }], ...]
```
to create a UMD/IIFE compatible output. If you want to use `getBabelOutputPlugin(...)` with other formats, you need to specify `allowAllFormats: true` as plugin option:
```js
rollup.rollup({...})
.then(bundle => bundle.generate({
format: 'iife',
plugins: [getBabelOutputPlugin({
allowAllFormats: true,
// ...
})]
}))
```
### Injected helpers
By default, helpers e.g. when transpiling classes will be inserted at the top of each chunk. In contrast to when applying this plugin on the input files, helpers will not be deduplicated across chunks.
Alternatively, you can use imported runtime helpers by adding the `@babel/transform-runtime` plugin. This will make `@babel/runtime` an external dependency of your project, see [@babel/plugin-transform-runtime](https://babeljs.io/docs/en/babel-plugin-transform-runtime) for details.
Note that this will only work for `esm` and `cjs` formats, and you need to make sure to set the `useESModules` option of `@babel/plugin-transform-runtime` to `true` if you create ESM output:
```js
rollup.rollup({...})
.then(bundle => bundle.generate({
format: 'esm',
plugins: [getBabelOutputPlugin({
presets: ['@babel/preset-env'],
plugins: [['@babel/plugin-transform-runtime', { useESModules: true }]]
})]
}))
```
```js
// input
export default class Foo {}
// output
import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';
var Foo = function Foo() {
_classCallCheck(this, Foo);
};
export default Foo;
```
And for CommonJS:
```js
rollup.rollup({...})
.then(bundle => bundle.generate({
format: 'cjs',
plugins: [getBabelOutputPlugin({
presets: ['@babel/preset-env'],
plugins: [['@babel/plugin-transform-runtime', { useESModules: false }]]
})]
}))
```
```js
// input
export default class Foo {}
// output
('use strict');
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var Foo = function Foo() {
_classCallCheck(this, Foo);
};
module.exports = Foo;
```
Another option is to use `@babel/plugin-external-helpers`, which will reference the global `babelHelpers` object. It is your responsibility to make sure this global variable exists.
## Custom plugin builder
`@rollup/plugin-babel` exposes a plugin-builder utility that allows users to add custom handling of Babel's configuration for each file that it processes.
`createBabelInputPluginFactory` accepts a callback that will be called with the loader's instance of `babel` so that tooling can ensure that it using exactly the same `@babel/core` instance as the loader itself.
It's main purpose is to allow other tools for configuration of transpilation without forcing people to add extra configuration but still allow for using their own babelrc / babel config files.
### Example
```js
import { createBabelInputPluginFactory } from '@rollup/plugin-babel';
export default createBabelInputPluginFactory((babelCore) => {
function myPlugin() {
return {
visitor: {}
};
}
return {
// Passed the plugin options.
options({ opt1, opt2, ...pluginOptions }) {
return {
// Pull out any custom options that the plugin might have.
customOptions: { opt1, opt2 },
// Pass the options back with the two custom options removed.
pluginOptions
};
},
config(cfg /* Passed Babel's 'PartialConfig' object. */, { code, customOptions }) {
if (cfg.hasFilesystemConfig()) {
// Use the normal config
return cfg.options;
}
return {
...cfg.options,
plugins: [
...(cfg.options.plugins || []),
// Include a custom plugin in the options.
myPlugin
]
};
},
result(result, { code, customOptions, config, transformOptions }) {
return {
...result,
code: result.code + '\n// Generated by some custom plugin'
};
}
};
});
```
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View File

@@ -0,0 +1,488 @@
import * as babel from '@babel/core';
import { createFilter } from '@rollup/pluginutils';
import { addNamed } from '@babel/helper-module-imports';
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
const BUNDLED = 'bundled';
const INLINE = 'inline';
const RUNTIME = 'runtime';
const EXTERNAL = 'external'; // NOTE: DO NOT REMOVE the null character `\0` as it may be used by other plugins
// e.g. https://github.com/rollup/rollup-plugin-node-resolve/blob/313a3e32f432f9eb18cc4c231cc7aac6df317a51/src/index.js#L74
const HELPERS = '\0rollupPluginBabelHelpers.js';
function importHelperPlugin({
types: t
}) {
return {
pre(file) {
const cachedHelpers = {};
file.set('helperGenerator', name => {
if (!file.availableHelper(name)) {
return null;
}
if (cachedHelpers[name]) {
return t.cloneNode(cachedHelpers[name]);
}
return cachedHelpers[name] = addNamed(file.path, name, HELPERS);
});
}
};
}
const addBabelPlugin = (options, plugin) => {
return _objectSpread2(_objectSpread2({}, options), {}, {
plugins: options.plugins.concat(plugin)
});
};
const warned = {};
function warnOnce(ctx, msg) {
if (warned[msg]) return;
warned[msg] = true;
ctx.warn(msg);
}
const regExpCharactersRegExp = /[\\^$.*+?()[\]{}|]/g;
const escapeRegExpCharacters = str => str.replace(regExpCharactersRegExp, '\\$&');
function stripQuery(id) {
// strip query params from import
const [bareId, query] = id.split('?');
const suffix = `${query ? `?${query}` : ''}`;
return {
bareId,
query,
suffix
};
}
const MODULE_ERROR = 'Rollup requires that your Babel configuration keeps ES6 module syntax intact. ' + 'Unfortunately it looks like your configuration specifies a module transformer ' + 'to replace ES6 modules with another module format. To continue you have to disable it.' + '\n\n' + "Most commonly it's a CommonJS transform added by @babel/preset-env - " + 'in such case you should disable it by adding `modules: false` option to that preset ' + '(described in more detail here - https://github.com/rollup/plugins/tree/master/packages/babel#modules ).';
const UNEXPECTED_ERROR = 'An unexpected situation arose. Please raise an issue at ' + 'https://github.com/rollup/plugins/issues. Thanks!';
const PREFLIGHT_TEST_STRING = '__ROLLUP__PREFLIGHT_CHECK_DO_NOT_TOUCH__';
const PREFLIGHT_INPUT = `export default "${PREFLIGHT_TEST_STRING}";`;
function helpersTestTransform() {
return {
visitor: {
StringLiteral(path, state) {
if (path.node.value === PREFLIGHT_TEST_STRING) {
path.replaceWith(state.file.addHelper('inherits'));
}
}
}
};
}
const mismatchError = (actual, expected, filename) => `You have declared using "${expected}" babelHelpers, but transforming ${filename} resulted in "${actual}". Please check your configuration.`; // Revert to /\/helpers\/(esm\/)?inherits/ when Babel 8 gets released, this was fixed in https://github.com/babel/babel/issues/14185
const inheritsHelperRe = /[\\/]+helpers[\\/]+(esm[\\/]+)?inherits/;
async function preflightCheck(ctx, babelHelpers, transformOptions) {
const finalOptions = addBabelPlugin(transformOptions, helpersTestTransform);
const check = (await babel.transformAsync(PREFLIGHT_INPUT, finalOptions)).code; // Babel sometimes splits ExportDefaultDeclaration into 2 statements, so we also check for ExportNamedDeclaration
if (!/export (d|{)/.test(check)) {
ctx.error(MODULE_ERROR);
}
if (inheritsHelperRe.test(check)) {
if (babelHelpers === RUNTIME) {
return;
}
ctx.error(mismatchError(RUNTIME, babelHelpers, transformOptions.filename));
}
if (check.includes('babelHelpers.inherits')) {
if (babelHelpers === EXTERNAL) {
return;
}
ctx.error(mismatchError(EXTERNAL, babelHelpers, transformOptions.filename));
} // test unminifiable string content
if (check.includes('Super expression must either be null or a function')) {
if (babelHelpers === INLINE || babelHelpers === BUNDLED) {
return;
}
if (babelHelpers === RUNTIME && !transformOptions.plugins.length) {
ctx.error(`You must use the \`@babel/plugin-transform-runtime\` plugin when \`babelHelpers\` is "${RUNTIME}".\n`);
}
ctx.error(mismatchError(INLINE, babelHelpers, transformOptions.filename));
}
ctx.error(UNEXPECTED_ERROR);
}
async function transformCode(inputCode, babelOptions, overrides, customOptions, ctx, finalizeOptions) {
// loadPartialConfigAsync has become available in @babel/core@7.8.0
const config = await (babel.loadPartialConfigAsync || babel.loadPartialConfig)(babelOptions); // file is ignored by babel
if (!config) {
return null;
}
let transformOptions = !overrides.config ? config.options : await overrides.config.call(ctx, config, {
code: inputCode,
customOptions
});
if (finalizeOptions) {
transformOptions = await finalizeOptions(transformOptions);
}
if (!overrides.result) {
const {
code,
map
} = await babel.transformAsync(inputCode, transformOptions);
return {
code,
map
};
}
const result = await babel.transformAsync(inputCode, transformOptions);
const {
code,
map
} = await overrides.result.call(ctx, result, {
code: inputCode,
customOptions,
config,
transformOptions
});
return {
code,
map
};
}
const unpackOptions = (_ref = {}) => {
let {
extensions = babel.DEFAULT_EXTENSIONS,
// rollup uses sourcemap, babel uses sourceMaps
// just normalize them here so people don't have to worry about it
sourcemap = true,
sourcemaps = true,
sourceMap = true,
sourceMaps = true
} = _ref,
rest = _objectWithoutProperties(_ref, ["extensions", "sourcemap", "sourcemaps", "sourceMap", "sourceMaps"]);
return _objectSpread2(_objectSpread2({
extensions,
plugins: [],
sourceMaps: sourcemap && sourcemaps && sourceMap && sourceMaps
}, rest), {}, {
caller: _objectSpread2({
name: '@rollup/plugin-babel'
}, rest.caller)
});
};
const warnAboutDeprecatedHelpersOption = ({
deprecatedOption,
suggestion
}) => {
// eslint-disable-next-line no-console
console.warn(`\`${deprecatedOption}\` has been removed in favor a \`babelHelpers\` option. Try changing your configuration to \`${suggestion}\`. ` + `Refer to the documentation to learn more: https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers`);
};
const unpackInputPluginOptions = (_ref2, rollupVersion) => {
let {
skipPreflightCheck = false
} = _ref2,
rest = _objectWithoutProperties(_ref2, ["skipPreflightCheck"]);
if ('runtimeHelpers' in rest) {
warnAboutDeprecatedHelpersOption({
deprecatedOption: 'runtimeHelpers',
suggestion: `babelHelpers: 'runtime'`
});
} else if ('externalHelpers' in rest) {
warnAboutDeprecatedHelpersOption({
deprecatedOption: 'externalHelpers',
suggestion: `babelHelpers: 'external'`
});
} else if (!rest.babelHelpers) {
// eslint-disable-next-line no-console
console.warn("babelHelpers: 'bundled' option was used by default. It is recommended to configure this option explicitly, read more here: " + 'https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers');
}
return unpackOptions(_objectSpread2(_objectSpread2({}, rest), {}, {
skipPreflightCheck,
babelHelpers: rest.babelHelpers || BUNDLED,
caller: _objectSpread2({
supportsStaticESM: true,
supportsDynamicImport: true,
supportsTopLevelAwait: true,
// todo: remove version checks for 1.20 - 1.25 when we bump peer deps
supportsExportNamespaceFrom: !rollupVersion.match(/^1\.2[0-5]\./)
}, rest.caller)
}));
};
const unpackOutputPluginOptions = (options, {
format
}) => unpackOptions(_objectSpread2(_objectSpread2({
configFile: false,
sourceType: format === 'es' ? 'module' : 'script'
}, options), {}, {
caller: _objectSpread2({
supportsStaticESM: format === 'es'
}, options.caller)
}));
function getOptionsWithOverrides(pluginOptions = {}, overrides = {}) {
if (!overrides.options) return {
customOptions: null,
pluginOptionsWithOverrides: pluginOptions
};
const overridden = overrides.options(pluginOptions);
if (typeof overridden.then === 'function') {
throw new Error(".options hook can't be asynchronous. It should return `{ customOptions, pluginsOptions }` synchronously.");
}
return {
customOptions: overridden.customOptions || null,
pluginOptionsWithOverrides: overridden.pluginOptions || pluginOptions
};
}
const returnObject = () => {
return {};
};
function createBabelInputPluginFactory(customCallback = returnObject) {
const overrides = customCallback(babel);
return pluginOptions => {
const {
customOptions,
pluginOptionsWithOverrides
} = getOptionsWithOverrides(pluginOptions, overrides);
let babelHelpers;
let babelOptions;
let filter;
let skipPreflightCheck;
return {
name: 'babel',
options() {
// todo: remove options hook and hoist declarations when version checks are removed
let exclude;
let include;
let extensions;
let customFilter;
var _unpackInputPluginOpt = unpackInputPluginOptions(pluginOptionsWithOverrides, this.meta.rollupVersion);
({
exclude,
extensions,
babelHelpers,
include,
filter: customFilter,
skipPreflightCheck
} = _unpackInputPluginOpt);
babelOptions = _objectWithoutProperties(_unpackInputPluginOpt, ["exclude", "extensions", "babelHelpers", "include", "filter", "skipPreflightCheck"]);
const extensionRegExp = new RegExp(`(${extensions.map(escapeRegExpCharacters).join('|')})$`);
if (customFilter && (include || exclude)) {
throw new Error('Could not handle include or exclude with custom filter together');
}
const userDefinedFilter = typeof customFilter === 'function' ? customFilter : createFilter(include, exclude);
filter = id => extensionRegExp.test(stripQuery(id).bareId) && userDefinedFilter(id);
return null;
},
resolveId(id) {
if (id !== HELPERS) {
return null;
}
return id;
},
load(id) {
if (id !== HELPERS) {
return null;
}
return babel.buildExternalHelpers(null, 'module');
},
transform(code, filename) {
if (!filter(filename)) return null;
if (filename === HELPERS) return null;
return transformCode(code, _objectSpread2(_objectSpread2({}, babelOptions), {}, {
filename
}), overrides, customOptions, this, async transformOptions => {
if (!skipPreflightCheck) {
await preflightCheck(this, babelHelpers, transformOptions);
}
return babelHelpers === BUNDLED ? addBabelPlugin(transformOptions, importHelperPlugin) : transformOptions;
});
}
};
};
}
function getRecommendedFormat(rollupFormat) {
switch (rollupFormat) {
case 'amd':
return 'amd';
case 'iife':
case 'umd':
return 'umd';
case 'system':
return 'systemjs';
default:
return '<module format>';
}
}
function createBabelOutputPluginFactory(customCallback = returnObject) {
const overrides = customCallback(babel);
return pluginOptions => {
const {
customOptions,
pluginOptionsWithOverrides
} = getOptionsWithOverrides(pluginOptions, overrides);
return {
name: 'babel',
renderStart(outputOptions) {
const {
extensions,
include,
exclude,
allowAllFormats
} = pluginOptionsWithOverrides;
if (extensions || include || exclude) {
warnOnce(this, 'The "include", "exclude" and "extensions" options are ignored when transforming the output.');
}
if (!allowAllFormats && outputOptions.format !== 'es' && outputOptions.format !== 'cjs') {
this.error(`Using Babel on the generated chunks is strongly discouraged for formats other than "esm" or "cjs" as it can easily break wrapper code and lead to accidentally created global variables. Instead, you should set "output.format" to "esm" and use Babel to transform to another format, e.g. by adding "presets: [['@babel/env', { modules: '${getRecommendedFormat(outputOptions.format)}' }]]" to your Babel options. If you still want to proceed, add "allowAllFormats: true" to your plugin options.`);
}
},
renderChunk(code, chunk, outputOptions) {
/* eslint-disable no-unused-vars */
const _unpackOutputPluginOp = unpackOutputPluginOptions(pluginOptionsWithOverrides, outputOptions),
babelOptions = _objectWithoutProperties(_unpackOutputPluginOp, ["allowAllFormats", "exclude", "extensions", "externalHelpers", "externalHelpersWhitelist", "include", "runtimeHelpers"]);
/* eslint-enable no-unused-vars */
return transformCode(code, babelOptions, overrides, customOptions, this);
}
};
};
} // export this for symmetry with output-related exports
const getBabelInputPlugin = createBabelInputPluginFactory();
const getBabelOutputPlugin = createBabelOutputPluginFactory();
export { getBabelInputPlugin as babel, createBabelInputPluginFactory, createBabelOutputPluginFactory, getBabelInputPlugin as default, getBabelInputPlugin, getBabelOutputPlugin };

View File

@@ -0,0 +1,517 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var babel = require('@babel/core');
var pluginutils = require('@rollup/pluginutils');
var helperModuleImports = require('@babel/helper-module-imports');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var babel__namespace = /*#__PURE__*/_interopNamespace(babel);
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
const BUNDLED = 'bundled';
const INLINE = 'inline';
const RUNTIME = 'runtime';
const EXTERNAL = 'external'; // NOTE: DO NOT REMOVE the null character `\0` as it may be used by other plugins
// e.g. https://github.com/rollup/rollup-plugin-node-resolve/blob/313a3e32f432f9eb18cc4c231cc7aac6df317a51/src/index.js#L74
const HELPERS = '\0rollupPluginBabelHelpers.js';
function importHelperPlugin({
types: t
}) {
return {
pre(file) {
const cachedHelpers = {};
file.set('helperGenerator', name => {
if (!file.availableHelper(name)) {
return null;
}
if (cachedHelpers[name]) {
return t.cloneNode(cachedHelpers[name]);
}
return cachedHelpers[name] = helperModuleImports.addNamed(file.path, name, HELPERS);
});
}
};
}
const addBabelPlugin = (options, plugin) => {
return _objectSpread2(_objectSpread2({}, options), {}, {
plugins: options.plugins.concat(plugin)
});
};
const warned = {};
function warnOnce(ctx, msg) {
if (warned[msg]) return;
warned[msg] = true;
ctx.warn(msg);
}
const regExpCharactersRegExp = /[\\^$.*+?()[\]{}|]/g;
const escapeRegExpCharacters = str => str.replace(regExpCharactersRegExp, '\\$&');
function stripQuery(id) {
// strip query params from import
const [bareId, query] = id.split('?');
const suffix = `${query ? `?${query}` : ''}`;
return {
bareId,
query,
suffix
};
}
const MODULE_ERROR = 'Rollup requires that your Babel configuration keeps ES6 module syntax intact. ' + 'Unfortunately it looks like your configuration specifies a module transformer ' + 'to replace ES6 modules with another module format. To continue you have to disable it.' + '\n\n' + "Most commonly it's a CommonJS transform added by @babel/preset-env - " + 'in such case you should disable it by adding `modules: false` option to that preset ' + '(described in more detail here - https://github.com/rollup/plugins/tree/master/packages/babel#modules ).';
const UNEXPECTED_ERROR = 'An unexpected situation arose. Please raise an issue at ' + 'https://github.com/rollup/plugins/issues. Thanks!';
const PREFLIGHT_TEST_STRING = '__ROLLUP__PREFLIGHT_CHECK_DO_NOT_TOUCH__';
const PREFLIGHT_INPUT = `export default "${PREFLIGHT_TEST_STRING}";`;
function helpersTestTransform() {
return {
visitor: {
StringLiteral(path, state) {
if (path.node.value === PREFLIGHT_TEST_STRING) {
path.replaceWith(state.file.addHelper('inherits'));
}
}
}
};
}
const mismatchError = (actual, expected, filename) => `You have declared using "${expected}" babelHelpers, but transforming ${filename} resulted in "${actual}". Please check your configuration.`; // Revert to /\/helpers\/(esm\/)?inherits/ when Babel 8 gets released, this was fixed in https://github.com/babel/babel/issues/14185
const inheritsHelperRe = /[\\/]+helpers[\\/]+(esm[\\/]+)?inherits/;
async function preflightCheck(ctx, babelHelpers, transformOptions) {
const finalOptions = addBabelPlugin(transformOptions, helpersTestTransform);
const check = (await babel__namespace.transformAsync(PREFLIGHT_INPUT, finalOptions)).code; // Babel sometimes splits ExportDefaultDeclaration into 2 statements, so we also check for ExportNamedDeclaration
if (!/export (d|{)/.test(check)) {
ctx.error(MODULE_ERROR);
}
if (inheritsHelperRe.test(check)) {
if (babelHelpers === RUNTIME) {
return;
}
ctx.error(mismatchError(RUNTIME, babelHelpers, transformOptions.filename));
}
if (check.includes('babelHelpers.inherits')) {
if (babelHelpers === EXTERNAL) {
return;
}
ctx.error(mismatchError(EXTERNAL, babelHelpers, transformOptions.filename));
} // test unminifiable string content
if (check.includes('Super expression must either be null or a function')) {
if (babelHelpers === INLINE || babelHelpers === BUNDLED) {
return;
}
if (babelHelpers === RUNTIME && !transformOptions.plugins.length) {
ctx.error(`You must use the \`@babel/plugin-transform-runtime\` plugin when \`babelHelpers\` is "${RUNTIME}".\n`);
}
ctx.error(mismatchError(INLINE, babelHelpers, transformOptions.filename));
}
ctx.error(UNEXPECTED_ERROR);
}
async function transformCode(inputCode, babelOptions, overrides, customOptions, ctx, finalizeOptions) {
// loadPartialConfigAsync has become available in @babel/core@7.8.0
const config = await (babel__namespace.loadPartialConfigAsync || babel__namespace.loadPartialConfig)(babelOptions); // file is ignored by babel
if (!config) {
return null;
}
let transformOptions = !overrides.config ? config.options : await overrides.config.call(ctx, config, {
code: inputCode,
customOptions
});
if (finalizeOptions) {
transformOptions = await finalizeOptions(transformOptions);
}
if (!overrides.result) {
const {
code,
map
} = await babel__namespace.transformAsync(inputCode, transformOptions);
return {
code,
map
};
}
const result = await babel__namespace.transformAsync(inputCode, transformOptions);
const {
code,
map
} = await overrides.result.call(ctx, result, {
code: inputCode,
customOptions,
config,
transformOptions
});
return {
code,
map
};
}
const unpackOptions = (_ref = {}) => {
let {
extensions = babel__namespace.DEFAULT_EXTENSIONS,
// rollup uses sourcemap, babel uses sourceMaps
// just normalize them here so people don't have to worry about it
sourcemap = true,
sourcemaps = true,
sourceMap = true,
sourceMaps = true
} = _ref,
rest = _objectWithoutProperties(_ref, ["extensions", "sourcemap", "sourcemaps", "sourceMap", "sourceMaps"]);
return _objectSpread2(_objectSpread2({
extensions,
plugins: [],
sourceMaps: sourcemap && sourcemaps && sourceMap && sourceMaps
}, rest), {}, {
caller: _objectSpread2({
name: '@rollup/plugin-babel'
}, rest.caller)
});
};
const warnAboutDeprecatedHelpersOption = ({
deprecatedOption,
suggestion
}) => {
// eslint-disable-next-line no-console
console.warn(`\`${deprecatedOption}\` has been removed in favor a \`babelHelpers\` option. Try changing your configuration to \`${suggestion}\`. ` + `Refer to the documentation to learn more: https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers`);
};
const unpackInputPluginOptions = (_ref2, rollupVersion) => {
let {
skipPreflightCheck = false
} = _ref2,
rest = _objectWithoutProperties(_ref2, ["skipPreflightCheck"]);
if ('runtimeHelpers' in rest) {
warnAboutDeprecatedHelpersOption({
deprecatedOption: 'runtimeHelpers',
suggestion: `babelHelpers: 'runtime'`
});
} else if ('externalHelpers' in rest) {
warnAboutDeprecatedHelpersOption({
deprecatedOption: 'externalHelpers',
suggestion: `babelHelpers: 'external'`
});
} else if (!rest.babelHelpers) {
// eslint-disable-next-line no-console
console.warn("babelHelpers: 'bundled' option was used by default. It is recommended to configure this option explicitly, read more here: " + 'https://github.com/rollup/plugins/tree/master/packages/babel#babelhelpers');
}
return unpackOptions(_objectSpread2(_objectSpread2({}, rest), {}, {
skipPreflightCheck,
babelHelpers: rest.babelHelpers || BUNDLED,
caller: _objectSpread2({
supportsStaticESM: true,
supportsDynamicImport: true,
supportsTopLevelAwait: true,
// todo: remove version checks for 1.20 - 1.25 when we bump peer deps
supportsExportNamespaceFrom: !rollupVersion.match(/^1\.2[0-5]\./)
}, rest.caller)
}));
};
const unpackOutputPluginOptions = (options, {
format
}) => unpackOptions(_objectSpread2(_objectSpread2({
configFile: false,
sourceType: format === 'es' ? 'module' : 'script'
}, options), {}, {
caller: _objectSpread2({
supportsStaticESM: format === 'es'
}, options.caller)
}));
function getOptionsWithOverrides(pluginOptions = {}, overrides = {}) {
if (!overrides.options) return {
customOptions: null,
pluginOptionsWithOverrides: pluginOptions
};
const overridden = overrides.options(pluginOptions);
if (typeof overridden.then === 'function') {
throw new Error(".options hook can't be asynchronous. It should return `{ customOptions, pluginsOptions }` synchronously.");
}
return {
customOptions: overridden.customOptions || null,
pluginOptionsWithOverrides: overridden.pluginOptions || pluginOptions
};
}
const returnObject = () => {
return {};
};
function createBabelInputPluginFactory(customCallback = returnObject) {
const overrides = customCallback(babel__namespace);
return pluginOptions => {
const {
customOptions,
pluginOptionsWithOverrides
} = getOptionsWithOverrides(pluginOptions, overrides);
let babelHelpers;
let babelOptions;
let filter;
let skipPreflightCheck;
return {
name: 'babel',
options() {
// todo: remove options hook and hoist declarations when version checks are removed
let exclude;
let include;
let extensions;
let customFilter;
var _unpackInputPluginOpt = unpackInputPluginOptions(pluginOptionsWithOverrides, this.meta.rollupVersion);
({
exclude,
extensions,
babelHelpers,
include,
filter: customFilter,
skipPreflightCheck
} = _unpackInputPluginOpt);
babelOptions = _objectWithoutProperties(_unpackInputPluginOpt, ["exclude", "extensions", "babelHelpers", "include", "filter", "skipPreflightCheck"]);
const extensionRegExp = new RegExp(`(${extensions.map(escapeRegExpCharacters).join('|')})$`);
if (customFilter && (include || exclude)) {
throw new Error('Could not handle include or exclude with custom filter together');
}
const userDefinedFilter = typeof customFilter === 'function' ? customFilter : pluginutils.createFilter(include, exclude);
filter = id => extensionRegExp.test(stripQuery(id).bareId) && userDefinedFilter(id);
return null;
},
resolveId(id) {
if (id !== HELPERS) {
return null;
}
return id;
},
load(id) {
if (id !== HELPERS) {
return null;
}
return babel__namespace.buildExternalHelpers(null, 'module');
},
transform(code, filename) {
if (!filter(filename)) return null;
if (filename === HELPERS) return null;
return transformCode(code, _objectSpread2(_objectSpread2({}, babelOptions), {}, {
filename
}), overrides, customOptions, this, async transformOptions => {
if (!skipPreflightCheck) {
await preflightCheck(this, babelHelpers, transformOptions);
}
return babelHelpers === BUNDLED ? addBabelPlugin(transformOptions, importHelperPlugin) : transformOptions;
});
}
};
};
}
function getRecommendedFormat(rollupFormat) {
switch (rollupFormat) {
case 'amd':
return 'amd';
case 'iife':
case 'umd':
return 'umd';
case 'system':
return 'systemjs';
default:
return '<module format>';
}
}
function createBabelOutputPluginFactory(customCallback = returnObject) {
const overrides = customCallback(babel__namespace);
return pluginOptions => {
const {
customOptions,
pluginOptionsWithOverrides
} = getOptionsWithOverrides(pluginOptions, overrides);
return {
name: 'babel',
renderStart(outputOptions) {
const {
extensions,
include,
exclude,
allowAllFormats
} = pluginOptionsWithOverrides;
if (extensions || include || exclude) {
warnOnce(this, 'The "include", "exclude" and "extensions" options are ignored when transforming the output.');
}
if (!allowAllFormats && outputOptions.format !== 'es' && outputOptions.format !== 'cjs') {
this.error(`Using Babel on the generated chunks is strongly discouraged for formats other than "esm" or "cjs" as it can easily break wrapper code and lead to accidentally created global variables. Instead, you should set "output.format" to "esm" and use Babel to transform to another format, e.g. by adding "presets: [['@babel/env', { modules: '${getRecommendedFormat(outputOptions.format)}' }]]" to your Babel options. If you still want to proceed, add "allowAllFormats: true" to your plugin options.`);
}
},
renderChunk(code, chunk, outputOptions) {
/* eslint-disable no-unused-vars */
const _unpackOutputPluginOp = unpackOutputPluginOptions(pluginOptionsWithOverrides, outputOptions),
babelOptions = _objectWithoutProperties(_unpackOutputPluginOp, ["allowAllFormats", "exclude", "extensions", "externalHelpers", "externalHelpersWhitelist", "include", "runtimeHelpers"]);
/* eslint-enable no-unused-vars */
return transformCode(code, babelOptions, overrides, customOptions, this);
}
};
};
} // export this for symmetry with output-related exports
const getBabelInputPlugin = createBabelInputPluginFactory();
const getBabelOutputPlugin = createBabelOutputPluginFactory();
exports.babel = getBabelInputPlugin;
exports.createBabelInputPluginFactory = createBabelInputPluginFactory;
exports.createBabelOutputPluginFactory = createBabelOutputPluginFactory;
exports["default"] = getBabelInputPlugin;
exports.getBabelInputPlugin = getBabelInputPlugin;
exports.getBabelOutputPlugin = getBabelOutputPlugin;

View File

@@ -0,0 +1,91 @@
{
"name": "@rollup/plugin-babel",
"version": "5.3.1",
"publishConfig": {
"access": "public"
},
"description": "Seamless integration between Rollup and Babel.",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/babel"
},
"author": "Rich Harris",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/babel#readme",
"bugs": "https://github.com/rollup/plugins/issues",
"main": "dist/index.js",
"module": "dist/index.es.js",
"engines": {
"node": ">= 10.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",
"prebuild": "del-cli dist",
"prerelease": "pnpm build",
"pretest": "pnpm build",
"release": "pnpm plugin:release --workspace-root -- --pkg $npm_package_name",
"test": "ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"
},
"files": [
"dist",
"types",
"README.md",
"LICENSE"
],
"keywords": [
"rollup",
"plugin",
"rollup-plugin",
"babel",
"es2015",
"es6"
],
"peerDependencies": {
"@babel/core": "^7.0.0",
"@types/babel__core": "^7.1.9",
"rollup": "^1.20.0||^2.0.0"
},
"peerDependenciesMeta": {
"@types/babel__core": {
"optional": true
}
},
"dependencies": {
"@babel/helper-module-imports": "^7.10.4",
"@rollup/pluginutils": "^3.1.0"
},
"devDependencies": {
"@babel/core": "^7.10.5",
"@babel/plugin-external-helpers": "^7.10.4",
"@babel/plugin-proposal-decorators": "^7.10.5",
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/plugin-transform-runtime": "^7.10.5",
"@babel/preset-env": "^7.10.4",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^10.0.0",
"@types/babel__core": "^7.1.9",
"rollup": "^2.67.3",
"source-map": "^0.7.3"
},
"types": "types/index.d.ts",
"ava": {
"babel": {
"compileEnhancements": false
},
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"contributors": [
"Bogdan Chadkin <trysound@yandex.ru>",
"Mateusz Burzyński <mateuszburzynski@gmail.com> (https://github.com/Andarist)"
]
}

View File

@@ -0,0 +1,133 @@
import { Plugin, PluginContext, TransformPluginContext } from 'rollup';
import { FilterPattern, CreateFilter } from '@rollup/pluginutils';
import * as babelCore from '@babel/core';
export interface RollupBabelInputPluginOptions
extends Omit<babelCore.TransformOptions, 'include' | 'exclude'> {
/**
* A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should operate on. When relying on Babel configuration files you cannot include files already excluded there.
* @default undefined;
*/
include?: FilterPattern;
/**
* A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore. When relaying on Babel configuration files you can only exclude additional files with this option, you cannot override what you have configured for Babel itself.
* @default undefined;
*/
exclude?: FilterPattern;
/**
* Custom filter function can be used to determine whether or not certain modules should be operated upon.
* Example:
* import { createFilter } from '@rollup/pluginutils';
* const include = 'include/**.js';
* const exclude = 'exclude/**.js';
* const filter = createFilter(include, exclude, {});
* @default undefined;
*/
filter?: ReturnType<CreateFilter>;
/**
* An array of file extensions that Babel should transpile. If you want to transpile TypeScript files with this plugin it's essential to include .ts and .tsx in this option.
* @default ['.js', '.jsx', '.es6', '.es', '.mjs']
*/
extensions?: string[];
/**
* It is recommended to configure this option explicitly (even if with its default value) so an informed decision is taken on how those babel helpers are inserted into the code.
* @default 'bundled'
*/
babelHelpers?: 'bundled' | 'runtime' | 'inline' | 'external';
/**
* Before transpiling your input files this plugin also transpile a short piece of code for each input file. This is used to validate some misconfiguration errors, but for sufficiently big projects it can slow your build times so if you are confident about your configuration then you might disable those checks with this option.
* @default false
*/
skipPreflightCheck?: boolean;
}
export interface RollupBabelOutputPluginOptions
extends Omit<babelCore.TransformOptions, 'include' | 'exclude'> {
/**
* Use with other formats than UMD/IIFE.
* @default false
*/
allowAllFormats?: boolean;
}
export type RollupBabelCustomInputPluginOptions = (
options: RollupBabelInputPluginOptions & Record<string, any>
) => {
customOptions: Record<string, any>;
pluginOptions: RollupBabelInputPluginOptions;
};
export type RollupBabelCustomOutputPluginOptions = (
options: RollupBabelOutputPluginOptions & Record<string, any>
) => {
customOptions: Record<string, any>;
pluginOptions: RollupBabelOutputPluginOptions;
};
export interface RollupBabelCustomPluginConfigOptions {
code: string;
customOptions: Record<string, any>;
}
export interface RollupBabelCustomPluginResultOptions {
code: string;
customOptions: Record<string, any>;
config: babelCore.PartialConfig;
transformOptions: babelCore.TransformOptions;
}
export type RollupBabelCustomInputPluginConfig = (
this: TransformPluginContext,
cfg: babelCore.PartialConfig,
options: RollupBabelCustomPluginConfigOptions
) => babelCore.TransformOptions;
export type RollupBabelCustomInputPluginResult = (
this: TransformPluginContext,
result: babelCore.BabelFileResult,
options: RollupBabelCustomPluginResultOptions
) => babelCore.BabelFileResult;
export type RollupBabelCustomOutputPluginConfig = (
this: PluginContext,
cfg: babelCore.PartialConfig,
options: RollupBabelCustomPluginConfigOptions
) => babelCore.TransformOptions;
export type RollupBabelCustomOutputPluginResult = (
this: PluginContext,
result: babelCore.BabelFileResult,
options: RollupBabelCustomPluginResultOptions
) => babelCore.BabelFileResult;
export interface RollupBabelCustomInputPlugin {
options?: RollupBabelCustomInputPluginOptions;
config?: RollupBabelCustomInputPluginConfig;
result?: RollupBabelCustomInputPluginResult;
}
export interface RollupBabelCustomOutputPlugin {
options?: RollupBabelCustomOutputPluginOptions;
config?: RollupBabelCustomOutputPluginConfig;
result?: RollupBabelCustomOutputPluginResult;
}
export type RollupBabelCustomInputPluginBuilder = (
babel: typeof babelCore
) => RollupBabelCustomInputPlugin;
export type RollupBabelCustomOutputPluginBuilder = (
babel: typeof babelCore
) => RollupBabelCustomOutputPlugin;
/**
* A Rollup plugin for seamless integration between Rollup and Babel.
* @param options - Plugin options.
* @returns Plugin instance.
*/
export function getBabelInputPlugin(options?: RollupBabelInputPluginOptions): Plugin;
export function getBabelOutputPlugin(options?: RollupBabelOutputPluginOptions): Plugin;
export function createBabelInputPluginFactory(
customCallback?: RollupBabelCustomInputPluginBuilder
): typeof getBabelInputPlugin;
export function createBabelOutputPluginFactory(
customCallback?: RollupBabelCustomOutputPluginBuilder
): typeof getBabelOutputPlugin;
/**
* A Rollup plugin for seamless integration between Rollup and Babel.
* @param options - Plugin options.
* @returns Plugin instance.
*/
export function babel(options?: RollupBabelInputPluginOptions): Plugin;
export default babel;