use directories for structure

This commit is contained in:
s2
2020-05-26 10:37:57 +02:00
parent 66580d4847
commit ae4aaf2668
1287 changed files with 92093 additions and 13113 deletions

22
node_modules/i18next-scanner/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015-2017 Cheton Wu
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.

802
node_modules/i18next-scanner/README.md generated vendored Normal file
View File

@@ -0,0 +1,802 @@
# i18next-scanner [![build status](https://travis-ci.org/i18next/i18next-scanner.svg?branch=master)](https://travis-ci.org/i18next/i18next-scanner) [![Coverage Status](https://coveralls.io/repos/i18next/i18next-scanner/badge.svg?branch=master&service=github)](https://coveralls.io/github/i18next/i18next-scanner?branch=master)
[![NPM](https://nodei.co/npm/i18next-scanner.png?downloads=true&stars=true)](https://www.npmjs.com/package/i18next-scanner)
Scan your code, extract translation keys/values, and merge them into i18n resource files.
Turns your code
```js
i18n._('Loading...');
i18n._('Backslashes in single quote: \' \\ \'');
i18n._('This is \
a multiline \
string');
i18n.t('car', { context: 'blue', count: 1 }); // output: 'One blue car'
i18n.t('car', { context: 'blue', count: 2 }); // output: '2 blue cars'
<Trans i18nKey="some.key">Default text</Trans>
```
into resource files
```js
{
"Loading...": "Wird geladen...", // uses existing translation
"Backslashes in single quote: ' \\ '": "__NOT_TRANSLATED__", // returns a custom string
"This is a multiline string": "this is a multiline string", // returns the key as the default value
"car": "car",
"car_blue": "One blue car",
"car_blue_plural": "{{count}} blue cars",
"some": {
"key": "Default text"
}
}
```
## Notice
There is a major breaking change since v1.0, and the API interface and options are not compatible with v0.x.
Checkout [Migration Guide](https://github.com/i18next/i18next-scanner/wiki/Migration-Guide) while upgrading from earlier versions.
## Features
* Fully compatible with [i18next](https://github.com/i18next/i18next) - a full-featured i18n javascript library for translating your webapplication.
* Support [react-i18next](https://github.com/i18next/react-i18next) for parsing the <b>Trans</b> component
* Support [Key Based Fallback](https://www.i18next.com/principles/fallback#key-fallback/) to write your code without the need to maintain i18n keys. This feature is available since [i18next@^2.1.0](https://github.com/i18next/i18next/blob/master/CHANGELOG.md#210)
* A standalone parser API
* A transform stream that works with both Gulp and Grunt task runner.
* Support custom transform and flush functions.
## Installation
```sh
npm install --save-dev i18next-scanner
```
or
```sh
npm install -g i18next-scanner
```
## Usage
### CLI Usage
```sh
$ i18next-scanner
Usage: i18next-scanner [options] <file ...>
Options:
-V, --version output the version number
--config <config> Path to the config file (default: i18next-scanner.config.js)
--output <path> Path to the output directory (default: .)
-h, --help output usage information
Examples:
$ i18next-scanner --config i18next-scanner.config.js --output /path/to/output 'src/**/*.{js,jsx}'
$ i18next-scanner --config i18next-scanner.config.js 'src/**/*.{js,jsx}'
$ i18next-scanner '/path/to/src/app.js' '/path/to/assets/index.html'
```
Globbing patterns are supported for specifying file paths:
* `*` 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
_Note: Globbing patterns should be wrapped in single quotes._
#### Examples
* [examples/i18next-scanner.config.js](https://github.com/i18next/i18next-scanner/blob/master/examples/i18next-scanner.config.js)
```js
const fs = require('fs');
const chalk = require('chalk');
module.exports = {
input: [
'app/**/*.{js,jsx}',
// Use ! to filter out files or directories
'!app/**/*.spec.{js,jsx}',
'!app/i18n/**',
'!**/node_modules/**',
],
output: './',
options: {
debug: true,
func: {
list: ['i18next.t', 'i18n.t'],
extensions: ['.js', '.jsx']
},
trans: {
component: 'Trans',
i18nKey: 'i18nKey',
defaultsKey: 'defaults',
extensions: ['.js', '.jsx'],
fallbackKey: function(ns, value) {
return value;
},
acorn: {
ecmaVersion: 10, // defaults to 10
sourceType: 'module', // defaults to 'module'
// Check out https://github.com/acornjs/acorn/tree/master/acorn#interface for additional options
}
},
lngs: ['en','de'],
ns: [
'locale',
'resource'
],
defaultLng: 'en',
defaultNs: 'resource',
defaultValue: '__STRING_NOT_TRANSLATED__',
resource: {
loadPath: 'i18n/{{lng}}/{{ns}}.json',
savePath: 'i18n/{{lng}}/{{ns}}.json',
jsonIndent: 2,
lineEnding: '\n'
},
nsSeparator: false, // namespace separator
keySeparator: false, // key separator
interpolation: {
prefix: '{{',
suffix: '}}'
}
},
transform: function customTransform(file, enc, done) {
"use strict";
const parser = this.parser;
const content = fs.readFileSync(file.path, enc);
let count = 0;
parser.parseFuncFromString(content, { list: ['i18next._', 'i18next.__'] }, (key, options) => {
parser.set(key, Object.assign({}, options, {
nsSeparator: false,
keySeparator: false
}));
++count;
});
if (count > 0) {
console.log(`i18next-scanner: count=${chalk.cyan(count)}, file=${chalk.yellow(JSON.stringify(file.relative))}`);
}
done();
}
};
```
### Standard API
```js
const fs = require('fs');
const Parser = require('i18next-scanner').Parser;
const customHandler = function(key) {
parser.set(key, '__TRANSLATION__');
};
const parser = new Parser();
const content = '';
// Parse Translation Function
// i18next.t('key');
content = fs.readFileSync('/path/to/app.js', 'utf-8');
parser
.parseFuncFromString(content, customHandler) // pass a custom handler
.parseFuncFromString(content, { list: ['i18next.t']}) // override `func.list`
.parseFuncFromString(content, { list: ['i18next.t']}, customHandler)
.parseFuncFromString(content); // use default options and handler
// Parse Trans component
content = fs.readFileSync('/path/to/app.jsx', 'utf-8');
parser
.parseTransFromString(content, customHandler) // pass a custom handler
.parseTransFromString(content, { component: 'Trans', i18nKey: 'i18nKey', defaultsKey: 'defaults' })
.parseTransFromString(content, { fallbackKey: true }) // Uses defaultValue as the fallback key when the i18nKey attribute is missing
.parseTransFromString(content); // use default options and handler
// Parse HTML Attribute
// <div data-i18n="key"></div>
content = fs.readFileSync('/path/to/index.html', 'utf-8');
parser
.parseAttrFromString(content, customHandler) // pass a custom handler
.parseAttrFromString(content, { list: ['data-i18n'] }) // override `attr.list`
.parseAttrFromString(content, { list: ['data-i18n'] }, customHandler)
.parseAttrFromString(content); // using default options and handler
console.log(parser.get());
console.log(parser.get({ sort: true }));
console.log(parser.get('translation:key', { lng: 'en'}));
```
### Transform Stream API
The main entry function of [i18next-scanner](https://github.com/i18next/i18next-scanner) is a transform stream. You can use [vinyl-fs](https://github.com/wearefractal/vinyl) to create a readable stream, pipe the stream through [i18next-scanner](https://github.com/i18next/i18next-scanner) to transform your code into an i18n resource object, and write to a destination folder.
Here is a simple example showing how that works:
```js
const scanner = require('i18next-scanner');
const vfs = require('vinyl-fs');
const sort = require('gulp-sort');
const options = {
// See options at https://github.com/i18next/i18next-scanner#options
};
vfs.src(['/path/to/src'])
.pipe(sort()) // Sort files in stream by path
.pipe(scanner(options))
.pipe(vfs.dest('/path/to/dest'));
```
Alternatively, you can get a transform stream by calling createStream() as show below:
```js
vfs.src(['/path/to/src'])
.pipe(sort()) // Sort files in stream by path
.pipe(scanner.createStream(options))
.pipe(vfs.dest('/path/to/dest'));
```
### Gulp
Now you are ready to set up a minimal configuration, and get started with Gulp. For example:
```js
const gulp = require('gulp');
const sort = require('gulp-sort');
const scanner = require('i18next-scanner');
gulp.task('i18next', function() {
return gulp.src(['src/**/*.{js,html}'])
.pipe(sort()) // Sort files in stream by path
.pipe(scanner({
lngs: ['en', 'de'], // supported languages
resource: {
// the source path is relative to current working directory
loadPath: 'assets/i18n/{{lng}}/{{ns}}.json',
// the destination path is relative to your `gulp.dest()` path
savePath: 'i18n/{{lng}}/{{ns}}.json'
}
}))
.pipe(gulp.dest('assets'));
});
```
### Grunt
Once you've finished the installation, add this line to your project's Gruntfile:
```js
grunt.loadNpmTasks('i18next-scanner');
```
In your project's Gruntfile, add a section named `i18next` to the data object passed into `grunt.initConfig()`, like so:
```js
grunt.initConfig({
i18next: {
dev: {
src: 'src/**/*.{js,html}',
dest: 'assets',
options: {
lngs: ['en', 'de'],
resource: {
loadPath: 'assets/i18n/{{lng}}/{{ns}}.json',
savePath: 'i18n/{{lng}}/{{ns}}.json'
}
}
}
}
});
```
## API
There are two ways to use i18next-scanner:
### Standard API
```js
const Parser = require('i18next-scanner').Parser;
const parser = new Parser(options);
const code = "i18next.t('key'); ...";
parser.parseFuncFromString(code);
const jsx = '<Trans i18nKey="some.key">Default text</Trans>';
parser.parseTransFromString(jsx);
const html = '<div data-i18n="key"></div>';
parser.parseAttrFromString(html);
parser.get();
```
#### parser.parseFuncFromString
Parse translation key from JS function
```js
parser.parseFuncFromString(content)
parser.parseFuncFromString(content, { list: ['_t'] });
parser.parseFuncFromString(content, function(key, options) {
options.defaultValue = key; // use key as the value
parser.set(key, options);
});
parser.parseFuncFromString(content, { list: ['_t'] }, function(key, options) {
parser.set(key, options); // use defaultValue
});
```
#### parser.parseTransFromString
Parse translation key from the [Trans component](https://github.com/i18next/react-i18next)
```js
parser.parseTransFromString(content);
parser.parseTransFromString(context, { component: 'Trans', i18nKey: 'i18nKey' });
// Uses defaultValue as the fallback key when the i18nKey attribute is missing
parser.parseTransFromString(content, { fallbackKey: true });
parser.parseTransFromString(content, {
fallbackKey: function(ns, value) {
// Returns a hash value as the fallback key
return sha1(value);
}
});
parser.parseTransFromString(content, function(key, options) {
options.defaultValue = key; // use key as the value
parser.set(key, options);
});
```
#### parser.parseAttrFromString
Parse translation key from HTML attribute
```js
parser.parseAttrFromString(content)
parser.parseAttrFromString(content, { list: ['data-i18n'] });
parser.parseAttrFromString(content, function(key) {
const defaultValue = key; // use key as the value
parser.set(key, defaultValue);
});
parser.parseAttrFromString(content, { list: ['data-i18n'] }, function(key) {
parser.set(key); // use defaultValue
});
```
#### parser.get
Get the value of a translation key or the whole i18n resource store
```js
// Returns the whole i18n resource store
parser.get();
// Returns the resource store with the top-level keys sorted by alphabetical order
parser.get({ sort: true });
// Returns a value in fallback language (@see options.fallbackLng) with namespace and key
parser.get('ns:key');
// Returns a value with namespace, key, and lng
parser.get('ns:key', { lng: 'en' });
```
#### parser.set
Set a translation key with an optional defaultValue to i18n resource store
```js
// Set a translation key
parser.set(key);
// Set a translation key with default value
parser.set(key, defaultValue);
// Set a translation key with default value using options
parser.set(key, {
defaultValue: defaultValue
});
```
### Transform Stream API
```js
const scanner = require('i18next-scanner');
scanner.createStream(options, customTransform /* optional */, customFlush /* optional */);
```
#### customTransform
The optional `customTransform` function is provided as the 2nd argument for the transform stream API. It must have the following signature: `function (file, encoding, done) {}`. A minimal implementation should call the `done()` function to indicate that the transformation is done, even if that transformation means discarding the file.
For example:
```js
const scanner = require('i18next-scanner');
const vfs = require('vinyl-fs');
const customTransform = function _transform(file, enc, done) {
const parser = this.parser;
const content = fs.readFileSync(file.path, enc);
// add your code
done();
};
vfs.src(['/path/to/src'])
.pipe(scanner(options, customTransform))
.pipe(vfs.dest('path/to/dest'));
```
To parse a translation key, call `parser.set(key, defaultValue)` to assign the key with an optional `defaultValue`.
For example:
```js
const customTransform = function _transform(file, enc, done) {
const parser = this.parser;
const content = fs.readFileSync(file.path, enc);
parser.parseFuncFromString(content, { list: ['i18n.t'] }, function(key) {
const defaultValue = '__L10N__';
parser.set(key, defaultValue);
});
done();
};
```
Alternatively, you may call `parser.set(defaultKey, value)` to assign the value with a default key. The `defaultKey` should be unique string and can never be `null`, `undefined`, or empty.
For example:
```js
const hash = require('sha1');
const customTransform = function _transform(file, enc, done) {
const parser = this.parser;
const content = fs.readFileSync(file.path, enc);
parser.parseFuncFromString(content, { list: ['i18n._'] }, function(key) {
const value = key;
const defaultKey = hash(value);
parser.set(defaultKey, value);
});
done();
};
```
#### customFlush
The optional `customFlush` function is provided as the last argument for the transform stream API, it is called just prior to the stream ending. You can implement your `customFlush` function to override the default `flush` function. When everything's done, call the `done()` function to indicate the stream is finished.
For example:
```js
const scanner = require('i18next-scanner');
const vfs = require('vinyl-fs');
const customFlush = function _flush(done) {
const parser = this.parser;
const resStore = parser.getResourceStore();
// loop over the resStore
Object.keys(resStore).forEach(function(lng) {
const namespaces = resStore[lng];
Object.keys(namespaces).forEach(function(ns) {
const obj = namespaces[ns];
// add your code
});
});
done();
};
vfs.src(['/path/to/src'])
.pipe(scanner(options, customTransform, customFlush))
.pipe(vfs.dest('/path/to/dest'));
```
## Default Options
Below are the configuration options with their default values:
```javascript
{
debug: false,
removeUnusedKeys: false,
sort: false,
attr: {
list: ['data-i18n'],
extensions: ['.html', '.htm']
},
func: {
list: ['i18next.t', 'i18n.t'],
extensions: ['.js', '.jsx']
},
trans: {
component: 'Trans',
i18nKey: 'i18nKey',
defaultsKey: 'defaults',
extensions: ['.js', '.jsx'],
fallbackKey: false
},
lngs: ['en'],
ns: ['translation'],
defaultLng: 'en',
defaultNs: 'translation',
defaultValue: '',
resource: {
loadPath: 'i18n/{{lng}}/{{ns}}.json',
savePath: 'i18n/{{lng}}/{{ns}}.json',
jsonIndent: 2,
lineEnding: '\n'
},
nsSeparator: ':',
keySeparator: '.',
pluralSeparator: '_',
contextSeparator: '_',
contextDefaultValues: [],
interpolation: {
prefix: '{{',
suffix: '}}'
}
}
```
#### debug
Type: `Boolean` Default: `false`
Set to `true` to turn on debug output.
#### removeUnusedKeys
Type: `Boolean` Default: `false`
Set to `true` to remove unused translation keys from i18n resource files.
#### sort
Type: `Boolean` Default: `false`
Set to `true` if you want to sort translation keys in ascending order.
#### attr
Type: `Object` or `false`
If an `Object` is supplied, you can either specify a list of attributes and extensions, or override the default.
```js
{ // Default
attr: {
list: ['data-i18n'],
extensions: ['.html', '.htm']
}
}
```
You can set attr to `false` to disable parsing attribute as below:
```js
{
attr: false
}
```
#### func
Type: `Object` or `false`
If an `Object` is supplied, you can either specify a list of translation functions and extensions, or override the default.
```js
{ // Default
func: {
list: ['i18next.t', 'i18n.t'],
extensions: ['.js', '.jsx']
}
}
```
You can set func to `false` to disable parsing translation function as below:
```js
{
func: false
}
```
#### trans
Type: `Object` or `false`
If an `Object` is supplied, you can specify a list of extensions, or override the default.
```js
{ // Default
trans: {
component: 'Trans',
i18nKey: 'i18nKey',
defaultsKey: 'defaults',
extensions: ['.js', '.jsx'],
fallbackKey: false
}
}
```
You can set trans to `false` to disable parsing Trans component as below:
```js
{
trans: false
}
```
The fallbackKey can either be a boolean value, or a function like so:
```js
fallbackKey: function(ns, value) {
// Returns a hash value as the fallback key
return sha1(value);
}
```
#### lngs
Type: `Array` Default: `['en']`
An array of supported languages.
#### ns
Type: `String` or `Array` Default: `['translation']`
A namespace string or an array of namespaces.
#### defaultLng
Type: `String` Default: `'en'`
The default language used for checking default values.
#### defaultNs
Type: `String` Default: `'translation'`
The default namespace used if not passed to translation function.
#### defaultValue
Type: `String` or `Function` Default: `''`
The default value used if not passed to `parser.set`.
##### Examples
Provides the default value with a string:
```js
{
defaultValue: '__NOT_TRANSLATED__'
}
```
Provides the default value as a callback function:
```js
{
// @param {string} lng The language currently used.
// @param {string} ns The namespace currently used.
// @param {string} key The translation key.
// @return {string} Returns a default value for the translation key.
defaultValue: function(lng, ns, key) {
if (lng === 'en') {
// Return key as the default value for English language
return key;
}
// Return the string '__NOT_TRANSLATED__' for other languages
return '__NOT_TRANSLATED__';
}
}
```
#### resource
Type: `Object`
Resource options:
```js
{ // Default
resource: {
// The path where resources get loaded from. Relative to current working directory.
loadPath: 'i18n/{{lng}}/{{ns}}.json',
// The path to store resources. Relative to the path specified by `gulp.dest(path)`.
savePath: 'i18n/{{lng}}/{{ns}}.json',
// Specify the number of space characters to use as white space to insert into the output JSON string for readability purpose.
jsonIndent: 2,
// Normalize line endings to '\r\n', '\r', '\n', or 'auto' for the current operating system. Defaults to '\n'.
// Aliases: 'CRLF', 'CR', 'LF', 'crlf', 'cr', 'lf'
lineEnding: '\n'
}
}
```
#### keySeparator
Type: `String` or `false` Default: `'.'`
Key separator used in translation keys.
Set to `false` to disable key separator if you prefer having keys as the fallback for translation (e.g. gettext). This feature is supported by [i18next@2.1.0](https://github.com/i18next/i18next/blob/master/CHANGELOG.md#210). Also see <strong>Key based fallback</strong> at https://www.i18next.com/principles/fallback#key-fallback.
#### nsSeparator
Type: `String` or `false` Default: `':'`
Namespace separator used in translation keys.
Set to `false` to disable namespace separator if you prefer having keys as the fallback for translation (e.g. gettext). This feature is supported by [i18next@2.1.0](https://github.com/i18next/i18next/blob/master/CHANGELOG.md#210). Also see <strong>Key based fallback</strong> at https://www.i18next.com/principles/fallback#key-fallback.
#### context
Type: `Boolean` or `Function` Default: `true`
Whether to add context form key.
```js
context: function(lng, ns, key, options) {
return true;
}
```
#### contextFallback
Type: `Boolean` Default: `true`
Whether to add a fallback key as well as the context form key.
#### contextSeparator
Type: `String` Default: `'_'`
The character to split context from key.
#### contextDefaultValues
Type: `Array` Default: `[]`
A list of default context values, used when the scanner encounters dynamic value as a `context`.
For a list of `['male', 'female']` the scanner will generate an entry for each value.
#### plural
Type: `Boolean` or `Function` Default: `true`
Whether to add plural form key.
```js
plural: function(lng, ns, key, options) {
return true;
}
```
#### pluralFallback
Type: `Boolean` Default: `true`
Whether to add a fallback key as well as the plural form key.
#### pluralSeparator
Type: `String` Default: `'_'`
The character to split plural from key.
#### interpolation
Type: `Object`
interpolation options
```js
{ // Default
interpolation: {
// The prefix for variables
prefix: '{{',
// The suffix for variables
suffix: '}}'
}
}
```
## Integration Guide
Checkout [Integration Guide](https://github.com/i18next/i18next-scanner/wiki/Integration-Guide) to learn how to integrate with [React](https://github.com/i18next/i18next-scanner/wiki/Integration-Guide#react), [Gettext Style I18n](https://github.com/i18next/i18next-scanner/wiki/Integration-Guide#gettext-style-i18n), and [Handlebars](https://github.com/i18next/i18next-scanner/wiki/Integration-Guide#handlebars).
## License
MIT

73
node_modules/i18next-scanner/bin/cli.js generated vendored Normal file
View File

@@ -0,0 +1,73 @@
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const program = require('commander');
const ensureArray = require('ensure-array');
const sort = require('gulp-sort');
const vfs = require('vinyl-fs');
const scanner = require('../lib');
const pkg = require('../package.json');
program
.version(pkg.version)
.usage('[options] <file ...>')
.option('--config <config>', 'Path to the config file (default: i18next-scanner.config.js)', 'i18next-scanner.config.js')
.option('--output <path>', 'Path to the output directory (default: .)');
program.on('--help', function() {
console.log('');
console.log(' Examples:');
console.log('');
console.log(' $ i18next-scanner --config i18next-scanner.config.js --output /path/to/output \'src/**/*.{js,jsx}\'');
console.log(' $ i18next-scanner --config i18next-scanner.config.js "src/**/*.{js,jsx}"');
console.log(' $ i18next-scanner "/path/to/src/app.js" "/path/to/assets/index.html"');
console.log('');
});
program.parse(process.argv);
if (!program.config) {
program.help();
return;
}
let config = {};
try {
config = require(path.resolve(program.config));
} catch (err) {
console.error('i18next-scanner:', err);
return;
}
{ // Input
config.input = (program.args.length > 0) ? program.args : ensureArray(config.input);
config.input = config.input.map(function(s) {
s = s.trim();
// On Windows, arguments contain spaces must be enclosed with double quotes, not single quotes.
if (s.match(/(^'.*'$|^".*"$)/)) {
// Remove first and last character
s = s.slice(1, -1);
}
return s;
});
if (config.input.length === 0) {
program.help();
return;
}
}
{ // Output
config.output = program.output || config.output;
if (!config.output) {
config.output = '.';
}
}
vfs.src(config.input)
.pipe(sort()) // Sort files in stream by path
.pipe(scanner(config.options, config.transform, config.flush))
.pipe(vfs.dest(config.output))

61
node_modules/i18next-scanner/lib/acorn-jsx-walk.js generated vendored Normal file
View File

@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _acornWalk = require("acorn-walk");
var _acornDynamicImport = require("acorn-dynamic-import");
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
Object.assign(_acornWalk.base, _defineProperty({
FieldDefinition: function FieldDefinition(node, state, callback) {
if (node.value !== null) {
callback(node.value, state);
}
}
}, _acornDynamicImport.DynamicImportKey, function () {})); // Extends acorn walk with JSX elements
// https://github.com/RReverser/acorn-jsx/issues/23#issuecomment-403753801
Object.assign(_acornWalk.base, {
JSXAttribute: function JSXAttribute(node, state, callback) {
if (node.value !== null) {
callback(node.value, state);
}
},
JSXElement: function JSXElement(node, state, callback) {
node.openingElement.attributes.forEach(function (attribute) {
callback(attribute, state);
});
node.children.forEach(function (node) {
callback(node, state);
});
},
JSXEmptyExpression: function JSXEmptyExpression(node, state, callback) {// Comments. Just ignore.
},
JSXExpressionContainer: function JSXExpressionContainer(node, state, callback) {
callback(node.expression, state);
},
JSXFragment: function JSXFragment(node, state, callback) {
node.children.forEach(function (node) {
callback(node, state);
});
},
JSXSpreadAttribute: function JSXSpreadAttribute(node, state, callback) {
callback(node.argument, state);
},
JSXText: function JSXText() {}
});
var _default = function _default(ast, options) {
(0, _acornWalk.simple)(ast, _objectSpread({}, options));
};
exports["default"] = _default;

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// flattenObjectKeys({
// a: {
// b: {
// c: [],
// d: {
// e: [{ f: [] }, { b: 1 }],
// g: {}
// }
// }
// }
// });
//
// [ [ 'a', 'b', 'c' ],
// [ 'a', 'b', 'd', 'e', '0', 'f' ],
// [ 'a', 'b', 'd', 'e', '1', 'b' ],
// [ 'a', 'b', 'd', 'g' ] ]
//
var flattenObjectKeys = function flattenObjectKeys(obj) {
var keys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
return Object.keys(obj).reduce(function (acc, key) {
var o = (0, _isPlainObject["default"])(obj[key]) && Object.keys(obj[key]).length > 0 || Array.isArray(obj[key]) && obj[key].length > 0 ? flattenObjectKeys(obj[key], keys.concat(key)) : [keys.concat(key)];
return acc.concat(o);
}, []);
};
var _default = flattenObjectKeys;
exports["default"] = _default;

147
node_modules/i18next-scanner/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,147 @@
"use strict";
var _fs = _interopRequireDefault(require("fs"));
var _path = _interopRequireDefault(require("path"));
var _eol = _interopRequireDefault(require("eol"));
var _get = _interopRequireDefault(require("lodash/get"));
var _includes = _interopRequireDefault(require("lodash/includes"));
var _vinyl = _interopRequireDefault(require("vinyl"));
var _through = _interopRequireDefault(require("through2"));
var _parser = _interopRequireDefault(require("./parser"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
/* eslint-disable no-buffer-constructor */
var transform = function transform(parser, customTransform) {
return function _transform(file, enc, done) {
var options = parser.options;
var content = _fs["default"].readFileSync(file.path, enc);
var extname = _path["default"].extname(file.path);
if ((0, _includes["default"])((0, _get["default"])(options, 'attr.extensions'), extname)) {
// Parse attribute (e.g. data-i18n="key")
parser.parseAttrFromString(content, {
transformOptions: {
filepath: file.path
}
});
}
if ((0, _includes["default"])((0, _get["default"])(options, 'func.extensions'), extname)) {
// Parse translation function (e.g. i18next.t('key'))
parser.parseFuncFromString(content, {
transformOptions: {
filepath: file.path
}
});
}
if ((0, _includes["default"])((0, _get["default"])(options, 'trans.extensions'), extname)) {
// Look for Trans components in JSX
parser.parseTransFromString(content, {
transformOptions: {
filepath: file.path
}
});
}
if (typeof customTransform === 'function') {
this.parser = parser;
customTransform.call(this, file, enc, done);
return;
}
done();
};
};
var flush = function flush(parser, customFlush) {
return function _flush(done) {
var _this = this;
var options = parser.options;
if (typeof customFlush === 'function') {
this.parser = parser;
customFlush.call(this, done);
return;
} // Flush to resource store
var resStore = parser.get({
sort: options.sort
});
var jsonIndent = options.resource.jsonIndent;
var lineEnding = String(options.resource.lineEnding).toLowerCase();
Object.keys(resStore).forEach(function (lng) {
var namespaces = resStore[lng];
Object.keys(namespaces).forEach(function (ns) {
var obj = namespaces[ns];
var resPath = parser.formatResourceSavePath(lng, ns);
var text = JSON.stringify(obj, null, jsonIndent) + '\n';
if (lineEnding === 'auto') {
text = _eol["default"].auto(text);
} else if (lineEnding === '\r\n' || lineEnding === 'crlf') {
text = _eol["default"].crlf(text);
} else if (lineEnding === '\n' || lineEnding === 'lf') {
text = _eol["default"].lf(text);
} else if (lineEnding === '\r' || lineEnding === 'cr') {
text = _eol["default"].cr(text);
} else {
// Defaults to LF
text = _eol["default"].lf(text);
}
var contents = null;
try {
// "Buffer.from(string[, encoding])" is added in Node.js v5.10.0
contents = Buffer.from(text);
} catch (e) {
// Fallback to "new Buffer(string[, encoding])" which is deprecated since Node.js v6.0.0
contents = new Buffer(text);
}
_this.push(new _vinyl["default"]({
path: resPath,
contents: contents
}));
});
});
done();
};
}; // @param {object} options The options object.
// @param {function} [customTransform]
// @param {function} [customFlush]
// @return {object} Returns a through2.obj().
var createStream = function createStream(options, customTransform, customFlush) {
var parser = new _parser["default"](options);
var stream = _through["default"].obj(transform(parser, customTransform), flush(parser, customFlush));
return stream;
}; // Convenience API
module.exports = function () {
var _module$exports;
return (_module$exports = module.exports).createStream.apply(_module$exports, arguments);
}; // Basic API
module.exports.createStream = createStream; // Parser
module.exports.Parser = _parser["default"];

85
node_modules/i18next-scanner/lib/nodes-to-string.js generated vendored Normal file
View File

@@ -0,0 +1,85 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _get2 = _interopRequireDefault(require("lodash/get"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var isJSXText = function isJSXText(node) {
if (!node) {
return false;
}
return node.type === 'JSXText';
};
var isNumericLiteral = function isNumericLiteral(node) {
if (!node) {
return false;
}
return node.type === 'Literal' && typeof node.value === 'number';
};
var isStringLiteral = function isStringLiteral(node) {
if (!node) {
return false;
}
return node.type === 'Literal' && typeof node.value === 'string';
};
var isObjectExpression = function isObjectExpression(node) {
if (!node) {
return false;
}
return node.type === 'ObjectExpression';
};
var nodesToString = function nodesToString(nodes) {
var memo = '';
var nodeIndex = 0;
nodes.forEach(function (node, i) {
if (isJSXText(node) || isStringLiteral(node)) {
var value = node.value.replace(/^[\r\n]+\s*/g, '') // remove leading spaces containing a leading newline character
.replace(/[\r\n]+\s*$/g, '') // remove trailing spaces containing a leading newline character
.replace(/[\r\n]+\s*/g, ' '); // replace spaces containing a leading newline character with a single space character
if (!value) {
return;
}
memo += value;
} else if (node.type === 'JSXExpressionContainer') {
var _node$expression = node.expression,
expression = _node$expression === void 0 ? {} : _node$expression;
if (isNumericLiteral(expression)) {
// Numeric literal is ignored in react-i18next
memo += '';
}
if (isStringLiteral(expression)) {
memo += expression.value;
} else if (isObjectExpression(expression) && (0, _get2["default"])(expression, 'properties[0].type') === 'Property') {
memo += "<".concat(nodeIndex, ">{{").concat(expression.properties[0].key.name, "}}</").concat(nodeIndex, ">");
} else {
console.error("Unsupported JSX expression. Only static values or {{interpolation}} blocks are supported. Got ".concat(expression.type, ":"));
console.error(node.expression);
}
} else if (node.children) {
memo += "<".concat(nodeIndex, ">").concat(nodesToString(node.children), "</").concat(nodeIndex, ">");
}
++nodeIndex;
});
return memo;
};
var _default = nodesToString;
exports["default"] = _default;

49
node_modules/i18next-scanner/lib/omit-empty-object.js generated vendored Normal file
View File

@@ -0,0 +1,49 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject"));
var _cloneDeep = _interopRequireDefault(require("clone-deep"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
// omitEmptyObject({
// a: {
// b: {
// c: 1,
// d: {
// e: {
// }
// }
// }
// }
// });
//
// { a: { b: { c: 1 } } }
//
var unsetEmptyObject = function unsetEmptyObject(obj) {
Object.keys(obj).forEach(function (key) {
if (!(0, _isPlainObject["default"])(obj[key])) {
return;
}
unsetEmptyObject(obj[key]);
if ((0, _isPlainObject["default"])(obj[key]) && Object.keys(obj[key]).length === 0) {
obj[key] = undefined;
delete obj[key];
}
});
return obj;
};
var omitEmptyObject = function omitEmptyObject(obj) {
return unsetEmptyObject((0, _cloneDeep["default"])(obj));
};
var _default = omitEmptyObject;
exports["default"] = _default;

1102
node_modules/i18next-scanner/lib/parser.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

15
node_modules/i18next-scanner/node_modules/.bin/esparse generated vendored Normal file
View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../esprima/bin/esparse.js" "$@"
ret=$?
else
node "$basedir/../esprima/bin/esparse.js" "$@"
ret=$?
fi
exit $ret

View File

@@ -0,0 +1,17 @@
@ECHO off
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
"%_prog%" "%dp0%\..\esprima\bin\esparse.js" %*
ENDLOCAL
EXIT /b %errorlevel%
:find_dp0
SET dp0=%~dp0
EXIT /b

View File

@@ -0,0 +1,18 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
& "$basedir/node$exe" "$basedir/../esprima/bin/esparse.js" $args
$ret=$LASTEXITCODE
} else {
& "node$exe" "$basedir/../esprima/bin/esparse.js" $args
$ret=$LASTEXITCODE
}
exit $ret

View File

@@ -0,0 +1,15 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../esprima/bin/esvalidate.js" "$@"
ret=$?
else
node "$basedir/../esprima/bin/esvalidate.js" "$@"
ret=$?
fi
exit $ret

View File

@@ -0,0 +1,17 @@
@ECHO off
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
"%_prog%" "%dp0%\..\esprima\bin\esvalidate.js" %*
ENDLOCAL
EXIT /b %errorlevel%
:find_dp0
SET dp0=%~dp0
EXIT /b

View File

@@ -0,0 +1,18 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
& "$basedir/node$exe" "$basedir/../esprima/bin/esvalidate.js" $args
$ret=$LASTEXITCODE
} else {
& "node$exe" "$basedir/../esprima/bin/esvalidate.js" $args
$ret=$LASTEXITCODE
}
exit $ret

View File

@@ -0,0 +1,515 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). (Format adopted after v3.0.0.)
## [3.0.2] (2019-09-27)
### Fixed
* Improve tracking of executable subcommands.
### Changed
* update development dependencies
## [3.0.1] (2019-08-30)
### Added
* .name and .usage to README ([#1010])
* Table of Contents to README ([#1010])
* TypeScript definition for `executableFile` in CommandOptions ([#1028])
### Changed
* consistently use `const` rather than `var` in README ([#1026])
### Fixed
* help for sub commands with custom executableFile ([#1018])
3.0.0 / 2019-08-08
=================
* Add option to specify executable file name ([#999])
* e.g. `.command('clone', 'clone description', { executableFile: 'myClone' })`
* Change docs for `.command` to contrast action handler vs git-style executable. ([#938] [#990])
* **Breaking** Change TypeScript to use overloaded function for `.command`. ([#938] [#990])
* Change to use straight quotes around strings in error messages (like 'this' instead of `this') ([#915])
* Add TypeScript "reference types" for node ([#974])
* Add support for hyphen as an option argument in subcommands ([#697])
* Add support for a short option flag and its value to be concatenated for action handler subcommands ([#599])
* e.g. `-p 80` can also be supplied as `-p80`
* Add executable arguments to spawn in win32, for git-style executables ([#611])
* e.g. `node --harmony myCommand.js clone`
* Add parent command as prefix of subcommand in help ([#980])
* Add optional custom description to `.version` ([#963])
* e.g. `program.version('0.0.1', '-v, --vers', 'output the current version')`
* Add `.helpOption(flags, description)` routine to customise help flags and description ([#963])
* e.g. `.helpOption('-e, --HELP', 'read more information')`
* Fix behavior of --no-* options ([#795])
* can now define both `--foo` and `--no-foo`
* **Breaking** custom event listeners: `--no-foo` on cli now emits `option:no-foo` (previously `option:foo`)
* **Breaking** default value: defining `--no-foo` after defining `--foo` leaves the default value unchanged (previously set it to false)
* allow boolean default value, such as from environment ([#987])
* Increment inspector port for spawned subcommands ([#991])
* e.g. `node --inspect myCommand.js clone`
Example Breaking Changes
------------------------
The custom event for a negated option like `--no-foo` is `option:no-foo` (previously `option:foo`).
```js
program
.option('--no-foo')
.on('option:no-foo', () => {
console.log('removing foo');
});
```
When using TypeScript, adding a command does not allow an explicit `undefined` for an unwanted executable description (e.g
for a command with an action handler).
```js
program
.command('action1', undefined, { noHelp: true }) // No longer valid
.command('action2', { noHelp: true }) // Correct
```
3.0.0-0 Prerelease / 2019-07-28
==============================
(Released as 3.0.0)
2.20.0 / 2019-04-02
==================
* fix: resolve symbolic links completely when hunting for subcommands (#935)
* Update index.d.ts (#930)
* Update Readme.md (#924)
* Remove --save option as it isn't required anymore (#918)
* Add link to the license file (#900)
* Added example of receiving args from options (#858)
* Added missing semicolon (#882)
* Add extension to .eslintrc (#876)
2.19.0 / 2018-10-02
==================
* Removed newline after Options and Commands headers (#864)
* Bugfix - Error output (#862)
* Fix to change default value to string (#856)
2.18.0 / 2018-09-07
==================
* Standardize help output (#853)
* chmod 644 travis.yml (#851)
* add support for execute typescript subcommand via ts-node (#849)
2.17.1 / 2018-08-07
==================
* Fix bug in command emit (#844)
2.17.0 / 2018-08-03
==================
* fixed newline output after help information (#833)
* Fix to emit the action even without command (#778)
* npm update (#823)
2.16.0 / 2018-06-29
==================
* Remove Makefile and `test/run` (#821)
* Make 'npm test' run on Windows (#820)
* Add badge to display install size (#807)
* chore: cache node_modules (#814)
* chore: remove Node.js 4 (EOL), add Node.js 10 (#813)
* fixed typo in readme (#812)
* Fix types (#804)
* Update eslint to resolve vulnerabilities in lodash (#799)
* updated readme with custom event listeners. (#791)
* fix tests (#794)
2.15.0 / 2018-03-07
==================
* Update downloads badge to point to graph of downloads over time instead of duplicating link to npm
* Arguments description
2.14.1 / 2018-02-07
==================
* Fix typing of help function
2.14.0 / 2018-02-05
==================
* only register the option:version event once
* Fixes issue #727: Passing empty string for option on command is set to undefined
* enable eqeqeq rule
* resolves #754 add linter configuration to project
* resolves #560 respect custom name for version option
* document how to override the version flag
* document using options per command
2.13.0 / 2018-01-09
==================
* Do not print default for --no-
* remove trailing spaces in command help
* Update CI's Node.js to LTS and latest version
* typedefs: Command and Option types added to commander namespace
2.12.2 / 2017-11-28
==================
* fix: typings are not shipped
2.12.1 / 2017-11-23
==================
* Move @types/node to dev dependency
2.12.0 / 2017-11-22
==================
* add attributeName() method to Option objects
* Documentation updated for options with --no prefix
* typings: `outputHelp` takes a string as the first parameter
* typings: use overloads
* feat(typings): update to match js api
* Print default value in option help
* Fix translation error
* Fail when using same command and alias (#491)
* feat(typings): add help callback
* fix bug when description is add after command with options (#662)
* Format js code
* Rename History.md to CHANGELOG.md (#668)
* feat(typings): add typings to support TypeScript (#646)
* use current node
2.11.0 / 2017-07-03
==================
* Fix help section order and padding (#652)
* feature: support for signals to subcommands (#632)
* Fixed #37, --help should not display first (#447)
* Fix translation errors. (#570)
* Add package-lock.json
* Remove engines
* Upgrade package version
* Prefix events to prevent conflicts between commands and options (#494)
* Removing dependency on graceful-readlink
* Support setting name in #name function and make it chainable
* Add .vscode directory to .gitignore (Visual Studio Code metadata)
* Updated link to ruby commander in readme files
2.10.0 / 2017-06-19
==================
* Update .travis.yml. drop support for older node.js versions.
* Fix require arguments in README.md
* On SemVer you do not start from 0.0.1
* Add missing semi colon in readme
* Add save param to npm install
* node v6 travis test
* Update Readme_zh-CN.md
* Allow literal '--' to be passed-through as an argument
* Test subcommand alias help
* link build badge to master branch
* Support the alias of Git style sub-command
* added keyword commander for better search result on npm
* Fix Sub-Subcommands
* test node.js stable
* Fixes TypeError when a command has an option called `--description`
* Update README.md to make it beginner friendly and elaborate on the difference between angled and square brackets.
* Add chinese Readme file
2.9.0 / 2015-10-13
==================
* Add option `isDefault` to set default subcommand #415 @Qix-
* Add callback to allow filtering or post-processing of help text #434 @djulien
* Fix `undefined` text in help information close #414 #416 @zhiyelee
2.8.1 / 2015-04-22
==================
* Back out `support multiline description` Close #396 #397
2.8.0 / 2015-04-07
==================
* Add `process.execArg` support, execution args like `--harmony` will be passed to sub-commands #387 @DigitalIO @zhiyelee
* Fix bug in Git-style sub-commands #372 @zhiyelee
* Allow commands to be hidden from help #383 @tonylukasavage
* When git-style sub-commands are in use, yet none are called, display help #382 @claylo
* Add ability to specify arguments syntax for top-level command #258 @rrthomas
* Support multiline descriptions #208 @zxqfox
2.7.1 / 2015-03-11
==================
* Revert #347 (fix collisions when option and first arg have same name) which causes a bug in #367.
2.7.0 / 2015-03-09
==================
* Fix git-style bug when installed globally. Close #335 #349 @zhiyelee
* Fix collisions when option and first arg have same name. Close #346 #347 @tonylukasavage
* Add support for camelCase on `opts()`. Close #353 @nkzawa
* Add node.js 0.12 and io.js to travis.yml
* Allow RegEx options. #337 @palanik
* Fixes exit code when sub-command failing. Close #260 #332 @pirelenito
* git-style `bin` files in $PATH make sense. Close #196 #327 @zhiyelee
2.6.0 / 2014-12-30
==================
* added `Command#allowUnknownOption` method. Close #138 #318 @doozr @zhiyelee
* Add application description to the help msg. Close #112 @dalssoft
2.5.1 / 2014-12-15
==================
* fixed two bugs incurred by variadic arguments. Close #291 @Quentin01 #302 @zhiyelee
2.5.0 / 2014-10-24
==================
* add support for variadic arguments. Closes #277 @whitlockjc
2.4.0 / 2014-10-17
==================
* fixed a bug on executing the coercion function of subcommands option. Closes #270
* added `Command.prototype.name` to retrieve command name. Closes #264 #266 @tonylukasavage
* added `Command.prototype.opts` to retrieve all the options as a simple object of key-value pairs. Closes #262 @tonylukasavage
* fixed a bug on subcommand name. Closes #248 @jonathandelgado
* fixed function normalize doesnt honor option terminator. Closes #216 @abbr
2.3.0 / 2014-07-16
==================
* add command alias'. Closes PR #210
* fix: Typos. Closes #99
* fix: Unused fs module. Closes #217
2.2.0 / 2014-03-29
==================
* add passing of previous option value
* fix: support subcommands on windows. Closes #142
* Now the defaultValue passed as the second argument of the coercion function.
2.1.0 / 2013-11-21
==================
* add: allow cflag style option params, unit test, fixes #174
2.0.0 / 2013-07-18
==================
* remove input methods (.prompt, .confirm, etc)
1.3.2 / 2013-07-18
==================
* add support for sub-commands to co-exist with the original command
1.3.1 / 2013-07-18
==================
* add quick .runningCommand hack so you can opt-out of other logic when running a sub command
1.3.0 / 2013-07-09
==================
* add EACCES error handling
* fix sub-command --help
1.2.0 / 2013-06-13
==================
* allow "-" hyphen as an option argument
* support for RegExp coercion
1.1.1 / 2012-11-20
==================
* add more sub-command padding
* fix .usage() when args are present. Closes #106
1.1.0 / 2012-11-16
==================
* add git-style executable subcommand support. Closes #94
1.0.5 / 2012-10-09
==================
* fix `--name` clobbering. Closes #92
* fix examples/help. Closes #89
1.0.4 / 2012-09-03
==================
* add `outputHelp()` method.
1.0.3 / 2012-08-30
==================
* remove invalid .version() defaulting
1.0.2 / 2012-08-24
==================
* add `--foo=bar` support [arv]
* fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus]
1.0.1 / 2012-08-03
==================
* fix issue #56
* fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode())
1.0.0 / 2012-07-05
==================
* add support for optional option descriptions
* add defaulting of `.version()` to package.json's version
0.6.1 / 2012-06-01
==================
* Added: append (yes or no) on confirmation
* Added: allow node.js v0.7.x
0.6.0 / 2012-04-10
==================
* Added `.prompt(obj, callback)` support. Closes #49
* Added default support to .choose(). Closes #41
* Fixed the choice example
0.5.1 / 2011-12-20
==================
* Fixed `password()` for recent nodes. Closes #36
0.5.0 / 2011-12-04
==================
* Added sub-command option support [itay]
0.4.3 / 2011-12-04
==================
* Fixed custom help ordering. Closes #32
0.4.2 / 2011-11-24
==================
* Added travis support
* Fixed: line-buffered input automatically trimmed. Closes #31
0.4.1 / 2011-11-18
==================
* Removed listening for "close" on --help
0.4.0 / 2011-11-15
==================
* Added support for `--`. Closes #24
0.3.3 / 2011-11-14
==================
* Fixed: wait for close event when writing help info [Jerry Hamlet]
0.3.2 / 2011-11-01
==================
* Fixed long flag definitions with values [felixge]
0.3.1 / 2011-10-31
==================
* Changed `--version` short flag to `-V` from `-v`
* Changed `.version()` so it's configurable [felixge]
0.3.0 / 2011-10-31
==================
* Added support for long flags only. Closes #18
0.2.1 / 2011-10-24
==================
* "node": ">= 0.4.x < 0.7.0". Closes #20
0.2.0 / 2011-09-26
==================
* Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs]
0.1.0 / 2011-08-24
==================
* Added support for custom `--help` output
0.0.5 / 2011-08-18
==================
* Changed: when the user enters nothing prompt for password again
* Fixed issue with passwords beginning with numbers [NuckChorris]
0.0.4 / 2011-08-15
==================
* Fixed `Commander#args`
0.0.3 / 2011-08-15
==================
* Added default option value support
0.0.2 / 2011-08-15
==================
* Added mask support to `Command#password(str[, mask], fn)`
* Added `Command#password(str, fn)`
0.0.1 / 2010-01-03
==================
* Initial release
[#599]: https://github.com/tj/commander.js/issues/599
[#611]: https://github.com/tj/commander.js/issues/611
[#697]: https://github.com/tj/commander.js/issues/697
[#795]: https://github.com/tj/commander.js/issues/795
[#915]: https://github.com/tj/commander.js/issues/915
[#938]: https://github.com/tj/commander.js/issues/938
[#963]: https://github.com/tj/commander.js/issues/963
[#974]: https://github.com/tj/commander.js/issues/974
[#980]: https://github.com/tj/commander.js/issues/980
[#987]: https://github.com/tj/commander.js/issues/987
[#990]: https://github.com/tj/commander.js/issues/990
[#991]: https://github.com/tj/commander.js/issues/991
[#999]: https://github.com/tj/commander.js/issues/999
[#1010]: https://github.com/tj/commander.js/pull/1010
[#1018]: https://github.com/tj/commander.js/pull/1018
[#1026]: https://github.com/tj/commander.js/pull/1026
[#1028]: https://github.com/tj/commander.js/pull/1028
[Unreleased]: https://github.com/tj/commander.js/compare/master...develop
[3.0.1]: https://github.com/tj/commander.js/compare/v3.0.0...v3.0.1

View File

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

View File

@@ -0,0 +1,612 @@
# Commander.js
[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
- [Commander.js](#commanderjs)
- [Installation](#installation)
- [Declaring _program_ variable](#declaring-program-variable)
- [Options](#options)
- [Common option types, boolean and value](#common-option-types-boolean-and-value)
- [Default option value](#default-option-value)
- [Other option types, negatable boolean and flag|value](#other-option-types-negatable-boolean-and-flagvalue)
- [Custom option processing](#custom-option-processing)
- [Version option](#version-option)
- [Commands](#commands)
- [Specify the argument syntax](#specify-the-argument-syntax)
- [Action handler (sub)commands](#action-handler-subcommands)
- [Git-style executable (sub)commands](#git-style-executable-subcommands)
- [Automated --help](#automated---help)
- [Custom help](#custom-help)
- [.usage and .name](#usage-and-name)
- [.outputHelp(cb)](#outputhelpcb)
- [.helpOption(flags, description)](#helpoptionflags-description)
- [.help(cb)](#helpcb)
- [Custom event listeners](#custom-event-listeners)
- [Bits and pieces](#bits-and-pieces)
- [TypeScript](#typescript)
- [Node options such as `--harmony`](#node-options-such-as---harmony)
- [Node debugging](#node-debugging)
- [Examples](#examples)
- [License](#license)
- [Support](#support)
## Installation
```bash
npm install commander
```
## Declaring _program_ variable
Commander exports a global object which is convenient for quick programs.
This is used in the examples in this README for brevity.
```js
const program = require('commander');
program.version('0.0.1');
```
For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
```js
const commander = require('commander');
const program = new commander.Command();
program.version('0.0.1');
```
## Options
Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space.
The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. Multiple short flags may be combined as a single arg, for example `-abc` is equivalent to `-a -b -c`.
### Common option types, boolean and value
The two most used option types are a boolean flag, and an option which takes a value (declared using angle brackets). Both are `undefined` unless specified on command line.
```js
const program = require('commander');
program
.option('-d, --debug', 'output extra debugging')
.option('-s, --small', 'small pizza size')
.option('-p, --pizza-type <type>', 'flavour of pizza');
program.parse(process.argv);
if (program.debug) console.log(program.opts());
console.log('pizza details:');
if (program.small) console.log('- small pizza size');
if (program.pizzaType) console.log(`- ${program.pizzaType}`);
```
```bash
$ pizza-options -d
{ debug: true, small: undefined, pizzaType: undefined }
pizza details:
$ pizza-options -p
error: option '-p, --pizza-type <type>' argument missing
$ pizza-options -ds -p vegetarian
{ debug: true, small: true, pizzaType: 'vegetarian' }
pizza details:
- small pizza size
- vegetarian
$ pizza-options --pizza-type=cheese
pizza details:
- cheese
```
`program.parse(arguments)` processes the arguments, leaving any args not consumed by the options as the `program.args` array.
### Default option value
You can specify a default value for an option which takes a value.
```js
const program = require('commander');
program
.option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');
program.parse(process.argv);
console.log(`cheese: ${program.cheese}`);
```
```bash
$ pizza-options
cheese: blue
$ pizza-options --cheese stilton
cheese: stilton
```
### Other option types, negatable boolean and flag|value
You can specify a boolean option long name with a leading `no-` to set the option value to false when used.
Defined alone this also makes the option true by default.
If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
otherwise be. You can specify a default boolean value for a boolean flag and it can be overridden on command line.
```js
const program = require('commander');
program
.option('--no-sauce', 'Remove sauce')
.option('--cheese <flavour>', 'cheese flavour', 'mozzarella')
.option('--no-cheese', 'plain with no cheese')
.parse(process.argv);
const sauceStr = program.sauce ? 'sauce' : 'no sauce';
const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`;
console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
```
```bash
$ pizza-options
You ordered a pizza with sauce and mozzarella cheese
$ pizza-options --sauce
error: unknown option '--sauce'
$ pizza-options --cheese=blue
You ordered a pizza with sauce and blue cheese
$ pizza-options --no-sauce --no-cheese
You ordered a pizza with no sauce and no cheese
```
You can specify an option which functions as a flag but may also take a value (declared using square brackets).
```js
const program = require('commander');
program
.option('-c, --cheese [type]', 'Add cheese with optional type');
program.parse(process.argv);
if (program.cheese === undefined) console.log('no cheese');
else if (program.cheese === true) console.log('add cheese');
else console.log(`add cheese type ${program.cheese}`);
```
```bash
$ pizza-options
no cheese
$ pizza-options --cheese
add cheese
$ pizza-options --cheese mozzarella
add cheese type mozzarella
```
### Custom option processing
You may specify a function to do custom processing of option values. The callback function receives two parameters, the user specified value and the
previous value for the option. It returns the new value for the option.
This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing.
You can optionally specify the default/starting value for the option after the function.
```js
const program = require('commander');
function myParseInt(value, dummyPrevious) {
// parseInt takes a string and an optional radix
return parseInt(value);
}
function increaseVerbosity(dummyValue, previous) {
return previous + 1;
}
function collect(value, previous) {
return previous.concat([value]);
}
function commaSeparatedList(value, dummyPrevious) {
return value.split(',');
}
program
.option('-f, --float <number>', 'float argument', parseFloat)
.option('-i, --integer <number>', 'integer argument', myParseInt)
.option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
.option('-c, --collect <value>', 'repeatable value', collect, [])
.option('-l, --list <items>', 'comma separated list', commaSeparatedList)
;
program.parse(process.argv);
if (program.float !== undefined) console.log(`float: ${program.float}`);
if (program.integer !== undefined) console.log(`integer: ${program.integer}`);
if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);
if (program.collect.length > 0) console.log(program.collect);
if (program.list !== undefined) console.log(program.list);
```
```bash
$ custom -f 1e2
float: 100
$ custom --integer 2
integer: 2
$ custom -v -v -v
verbose: 3
$ custom -c a -c b -c c
[ 'a', 'b', 'c' ]
$ custom --list x,y,z
[ 'x', 'y', 'z' ]
```
### Version option
The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.
```js
program.version('0.0.1');
```
```bash
$ ./examples/pizza -V
0.0.1
```
You may change the flags and description by passing additional parameters to the `version` method, using
the same syntax for flags as the `option` method. The version flags can be named anything, but a long name is required.
```js
program.version('0.0.1', '-v, --vers', 'output the current version');
```
## Commands
You can specify (sub)commands for your top-level command using `.command`. There are two ways these can be implemented: using an action handler attached to the command, or as a separate executable file (described in more detail later). In the first parameter to `.command` you specify the command name and any command arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.
For example:
```js
// Command implemented using action handler (description is supplied separately to `.command`)
// Returns new command for configuring.
program
.command('clone <source> [destination]')
.description('clone a repository into a newly created directory')
.action((source, destination) => {
console.log('clone command called');
});
// Command implemented using separate executable file (description is second parameter to `.command`)
// Returns top-level command for adding more commands.
program
.command('start <service>', 'start named service')
.command('stop [service]', 'stop named service, or all if no name supplied');
```
### Specify the argument syntax
You use `.arguments` to specify the arguments for the top-level command, and for subcommands they are included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input.
```js
const program = require('commander');
program
.version('0.1.0')
.arguments('<cmd> [env]')
.action(function (cmd, env) {
cmdValue = cmd;
envValue = env;
});
program.parse(process.argv);
if (typeof cmdValue === 'undefined') {
console.error('no command given!');
process.exit(1);
}
console.log('command:', cmdValue);
console.log('environment:', envValue || "no environment given");
```
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
append `...` to the argument name. For example:
```js
const program = require('commander');
program
.version('0.1.0')
.command('rmdir <dir> [otherDirs...]')
.action(function (dir, otherDirs) {
console.log('rmdir %s', dir);
if (otherDirs) {
otherDirs.forEach(function (oDir) {
console.log('rmdir %s', oDir);
});
}
});
program.parse(process.argv);
```
The variadic argument is passed to the action handler as an array. (And this also applies to `program.args`.)
### Action handler (sub)commands
You can add options to a command that uses an action handler.
The action handler gets passed a parameter for each argument you declared, and one additional argument which is the
command object itself. This command argument has the values for the command-specific options added as properties.
```js
const program = require('commander');
program
.command('rm <dir>')
.option('-r, --recursive', 'Remove recursively')
.action(function (dir, cmdObj) {
console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : ''))
})
program.parse(process.argv)
```
A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output.
### Git-style executable (sub)commands
When `.command()` is invoked with a description argument, this tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.
You can specify a custom name with the `executableFile` configuration option.
You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
```js
// file: ./examples/pm
const program = require('commander');
program
.version('0.1.0')
.command('install [name]', 'install one or more packages')
.command('search [query]', 'search with optional query')
.command('update', 'update installed packages', {executableFile: 'myUpdateSubCommand'})
.command('list', 'list packages installed', {isDefault: true})
.parse(process.argv);
```
Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
Specifying a name with `executableFile` will override the default constructed name.
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
## Automated --help
The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
```bash
$ ./examples/pizza --help
Usage: pizza [options]
An application for pizzas ordering
Options:
-V, --version output the version number
-p, --peppers Add peppers
-P, --pineapple Add pineapple
-b, --bbq Add bbq sauce
-c, --cheese <type> Add the specified type of cheese (default: "marble")
-C, --no-cheese You do not want any cheese
-h, --help output usage information
```
### Custom help
You can display arbitrary `-h, --help` information
by listening for "--help". Commander will automatically
exit once you are done so that the remainder of your program
does not execute causing undesired behaviors, for example
in the following executable "stuff" will not output when
`--help` is used.
```js
#!/usr/bin/env node
const program = require('commander');
program
.version('0.1.0')
.option('-f, --foo', 'enable some foo')
.option('-b, --bar', 'enable some bar')
.option('-B, --baz', 'enable some baz');
// must be before .parse() since
// node's emit() is immediate
program.on('--help', function(){
console.log('')
console.log('Examples:');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
});
program.parse(process.argv);
console.log('stuff');
```
Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
```Text
Usage: custom-help [options]
Options:
-h, --help output usage information
-V, --version output the version number
-f, --foo enable some foo
-b, --bar enable some bar
-B, --baz enable some baz
Examples:
$ custom-help --help
$ custom-help -h
```
### .usage and .name
These allow you to customise the usage description in the first line of the help. The name is otherwise
deduced from the (full) program arguments. Given:
```js
program
.name("my-command")
.usage("[global options] command")
```
The help will start with:
```Text
Usage: my-command [global options] command
```
### .outputHelp(cb)
Output help information without exiting.
Optional callback cb allows post-processing of help text before it is displayed.
If you want to display help by default (e.g. if no command was provided), you can use something like:
```js
const program = require('commander');
const colors = require('colors');
program
.version('0.1.0')
.command('getstream [url]', 'get stream URL')
.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp(make_red);
}
function make_red(txt) {
return colors.red(txt); //display the help text in red on the console
}
```
### .helpOption(flags, description)
Override the default help flags and description.
```js
program
.helpOption('-e, --HELP', 'read more information');
```
### .help(cb)
Output help information and exit immediately.
Optional callback cb allows post-processing of help text before it is displayed.
## Custom event listeners
You can execute custom actions by listening to command and option events.
```js
program.on('option:verbose', function () {
process.env.VERBOSE = this.verbose;
});
// error on unknown commands
program.on('command:*', function () {
console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
process.exit(1);
});
```
## Bits and pieces
### TypeScript
The Commander package includes its TypeScript Definition file, but also requires the node types which you need to install yourself. e.g.
```bash
npm install commander
npm install --save-dev @types/node
```
If you use `ts-node` and git-style sub-commands written as `.ts` files, you need to call your program through node to get the sub-commands called correctly. e.g.
```bash
node -r ts-node/register pm.ts
```
### Node options such as `--harmony`
You can enable `--harmony` option in two ways:
- Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. (Note Windows does not support this pattern.)
- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.
### Node debugging
If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) git-style executable (sub)commands using `node -inspect` et al,
the inspector port is incremented by 1 for the spawned subcommand.
## Examples
```js
const program = require('commander');
program
.version('0.1.0')
.option('-C, --chdir <path>', 'change the working directory')
.option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
.option('-T, --no-tests', 'ignore test hook');
program
.command('setup [env]')
.description('run setup commands for all envs')
.option("-s, --setup_mode [mode]", "Which setup mode to use")
.action(function(env, options){
const mode = options.setup_mode || "normal";
env = env || 'all';
console.log('setup for %s env(s) with %s mode', env, mode);
});
program
.command('exec <cmd>')
.alias('ex')
.description('execute the given remote cmd')
.option("-e, --exec_mode <mode>", "Which exec mode to use")
.action(function(cmd, options){
console.log('exec "%s" using %s mode', cmd, options.exec_mode);
}).on('--help', function() {
console.log('');
console.log('Examples:');
console.log('');
console.log(' $ deploy exec sequential');
console.log(' $ deploy exec async');
});
program
.command('*')
.action(function(env){
console.log('deploying "%s"', env);
});
program.parse(process.argv);
```
More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
## License
[MIT](https://github.com/tj/commander.js/blob/master/LICENSE)
## Support
[Professionally supported commander is now available](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=readme)
Tidelift gives software development teams a single source for purchasing and maintaining their software, with professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,74 @@
{
"_args": [
[
"commander@3.0.2",
"D:\\Projects\\siag\\vanillajs-seed"
]
],
"_development": true,
"_from": "commander@3.0.2",
"_id": "commander@3.0.2",
"_inBundle": false,
"_integrity": "sha512-Gar0ASD4BDyKC4hl4DwHqDrmvjoxWKZigVnAbn5H1owvm4CxCPdb0HQDehwNYMJpla5+M2tPmPARzhtYuwpHow==",
"_location": "/i18next-scanner/commander",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "commander@3.0.2",
"name": "commander",
"escapedName": "commander",
"rawSpec": "3.0.2",
"saveSpec": null,
"fetchSpec": "3.0.2"
},
"_requiredBy": [
"/i18next-scanner"
],
"_resolved": "https://registry.npmjs.org/commander/-/commander-3.0.2.tgz",
"_spec": "3.0.2",
"_where": "D:\\Projects\\siag\\vanillajs-seed",
"author": {
"name": "TJ Holowaychuk",
"email": "tj@vision-media.ca"
},
"bugs": {
"url": "https://github.com/tj/commander.js/issues"
},
"dependencies": {},
"description": "the complete solution for node.js command-line programs",
"devDependencies": {
"@types/node": "^12.7.8",
"eslint": "^6.4.0",
"should": "^13.2.3",
"sinon": "^7.5.0",
"standard": "^13.1.0",
"ts-node": "^8.4.1",
"typescript": "^3.6.3"
},
"files": [
"index.js",
"typings/index.d.ts"
],
"homepage": "https://github.com/tj/commander.js#readme",
"keywords": [
"commander",
"command",
"option",
"parser"
],
"license": "MIT",
"main": "index",
"name": "commander",
"repository": {
"type": "git",
"url": "git+https://github.com/tj/commander.js.git"
},
"scripts": {
"lint": "eslint index.js",
"test": "node test/run.js && npm run test-typings",
"test-typings": "tsc -p tsconfig.json"
},
"typings": "typings/index.d.ts",
"version": "3.0.2"
}

View File

@@ -0,0 +1,300 @@
// Type definitions for commander 2.11
// Project: https://github.com/visionmedia/commander.js
// Definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///<reference types="node" />
declare namespace local {
class Option {
flags: string;
required: boolean;
optional: boolean;
bool: boolean;
short?: string;
long: string;
description: string;
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {string} flags
* @param {string} [description]
*/
constructor(flags: string, description?: string);
}
class Command extends NodeJS.EventEmitter {
[key: string]: any;
args: string[];
/**
* Initialize a new `Command`.
*
* @param {string} [name]
*/
constructor(name?: string);
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* You can optionally supply the flags and description to override the defaults.
*
*/
version(str: string, flags?: string, description?: string): Command;
/**
* Define a command, implemented using an action handler.
*
* @remarks
* The command description is supplied using `.description`, not as a parameter to `.command`.
*
* @example
* ```ts
* program
* .command('clone <source> [destination]')
* .description('clone a repository into a newly created directory')
* .action((source, destination) => {
* console.log('clone command called');
* });
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param opts - configuration options
* @returns new command
*/
command(nameAndArgs: string, opts?: commander.CommandOptions): Command;
/**
* Define a command, implemented in a separate executable file.
*
* @remarks
* The command description is supplied as the second parameter to `.command`.
*
* @example
* ```ts
* program
* .command('start <service>', 'start named service')
* .command('stop [service]', 'stop named serice, or all if no name supplied');
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param description - description of executable command
* @param opts - configuration options
* @returns top level command for chaining more command definitions
*/
command(nameAndArgs: string, description: string, opts?: commander.CommandOptions): Command;
/**
* Define argument syntax for the top-level command.
*
* @param {string} desc
* @returns {Command} for chaining
*/
arguments(desc: string): Command;
/**
* Parse expected `args`.
*
* For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
*
* @param {string[]} args
* @returns {Command} for chaining
*/
parseExpectedArgs(args: string[]): Command;
/**
* Register callback `fn` for the command.
*
* @example
* program
* .command('help')
* .description('display verbose help')
* .action(function() {
* // output help here
* });
*
* @param {(...args: any[]) => void} fn
* @returns {Command} for chaining
*/
action(fn: (...args: any[]) => void): Command;
/**
* Define option with `flags`, `description` and optional
* coercion `fn`.
*
* The `flags` string should contain both the short and long flags,
* separated by comma, a pipe or space. The following are all valid
* all will output this way when `--help` is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* @example
* // simple boolean defaulting to false
* program.option('-p, --pepper', 'add pepper');
*
* --pepper
* program.pepper
* // => Boolean
*
* // simple boolean defaulting to true
* program.option('-C, --no-cheese', 'remove cheese');
*
* program.cheese
* // => true
*
* --no-cheese
* program.cheese
* // => false
*
* // required argument
* program.option('-C, --chdir <path>', 'change the working directory');
*
* --chdir /tmp
* program.chdir
* // => "/tmp"
*
* // optional argument
* program.option('-c, --cheese [type]', 'add cheese [marble]');
*
* @param {string} flags
* @param {string} [description]
* @param {((arg1: any, arg2: any) => void) | RegExp} [fn] function or default
* @param {*} [defaultValue]
* @returns {Command} for chaining
*/
option(flags: string, description?: string, fn?: ((arg1: any, arg2: any) => void) | RegExp, defaultValue?: any): Command;
option(flags: string, description?: string, defaultValue?: any): Command;
/**
* Allow unknown options on the command line.
*
* @param {boolean} [arg] if `true` or omitted, no error will be thrown for unknown options.
* @returns {Command} for chaining
*/
allowUnknownOption(arg?: boolean): Command;
/**
* Parse `argv`, settings options and invoking commands when defined.
*
* @param {string[]} argv
* @returns {Command} for chaining
*/
parse(argv: string[]): Command;
/**
* Parse options from `argv` returning `argv` void of these options.
*
* @param {string[]} argv
* @returns {ParseOptionsResult}
*/
parseOptions(argv: string[]): commander.ParseOptionsResult;
/**
* Return an object containing options as key-value pairs
*
* @returns {{[key: string]: any}}
*/
opts(): { [key: string]: any };
/**
* Set the description to `str`.
*
* @param {string} str
* @param {{[argName: string]: string}} argsDescription
* @return {(Command | string)}
*/
description(str: string, argsDescription?: {[argName: string]: string}): Command;
description(): string;
/**
* Set an alias for the command.
*
* @param {string} alias
* @return {(Command | string)}
*/
alias(alias: string): Command;
alias(): string;
/**
* Set or get the command usage.
*
* @param {string} str
* @return {(Command | string)}
*/
usage(str: string): Command;
usage(): string;
/**
* Set the name of the command.
*
* @param {string} str
* @return {Command}
*/
name(str: string): Command;
/**
* Get the name of the command.
*
* @return {string}
*/
name(): string;
/**
* Output help information for this command.
*
* When listener(s) are available for the helpLongFlag
* those callbacks are invoked.
*
* @param {(str: string) => string} [cb]
*/
outputHelp(cb?: (str: string) => string): void;
/**
* You can pass in flags and a description to override the help
* flags and help description for your command.
*/
helpOption(flags?: string, description?: string): Command;
/**
* Output help information and exit.
*/
help(cb?: (str: string) => string): never;
}
}
declare namespace commander {
type Command = local.Command
type Option = local.Option
interface CommandOptions {
noHelp?: boolean;
isDefault?: boolean;
executableFile?: string;
}
interface ParseOptionsResult {
args: string[];
unknown: string[];
}
interface CommanderStatic extends Command {
Command: typeof local.Command;
Option: typeof local.Option;
CommandOptions: CommandOptions;
ParseOptionsResult: ParseOptionsResult;
}
}
declare const commander: commander.CommanderStatic;
export = commander;

View File

@@ -0,0 +1,235 @@
2018-06-17: Version 4.0.1
* Fix parsing async get/set in a class (issue 1861, 1875)
* Account for different return statement argument (issue 1829, 1897, 1928)
* Correct the handling of HTML comment when parsing a module (issue 1841)
* Fix incorrect parse async with proto-identifier-shorthand (issue 1847)
* Fix negative column in binary expression (issue 1844)
* Fix incorrect YieldExpression in object methods (issue 1834)
* Various documentation fixes
2017-06-10: Version 4.0.0
* Support ES2017 async function and await expression (issue 1079)
* Support ES2017 trailing commas in function parameters (issue 1550)
* Explicitly distinguish parsing a module vs a script (issue 1576)
* Fix JSX non-empty container (issue 1786)
* Allow JSX element in a yield expression (issue 1765)
* Allow `in` expression in a concise body with a function body (issue 1793)
* Setter function argument must not be a rest parameter (issue 1693)
* Limit strict mode directive to functions with a simple parameter list (issue 1677)
* Prohibit any escape sequence in a reserved word (issue 1612)
* Only permit hex digits in hex escape sequence (issue 1619)
* Prohibit labelled class/generator/function declaration (issue 1484)
* Limit function declaration as if statement clause only in non-strict mode (issue 1657)
* Tolerate missing ) in a with and do-while statement (issue 1481)
2016-12-22: Version 3.1.3
* Support binding patterns as rest element (issue 1681)
* Account for different possible arguments of a yield expression (issue 1469)
2016-11-24: Version 3.1.2
* Ensure that import specifier is more restrictive (issue 1615)
* Fix duplicated JSX tokens (issue 1613)
* Scan template literal in a JSX expression container (issue 1622)
* Improve XHTML entity scanning in JSX (issue 1629)
2016-10-31: Version 3.1.1
* Fix assignment expression problem in an export declaration (issue 1596)
* Fix incorrect tokenization of hex digits (issue 1605)
2016-10-09: Version 3.1.0
* Do not implicitly collect comments when comment attachment is specified (issue 1553)
* Fix incorrect handling of duplicated proto shorthand fields (issue 1485)
* Prohibit initialization in some variants of for statements (issue 1309, 1561)
* Fix incorrect parsing of export specifier (issue 1578)
* Fix ESTree compatibility for assignment pattern (issue 1575)
2016-09-03: Version 3.0.0
* Support ES2016 exponentiation expression (issue 1490)
* Support JSX syntax (issue 1467)
* Use the latest Unicode 8.0 (issue 1475)
* Add the support for syntax node delegate (issue 1435)
* Fix ESTree compatibility on meta property (issue 1338)
* Fix ESTree compatibility on default parameter value (issue 1081)
* Fix ESTree compatibility on try handler (issue 1030)
2016-08-23: Version 2.7.3
* Fix tokenizer confusion with a comment (issue 1493, 1516)
2016-02-02: Version 2.7.2
* Fix out-of-bound error location in an invalid string literal (issue 1457)
* Fix shorthand object destructuring defaults in variable declarations (issue 1459)
2015-12-10: Version 2.7.1
* Do not allow trailing comma in a variable declaration (issue 1360)
* Fix assignment to `let` in non-strict mode (issue 1376)
* Fix missing delegate property in YieldExpression (issue 1407)
2015-10-22: Version 2.7.0
* Fix the handling of semicolon in a break statement (issue 1044)
* Run the test suite with major web browsers (issue 1259, 1317)
* Allow `let` as an identifier in non-strict mode (issue 1289)
* Attach orphaned comments as `innerComments` (issue 1328)
* Add the support for token delegator (issue 1332)
2015-09-01: Version 2.6.0
* Properly allow or prohibit `let` in a binding identifier/pattern (issue 1048, 1098)
* Add sourceType field for Program node (issue 1159)
* Ensure that strict mode reserved word binding throw an error (issue 1171)
* Run the test suite with Node.js and IE 11 on Windows (issue 1294)
* Allow binding pattern with no initializer in a for statement (issue 1301)
2015-07-31: Version 2.5.0
* Run the test suite in a browser environment (issue 1004)
* Ensure a comma between imported default binding and named imports (issue 1046)
* Distinguish `yield` as a keyword vs an identifier (issue 1186)
* Support ES6 meta property `new.target` (issue 1203)
* Fix the syntax node for yield with expression (issue 1223)
* Fix the check of duplicated proto in property names (issue 1225)
* Fix ES6 Unicode escape in identifier name (issue 1229)
* Support ES6 IdentifierStart and IdentifierPart (issue 1232)
* Treat await as a reserved word when parsing as a module (issue 1234)
* Recognize identifier characters from Unicode SMP (issue 1244)
* Ensure that export and import can be followed by a comma (issue 1250)
* Fix yield operator precedence (issue 1262)
2015-07-01: Version 2.4.1
* Fix some cases of comment attachment (issue 1071, 1175)
* Fix the handling of destructuring in function arguments (issue 1193)
* Fix invalid ranges in assignment expression (issue 1201)
2015-06-26: Version 2.4.0
* Support ES6 for-of iteration (issue 1047)
* Support ES6 spread arguments (issue 1169)
* Minimize npm payload (issue 1191)
2015-06-16: Version 2.3.0
* Support ES6 generator (issue 1033)
* Improve parsing of regular expressions with `u` flag (issue 1179)
2015-04-17: Version 2.2.0
* Support ES6 import and export declarations (issue 1000)
* Fix line terminator before arrow not recognized as error (issue 1009)
* Support ES6 destructuring (issue 1045)
* Support ES6 template literal (issue 1074)
* Fix the handling of invalid/incomplete string escape sequences (issue 1106)
* Fix ES3 static member access restriction (issue 1120)
* Support for `super` in ES6 class (issue 1147)
2015-03-09: Version 2.1.0
* Support ES6 class (issue 1001)
* Support ES6 rest parameter (issue 1011)
* Expand the location of property getter, setter, and methods (issue 1029)
* Enable TryStatement transition to a single handler (issue 1031)
* Support ES6 computed property name (issue 1037)
* Tolerate unclosed block comment (issue 1041)
* Support ES6 lexical declaration (issue 1065)
2015-02-06: Version 2.0.0
* Support ES6 arrow function (issue 517)
* Support ES6 Unicode code point escape (issue 521)
* Improve the speed and accuracy of comment attachment (issue 522)
* Support ES6 default parameter (issue 519)
* Support ES6 regular expression flags (issue 557)
* Fix scanning of implicit octal literals (issue 565)
* Fix the handling of automatic semicolon insertion (issue 574)
* Support ES6 method definition (issue 620)
* Support ES6 octal integer literal (issue 621)
* Support ES6 binary integer literal (issue 622)
* Support ES6 object literal property value shorthand (issue 624)
2015-03-03: Version 1.2.5
* Fix scanning of implicit octal literals (issue 565)
2015-02-05: Version 1.2.4
* Fix parsing of LeftHandSideExpression in ForInStatement (issue 560)
* Fix the handling of automatic semicolon insertion (issue 574)
2015-01-18: Version 1.2.3
* Fix division by this (issue 616)
2014-05-18: Version 1.2.2
* Fix duplicated tokens when collecting comments (issue 537)
2014-05-04: Version 1.2.1
* Ensure that Program node may still have leading comments (issue 536)
2014-04-29: Version 1.2.0
* Fix semicolon handling for expression statement (issue 462, 533)
* Disallow escaped characters in regular expression flags (issue 503)
* Performance improvement for location tracking (issue 520)
* Improve the speed of comment attachment (issue 522)
2014-03-26: Version 1.1.1
* Fix token handling of forward slash after an array literal (issue 512)
2014-03-23: Version 1.1.0
* Optionally attach comments to the owning syntax nodes (issue 197)
* Simplify binary parsing with stack-based shift reduce (issue 352)
* Always include the raw source of literals (issue 376)
* Add optional input source information (issue 386)
* Tokenizer API for pure lexical scanning (issue 398)
* Improve the web site and its online demos (issue 337, 400, 404)
* Performance improvement for location tracking (issue 417, 424)
* Support HTML comment syntax (issue 451)
* Drop support for legacy browsers (issue 474)
2013-08-27: Version 1.0.4
* Minimize the payload for packages (issue 362)
* Fix missing cases on an empty switch statement (issue 436)
* Support escaped ] in regexp literal character classes (issue 442)
* Tolerate invalid left-hand side expression (issue 130)
2013-05-17: Version 1.0.3
* Variable declaration needs at least one declarator (issue 391)
* Fix benchmark's variance unit conversion (issue 397)
* IE < 9: \v should be treated as vertical tab (issue 405)
* Unary expressions should always have prefix: true (issue 418)
* Catch clause should only accept an identifier (issue 423)
* Tolerate setters without parameter (issue 426)
2012-11-02: Version 1.0.2
Improvement:
* Fix esvalidate JUnit output upon a syntax error (issue 374)
2012-10-28: Version 1.0.1
Improvements:
* esvalidate understands shebang in a Unix shell script (issue 361)
* esvalidate treats fatal parsing failure as an error (issue 361)
* Reduce Node.js package via .npmignore (issue 362)
2012-10-22: Version 1.0.0
Initial release.

View File

@@ -0,0 +1,21 @@
Copyright JS Foundation and other contributors, https://js.foundation/
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.
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 <COPYRIGHT HOLDER> 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.

View File

@@ -0,0 +1,46 @@
[![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima)
[![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima)
[![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima)
[![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima)
**Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance,
standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
parser written in ECMAScript (also popularly known as
[JavaScript](https://en.wikipedia.org/wiki/JavaScript)).
Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat),
with the help of [many contributors](https://github.com/jquery/esprima/contributors).
### Features
- Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm))
- Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree)
- Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/)
- Optional tracking of syntax node location (index-based and line-column)
- [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima))
### API
Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program.
A simple example on Node.js REPL:
```javascript
> var esprima = require('esprima');
> var program = 'const answer = 42';
> esprima.tokenize(program);
[ { type: 'Keyword', value: 'const' },
{ type: 'Identifier', value: 'answer' },
{ type: 'Punctuator', value: '=' },
{ type: 'Numeric', value: '42' } ]
> esprima.parseScript(program);
{ type: 'Program',
body:
[ { type: 'VariableDeclaration',
declarations: [Object],
kind: 'const' } ],
sourceType: 'script' }
```
For more information, please read the [complete documentation](http://esprima.org/doc).

View File

@@ -0,0 +1,139 @@
#!/usr/bin/env node
/*
Copyright JS Foundation and other contributors, https://js.foundation/
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.
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 <COPYRIGHT HOLDER> 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.
*/
/*jslint sloppy:true node:true rhino:true */
var fs, esprima, fname, forceFile, content, options, syntax;
if (typeof require === 'function') {
fs = require('fs');
try {
esprima = require('esprima');
} catch (e) {
esprima = require('../');
}
} else if (typeof load === 'function') {
try {
load('esprima.js');
} catch (e) {
load('../esprima.js');
}
}
// Shims to Node.js objects when running under Rhino.
if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print };
fs = { readFileSync: readFile };
process = { argv: arguments, exit: quit };
process.argv.unshift('esparse.js');
process.argv.unshift('rhino');
}
function showUsage() {
console.log('Usage:');
console.log(' esparse [options] [file.js]');
console.log();
console.log('Available options:');
console.log();
console.log(' --comment Gather all line and block comments in an array');
console.log(' --loc Include line-column location info for each syntax node');
console.log(' --range Include index-based range for each syntax node');
console.log(' --raw Display the raw value of literals');
console.log(' --tokens List all tokens in an array');
console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)');
console.log(' -v, --version Shows program version');
console.log();
process.exit(1);
}
options = {};
process.argv.splice(2).forEach(function (entry) {
if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') {
if (typeof fname === 'string') {
console.log('Error: more than one input file.');
process.exit(1);
} else {
fname = entry;
}
} else if (entry === '-h' || entry === '--help') {
showUsage();
} else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Parser (using Esprima version', esprima.version, ')');
console.log();
process.exit(0);
} else if (entry === '--comment') {
options.comment = true;
} else if (entry === '--loc') {
options.loc = true;
} else if (entry === '--range') {
options.range = true;
} else if (entry === '--raw') {
options.raw = true;
} else if (entry === '--tokens') {
options.tokens = true;
} else if (entry === '--tolerant') {
options.tolerant = true;
} else if (entry === '--') {
forceFile = true;
} else {
console.log('Error: unknown option ' + entry + '.');
process.exit(1);
}
});
// Special handling for regular expression literal since we need to
// convert it to a string literal, otherwise it will be decoded
// as object "{}" and the regular expression would be lost.
function adjustRegexLiteral(key, value) {
if (key === 'value' && value instanceof RegExp) {
value = value.toString();
}
return value;
}
function run(content) {
syntax = esprima.parse(content, options);
console.log(JSON.stringify(syntax, adjustRegexLiteral, 4));
}
try {
if (fname && (fname !== '-' || forceFile)) {
run(fs.readFileSync(fname, 'utf-8'));
} else {
var content = '';
process.stdin.resume();
process.stdin.on('data', function(chunk) {
content += chunk;
});
process.stdin.on('end', function() {
run(content);
});
}
} catch (e) {
console.log('Error: ' + e.message);
process.exit(1);
}

View File

@@ -0,0 +1,236 @@
#!/usr/bin/env node
/*
Copyright JS Foundation and other contributors, https://js.foundation/
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.
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 <COPYRIGHT HOLDER> 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.
*/
/*jslint sloppy:true plusplus:true node:true rhino:true */
/*global phantom:true */
var fs, system, esprima, options, fnames, forceFile, count;
if (typeof esprima === 'undefined') {
// PhantomJS can only require() relative files
if (typeof phantom === 'object') {
fs = require('fs');
system = require('system');
esprima = require('./esprima');
} else if (typeof require === 'function') {
fs = require('fs');
try {
esprima = require('esprima');
} catch (e) {
esprima = require('../');
}
} else if (typeof load === 'function') {
try {
load('esprima.js');
} catch (e) {
load('../esprima.js');
}
}
}
// Shims to Node.js objects when running under PhantomJS 1.7+.
if (typeof phantom === 'object') {
fs.readFileSync = fs.read;
process = {
argv: [].slice.call(system.args),
exit: phantom.exit,
on: function (evt, callback) {
callback();
}
};
process.argv.unshift('phantomjs');
}
// Shims to Node.js objects when running under Rhino.
if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print };
fs = { readFileSync: readFile };
process = {
argv: arguments,
exit: quit,
on: function (evt, callback) {
callback();
}
};
process.argv.unshift('esvalidate.js');
process.argv.unshift('rhino');
}
function showUsage() {
console.log('Usage:');
console.log(' esvalidate [options] [file.js...]');
console.log();
console.log('Available options:');
console.log();
console.log(' --format=type Set the report format, plain (default) or junit');
console.log(' -v, --version Print program version');
console.log();
process.exit(1);
}
options = {
format: 'plain'
};
fnames = [];
process.argv.splice(2).forEach(function (entry) {
if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') {
fnames.push(entry);
} else if (entry === '-h' || entry === '--help') {
showUsage();
} else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Validator (using Esprima version', esprima.version, ')');
console.log();
process.exit(0);
} else if (entry.slice(0, 9) === '--format=') {
options.format = entry.slice(9);
if (options.format !== 'plain' && options.format !== 'junit') {
console.log('Error: unknown report format ' + options.format + '.');
process.exit(1);
}
} else if (entry === '--') {
forceFile = true;
} else {
console.log('Error: unknown option ' + entry + '.');
process.exit(1);
}
});
if (fnames.length === 0) {
fnames.push('');
}
if (options.format === 'junit') {
console.log('<?xml version="1.0" encoding="UTF-8"?>');
console.log('<testsuites>');
}
count = 0;
function run(fname, content) {
var timestamp, syntax, name;
try {
if (typeof content !== 'string') {
throw content;
}
if (content[0] === '#' && content[1] === '!') {
content = '//' + content.substr(2, content.length);
}
timestamp = Date.now();
syntax = esprima.parse(content, { tolerant: true });
if (options.format === 'junit') {
name = fname;
if (name.lastIndexOf('/') >= 0) {
name = name.slice(name.lastIndexOf('/') + 1);
}
console.log('<testsuite name="' + fname + '" errors="0" ' +
' failures="' + syntax.errors.length + '" ' +
' tests="' + syntax.errors.length + '" ' +
' time="' + Math.round((Date.now() - timestamp) / 1000) +
'">');
syntax.errors.forEach(function (error) {
var msg = error.message;
msg = msg.replace(/^Line\ [0-9]*\:\ /, '');
console.log(' <testcase name="Line ' + error.lineNumber + ': ' + msg + '" ' +
' time="0">');
console.log(' <error type="SyntaxError" message="' + error.message + '">' +
error.message + '(' + name + ':' + error.lineNumber + ')' +
'</error>');
console.log(' </testcase>');
});
console.log('</testsuite>');
} else if (options.format === 'plain') {
syntax.errors.forEach(function (error) {
var msg = error.message;
msg = msg.replace(/^Line\ [0-9]*\:\ /, '');
msg = fname + ':' + error.lineNumber + ': ' + msg;
console.log(msg);
++count;
});
}
} catch (e) {
++count;
if (options.format === 'junit') {
console.log('<testsuite name="' + fname + '" errors="1" failures="0" tests="1" ' +
' time="' + Math.round((Date.now() - timestamp) / 1000) + '">');
console.log(' <testcase name="' + e.message + '" ' + ' time="0">');
console.log(' <error type="ParseError" message="' + e.message + '">' +
e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') +
')</error>');
console.log(' </testcase>');
console.log('</testsuite>');
} else {
console.log(fname + ':' + e.lineNumber + ': ' + e.message.replace(/^Line\ [0-9]*\:\ /, ''));
}
}
}
fnames.forEach(function (fname) {
var content = '';
try {
if (fname && (fname !== '-' || forceFile)) {
content = fs.readFileSync(fname, 'utf-8');
} else {
fname = '';
process.stdin.resume();
process.stdin.on('data', function(chunk) {
content += chunk;
});
process.stdin.on('end', function() {
run(fname, content);
});
return;
}
} catch (e) {
content = e;
}
run(fname, content);
});
process.on('exit', function () {
if (options.format === 'junit') {
console.log('</testsuites>');
}
if (count > 0) {
process.exit(1);
}
if (count === 0 && typeof phantom === 'object') {
process.exit(0);
}
});

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,141 @@
{
"_args": [
[
"esprima@4.0.1",
"D:\\Projects\\siag\\vanillajs-seed"
]
],
"_development": true,
"_from": "esprima@4.0.1",
"_id": "esprima@4.0.1",
"_inBundle": false,
"_integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
"_location": "/i18next-scanner/esprima",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "esprima@4.0.1",
"name": "esprima",
"escapedName": "esprima",
"rawSpec": "4.0.1",
"saveSpec": null,
"fetchSpec": "4.0.1"
},
"_requiredBy": [
"/i18next-scanner"
],
"_resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
"_spec": "4.0.1",
"_where": "D:\\Projects\\siag\\vanillajs-seed",
"author": {
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com"
},
"bin": {
"esparse": "bin/esparse.js",
"esvalidate": "bin/esvalidate.js"
},
"bugs": {
"url": "https://github.com/jquery/esprima/issues"
},
"description": "ECMAScript parsing infrastructure for multipurpose analysis",
"devDependencies": {
"codecov.io": "~0.1.6",
"escomplex-js": "1.2.0",
"everything.js": "~1.0.3",
"glob": "~7.1.0",
"istanbul": "~0.4.0",
"json-diff": "~0.3.1",
"karma": "~1.3.0",
"karma-chrome-launcher": "~2.0.0",
"karma-detect-browsers": "~2.2.3",
"karma-edge-launcher": "~0.2.0",
"karma-firefox-launcher": "~1.0.0",
"karma-ie-launcher": "~1.0.0",
"karma-mocha": "~1.3.0",
"karma-safari-launcher": "~1.0.0",
"karma-safaritechpreview-launcher": "~0.0.4",
"karma-sauce-launcher": "~1.1.0",
"lodash": "~3.10.1",
"mocha": "~3.2.0",
"node-tick-processor": "~0.0.2",
"regenerate": "~1.3.2",
"temp": "~0.8.3",
"tslint": "~5.1.0",
"typescript": "~2.3.2",
"typescript-formatter": "~5.1.3",
"unicode-8.0.0": "~0.7.0",
"webpack": "~1.14.0"
},
"engines": {
"node": ">=4"
},
"files": [
"bin",
"dist/esprima.js"
],
"homepage": "http://esprima.org",
"keywords": [
"ast",
"ecmascript",
"esprima",
"javascript",
"parser",
"syntax"
],
"license": "BSD-2-Clause",
"main": "dist/esprima.js",
"maintainers": [
{
"name": "Ariya Hidayat",
"email": "ariya.hidayat@gmail.com",
"url": "http://ariya.ofilabs.com"
}
],
"name": "esprima",
"repository": {
"type": "git",
"url": "git+https://github.com/jquery/esprima.git"
},
"scripts": {
"all-tests": "npm run verify-line-ending && npm run generate-fixtures && npm run unit-tests && npm run api-tests && npm run grammar-tests && npm run regression-tests && npm run hostile-env-tests",
"analyze-coverage": "istanbul cover test/unit-tests.js",
"api-tests": "mocha -R dot test/api-tests.js",
"appveyor": "npm run compile && npm run all-tests && npm run browser-tests",
"benchmark": "npm run benchmark-parser && npm run benchmark-tokenizer",
"benchmark-parser": "node -expose_gc test/benchmark-parser.js",
"benchmark-tokenizer": "node --expose_gc test/benchmark-tokenizer.js",
"browser-tests": "npm run compile && npm run generate-fixtures && cd test && karma start --single-run",
"check-coverage": "istanbul check-coverage --statement 100 --branch 100 --function 100",
"check-version": "node test/check-version.js",
"circleci": "npm test && npm run codecov && npm run downstream",
"code-style": "tsfmt --verify src/*.ts && tsfmt --verify test/*.js",
"codecov": "istanbul report cobertura && codecov < ./coverage/cobertura-coverage.xml",
"compile": "tsc -p src/ && webpack && node tools/fixupbundle.js",
"complexity": "node test/check-complexity.js",
"downstream": "node test/downstream.js",
"droneio": "npm run compile && npm run all-tests && npm run saucelabs",
"dynamic-analysis": "npm run analyze-coverage && npm run check-coverage",
"format-code": "tsfmt -r src/*.ts && tsfmt -r test/*.js",
"generate-fixtures": "node tools/generate-fixtures.js",
"generate-regex": "node tools/generate-identifier-regex.js",
"generate-xhtml-entities": "node tools/generate-xhtml-entities.js",
"grammar-tests": "node test/grammar-tests.js",
"hostile-env-tests": "node test/hostile-environment-tests.js",
"prepublish": "npm run compile",
"profile": "node --prof test/profile.js && mv isolate*.log v8.log && node-tick-processor",
"regression-tests": "node test/regression-tests.js",
"saucelabs": "npm run saucelabs-evergreen && npm run saucelabs-ie && npm run saucelabs-safari",
"saucelabs-evergreen": "cd test && karma start saucelabs-evergreen.conf.js",
"saucelabs-ie": "cd test && karma start saucelabs-ie.conf.js",
"saucelabs-safari": "cd test && karma start saucelabs-safari.conf.js",
"static-analysis": "npm run check-version && npm run tslint && npm run code-style && npm run complexity",
"test": "npm run compile && npm run all-tests && npm run static-analysis && npm run dynamic-analysis",
"travis": "npm test",
"tslint": "tslint src/*.ts",
"unit-tests": "node test/unit-tests.js",
"verify-line-ending": "node test/verify-line-ending.js"
},
"version": "4.0.1"
}

127
node_modules/i18next-scanner/package.json generated vendored Normal file
View File

@@ -0,0 +1,127 @@
{
"_args": [
[
"i18next-scanner@2.11.0",
"D:\\Projects\\siag\\vanillajs-seed"
]
],
"_development": true,
"_from": "i18next-scanner@2.11.0",
"_id": "i18next-scanner@2.11.0",
"_inBundle": false,
"_integrity": "sha512-/QqbSnUj9v6EwndaWeHp8NkHqLKAIHSlI1HXSyLdIPKWYM+Fnpk2tjnyjP8qn7L0rLT7HLH4bvyiw61wOIxf0A==",
"_location": "/i18next-scanner",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "i18next-scanner@2.11.0",
"name": "i18next-scanner",
"escapedName": "i18next-scanner",
"rawSpec": "2.11.0",
"saveSpec": null,
"fetchSpec": "2.11.0"
},
"_requiredBy": [
"#DEV:/"
],
"_resolved": "https://registry.npmjs.org/i18next-scanner/-/i18next-scanner-2.11.0.tgz",
"_spec": "2.11.0",
"_where": "D:\\Projects\\siag\\vanillajs-seed",
"author": {
"name": "Cheton Wu",
"email": "cheton@gmail.com"
},
"bin": {
"i18next-scanner": "bin/cli.js"
},
"bugs": {
"url": "https://github.com/i18next/i18next-scanner/issues"
},
"contributors": [
{
"name": "Cheton Wu",
"email": "cheton@gmail.com",
"url": "https://github.com/cheton"
}
],
"dependencies": {
"acorn": "^6.0.0",
"acorn-dynamic-import": "^4.0.0",
"acorn-jsx": "^5.2.0",
"acorn-stage3": "^2.0.0",
"acorn-walk": "^6.0.0",
"chalk": "^2.4.1",
"clone-deep": "^4.0.0",
"commander": "^3.0.1",
"deepmerge": "^4.0.0",
"ensure-array": "^1.0.0",
"eol": "^0.9.1",
"esprima": "^4.0.0",
"gulp-sort": "^2.0.0",
"i18next": "*",
"lodash": "^4.0.0",
"parse5": "^5.0.0",
"sortobject": "^1.1.1",
"through2": "^3.0.1",
"vinyl": "^2.2.0",
"vinyl-fs": "^3.0.1"
},
"description": "Scan your code, extract translation keys/values, and merge them into i18n resource files.",
"devDependencies": {
"@babel/cli": "~7.8.4",
"@babel/core": "~7.8.7",
"@babel/preset-env": "~7.8.7",
"@babel/register": "~7.8.6",
"@trendmicro/babel-config": "~1.0.0-alpha",
"babel-eslint": "~10.1.0",
"core-js": "^3.6.4",
"coveralls": "^3.0.9",
"eslint": "^6.8.0",
"eslint-config-trendmicro": "^1.4.1",
"eslint-plugin-import": "^2.20.1",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.19.0",
"gulp": "^4.0.2",
"gulp-tap": "^2.0.0",
"gulp-util": "^3.0.8",
"sha1": "^1.1.1",
"tap": "^14.10.6",
"text-table": "^0.2.0"
},
"engines": {
"node": ">=6"
},
"files": [
"bin",
"lib",
"tasks"
],
"homepage": "https://github.com/i18next/i18next-scanner",
"keywords": [
"i18n",
"i18next",
"gruntplugin",
"gulpplugin",
"gettext",
"hash",
"sha1",
"crc32",
"md5"
],
"license": "MIT",
"main": "lib/index.js",
"name": "i18next-scanner",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/i18next/i18next-scanner.git"
},
"scripts": {
"build": "babel ./src --out-dir ./lib",
"coveralls": "tap test/*.js --coverage --coverage-report=text-lcov --nyc-arg=--require --nyc-arg=babel-register | coveralls",
"eslint": "eslint ./src",
"prepublish": "npm run eslint && npm run build && npm test",
"test": "tap test/*.js --no-esm --no-timeout --node-arg=--require --node-arg=@babel/register --node-arg=--require --node-arg=core-js/stable --node-arg=--require --node-arg=regenerator-runtime/runtime"
},
"version": "2.11.0"
}

21
node_modules/i18next-scanner/tasks/index.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
'use strict';
var i18next = require('../lib');
var vfs = require('vinyl-fs');
module.exports = function(grunt) {
grunt.registerMultiTask('i18next', 'A grunt task for i18next-scanner', function() {
var done = this.async();
var options = this.options() || {};
var targets = (this.file) ? [this.file] : this.files;
targets.forEach(function(target) {
vfs.src(target.files || target.src, {base: target.base || '.'})
.pipe(i18next(options, target.customTransform, target.customFlush))
.pipe(vfs.dest(target.dest || '.'))
.on('end', function() {
done();
});
});
});
};