first commit

This commit is contained in:
DanielRamirezGe
2020-01-14 20:43:08 -06:00
parent 3557894f7f
commit 5eecfbf6cd
26326 changed files with 2434803 additions and 0 deletions
+327
View File
@@ -0,0 +1,327 @@
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### [5.0.5](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v5.0.4...v5.0.5) (2019-11-06)
### Performance Improvements
* improvements for webpack@5
### [5.0.4](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v5.0.3...v5.0.4) (2019-07-26)
### Bug Fixes
* use posix separator for emitting assets ([#392](https://github.com/webpack-contrib/copy-webpack-plugin/issues/392)) ([7f08be6](https://github.com/webpack-contrib/copy-webpack-plugin/commit/7f08be6))
<a name="5.0.3"></a>
## [5.0.3](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v5.0.2...v5.0.3) (2019-04-24)
### Bug Fixes
* alone `[N]` interpolation in `to` option ([#375](https://github.com/webpack-contrib/copy-webpack-plugin/issues/375)) ([70917b7](https://github.com/webpack-contrib/copy-webpack-plugin/commit/70917b7))
<a name="5.0.2"></a>
## [5.0.2](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v5.0.1...v5.0.2) (2019-03-22)
### Bug Fixes
* add fallback to transform cache directory ([#361](https://github.com/webpack-contrib/copy-webpack-plugin/issues/361)) ([05963eb](https://github.com/webpack-contrib/copy-webpack-plugin/commit/05963eb))
* better determinate template in `to` option ([#363](https://github.com/webpack-contrib/copy-webpack-plugin/issues/363)) ([52f8be6](https://github.com/webpack-contrib/copy-webpack-plugin/commit/52f8be6))
* emit errors instead throw ([#362](https://github.com/webpack-contrib/copy-webpack-plugin/issues/362)) ([3946473](https://github.com/webpack-contrib/copy-webpack-plugin/commit/3946473))
* watch on windows ([#359](https://github.com/webpack-contrib/copy-webpack-plugin/issues/359)) ([eaf4306](https://github.com/webpack-contrib/copy-webpack-plugin/commit/eaf4306))
### Performance Improvements
* avoid extra call `stat` for file ([#365](https://github.com/webpack-contrib/copy-webpack-plugin/issues/365)) ([ae2258f](https://github.com/webpack-contrib/copy-webpack-plugin/commit/ae2258f))
<a name="5.0.1"></a>
## [5.0.1](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.6.0...v5.0.1) (2019-03-11)
### Bug Fixes
* respect base of `glob` for context dependencies ([#352](https://github.com/webpack-contrib/copy-webpack-plugin/issues/352)) ([5b407f1](https://github.com/webpack-contrib/copy-webpack-plugin/commit/5b407f1))
<a name="5.0.0"></a>
# [5.0.0](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.6.0...v5.0.0) (2019-02-20)
### Bug Fixes
* copy only modified files when you use patterns with difference `to` and same `context` ([#341](https://github.com/webpack-contrib/copy-webpack-plugin/issues/341)) ([e808aa2](https://github.com/webpack-contrib/copy-webpack-plugin/commit/e808aa2))
* handle `[contenthash]` as template ([#328](https://github.com/webpack-contrib/copy-webpack-plugin/issues/328)) ([61dfe52](https://github.com/webpack-contrib/copy-webpack-plugin/commit/61dfe52))
* handles when you add new files in watch mode and use `glob` ([#333](https://github.com/webpack-contrib/copy-webpack-plugin/issues/333)) ([49a28f0](https://github.com/webpack-contrib/copy-webpack-plugin/commit/49a28f0))
* normalize path segment separation, no problems when you mixed `/` and `\\` ([#339](https://github.com/webpack-contrib/copy-webpack-plugin/issues/339)) ([8f5e638](https://github.com/webpack-contrib/copy-webpack-plugin/commit/8f5e638))
* throw error if `from` is an empty string [#278](https://github.com/webpack-contrib/copy-webpack-plugin/issues/278) ([#285](https://github.com/webpack-contrib/copy-webpack-plugin/issues/285)) ([adf1046](https://github.com/webpack-contrib/copy-webpack-plugin/commit/adf1046))
### Features
* emit warning instead error if file doesn't exist ([#338](https://github.com/webpack-contrib/copy-webpack-plugin/issues/338)) ([a1c5372](https://github.com/webpack-contrib/copy-webpack-plugin/commit/a1c5372))
* supports copy nested directories/files in symlink ([#335](https://github.com/webpack-contrib/copy-webpack-plugin/issues/335)) ([f551c0d](https://github.com/webpack-contrib/copy-webpack-plugin/commit/f551c0d))
### BREAKING CHANGES
* drop support for webpack < 4
* drop support for node < 6.9
* `debug` option was renamed to `logLevel`, it only accepts string values: `trace`, `debug`, `info`, `warn`, `error` and `silent`
* plugin emit warning instead error if file doesn't exist
* change `prototype` of plugin, now you can to get correct plugin name
<a name="4.6.0"></a>
# [4.6.0](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.5.4...v4.6.0) (2018-10-31)
### Bug Fixes
* handle undefined and null as stats value ([#302](https://github.com/webpack-contrib/copy-webpack-plugin/issues/302)) ([78c5d12](https://github.com/webpack-contrib/copy-webpack-plugin/commit/78c5d12))
### Features
* add support for target path transform ([#284](https://github.com/webpack-contrib/copy-webpack-plugin/issues/284)) ([7fe0c06](https://github.com/webpack-contrib/copy-webpack-plugin/commit/7fe0c06))
<a name="4.5.4"></a>
## [4.5.4](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.5.3...v4.5.4) (2018-10-18)
### Bug Fixes
* **processPattern:** don't add `'glob'` as directory when it is a file (`contextDependencies`) ([#296](https://github.com/webpack-contrib/copy-webpack-plugin/issues/296)) ([5670926](https://github.com/webpack-contrib/copy-webpack-plugin/commit/5670926))
<a name="4.5.3"></a>
## [4.5.3](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.5.2...v4.5.3) (2018-10-10)
### Bug Fixes
* **processPattern:** add `glob` directory context to `contextDependencies` ([#290](https://github.com/webpack-contrib/copy-webpack-plugin/issues/290)) ([5fa69db](https://github.com/webpack-contrib/copy-webpack-plugin/commit/5fa69db))
<a name="4.5.2"></a>
## [4.5.2](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.5.1...v4.5.2) (2018-06-26)
### Bug Fixes
* allow square brackets in path ([#264](https://github.com/webpack-contrib/copy-webpack-plugin/issues/264)) ([3ef5b6c](https://github.com/webpack-contrib/copy-webpack-plugin/commit/3ef5b6c)), closes [#231](https://github.com/webpack-contrib/copy-webpack-plugin/issues/231)
<a name="4.5.1"></a>
## [4.5.1](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.5.0...v4.5.1) (2018-03-09)
### Bug Fixes
* **package:** update `cacache` v10.0.1...10.0.4 (`dependencies`) ([#238](https://github.com/webpack-contrib/copy-webpack-plugin/issues/238)) ([0b288f9](https://github.com/webpack-contrib/copy-webpack-plugin/commit/0b288f9))
### Performance Improvements
* **index:** switch to `md4` for content hashing ([#239](https://github.com/webpack-contrib/copy-webpack-plugin/issues/239)) ([2be8191](https://github.com/webpack-contrib/copy-webpack-plugin/commit/2be8191))
<a name="4.5.0"></a>
# [4.5.0](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.4.3...v4.5.0) (2018-03-02)
### Features
* **processPattern:** add support for `{RegExp)` matches (`pattern.test`) ([#235](https://github.com/webpack-contrib/copy-webpack-plugin/issues/235)) ([1861730](https://github.com/webpack-contrib/copy-webpack-plugin/commit/1861730))
<a name="4.4.3"></a>
## [4.4.3](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.4.2...v4.4.3) (2018-03-01)
### Bug Fixes
* **index:** `tapable` deprecation warnings (`webpack >= v4.0.0`) ([#234](https://github.com/webpack-contrib/copy-webpack-plugin/issues/234)) ([445d548](https://github.com/webpack-contrib/copy-webpack-plugin/commit/445d548))
<a name="4.4.2"></a>
## [4.4.2](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.4.1...v4.4.2) (2018-02-23)
### Bug Fixes
* **src/:** don't escape non-glob patterns ([#230](https://github.com/webpack-contrib/copy-webpack-plugin/issues/230)) ([0eb2cd5](https://github.com/webpack-contrib/copy-webpack-plugin/commit/0eb2cd5))
<a name="4.4.1"></a>
## [4.4.1](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.4.0...v4.4.1) (2018-02-08)
### Bug Fixes
* replace `pify` with simpler promise helpers ([#221](https://github.com/webpack-contrib/copy-webpack-plugin/issues/221)) ([dadac24](https://github.com/webpack-contrib/copy-webpack-plugin/commit/dadac24))
<a name="4.4.0"></a>
# [4.4.0](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.3.1...v4.4.0) (2018-02-08)
### Bug Fixes
* **package:** add `prepare` script ([9bf0d99](https://github.com/webpack-contrib/copy-webpack-plugin/commit/9bf0d99))
* **preProcessPatterns:** support glob context paths with special characters ([#208](https://github.com/webpack-contrib/copy-webpack-plugin/issues/208)) ([ea0c05f](https://github.com/webpack-contrib/copy-webpack-plugin/commit/ea0c05f))
* support `webpack >= v4.0.0` ([6a16b3c](https://github.com/webpack-contrib/copy-webpack-plugin/commit/6a16b3c))
### Features
* use `compiler.inputFileSystem` instead `fs` ([#205](https://github.com/webpack-contrib/copy-webpack-plugin/issues/205)) ([158f821](https://github.com/webpack-contrib/copy-webpack-plugin/commit/158f821))
<a name="4.3.1"></a>
## [4.3.1](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.3.0...v4.3.1) (2017-12-22)
### Bug Fixes
* `cache` behaviour ([#196](https://github.com/webpack-contrib/copy-webpack-plugin/issues/196)) ([6beb89e](https://github.com/webpack-contrib/copy-webpack-plugin/commit/6beb89e))
* `cache` option behaviour ([3b088d0](https://github.com/webpack-contrib/copy-webpack-plugin/commit/3b088d0))
<a name="4.3.0"></a>
# [4.3.0](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.2.4...v4.3.0) (2017-12-14)
### Features
* add option to cache `pattern.transform` (`pattern.cache`) ([#176](https://github.com/webpack-contrib/copy-webpack-plugin/issues/176)) ([20c143b](https://github.com/webpack-contrib/copy-webpack-plugin/commit/20c143b))
* option for caching `transform` function ([48c19ff](https://github.com/webpack-contrib/copy-webpack-plugin/commit/48c19ff))
<a name="4.2.4"></a>
## [4.2.4](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.2.3...v4.2.4) (2017-12-14)
### Refactoring
* refactor: use native `{Promise}` instead of `bluebird` ([#178](https://github.com/webpack-contrib/copy-webpack-plugin/issues/178)) ([a508f14](https://github.com/webpack-contrib/copy-webpack-plugin/commit/a508f14))
<a name="4.2.3"></a>
## [4.2.3](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.2.2...v4.2.3) (2017-11-23)
<a name="4.2.2"></a>
## [4.2.2](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.2.0...v4.2.2) (2017-11-23)
### Bug Fixes
* copying same file to multiple targets ([#165](https://github.com/webpack-contrib/copy-webpack-plugin/issues/165)) ([43a9870](https://github.com/webpack-contrib/copy-webpack-plugin/commit/43a9870))
<a name="4.2.0"></a>
# [4.2.0](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.1.1...v4.2.0) (2017-10-19)
### Features
* add `context` option (`options.context`) ([#149](https://github.com/webpack-contrib/copy-webpack-plugin/issues/149)) ([10cd1a2](https://github.com/webpack-contrib/copy-webpack-plugin/commit/10cd1a2))
* allow async transforms ([#111](https://github.com/webpack-contrib/copy-webpack-plugin/issues/111)) ([8794e5f](https://github.com/webpack-contrib/copy-webpack-plugin/commit/8794e5f))
* Plugin context option ([5c54e92](https://github.com/webpack-contrib/copy-webpack-plugin/commit/5c54e92)), closes [#148](https://github.com/webpack-contrib/copy-webpack-plugin/issues/148)
* support `{String}` patterns ([#155](https://github.com/webpack-contrib/copy-webpack-plugin/issues/155)) ([b6c2e66](https://github.com/webpack-contrib/copy-webpack-plugin/commit/b6c2e66))
* Support simple string patterns ([056a60b](https://github.com/webpack-contrib/copy-webpack-plugin/commit/056a60b)), closes [#150](https://github.com/webpack-contrib/copy-webpack-plugin/issues/150)
<a name="4.1.1"></a>
## [4.1.1](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.1.0...v4.1.1) (2017-10-05)
### Chore
* Update dependencies for NSP security advisory ([#151](https://github.com/webpack-contrib/copy-webpack-plugin/issues/151)) ([6d4346e](https://github.com/webpack-contrib/copy-webpack-plugin/commit/6d4346e))
- Reference issue: https://nodesecurity.io/advisories/minimatch_regular-expression-denial-of-service
<a name="4.1.0"></a>
# [4.1.0](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v2.1.3...v4.1.0) (2017-09-29)
### Bug Fixes
* Changed default ignore glob to ignore dot files ([#80](https://github.com/webpack-contrib/copy-webpack-plugin/issues/80)) ([08b69a4](https://github.com/webpack-contrib/copy-webpack-plugin/commit/08b69a4))
* Fixed glob as object ([1b2c21a](https://github.com/webpack-contrib/copy-webpack-plugin/commit/1b2c21a))
* Improved Windows compatibility ([#85](https://github.com/webpack-contrib/copy-webpack-plugin/issues/85)) ([ad62899](https://github.com/webpack-contrib/copy-webpack-plugin/commit/ad62899))
* Memory leak in watch mode and use Set for performance ([#130](https://github.com/webpack-contrib/copy-webpack-plugin/issues/130)) ([de46fde](https://github.com/webpack-contrib/copy-webpack-plugin/commit/de46fde))
* subdirectory errors in blob patterns ([c2720d0](https://github.com/webpack-contrib/copy-webpack-plugin/commit/c2720d0))
### Features
* Added non-wildcard glob support ([405d1ec](https://github.com/webpack-contrib/copy-webpack-plugin/commit/405d1ec))
* Added transform method to patterns ([#77](https://github.com/webpack-contrib/copy-webpack-plugin/issues/77)) ([6371eb1](https://github.com/webpack-contrib/copy-webpack-plugin/commit/6371eb1))
<a name="4.0.1"></a>
## [4.0.1](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v2.1.3...v4.0.1) (2017-09-29)
### Bug Fixes
* Fixed glob as object ([1b2c21a](https://github.com/webpack-contrib/copy-webpack-plugin/commit/1b2c21a))
* Improved Windows compatibility ([#85](https://github.com/webpack-contrib/copy-webpack-plugin/issues/85)) ([ad62899](https://github.com/webpack-contrib/copy-webpack-plugin/commit/ad62899))
* subdirectory errors in blob patterns ([c2720d0](https://github.com/webpack-contrib/copy-webpack-plugin/commit/c2720d0))
### Features
* Added non-wildcard glob support ([405d1ec](https://github.com/webpack-contrib/copy-webpack-plugin/commit/405d1ec))
* Added transform method to patterns ([#77](https://github.com/webpack-contrib/copy-webpack-plugin/issues/77)) ([6371eb1](https://github.com/webpack-contrib/copy-webpack-plugin/commit/6371eb1))
<a name="4.0.0"></a>
## [4.0.0](https://github.com/webpack-contrib/copy-webpack-plugin/compare/v4.0.0...v3.0.1) (2016-10-23)
### Bug Fixes
* Changed default ignore glob to ignore dot files ([#80](https://github.com/webpack-contrib/copy-webpack-plugin/issues/80)) ([08b69a4](https://github.com/webpack-contrib/copy-webpack-plugin/commit/08b69a4))
### Features
* Added transform method to patterns ([6371eb1](https://github.com/webpack-contrib/copy-webpack-plugin/commit/6371eb1))
+20
View File
@@ -0,0 +1,20 @@
Copyright JS Foundation and other 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.
+548
View File
@@ -0,0 +1,548 @@
<div align="center">
<a href="https://github.com/webpack/webpack">
<img width="200" height="200"
src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
</div>
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
[![tests][tests]][tests-url]
[![cover][cover]][cover-url]
[![chat][chat]][chat-url]
[![size][size]][size-url]
# copy-webpack-plugin
Copies individual files or entire directories, which already exist, to the build directory.
## Getting Started
To begin, you'll need to install `copy-webpack-plugin`:
```console
$ npm install copy-webpack-plugin --save-dev
```
Then add the plugin to your `webpack` config. For example:
**webpack.config.js**
```js
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
plugins: [
new CopyPlugin([
{ from: 'source', to: 'dest' },
{ from: 'other', to: 'public' },
]),
],
};
```
> ️ `webpack-copy-plugin` is not designed to copy files generated from the build process; rather, it is to copy files that already exist in the source tree, as part of the build process.
> ️ If you want `webpack-dev-server` to write files to the output directory during development, you can force it with the [`writeToDisk`](https://github.com/webpack/webpack-dev-middleware#writetodisk) option or the [`write-file-webpack-plugin`](https://github.com/gajus/write-file-webpack-plugin).
## Options
The plugin's signature:
**webpack.config.js**
```js
module.exports = {
plugins: [new CopyPlugin(patterns, options)],
};
```
### Patterns
| Name | Type | Default | Description |
| :-------------------------------: | :-------------------: | :---------------------------------------------: | :---------------------------------------------------------------------------------------------------- |
| [`from`](#from) | `{String\|Object}` | `undefined` | Glob or path from where we сopy files. |
| [`to`](#to) | `{String}` | `undefined` | Output path. |
| [`context`](#context) | `{String}` | `options.context \|\| compiler.options.context` | A path that determines how to interpret the `from` path. |
| [`toType`](#totype) | `{String}` | `undefined` | Determinate what is `to` option - directory, file or template. |
| [`test`](#test) | `{RegExp}` | `undefined` | Pattern for extracting elements to be used in `to` templates. |
| [`force`](#force) | `{Boolean}` | `false` | Overwrites files already in `compilation.assets` (usually added by other plugins/loaders). |
| [`ignore`](#ignore) | `{Array}` | `[]` | Globs to ignore files. |
| [`flatten`](#flatten) | `{Boolean}` | `false` | Removes all directory references and only copies file names. |
| [`cache`](#cache) | `{Boolean\|Object}` | `false` | Enable `transform` caching. You can use `{ cache: { key: 'my-cache-key' } }` to invalidate the cache. |
| [`transform`](#transform) | `{Function\|Promise}` | `undefined` | Allows to modify the file contents. |
| [`transformPath`](#transformpath) | `{Function\|Promise}` | `undefined` | Allows to modify the writing path. |
#### `from`
Type: `String\|Object`
Default: `undefined`
Glob or path from where we сopy files.
Globs accept [minimatch options](https://github.com/isaacs/minimatch).
You can define `from` as `Object` and use the [`node-glob` options](https://github.com/isaacs/node-glob#options).
> ⚠️ Don't use directly `\\` in `from` (i.e `path\to\file.ext`) option because on UNIX the backslash is a valid character inside a path component, i.e., it's not a separator.
> On Windows, the forward slash and the backward slash are both separators.
> Instead please use `/` or `path` methods.
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
'relative/path/to/file.ext',
'/absolute/path/to/file.ext',
'relative/path/to/dir',
'/absolute/path/to/dir',
'**/*',
{ glob: '**/*', dot: false },
]),
],
};
```
#### `to`
Type: `String`
Default: `undefined`
Output path.
> ⚠️ Don't use directly `\\` in `to` (i.e `path\to\dest`) option because on UNIX the backslash is a valid character inside a path component, i.e., it's not a separator.
> On Windows, the forward slash and the backward slash are both separators.
> Instead please use `/` or `path` methods.
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{ from: '**/*', to: 'relative/path/to/dest/' },
{ from: '**/*', to: '/absolute/path/to/dest/' },
]),
],
};
```
#### `context`
Type: `String`
Default: `options.context|compiler.options.context`
A path that determines how to interpret the `from` path.
> ⚠️ Don't use directly `\\` in `context` (i.e `path\to\context`) option because on UNIX the backslash is a valid character inside a path component, i.e., it's not a separator.
> On Windows, the forward slash and the backward slash are both separators.
> Instead please use `/` or `path` methods.
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/*.txt',
to: 'dest/',
context: 'app/',
},
]),
],
};
```
#### `toType`
Type: `String`
Default: `undefined`
Determinate what is `to` option - directory, file or template.
Sometimes it is hard to say what is `to`, example `path/to/dir-with.ext`.
If you want to copy files in directory you need use `dir` option.
We try to automatically determine the `type` so you most likely do not need this option.
| Name | Type | Default | Description |
| :--------------: | :--------: | :---------: | :------------------------------------------------------------------------------------------------- |
| **`'dir'`** | `{String}` | `undefined` | If `from` is directory, `to` has no extension or ends in `'/'` |
| **`'file'`** | `{String}` | `undefined` | If `to` has extension or `from` is file |
| **`'template'`** | `{String}` | `undefined` | If `to` contains [a template pattern](https://github.com/webpack-contrib/file-loader#placeholders) |
##### `'dir'`
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'path/to/file.txt',
to: 'directory/with/extension.ext',
toType: 'dir',
},
]),
],
};
```
##### `'file'`
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'path/to/file.txt',
to: 'file/without/extension',
toType: 'file',
},
]),
],
};
```
##### `'template'`
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/',
to: 'dest/[name].[hash].[ext]',
toType: 'template',
},
]),
],
};
```
#### `test`
Type: `RegExp`
Default: `undefined`
Pattern for extracting elements to be used in `to` templates.
Defines a `{RegExp}` to match some parts of the file path.
These capture groups can be reused in the name property using `[N]` placeholder.
Note that `[0]` will be replaced by the entire path of the file,
whereas `[1]` will contain the first capturing parenthesis of your `{RegExp}`
and so on...
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: '*/*',
to: '[1]-[2].[hash].[ext]',
test: /([^/]+)\/(.+)\.png$/,
},
]),
],
};
```
#### `force`
Type: `Boolean`
Default: `false`
Overwrites files already in `compilation.assets` (usually added by other plugins/loaders).
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/**/*',
to: 'dest/',
force: true,
},
]),
],
};
```
#### `ignore`
Type: `Array`
Default: `[]`
Globs to ignore files.
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/**/*',
to: 'dest/',
ignore: ['*.js'],
},
]),
],
};
```
#### `flatten`
Type: `Boolean`
Default: `false`
Removes all directory references and only copies file names.
> ⚠️ If files have the same name, the result is non-deterministic.
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/**/*',
to: 'dest/',
flatten: true,
},
]),
],
};
```
#### `cache`
Type: `Boolean|Object`
Default: `false`
Enable/disable `transform` caching. You can use `{ cache: { key: 'my-cache-key' } }` to invalidate the cache.
Default path to cache directory: `node_modules/.cache/copy-webpack-plugin`.
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/*.png',
to: 'dest/',
transform(content, path) {
return optimize(content);
},
cache: true,
},
]),
],
};
```
#### `transform`
Type: `Function|Promise`
Default: `undefined`
Allows to modify the file contents.
##### `{Function}`
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/*.png',
to: 'dest/',
transform(content, path) {
return optimize(content);
},
},
]),
],
};
```
##### `{Promise}`
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/*.png',
to: 'dest/',
transform(content, path) {
return Promise.resolve(optimize(content));
},
},
]),
],
};
```
#### `transformPath`
Type: `Function|Promise`
Default: `undefined`
Allows to modify the writing path.
> ⚠️ Don't return directly `\\` in `transformPath` (i.e `path\to\newFile`) option because on UNIX the backslash is a valid character inside a path component, i.e., it's not a separator.
> On Windows, the forward slash and the backward slash are both separators.
> Instead please use `/` or `path` methods.
##### `{Function}`
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/*.png',
to: 'dest/',
transformPath(targetPath, absolutePath) {
return 'newPath';
},
},
]),
],
};
```
##### `{Promise}`
**webpack.config.js**
```js
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/*.png',
to: 'dest/',
transformPath(targetPath, absolutePath) {
return Promise.resolve('newPath');
},
},
]),
],
};
```
### Options
| Name | Type | Default | Description |
| :---------------------------------: | :---------: | :------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------ |
| [`logLevel`](#loglevel) | `{String}` | **`'warn'`** | Level of messages that the module will log |
| [`ignore`](#ignore) | `{Array}` | `[]` | Array of globs to ignore (applied to `from`) |
| [`context`](#context) | `{String}` | `compiler.options.context` | A path that determines how to interpret the `from` path, shared for all patterns |
| [`copyUnmodified`](#copyunmodified) | `{Boolean}` | `false` | Copies files, regardless of modification when using watch or `webpack-dev-server`. All files are copied on first build, regardless of this option |
#### `logLevel`
This property defines the level of messages that the module will log. Valid levels include:
- `trace`
- `debug`
- `info`
- `warn` (default)
- `error`
- `silent`
Setting a log level means that all other levels below it will be visible in the
console. Setting `logLevel: 'silent'` will hide all console output. The module
leverages [`webpack-log`](https://github.com/webpack-contrib/webpack-log#readme)
for logging management, and more information can be found on its page.
**webpack.config.js**
```js
module.exports = {
plugins: [new CopyPlugin([...patterns], { logLevel: 'debug' })],
};
```
#### `ignore`
Array of globs to ignore (applied to `from`).
**webpack.config.js**
```js
module.exports = {
plugins: [new CopyPlugin([...patterns], { ignore: ['*.js', '*.css'] })],
};
```
#### `context`
A path that determines how to interpret the `from` path, shared for all patterns.
**webpack.config.js**
```js
module.exports = {
plugins: [new CopyPlugin([...patterns], { context: '/app' })],
};
```
#### `copyUnmodified`
Copies files, regardless of modification when using watch or `webpack-dev-server`. All files are copied on first build, regardless of this option.
> ️ By default, we only copy **modified** files during a `webpack --watch` or `webpack-dev-server` build. Setting this option to `true` will copy all files.
**webpack.config.js**
```js
module.exports = {
plugins: [new CopyPlugin([...patterns], { copyUnmodified: true })],
};
```
## Contributing
Please take a moment to read our contributing guidelines if you haven't yet done so.
[CONTRIBUTING](./.github/CONTRIBUTING.md)
## License
[MIT](./LICENSE)
[npm]: https://img.shields.io/npm/v/copy-webpack-plugin.svg
[npm-url]: https://npmjs.com/package/copy-webpack-plugin
[node]: https://img.shields.io/node/v/copy-webpack-plugin.svg
[node-url]: https://nodejs.org
[deps]: https://david-dm.org/webpack-contrib/copy-webpack-plugin.svg
[deps-url]: https://david-dm.org/webpack-contrib/copy-webpack-plugin
[tests]: https://dev.azure.com/webpack-contrib/copy-webpack-plugin/_apis/build/status/webpack-contrib.copy-webpack-plugin?branchName=master
[tests-url]: https://dev.azure.com/webpack-contrib/copy-webpack-plugin/_build/latest?definitionId=5&branchName=master
[cover]: https://codecov.io/gh/webpack-contrib/copy-webpack-plugin/branch/master/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack-contrib/copy-webpack-plugin
[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
[chat-url]: https://gitter.im/webpack/webpack
[size]: https://packagephobia.now.sh/badge?p=copy-webpack-plugin
[size-url]: https://packagephobia.now.sh/result?p=copy-webpack-plugin
+5
View File
@@ -0,0 +1,5 @@
"use strict";
const plugin = require('./index');
module.exports = plugin.default;
+121
View File
@@ -0,0 +1,121 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _path = _interopRequireDefault(require("path"));
var _webpackLog = _interopRequireDefault(require("webpack-log"));
var _preProcessPattern = _interopRequireDefault(require("./preProcessPattern"));
var _processPattern = _interopRequireDefault(require("./processPattern"));
var _postProcessPattern = _interopRequireDefault(require("./postProcessPattern"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class CopyPlugin {
constructor(patterns = [], options = {}) {
if (!Array.isArray(patterns)) {
throw new Error('[copy-webpack-plugin] patterns must be an array');
}
this.patterns = patterns;
this.options = options;
}
apply(compiler) {
const fileDependencies = new Set();
const contextDependencies = new Set();
const written = {};
let context;
if (!this.options.context) {
({
context
} = compiler.options);
} else if (!_path.default.isAbsolute(this.options.context)) {
context = _path.default.join(compiler.options.context, this.options.context);
} else {
({
context
} = this.options);
}
const logger = (0, _webpackLog.default)({
name: 'copy-webpack-plugin',
level: this.options.logLevel || 'warn'
});
const plugin = {
name: 'CopyPlugin'
};
compiler.hooks.emit.tapAsync(plugin, (compilation, callback) => {
logger.debug('starting emit');
const globalRef = {
logger,
compilation,
written,
fileDependencies,
contextDependencies,
context,
inputFileSystem: compiler.inputFileSystem,
output: compiler.options.output.path,
ignore: this.options.ignore || [],
copyUnmodified: this.options.copyUnmodified,
concurrency: this.options.concurrency
};
if (globalRef.output === '/' && compiler.options.devServer && compiler.options.devServer.outputPath) {
globalRef.output = compiler.options.devServer.outputPath;
}
const {
patterns
} = this;
Promise.all(patterns.map(pattern => Promise.resolve().then(() => (0, _preProcessPattern.default)(globalRef, pattern)) // Every source (from) is assumed to exist here
// eslint-disable-next-line no-shadow
.then(pattern => (0, _processPattern.default)(globalRef, pattern).then(files => {
if (!files) {
return Promise.resolve();
}
return Promise.all(files.filter(Boolean).map(file => (0, _postProcessPattern.default)(globalRef, pattern, file)));
})))).catch(error => {
compilation.errors.push(error);
}).then(() => {
logger.debug('finishing emit');
callback();
});
});
compiler.hooks.afterEmit.tapAsync(plugin, (compilation, callback) => {
logger.debug('starting after-emit'); // Add file dependencies
if ("addAll" in compilation.fileDependencies) {
compilation.fileDependencies.addAll(fileDependencies);
} else {
for (const fileDependency of fileDependencies) {
compilation.fileDependencies.add(fileDependency);
}
} // Add context dependencies
if ("addAll" in compilation.contextDependencies) {
compilation.contextDependencies.addAll(contextDependencies);
} else {
for (const contextDependency of contextDependencies) {
compilation.contextDependencies.add(contextDependency);
}
}
logger.debug('finishing after-emit');
callback();
});
}
}
var _default = CopyPlugin;
exports.default = _default;
+156
View File
@@ -0,0 +1,156 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = postProcessPattern;
var _path = _interopRequireDefault(require("path"));
var _os = _interopRequireDefault(require("os"));
var _crypto = _interopRequireDefault(require("crypto"));
var _loaderUtils = _interopRequireDefault(require("loader-utils"));
var _cacache = _interopRequireDefault(require("cacache"));
var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"));
var _findCacheDir = _interopRequireDefault(require("find-cache-dir"));
var _normalizePath = _interopRequireDefault(require("normalize-path"));
var _package = require("../package.json");
var _promisify = require("./utils/promisify");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-param-reassign */
function postProcessPattern(globalRef, pattern, file) {
const {
logger,
compilation,
fileDependencies,
written,
inputFileSystem,
copyUnmodified
} = globalRef;
logger.debug(`getting stats for '${file.absoluteFrom}' to write to assets`);
const getStats = pattern.stats ? Promise.resolve().then(() => pattern.stats) : (0, _promisify.stat)(inputFileSystem, file.absoluteFrom);
return getStats.then(stats => {
// We don't write empty directories
if (stats.isDirectory()) {
logger.debug(`skipping '${file.absoluteFrom}' because it is empty directory`);
return Promise.resolve();
} // If this came from a glob, add it to the file watchlist
if (pattern.fromType === 'glob') {
fileDependencies.add(file.absoluteFrom);
}
logger.debug(`reading '${file.absoluteFrom}' to write to assets`);
return (0, _promisify.readFile)(inputFileSystem, file.absoluteFrom).then(content => {
if (pattern.transform) {
logger.info(`transforming content for '${file.absoluteFrom}'`); // eslint-disable-next-line no-shadow
const transform = (content, absoluteFrom) => pattern.transform(content, absoluteFrom);
if (pattern.cache) {
if (!globalRef.cacheDir) {
globalRef.cacheDir = (0, _findCacheDir.default)({
name: 'copy-webpack-plugin'
}) || _os.default.tmpdir();
}
const cacheKey = pattern.cache.key ? pattern.cache.key : (0, _serializeJavascript.default)({
name: _package.name,
version: _package.version,
pattern,
hash: _crypto.default.createHash('md4').update(content).digest('hex')
});
return _cacache.default.get(globalRef.cacheDir, cacheKey).then(result => {
logger.debug(`getting cached transformation for '${file.absoluteFrom}'`);
return result.data;
}, () => Promise.resolve().then(() => transform(content, file.absoluteFrom)) // eslint-disable-next-line no-shadow
.then(content => {
logger.debug(`caching transformation for '${file.absoluteFrom}'`);
return _cacache.default.put(globalRef.cacheDir, cacheKey, content).then(() => content);
}));
}
content = transform(content, file.absoluteFrom);
}
return content;
}).then(content => {
if (pattern.toType === 'template') {
logger.info(`interpolating template '${file.webpackTo}' for '${file.relativeFrom}'`); // If it doesn't have an extension, remove it from the pattern
// ie. [name].[ext] or [name][ext] both become [name]
if (!_path.default.extname(file.relativeFrom)) {
file.webpackTo = file.webpackTo.replace(/\.?\[ext\]/g, '');
}
file.webpackTo = _loaderUtils.default.interpolateName({
resourcePath: file.absoluteFrom
}, file.webpackTo, {
content,
regExp: file.webpackToRegExp,
context: pattern.context
}); // Bug in `loader-utils`, package convert `\\` to `/`, need fix in loader-utils
file.webpackTo = _path.default.normalize(file.webpackTo);
}
return content;
}).then(content => {
if (pattern.transformPath) {
logger.info(`transforming path '${file.webpackTo}' for '${file.absoluteFrom}'`);
return Promise.resolve().then(() => pattern.transformPath(file.webpackTo, file.absoluteFrom)).then(newPath => {
file.webpackTo = newPath;
return content;
});
}
return content;
}).then(content => {
const hash = _loaderUtils.default.getHashDigest(content);
const targetPath = (0, _normalizePath.default)(file.webpackTo);
const targetAbsolutePath = (0, _normalizePath.default)(file.absoluteFrom);
if (!copyUnmodified && written[targetPath] && written[targetPath][targetAbsolutePath] && written[targetPath][targetAbsolutePath] === hash) {
logger.info(`skipping '${file.webpackTo}', because content hasn't changed`);
return;
}
logger.debug(`adding '${file.webpackTo}' for tracking content changes`);
if (!written[targetPath]) {
written[targetPath] = {};
}
written[targetPath][targetAbsolutePath] = hash;
if (compilation.assets[targetPath] && !file.force) {
logger.info(`skipping '${file.webpackTo}', because it already exists`);
return;
}
logger.info(`writing '${file.webpackTo}' to compilation assets from '${file.absoluteFrom}'`);
compilation.assets[targetPath] = {
size() {
return stats.size;
},
source() {
return content;
}
};
});
});
}
+156
View File
@@ -0,0 +1,156 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = preProcessPattern;
var _path = _interopRequireDefault(require("path"));
var _isGlob = _interopRequireDefault(require("is-glob"));
var _globParent = _interopRequireDefault(require("glob-parent"));
var _normalize = _interopRequireDefault(require("./utils/normalize"));
var _isTemplateLike = _interopRequireDefault(require("./utils/isTemplateLike"));
var _isObject = _interopRequireDefault(require("./utils/isObject"));
var _promisify = require("./utils/promisify");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* eslint-disable no-param-reassign */
function preProcessPattern(globalRef, pattern) {
const {
logger,
context,
inputFileSystem,
fileDependencies,
contextDependencies,
compilation
} = globalRef;
pattern = typeof pattern === 'string' ? {
from: pattern
} : Object.assign({}, pattern);
if (pattern.from === '') {
const message = 'path "from" cannot be empty string';
logger.error(message);
compilation.errors.push(new Error(message));
}
pattern.to = pattern.to || '';
pattern.context = pattern.context || context;
if (!_path.default.isAbsolute(pattern.context)) {
pattern.context = _path.default.join(context, pattern.context);
}
const isFromGlobPatten = (0, _isObject.default)(pattern.from) && pattern.from.glob; // Todo remove this in next major
const isToDirectory = _path.default.extname(pattern.to) === '' || pattern.to.slice(-1) === _path.default.sep; // Normalize paths
pattern.from = isFromGlobPatten ? pattern.from : _path.default.normalize(pattern.from);
pattern.context = _path.default.normalize(pattern.context);
pattern.to = _path.default.normalize(pattern.to);
pattern.ignore = globalRef.ignore.concat(pattern.ignore || []);
logger.debug(`processing from: '${pattern.from}' to: '${pattern.to}'`);
switch (true) {
// if toType already exists
case !!pattern.toType:
break;
case (0, _isTemplateLike.default)(pattern.to):
pattern.toType = 'template';
break;
case isToDirectory:
pattern.toType = 'dir';
break;
default:
pattern.toType = 'file';
} // If we know it's a glob, then bail early
if (isFromGlobPatten) {
logger.debug(`determined '${pattern.absoluteFrom}' is a glob`);
pattern.fromType = 'glob';
const globOptions = Object.assign({}, pattern.from);
delete globOptions.glob;
pattern.glob = (0, _normalize.default)(pattern.context, pattern.from.glob);
pattern.globOptions = globOptions;
pattern.absoluteFrom = _path.default.resolve(pattern.context, pattern.from.glob);
return Promise.resolve(pattern);
}
if (_path.default.isAbsolute(pattern.from)) {
pattern.absoluteFrom = pattern.from;
} else {
pattern.absoluteFrom = _path.default.resolve(pattern.context, pattern.from);
}
logger.debug(`determined '${pattern.from}' to be read from '${pattern.absoluteFrom}'`);
const noStatsHandler = () => {
// If from doesn't appear to be a glob, then log a warning
if ((0, _isGlob.default)(pattern.from) || pattern.from.includes('*')) {
logger.debug(`determined '${pattern.absoluteFrom}' is a glob`);
pattern.fromType = 'glob';
pattern.glob = (0, _normalize.default)(pattern.context, pattern.from); // We need to add context directory as dependencies to avoid problems when new files added in directories
// when we already in watch mode and this directories are not in context dependencies
// `glob-parent` always return `/` we need normalize path
contextDependencies.add(_path.default.normalize((0, _globParent.default)(pattern.absoluteFrom)));
} else {
const newWarning = new Error(`unable to locate '${pattern.from}' at '${pattern.absoluteFrom}'`);
const hasWarning = compilation.warnings.some( // eslint-disable-next-line no-shadow
warning => warning.message === newWarning.message); // Only display the same message once
if (!hasWarning) {
logger.warn(newWarning.message);
compilation.warnings.push(newWarning);
}
pattern.fromType = 'nonexistent';
}
};
logger.debug(`getting stats for '${pattern.absoluteFrom}' to determinate 'fromType'`);
return (0, _promisify.stat)(inputFileSystem, pattern.absoluteFrom).catch(() => noStatsHandler()).then(stats => {
if (!stats) {
noStatsHandler();
return pattern;
}
if (stats.isDirectory()) {
logger.debug(`determined '${pattern.absoluteFrom}' is a directory`);
contextDependencies.add(pattern.absoluteFrom);
pattern.fromType = 'dir';
pattern.context = pattern.absoluteFrom;
pattern.glob = (0, _normalize.default)(pattern.absoluteFrom, '**/*');
pattern.absoluteFrom = _path.default.join(pattern.absoluteFrom, '**/*');
pattern.globOptions = {
dot: true
};
} else if (stats.isFile()) {
logger.debug(`determined '${pattern.absoluteFrom}' is a file`);
fileDependencies.add(pattern.absoluteFrom);
pattern.stats = stats;
pattern.fromType = 'file';
pattern.context = _path.default.dirname(pattern.absoluteFrom);
pattern.glob = (0, _normalize.default)(pattern.absoluteFrom);
pattern.globOptions = {
dot: true
};
} else if (!pattern.fromType) {
logger.warn(`unrecognized file type for ${pattern.from}`);
}
return pattern;
});
}
+108
View File
@@ -0,0 +1,108 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = processPattern;
var _path = _interopRequireDefault(require("path"));
var _globby = _interopRequireDefault(require("globby"));
var _pLimit = _interopRequireDefault(require("p-limit"));
var _minimatch = _interopRequireDefault(require("minimatch"));
var _isObject = _interopRequireDefault(require("./utils/isObject"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function processPattern(globalRef, pattern) {
const {
logger,
output,
concurrency,
compilation
} = globalRef;
const globOptions = Object.assign({
cwd: pattern.context,
follow: true // Todo in next major release
// dot: false
}, pattern.globOptions || {});
if (pattern.fromType === 'nonexistent') {
return Promise.resolve();
}
const limit = (0, _pLimit.default)(concurrency || 100);
logger.info(`begin globbing '${pattern.glob}' with a context of '${pattern.context}'`);
return (0, _globby.default)(pattern.glob, globOptions).then(paths => Promise.all(paths.map(from => limit(() => {
const file = {
force: pattern.force,
absoluteFrom: _path.default.resolve(pattern.context, from)
};
file.relativeFrom = _path.default.relative(pattern.context, file.absoluteFrom);
if (pattern.flatten) {
file.relativeFrom = _path.default.basename(file.relativeFrom);
}
logger.debug(`found ${from}`); // Check the ignore list
let il = pattern.ignore.length; // eslint-disable-next-line no-plusplus
while (il--) {
const ignoreGlob = pattern.ignore[il];
let globParams = {
dot: true,
matchBase: true
};
let glob;
if (typeof ignoreGlob === 'string') {
glob = ignoreGlob;
} else if ((0, _isObject.default)(ignoreGlob)) {
glob = ignoreGlob.glob || '';
const ignoreGlobParams = Object.assign({}, ignoreGlob);
delete ignoreGlobParams.glob; // Overwrite minimatch defaults
globParams = Object.assign(globParams, ignoreGlobParams);
} else {
glob = '';
}
logger.debug(`testing ${glob} against ${file.relativeFrom}`);
if ((0, _minimatch.default)(file.relativeFrom, glob, globParams)) {
logger.info(`ignoring '${file.relativeFrom}', because it matches the ignore glob '${glob}'`);
return Promise.resolve();
}
logger.debug(`${glob} doesn't match ${file.relativeFrom}`);
} // Change the to path to be relative for webpack
if (pattern.toType === 'dir') {
file.webpackTo = _path.default.join(pattern.to, file.relativeFrom);
} else if (pattern.toType === 'file') {
file.webpackTo = pattern.to || file.relativeFrom;
} else if (pattern.toType === 'template') {
file.webpackTo = pattern.to;
file.webpackToRegExp = pattern.test;
}
if (_path.default.isAbsolute(file.webpackTo)) {
if (output === '/') {
const message = 'using older versions of webpack-dev-server, devServer.outputPath must be defined to write to absolute paths';
logger.error(message);
compilation.errors.push(new Error(message));
}
file.webpackTo = _path.default.relative(output, file.webpackTo);
}
logger.info(`determined that '${from}' should write to '${file.webpackTo}'`);
return file;
}))));
}
+10
View File
@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = val => Object.prototype.toString.call(val) === '[object Object]';
exports.default = _default;
+10
View File
@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _default = pattern => /(\[ext\])|(\[name\])|(\[path\])|(\[folder\])|(\[emoji(?::(\d+))?\])|(\[(?:([^:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*))?(?::(\d+))?\])|(\[\d+\])/.test(pattern);
exports.default = _default;
+39
View File
@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = normalize;
var _path = _interopRequireDefault(require("path"));
var _normalizePath = _interopRequireDefault(require("normalize-path"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function escape(context, from) {
if (from && _path.default.isAbsolute(from)) {
return from;
} // Ensure context is escaped before globbing
// Handles special characters in paths
const absoluteContext = _path.default.resolve(context) // Need refactor
// eslint-disable-next-line no-useless-escape
.replace(/[\*|\?|\!|\(|\)|\[|\]|\{|\}]/g, substring => `[${substring}]`);
if (!from) {
return absoluteContext;
} // Cannot use path.join/resolve as it "fixes" the path separators
if (absoluteContext.endsWith('/')) {
return `${absoluteContext}${from}`;
}
return `${absoluteContext}/${from}`;
}
function normalize(context, from) {
return (0, _normalizePath.default)(escape(context, from));
}
+30
View File
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.readFile = exports.stat = void 0;
const stat = (inputFileSystem, path) => new Promise((resolve, reject) => {
inputFileSystem.stat(path, (err, stats) => {
if (err) {
reject(err);
}
resolve(stats);
});
});
exports.stat = stat;
const readFile = (inputFileSystem, path) => new Promise((resolve, reject) => {
inputFileSystem.readFile(path, (err, stats) => {
if (err) {
reject(err);
}
resolve(stats);
});
});
exports.readFile = readFile;
+88
View File
@@ -0,0 +1,88 @@
'use strict';
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const gitIgnore = require('ignore');
const pify = require('pify');
const slash = require('slash');
const globP = pify(glob);
const readFileP = pify(fs.readFile);
const mapGitIgnorePatternTo = base => ignore => {
if (ignore.startsWith('!')) {
return '!' + path.posix.join(base, ignore.substr(1));
}
return path.posix.join(base, ignore);
};
const parseGitIgnore = (content, opts) => {
const base = slash(path.relative(opts.cwd, path.dirname(opts.fileName)));
return content
.split(/\r?\n/)
.filter(Boolean)
.filter(l => l.charAt(0) !== '#')
.map(mapGitIgnorePatternTo(base));
};
const reduceIgnore = files => {
return files.reduce((ignores, file) => {
ignores.add(parseGitIgnore(file.content, {
cwd: file.cwd,
fileName: file.filePath
}));
return ignores;
}, gitIgnore());
};
const getIsIgnoredPredecate = (ignores, cwd) => {
return p => ignores.ignores(slash(path.relative(cwd, p)));
};
const getFile = (file, cwd) => {
const filePath = path.join(cwd, file);
return readFileP(filePath, 'utf8')
.then(content => ({
content,
cwd,
filePath
}));
};
const getFileSync = (file, cwd) => {
const filePath = path.join(cwd, file);
const content = fs.readFileSync(filePath, 'utf8');
return {
content,
cwd,
filePath
};
};
const normalizeOpts = opts => {
opts = opts || {};
const ignore = opts.ignore || [];
const cwd = opts.cwd || process.cwd();
return {ignore, cwd};
};
module.exports = o => {
const opts = normalizeOpts(o);
return globP('**/.gitignore', {ignore: opts.ignore, cwd: opts.cwd})
.then(paths => Promise.all(paths.map(file => getFile(file, opts.cwd))))
.then(files => reduceIgnore(files))
.then(ignores => getIsIgnoredPredecate(ignores, opts.cwd));
};
module.exports.sync = o => {
const opts = normalizeOpts(o);
const paths = glob.sync('**/.gitignore', {ignore: opts.ignore, cwd: opts.cwd});
const files = paths.map(file => getFileSync(file, opts.cwd));
const ignores = reduceIgnore(files);
return getIsIgnoredPredecate(ignores, opts.cwd);
};
+134
View File
@@ -0,0 +1,134 @@
'use strict';
const arrayUnion = require('array-union');
const glob = require('glob');
const pify = require('pify');
const dirGlob = require('dir-glob');
const gitignore = require('./gitignore');
const globP = pify(glob);
const DEFAULT_FILTER = () => false;
const isNegative = pattern => pattern[0] === '!';
const assertPatternsInput = patterns => {
if (!patterns.every(x => typeof x === 'string')) {
throw new TypeError('Patterns must be a string or an array of strings');
}
};
const generateGlobTasks = (patterns, taskOpts) => {
patterns = [].concat(patterns);
assertPatternsInput(patterns);
const globTasks = [];
taskOpts = Object.assign({
cache: Object.create(null),
statCache: Object.create(null),
realpathCache: Object.create(null),
symlinks: Object.create(null),
ignore: [],
expandDirectories: true,
nodir: true
}, taskOpts);
patterns.forEach((pattern, i) => {
if (isNegative(pattern)) {
return;
}
const ignore = patterns
.slice(i)
.filter(isNegative)
.map(pattern => pattern.slice(1));
const opts = Object.assign({}, taskOpts, {
ignore: taskOpts.ignore.concat(ignore)
});
globTasks.push({pattern, opts});
});
return globTasks;
};
const globDirs = (task, fn) => {
if (Array.isArray(task.opts.expandDirectories)) {
return fn(task.pattern, {files: task.opts.expandDirectories});
}
if (typeof task.opts.expandDirectories === 'object') {
return fn(task.pattern, task.opts.expandDirectories);
}
return fn(task.pattern);
};
const getPattern = (task, fn) => task.opts.expandDirectories ? globDirs(task, fn) : [task.pattern];
module.exports = (patterns, opts) => {
let globTasks;
try {
globTasks = generateGlobTasks(patterns, opts);
} catch (err) {
return Promise.reject(err);
}
const getTasks = Promise.all(globTasks.map(task => Promise.resolve(getPattern(task, dirGlob))
.then(globs => Promise.all(globs.map(glob => ({
pattern: glob,
opts: task.opts
}))))
))
.then(tasks => arrayUnion.apply(null, tasks));
const getFilter = () => {
return Promise.resolve(
opts && opts.gitignore ?
gitignore({cwd: opts.cwd, ignore: opts.ignore}) :
DEFAULT_FILTER
);
};
return getFilter()
.then(filter => {
return getTasks
.then(tasks => Promise.all(tasks.map(task => globP(task.pattern, task.opts))))
.then(paths => arrayUnion.apply(null, paths))
.then(paths => paths.filter(p => !filter(p)));
});
};
module.exports.sync = (patterns, opts) => {
const globTasks = generateGlobTasks(patterns, opts);
const getFilter = () => {
return opts && opts.gitignore ?
gitignore.sync({cwd: opts.cwd, ignore: opts.ignore}) :
DEFAULT_FILTER;
};
const tasks = globTasks.reduce((tasks, task) => {
const newTask = getPattern(task, dirGlob.sync).map(glob => ({
pattern: glob,
opts: task.opts
}));
return tasks.concat(newTask);
}, []);
const filter = getFilter();
return tasks.reduce(
(matches, task) => arrayUnion(matches, glob.sync(task.pattern, task.opts)),
[]
).filter(p => !filter(p));
};
module.exports.generateGlobTasks = generateGlobTasks;
module.exports.hasMagic = (patterns, opts) => []
.concat(patterns)
.some(pattern => glob.hasMagic(pattern, opts));
module.exports.gitignore = gitignore;
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+106
View File
@@ -0,0 +1,106 @@
{
"_from": "globby@^7.1.1",
"_id": "globby@7.1.1",
"_inBundle": false,
"_integrity": "sha1-+yzP+UAfhgCUXfral0QMypcrhoA=",
"_location": "/copy-webpack-plugin/globby",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "globby@^7.1.1",
"name": "globby",
"escapedName": "globby",
"rawSpec": "^7.1.1",
"saveSpec": null,
"fetchSpec": "^7.1.1"
},
"_requiredBy": [
"/copy-webpack-plugin"
],
"_resolved": "https://registry.npmjs.org/globby/-/globby-7.1.1.tgz",
"_shasum": "fb2ccff9401f8600945dfada97440cca972b8680",
"_spec": "globby@^7.1.1",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/copy-webpack-plugin",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/globby/issues"
},
"bundleDependencies": false,
"dependencies": {
"array-union": "^1.0.1",
"dir-glob": "^2.0.0",
"glob": "^7.1.2",
"ignore": "^3.3.5",
"pify": "^3.0.0",
"slash": "^1.0.0"
},
"deprecated": false,
"description": "Extends `glob` with support for multiple patterns and exposes a Promise API",
"devDependencies": {
"ava": "*",
"fast-glob": "^1.0.1",
"glob-stream": "^6.1.0",
"globby": "github:sindresorhus/globby#master",
"matcha": "^0.7.0",
"rimraf": "^2.2.8",
"xo": "^0.18.0"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js",
"gitignore.js"
],
"homepage": "https://github.com/sindresorhus/globby#readme",
"keywords": [
"all",
"array",
"directories",
"dirs",
"expand",
"files",
"filesystem",
"filter",
"find",
"fnmatch",
"folders",
"fs",
"glob",
"globbing",
"globs",
"gulpfriendly",
"match",
"matcher",
"minimatch",
"multi",
"multiple",
"paths",
"pattern",
"patterns",
"traverse",
"util",
"utility",
"wildcard",
"wildcards",
"promise",
"gitignore",
"git"
],
"license": "MIT",
"name": "globby",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/globby.git"
},
"scripts": {
"bench": "npm update glob-stream fast-glob && matcha bench.js",
"test": "xo && ava"
},
"version": "7.1.1"
}
+156
View File
@@ -0,0 +1,156 @@
# globby [![Build Status](https://travis-ci.org/sindresorhus/globby.svg?branch=master)](https://travis-ci.org/sindresorhus/globby)
> User-friendly glob matching
Based on [`glob`](https://github.com/isaacs/node-glob), but adds a bunch of useful features and a nicer API.
## Features
- Promise API
- Multiple patterns
- Negated patterns: `['foo*', '!foobar']`
- Expands directories: `dir``dir/**/*`
- Supports `.gitignore`
## Install
```
$ npm install globby
```
## Usage
```
├── unicorn
├── cake
└── rainbow
```
```js
const globby = require('globby');
(async () => {
const paths = await globby(['*', '!cake']);
console.log(paths);
//=> ['unicorn', 'rainbow']
})();
```
## API
### globby(patterns, [options])
Returns a `Promise<Array>` of matching paths.
#### patterns
Type: `string` `Array`
See supported `minimatch` [patterns](https://github.com/isaacs/minimatch#usage).
#### options
Type: `Object`
See the [`node-glob` options](https://github.com/isaacs/node-glob#options) in addition to the ones below.
One difference is that `nodir` is `true` by default here.
##### expandDirectories
Type: `boolean` `Array` `Object`<br>
Default: `true`
If set to `true`, `globby` will automatically glob directories for you. If you define an `Array` it will only glob files that matches the patterns inside the `Array`. You can also define an `Object` with `files` and `extensions` like below:
```js
(async () => {
const paths = await globby('images', {
expandDirectories: {
files: ['cat', 'unicorn', '*.jpg'],
extensions: ['png']
}
});
console.log(paths);
//=> ['cat.png', 'unicorn.png', 'cow.jpg', 'rainbow.jpg']
})();
```
Note that if you set this option to `false`, you won't get back matched directories unless you set `nodir: false`.
##### gitignore
Type: `boolean`<br>
Default: `false`
Respect ignore patterns in `.gitignore` files that apply to the globbed files.
### globby.sync(patterns, [options])
Returns an `Array` of matching paths.
### globby.generateGlobTasks(patterns, [options])
Returns an `Array<Object>` in the format `{pattern: string, opts: Object}`, which can be passed as arguments to [`node-glob`](https://github.com/isaacs/node-glob). This is useful for other globbing-related packages.
Note that you should avoid running the same tasks multiple times as they contain a file system cache. Instead, run this method each time to ensure file system changes are taken into consideration.
### globby.hasMagic(patterns, [options])
Returns a `boolean` of whether there are any special glob characters in the `patterns`.
Note that the options affect the results. If `noext: true` is set, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}`, then that is considered magical, unless `nobrace: true` is set.
### globby.gitignore([options])
Returns a `Promise<(path: string) => boolean>` indicating wether a given path is ignored via a `.gitignore` file.
Takes `cwd?: string` and `ignore?: string[]` as options. `.gitignore` files matched by the ignore config are not
used for the resulting filter function.
```js
const {gitignore} = require('globby');
(async () => {
const isIgnored = await gitignore();
console.log(isIgnored('some/file'));
})();
```
### globby.gitignore.sync([options])
Returns a `(path: string) => boolean` indicating wether a given path is ignored via a `.gitignore` file.
Takes the same options as `globby.gitignore`.
## Globbing patterns
Just a quick overview.
- `*` matches any number of characters, but not `/`
- `?` matches a single character, but not `/`
- `**` matches any number of characters, including `/`, as long as it's the only thing in a path part
- `{}` allows for a comma-separated list of "or" expressions
- `!` at the beginning of a pattern will negate the match
[Various patterns and expected matches.](https://github.com/sindresorhus/multimatch/blob/master/test/test.js)
## Related
- [multimatch](https://github.com/sindresorhus/multimatch) - Match against a list instead of the filesystem
- [matcher](https://github.com/sindresorhus/matcher) - Simple wildcard matching
- [del](https://github.com/sindresorhus/del) - Delete files and directories
- [make-dir](https://github.com/sindresorhus/make-dir) - Make a directory and its parents if needed
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+262
View File
@@ -0,0 +1,262 @@
<table><thead>
<tr>
<th>Linux</th>
<th>OS X</th>
<th>Windows</th>
<th>Coverage</th>
<th>Downloads</th>
</tr>
</thead><tbody><tr>
<td colspan="2" align="center">
<a href="https://travis-ci.org/kaelzhang/node-ignore">
<img
src="https://travis-ci.org/kaelzhang/node-ignore.svg?branch=master"
alt="Build Status" /></a>
</td>
<td align="center">
<a href="https://ci.appveyor.com/project/kaelzhang/node-ignore">
<img
src="https://ci.appveyor.com/api/projects/status/github/kaelzhang/node-ignore?branch=master&svg=true"
alt="Windows Build Status" /></a>
</td>
<td align="center">
<a href="https://codecov.io/gh/kaelzhang/node-ignore">
<img
src="https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg"
alt="Coverage Status" /></a>
</td>
<td align="center">
<a href="https://www.npmjs.org/package/ignore">
<img
src="http://img.shields.io/npm/dm/ignore.svg"
alt="npm module downloads per month" /></a>
</td>
</tr></tbody></table>
# ignore
`ignore` is a manager, filter and parser which implemented in pure JavaScript according to the .gitignore [spec](http://git-scm.com/docs/gitignore).
Pay attention that [`minimatch`](https://www.npmjs.org/package/minimatch) does not work in the gitignore way. To filter filenames according to .gitignore file, I recommend this module.
##### Tested on
- Linux + Node: `0.8` - `7.x`
- Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor.
Actually, `ignore` does not rely on any versions of node specially.
## Table Of Main Contents
- [Usage](#usage)
- [Guide for 2.x -> 3.x](#upgrade-2x---3x)
- [Contributing](#contributing)
- Related Packages
- [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules.
## Usage
```js
const ignore = require('ignore')
const ig = ignore().add(['.abc/*', '!.abc/d/'])
```
### Filter the given paths
```js
const paths = [
'.abc/a.js', // filtered out
'.abc/d/e.js' // included
]
ig.filter(paths) // ['.abc/d/e.js']
ig.ignores('.abc/a.js') // true
```
### As the filter function
```js
paths.filter(ig.createFilter()); // ['.abc/d/e.js']
```
### Win32 paths will be handled
```js
ig.filter(['.abc\\a.js', '.abc\\d\\e.js'])
// if the code above runs on windows, the result will be
// ['.abc\\d\\e.js']
```
## Why another ignore?
- `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family.
- `ignore` only contains utility methods to filter paths according to the specified ignore rules, so
- `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations.
- `ignore` don't cares about sub-modules of git projects.
- Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as:
- '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'.
- '`**/foo`' should match '`foo`' anywhere.
- Prevent re-including a file if a parent directory of that file is excluded.
- Handle trailing whitespaces:
- `'a '`(one space) should not match `'a '`(two spaces).
- `'a \ '` matches `'a '`
- All test cases are verified with the result of `git check-ignore`.
## Methods
### .add(pattern)
### .add(patterns)
- **pattern** `String|Ignore` An ignore pattern string, or the `Ignore` instance
- **patterns** `Array.<pattern>` Array of ignore patterns.
Adds a rule or several rules to the current manager.
Returns `this`
Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename.
```js
ignore().add('#abc').ignores('#abc') // false
ignore().add('\#abc').ignores('#abc') // true
```
`pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file:
```js
ignore()
.add(fs.readFileSync(filenameOfGitignore).toString())
.filter(filenames)
```
`pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance.
### <strike>.addIgnoreFile(path)</strike>
REMOVED in `3.x` for now.
To upgrade `ignore@2.x` up to `3.x`, use
```js
const fs = require('fs')
if (fs.existsSync(filename)) {
ignore().add(fs.readFileSync(filename).toString())
}
```
instead.
### .ignores(pathname)
> new in 3.2.0
Returns `Boolean` whether `pathname` should be ignored.
```js
ig.ignores('.abc/a.js') // true
```
### .filter(paths)
Filters the given array of pathnames, and returns the filtered array.
- **paths** `Array.<path>` The array of `pathname`s to be filtered.
**NOTICE** that:
- `pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory.
```js
// WRONG
ig.ignores('./abc')
// WRONG, for it will never happen.
// If the gitignore rule locates at the root directory,
// `'/abc'` should be changed to `'abc'`.
// ```
// path.relative('/', '/abc') -> 'abc'
// ```
ig.ignores('/abc')
// Right
ig.ignores('abc')
// Right
ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc'
```
- In other words, each `pathname` here should be a relative path to the directory of the git ignore rules.
Suppose the dir structure is:
```
/path/to/your/repo
|-- a
| |-- a.js
|
|-- .b
|
|-- .c
|-- .DS_store
```
Then the `paths` might be like this:
```js
[
'a/a.js'
'.b',
'.c/.DS_store'
]
```
Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory:
```js
const glob = require('glob')
glob('**', {
// Adds a / character to directory matches.
mark: true
}, (err, files) => {
if (err) {
return console.error(err)
}
let filtered = ignore().add(patterns).filter(files)
console.log(filtered)
})
```
### .createFilter()
Creates a filter function which could filter an array of paths with `Array.prototype.filter`.
Returns `function(path)` the filter function.
****
## Upgrade 2.x -> 3.x
- All `options` of 2.x are unnecessary and removed, so just remove them.
- `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed.
- `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details.
****
## Contributing
The code of `node-ignore` is based on es6 and babel, but babel and its preset is not included in the `dependencies` field of package.json, so that the installation process of test cases will not fail in older versions of node.
So use `bash install.sh` to install dependencies and `bash test.sh` to run test cases in your local machine.
#### Collaborators
- [SamyPesse](https://github.com/SamyPesse) *Samy Pessé*
- [azproduction](https://github.com/azproduction) *Mikhail Davydov*
- [TrySound](https://github.com/TrySound) *Bogdan Chadkin*
- [JanMattner](https://github.com/JanMattner) *Jan Mattner*
+425
View File
@@ -0,0 +1,425 @@
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
module.exports = function () {
return new IgnoreBase();
};
// A simple implementation of make-array
function make_array(subject) {
return Array.isArray(subject) ? subject : [subject];
}
var REGEX_BLANK_LINE = /^\s+$/;
var REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\\!/;
var REGEX_LEADING_EXCAPED_HASH = /^\\#/;
var SLASH = '/';
var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
/* istanbul ignore next */
: 'node-ignore';
var IgnoreBase = function () {
function IgnoreBase() {
_classCallCheck(this, IgnoreBase);
this._rules = [];
this[KEY_IGNORE] = true;
this._initCache();
}
_createClass(IgnoreBase, [{
key: '_initCache',
value: function _initCache() {
this._cache = {};
}
// @param {Array.<string>|string|Ignore} pattern
}, {
key: 'add',
value: function add(pattern) {
this._added = false;
if (typeof pattern === 'string') {
pattern = pattern.split(/\r?\n/g);
}
make_array(pattern).forEach(this._addPattern, this);
// Some rules have just added to the ignore,
// making the behavior changed.
if (this._added) {
this._initCache();
}
return this;
}
// legacy
}, {
key: 'addPattern',
value: function addPattern(pattern) {
return this.add(pattern);
}
}, {
key: '_addPattern',
value: function _addPattern(pattern) {
// #32
if (pattern && pattern[KEY_IGNORE]) {
this._rules = this._rules.concat(pattern._rules);
this._added = true;
return;
}
if (this._checkPattern(pattern)) {
var rule = this._createRule(pattern);
this._added = true;
this._rules.push(rule);
}
}
}, {
key: '_checkPattern',
value: function _checkPattern(pattern) {
// > A blank line matches no files, so it can serve as a separator for readability.
return pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern)
// > A line starting with # serves as a comment.
&& pattern.indexOf('#') !== 0;
}
}, {
key: 'filter',
value: function filter(paths) {
var _this = this;
return make_array(paths).filter(function (path) {
return _this._filter(path);
});
}
}, {
key: 'createFilter',
value: function createFilter() {
var _this2 = this;
return function (path) {
return _this2._filter(path);
};
}
}, {
key: 'ignores',
value: function ignores(path) {
return !this._filter(path);
}
}, {
key: '_createRule',
value: function _createRule(pattern) {
var origin = pattern;
var negative = false;
// > An optional prefix "!" which negates the pattern;
if (pattern.indexOf('!') === 0) {
negative = true;
pattern = pattern.substr(1);
}
pattern = pattern
// > Put a backslash ("\") in front of the first "!" for patterns that begin with a literal "!", for example, `"\!important!.txt"`.
.replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!')
// > Put a backslash ("\") in front of the first hash for patterns that begin with a hash.
.replace(REGEX_LEADING_EXCAPED_HASH, '#');
var regex = make_regex(pattern, negative);
return {
origin: origin,
pattern: pattern,
negative: negative,
regex: regex
};
}
// @returns `Boolean` true if the `path` is NOT ignored
}, {
key: '_filter',
value: function _filter(path, slices) {
if (!path) {
return false;
}
if (path in this._cache) {
return this._cache[path];
}
if (!slices) {
// path/to/a.js
// ['path', 'to', 'a.js']
slices = path.split(SLASH);
}
slices.pop();
return this._cache[path] = slices.length
// > It is not possible to re-include a file if a parent directory of that file is excluded.
// If the path contains a parent directory, check the parent first
? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path)
// Or only test the path
: this._test(path);
}
// @returns {Boolean} true if a file is NOT ignored
}, {
key: '_test',
value: function _test(path) {
// Explicitly define variable type by setting matched to `0`
var matched = 0;
this._rules.forEach(function (rule) {
// if matched = true, then we only test negative rules
// if matched = false, then we test non-negative rules
if (!(matched ^ rule.negative)) {
matched = rule.negative ^ rule.regex.test(path);
}
});
return !matched;
}
}]);
return IgnoreBase;
}();
// > If the pattern ends with a slash,
// > it is removed for the purpose of the following description,
// > but it would only find a match with a directory.
// > In other words, foo/ will match a directory foo and paths underneath it,
// > but will not match a regular file or a symbolic link foo
// > (this is consistent with the way how pathspec works in general in Git).
// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
// you could use option `mark: true` with `glob`
// '`foo/`' should not continue with the '`..`'
var DEFAULT_REPLACER_PREFIX = [
// > Trailing spaces are ignored unless they are quoted with backslash ("\")
[
// (a\ ) -> (a )
// (a ) -> (a)
// (a \ ) -> (a )
/\\?\s+$/, function (match) {
return match.indexOf('\\') === 0 ? ' ' : '';
}],
// replace (\ ) with ' '
[/\\\s/g, function () {
return ' ';
}],
// Escape metacharacters
// which is written down by users but means special for regular expressions.
// > There are 12 characters with special meanings:
// > - the backslash \,
// > - the caret ^,
// > - the dollar sign $,
// > - the period or dot .,
// > - the vertical bar or pipe symbol |,
// > - the question mark ?,
// > - the asterisk or star *,
// > - the plus sign +,
// > - the opening parenthesis (,
// > - the closing parenthesis ),
// > - and the opening square bracket [,
// > - the opening curly brace {,
// > These special characters are often called "metacharacters".
[/[\\\^$.|?*+()\[{]/g, function (match) {
return '\\' + match;
}],
// leading slash
[
// > A leading slash matches the beginning of the pathname.
// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
// A leading slash matches the beginning of the pathname
/^\//, function () {
return '^';
}],
// replace special metacharacter slash after the leading slash
[/\//g, function () {
return '\\/';
}], [
// > A leading "**" followed by a slash means match in all directories.
// > For example, "**/foo" matches file or directory "foo" anywhere,
// > the same as pattern "foo".
// > "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".
// Notice that the '*'s have been replaced as '\\*'
/^\^*\\\*\\\*\\\//,
// '**/foo' <-> 'foo'
function () {
return '^(?:.*\\/)?';
}]];
var DEFAULT_REPLACER_SUFFIX = [
// starting
[
// there will be no leading '/' (which has been replaced by section "leading slash")
// If starts with '**', adding a '^' to the regular expression also works
/^(?=[^\^])/, function () {
return !/\/(?!$)/.test(this)
// > If the pattern does not contain a slash /, Git treats it as a shell glob pattern
// Actually, if there is only a trailing slash, git also treats it as a shell glob pattern
? '(?:^|\\/)'
// > Otherwise, Git treats the pattern as a shell glob suitable for consumption by fnmatch(3)
: '^';
}],
// two globstars
[
// Use lookahead assertions so that we could match more than one `'/**'`
/\\\/\\\*\\\*(?=\\\/|$)/g,
// Zero, one or several directories
// should not use '*', or it will be replaced by the next replacer
// Check if it is not the last `'/**'`
function (match, index, str) {
return index + 6 < str.length
// case: /**/
// > A slash followed by two consecutive asterisks then a slash matches zero or more directories.
// > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
// '/**/'
? '(?:\\/[^\\/]+)*'
// case: /**
// > A trailing `"/**"` matches everything inside.
// #21: everything inside but it should not include the current folder
: '\\/.+';
}],
// intermediate wildcards
[
// Never replace escaped '*'
// ignore rule '\*' will match the path '*'
// 'abc.*/' -> go
// 'abc.*' -> skip this rule
/(^|[^\\]+)\\\*(?=.+)/g,
// '*.js' matches '.js'
// '*.js' doesn't match 'abc'
function (match, p1) {
return p1 + '[^\\/]*';
}],
// trailing wildcard
[/(\^|\\\/)?\\\*$/, function (match, p1) {
return (p1
// '\^':
// '/*' does not match ''
// '/*' does not match everything
// '\\\/':
// 'abc/*' does not match 'abc/'
? p1 + '[^/]+'
// 'a*' matches 'a'
// 'a*' matches 'aa'
: '[^/]*') + '(?=$|\\/$)';
}], [
// unescape
/\\\\\\/g, function () {
return '\\';
}]];
var POSITIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [
// 'f'
// matches
// - /f(end)
// - /f/
// - (start)f(end)
// - (start)f/
// doesn't match
// - oof
// - foo
// pseudo:
// -> (^|/)f(/|$)
// ending
[
// 'js' will not match 'js.'
// 'ab' will not match 'abc'
/(?:[^*\/])$/,
// 'js*' will not match 'a.js'
// 'js/' will not match 'a.js'
// 'js' will match 'a.js' and 'a.js/'
function (match) {
return match + '(?=$|\\/)';
}]], DEFAULT_REPLACER_SUFFIX);
var NEGATIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [
// #24, #38
// The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
// A negative pattern without a trailing wildcard should not
// re-include the things inside that directory.
// eg:
// ['node_modules/*', '!node_modules']
// should ignore `node_modules/a.js`
[/(?:[^*])$/, function (match) {
return match + '(?=$|\\/$)';
}]], DEFAULT_REPLACER_SUFFIX);
// A simple cache, because an ignore rule only has only one certain meaning
var cache = {};
// @param {pattern}
function make_regex(pattern, negative) {
var r = cache[pattern];
if (r) {
return r;
}
var replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
var source = replacers.reduce(function (prev, current) {
return prev.replace(current[0], current[1].bind(pattern));
}, pattern);
return cache[pattern] = new RegExp(source, 'i');
}
// Windows
// --------------------------------------------------------------
/* istanbul ignore if */
if (
// Detect `process` so that it can run in browsers.
typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
var filter = IgnoreBase.prototype._filter;
var make_posix = function make_posix(str) {
return (/^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/')
);
};
IgnoreBase.prototype._filter = function (path, slices) {
path = make_posix(path);
return filter.call(this, path, slices);
};
}
+41
View File
@@ -0,0 +1,41 @@
interface Ignore {
/**
* Adds a rule rules to the current manager.
* @param {string | Ignore} pattern
* @returns IgnoreBase
*/
add(pattern: string | Ignore): Ignore
/**
* Adds several rules to the current manager.
* @param {string[]} patterns
* @returns IgnoreBase
*/
add(patterns: (string | Ignore)[]): Ignore
/**
* Filters the given array of pathnames, and returns the filtered array.
* NOTICE that each path here should be a relative path to the root of your repository.
* @param paths the array of paths to be filtered.
* @returns The filtered array of paths
*/
filter(paths: string[]): string[]
/**
* Creates a filter function which could filter
* an array of paths with Array.prototype.filter.
*/
createFilter(): (path: string) => boolean
/**
* Returns Boolean whether pathname should be ignored.
* @param {string} pathname a path to check
* @returns boolean
*/
ignores(pathname: string): boolean
}
/**
* Creates new ignore manager.
*/
declare function ignore(): Ignore
export default ignore
+84
View File
@@ -0,0 +1,84 @@
{
"_from": "ignore@^3.3.5",
"_id": "ignore@3.3.10",
"_inBundle": false,
"_integrity": "sha512-Pgs951kaMm5GXP7MOvxERINe3gsaVjUWFm+UZPSq9xYriQAksyhg0csnS0KXSNRD5NmNdapXEpjxG49+AKh/ug==",
"_location": "/copy-webpack-plugin/ignore",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "ignore@^3.3.5",
"name": "ignore",
"escapedName": "ignore",
"rawSpec": "^3.3.5",
"saveSpec": null,
"fetchSpec": "^3.3.5"
},
"_requiredBy": [
"/copy-webpack-plugin/globby"
],
"_resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.10.tgz",
"_shasum": "0a97fb876986e8081c631160f8f9f389157f0043",
"_spec": "ignore@^3.3.5",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/copy-webpack-plugin/node_modules/globby",
"author": {
"name": "kael"
},
"bugs": {
"url": "https://github.com/kaelzhang/node-ignore/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Ignore is a manager and filter for .gitignore rules.",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"chai": "~1.7.2",
"codecov": "^3.0.2",
"istanbul": "^0.4.5",
"mkdirp": "^0.5.1",
"mocha": "~1.13.0",
"pre-suf": "^1.0.4",
"rimraf": "^2.6.2",
"spawn-sync": "^1.0.15",
"tmp": "0.0.33",
"typescript": "^2.9.2"
},
"files": [
"ignore.js",
"index.d.ts"
],
"homepage": "https://github.com/kaelzhang/node-ignore#readme",
"keywords": [
"ignore",
".gitignore",
"gitignore",
"npmignore",
"rules",
"manager",
"filter",
"regexp",
"regex",
"fnmatch",
"glob",
"asterisks",
"regular-expression"
],
"license": "MIT",
"main": "./ignore.js",
"name": "ignore",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/kaelzhang/node-ignore.git"
},
"scripts": {
"build": "babel -o ignore.js index.js",
"cov-report": "istanbul report",
"prepublish": "npm run build",
"test": "npm run tsc && npm run build && istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec ./test/ignore.js && codecov",
"test-no-cov": "npm run tsc && npm run build && mocha --reporter spec ./test/ignore.js",
"tsc": "tsc ./test/ts/simple.ts"
},
"version": "3.3.10"
}
+84
View File
@@ -0,0 +1,84 @@
'use strict';
const processFn = (fn, opts) => function () {
const P = opts.promiseModule;
const args = new Array(arguments.length);
for (let i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
return new P((resolve, reject) => {
if (opts.errorFirst) {
args.push(function (err, result) {
if (opts.multiArgs) {
const results = new Array(arguments.length - 1);
for (let i = 1; i < arguments.length; i++) {
results[i - 1] = arguments[i];
}
if (err) {
results.unshift(err);
reject(results);
} else {
resolve(results);
}
} else if (err) {
reject(err);
} else {
resolve(result);
}
});
} else {
args.push(function (result) {
if (opts.multiArgs) {
const results = new Array(arguments.length - 1);
for (let i = 0; i < arguments.length; i++) {
results[i] = arguments[i];
}
resolve(results);
} else {
resolve(result);
}
});
}
fn.apply(this, args);
});
};
module.exports = (obj, opts) => {
opts = Object.assign({
exclude: [/.+(Sync|Stream)$/],
errorFirst: true,
promiseModule: Promise
}, opts);
const filter = key => {
const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key);
return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
};
let ret;
if (typeof obj === 'function') {
ret = function () {
if (opts.excludeMain) {
return obj.apply(this, arguments);
}
return processFn(obj, opts).apply(this, arguments);
};
} else {
ret = Object.create(Object.getPrototypeOf(obj));
}
for (const key in obj) { // eslint-disable-line guard-for-in
const x = obj[key];
ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x;
}
return ret;
};
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
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.
+83
View File
@@ -0,0 +1,83 @@
{
"_from": "pify@^3.0.0",
"_id": "pify@3.0.0",
"_inBundle": false,
"_integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=",
"_location": "/copy-webpack-plugin/pify",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "pify@^3.0.0",
"name": "pify",
"escapedName": "pify",
"rawSpec": "^3.0.0",
"saveSpec": null,
"fetchSpec": "^3.0.0"
},
"_requiredBy": [
"/copy-webpack-plugin/globby"
],
"_resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz",
"_shasum": "e5a4acd2c101fdf3d9a4d07f0dbc4db49dd28176",
"_spec": "pify@^3.0.0",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/copy-webpack-plugin/node_modules/globby",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/pify/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Promisify a callback-style function",
"devDependencies": {
"ava": "*",
"pinkie-promise": "^2.0.0",
"v8-natives": "^1.0.0",
"xo": "*"
},
"engines": {
"node": ">=4"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/pify#readme",
"keywords": [
"promise",
"promises",
"promisify",
"all",
"denodify",
"denodeify",
"callback",
"cb",
"node",
"then",
"thenify",
"convert",
"transform",
"wrap",
"wrapper",
"bind",
"to",
"async",
"await",
"es2015",
"bluebird"
],
"license": "MIT",
"name": "pify",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/pify.git"
},
"scripts": {
"optimization-test": "node --allow-natives-syntax optimization-test.js",
"test": "xo && ava && npm run optimization-test"
},
"version": "3.0.0"
}
+131
View File
@@ -0,0 +1,131 @@
# pify [![Build Status](https://travis-ci.org/sindresorhus/pify.svg?branch=master)](https://travis-ci.org/sindresorhus/pify)
> Promisify a callback-style function
## Install
```
$ npm install --save pify
```
## Usage
```js
const fs = require('fs');
const pify = require('pify');
// Promisify a single function
pify(fs.readFile)('package.json', 'utf8').then(data => {
console.log(JSON.parse(data).name);
//=> 'pify'
});
// Promisify all methods in a module
pify(fs).readFile('package.json', 'utf8').then(data => {
console.log(JSON.parse(data).name);
//=> 'pify'
});
```
## API
### pify(input, [options])
Returns a `Promise` wrapped version of the supplied function or module.
#### input
Type: `Function` `Object`
Callback-style function or module whose methods you want to promisify.
#### options
##### multiArgs
Type: `boolean`<br>
Default: `false`
By default, the promisified function will only return the second argument from the callback, which works fine for most APIs. This option can be useful for modules like `request` that return multiple arguments. Turning this on will make it return an array of all arguments from the callback, excluding the error argument, instead of just the second argument. This also applies to rejections, where it returns an array of all the callback arguments, including the error.
```js
const request = require('request');
const pify = require('pify');
pify(request, {multiArgs: true})('https://sindresorhus.com').then(result => {
const [httpResponse, body] = result;
});
```
##### include
Type: `string[]` `RegExp[]`
Methods in a module to promisify. Remaining methods will be left untouched.
##### exclude
Type: `string[]` `RegExp[]`<br>
Default: `[/.+(Sync|Stream)$/]`
Methods in a module **not** to promisify. Methods with names ending with `'Sync'` are excluded by default.
##### excludeMain
Type: `boolean`<br>
Default: `false`
If given module is a function itself, it will be promisified. Turn this option on if you want to promisify only methods of the module.
```js
const pify = require('pify');
function fn() {
return true;
}
fn.method = (data, callback) => {
setImmediate(() => {
callback(null, data);
});
};
// Promisify methods but not `fn()`
const promiseFn = pify(fn, {excludeMain: true});
if (promiseFn()) {
promiseFn.method('hi').then(data => {
console.log(data);
});
}
```
##### errorFirst
Type: `boolean`<br>
Default: `true`
Whether the callback has an error as the first argument. You'll want to set this to `false` if you're dealing with an API that doesn't have an error as the first argument, like `fs.exists()`, some browser APIs, Chrome Extension APIs, etc.
##### promiseModule
Type: `Function`
Custom promise module to use instead of the native one.
Check out [`pinkie-promise`](https://github.com/floatdrop/pinkie-promise) if you need a tiny promise polyfill.
## Related
- [p-event](https://github.com/sindresorhus/p-event) - Promisify an event by waiting for it to be emitted
- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently
- [More…](https://github.com/sindresorhus/promise-fun)
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+134
View File
@@ -0,0 +1,134 @@
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<a name="1.0.0"></a>
# [1.0.0](https://github.com/webpack-contrib/schema-utils/compare/v0.4.7...v1.0.0) (2018-08-07)
### Features
* **src:** add support for custom error messages ([#33](https://github.com/webpack-contrib/schema-utils/issues/33)) ([1cbe4ef](https://github.com/webpack-contrib/schema-utils/commit/1cbe4ef))
<a name="0.4.7"></a>
## [0.4.7](https://github.com/webpack-contrib/schema-utils/compare/v0.4.6...v0.4.7) (2018-08-07)
### Bug Fixes
* **src:** `node >= v4.0.0` support ([#32](https://github.com/webpack-contrib/schema-utils/issues/32)) ([cb13dd4](https://github.com/webpack-contrib/schema-utils/commit/cb13dd4))
<a name="0.4.6"></a>
## [0.4.6](https://github.com/webpack-contrib/schema-utils/compare/v0.4.5...v0.4.6) (2018-08-06)
### Bug Fixes
* **package:** remove lockfile ([#28](https://github.com/webpack-contrib/schema-utils/issues/28)) ([69f1a81](https://github.com/webpack-contrib/schema-utils/commit/69f1a81))
* **package:** remove unnecessary `webpack` dependency ([#26](https://github.com/webpack-contrib/schema-utils/issues/26)) ([532eaa5](https://github.com/webpack-contrib/schema-utils/commit/532eaa5))
<a name="0.4.5"></a>
## [0.4.5](https://github.com/webpack-contrib/schema-utils/compare/v0.4.4...v0.4.5) (2018-02-13)
### Bug Fixes
* **CHANGELOG:** update broken links ([4483b9f](https://github.com/webpack-contrib/schema-utils/commit/4483b9f))
* **package:** update broken links ([f2494ba](https://github.com/webpack-contrib/schema-utils/commit/f2494ba))
<a name="0.4.4"></a>
## [0.4.4](https://github.com/webpack-contrib/schema-utils/compare/v0.4.3...v0.4.4) (2018-02-13)
### Bug Fixes
* **package:** update `dependencies` ([#22](https://github.com/webpack-contrib/schema-utils/issues/22)) ([3aecac6](https://github.com/webpack-contrib/schema-utils/commit/3aecac6))
<a name="0.4.3"></a>
## [0.4.3](https://github.com/webpack-contrib/schema-utils/compare/v0.4.2...v0.4.3) (2017-12-14)
### Bug Fixes
* **validateOptions:** throw `err` instead of `process.exit(1)` ([#17](https://github.com/webpack-contrib/schema-utils/issues/17)) ([c595eda](https://github.com/webpack-contrib/schema-utils/commit/c595eda))
* **ValidationError:** never return `this` in the ctor ([#16](https://github.com/webpack-contrib/schema-utils/issues/16)) ([c723791](https://github.com/webpack-contrib/schema-utils/commit/c723791))
<a name="0.4.2"></a>
## [0.4.2](https://github.com/webpack-contrib/schema-utils/compare/v0.4.1...v0.4.2) (2017-11-09)
### Bug Fixes
* **validateOptions:** catch `ValidationError` and handle it internally ([#15](https://github.com/webpack-contrib/schema-utils/issues/15)) ([9c5ef5e](https://github.com/webpack-contrib/schema-utils/commit/9c5ef5e))
<a name="0.4.1"></a>
## [0.4.1](https://github.com/webpack-contrib/schema-utils/compare/v0.4.0...v0.4.1) (2017-11-03)
### Bug Fixes
* **ValidationError:** use `Error.captureStackTrace` for `err.stack` handling ([#14](https://github.com/webpack-contrib/schema-utils/issues/14)) ([a6fb974](https://github.com/webpack-contrib/schema-utils/commit/a6fb974))
<a name="0.4.0"></a>
# [0.4.0](https://github.com/webpack-contrib/schema-utils/compare/v0.3.0...v0.4.0) (2017-10-28)
### Features
* add support for `typeof`, `instanceof` (`{Function\|RegExp}`) ([#10](https://github.com/webpack-contrib/schema-utils/issues/10)) ([9f01816](https://github.com/webpack-contrib/schema-utils/commit/9f01816))
<a name="0.3.0"></a>
# [0.3.0](https://github.com/webpack-contrib/schema-utils/compare/v0.2.1...v0.3.0) (2017-04-29)
### Features
* add ValidationError ([#8](https://github.com/webpack-contrib/schema-utils/issues/8)) ([d48f0fb](https://github.com/webpack-contrib/schema-utils/commit/d48f0fb))
<a name="0.2.1"></a>
## [0.2.1](https://github.com/webpack-contrib/schema-utils/compare/v0.2.0...v0.2.1) (2017-03-13)
### Bug Fixes
* Include .babelrc to `files` ([28f0363](https://github.com/webpack-contrib/schema-utils/commit/28f0363))
* Include source to `files` ([43b0f2f](https://github.com/webpack-contrib/schema-utils/commit/43b0f2f))
<a name="0.2.0"></a>
# [0.2.0](https://github.com/webpack-contrib/schema-utils/compare/v0.1.0...v0.2.0) (2017-03-12)
<a name="0.1.0"></a>
# 0.1.0 (2017-03-07)
### Features
* **validations:** add validateOptions module ([ae9b47b](https://github.com/webpack-contrib/schema-utils/commit/ae9b47b))
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
+20
View File
@@ -0,0 +1,20 @@
Copyright JS Foundation and other 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.
+149
View File
@@ -0,0 +1,149 @@
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
[![test][test]][test-url]
[![coverage][cover]][cover-url]
[![chat][chat]][chat-url]
<div align="center">
<a href="http://json-schema.org">
<img width="160" height="160"
src="https://raw.githubusercontent.com/webpack-contrib/schema-utils/master/docs/logo.png">
</a>
<a href="https://github.com/webpack/webpack">
<img width="200" height="200"
src="https://webpack.js.org/assets/icon-square-big.svg">
</a>
<h1>Schema Utils</h1>
</div>
<h2 align="center">Install</h2>
```bash
npm i schema-utils
```
<h2 align="center">Usage</h2>
### `validateOptions`
**`schema.json`**
```js
{
"type": "object",
"properties": {
// Options...
},
"additionalProperties": false
}
```
#### Error Messages (Custom)
**`schema.json`**
```js
{
"type": "object",
"properties": {
"option": {
"type": [ "boolean" ]
}
},
// Overrides the default err.message for option
"errorMessage": {
"option": "should be {Boolean} (https:/github.com/org/repo#anchor)"
}
"additionalProperties": false
}
```
```js
import schema from 'path/to/schema.json'
import validateOptions from 'schema-utils'
validateOptions(schema, options, 'Loader/Plugin Name')
```
<h2 align="center">Examples</h2>
**schema.json**
```json
{
"type": "object",
"properties": {
"name": {
"type": "string"
},
"test": {
"anyOf": [
{ "type": "array" },
{ "type": "string" },
{ "instanceof": "RegExp" }
]
},
"transform": {
"instanceof": "Function"
},
"sourceMap": {
"type": "boolean"
}
},
"additionalProperties": false
}
```
### `Loader`
```js
import { getOptions } from 'loader-utils'
import validateOptions from 'schema-utils'
import schema from 'path/to/schema.json'
function loader (src, map) {
const options = getOptions(this) || {}
validateOptions(schema, options, 'Loader Name')
// Code...
}
```
### `Plugin`
```js
import validateOptions from 'schema-utils'
import schema from 'path/to/schema.json'
class Plugin {
constructor (options) {
validateOptions(schema, options, 'Plugin Name')
this.options = options
}
apply (compiler) {
// Code...
}
}
```
[npm]: https://img.shields.io/npm/v/schema-utils.svg
[npm-url]: https://npmjs.com/package/schema-utils
[node]: https://img.shields.io/node/v/schema-utils.svg
[node-url]: https://nodejs.org
[deps]: https://david-dm.org/webpack-contrib/schema-utils.svg
[deps-url]: https://david-dm.org/webpack-contrib/schema-utils
[test]: http://img.shields.io/travis/webpack-contrib/schema-utils.svg
[test-url]: https://travis-ci.org/webpack-contrib/schema-utils
[cover]: https://codecov.io/gh/webpack-contrib/schema-utils/branch/master/graph/badge.svg
[cover-url]: https://codecov.io/gh/webpack-contrib/schema-utils
[chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
[chat-url]: https://gitter.im/webpack/webpack
@@ -0,0 +1,74 @@
{
"_from": "schema-utils@^1.0.0",
"_id": "schema-utils@1.0.0",
"_inBundle": false,
"_integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==",
"_location": "/copy-webpack-plugin/schema-utils",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "schema-utils@^1.0.0",
"name": "schema-utils",
"escapedName": "schema-utils",
"rawSpec": "^1.0.0",
"saveSpec": null,
"fetchSpec": "^1.0.0"
},
"_requiredBy": [
"/copy-webpack-plugin"
],
"_resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz",
"_shasum": "0b79a93204d7b600d4b2850d1f66c2a34951c770",
"_spec": "schema-utils@^1.0.0",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/copy-webpack-plugin",
"author": {
"name": "webpack Contrib",
"url": "https://github.com/webpack-contrib"
},
"bugs": {
"url": "https://github.com/webpack-contrib/schema-utils/issues"
},
"bundleDependencies": false,
"dependencies": {
"ajv": "^6.1.0",
"ajv-errors": "^1.0.0",
"ajv-keywords": "^3.1.0"
},
"deprecated": false,
"description": "webpack Validation Utils",
"devDependencies": {
"@commitlint/cli": "^7.0.0",
"@commitlint/config-conventional": "^7.0.0",
"@webpack-contrib/eslint-config-webpack": "^2.0.0",
"del-cli": "^1.0.0",
"eslint": "^5.0.0",
"eslint-plugin-import": "^2.0.0",
"eslint-plugin-prettier": "^2.0.0",
"jest": "^21.0.0",
"prettier": "^1.0.0",
"standard-version": "^4.0.0"
},
"engines": {
"node": ">= 4"
},
"files": [
"src"
],
"homepage": "https://github.com/webpack-contrib/schema-utils",
"license": "MIT",
"main": "src/index.js",
"name": "schema-utils",
"repository": {
"type": "git",
"url": "git+https://github.com/webpack-contrib/schema-utils.git"
},
"scripts": {
"clean": "del-cli coverage",
"commits": "commitlint --from $(git rev-list --tags --max-count=1)",
"lint": "eslint --cache src test",
"release": "npm run commits && standard-version",
"test": "jest --env node --verbose --coverage"
},
"version": "1.0.0"
}
@@ -0,0 +1,30 @@
/* eslint-disable
strict,
no-param-reassign
*/
'use strict';
class ValidationError extends Error {
constructor(errors, name) {
super();
this.name = 'ValidationError';
this.message = `${name || ''} Invalid Options\n\n`;
this.errors = errors.map((err) => {
err.dataPath = err.dataPath.replace(/\//g, '.');
return err;
});
this.errors.forEach((err) => {
this.message += `options${err.dataPath} ${err.message}\n`;
});
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = ValidationError;
@@ -0,0 +1,9 @@
/* eslint-disable
strict
*/
'use strict';
const validateOptions = require('./validateOptions');
module.exports = validateOptions;
@@ -0,0 +1,38 @@
/* eslint-disable
strict,
no-param-reassign
*/
'use strict';
const fs = require('fs');
const path = require('path');
const Ajv = require('ajv');
const errors = require('ajv-errors');
const keywords = require('ajv-keywords');
const ValidationError = require('./ValidationError');
const ajv = new Ajv({
allErrors: true,
jsonPointers: true,
});
errors(ajv);
keywords(ajv, ['instanceof', 'typeof']);
const validateOptions = (schema, options, name) => {
if (typeof schema === 'string') {
schema = fs.readFileSync(path.resolve(schema), 'utf8');
schema = JSON.parse(schema);
}
if (!ajv.validate(schema, options)) {
throw new ValidationError(ajv.errors, name);
}
return true;
};
module.exports = validateOptions;
@@ -0,0 +1,27 @@
Copyright 2014 Yahoo! Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yahoo! Inc. nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,143 @@
Serialize JavaScript
====================
Serialize JavaScript to a _superset_ of JSON that includes regular expressions, dates and functions.
[![npm Version][npm-badge]][npm]
[![Dependency Status][david-badge]][david]
[![Build Status][travis-badge]][travis]
## Overview
The code in this package began its life as an internal module to [express-state][]. To expand its usefulness, it now lives as `serialize-javascript` — an independent package on npm.
You're probably wondering: **What about `JSON.stringify()`!?** We've found that sometimes we need to serialize JavaScript **functions**, **regexps**, **dates**, **sets** or **maps**. A great example is a web app that uses client-side URL routing where the route definitions are regexps that need to be shared from the server to the client. But this module is also great for communicating between node processes.
The string returned from this package's single export function is literal JavaScript which can be saved to a `.js` file, or be embedded into an HTML document by making the content of a `<script>` element.
> **HTML characters and JavaScript line terminators are escaped automatically.**
Please note that serialization for ES6 Sets & Maps requires support for `Array.from` (not available in IE or Node < 0.12), or an `Array.from` polyfill.
## Installation
Install using npm:
```shell
$ npm install serialize-javascript
```
## Usage
```js
var serialize = require('serialize-javascript');
serialize({
str : 'string',
num : 0,
obj : {foo: 'foo'},
arr : [1, 2, 3],
bool : true,
nil : null,
undef: undefined,
date: new Date("Thu, 28 Apr 2016 22:02:17 GMT"),
map: new Map([['hello', 'world']]),
set: new Set([123, 456]),
fn: function echo(arg) { return arg; },
re: /([^\s]+)/g
});
```
The above will produce the following string output:
```js
'{"str":"string","num":0,"obj":{"foo":"foo"},"arr":[1,2,3],"bool":true,"nil":null,"undef":undefined,"date":new Date("2016-04-28T22:02:17.000Z"),"map":new Map([["hello","world"]]),"set":new Set([123,456]),"fn":function echo(arg) { return arg; },"re":/([^\s]+)/g}'
```
Note: to produced a beautified string, you can pass an optional second argument to `serialize()` to define the number of spaces to be used for the indentation.
### Automatic Escaping of HTML Characters
A primary feature of this package is to serialize code to a string of literal JavaScript which can be embedded in an HTML document by adding it as the contents of the `<script>` element. In order to make this safe, HTML characters and JavaScript line terminators are escaped automatically.
```js
serialize({
haxorXSS: '</script>'
});
```
The above will produce the following string, HTML-escaped output which is safe to put into an HTML document as it will not cause the inline script element to terminate:
```js
'{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}'
```
> You can pass an optional `unsafe` argument to `serialize()` for straight serialization.
### Options
The `serialize()` function accepts an `options` object as its second argument. All options are being defaulted to `undefined`:
#### `options.space`
This option is the same as the `space` argument that can be passed to [`JSON.stringify`][JSON.stringify]. It can be used to add whitespace and indentation to the serialized output to make it more readable.
```js
serialize(obj, {space: 2});
```
#### `options.isJSON`
This option is a signal to `serialize()` that the object being serialized does not contain any function or regexps values. This enables a hot-path that allows serialization to be over 3x faster. If you're serializing a lot of data, and know its pure JSON, then you can enable this option for a speed-up.
**Note:** That when using this option, the output will still be escaped to protect against XSS.
```js
serialize(obj, {isJSON: true});
```
#### `options.unsafe`
This option is to signal `serialize()` that we want to do a straight conversion, without the XSS protection. This options needs to be explicitly set to `true`. HTML characters and JavaScript line terminators will not be escaped. You will have to roll your own.
```js
serialize(obj, {unsafe: true});
```
#### `options.ignoreFunction`
This option is to signal `serialize()` that we do not want serialize JavaScript function.
Just treat function like `JSON.stringify` do, but other features will work as expected.
```js
serialize(obj, {ignoreFunction: true});
```
## Deserializing
For some use cases you might also need to deserialize the string. This is explicitly not part of this module. However, you can easily write it yourself:
```js
function deserialize(serializedJavascript){
return eval('(' + serializedJavascript + ')');
}
```
**Note:** Don't forget the parentheses around the serialized javascript, as the opening bracket `{` will be considered to be the start of a body.
## License
This software is free to use under the Yahoo! Inc. BSD license.
See the [LICENSE file][LICENSE] for license text and copyright information.
[npm]: https://www.npmjs.org/package/serialize-javascript
[npm-badge]: https://img.shields.io/npm/v/serialize-javascript.svg?style=flat-square
[david]: https://david-dm.org/yahoo/serialize-javascript
[david-badge]: https://img.shields.io/david/yahoo/serialize-javascript.svg?style=flat-square
[travis]: https://travis-ci.org/yahoo/serialize-javascript
[travis-badge]: https://img.shields.io/travis/yahoo/serialize-javascript.svg?style=flat-square
[express-state]: https://github.com/yahoo/express-state
[JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
[LICENSE]: https://github.com/yahoo/serialize-javascript/blob/master/LICENSE
@@ -0,0 +1,210 @@
/*
Copyright (c) 2014, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/
'use strict';
// Generate an internal UID to make the regexp pattern harder to guess.
var UID = Math.floor(Math.random() * 0x10000000000).toString(16);
var PLACE_HOLDER_REGEXP = new RegExp('"@__(F|R|D|M|S|U)-' + UID + '-(\\d+)__@"', 'g');
var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g;
var IS_PURE_FUNCTION = /function.*?\(/;
var IS_ARROW_FUNCTION = /.*?=>.*?/;
var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g;
var RESERVED_SYMBOLS = ['*', 'async'];
// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their
// Unicode char counterparts which are safe to use in JavaScript strings.
var ESCAPED_CHARS = {
'<' : '\\u003C',
'>' : '\\u003E',
'/' : '\\u002F',
'\u2028': '\\u2028',
'\u2029': '\\u2029'
};
function escapeUnsafeChars(unsafeChar) {
return ESCAPED_CHARS[unsafeChar];
}
function deleteFunctions(obj){
var functionKeys = [];
for (var key in obj) {
if (typeof obj[key] === "function") {
functionKeys.push(key);
}
}
for (var i = 0; i < functionKeys.length; i++) {
delete obj[functionKeys[i]];
}
}
module.exports = function serialize(obj, options) {
options || (options = {});
// Backwards-compatibility for `space` as the second argument.
if (typeof options === 'number' || typeof options === 'string') {
options = {space: options};
}
var functions = [];
var regexps = [];
var dates = [];
var maps = [];
var sets = [];
var undefs = [];
// Returns placeholders for functions and regexps (identified by index)
// which are later replaced by their string representation.
function replacer(key, value) {
// For nested function
if(options.ignoreFunction){
deleteFunctions(value);
}
if (!value && value !== undefined) {
return value;
}
// If the value is an object w/ a toJSON method, toJSON is called before
// the replacer runs, so we use this[key] to get the non-toJSONed value.
var origValue = this[key];
var type = typeof origValue;
if (type === 'object') {
if(origValue instanceof RegExp) {
return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@';
}
if(origValue instanceof Date) {
return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@';
}
if(origValue instanceof Map) {
return '@__M-' + UID + '-' + (maps.push(origValue) - 1) + '__@';
}
if(origValue instanceof Set) {
return '@__S-' + UID + '-' + (sets.push(origValue) - 1) + '__@';
}
}
if (type === 'function') {
return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@';
}
if (type === 'undefined') {
return '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@';
}
return value;
}
function serializeFunc(fn) {
var serializedFn = fn.toString();
if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) {
throw new TypeError('Serializing native function: ' + fn.name);
}
// pure functions, example: {key: function() {}}
if(IS_PURE_FUNCTION.test(serializedFn)) {
return serializedFn;
}
// arrow functions, example: arg1 => arg1+5
if(IS_ARROW_FUNCTION.test(serializedFn)) {
return serializedFn;
}
var argsStartsAt = serializedFn.indexOf('(');
var def = serializedFn.substr(0, argsStartsAt)
.trim()
.split(' ')
.filter(function(val) { return val.length > 0 });
var nonReservedSymbols = def.filter(function(val) {
return RESERVED_SYMBOLS.indexOf(val) === -1
});
// enhanced literal objects, example: {key() {}}
if(nonReservedSymbols.length > 0) {
return (def.indexOf('async') > -1 ? 'async ' : '') + 'function'
+ (def.join('').indexOf('*') > -1 ? '*' : '')
+ serializedFn.substr(argsStartsAt);
}
// arrow functions
return serializedFn;
}
// Check if the parameter is function
if (options.ignoreFunction && typeof obj === "function") {
obj = undefined;
}
// Protects against `JSON.stringify()` returning `undefined`, by serializing
// to the literal string: "undefined".
if (obj === undefined) {
return String(obj);
}
var str;
// Creates a JSON string representation of the value.
// NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args.
if (options.isJSON && !options.space) {
str = JSON.stringify(obj);
} else {
str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
}
// Protects against `JSON.stringify()` returning `undefined`, by serializing
// to the literal string: "undefined".
if (typeof str !== 'string') {
return String(str);
}
// Replace unsafe HTML and invalid JavaScript line terminator chars with
// their safe Unicode char counterpart. This _must_ happen before the
// regexps and functions are serialized and added back to the string.
if (options.unsafe !== true) {
str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
}
if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && undefs.length === 0) {
return str;
}
// Replaces all occurrences of function, regexp, date, map and set placeholders in the
// JSON string with their string representations. If the original value can
// not be found, then `undefined` is used.
return str.replace(PLACE_HOLDER_REGEXP, function (match, type, valueIndex) {
if (type === 'D') {
return "new Date(\"" + dates[valueIndex].toISOString() + "\")";
}
if (type === 'R') {
return regexps[valueIndex].toString();
}
if (type === 'M') {
return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")";
}
if (type === 'S') {
return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")";
}
if (type === 'U') {
return 'undefined'
}
var fn = functions[valueIndex];
return serializeFunc(fn);
});
}
@@ -0,0 +1,61 @@
{
"_from": "serialize-javascript@^2.1.0",
"_id": "serialize-javascript@2.1.0",
"_inBundle": false,
"_integrity": "sha512-a/mxFfU00QT88umAJQsNWOnUKckhNCqOl028N48e7wFmo2/EHpTo9Wso+iJJCMrQnmFvcjto5RJdAHEvVhcyUQ==",
"_location": "/copy-webpack-plugin/serialize-javascript",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "serialize-javascript@^2.1.0",
"name": "serialize-javascript",
"escapedName": "serialize-javascript",
"rawSpec": "^2.1.0",
"saveSpec": null,
"fetchSpec": "^2.1.0"
},
"_requiredBy": [
"/copy-webpack-plugin"
],
"_resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-2.1.0.tgz",
"_shasum": "9310276819efd0eb128258bb341957f6eb2fc570",
"_spec": "serialize-javascript@^2.1.0",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/copy-webpack-plugin",
"author": {
"name": "Eric Ferraiuolo",
"email": "edf@ericf.me"
},
"bugs": {
"url": "https://github.com/yahoo/serialize-javascript/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Serialize JavaScript to a superset of JSON that includes regular expressions and functions.",
"devDependencies": {
"benchmark": "^2.1.4",
"chai": "^4.1.0",
"istanbul": "^0.4.5",
"mocha": "^6.2.0"
},
"homepage": "https://github.com/yahoo/serialize-javascript",
"keywords": [
"serialize",
"serialization",
"javascript",
"js",
"json"
],
"license": "BSD-3-Clause",
"main": "index.js",
"name": "serialize-javascript",
"repository": {
"type": "git",
"url": "git+https://github.com/yahoo/serialize-javascript.git"
},
"scripts": {
"benchmark": "node -v && node test/benchmark/serialize.js",
"test": "istanbul cover -- ./node_modules/mocha/bin/_mocha test/unit/ --reporter spec"
},
"version": "2.1.0"
}
+11
View File
@@ -0,0 +1,11 @@
'use strict';
module.exports = function (str) {
var isExtendedLengthPath = /^\\\\\?\\/.test(str);
var hasNonAscii = /[^\x00-\x80]+/.test(str);
if (isExtendedLengthPath || hasNonAscii) {
return str;
}
return str.replace(/\\/g, '/');
};
+65
View File
@@ -0,0 +1,65 @@
{
"_from": "slash@^1.0.0",
"_id": "slash@1.0.0",
"_inBundle": false,
"_integrity": "sha1-xB8vbDn8FtHNF61LXYlhFK5HDVU=",
"_location": "/copy-webpack-plugin/slash",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "slash@^1.0.0",
"name": "slash",
"escapedName": "slash",
"rawSpec": "^1.0.0",
"saveSpec": null,
"fetchSpec": "^1.0.0"
},
"_requiredBy": [
"/copy-webpack-plugin/globby"
],
"_resolved": "https://registry.npmjs.org/slash/-/slash-1.0.0.tgz",
"_shasum": "c41f2f6c39fc16d1cd17ad4b5d896114ae470d55",
"_spec": "slash@^1.0.0",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/copy-webpack-plugin/node_modules/globby",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/slash/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Convert Windows backslash paths to slash paths",
"devDependencies": {
"mocha": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/sindresorhus/slash#readme",
"keywords": [
"path",
"seperator",
"sep",
"slash",
"backslash",
"windows",
"win"
],
"license": "MIT",
"name": "slash",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/slash.git"
},
"scripts": {
"test": "mocha"
},
"version": "1.0.0"
}
+44
View File
@@ -0,0 +1,44 @@
# slash [![Build Status](https://travis-ci.org/sindresorhus/slash.svg?branch=master)](https://travis-ci.org/sindresorhus/slash)
> Convert Windows backslash paths to slash paths: `foo\\bar` ➔ `foo/bar`
[Forward-slash paths can be used in Windows](http://superuser.com/a/176395/6877) as long as they're not extended-length paths and don't contain any non-ascii characters.
This was created since the `path` methods in Node outputs `\\` paths on Windows.
## Install
```sh
$ npm install --save slash
```
## Usage
```js
var path = require('path');
var slash = require('slash');
var str = path.join('foo', 'bar');
// Unix => foo/bar
// Windows => foo\\bar
slash(str);
// Unix => foo/bar
// Windows => foo/bar
```
## API
### slash(path)
Type: `string`
Accepts a Windows backslash path and returns a slash path.
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)
+128
View File
@@ -0,0 +1,128 @@
{
"_from": "copy-webpack-plugin@^5.0.5",
"_id": "copy-webpack-plugin@5.0.5",
"_inBundle": false,
"_integrity": "sha512-7N68eIoQTyudAuxkfPT7HzGoQ+TsmArN/I3HFwG+lVE3FNzqvZKIiaxtYh4o3BIznioxUvx9j26+Rtsc9htQUQ==",
"_location": "/copy-webpack-plugin",
"_phantomChildren": {
"ajv": "6.10.2",
"ajv-errors": "1.0.1",
"ajv-keywords": "3.4.1",
"array-union": "1.0.2",
"dir-glob": "2.2.2",
"glob": "7.1.6"
},
"_requested": {
"type": "range",
"registry": true,
"raw": "copy-webpack-plugin@^5.0.5",
"name": "copy-webpack-plugin",
"escapedName": "copy-webpack-plugin",
"rawSpec": "^5.0.5",
"saveSpec": null,
"fetchSpec": "^5.0.5"
},
"_requiredBy": [
"/@vue/cli-service"
],
"_resolved": "https://registry.npmjs.org/copy-webpack-plugin/-/copy-webpack-plugin-5.0.5.tgz",
"_shasum": "731df6a837a2ef0f8f8e2345bdfe9b7c62a2da68",
"_spec": "copy-webpack-plugin@^5.0.5",
"_where": "/home/george/citwa/red_de_investigacion_front/first/node_modules/@vue/cli-service",
"author": {
"name": "Len Boyette"
},
"bugs": {
"url": "https://github.com/webpack-contrib/copy-webpack-plugin/issues"
},
"bundleDependencies": false,
"dependencies": {
"cacache": "^12.0.3",
"find-cache-dir": "^2.1.0",
"glob-parent": "^3.1.0",
"globby": "^7.1.1",
"is-glob": "^4.0.1",
"loader-utils": "^1.2.3",
"minimatch": "^3.0.4",
"normalize-path": "^3.0.0",
"p-limit": "^2.2.1",
"schema-utils": "^1.0.0",
"serialize-javascript": "^2.1.0",
"webpack-log": "^2.0.0"
},
"deprecated": false,
"description": "Copy files && directories with webpack",
"devDependencies": {
"@babel/cli": "^7.7.0",
"@babel/core": "^7.7.0",
"@babel/preset-env": "^7.7.1",
"@commitlint/cli": "^8.2.0",
"@commitlint/config-conventional": "^8.2.0",
"@webpack-contrib/defaults": "^5.1.1",
"@webpack-contrib/eslint-config-webpack": "^3.0.0",
"babel-jest": "^24.9.0",
"commitlint-azure-pipelines-cli": "^1.0.2",
"cross-env": "^5.2.1",
"del": "^4.1.1",
"del-cli": "^1.1.0",
"enhanced-resolve": "^4.1.1",
"eslint": "^6.6.0",
"eslint-config-prettier": "^6.5.0",
"eslint-plugin-import": "^2.18.2",
"husky": "^3.0.9",
"is-gzip": "^2.0.0",
"jest": "^24.9.0",
"jest-junit": "^9.0.0",
"lint-staged": "^9.4.2",
"memory-fs": "^0.5.0",
"mkdirp": "^0.5.1",
"npm-run-all": "^4.1.5",
"prettier": "^1.18.2",
"standard-version": "^7.0.0",
"webpack": "^4.41.2"
},
"engines": {
"node": ">= 6.9.0"
},
"files": [
"dist"
],
"homepage": "https://github.com/webpack-contrib/copy-webpack-plugin",
"keywords": [
"webpack",
"plugin",
"transfer",
"move",
"copy"
],
"license": "MIT",
"main": "dist/cjs.js",
"name": "copy-webpack-plugin",
"peerDependencies": {
"webpack": "^4.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/webpack-contrib/copy-webpack-plugin.git"
},
"scripts": {
"build": "cross-env NODE_ENV=production babel src -d dist --ignore \"src/**/*.test.js\" --copy-files",
"clean": "del-cli dist",
"commitlint": "commitlint --from=master",
"defaults": "webpack-defaults",
"lint": "npm-run-all -l -p \"lint:**\"",
"lint:js": "eslint --cache src test",
"lint:prettier": "prettier \"{**/*,*}.{js,json,md,yml,css}\" --list-different",
"prebuild": "npm run clean",
"prepare": "npm run build",
"pretest": "npm run lint",
"release": "standard-version",
"security": "npm audit",
"start": "npm run build -- -w",
"test": "cross-env NODE_ENV=test npm run test:coverage",
"test:coverage": "cross-env NODE_ENV=test jest --collectCoverageFrom=\"src/**/*.js\" --coverage",
"test:only": "cross-env NODE_ENV=test jest",
"test:watch": "cross-env NODE_ENV=test jest --watch"
},
"version": "5.0.5"
}