Fix bin/publish: copy docs.dist from project root

Fix bin/publish: use correct .env path for rspade_system
Fix bin/publish script: prevent grep exit code 1 from terminating script

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2025-10-21 02:08:33 +00:00
commit f6fac6c4bc
79758 changed files with 10547827 additions and 0 deletions

21
node_modules/@rollup/plugin-node-resolve/LICENSE generated vendored Executable 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.

296
node_modules/@rollup/plugin-node-resolve/README.md generated vendored Executable file
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)

1377
node_modules/@rollup/plugin-node-resolve/dist/cjs/index.js generated vendored Executable file

File diff suppressed because it is too large Load Diff

1370
node_modules/@rollup/plugin-node-resolve/dist/es/index.js generated vendored Executable file

File diff suppressed because it is too large Load Diff

View File

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

89
node_modules/@rollup/plugin-node-resolve/package.json generated vendored Executable file
View File

@@ -0,0 +1,89 @@
{
"name": "@rollup/plugin-node-resolve",
"version": "16.0.1",
"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"
}
}

122
node_modules/@rollup/plugin-node-resolve/types/index.d.ts generated vendored Executable file
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;

21
node_modules/@rollup/plugin-replace/LICENSE generated vendored Executable 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.

240
node_modules/@rollup/plugin-replace/README.md generated vendored Executable file
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: `['\\b', '\\b(?!\\.)']`
Specifies the boundaries around which strings will be replaced. By default, delimiters are [word boundaries](https://www.regular-expressions.info/wordboundaries.html) 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 `(?!\.)` boundary
- `typeof windowSmth` **will not** be replaced due to a `\b` boundary
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_.
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)

139
node_modules/@rollup/plugin-replace/dist/cjs/index.js generated vendored Executable file
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 = ['\\b', '\\b(?!\\.)'];
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

134
node_modules/@rollup/plugin-replace/dist/es/index.js generated vendored Executable file
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 = ['\\b', '\\b(?!\\.)'];
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

1
node_modules/@rollup/plugin-replace/dist/es/package.json generated vendored Executable file
View File

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

84
node_modules/@rollup/plugin-replace/package.json generated vendored Executable file
View File

@@ -0,0 +1,84 @@
{
"name": "@rollup/plugin-replace",
"version": "6.0.2",
"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"
}
}

127
node_modules/@rollup/plugin-replace/src/index.js generated vendored Executable file
View File

@@ -0,0 +1,127 @@
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 = ['\\b', '\\b(?!\\.)'], 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;
}
}

57
node_modules/@rollup/plugin-replace/types/index.d.ts generated vendored Executable file
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;

80
node_modules/@rollup/plugin-terser/README.md generated vendored Executable file
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)

232
node_modules/@rollup/plugin-terser/dist/cjs/index.js generated vendored Executable file
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

226
node_modules/@rollup/plugin-terser/dist/es/index.js generated vendored Executable file
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

1
node_modules/@rollup/plugin-terser/dist/es/package.json generated vendored Executable file
View File

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

74
node_modules/@rollup/plugin-terser/package.json generated vendored Executable file
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"
}

3
node_modules/@rollup/plugin-terser/src/constants.ts generated vendored Executable file
View File

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

8
node_modules/@rollup/plugin-terser/src/index.ts generated vendored Executable file
View File

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

105
node_modules/@rollup/plugin-terser/src/module.ts generated vendored Executable file
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;
}
};
}

45
node_modules/@rollup/plugin-terser/src/type.ts generated vendored Executable file
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;
}

128
node_modules/@rollup/plugin-terser/src/worker-pool.ts generated vendored Executable file
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)
});
}
}
}

58
node_modules/@rollup/plugin-terser/src/worker.ts generated vendored Executable file
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);
});
}

15
node_modules/@rollup/plugin-terser/types/index.d.ts generated vendored Executable file
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;

21
node_modules/@rollup/plugin-typescript/LICENSE generated vendored Executable 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.

349
node_modules/@rollup/plugin-typescript/README.md generated vendored Executable file
View File

@@ -0,0 +1,349 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-typescript
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-typescript
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-typescript
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-typescript
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-typescript
🍣 A Rollup plugin for seamless integration between Rollup and Typescript.
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v2.14.0+. This plugin also requires at least [TypeScript 3.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html).
## Install
Using npm:
```console
npm install @rollup/plugin-typescript --save-dev
```
Note that both `typescript` and `tslib` are peer dependencies of this plugin that need to be installed separately.
## Why?
See [@rollup/plugin-babel](https://github.com/rollup/plugins/tree/master/packages/babel).
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
// rollup.config.js
import typescript from '@rollup/plugin-typescript';
export default {
input: 'src/index.ts',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [typescript()]
};
```
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 loads any [`compilerOptions`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) from the `tsconfig.json` file by default. Passing options to the plugin directly overrides those options:
```js
...
export default {
input: './main.ts',
plugins: [
typescript({ compilerOptions: {lib: ["es5", "es6", "dom"], target: "es5"}})
]
}
```
The following options are unique to `@rollup/plugin-typescript`:
### `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 `.ts` and `.tsx` files are targeted.
### `filterRoot`
Type: `String` | `Boolean`<br>
Default: `rootDir` ?? `tsConfig.compilerOptions.rootDir` ?? `process.cwd()`
Optionally resolves the include and exclude 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.
By default, patterns resolve against the rootDir set in your TS config file.
This can fix plugin errors when parsing files outside the current working directory (process.cwd()).
### `tsconfig`
Type: `String` | `Boolean`<br>
Default: `true`
When set to false, ignores any options specified in the config file. If set to a string that corresponds to a file path, the specified file will be used as config file.
### `typescript`
Type: `import('typescript')`<br>
Default: _peer dependency_
Overrides the TypeScript module used for transpilation.
```js
typescript({
typescript: require('some-fork-of-typescript')
});
```
### `tslib`
Type: `String`<br>
Default: _peer dependency_
Overrides the injected TypeScript helpers with a custom version.
```js
typescript({
tslib: require.resolve('some-fork-of-tslib')
});
```
### `transformers`
Type: `{ [before | after | afterDeclarations]: TransformerFactory[] } | ((program: ts.Program) => ts.CustomTransformers)`<br>
Default: `undefined`
Allows registration of TypeScript custom transformers at any of the supported stages:
- **before**: transformers will execute before the TypeScript's own transformers on raw TypeScript files
- **after**: transformers will execute after the TypeScript transformers on transpiled code
- **afterDeclarations**: transformers will execute after declaration file generation allowing to modify existing declaration files
Supported transformer factories:
- all **built-in** TypeScript custom transformer factories:
- `import('typescript').TransformerFactory` annotated **TransformerFactory** bellow
- `import('typescript').CustomTransformerFactory` annotated **CustomTransformerFactory** bellow
- **ProgramTransformerFactory** represents a transformer factory allowing the resulting transformer to grab a reference to the **Program** instance
```js
{
type: 'program',
factory: (program: Program) => TransformerFactory | CustomTransformerFactory
}
```
- **TypeCheckerTransformerFactory** represents a transformer factory allowing the resulting transformer to grab a reference to the **TypeChecker** instance
```js
{
type: 'typeChecker',
factory: (typeChecker: TypeChecker) => TransformerFactory | CustomTransformerFactory
}
```
```js
typescript({
transformers: {
before: [
{
// Allow the transformer to get a Program reference in it's factory
type: 'program',
factory: (program) => {
return ProgramRequiringTransformerFactory(program);
}
},
{
type: 'typeChecker',
factory: (typeChecker) => {
// Allow the transformer to get a TypeChecker reference in it's factory
return TypeCheckerRequiringTransformerFactory(typeChecker);
}
}
],
after: [
// You can use normal transformers directly
require('custom-transformer-based-on-Context')
],
afterDeclarations: [
// Or even define in place
function fixDeclarationFactory(context) {
return function fixDeclaration(source) {
function visitor(node) {
// Do real work here
return ts.visitEachChild(node, visitor, context);
}
return ts.visitEachChild(source, visitor, context);
};
}
]
}
});
```
Alternatively, the transformers can be created inside a factory.
Supported transformer factories:
- all **built-in** TypeScript custom transformer factories:
- `import('typescript').TransformerFactory` annotated **TransformerFactory** bellow
- `import('typescript').CustomTransformerFactory` annotated **CustomTransformerFactory** bellow
The example above could be written like this:
```js
typescript({
transformers: function (program) {
return {
before: [
ProgramRequiringTransformerFactory(program),
TypeCheckerRequiringTransformerFactory(program.getTypeChecker())
],
after: [
// You can use normal transformers directly
require('custom-transformer-based-on-Context')
],
afterDeclarations: [
// Or even define in place
function fixDeclarationFactory(context) {
return function fixDeclaration(source) {
function visitor(node) {
// Do real work here
return ts.visitEachChild(node, visitor, context);
}
return ts.visitEachChild(source, visitor, context);
};
}
]
};
}
});
```
### `cacheDir`
Type: `String`<br>
Default: _.rollup.cache_
When compiling with `incremental` or `composite` options the plugin will
store compiled files in this folder. This allows the use of incremental
compilation.
```js
typescript({
cacheDir: '.rollup.tscache'
});
```
### `noForceEmit`
Type: `Boolean`<br>
Default: `false`
Earlier version of `@rollup/plugin-typescript` required that the `compilerOptions` `noEmit` and `emitDeclarationOnly` both false to guarantee that source code was fed into the next plugin/output. This is no longer true. This option disables the plugin forcing the values of those options and instead defers to the values set in `tsconfig.json`.
`noForceEmit` can be very useful if you use with `@rollup/plugin-babel` and `@babel/preset-typescript`. Having `@rollup/plugin-typescript` only do typechecking / declarations with `"emitDeclarationOnly": true` while deferring to `@rollup/plugin-babel` for transpilation can dramatically reduce `rollup` build times for large projects.
### Typescript compiler options
Some of Typescript's [CompilerOptions](https://www.typescriptlang.org/docs/handbook/compiler-options.html) affect how Rollup builds files.
#### `noEmitOnError`
Type: `Boolean`<br>
Default: `false`
If a type error is detected, the Rollup build is aborted when this option is set to true.
#### `files`, `include`, `exclude`
Type: `Array[...String]`<br>
Default: `[]`
Declaration files are automatically included if they are listed in the `files` field in your `tsconfig.json` file. Source files in these fields are ignored as Rollup's configuration is used instead.
#### Ignored options
These compiler options are ignored by Rollup:
- `noEmitHelpers`, `importHelpers`: The `tslib` helper module always must be used.
- `noEmit`, `emitDeclarationOnly`: Typescript needs to emit code for the plugin to work with.
- _Note: While this was true for early iterations of `@rollup/plugin-typescript`, it is no longer. To override this behavior, and defer to `tsconfig.json` for these options, see the [`noForceEmit`](#noForceEmit) option_
- `noResolve`: Preventing Typescript from resolving code may break compilation
### Importing CommonJS
Though it is not recommended, it is possible to configure this plugin to handle imports of CommonJS files from TypeScript. For this, you need to specify `CommonJS` as the module format and add [`@rollup/plugin-commonjs`](https://github.com/rollup/plugins/tree/master/packages/commonjs) to transpile the CommonJS output generated by TypeScript to ES Modules so that rollup can process it.
```js
// rollup.config.js
import typescript from '@rollup/plugin-typescript';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: './main.ts',
plugins: [
typescript({ compilerOptions: { module: 'CommonJS' } }),
commonjs({ extensions: ['.js', '.ts'] }) // the ".ts" extension is required
]
};
```
Note that this will often result in less optimal output.
### Preserving JSX output
Whenever choosing to preserve JSX output to be further consumed by another transform step via `tsconfig` `compilerOptions` by setting `jsx: 'preserve'` or [overriding options](#options), please bear in mind that, by itself, this plugin won't be able to preserve JSX output, usually failing with:
```sh
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
file.tsx (1:15)
1: export default <span>Foobar</span>
^
```
To prevent that, make sure to use the acorn plugin, namely `acorn-jsx`, which will make Rollup's parser acorn handle JSX tokens. (See https://rollupjs.org/guide/en/#acorninjectplugins)
After adding `acorn-jsx` plugin, your Rollup config would look like the following, correctly preserving your JSX output.
```js
import jsx from 'acorn-jsx';
import typescript from '@rollup/plugin-typescript';
export default {
// … other options …
acornInjectPlugins: [jsx()],
plugins: [typescript({ compilerOptions: { jsx: 'preserve' } })]
};
```
### Faster compiling
Previous versions of this plugin used Typescript's `transpileModule` API, which is faster but does not perform typechecking and does not support cross-file features like `const enum`s and emit-less types. If you want this behaviour, you can use [@rollup/plugin-sucrase](https://github.com/rollup/plugins/tree/master/packages/sucrase) instead.
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

937
node_modules/@rollup/plugin-typescript/dist/cjs/index.js generated vendored Executable file
View File

@@ -0,0 +1,937 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var path = require('path');
var pluginutils = require('@rollup/pluginutils');
var typescript$1 = require('typescript');
var url = require('url');
var resolve = require('resolve');
var fs = require('fs');
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopNamespaceDefault(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 path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
/**
* Create a format diagnostics host to use with the Typescript type checking APIs.
* Typescript hosts are used to represent the user's system,
* with an API for checking case sensitivity etc.
* @param compilerOptions Typescript compiler options. Affects functions such as `getNewLine`.
* @see https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
*/
function createFormattingHost(ts, compilerOptions) {
return {
/** Returns the compiler options for the project. */
getCompilationSettings: () => compilerOptions,
/** Returns the current working directory. */
getCurrentDirectory: () => process.cwd(),
/** Returns the string that corresponds with the selected `NewLineKind`. */
getNewLine() {
switch (compilerOptions.newLine) {
case ts.NewLineKind.CarriageReturnLineFeed:
return '\r\n';
case ts.NewLineKind.LineFeed:
return '\n';
default:
return ts.sys.newLine;
}
},
/** Returns a lower case name on case insensitive systems, otherwise the original name. */
getCanonicalFileName: (fileName) => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase()
};
}
/**
* Create a helper for resolving modules using Typescript.
* @param ts custom typescript implementation
* @param host Typescript host that extends {@link ModuleResolutionHost}
* @param filter
* with methods for sanitizing filenames and getting compiler options.
*/
function createModuleResolver(ts, host, filter) {
const compilerOptions = host.getCompilationSettings();
const cache = ts.createModuleResolutionCache(process.cwd(), host.getCanonicalFileName, compilerOptions);
const moduleHost = { ...ts.sys, ...host };
return (moduleName, containingFile, redirectedReference, mode) => {
const { resolvedModule } = ts.resolveModuleName(moduleName, containingFile, compilerOptions, moduleHost, cache, redirectedReference, mode);
/**
* If the module's path contains 'node_modules', ts considers it an external library and refuses to compile it,
* so we have to change the value of `isExternalLibraryImport` to false if it's true
* */
if ((resolvedModule === null || resolvedModule === void 0 ? void 0 : resolvedModule.isExternalLibraryImport) && filter(resolvedModule === null || resolvedModule === void 0 ? void 0 : resolvedModule.resolvedFileName)) {
resolvedModule.isExternalLibraryImport = false;
}
return resolvedModule;
};
}
// const resolveIdAsync = (file: string, opts: AsyncOpts) =>
// new Promise<string>((fulfil, reject) =>
// resolveId(file, opts, (err, contents) =>
// err || typeof contents === 'undefined' ? reject(err) : fulfil(contents)
// )
// );
const resolveId = (file, opts) => resolve.sync(file, opts);
/**
* Returns code asynchronously for the tslib helper library.
*/
const getTsLibPath = () => {
// Note: This isn't preferable, but we've no other way to test this bit. Removing the tslib devDep
// during the test run doesn't work due to the nature of the pnpm flat node_modules, and
// other workspace dependencies that depenend upon tslib.
try {
// eslint-disable-next-line no-underscore-dangle
return resolveId(process.env.__TSLIB_TEST_PATH__ || 'tslib/tslib.es6.js', {
// @ts-ignore import.meta.url is allowed because the Rollup plugin injects the correct module format
basedir: url.fileURLToPath(new URL('.', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('index.js', document.baseURI).href))))
});
}
catch (_) {
return null;
}
};
/**
* Separate the Rollup plugin options from the Typescript compiler options,
* and normalize the Rollup options.
* @returns Object with normalized options:
* - `filter`: Checks if a file should be included.
* - `tsconfig`: Path to a tsconfig, or directive to ignore tsconfig.
* - `compilerOptions`: Custom Typescript compiler options that override tsconfig.
* - `typescript`: Instance of Typescript library (possibly custom).
* - `tslib`: ESM code from the tslib helper library (possibly custom).
*/
const getPluginOptions = (options) => {
const { cacheDir, exclude, include, filterRoot, noForceEmit, transformers, tsconfig, tslib, typescript, outputToFilesystem, compilerOptions,
// previously was compilerOptions
...extra } = options;
return {
cacheDir,
include,
exclude,
filterRoot,
noForceEmit: noForceEmit || false,
tsconfig,
compilerOptions: { ...extra, ...compilerOptions },
typescript: typescript || typescript$1,
tslib: tslib || getTsLibPath(),
transformers,
outputToFilesystem
};
};
/**
* Converts a Typescript type error into an equivalent Rollup warning object.
*/
function diagnosticToWarning(ts, host, diagnostic) {
const pluginCode = `TS${diagnostic.code}`;
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
// Build a Rollup warning object from the diagnostics object.
const warning = {
pluginCode,
message: `@rollup/plugin-typescript ${pluginCode}: ${message}`
};
if (diagnostic.file) {
// Add information about the file location
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
warning.loc = {
column: character + 1,
line: line + 1,
file: diagnostic.file.fileName
};
if (host) {
// Extract a code frame from Typescript
const formatted = ts.formatDiagnosticsWithColorAndContext([diagnostic], host);
// Typescript only exposes this formatter as a string prefixed with the flattened message.
// We need to remove it here since Rollup treats the properties as separate parts.
let frame = formatted.slice(formatted.indexOf(message) + message.length);
const newLine = host.getNewLine();
if (frame.startsWith(newLine)) {
frame = frame.slice(frame.indexOf(newLine) + newLine.length);
}
warning.frame = frame;
}
}
return warning;
}
const DEFAULT_COMPILER_OPTIONS = {
module: 'esnext',
skipLibCheck: true
};
const OVERRIDABLE_EMIT_COMPILER_OPTIONS = {
noEmit: false,
emitDeclarationOnly: false
};
const FORCED_COMPILER_OPTIONS = {
// Always use tslib
noEmitHelpers: true,
importHelpers: true,
// Preventing Typescript from resolving code may break compilation
noResolve: false
};
/* eslint-disable no-param-reassign */
const DIRECTORY_PROPS = ['outDir', 'declarationDir'];
/**
* Mutates the compiler options to convert paths from relative to absolute.
* This should be used with compiler options passed through the Rollup plugin options,
* not those found from loading a tsconfig.json file.
* @param compilerOptions Compiler options to _mutate_.
* @param relativeTo Paths are resolved relative to this path.
*/
function makePathsAbsolute(compilerOptions, relativeTo) {
for (const pathProp of DIRECTORY_PROPS) {
if (compilerOptions[pathProp]) {
compilerOptions[pathProp] = path.resolve(relativeTo, compilerOptions[pathProp]);
}
}
}
/**
* Mutates the compiler options to normalize some values for Rollup.
* @param compilerOptions Compiler options to _mutate_.
* @returns True if the source map compiler option was not initially set.
*/
function normalizeCompilerOptions(ts, compilerOptions) {
let autoSetSourceMap = false;
if (compilerOptions.inlineSourceMap) {
// Force separate source map files for Rollup to work with.
compilerOptions.sourceMap = true;
compilerOptions.inlineSourceMap = false;
}
else if (typeof compilerOptions.sourceMap !== 'boolean') {
// Default to using source maps.
// If the plugin user sets sourceMap to false we keep that option.
compilerOptions.sourceMap = true;
// Using inlineSources to make sure typescript generate source content
// instead of source path.
compilerOptions.inlineSources = true;
autoSetSourceMap = true;
}
switch (compilerOptions.module) {
case ts.ModuleKind.ES2015:
case ts.ModuleKind.ESNext:
case ts.ModuleKind.Node16:
case ts.ModuleKind.NodeNext:
case ts.ModuleKind.CommonJS:
// OK module type
return autoSetSourceMap;
case ts.ModuleKind.None:
case ts.ModuleKind.AMD:
case ts.ModuleKind.UMD:
case ts.ModuleKind.System: {
// Invalid module type
const moduleType = ts.ModuleKind[compilerOptions.module];
throw new Error(`@rollup/plugin-typescript: The module kind should be 'ES2015', 'ESNext', 'node16' or 'nodenext', found: '${moduleType}'`);
}
default:
// Unknown or unspecified module type, force ESNext
compilerOptions.module = ts.ModuleKind.ESNext;
}
return autoSetSourceMap;
}
const { ModuleKind: ModuleKind$1, ModuleResolutionKind } = typescript$1;
function makeForcedCompilerOptions(noForceEmit) {
return { ...FORCED_COMPILER_OPTIONS, ...(noForceEmit ? {} : OVERRIDABLE_EMIT_COMPILER_OPTIONS) };
}
/**
* Finds the path to the tsconfig file relative to the current working directory.
* @param ts Custom typescript implementation
* @param relativePath Relative tsconfig path given by the user.
* If `false` is passed, then a null path is returned.
* @returns The absolute path, or null if the file does not exist.
*/
function getTsConfigPath(ts, relativePath) {
if (relativePath === false)
return null;
// Resolve path to file. `tsConfigOption` defaults to 'tsconfig.json'.
const tsConfigPath = path.resolve(process.cwd(), relativePath || 'tsconfig.json');
if (!ts.sys.fileExists(tsConfigPath)) {
if (relativePath) {
// If an explicit path was provided but no file was found, throw
throw new Error(`Could not find specified tsconfig.json at ${tsConfigPath}`);
}
else {
return null;
}
}
return tsConfigPath;
}
/**
* Tries to read the tsconfig file at `tsConfigPath`.
* @param ts Custom typescript implementation
* @param tsConfigPath Absolute path to tsconfig JSON file.
*/
function readTsConfigFile(ts, tsConfigPath) {
const { config, error } = ts.readConfigFile(tsConfigPath, (path) => fs.readFileSync(path, 'utf8'));
if (error) {
throw Object.assign(Error(), diagnosticToWarning(ts, null, error));
}
return config || {};
}
/**
* Returns true if any of the `compilerOptions` contain an enum value (i.e.: ts.ScriptKind) rather than a string.
* This indicates that the internal CompilerOptions type is used rather than the JsonCompilerOptions.
*/
function containsEnumOptions(compilerOptions) {
const enums = [
'module',
'target',
'jsx',
'moduleResolution',
'newLine'
];
return enums.some((prop) => prop in compilerOptions && typeof compilerOptions[prop] === 'number');
}
/**
* The module resolution kind is a function of the resolved `compilerOptions.module`.
* This needs to be set explicitly for `resolveModuleName` to select the correct resolution method
*/
function setModuleResolutionKind(parsedConfig) {
const moduleKind = parsedConfig.options.module;
// Fallback if `parsedConfig.options.moduleResolution` is not set
const moduleResolution = moduleKind === ModuleKind$1.Node16
? ModuleResolutionKind.Node16
: moduleKind === ModuleKind$1.NodeNext
? ModuleResolutionKind.NodeNext
: ModuleResolutionKind.NodeJs;
return {
...parsedConfig,
options: {
moduleResolution,
...parsedConfig.options
}
};
}
const configCache = new Map();
/**
* Parse the Typescript config to use with the plugin.
* @param ts Typescript library instance.
* @param tsconfig Path to the tsconfig file, or `false` to ignore the file.
* @param compilerOptions Options passed to the plugin directly for Typescript.
* @param noForceEmit Whether to respect emit options from {@link tsconfig}
*
* @returns Parsed tsconfig.json file with some important properties:
* - `options`: Parsed compiler options.
* - `fileNames` Type definition files that should be included in the build.
* - `errors`: Any errors from parsing the config file.
*/
function parseTypescriptConfig(ts, tsconfig, compilerOptions, noForceEmit) {
/* eslint-disable no-undefined */
const cwd = process.cwd();
makePathsAbsolute(compilerOptions, cwd);
let parsedConfig;
// Resolve path to file. If file is not found, pass undefined path to `parseJsonConfigFileContent`.
// eslint-disable-next-line no-undefined
const tsConfigPath = getTsConfigPath(ts, tsconfig) || undefined;
const tsConfigFile = tsConfigPath ? readTsConfigFile(ts, tsConfigPath) : {};
const basePath = tsConfigPath ? path.dirname(tsConfigPath) : cwd;
// If compilerOptions has enums, it represents an CompilerOptions object instead of parsed JSON.
// This determines where the data is passed to the parser.
if (containsEnumOptions(compilerOptions)) {
parsedConfig = setModuleResolutionKind(ts.parseJsonConfigFileContent({
...tsConfigFile,
compilerOptions: {
...DEFAULT_COMPILER_OPTIONS,
...tsConfigFile.compilerOptions
}
}, ts.sys, basePath, { ...compilerOptions, ...makeForcedCompilerOptions(noForceEmit) }, tsConfigPath, undefined, undefined, configCache));
}
else {
parsedConfig = setModuleResolutionKind(ts.parseJsonConfigFileContent({
...tsConfigFile,
compilerOptions: {
...DEFAULT_COMPILER_OPTIONS,
...tsConfigFile.compilerOptions,
...compilerOptions
}
}, ts.sys, basePath, makeForcedCompilerOptions(noForceEmit), tsConfigPath, undefined, undefined, configCache));
}
const autoSetSourceMap = normalizeCompilerOptions(ts, parsedConfig.options);
return {
...parsedConfig,
autoSetSourceMap
};
}
/**
* If errors are detected in the parsed options,
* display all of them as warnings then emit an error.
*/
function emitParsedOptionsErrors(ts, context, parsedOptions) {
if (parsedOptions.errors.length > 0) {
parsedOptions.errors.forEach((error) => context.warn(diagnosticToWarning(ts, null, error)));
context.error(`@rollup/plugin-typescript: Couldn't process compiler options`);
}
}
/**
* Validate that the `compilerOptions.sourceMap` option matches `outputOptions.sourcemap`.
* @param context Rollup plugin context used to emit warnings.
* @param compilerOptions Typescript compiler options.
* @param outputOptions Rollup output options.
* @param autoSetSourceMap True if the `compilerOptions.sourceMap` property was set to `true`
* by the plugin, not the user.
*/
function validateSourceMap(context, compilerOptions, outputOptions, autoSetSourceMap) {
if (compilerOptions.sourceMap && !outputOptions.sourcemap && !autoSetSourceMap) {
context.warn(`@rollup/plugin-typescript: Rollup 'sourcemap' option must be set to generate source maps.`);
}
else if (!compilerOptions.sourceMap && outputOptions.sourcemap) {
context.warn(`@rollup/plugin-typescript: Typescript 'sourceMap' compiler option must be set to generate source maps.`);
}
}
/**
* Validate that the out directory used by Typescript can be controlled by Rollup.
* @param context Rollup plugin context used to emit errors.
* @param compilerOptions Typescript compiler options.
* @param outputOptions Rollup output options.
*/
function validatePaths(context, compilerOptions, outputOptions) {
if (compilerOptions.out) {
context.error(`@rollup/plugin-typescript: Deprecated Typescript compiler option 'out' is not supported. Use 'outDir' instead.`);
}
else if (compilerOptions.outFile) {
context.error(`@rollup/plugin-typescript: Typescript compiler option 'outFile' is not supported. Use 'outDir' instead.`);
}
let outputDir = outputOptions.dir;
if (outputOptions.file) {
outputDir = path.dirname(outputOptions.file);
}
for (const dirProperty of DIRECTORY_PROPS) {
if (compilerOptions[dirProperty] && outputDir) {
// Checks if the given path lies within Rollup output dir
if (outputOptions.dir) {
const fromRollupDirToTs = path.relative(outputDir, compilerOptions[dirProperty]);
if (fromRollupDirToTs.startsWith('..')) {
context.error(`@rollup/plugin-typescript: Path of Typescript compiler option '${dirProperty}' must be located inside Rollup 'dir' option.`);
}
}
else if (dirProperty === 'outDir') {
const fromTsDirToRollup = path.relative(compilerOptions[dirProperty], outputDir);
if (fromTsDirToRollup.startsWith('..')) {
context.error(`@rollup/plugin-typescript: Path of Typescript compiler option '${dirProperty}' must be located inside the same directory as the Rollup 'file' option.`);
}
}
else {
const fromTsDirToRollup = path.relative(outputDir, compilerOptions[dirProperty]);
if (fromTsDirToRollup.startsWith('..')) {
context.error(`@rollup/plugin-typescript: Path of Typescript compiler option '${dirProperty}' must be located inside the same directory as the Rollup 'file' option.`);
}
}
}
}
if (compilerOptions.declaration || compilerOptions.declarationMap || compilerOptions.composite) {
if (DIRECTORY_PROPS.every((dirProperty) => !compilerOptions[dirProperty])) {
context.error(`@rollup/plugin-typescript: You are using one of Typescript's compiler options 'declaration', 'declarationMap' or 'composite'. ` +
`In this case 'outDir' or 'declarationDir' must be specified to generate declaration files.`);
}
}
}
/**
* Checks if the given OutputFile represents some code
*/
function isCodeOutputFile(name) {
return !isMapOutputFile(name) && !isDeclarationOutputFile(name);
}
/**
* Checks if the given OutputFile represents some source map
*/
function isMapOutputFile(name) {
return name.endsWith('.map');
}
/**
* Checks if the given OutputFile represents some TypeScript source map
*/
function isTypeScriptMapOutputFile(name) {
return name.endsWith('ts.map');
}
/**
* Checks if the given OutputFile represents some declaration
*/
function isDeclarationOutputFile(name) {
return /\.d\.[cm]?ts$/.test(name);
}
/**
* Returns the content of a filename either from the current
* typescript compiler instance or from the cached content.
* @param fileName The filename for the contents to retrieve
* @param emittedFiles The files emitted in the current typescript instance
* @param tsCache A cache to files cached by Typescript
*/
function getEmittedFile(fileName, emittedFiles, tsCache) {
let code;
if (fileName) {
if (emittedFiles.has(fileName)) {
code = emittedFiles.get(fileName);
}
else {
code = tsCache.getCached(fileName);
}
}
return code;
}
/**
* Finds the corresponding emitted Javascript files for a given Typescript file.
* @param id Path to the Typescript file.
* @param emittedFiles Map of file names to source code,
* containing files emitted by the Typescript compiler.
*/
function findTypescriptOutput(ts, parsedOptions, id, emittedFiles, tsCache) {
const emittedFileNames = ts.getOutputFileNames(parsedOptions, id, !ts.sys.useCaseSensitiveFileNames);
const codeFile = emittedFileNames.find(isCodeOutputFile);
const mapFile = emittedFileNames.find(isMapOutputFile);
return {
code: getEmittedFile(codeFile, emittedFiles, tsCache),
map: getEmittedFile(mapFile, emittedFiles, tsCache),
declarations: emittedFileNames.filter((name) => name !== codeFile && name !== mapFile)
};
}
function normalizePath(fileName) {
return fileName.split(path__namespace.win32.sep).join(path__namespace.posix.sep);
}
async function emitFile({ dir }, outputToFilesystem, context, filePath, fileSource) {
const normalizedFilePath = normalizePath(filePath);
// const normalizedPath = normalizePath(filePath);
// Note: `dir` can be a value like `dist` in which case, `path.relative` could result in a value
// of something like `'../.tsbuildinfo'. Our else-case below needs to mimic `path.relative`
// returning a dot-notated relative path, so the first if-then branch is entered into
const relativePath = dir ? path__namespace.relative(dir, normalizedFilePath) : '..';
// legal paths do not start with . nor .. : https://github.com/rollup/rollup/issues/3507#issuecomment-616495912
if (relativePath.startsWith('..')) {
if (outputToFilesystem == null) {
context.warn(`@rollup/plugin-typescript: outputToFilesystem option is defaulting to true.`);
}
if (outputToFilesystem !== false) {
await fs.promises.mkdir(path__namespace.dirname(normalizedFilePath), { recursive: true });
await fs.promises.writeFile(normalizedFilePath, fileSource);
}
}
else {
context.emitFile({
type: 'asset',
fileName: relativePath,
source: fileSource
});
}
}
// import { resolveIdAsync } from './tslib';
const { ModuleKind } = typescript$1;
const pluginName = '@rollup/plugin-typescript';
const moduleErrorMessage = `
${pluginName}: Rollup requires that TypeScript produces ES Modules. Unfortunately your configuration specifies a
"module" other than "esnext". Unless you know what you're doing, please change "module" to "esnext"
in the target tsconfig.json file or plugin options.`.replace(/\n/g, '');
const tsLibErrorMessage = `${pluginName}: Could not find module 'tslib', which is required by this plugin. Is it installed?`;
let undef;
const validModules = [
ModuleKind.ES2015,
ModuleKind.ES2020,
ModuleKind.ESNext,
ModuleKind.Node16,
ModuleKind.NodeNext,
undef
];
// eslint-disable-next-line import/prefer-default-export
const preflight = ({ config, context, inputPreserveModules, tslib }) => {
if (!validModules.includes(config.options.module)) {
context.warn(moduleErrorMessage);
}
if (!inputPreserveModules && tslib === null) {
context.error(tsLibErrorMessage);
}
};
// `Cannot compile modules into 'es6' when targeting 'ES5' or lower.`
const CANNOT_COMPILE_ESM = 1204;
/**
* Emit a Rollup warning or error for a Typescript type error.
*/
function emitDiagnostic(ts, context, host, diagnostic) {
if (diagnostic.code === CANNOT_COMPILE_ESM)
return;
const { noEmitOnError } = host.getCompilationSettings();
// Build a Rollup warning object from the diagnostics object.
const warning = diagnosticToWarning(ts, host, diagnostic);
// Errors are fatal. Otherwise emit warnings.
if (noEmitOnError && diagnostic.category === ts.DiagnosticCategory.Error) {
context.error(warning);
}
else {
context.warn(warning);
}
}
function buildDiagnosticReporter(ts, context, host) {
return function reportDiagnostics(diagnostic) {
emitDiagnostic(ts, context, host, diagnostic);
};
}
/**
* Merges all received custom transformer definitions into a single CustomTransformers object
*/
function mergeTransformers(builder, ...input) {
// List of all transformer stages
const transformerTypes = ['after', 'afterDeclarations', 'before'];
const accumulator = {
after: [],
afterDeclarations: [],
before: []
};
let program;
let typeChecker;
input.forEach((transformers) => {
if (!transformers) {
// Skip empty arguments lists
return;
}
transformerTypes.forEach((stage) => {
getTransformers(transformers[stage]).forEach((transformer) => {
if (!transformer) {
// Skip empty
return;
}
if ('type' in transformer) {
if (typeof transformer.factory === 'function') {
// Allow custom factories to grab the extra information required
program = program || builder.getProgram();
typeChecker = typeChecker || program.getTypeChecker();
let factory;
if (transformer.type === 'program') {
program = program || builder.getProgram();
factory = transformer.factory(program);
}
else {
program = program || builder.getProgram();
typeChecker = typeChecker || program.getTypeChecker();
factory = transformer.factory(typeChecker);
}
// Forward the requested reference to the custom transformer factory
if (factory) {
accumulator[stage].push(factory);
}
}
}
else {
// Add normal transformer factories as is
accumulator[stage].push(transformer);
}
});
});
});
return accumulator;
}
function getTransformers(transformers) {
return transformers || [];
}
const { DiagnosticCategory } = typescript$1;
// @see https://github.com/microsoft/TypeScript/blob/master/src/compiler/diagnosticMessages.json
// eslint-disable-next-line no-shadow
var DiagnosticCode;
(function (DiagnosticCode) {
DiagnosticCode[DiagnosticCode["FILE_CHANGE_DETECTED"] = 6032] = "FILE_CHANGE_DETECTED";
DiagnosticCode[DiagnosticCode["FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES"] = 6193] = "FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES";
DiagnosticCode[DiagnosticCode["FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES"] = 6194] = "FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES";
})(DiagnosticCode || (DiagnosticCode = {}));
function createDeferred(timeout) {
let promise;
let resolve = () => { };
if (timeout) {
promise = Promise.race([
new Promise((r) => setTimeout(r, timeout, true)),
new Promise((r) => (resolve = r))
]);
}
else {
promise = new Promise((r) => (resolve = r));
}
return { promise, resolve };
}
/**
* Typescript watch program helper to sync Typescript watch status with Rollup hooks.
*/
class WatchProgramHelper {
constructor() {
this._startDeferred = null;
this._finishDeferred = null;
}
watch(timeout = 1000) {
// Race watcher start promise against a timeout in case Typescript and Rollup change detection is not in sync.
this._startDeferred = createDeferred(timeout);
this._finishDeferred = createDeferred();
}
handleStatus(diagnostic) {
// Fullfil deferred promises by Typescript diagnostic message codes.
if (diagnostic.category === DiagnosticCategory.Message) {
switch (diagnostic.code) {
case DiagnosticCode.FILE_CHANGE_DETECTED:
this.resolveStart();
break;
case DiagnosticCode.FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES:
case DiagnosticCode.FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES:
this.resolveFinish();
break;
}
}
}
resolveStart() {
if (this._startDeferred) {
this._startDeferred.resolve(false);
this._startDeferred = null;
}
}
resolveFinish() {
if (this._finishDeferred) {
this._finishDeferred.resolve(false);
this._finishDeferred = null;
}
}
async wait() {
var _a;
if (this._startDeferred) {
const timeout = await this._startDeferred.promise;
// If there is no file change detected by Typescript skip deferred promises.
if (timeout) {
this._startDeferred = null;
this._finishDeferred = null;
}
await ((_a = this._finishDeferred) === null || _a === void 0 ? void 0 : _a.promise);
}
}
}
/**
* Create a language service host to use with the Typescript compiler & type checking APIs.
* Typescript hosts are used to represent the user's system,
* with an API for reading files, checking directories and case sensitivity etc.
* @see https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
*/
function createWatchHost(ts, context, { formatHost, parsedOptions, writeFile, status, resolveModule, transformers }) {
const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
const baseHost = ts.createWatchCompilerHost(parsedOptions.fileNames, parsedOptions.options, ts.sys, createProgram, buildDiagnosticReporter(ts, context, formatHost), status, parsedOptions.projectReferences);
let createdTransformers;
return {
...baseHost,
/** Override the created program so an in-memory emit is used */
afterProgramCreate(program) {
const origEmit = program.emit;
// eslint-disable-next-line no-param-reassign
program.emit = (targetSourceFile, _, cancellationToken, emitOnlyDtsFiles, customTransformers) => {
createdTransformers !== null && createdTransformers !== void 0 ? createdTransformers : (createdTransformers = typeof transformers === 'function'
? transformers(program.getProgram())
: mergeTransformers(program, transformers, customTransformers));
return origEmit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, createdTransformers);
};
return baseHost.afterProgramCreate(program);
},
/** Add helper to deal with module resolution */
resolveModuleNames(moduleNames, containingFile, _reusedNames, redirectedReference, _optionsOnlyWithNewerTsVersions, containingSourceFile) {
return moduleNames.map((moduleName, i) => {
var _a;
const mode = containingSourceFile
? (_a = ts.getModeForResolutionAtIndex) === null || _a === void 0 ? void 0 : _a.call(ts, containingSourceFile, i)
: undefined; // eslint-disable-line no-undefined
return resolveModule(moduleName, containingFile, redirectedReference, mode);
});
}
};
}
function createWatchProgram(ts, context, options) {
return ts.createWatchProgram(createWatchHost(ts, context, options));
}
/** Creates the folders needed given a path to a file to be saved*/
const createFileFolder = (filePath) => {
const folderPath = path.dirname(filePath);
fs.mkdirSync(folderPath, { recursive: true });
};
class TSCache {
constructor(cacheFolder = '.rollup.cache') {
this._cacheFolder = cacheFolder;
}
/** Returns the path to the cached file */
cachedFilename(fileName) {
return path.join(this._cacheFolder, fileName.replace(/^([a-zA-Z]+):/, '$1'));
}
/** Emits a file in the cache folder */
cacheCode(fileName, code) {
const cachedPath = this.cachedFilename(fileName);
createFileFolder(cachedPath);
fs.writeFileSync(cachedPath, code);
}
/** Checks if a file is in the cache */
isCached(fileName) {
return fs.existsSync(this.cachedFilename(fileName));
}
/** Read a file from the cache given the output name*/
getCached(fileName) {
let code;
if (this.isCached(fileName)) {
code = fs.readFileSync(this.cachedFilename(fileName), { encoding: 'utf-8' });
}
return code;
}
}
function typescript(options = {}) {
const { cacheDir, compilerOptions, exclude, filterRoot, include, outputToFilesystem, noForceEmit, transformers, tsconfig, tslib, typescript: ts } = getPluginOptions(options);
const tsCache = new TSCache(cacheDir);
const emittedFiles = new Map();
const watchProgramHelper = new WatchProgramHelper();
const parsedOptions = parseTypescriptConfig(ts, tsconfig, compilerOptions, noForceEmit);
const filter = pluginutils.createFilter(include || '{,**/}*.(cts|mts|ts|tsx)', exclude, {
resolve: filterRoot !== null && filterRoot !== void 0 ? filterRoot : parsedOptions.options.rootDir
});
parsedOptions.fileNames = parsedOptions.fileNames.filter(filter);
const formatHost = createFormattingHost(ts, parsedOptions.options);
const resolveModule = createModuleResolver(ts, formatHost, filter);
let program = null;
return {
name: 'typescript',
buildStart(rollupOptions) {
emitParsedOptionsErrors(ts, this, parsedOptions);
preflight({
config: parsedOptions,
context: this,
// TODO drop rollup@3 support and remove
inputPreserveModules: rollupOptions
.preserveModules,
tslib
});
// Fixes a memory leak https://github.com/rollup/plugins/issues/322
if (this.meta.watchMode !== true) {
// eslint-disable-next-line
program === null || program === void 0 ? void 0 : program.close();
program = null;
}
if (!program) {
program = createWatchProgram(ts, this, {
formatHost,
resolveModule,
parsedOptions,
writeFile(fileName, data) {
if (parsedOptions.options.composite || parsedOptions.options.incremental) {
tsCache.cacheCode(fileName, data);
}
emittedFiles.set(fileName, data);
},
status(diagnostic) {
watchProgramHelper.handleStatus(diagnostic);
},
transformers
});
}
},
watchChange(id) {
if (!filter(id))
return;
watchProgramHelper.watch();
},
buildEnd() {
if (this.meta.watchMode !== true) {
// ESLint doesn't understand optional chaining
// eslint-disable-next-line
program === null || program === void 0 ? void 0 : program.close();
}
},
renderStart(outputOptions) {
validateSourceMap(this, parsedOptions.options, outputOptions, parsedOptions.autoSetSourceMap);
validatePaths(this, parsedOptions.options, outputOptions);
},
resolveId(importee, importer) {
if (importee === 'tslib') {
return tslib;
}
if (!importer)
return null;
// Convert path from windows separators to posix separators
const containingFile = normalizePath(importer);
// when using node16 or nodenext module resolution, we need to tell ts if
// we are resolving to a commonjs or esnext module
const mode = typeof ts.getImpliedNodeFormatForFile === 'function'
? ts.getImpliedNodeFormatForFile(
// @ts-expect-error
containingFile, undefined, // eslint-disable-line no-undefined
{ ...ts.sys, ...formatHost }, parsedOptions.options)
: undefined; // eslint-disable-line no-undefined
// eslint-disable-next-line no-undefined
const resolved = resolveModule(importee, containingFile, undefined, mode);
if (resolved) {
if (/\.d\.[cm]?ts/.test(resolved.extension))
return null;
if (!filter(resolved.resolvedFileName))
return null;
return path__namespace.normalize(resolved.resolvedFileName);
}
return null;
},
async load(id) {
if (!filter(id))
return null;
this.addWatchFile(id);
await watchProgramHelper.wait();
const fileName = normalizePath(id);
if (!parsedOptions.fileNames.includes(fileName)) {
// Discovered new file that was not known when originally parsing the TypeScript config
parsedOptions.fileNames.push(fileName);
}
const output = findTypescriptOutput(ts, parsedOptions, id, emittedFiles, tsCache);
return output.code != null ? output : null;
},
async generateBundle(outputOptions) {
const declarationAndTypeScriptMapFiles = [...emittedFiles.keys()].filter((fileName) => isDeclarationOutputFile(fileName) || isTypeScriptMapOutputFile(fileName));
declarationAndTypeScriptMapFiles.forEach((id) => {
const code = getEmittedFile(id, emittedFiles, tsCache);
if (!code || !parsedOptions.options.declaration) {
return;
}
let baseDir;
if (outputOptions.dir) {
baseDir = outputOptions.dir;
}
else if (outputOptions.file) {
// the bundle output directory used by rollup when outputOptions.file is used instead of outputOptions.dir
baseDir = path__namespace.dirname(outputOptions.file);
}
if (!baseDir)
return;
this.emitFile({
type: 'asset',
fileName: normalizePath(path__namespace.relative(baseDir, id)),
source: code
});
});
const tsBuildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(parsedOptions.options);
if (tsBuildInfoPath) {
const tsBuildInfoSource = emittedFiles.get(tsBuildInfoPath);
// https://github.com/rollup/plugins/issues/681
if (tsBuildInfoSource) {
await emitFile(outputOptions, outputToFilesystem, this, tsBuildInfoPath, tsBuildInfoSource);
}
}
}
};
}
exports.default = typescript;
module.exports = Object.assign(exports.default, exports);
//# sourceMappingURL=index.js.map

913
node_modules/@rollup/plugin-typescript/dist/es/index.js generated vendored Executable file
View File

@@ -0,0 +1,913 @@
import * as path from 'path';
import path__default, { resolve as resolve$1, dirname, relative } from 'path';
import { createFilter } from '@rollup/pluginutils';
import typescript$1 from 'typescript';
import { fileURLToPath } from 'url';
import resolve from 'resolve';
import fs, { readFileSync, promises } from 'fs';
/**
* Create a format diagnostics host to use with the Typescript type checking APIs.
* Typescript hosts are used to represent the user's system,
* with an API for checking case sensitivity etc.
* @param compilerOptions Typescript compiler options. Affects functions such as `getNewLine`.
* @see https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
*/
function createFormattingHost(ts, compilerOptions) {
return {
/** Returns the compiler options for the project. */
getCompilationSettings: () => compilerOptions,
/** Returns the current working directory. */
getCurrentDirectory: () => process.cwd(),
/** Returns the string that corresponds with the selected `NewLineKind`. */
getNewLine() {
switch (compilerOptions.newLine) {
case ts.NewLineKind.CarriageReturnLineFeed:
return '\r\n';
case ts.NewLineKind.LineFeed:
return '\n';
default:
return ts.sys.newLine;
}
},
/** Returns a lower case name on case insensitive systems, otherwise the original name. */
getCanonicalFileName: (fileName) => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase()
};
}
/**
* Create a helper for resolving modules using Typescript.
* @param ts custom typescript implementation
* @param host Typescript host that extends {@link ModuleResolutionHost}
* @param filter
* with methods for sanitizing filenames and getting compiler options.
*/
function createModuleResolver(ts, host, filter) {
const compilerOptions = host.getCompilationSettings();
const cache = ts.createModuleResolutionCache(process.cwd(), host.getCanonicalFileName, compilerOptions);
const moduleHost = { ...ts.sys, ...host };
return (moduleName, containingFile, redirectedReference, mode) => {
const { resolvedModule } = ts.resolveModuleName(moduleName, containingFile, compilerOptions, moduleHost, cache, redirectedReference, mode);
/**
* If the module's path contains 'node_modules', ts considers it an external library and refuses to compile it,
* so we have to change the value of `isExternalLibraryImport` to false if it's true
* */
if ((resolvedModule === null || resolvedModule === void 0 ? void 0 : resolvedModule.isExternalLibraryImport) && filter(resolvedModule === null || resolvedModule === void 0 ? void 0 : resolvedModule.resolvedFileName)) {
resolvedModule.isExternalLibraryImport = false;
}
return resolvedModule;
};
}
// const resolveIdAsync = (file: string, opts: AsyncOpts) =>
// new Promise<string>((fulfil, reject) =>
// resolveId(file, opts, (err, contents) =>
// err || typeof contents === 'undefined' ? reject(err) : fulfil(contents)
// )
// );
const resolveId = (file, opts) => resolve.sync(file, opts);
/**
* Returns code asynchronously for the tslib helper library.
*/
const getTsLibPath = () => {
// Note: This isn't preferable, but we've no other way to test this bit. Removing the tslib devDep
// during the test run doesn't work due to the nature of the pnpm flat node_modules, and
// other workspace dependencies that depenend upon tslib.
try {
// eslint-disable-next-line no-underscore-dangle
return resolveId(process.env.__TSLIB_TEST_PATH__ || 'tslib/tslib.es6.js', {
// @ts-ignore import.meta.url is allowed because the Rollup plugin injects the correct module format
basedir: fileURLToPath(new URL('.', import.meta.url))
});
}
catch (_) {
return null;
}
};
/**
* Separate the Rollup plugin options from the Typescript compiler options,
* and normalize the Rollup options.
* @returns Object with normalized options:
* - `filter`: Checks if a file should be included.
* - `tsconfig`: Path to a tsconfig, or directive to ignore tsconfig.
* - `compilerOptions`: Custom Typescript compiler options that override tsconfig.
* - `typescript`: Instance of Typescript library (possibly custom).
* - `tslib`: ESM code from the tslib helper library (possibly custom).
*/
const getPluginOptions = (options) => {
const { cacheDir, exclude, include, filterRoot, noForceEmit, transformers, tsconfig, tslib, typescript, outputToFilesystem, compilerOptions,
// previously was compilerOptions
...extra } = options;
return {
cacheDir,
include,
exclude,
filterRoot,
noForceEmit: noForceEmit || false,
tsconfig,
compilerOptions: { ...extra, ...compilerOptions },
typescript: typescript || typescript$1,
tslib: tslib || getTsLibPath(),
transformers,
outputToFilesystem
};
};
/**
* Converts a Typescript type error into an equivalent Rollup warning object.
*/
function diagnosticToWarning(ts, host, diagnostic) {
const pluginCode = `TS${diagnostic.code}`;
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
// Build a Rollup warning object from the diagnostics object.
const warning = {
pluginCode,
message: `@rollup/plugin-typescript ${pluginCode}: ${message}`
};
if (diagnostic.file) {
// Add information about the file location
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
warning.loc = {
column: character + 1,
line: line + 1,
file: diagnostic.file.fileName
};
if (host) {
// Extract a code frame from Typescript
const formatted = ts.formatDiagnosticsWithColorAndContext([diagnostic], host);
// Typescript only exposes this formatter as a string prefixed with the flattened message.
// We need to remove it here since Rollup treats the properties as separate parts.
let frame = formatted.slice(formatted.indexOf(message) + message.length);
const newLine = host.getNewLine();
if (frame.startsWith(newLine)) {
frame = frame.slice(frame.indexOf(newLine) + newLine.length);
}
warning.frame = frame;
}
}
return warning;
}
const DEFAULT_COMPILER_OPTIONS = {
module: 'esnext',
skipLibCheck: true
};
const OVERRIDABLE_EMIT_COMPILER_OPTIONS = {
noEmit: false,
emitDeclarationOnly: false
};
const FORCED_COMPILER_OPTIONS = {
// Always use tslib
noEmitHelpers: true,
importHelpers: true,
// Preventing Typescript from resolving code may break compilation
noResolve: false
};
/* eslint-disable no-param-reassign */
const DIRECTORY_PROPS = ['outDir', 'declarationDir'];
/**
* Mutates the compiler options to convert paths from relative to absolute.
* This should be used with compiler options passed through the Rollup plugin options,
* not those found from loading a tsconfig.json file.
* @param compilerOptions Compiler options to _mutate_.
* @param relativeTo Paths are resolved relative to this path.
*/
function makePathsAbsolute(compilerOptions, relativeTo) {
for (const pathProp of DIRECTORY_PROPS) {
if (compilerOptions[pathProp]) {
compilerOptions[pathProp] = resolve$1(relativeTo, compilerOptions[pathProp]);
}
}
}
/**
* Mutates the compiler options to normalize some values for Rollup.
* @param compilerOptions Compiler options to _mutate_.
* @returns True if the source map compiler option was not initially set.
*/
function normalizeCompilerOptions(ts, compilerOptions) {
let autoSetSourceMap = false;
if (compilerOptions.inlineSourceMap) {
// Force separate source map files for Rollup to work with.
compilerOptions.sourceMap = true;
compilerOptions.inlineSourceMap = false;
}
else if (typeof compilerOptions.sourceMap !== 'boolean') {
// Default to using source maps.
// If the plugin user sets sourceMap to false we keep that option.
compilerOptions.sourceMap = true;
// Using inlineSources to make sure typescript generate source content
// instead of source path.
compilerOptions.inlineSources = true;
autoSetSourceMap = true;
}
switch (compilerOptions.module) {
case ts.ModuleKind.ES2015:
case ts.ModuleKind.ESNext:
case ts.ModuleKind.Node16:
case ts.ModuleKind.NodeNext:
case ts.ModuleKind.CommonJS:
// OK module type
return autoSetSourceMap;
case ts.ModuleKind.None:
case ts.ModuleKind.AMD:
case ts.ModuleKind.UMD:
case ts.ModuleKind.System: {
// Invalid module type
const moduleType = ts.ModuleKind[compilerOptions.module];
throw new Error(`@rollup/plugin-typescript: The module kind should be 'ES2015', 'ESNext', 'node16' or 'nodenext', found: '${moduleType}'`);
}
default:
// Unknown or unspecified module type, force ESNext
compilerOptions.module = ts.ModuleKind.ESNext;
}
return autoSetSourceMap;
}
const { ModuleKind: ModuleKind$1, ModuleResolutionKind } = typescript$1;
function makeForcedCompilerOptions(noForceEmit) {
return { ...FORCED_COMPILER_OPTIONS, ...(noForceEmit ? {} : OVERRIDABLE_EMIT_COMPILER_OPTIONS) };
}
/**
* Finds the path to the tsconfig file relative to the current working directory.
* @param ts Custom typescript implementation
* @param relativePath Relative tsconfig path given by the user.
* If `false` is passed, then a null path is returned.
* @returns The absolute path, or null if the file does not exist.
*/
function getTsConfigPath(ts, relativePath) {
if (relativePath === false)
return null;
// Resolve path to file. `tsConfigOption` defaults to 'tsconfig.json'.
const tsConfigPath = resolve$1(process.cwd(), relativePath || 'tsconfig.json');
if (!ts.sys.fileExists(tsConfigPath)) {
if (relativePath) {
// If an explicit path was provided but no file was found, throw
throw new Error(`Could not find specified tsconfig.json at ${tsConfigPath}`);
}
else {
return null;
}
}
return tsConfigPath;
}
/**
* Tries to read the tsconfig file at `tsConfigPath`.
* @param ts Custom typescript implementation
* @param tsConfigPath Absolute path to tsconfig JSON file.
*/
function readTsConfigFile(ts, tsConfigPath) {
const { config, error } = ts.readConfigFile(tsConfigPath, (path) => readFileSync(path, 'utf8'));
if (error) {
throw Object.assign(Error(), diagnosticToWarning(ts, null, error));
}
return config || {};
}
/**
* Returns true if any of the `compilerOptions` contain an enum value (i.e.: ts.ScriptKind) rather than a string.
* This indicates that the internal CompilerOptions type is used rather than the JsonCompilerOptions.
*/
function containsEnumOptions(compilerOptions) {
const enums = [
'module',
'target',
'jsx',
'moduleResolution',
'newLine'
];
return enums.some((prop) => prop in compilerOptions && typeof compilerOptions[prop] === 'number');
}
/**
* The module resolution kind is a function of the resolved `compilerOptions.module`.
* This needs to be set explicitly for `resolveModuleName` to select the correct resolution method
*/
function setModuleResolutionKind(parsedConfig) {
const moduleKind = parsedConfig.options.module;
// Fallback if `parsedConfig.options.moduleResolution` is not set
const moduleResolution = moduleKind === ModuleKind$1.Node16
? ModuleResolutionKind.Node16
: moduleKind === ModuleKind$1.NodeNext
? ModuleResolutionKind.NodeNext
: ModuleResolutionKind.NodeJs;
return {
...parsedConfig,
options: {
moduleResolution,
...parsedConfig.options
}
};
}
const configCache = new Map();
/**
* Parse the Typescript config to use with the plugin.
* @param ts Typescript library instance.
* @param tsconfig Path to the tsconfig file, or `false` to ignore the file.
* @param compilerOptions Options passed to the plugin directly for Typescript.
* @param noForceEmit Whether to respect emit options from {@link tsconfig}
*
* @returns Parsed tsconfig.json file with some important properties:
* - `options`: Parsed compiler options.
* - `fileNames` Type definition files that should be included in the build.
* - `errors`: Any errors from parsing the config file.
*/
function parseTypescriptConfig(ts, tsconfig, compilerOptions, noForceEmit) {
/* eslint-disable no-undefined */
const cwd = process.cwd();
makePathsAbsolute(compilerOptions, cwd);
let parsedConfig;
// Resolve path to file. If file is not found, pass undefined path to `parseJsonConfigFileContent`.
// eslint-disable-next-line no-undefined
const tsConfigPath = getTsConfigPath(ts, tsconfig) || undefined;
const tsConfigFile = tsConfigPath ? readTsConfigFile(ts, tsConfigPath) : {};
const basePath = tsConfigPath ? dirname(tsConfigPath) : cwd;
// If compilerOptions has enums, it represents an CompilerOptions object instead of parsed JSON.
// This determines where the data is passed to the parser.
if (containsEnumOptions(compilerOptions)) {
parsedConfig = setModuleResolutionKind(ts.parseJsonConfigFileContent({
...tsConfigFile,
compilerOptions: {
...DEFAULT_COMPILER_OPTIONS,
...tsConfigFile.compilerOptions
}
}, ts.sys, basePath, { ...compilerOptions, ...makeForcedCompilerOptions(noForceEmit) }, tsConfigPath, undefined, undefined, configCache));
}
else {
parsedConfig = setModuleResolutionKind(ts.parseJsonConfigFileContent({
...tsConfigFile,
compilerOptions: {
...DEFAULT_COMPILER_OPTIONS,
...tsConfigFile.compilerOptions,
...compilerOptions
}
}, ts.sys, basePath, makeForcedCompilerOptions(noForceEmit), tsConfigPath, undefined, undefined, configCache));
}
const autoSetSourceMap = normalizeCompilerOptions(ts, parsedConfig.options);
return {
...parsedConfig,
autoSetSourceMap
};
}
/**
* If errors are detected in the parsed options,
* display all of them as warnings then emit an error.
*/
function emitParsedOptionsErrors(ts, context, parsedOptions) {
if (parsedOptions.errors.length > 0) {
parsedOptions.errors.forEach((error) => context.warn(diagnosticToWarning(ts, null, error)));
context.error(`@rollup/plugin-typescript: Couldn't process compiler options`);
}
}
/**
* Validate that the `compilerOptions.sourceMap` option matches `outputOptions.sourcemap`.
* @param context Rollup plugin context used to emit warnings.
* @param compilerOptions Typescript compiler options.
* @param outputOptions Rollup output options.
* @param autoSetSourceMap True if the `compilerOptions.sourceMap` property was set to `true`
* by the plugin, not the user.
*/
function validateSourceMap(context, compilerOptions, outputOptions, autoSetSourceMap) {
if (compilerOptions.sourceMap && !outputOptions.sourcemap && !autoSetSourceMap) {
context.warn(`@rollup/plugin-typescript: Rollup 'sourcemap' option must be set to generate source maps.`);
}
else if (!compilerOptions.sourceMap && outputOptions.sourcemap) {
context.warn(`@rollup/plugin-typescript: Typescript 'sourceMap' compiler option must be set to generate source maps.`);
}
}
/**
* Validate that the out directory used by Typescript can be controlled by Rollup.
* @param context Rollup plugin context used to emit errors.
* @param compilerOptions Typescript compiler options.
* @param outputOptions Rollup output options.
*/
function validatePaths(context, compilerOptions, outputOptions) {
if (compilerOptions.out) {
context.error(`@rollup/plugin-typescript: Deprecated Typescript compiler option 'out' is not supported. Use 'outDir' instead.`);
}
else if (compilerOptions.outFile) {
context.error(`@rollup/plugin-typescript: Typescript compiler option 'outFile' is not supported. Use 'outDir' instead.`);
}
let outputDir = outputOptions.dir;
if (outputOptions.file) {
outputDir = dirname(outputOptions.file);
}
for (const dirProperty of DIRECTORY_PROPS) {
if (compilerOptions[dirProperty] && outputDir) {
// Checks if the given path lies within Rollup output dir
if (outputOptions.dir) {
const fromRollupDirToTs = relative(outputDir, compilerOptions[dirProperty]);
if (fromRollupDirToTs.startsWith('..')) {
context.error(`@rollup/plugin-typescript: Path of Typescript compiler option '${dirProperty}' must be located inside Rollup 'dir' option.`);
}
}
else if (dirProperty === 'outDir') {
const fromTsDirToRollup = relative(compilerOptions[dirProperty], outputDir);
if (fromTsDirToRollup.startsWith('..')) {
context.error(`@rollup/plugin-typescript: Path of Typescript compiler option '${dirProperty}' must be located inside the same directory as the Rollup 'file' option.`);
}
}
else {
const fromTsDirToRollup = relative(outputDir, compilerOptions[dirProperty]);
if (fromTsDirToRollup.startsWith('..')) {
context.error(`@rollup/plugin-typescript: Path of Typescript compiler option '${dirProperty}' must be located inside the same directory as the Rollup 'file' option.`);
}
}
}
}
if (compilerOptions.declaration || compilerOptions.declarationMap || compilerOptions.composite) {
if (DIRECTORY_PROPS.every((dirProperty) => !compilerOptions[dirProperty])) {
context.error(`@rollup/plugin-typescript: You are using one of Typescript's compiler options 'declaration', 'declarationMap' or 'composite'. ` +
`In this case 'outDir' or 'declarationDir' must be specified to generate declaration files.`);
}
}
}
/**
* Checks if the given OutputFile represents some code
*/
function isCodeOutputFile(name) {
return !isMapOutputFile(name) && !isDeclarationOutputFile(name);
}
/**
* Checks if the given OutputFile represents some source map
*/
function isMapOutputFile(name) {
return name.endsWith('.map');
}
/**
* Checks if the given OutputFile represents some TypeScript source map
*/
function isTypeScriptMapOutputFile(name) {
return name.endsWith('ts.map');
}
/**
* Checks if the given OutputFile represents some declaration
*/
function isDeclarationOutputFile(name) {
return /\.d\.[cm]?ts$/.test(name);
}
/**
* Returns the content of a filename either from the current
* typescript compiler instance or from the cached content.
* @param fileName The filename for the contents to retrieve
* @param emittedFiles The files emitted in the current typescript instance
* @param tsCache A cache to files cached by Typescript
*/
function getEmittedFile(fileName, emittedFiles, tsCache) {
let code;
if (fileName) {
if (emittedFiles.has(fileName)) {
code = emittedFiles.get(fileName);
}
else {
code = tsCache.getCached(fileName);
}
}
return code;
}
/**
* Finds the corresponding emitted Javascript files for a given Typescript file.
* @param id Path to the Typescript file.
* @param emittedFiles Map of file names to source code,
* containing files emitted by the Typescript compiler.
*/
function findTypescriptOutput(ts, parsedOptions, id, emittedFiles, tsCache) {
const emittedFileNames = ts.getOutputFileNames(parsedOptions, id, !ts.sys.useCaseSensitiveFileNames);
const codeFile = emittedFileNames.find(isCodeOutputFile);
const mapFile = emittedFileNames.find(isMapOutputFile);
return {
code: getEmittedFile(codeFile, emittedFiles, tsCache),
map: getEmittedFile(mapFile, emittedFiles, tsCache),
declarations: emittedFileNames.filter((name) => name !== codeFile && name !== mapFile)
};
}
function normalizePath(fileName) {
return fileName.split(path.win32.sep).join(path.posix.sep);
}
async function emitFile({ dir }, outputToFilesystem, context, filePath, fileSource) {
const normalizedFilePath = normalizePath(filePath);
// const normalizedPath = normalizePath(filePath);
// Note: `dir` can be a value like `dist` in which case, `path.relative` could result in a value
// of something like `'../.tsbuildinfo'. Our else-case below needs to mimic `path.relative`
// returning a dot-notated relative path, so the first if-then branch is entered into
const relativePath = dir ? path.relative(dir, normalizedFilePath) : '..';
// legal paths do not start with . nor .. : https://github.com/rollup/rollup/issues/3507#issuecomment-616495912
if (relativePath.startsWith('..')) {
if (outputToFilesystem == null) {
context.warn(`@rollup/plugin-typescript: outputToFilesystem option is defaulting to true.`);
}
if (outputToFilesystem !== false) {
await promises.mkdir(path.dirname(normalizedFilePath), { recursive: true });
await promises.writeFile(normalizedFilePath, fileSource);
}
}
else {
context.emitFile({
type: 'asset',
fileName: relativePath,
source: fileSource
});
}
}
// import { resolveIdAsync } from './tslib';
const { ModuleKind } = typescript$1;
const pluginName = '@rollup/plugin-typescript';
const moduleErrorMessage = `
${pluginName}: Rollup requires that TypeScript produces ES Modules. Unfortunately your configuration specifies a
"module" other than "esnext". Unless you know what you're doing, please change "module" to "esnext"
in the target tsconfig.json file or plugin options.`.replace(/\n/g, '');
const tsLibErrorMessage = `${pluginName}: Could not find module 'tslib', which is required by this plugin. Is it installed?`;
let undef;
const validModules = [
ModuleKind.ES2015,
ModuleKind.ES2020,
ModuleKind.ESNext,
ModuleKind.Node16,
ModuleKind.NodeNext,
undef
];
// eslint-disable-next-line import/prefer-default-export
const preflight = ({ config, context, inputPreserveModules, tslib }) => {
if (!validModules.includes(config.options.module)) {
context.warn(moduleErrorMessage);
}
if (!inputPreserveModules && tslib === null) {
context.error(tsLibErrorMessage);
}
};
// `Cannot compile modules into 'es6' when targeting 'ES5' or lower.`
const CANNOT_COMPILE_ESM = 1204;
/**
* Emit a Rollup warning or error for a Typescript type error.
*/
function emitDiagnostic(ts, context, host, diagnostic) {
if (diagnostic.code === CANNOT_COMPILE_ESM)
return;
const { noEmitOnError } = host.getCompilationSettings();
// Build a Rollup warning object from the diagnostics object.
const warning = diagnosticToWarning(ts, host, diagnostic);
// Errors are fatal. Otherwise emit warnings.
if (noEmitOnError && diagnostic.category === ts.DiagnosticCategory.Error) {
context.error(warning);
}
else {
context.warn(warning);
}
}
function buildDiagnosticReporter(ts, context, host) {
return function reportDiagnostics(diagnostic) {
emitDiagnostic(ts, context, host, diagnostic);
};
}
/**
* Merges all received custom transformer definitions into a single CustomTransformers object
*/
function mergeTransformers(builder, ...input) {
// List of all transformer stages
const transformerTypes = ['after', 'afterDeclarations', 'before'];
const accumulator = {
after: [],
afterDeclarations: [],
before: []
};
let program;
let typeChecker;
input.forEach((transformers) => {
if (!transformers) {
// Skip empty arguments lists
return;
}
transformerTypes.forEach((stage) => {
getTransformers(transformers[stage]).forEach((transformer) => {
if (!transformer) {
// Skip empty
return;
}
if ('type' in transformer) {
if (typeof transformer.factory === 'function') {
// Allow custom factories to grab the extra information required
program = program || builder.getProgram();
typeChecker = typeChecker || program.getTypeChecker();
let factory;
if (transformer.type === 'program') {
program = program || builder.getProgram();
factory = transformer.factory(program);
}
else {
program = program || builder.getProgram();
typeChecker = typeChecker || program.getTypeChecker();
factory = transformer.factory(typeChecker);
}
// Forward the requested reference to the custom transformer factory
if (factory) {
accumulator[stage].push(factory);
}
}
}
else {
// Add normal transformer factories as is
accumulator[stage].push(transformer);
}
});
});
});
return accumulator;
}
function getTransformers(transformers) {
return transformers || [];
}
const { DiagnosticCategory } = typescript$1;
// @see https://github.com/microsoft/TypeScript/blob/master/src/compiler/diagnosticMessages.json
// eslint-disable-next-line no-shadow
var DiagnosticCode;
(function (DiagnosticCode) {
DiagnosticCode[DiagnosticCode["FILE_CHANGE_DETECTED"] = 6032] = "FILE_CHANGE_DETECTED";
DiagnosticCode[DiagnosticCode["FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES"] = 6193] = "FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES";
DiagnosticCode[DiagnosticCode["FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES"] = 6194] = "FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES";
})(DiagnosticCode || (DiagnosticCode = {}));
function createDeferred(timeout) {
let promise;
let resolve = () => { };
if (timeout) {
promise = Promise.race([
new Promise((r) => setTimeout(r, timeout, true)),
new Promise((r) => (resolve = r))
]);
}
else {
promise = new Promise((r) => (resolve = r));
}
return { promise, resolve };
}
/**
* Typescript watch program helper to sync Typescript watch status with Rollup hooks.
*/
class WatchProgramHelper {
constructor() {
this._startDeferred = null;
this._finishDeferred = null;
}
watch(timeout = 1000) {
// Race watcher start promise against a timeout in case Typescript and Rollup change detection is not in sync.
this._startDeferred = createDeferred(timeout);
this._finishDeferred = createDeferred();
}
handleStatus(diagnostic) {
// Fullfil deferred promises by Typescript diagnostic message codes.
if (diagnostic.category === DiagnosticCategory.Message) {
switch (diagnostic.code) {
case DiagnosticCode.FILE_CHANGE_DETECTED:
this.resolveStart();
break;
case DiagnosticCode.FOUND_1_ERROR_WATCHING_FOR_FILE_CHANGES:
case DiagnosticCode.FOUND_N_ERRORS_WATCHING_FOR_FILE_CHANGES:
this.resolveFinish();
break;
}
}
}
resolveStart() {
if (this._startDeferred) {
this._startDeferred.resolve(false);
this._startDeferred = null;
}
}
resolveFinish() {
if (this._finishDeferred) {
this._finishDeferred.resolve(false);
this._finishDeferred = null;
}
}
async wait() {
var _a;
if (this._startDeferred) {
const timeout = await this._startDeferred.promise;
// If there is no file change detected by Typescript skip deferred promises.
if (timeout) {
this._startDeferred = null;
this._finishDeferred = null;
}
await ((_a = this._finishDeferred) === null || _a === void 0 ? void 0 : _a.promise);
}
}
}
/**
* Create a language service host to use with the Typescript compiler & type checking APIs.
* Typescript hosts are used to represent the user's system,
* with an API for reading files, checking directories and case sensitivity etc.
* @see https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API
*/
function createWatchHost(ts, context, { formatHost, parsedOptions, writeFile, status, resolveModule, transformers }) {
const createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram;
const baseHost = ts.createWatchCompilerHost(parsedOptions.fileNames, parsedOptions.options, ts.sys, createProgram, buildDiagnosticReporter(ts, context, formatHost), status, parsedOptions.projectReferences);
let createdTransformers;
return {
...baseHost,
/** Override the created program so an in-memory emit is used */
afterProgramCreate(program) {
const origEmit = program.emit;
// eslint-disable-next-line no-param-reassign
program.emit = (targetSourceFile, _, cancellationToken, emitOnlyDtsFiles, customTransformers) => {
createdTransformers !== null && createdTransformers !== void 0 ? createdTransformers : (createdTransformers = typeof transformers === 'function'
? transformers(program.getProgram())
: mergeTransformers(program, transformers, customTransformers));
return origEmit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, createdTransformers);
};
return baseHost.afterProgramCreate(program);
},
/** Add helper to deal with module resolution */
resolveModuleNames(moduleNames, containingFile, _reusedNames, redirectedReference, _optionsOnlyWithNewerTsVersions, containingSourceFile) {
return moduleNames.map((moduleName, i) => {
var _a;
const mode = containingSourceFile
? (_a = ts.getModeForResolutionAtIndex) === null || _a === void 0 ? void 0 : _a.call(ts, containingSourceFile, i)
: undefined; // eslint-disable-line no-undefined
return resolveModule(moduleName, containingFile, redirectedReference, mode);
});
}
};
}
function createWatchProgram(ts, context, options) {
return ts.createWatchProgram(createWatchHost(ts, context, options));
}
/** Creates the folders needed given a path to a file to be saved*/
const createFileFolder = (filePath) => {
const folderPath = path__default.dirname(filePath);
fs.mkdirSync(folderPath, { recursive: true });
};
class TSCache {
constructor(cacheFolder = '.rollup.cache') {
this._cacheFolder = cacheFolder;
}
/** Returns the path to the cached file */
cachedFilename(fileName) {
return path__default.join(this._cacheFolder, fileName.replace(/^([a-zA-Z]+):/, '$1'));
}
/** Emits a file in the cache folder */
cacheCode(fileName, code) {
const cachedPath = this.cachedFilename(fileName);
createFileFolder(cachedPath);
fs.writeFileSync(cachedPath, code);
}
/** Checks if a file is in the cache */
isCached(fileName) {
return fs.existsSync(this.cachedFilename(fileName));
}
/** Read a file from the cache given the output name*/
getCached(fileName) {
let code;
if (this.isCached(fileName)) {
code = fs.readFileSync(this.cachedFilename(fileName), { encoding: 'utf-8' });
}
return code;
}
}
function typescript(options = {}) {
const { cacheDir, compilerOptions, exclude, filterRoot, include, outputToFilesystem, noForceEmit, transformers, tsconfig, tslib, typescript: ts } = getPluginOptions(options);
const tsCache = new TSCache(cacheDir);
const emittedFiles = new Map();
const watchProgramHelper = new WatchProgramHelper();
const parsedOptions = parseTypescriptConfig(ts, tsconfig, compilerOptions, noForceEmit);
const filter = createFilter(include || '{,**/}*.(cts|mts|ts|tsx)', exclude, {
resolve: filterRoot !== null && filterRoot !== void 0 ? filterRoot : parsedOptions.options.rootDir
});
parsedOptions.fileNames = parsedOptions.fileNames.filter(filter);
const formatHost = createFormattingHost(ts, parsedOptions.options);
const resolveModule = createModuleResolver(ts, formatHost, filter);
let program = null;
return {
name: 'typescript',
buildStart(rollupOptions) {
emitParsedOptionsErrors(ts, this, parsedOptions);
preflight({
config: parsedOptions,
context: this,
// TODO drop rollup@3 support and remove
inputPreserveModules: rollupOptions
.preserveModules,
tslib
});
// Fixes a memory leak https://github.com/rollup/plugins/issues/322
if (this.meta.watchMode !== true) {
// eslint-disable-next-line
program === null || program === void 0 ? void 0 : program.close();
program = null;
}
if (!program) {
program = createWatchProgram(ts, this, {
formatHost,
resolveModule,
parsedOptions,
writeFile(fileName, data) {
if (parsedOptions.options.composite || parsedOptions.options.incremental) {
tsCache.cacheCode(fileName, data);
}
emittedFiles.set(fileName, data);
},
status(diagnostic) {
watchProgramHelper.handleStatus(diagnostic);
},
transformers
});
}
},
watchChange(id) {
if (!filter(id))
return;
watchProgramHelper.watch();
},
buildEnd() {
if (this.meta.watchMode !== true) {
// ESLint doesn't understand optional chaining
// eslint-disable-next-line
program === null || program === void 0 ? void 0 : program.close();
}
},
renderStart(outputOptions) {
validateSourceMap(this, parsedOptions.options, outputOptions, parsedOptions.autoSetSourceMap);
validatePaths(this, parsedOptions.options, outputOptions);
},
resolveId(importee, importer) {
if (importee === 'tslib') {
return tslib;
}
if (!importer)
return null;
// Convert path from windows separators to posix separators
const containingFile = normalizePath(importer);
// when using node16 or nodenext module resolution, we need to tell ts if
// we are resolving to a commonjs or esnext module
const mode = typeof ts.getImpliedNodeFormatForFile === 'function'
? ts.getImpliedNodeFormatForFile(
// @ts-expect-error
containingFile, undefined, // eslint-disable-line no-undefined
{ ...ts.sys, ...formatHost }, parsedOptions.options)
: undefined; // eslint-disable-line no-undefined
// eslint-disable-next-line no-undefined
const resolved = resolveModule(importee, containingFile, undefined, mode);
if (resolved) {
if (/\.d\.[cm]?ts/.test(resolved.extension))
return null;
if (!filter(resolved.resolvedFileName))
return null;
return path.normalize(resolved.resolvedFileName);
}
return null;
},
async load(id) {
if (!filter(id))
return null;
this.addWatchFile(id);
await watchProgramHelper.wait();
const fileName = normalizePath(id);
if (!parsedOptions.fileNames.includes(fileName)) {
// Discovered new file that was not known when originally parsing the TypeScript config
parsedOptions.fileNames.push(fileName);
}
const output = findTypescriptOutput(ts, parsedOptions, id, emittedFiles, tsCache);
return output.code != null ? output : null;
},
async generateBundle(outputOptions) {
const declarationAndTypeScriptMapFiles = [...emittedFiles.keys()].filter((fileName) => isDeclarationOutputFile(fileName) || isTypeScriptMapOutputFile(fileName));
declarationAndTypeScriptMapFiles.forEach((id) => {
const code = getEmittedFile(id, emittedFiles, tsCache);
if (!code || !parsedOptions.options.declaration) {
return;
}
let baseDir;
if (outputOptions.dir) {
baseDir = outputOptions.dir;
}
else if (outputOptions.file) {
// the bundle output directory used by rollup when outputOptions.file is used instead of outputOptions.dir
baseDir = path.dirname(outputOptions.file);
}
if (!baseDir)
return;
this.emitFile({
type: 'asset',
fileName: normalizePath(path.relative(baseDir, id)),
source: code
});
});
const tsBuildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(parsedOptions.options);
if (tsBuildInfoPath) {
const tsBuildInfoSource = emittedFiles.get(tsBuildInfoPath);
// https://github.com/rollup/plugins/issues/681
if (tsBuildInfoSource) {
await emitFile(outputOptions, outputToFilesystem, this, tsBuildInfoPath, tsBuildInfoSource);
}
}
}
};
}
export { typescript as default };
//# sourceMappingURL=index.js.map

View File

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

79
node_modules/@rollup/plugin-typescript/package.json generated vendored Executable file
View File

@@ -0,0 +1,79 @@
{
"name": "@rollup/plugin-typescript",
"version": "12.1.4",
"publishConfig": {
"access": "public"
},
"description": "Seamless integration between Rollup and TypeScript.",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/typescript"
},
"author": "Oskar Segersvärd",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/typescript/#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",
"typescript",
"es2015"
],
"peerDependencies": {
"rollup": "^2.14.0||^3.0.0||^4.0.0",
"tslib": "*",
"typescript": ">=3.7.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
},
"tslib": {
"optional": true
}
},
"dependencies": {
"@rollup/pluginutils": "^5.1.0",
"resolve": "^1.22.1"
},
"devDependencies": {
"@rollup/plugin-buble": "^1.0.0",
"@rollup/plugin-commonjs": "^23.0.0",
"@types/node": "^14.18.30",
"@types/resolve": "^1.20.2",
"buble": "^0.20.0",
"rollup": "^4.0.0-24",
"typescript": "^4.8.3"
},
"types": "./types/index.d.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 --serial",
"prebuild": "del-cli dist",
"prerelease": "pnpm build",
"pretest": "pnpm build",
"release": "pnpm --workspace-root package:release $(pwd)",
"test": "ava",
"test:ts": "tsc --noEmit"
}
}

115
node_modules/@rollup/plugin-typescript/types/index.d.ts generated vendored Executable file
View File

@@ -0,0 +1,115 @@
/* eslint-disable no-use-before-define */
import type _typescript from 'typescript';
import type { FilterPattern } from '@rollup/pluginutils';
import type { Plugin } from 'rollup';
import type {
CompilerOptions,
CompilerOptionsValue,
CustomTransformers,
Program,
TsConfigSourceFile,
TypeChecker
} from 'typescript';
type ElementType<T extends Array<any> | undefined> = T extends (infer U)[] ? U : never;
export type TransformerStage = keyof CustomTransformers;
type StagedTransformerFactory<T extends TransformerStage> = ElementType<CustomTransformers[T]>;
type TransformerFactory<T extends TransformerStage> =
| StagedTransformerFactory<T>
| ProgramTransformerFactory<T>
| TypeCheckerTransformerFactory<T>;
export type CustomTransformerFactories = {
[stage in TransformerStage]?: Array<TransformerFactory<stage>>;
};
interface ProgramTransformerFactory<T extends TransformerStage> {
type: 'program';
factory(program: Program): StagedTransformerFactory<T>;
}
interface TypeCheckerTransformerFactory<T extends TransformerStage> {
type: 'typeChecker';
factory(typeChecker: TypeChecker): StagedTransformerFactory<T>;
}
export interface RollupTypescriptPluginOptions {
/**
* If using incremental this is the folder where the cached
* files will be created and kept for Typescript incremental
* compilation.
*/
cacheDir?: string;
/**
* Determine which files are transpiled by Typescript (all `.ts` and
* `.tsx` files by default).
*/
include?: FilterPattern;
/**
* Determine which files are ignored by Typescript
*/
exclude?: FilterPattern;
/**
* Sets the `resolve` value for the underlying filter function. If not set will use the `rootDir` property
* @see {@link https://github.com/rollup/plugins/tree/master/packages/pluginutils#createfilter} @rollup/pluginutils `createFilter`
*/
filterRoot?: string | false;
/**
* When set to false, ignores any options specified in the config file.
* If set to a string that corresponds to a file path, the specified file
* will be used as config file.
*/
tsconfig?: string | false;
/**
* Overrides TypeScript used for transpilation
*/
typescript?: typeof _typescript;
/**
* Overrides the injected TypeScript helpers with a custom version.
*/
tslib?: Promise<string> | string;
/**
* TypeScript custom transformers
*/
transformers?: CustomTransformerFactories | ((program: Program) => CustomTransformers);
/**
* When set to false, force non-cached files to always be emitted in the output directory.output
* If not set, will default to true with a warning.
*/
outputToFilesystem?: boolean;
/**
* Pass additional compiler options to the plugin.
*/
compilerOptions?: PartialCompilerOptions;
/**
* Override force setting of `noEmit` and `emitDeclarationOnly` and use what is defined in `tsconfig.json`
*/
noForceEmit?: boolean;
}
export interface FlexibleCompilerOptions extends CompilerOptions {
[option: string]: CompilerOptionsValue | TsConfigSourceFile | undefined | any;
}
/** Properties of `CompilerOptions` that are normally enums */
export type EnumCompilerOptions = 'module' | 'moduleResolution' | 'newLine' | 'jsx' | 'target';
/** JSON representation of Typescript compiler options */
export type JsonCompilerOptions = Omit<FlexibleCompilerOptions, EnumCompilerOptions> &
Record<EnumCompilerOptions, string>;
/** Compiler options set by the plugin user. */
export type PartialCompilerOptions =
| Partial<FlexibleCompilerOptions>
| Partial<JsonCompilerOptions>;
export type RollupTypescriptOptions = RollupTypescriptPluginOptions & PartialCompilerOptions;
/**
* Seamless integration between Rollup and Typescript.
*/
export default function typescript(options?: RollupTypescriptOptions): Plugin;

21
node_modules/@rollup/pluginutils/LICENSE generated vendored Executable 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.

313
node_modules/@rollup/pluginutils/README.md generated vendored Executable file
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)

407
node_modules/@rollup/pluginutils/dist/cjs/index.js generated vendored Executable file
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

392
node_modules/@rollup/pluginutils/dist/es/index.js generated vendored Executable file
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

1
node_modules/@rollup/pluginutils/dist/es/package.json generated vendored Executable file
View File

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

99
node_modules/@rollup/pluginutils/package.json generated vendored Executable file
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"
}
}

125
node_modules/@rollup/pluginutils/types/index.d.ts generated vendored Executable file
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;

3
node_modules/@rollup/rollup-linux-x64-gnu/README.md generated vendored Executable file
View File

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

22
node_modules/@rollup/rollup-linux-x64-gnu/package.json generated vendored Executable file
View File

@@ -0,0 +1,22 @@
{
"name": "@rollup/rollup-linux-x64-gnu",
"version": "4.50.2",
"os": [
"linux"
],
"cpu": [
"x64"
],
"files": [
"rollup.linux-x64-gnu.node"
],
"description": "Native bindings for Rollup",
"author": "Lukas Taegert-Atkinson",
"homepage": "https://rollupjs.org/",
"license": "MIT",
"repository": "rollup/rollup",
"libc": [
"glibc"
],
"main": "./rollup.linux-x64-gnu.node"
}

Binary file not shown.

3
node_modules/@rollup/rollup-linux-x64-musl/README.md generated vendored Executable file
View File

@@ -0,0 +1,3 @@
# `@rollup/rollup-linux-x64-musl`
This is the **x86_64-unknown-linux-musl** binary for `rollup`

22
node_modules/@rollup/rollup-linux-x64-musl/package.json generated vendored Executable file
View File

@@ -0,0 +1,22 @@
{
"name": "@rollup/rollup-linux-x64-musl",
"version": "4.50.2",
"os": [
"linux"
],
"cpu": [
"x64"
],
"files": [
"rollup.linux-x64-musl.node"
],
"description": "Native bindings for Rollup",
"author": "Lukas Taegert-Atkinson",
"homepage": "https://rollupjs.org/",
"license": "MIT",
"repository": "rollup/rollup",
"libc": [
"musl"
],
"main": "./rollup.linux-x64-musl.node"
}

Binary file not shown.

3
node_modules/@rollup/rollup-win32-x64-msvc/README.md generated vendored Executable file
View File

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

19
node_modules/@rollup/rollup-win32-x64-msvc/package.json generated vendored Executable file
View File

@@ -0,0 +1,19 @@
{
"name": "@rollup/rollup-win32-x64-msvc",
"version": "4.50.2",
"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": "rollup/rollup",
"main": "./rollup.win32-x64-msvc.node"
}

Binary file not shown.