diff --git a/gulpfile.js b/gulpfile.js index 77628eb5..1f2665c4 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -5,7 +5,7 @@ var sass = require('gulp-sass')(require('sass')); var cleanCSS = require('gulp-clean-css'); var rename = require('gulp-rename'); var autoprefixer = require('gulp-autoprefixer'); -//var imagemin = require('gulp-imagemin'); +var imagemin = require('gulp-imagemin'); var sourcemaps = require('gulp-sourcemaps'); //var uglify = require('gulp-uglify'); //var concat = require('gulp-concat'); @@ -49,7 +49,7 @@ gulp.task('min-jpg', () => { progressive: true })])) .pipe(rename({prefix: "min-"})) - .pipe(gulp.dest('media')) + .pipe(gulp.dest('media/img')) }); // gulp verzeichnisse beobachten // ------------------------------------------------ @@ -57,7 +57,7 @@ gulp.task('watch', function() { gulp.series('default'); gulp.watch('src/sass/*.sass', gulp.series('sass')); // gulp.watch('src/js/*', //gulp.series('min-js')); - gulp.watch('src/images/*', //gulp.series('min-jpg')); + // gulp.watch('src/images/*', //gulp.series('min-jpg')); }); // gulp 1mal ausführen mit allen task // ------------------------------------------------ diff --git a/inc/MwllyKallernderQR.sla b/inc/MwllyKallernderQR.sla new file mode 100644 index 00000000..6a5f40ba --- /dev/null +++ b/inc/MwllyKallernderQR.sla @@ -0,0 +1,4563 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+

+ All files coa +

+
+
+ 100% + Statements + 1/1 +
+
+ 100% + Branches + 0/0 +
+
+ 100% + Functions + 0/0 +
+
+ 100% + Lines + 1/1 +
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
index.js
100%1/1100%0/0100%0/0100%1/1
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/index.js.html b/node_modules/coa/coverage/coa/index.js.html new file mode 100644 index 00000000..a5da1dd3 --- /dev/null +++ b/node_modules/coa/coverage/coa/index.js.html @@ -0,0 +1,68 @@ + + + + Code coverage report for coa/index.js + + + + + + + +
+
+

+ All files / coa index.js +

+
+
+ 100% + Statements + 1/1 +
+
+ 100% + Branches + 0/0 +
+
+ 100% + Functions + 0/0 +
+
+ 100% + Lines + 1/1 +
+
+
+
+

+
+
1 +21x + 
module.exports = require('./lib');
+ 
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/lib/arg.js.html b/node_modules/coa/coverage/coa/lib/arg.js.html new file mode 100644 index 00000000..85b03aec --- /dev/null +++ b/node_modules/coa/coverage/coa/lib/arg.js.html @@ -0,0 +1,239 @@ + + + + Code coverage report for coa/lib/arg.js + + + + + + + +
+
+

+ All files / coa/lib arg.js +

+
+
+ 100% + Statements + 16/16 +
+
+ 87.5% + Branches + 7/8 +
+
+ 100% + Functions + 6/6 +
+
+ 100% + Lines + 16/16 +
+
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59  +  +  +1x +1x +  +  +  +  +  +  +  +  +  +1x +  +  +  +  +  +16x +  +16x +  +  +  +31x +  +31x +31x +  +  +  +31x +  +  +  +28x +  +  +  +2x +  +  +  +1x +  +1x +  +1x +  +1x +  +  +  +1x +  +  + 
'use strict';
+ 
+const
+    CoaParam = require('./coaparam'),
+    Color = require('./color');
+ 
+/**
+ * Argument
+ *
+ * Unnamed entity. From command line arguments passed as list of unnamed values.
+ *
+ * @class Arg
+ * @extends CoaParam
+ */
+module.exports = class Arg extends CoaParam {
+    /**
+     * @constructs
+     * @param {COA.Cmd} cmd - parent command
+     */
+    constructor(cmd) {
+        super(cmd);
+ 
+        this._cmd._args.push(this);
+    }
+ 
+    _saveVal(args, val) {
+        this._val && (val = this._val(val));
+ 
+        const name = this._name;
+        this._arr
+            ? (args[name] || (args[name] = [])).push(val)
+            : (args[name] = val);
+ 
+        return val;
+    }
+ 
+    _parse(arg, args) {
+        return this._saveVal(args, arg);
+    }
+ 
+    _checkParsed(opts, args) {
+        return !args.hasOwnProperty(this._name);
+    }
+ 
+    _usage() {
+        const res = [];
+ 
+        res.push(Color('lpurple', this._name.toUpperCase()), ' : ', this._title);
+ 
+        this._req && res.push(' ', Color('lred', '(required)'));
+ 
+        return res.join('');
+    }
+ 
+    _requiredText() {
+        return `Missing required argument:\n  ${this._usage()}`;
+    }
+};
+ 
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/lib/cmd.js.html b/node_modules/coa/coverage/coa/lib/cmd.js.html new file mode 100644 index 00000000..03a50aca --- /dev/null +++ b/node_modules/coa/coverage/coa/lib/cmd.js.html @@ -0,0 +1,1556 @@ + + + + Code coverage report for coa/lib/cmd.js + + + + + + + +
+
+

+ All files / coa/lib cmd.js +

+
+
+ 81.22% + Statements + 147/181 +
+
+ 71.64% + Branches + 96/134 +
+
+ 68.75% + Functions + 33/48 +
+
+ 82.53% + Lines + 137/166 +
+
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291 +292 +293 +294 +295 +296 +297 +298 +299 +300 +301 +302 +303 +304 +305 +306 +307 +308 +309 +310 +311 +312 +313 +314 +315 +316 +317 +318 +319 +320 +321 +322 +323 +324 +325 +326 +327 +328 +329 +330 +331 +332 +333 +334 +335 +336 +337 +338 +339 +340 +341 +342 +343 +344 +345 +346 +347 +348 +349 +350 +351 +352 +353 +354 +355 +356 +357 +358 +359 +360 +361 +362 +363 +364 +365 +366 +367 +368 +369 +370 +371 +372 +373 +374 +375 +376 +377 +378 +379 +380 +381 +382 +383 +384 +385 +386 +387 +388 +389 +390 +391 +392 +393 +394 +395 +396 +397 +398 +399 +400 +401 +402 +403 +404 +405 +406 +407 +408 +409 +410 +411 +412 +413 +414 +415 +416 +417 +418 +419 +420 +421 +422 +423 +424 +425 +426 +427 +428 +429 +430 +431 +432 +433 +434 +435 +436 +437 +438 +439 +440 +441 +442 +443 +444 +445 +446 +447 +448 +449 +450 +451 +452 +453 +454 +455 +456 +457 +458 +459 +460 +461 +462 +463 +464 +465 +466 +467 +468 +469 +470 +471 +472 +473 +474 +475 +476 +477 +478 +479 +480 +481 +482 +483 +484 +485 +486 +487 +488 +489 +490 +491 +492 +493 +494 +495 +496 +497 +498  +  +  +1x +1x +1x +  +1x +  +1x +1x +1x +1x +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +26x +  +26x +26x +26x +26x +26x +26x +26x +26x +  +  +  +21x +  +  +  +  +  +  +  +  +  +  +2x +2x +1x +  +  +2x +2x +1x +  +2x +  +  +  +28x +  +28x +  +  +  +  +28x +  +  +  +44x +  +  +  +  +  +  +  +  +  +12x +  +12x +  +  +12x +  +  +  +  +  +  +  +  +  +7x +  +  +  +  +  +  +  +  +  +  +16x +  +  +  +  +  +  +  +  +16x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +16x +  +16x +16x +  +16x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +5x +5x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +19x +19x +1x +  +18x +  +  +  +  +  +22x +  +21x +  +21x +41x +2x +  +  +  +35x +  +  +35x +35x +75x +  +75x +62x +62x +  +  +13x +13x +5x +2x +  +  +  +3x +3x +3x +3x +4x +4x +1x +  +  +  +5x +5x +5x +3x +  +2x +2x +2x +  +  +  +  +5x +  +  +  +13x +  +5x +  +  +27x +  +  +  +24x +24x +24x +24x +  +  +24x +47x +19x +19x +1x +1x +  +  +19x +19x +  +18x +  +17x +  +  +28x +28x +  +  +28x +30x +30x +  +28x +28x +  +  +  +20x +  +  +  +  +  +  +44x +14x +  +  +  +44x +  +  +  +4x +  +4x +3x +  +3x +  +  +  +  +3x +3x +  +  +3x +4x +  +  +  +4x +  +  +  +24x +24x +  +  +  +  +  +  +  +26x +22x +  +  +44x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +3x +3x +3x +3x +  +3x +1x +1x +1x +  +  +3x +3x +1x +  +2x +  +2x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +24x +  +  +  +5x +5x +  +  +  +  +  +1x + 
'use strict';
+ 
+const
+    UTIL = require('util'),
+    PATH = require('path'),
+    EOL = require('os').EOL,
+ 
+    Q = require('q'),
+ 
+    CoaObject = require('./coaobject'),
+    Color = require('./color'),
+    Opt = require('./opt'),
+    Arg = require('./arg'),
+    completion = require('./completion');
+ 
+/**
+ * Command
+ *
+ * Top level entity. Commands may have options and arguments.
+ *
+ * @namespace
+ * @class Cmd
+ * @extends CoaObject
+ */
+class Cmd extends CoaObject {
+    /**
+     * @constructs
+     * @param {COA.Cmd} [cmd] parent command
+     */
+    constructor(cmd) {
+        super(cmd);
+ 
+        this._parent(cmd);
+        this._cmds = [];
+        this._cmdsByName = {};
+        this._opts = [];
+        this._optsByKey = {};
+        this._args = [];
+        this._api = null;
+        this._ext = false;
+    }
+ 
+    static create(cmd) {
+        return new Cmd(cmd);
+    }
+ 
+    /**
+     * Returns object containing all its subcommands as methods
+     * to use from other programs.
+     *
+     * @returns {Object}
+     */
+    get api() {
+        // Need _this here because of passed arguments into _api
+        const _this = this;
+        this._api || (this._api = function () {
+            return _this.invoke.apply(_this, arguments);
+        });
+ 
+        const cmds = this._cmdsByName;
+        Object.keys(cmds).forEach((c) => {
+            this._api[c] = cmds[c].api;
+        });
+        return this._api;
+    }
+ 
+    _parent(cmd) {
+        this._cmd = cmd || this;
+ 
+        this.isRootCmd
+            || cmd._cmds.push(this)
+            && this._name
+            && (this._cmd._cmdsByName[this._name] = this);
+ 
+        return this;
+    }
+ 
+    get isRootCmd() {
+        return this._cmd === this;
+    }
+ 
+    /**
+     * Set a canonical command identifier to be used anywhere in the API.
+     *
+     * @param {String} name - command name
+     * @returns {COA.Cmd} - this instance (for chainability)
+     */
+    name(name) {
+        super.name(name);
+ 
+        this.isRootCmd
+            || (this._cmd._cmdsByName[name] = this);
+ 
+        return this;
+    }
+ 
+    /**
+     * Create new or add existing subcommand for current command.
+     *
+     * @param {COA.Cmd} [cmd] existing command instance
+     * @returns {COA.Cmd} new subcommand instance
+     */
+    cmd(cmd) {
+        return cmd?
+            cmd._parent(this)
+            : new Cmd(this);
+    }
+ 
+    /**
+     * Create option for current command.
+     *
+     * @returns {COA.Opt} new option instance
+     */
+    opt() {
+        return new Opt(this);
+    }
+ 
+    /**
+     * Create argument for current command.
+     *
+     * @returns {COA.Opt} new argument instance
+     */
+    arg() {
+        return new Arg(this);
+    }
+ 
+    /**
+     * Add (or set) action for current command.
+     *
+     * @param {Function} act - action function,
+     *         invoked in the context of command instance
+     *         and has the parameters:
+     *                 - {Object} opts - parsed options
+     *                 - {String[]} args - parsed arguments
+     *                 - {Object} res - actions result accumulator
+     *         It can return rejected promise by Cmd.reject (in case of error)
+     *         or any other value treated as result.
+     * @param {Boolean} [force=false] flag for set action instead add to existings
+     * @returns {COA.Cmd} - this instance (for chainability)
+     */
+    act(act, force) {
+        Iif(!act) return this;
+ 
+        (!this._act || force) && (this._act = []);
+        this._act.push(act);
+ 
+        return this;
+    }
+ 
+    /**
+     * Make command "helpful", i.e. add -h --help flags for print usage.
+     *
+     * @returns {COA.Cmd} - this instance (for chainability)
+     */
+    helpful() {
+        return this.opt()
+            .name('help')
+            .title('Help')
+            .short('h')
+            .long('help')
+            .flag()
+            .only()
+            .act(function() {
+                return this.usage();
+            })
+            .end();
+    }
+ 
+    /**
+     * Adds shell completion to command, adds "completion" subcommand,
+     * that makes all the magic.
+     * Must be called only on root command.
+     *
+     * @returns {COA.Cmd} - this instance (for chainability)
+     */
+    completable() {
+        return this.cmd()
+            .name('completion')
+            .apply(completion)
+            .end();
+    }
+ 
+    /**
+     * Allow command to be extendable by external node.js modules.
+     *
+     * @param {String} [pattern]  Pattern of node.js module to find subcommands at.
+     * @returns {COA.Cmd} - this instance (for chainability)
+     */
+    extendable(pattern) {
+        this._ext = pattern || true;
+        return this;
+    }
+ 
+    _exit(msg, code) {
+        return process.once('exit', function() {
+            msg && console.error(msg);
+            return process.exit(code || 0);
+        });
+    }
+ 
+    /**
+     * Build full usage text for current command instance.
+     *
+     * @returns {String} usage text
+     */
+    usage() {
+        const res = [];
+ 
+        this._title && res.push(this._fullTitle());
+ 
+        res.push('', 'Usage:');
+ 
+        this._cmds.length
+            && res.push([
+                '', '', Color('lred', this._fullName()), Color('lblue', 'COMMAND'),
+                Color('lgreen', '[OPTIONS]'), Color('lpurple', '[ARGS]')
+            ].join(' '));
+ 
+        (this._opts.length + this._args.length)
+            && res.push([
+                '', '', Color('lred', this._fullName()),
+                Color('lgreen', '[OPTIONS]'), Color('lpurple', '[ARGS]')
+            ].join(' '));
+ 
+        res.push(
+            this._usages(this._cmds, 'Commands'),
+            this._usages(this._opts, 'Options'),
+            this._usages(this._args, 'Arguments')
+        );
+ 
+        return res.join(EOL);
+    }
+ 
+    _usage() {
+        return Color('lblue', this._name) + ' : ' + this._title;
+    }
+ 
+    _usages(os, title) {
+        if(!os.length) return;
+ 
+        return ['', title + ':']
+            .concat(os.map(o => `  ${o._usage()}`))
+            .join(EOL);
+    }
+ 
+    _fullTitle() {
+        return `${this.isRootCmd? '' : this._cmd._fullTitle() + EOL}${this._title}`;
+    }
+ 
+    _fullName() {
+        return `${this.isRootCmd? '' : this._cmd._fullName() + ' '}${PATH.basename(this._name)}`;
+    }
+ 
+    _ejectOpt(opts, opt) {
+        const pos = opts.indexOf(opt);
+        if(pos === -1)
+            return;
+ 
+        return opts[pos]._arr?
+            opts[pos]
+            : opts.splice(pos, 1)[0];
+    }
+ 
+    _checkRequired(opts, args) {
+        if(this._opts.some(opt => opt._only && opt._name in opts)) return;
+ 
+        const all = this._opts.concat(this._args);
+        let i;
+        while(i = all.shift())
+            if(i._req && i._checkParsed(opts, args))
+                return this.reject(i._requiredText());
+    }
+ 
+    _parseCmd(argv, unparsed) {
+        unparsed || (unparsed = []);
+ 
+        let i,
+            optSeen = false;
+        while(i = argv.shift()) {
+            i.indexOf('-') || (optSeen = true);
+ 
+            if(optSeen || !/^\w[\w-_]*$/.test(i)) {
+                unparsed.push(i);
+                continue;
+            }
+ 
+            let pkg, cmd = this._cmdsByName[i];
+            if(!cmd && this._ext) {
+                if(typeof this._ext === 'string') {
+                    pkg = ~this._ext.indexOf('%s')?
+                        UTIL.format(this._ext, i)
+                        : this._ext + i;
+ 
+                } else Eif(this._ext === true) {
+                    pkg = i;
+                    let c = this;
+                    while(true) { // eslint-disable-line
+                        pkg = c._name + '-' + pkg;
+                        if(c.isRootCmd) break;
+                        c = c._cmd;
+                    }
+                }
+ 
+                const cmdDesc = tryCatch(() => require(pkg));
+                Eif(cmdDesc) {
+                    if(typeof cmdDesc === 'function') {
+                        this.cmd().name(i).apply(cmdDesc).end();
+ 
+                    } else Eif(typeof cmdDesc === 'object') {
+                        this.cmd(cmdDesc);
+                        cmdDesc.name(i);
+ 
+                    } else throw new Error('Error: Unsupported command declaration type, '
+                        + 'should be a function or COA.Cmd() object');
+ 
+                    cmd = this._cmdsByName[i];
+                }
+            }
+ 
+            if(cmd) return cmd._parseCmd(argv, unparsed);
+ 
+            unparsed.push(i);
+        }
+ 
+        return { cmd : this, argv : unparsed };
+    }
+ 
+    _parseOptsAndArgs(argv) {
+        const opts = {},
+            args = {},
+            nonParsedOpts = this._opts.concat(),
+            nonParsedArgs = this._args.concat();
+ 
+        let res, i;
+        while(i = argv.shift()) {
+            if(i !== '--' && i[0] === '-') {
+                const m = i.match(/^(--\w[\w-_]*)=(.*)$/);
+                if(m) {
+                    i = m[1];
+                    this._optsByKey[i]._flag || argv.unshift(m[2]);
+                }
+ 
+                const opt = this._ejectOpt(nonParsedOpts, this._optsByKey[i]);
+                if(!opt) return this.reject(`Unknown option: ${i}`);
+ 
+                if(Q.isRejected(res = opt._parse(argv, opts))) return res;
+ 
+                continue;
+            }
+ 
+            i === '--' && (i = argv.splice(0));
+            Array.isArray(i) || (i = [i]);
+ 
+            let a;
+            while(a = i.shift()) {
+                let arg = nonParsedArgs.shift();
+                if(!arg) return this.reject(`Unknown argument: ${a}`);
+ 
+                arg._arr && nonParsedArgs.unshift(arg);
+                Iif(Q.isRejected(res = arg._parse(a, args))) return res;
+            }
+        }
+ 
+        return {
+            opts : this._setDefaults(opts, nonParsedOpts),
+            args : this._setDefaults(args, nonParsedArgs)
+        };
+    }
+ 
+    _setDefaults(params, desc) {
+        for(const item of desc)
+            item._def
+                && !(item._name in params)
+                && item._saveVal(params, item._def);
+ 
+        return params;
+    }
+ 
+    _processParams(params, desc) {
+        const notExists = [];
+ 
+        for(const item of desc) {
+            const n = item._name;
+ 
+            Iif(!(n in params)) {
+                notExists.push(item);
+                continue;
+            }
+ 
+            const vals = [].concat(params[n]);
+            delete params[n];
+ 
+            let res;
+            for(const v of vals)
+                Iif(Q.isRejected(res = item._saveVal(params, v)))
+                    return res;
+        }
+ 
+        return this._setDefaults(params, notExists);
+    }
+ 
+    _parseArr(argv) {
+        return Q.when(this._parseCmd(argv), (p) =>
+            Q.when(p.cmd._parseOptsAndArgs(p.argv), (r) => ({
+                cmd : p.cmd,
+                opts : r.opts,
+                args : r.args
+            })));
+    }
+ 
+    _do(inputPromise) {
+        return Q.when(inputPromise, (input) => {
+            return [this._checkRequired]
+                .concat(input.cmd._act || [])
+                .reduce((res, act) =>
+                    Q.when(res, (prev) => act.call(input.cmd, input.opts, input.args, prev)),
+                    void 0);
+        });
+    }
+ 
+    /**
+     * Parse arguments from simple format like NodeJS process.argv
+     * and run ahead current program, i.e. call process.exit when all actions done.
+     *
+     * @param {String[]} argv - arguments
+     * @returns {COA.Cmd} - this instance (for chainability)
+     */
+    run(argv) {
+        argv || (argv = process.argv.slice(2));
+ 
+        const cb = (code) => (res) => res?
+            this._exit(res.stack || res.toString(), res.exitCode || code)
+            : this._exit();
+ 
+        Q.when(this.do(argv), cb(0), cb(1)).done();
+ 
+        return this;
+    }
+ 
+    /**
+     * Invoke specified (or current) command using provided
+     * options and arguments.
+     *
+     * @param {String|String[]} [cmds] - subcommand to invoke (optional)
+     * @param {Object} [opts] - command options (optional)
+     * @param {Object} [args] - command arguments (optional)
+     * @returns {Q.Promise}
+     */
+    invoke(cmds, opts, args) {
+        cmds || (cmds = []);
+        opts || (opts = {});
+        args || (args = {});
+        typeof cmds === 'string' && (cmds = cmds.split(' '));
+ 
+        if(arguments.length < 3 && !Array.isArray(cmds)) {
+            args = opts;
+            opts = cmds;
+            cmds = [];
+        }
+ 
+        return Q.when(this._parseCmd(cmds), (p) => {
+            if(p.argv.length)
+                return this.reject(`Unknown command: ${cmds.join(' ')}`);
+ 
+            return Q.all([this._processParams(opts, this._opts), this._processParams(args, this._args)])
+                .spread((_opts, _args) =>
+                    this._do({
+                        cmd : p.cmd,
+                        opts : _opts,
+                        args : _args
+                    })
+                    .fail((res) => (res && res.exitCode === 0)?
+                        res.toString()
+                        : this.reject(res)));
+        });
+    }
+}
+ 
+/**
+ * Convenient function to run command from tests.
+ *
+ * @param {String[]} argv - arguments
+ * @returns {Q.Promise}
+ */
+Cmd.prototype.do = function(argv) {
+    return this._do(this._parseArr(argv || []));
+};
+ 
+function tryCatch(fn, cb) {
+    try {
+        return fn();
+    } catch(e) {
+        return cb(e);
+    }
+}
+ 
+module.exports = Cmd;
+ 
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/lib/coaobject.js.html b/node_modules/coa/coverage/coa/lib/coaobject.js.html new file mode 100644 index 00000000..32dfc7f5 --- /dev/null +++ b/node_modules/coa/coverage/coa/lib/coaobject.js.html @@ -0,0 +1,365 @@ + + + + Code coverage report for coa/lib/coaobject.js + + + + + + + +
+
+

+ All files / coa/lib coaobject.js +

+
+
+ 75% + Statements + 12/16 +
+
+ 50% + Branches + 1/2 +
+
+ 71.43% + Functions + 5/7 +
+
+ 75% + Lines + 12/16 +
+
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101  +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +  +58x +58x +58x +58x +  +  +  +  +  +  +  +  +  +44x +44x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +3x +  +  +  +3x +  +  +  +  +  +  +  +  +  +  +  +8x +  +  +  +  +  +  +  +38x +  +  + 
'use strict';
+ 
+const Q = require('q');
+ 
+/**
+ * COA Object
+ *
+ * Base class for all COA-related objects
+ *
+ * --------|-----|-----|-----
+ *         | Cmd | Opt | Arg
+ * --------|-----|-----|-----
+ *  name   | ✓   | ✓   | ✓
+ *  title  | ✓   | ✓   | ✓
+ *  comp   | ✓   | ✓   | ✓
+ *  reject | ✓   | ✓   | ✓
+ *  end    | ✓   | ✓   | ✓
+ *  apply  | ✓   | ✓   | ✓
+ *
+ * @class CoaObject
+ */
+module.exports = class CoaObject {
+    constructor(cmd) {
+        this._cmd = cmd;
+        this._name = null;
+        this._title = null;
+        this._comp = null;
+    }
+ 
+    /**
+     * Set a canonical identifier to be used anywhere in the API.
+     *
+     * @param {String} name - command, option or argument name
+     * @returns {COA.CoaObject} - this instance (for chainability)
+     */
+    name(name) {
+        this._name = name;
+        return this;
+    }
+ 
+    /**
+     * Set a long description to be used anywhere in text messages.
+     * @param {String} title - human readable entity title
+     * @returns {COA.CoaObject} - this instance (for chainability)
+     */
+    title(title) {
+        this._title = title;
+        return this;
+    }
+ 
+    /**
+     * Set custom additional completion for current object.
+     *
+     * @param {Function} comp - completion generation function,
+     *         invoked in the context of object instance.
+     *         Accepts parameters:
+     *                 - {Object} opts - completion options
+     *         It can return promise or any other value threated as a result.
+     * @returns {COA.CoaObject} - this instance (for chainability)
+     */
+    comp(comp) {
+        this._comp = comp;
+        return this;
+    }
+ 
+    /**
+     * Apply function with arguments in a context of object instance.
+     *
+     * @param {Function} fn - body
+     * @param {Array.<*>} args... - arguments
+     * @returns {COA.CoaObject} - this instance (for chainability)
+     */
+    apply(fn) {
+        arguments.length > 1?
+            fn.apply(this, [].slice.call(arguments, 1))
+            : fn.call(this);
+ 
+        return this;
+    }
+ 
+    /**
+     * Return reject of actions results promise with error code.
+     * Use in .act() for return with error.
+     * @param {Object} reason - reject reason
+     *         You can customize toString() method and exitCode property
+     *         of reason object.
+     * @returns {Q.promise} rejected promise
+     */
+    reject(reason) {
+        return Q.reject(reason);
+    }
+ 
+    /**
+     * Finish chain for current subcommand and return parent command instance.
+     * @returns {COA.Cmd} parent command
+     */
+    end() {
+        return this._cmd;
+    }
+};
+ 
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/lib/coaparam.js.html b/node_modules/coa/coverage/coa/lib/coaparam.js.html new file mode 100644 index 00000000..b8bc9bd8 --- /dev/null +++ b/node_modules/coa/coverage/coa/lib/coaparam.js.html @@ -0,0 +1,440 @@ + + + + Code coverage report for coa/lib/coaparam.js + + + + + + + +
+
+

+ All files / coa/lib coaparam.js +

+
+
+ 51.61% + Statements + 16/31 +
+
+ 0% + Branches + 0/8 +
+
+ 55.56% + Functions + 5/9 +
+
+ 51.61% + Lines + 16/31 +
+
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126  +  +1x +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +  +32x +  +32x +32x +32x +32x +  +  +  +  +  +  +  +  +  +9x +9x +  +  +  +  +  +  +  +  +3x +3x +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +1x +  +  +  +  +  +  +  +  +  +  +1x +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  + 
'use strict';
+ 
+const fs = require('fs');
+ 
+const CoaObject = require('./coaobject');
+ 
+/**
+ * COA Parameter
+ *
+ * Base class for options and arguments
+ *
+ * --------|-----|-----|-----
+ *         | Cmd | Opt | Arg
+ * --------|-----|-----|-----
+ *  arr    |     | ✓   | ✓
+ *  req    |     | ✓   | ✓
+ *  val    |     | ✓   | ✓
+ *  def    |     | ✓   | ✓
+ *  input  |     | ✓   | ✓
+ *  output |     | ✓   | ✓
+ *
+ * @class CoaParam
+ * @extends CoaObject
+ */
+module.exports = class CoaParam extends CoaObject {
+    constructor(cmd) {
+        super(cmd);
+ 
+        this._arr = false;
+        this._req = false;
+        this._val = undefined;
+        this._def = undefined;
+    }
+ 
+    /**
+     * Makes a param accepts multiple values.
+     * Otherwise, the value will be used by the latter passed.
+     *
+     * @returns {COA.CoaParam} - this instance (for chainability)
+     */
+    arr() {
+        this._arr = true;
+        return this;
+    }
+ 
+    /**
+     * Makes a param required.
+     *
+     * @returns {COA.CoaParam} - this instance (for chainability)
+     */
+    req() {
+        this._req = true;
+        return this;
+    }
+ 
+    /**
+     * Set a validation (or value) function for param.
+     * Value from command line passes through before becoming available from API.
+     * Using for validation and convertion simple types to any values.
+     *
+     * @param {Function} val - validating function,
+     *         invoked in the context of option instance
+     *         and has one parameter with value from command line.
+     * @returns {COA.CoaParam} - this instance (for chainability)
+     */
+    val(val) {
+        this._val = val;
+        return this;
+    }
+ 
+    /**
+     * Set a default value for param.
+     * Default value passed through validation function as ordinary value.
+     *
+     * @param {*} def - default value of function generator
+     * @returns {COA.CoaParam} - this instance (for chainability)
+     */
+    def(def) {
+        this._def = def;
+        return this;
+    }
+ 
+    /**
+     * Make option value inputting stream.
+     * It's add useful validation and shortcut for STDIN.
+     *
+     * @returns {COA.CoaParam} - this instance (for chainability)
+     */
+    input() {
+        process.stdin.pause();
+        return this
+            .def(process.stdin)
+            .val(function(v) {
+                if(typeof v !== 'string')
+                    return v;
+ 
+                if(v === '-')
+                    return process.stdin;
+ 
+                const s = fs.createReadStream(v, { encoding : 'utf8' });
+                s.pause();
+                return s;
+            });
+    }
+ 
+    /**
+     * Make option value outputing stream.
+     * It's add useful validation and shortcut for STDOUT.
+     *
+     * @returns {COA.CoaParam} - this instance (for chainability)
+     */
+    output() {
+        return this
+            .def(process.stdout)
+            .val(function(v) {
+                if(typeof v !== 'string')
+                    return v;
+ 
+                if(v === '-')
+                    return process.stdout;
+ 
+                return fs.createWriteStream(v, { encoding : 'utf8' });
+            });
+    }
+};
+ 
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/lib/color.js.html b/node_modules/coa/coverage/coa/lib/color.js.html new file mode 100644 index 00000000..14531caf --- /dev/null +++ b/node_modules/coa/coverage/coa/lib/color.js.html @@ -0,0 +1,131 @@ + + + + Code coverage report for coa/lib/color.js + + + + + + + +
+
+

+ All files / coa/lib color.js +

+
+
+ 100% + Statements + 3/3 +
+
+ 100% + Branches + 0/0 +
+
+ 100% + Functions + 1/1 +
+
+ 100% + Lines + 2/2 +
+
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23  +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +4x + 
'use strict';
+ 
+const colors = {
+    black : '30',
+    dgray : '1;30',
+    red : '31',
+    lred : '1;31',
+    green : '32',
+    lgreen : '1;32',
+    brown : '33',
+    yellow : '1;33',
+    blue : '34',
+    lblue : '1;34',
+    purple : '35',
+    lpurple : '1;35',
+    cyan : '36',
+    lcyan : '1;36',
+    lgray : '37',
+    white : '1;37'
+};
+ 
+module.exports = (c, str) => `\x1B[${colors[c]}m${str}\x1B[m`;
+ 
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/lib/completion.js.html b/node_modules/coa/coverage/coa/lib/completion.js.html new file mode 100644 index 00000000..fb042e25 --- /dev/null +++ b/node_modules/coa/coverage/coa/lib/completion.js.html @@ -0,0 +1,593 @@ + + + + Code coverage report for coa/lib/completion.js + + + + + + + +
+
+

+ All files / coa/lib completion.js +

+
+
+ 11.27% + Statements + 8/71 +
+
+ 0% + Branches + 0/32 +
+
+ 0% + Functions + 0/14 +
+
+ 12.5% + Lines + 8/64 +
+
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177  +  +1x +1x +1x +  +1x +  +1x +1x +1x +  +  +  +  +  +  +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  + 
'use strict';
+ 
+const constants = require('constants');
+const fs = require('fs');
+const path = require('path');
+ 
+const Q = require('q');
+ 
+const shell = require('./shell');
+const escape = shell.escape;
+const unescape = shell.unescape;
+ 
+/**
+ * Most of the code adopted from the npm package shell completion code.
+ * See https://github.com/isaacs/npm/blob/master/lib/completion.js
+ *
+ * @returns {COA.CoaObject}
+ */
+module.exports = function completion() {
+    return this
+        .title('Shell completion')
+        .helpful()
+        .arg()
+            .name('raw')
+            .title('Completion words')
+            .arr()
+            .end()
+        .act((opts, args) => {
+            if(process.platform === 'win32') {
+                const e = new Error('shell completion not supported on windows');
+                e.code = 'ENOTSUP';
+                e.errno = constants.ENOTSUP;
+                return this.reject(e);
+            }
+ 
+            // if the COMP_* isn't in the env, then just dump the script
+            if((process.env.COMP_CWORD == null)
+                || (process.env.COMP_LINE == null)
+                || (process.env.COMP_POINT == null)) {
+                return dumpScript(this._cmd._name);
+            }
+ 
+            console.error('COMP_LINE:  %s', process.env.COMP_LINE);
+            console.error('COMP_CWORD: %s', process.env.COMP_CWORD);
+            console.error('COMP_POINT: %s', process.env.COMP_POINT);
+            console.error('args: %j', args.raw);
+ 
+            // completion opts
+            opts = getOpts(args.raw);
+ 
+            // cmd
+            const parsed = this._cmd._parseCmd(opts.partialWords);
+            return Q.when(complete(parsed.cmd, parsed.opts), (compls) => {
+                console.error('filtered: %j', compls);
+                return console.log(compls.map(escape).join('\n'));
+            });
+        });
+};
+ 
+function dumpScript(name) {
+    const defer = Q.defer();
+ 
+    fs.readFile(path.resolve(__dirname, 'completion.sh'), 'utf8', function(err, d) {
+        if(err) return defer.reject(err);
+        d = d.replace(/{{cmd}}/g, path.basename(name)).replace(/^\#\!.*?\n/, '');
+ 
+        process.stdout.on('error', onError);
+        process.stdout.write(d, () => defer.resolve());
+    });
+ 
+    return defer.promise;
+ 
+    function onError(err) {
+        // Darwin is a real dick sometimes.
+        //
+        // This is necessary because the "source" or "." program in
+        // bash on OS X closes its file argument before reading
+        // from it, meaning that you get exactly 1 write, which will
+        // work most of the time, and will always raise an EPIPE.
+        //
+        // Really, one should not be tossing away EPIPE errors, or any
+        // errors, so casually. But, without this, `. <(cmd completion)`
+        // can never ever work on OS X.
+        if(err.errno !== constants.EPIPE) return defer.reject(err);
+        process.stdout.removeListener('error', onError);
+        return defer.resolve();
+    }
+}
+ 
+function getOpts(argv) {
+    // get the partial line and partial word, if the point isn't at the end
+    // ie, tabbing at: cmd foo b|ar
+    const line = process.env.COMP_LINE;
+    const w = +process.env.COMP_CWORD;
+    const point = +process.env.COMP_POINT;
+    const words = argv.map(unescape);
+    const word = words[w];
+    const partialLine = line.substr(0, point);
+    const partialWords = words.slice(0, w);
+ 
+    // figure out where in that last word the point is
+    let partialWord = argv[w] || '';
+    let i = partialWord.length;
+    while(partialWord.substr(0, i) !== partialLine.substr(-1 * i) && i > 0) i--;
+ 
+    partialWord = unescape(partialWord.substr(0, i));
+    partialWord && partialWords.push(partialWord);
+ 
+    return {
+        line,
+        w,
+        point,
+        words,
+        word,
+        partialLine,
+        partialWords,
+        partialWord
+    };
+}
+ 
+function complete(cmd, opts) {
+    let optWord, optPrefix,
+        compls = [];
+ 
+    // Complete on cmds
+    if(opts.partialWord.indexOf('-'))
+        compls = Object.keys(cmd._cmdsByName);
+        // Complete on required opts without '-' in last partial word
+        // (if required not already specified)
+        //
+        // Commented out because of uselessness:
+        // -b, --block suggest results in '-' on cmd line;
+        // next completion suggest all options, because of '-'
+        //.concat Object.keys(cmd._optsByKey).filter (v) -> cmd._optsByKey[v]._req
+    else {
+        // complete on opt values: --opt=| case
+        const m = opts.partialWord.match(/^(--\w[\w-_]*)=(.*)$/);
+        if(m) {
+            optWord = m[1];
+            optPrefix = optWord + '=';
+        } else
+            // complete on opts
+            // don't complete on opts in case of --opt=val completion
+            // TODO: don't complete on opts in case of unknown arg after commands
+            // TODO: complete only on opts with arr() or not already used
+            // TODO: complete only on full opts?
+            compls = Object.keys(cmd._optsByKey);
+    }
+ 
+    // complete on opt values: next arg case
+    opts.partialWords[opts.w - 1].indexOf('-') || (optWord = opts.partialWords[opts.w - 1]);
+ 
+    // complete on opt values: completion
+    let opt;
+    optWord
+        && (opt = cmd._optsByKey[optWord])
+        && !opt._flag
+        && opt._comp
+        && (compls = Q.join(compls,
+            Q.when(opt._comp(opts),
+                (c, o) => c.concat(o.map(v => (optPrefix || '') + v)))));
+ 
+    // TODO: complete on args values (context aware, custom completion?)
+ 
+    // custom completion on cmds
+    cmd._comp && (compls = Q.join(compls, Q.when(cmd._comp(opts)), (c, o) => c.concat(o)));
+ 
+    // TODO: context aware custom completion on cmds, opts and args
+    // (can depend on already entered values, especially options)
+ 
+    return Q.when(compls, complitions => {
+        console.error('partialWord: %s', opts.partialWord);
+        console.error('compls: %j', complitions);
+        return compls.filter((c) => c.indexOf(opts.partialWord) === 0);
+    });
+}
+ 
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/lib/index.html b/node_modules/coa/coverage/coa/lib/index.html new file mode 100644 index 00000000..a9301282 --- /dev/null +++ b/node_modules/coa/coverage/coa/lib/index.html @@ -0,0 +1,197 @@ + + + + Code coverage report for coa/lib + + + + + + + +
+
+

+ All files coa/lib +

+
+
+ 68.17% + Statements + 257/377 +
+
+ 59.05% + Branches + 124/210 +
+
+ 65.35% + Functions + 66/101 +
+
+ 69.8% + Lines + 245/351 +
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
arg.js
100%16/1687.5%7/8100%6/6100%16/16
cmd.js
81.22%147/18171.64%96/13468.75%33/4882.53%137/166
coaobject.js
75%12/1650%1/271.43%5/775%12/16
coaparam.js
51.61%16/310%0/855.56%5/951.61%16/31
color.js
100%3/3100%0/0100%1/1100%2/2
completion.js
11.27%8/710%0/320%0/1412.5%8/64
index.js
100%5/5100%0/0100%0/0100%5/5
opt.js
91.84%45/4972.73%16/22100%14/1495.65%44/46
shell.js
100%5/5100%4/4100%2/2100%5/5
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/lib/index.js.html b/node_modules/coa/coverage/coa/lib/index.js.html new file mode 100644 index 00000000..cfc7c0f0 --- /dev/null +++ b/node_modules/coa/coverage/coa/lib/index.js.html @@ -0,0 +1,107 @@ + + + + Code coverage report for coa/lib/index.js + + + + + + + +
+
+

+ All files / coa/lib index.js +

+
+
+ 100% + Statements + 5/5 +
+
+ 100% + Branches + 0/0 +
+
+ 100% + Functions + 0/0 +
+
+ 100% + Lines + 5/5 +
+
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15  +1x +1x +1x +1x +  +1x +  +  +  +  +  +  +  + 
const
+    Cmd = require('./cmd'),
+    Opt = require('./opt'),
+    Arg = require('./arg'),
+    shell = require('./shell');
+ 
+module.exports = {
+    Cmd : Cmd.create,
+    Opt : Opt.create,
+    Arg : Arg.create,
+    classes : { Cmd, Opt, Arg },
+    shell,
+    require
+};
+ 
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/lib/opt.js.html b/node_modules/coa/coverage/coa/lib/opt.js.html new file mode 100644 index 00000000..74e05c28 --- /dev/null +++ b/node_modules/coa/coverage/coa/lib/opt.js.html @@ -0,0 +1,524 @@ + + + + Code coverage report for coa/lib/opt.js + + + + + + + +
+
+

+ All files / coa/lib opt.js +

+
+
+ 91.84% + Statements + 45/49 +
+
+ 72.73% + Branches + 16/22 +
+
+ 100% + Functions + 14/14 +
+
+ 95.65% + Lines + 44/46 +
+
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154  +  +  +1x +  +1x +1x +  +  +  +  +  +  +  +  +  +  +1x +  +  +  +  +  +16x +  +16x +16x +16x +16x +16x +  +  +  +  +  +  +  +  +  +7x +7x +7x +  +  +  +  +  +  +  +  +  +9x +9x +9x +  +  +  +  +  +  +  +  +1x +1x +  +  +  +  +  +  +  +  +  +1x +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +1x +  +1x +1x +  +1x +2x +  +  +  +  +1x +  +  +  +20x +  +20x +20x +  +  +  +20x +  +  +  +18x +  +  +  +2x +  +  +  +1x +1x +  +1x +1x +1x +1x +  +  +1x +  +  +  +  +1x +  +1x +  +1x +  +  +  +1x +  +  + 
'use strict';
+ 
+const
+    Q = require('q'),
+ 
+    CoaParam = require('./coaparam'),
+    Color = require('./color');
+ 
+/**
+ * Option
+ *
+ * Named entity. Options may have short and long keys for use from command line.
+ *
+ * @namespace
+ * @class Opt
+ * @extends CoaParam
+ */
+module.exports = class Opt extends CoaParam {
+    /**
+     * @constructs
+     * @param {COA.Cmd} cmd - parent command
+     */
+    constructor(cmd) {
+        super(cmd);
+ 
+        this._short = null;
+        this._long = null;
+        this._flag = false;
+        this._only = false;
+        this._cmd._opts.push(this);
+    }
+ 
+    /**
+     * Set a short key for option to be used with one hyphen from command line.
+     *
+     * @param {String} short - short name
+     * @returns {COA.Opt} - this instance (for chainability)
+     */
+    short(short) {
+        this._short = short;
+        this._cmd._optsByKey[`-${short}`] = this;
+        return this;
+    }
+ 
+    /**
+     * Set a short key for option to be used with double hyphens from command line.
+     *
+     * @param {String} long - long name
+     * @returns {COA.Opt} - this instance (for chainability)
+     */
+    long(long) {
+        this._long = long;
+        this._cmd._optsByKey[`--${long}`] = this;
+        return this;
+    }
+ 
+    /**
+     * Make an option boolean, i.e. option without value.
+     *
+     * @returns {COA.Opt} - this instance (for chainability)
+     */
+    flag() {
+        this._flag = true;
+        return this;
+    }
+ 
+    /**
+     * Makes an option to act as a command,
+     * i.e. program will exit just after option action.
+     *
+     * @returns {COA.Opt} - this instance (for chainability)
+     */
+    only() {
+        this._only = true;
+        return this;
+    }
+ 
+    /**
+     * Add action for current option command.
+     * This action is performed if the current option
+     * is present in parsed options (with any value).
+     *
+     * @param {Function} act - action function,
+     *         invoked in the context of command instance
+     *         and has the parameters:
+     *                 - {Object} opts - parsed options
+     *                 - {Array} args - parsed arguments
+     *                 - {Object} res - actions result accumulator
+     *         It can return rejected promise by Cmd.reject (in case of error)
+     *         or any other value treated as result.
+     * @returns {COA.Opt} - this instance (for chainability)
+     */
+    act(act) {
+        this._cmd.act((opts) => {
+            Iif(!opts.hasOwnProperty(this._name)) return;
+ 
+            const res = act.apply(this._cmd, arguments);
+            Iif(!this._only) return res;
+ 
+            return Q.when(res, (out) => this._cmd.reject({
+                toString : () => out.toString(),
+                exitCode : 0
+            }));
+        });
+ 
+        return this;
+    }
+ 
+    _saveVal(opts, val) {
+        this._val && (val = this._val(val));
+ 
+        const name = this._name;
+        this._arr
+            ? (opts[name] || (opts[name] = [])).push(val)
+            : (opts[name] = val);
+ 
+        return val;
+    }
+ 
+    _parse(argv, opts) {
+        return this._saveVal(opts, this._flag ? true : argv.shift());
+    }
+ 
+    _checkParsed(opts) {
+        return !opts.hasOwnProperty(this._name);
+    }
+ 
+    _usage() {
+        const res = [],
+            nameStr = this._name.toUpperCase();
+ 
+        Eif(this._short) {
+            res.push('-', Color('lgreen', this._short));
+            this._flag || res.push(' ' + nameStr);
+            res.push(', ');
+        }
+ 
+        Iif(this._long) {
+            res.push('--', Color('green', this._long));
+            this._flag || res.push('=' + nameStr);
+        }
+ 
+        res.push(' : ', this._title);
+ 
+        this._req && res.push(' ', Color('lred', '(required)'));
+ 
+        return res.join('');
+    }
+ 
+    _requiredText() {
+        return `Missing required option:\n  ${this._usage()}`;
+    }
+};
+ 
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/coa/lib/shell.js.html b/node_modules/coa/coverage/coa/lib/shell.js.html new file mode 100644 index 00000000..b98935af --- /dev/null +++ b/node_modules/coa/coverage/coa/lib/shell.js.html @@ -0,0 +1,107 @@ + + + + Code coverage report for coa/lib/shell.js + + + + + + + +
+
+

+ All files / coa/lib shell.js +

+
+
+ 100% + Statements + 5/5 +
+
+ 100% + Branches + 4/4 +
+
+ 100% + Functions + 2/2 +
+
+ 100% + Lines + 5/5 +
+
+
+
+

+
+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +151x +  +  +2x +  +  +  +2x +  +  +  +6x +6x +  + 
module.exports = { escape, unescape };
+ 
+function unescape(w) {
+    w = w.charAt(0) === '"'
+        ? w.replace(/^"|([^\\])"$/g, '$1')
+        : w.replace(/\\ /g, ' ');
+ 
+    return w.replace(/\\("|'|\$|`|\\)/g, '$1');
+}
+ 
+function escape(w) {
+    w = w.replace(/(["'$`\\])/g,'\\$1');
+    return w.match(/\s+/) ? `"${w}"` : w;
+}
+ 
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/index.html b/node_modules/coa/coverage/index.html new file mode 100644 index 00000000..ee3d492f --- /dev/null +++ b/node_modules/coa/coverage/index.html @@ -0,0 +1,106 @@ + + + + Code coverage report for All files + + + + + + + +
+
+

+ All files +

+
+
+ 68.25% + Statements + 258/378 +
+
+ 59.05% + Branches + 124/210 +
+
+ 65.35% + Functions + 66/101 +
+
+ 69.89% + Lines + 246/352 +
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
coa
100%1/1100%0/0100%0/0100%1/1
coa/lib
68.17%257/37759.05%124/21065.35%66/10169.8%245/351
+
+
+ + + + + + + diff --git a/node_modules/coa/coverage/prettify.css b/node_modules/coa/coverage/prettify.css new file mode 100644 index 00000000..b317a7cd --- /dev/null +++ b/node_modules/coa/coverage/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/node_modules/coa/coverage/prettify.js b/node_modules/coa/coverage/prettify.js new file mode 100644 index 00000000..ef51e038 --- /dev/null +++ b/node_modules/coa/coverage/prettify.js @@ -0,0 +1 @@ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;arat[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/node_modules/coa/coverage/sort-arrow-sprite.png b/node_modules/coa/coverage/sort-arrow-sprite.png new file mode 100644 index 00000000..03f704a6 Binary files /dev/null and b/node_modules/coa/coverage/sort-arrow-sprite.png differ diff --git a/node_modules/coa/coverage/sorter.js b/node_modules/coa/coverage/sorter.js new file mode 100644 index 00000000..6c5034e4 --- /dev/null +++ b/node_modules/coa/coverage/sorter.js @@ -0,0 +1,158 @@ +var addSorting = (function () { + "use strict"; + var cols, + currentSort = { + index: 0, + desc: false + }; + + // returns the summary table element + function getTable() { return document.querySelector('.coverage-summary'); } + // returns the thead element of the summary table + function getTableHeader() { return getTable().querySelector('thead tr'); } + // returns the tbody element of the summary table + function getTableBody() { return getTable().querySelector('tbody'); } + // returns the th element for nth column + function getNthColumn(n) { return getTableHeader().querySelectorAll('th')[n]; } + + // loads all columns + function loadColumns() { + var colNodes = getTableHeader().querySelectorAll('th'), + colNode, + cols = [], + col, + i; + + for (i = 0; i < colNodes.length; i += 1) { + colNode = colNodes[i]; + col = { + key: colNode.getAttribute('data-col'), + sortable: !colNode.getAttribute('data-nosort'), + type: colNode.getAttribute('data-type') || 'string' + }; + cols.push(col); + if (col.sortable) { + col.defaultDescSort = col.type === 'number'; + colNode.innerHTML = colNode.innerHTML + ''; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function (a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function (a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc ? ' sorted-desc' : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function () { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i =0 ; i < cols.length; i += 1) { + if (cols[i].sortable) { + // add the click event handler on the th so users + // dont have to click on those tiny arrows + el = getNthColumn(i).querySelector('.sorter').parentElement; + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function () { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(cols); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/node_modules/coa/index.js b/node_modules/coa/index.js index bb0a047c..76c1c3a3 100644 --- a/node_modules/coa/index.js +++ b/node_modules/coa/index.js @@ -1 +1 @@ -module.exports = require('./lib'); +module.exports = require(process.env.COVER? './lib-cov' : './lib'); diff --git a/node_modules/coa/lib/arg.js b/node_modules/coa/lib/arg.js index e17b83e9..4444a8a5 100644 --- a/node_modules/coa/lib/arg.js +++ b/node_modules/coa/lib/arg.js @@ -1,58 +1,175 @@ -'use strict'; +// Generated by CoffeeScript 1.6.3 +var Arg, Cmd, Color, Opt; -const - CoaParam = require('./coaparam'), - chalk = require('chalk'); +Color = require('./color').Color; + +Cmd = require('./cmd').Cmd; + +Opt = require('./opt').Opt; /** - * Argument - * - * Unnamed entity. From command line arguments passed as list of unnamed values. - * - * @class Arg - * @extends CoaParam - */ -module.exports = class Arg extends CoaParam { - /** - * @constructs - * @param {COA.Cmd} cmd - parent command - */ - constructor(cmd) { - super(cmd); +Argument - this._cmd._args.push(this); +Unnamed entity. From command line arguments passed as list of unnamed values. +@namespace +@class Presents argument +*/ + + +exports.Arg = Arg = (function() { + /** + @constructs + @param {COA.Cmd} cmd parent command + */ + + function Arg(_cmd) { + this._cmd = _cmd; + this._cmd._args.push(this); + } + + /** + Set a canonical argument identifier to be used anywhere in text messages. + @param {String} _name argument name + @returns {COA.Arg} this instance (for chainability) + */ + + + Arg.prototype.name = Opt.prototype.name; + + /** + Set a long description for argument to be used anywhere in text messages. + @param {String} _title argument title + @returns {COA.Arg} this instance (for chainability) + */ + + + Arg.prototype.title = Cmd.prototype.title; + + /** + Makes an argument accepts multiple values. + Otherwise, the value will be used by the latter passed. + @returns {COA.Arg} this instance (for chainability) + */ + + + Arg.prototype.arr = Opt.prototype.arr; + + /** + Makes an argument required. + @returns {COA.Arg} this instance (for chainability) + */ + + + Arg.prototype.req = Opt.prototype.req; + + /** + Set a validation (or value) function for argument. + Value from command line passes through before becoming available from API. + Using for validation and convertion simple types to any values. + @param {Function} _val validating function, + invoked in the context of argument instance + and has one parameter with value from command line + @returns {COA.Arg} this instance (for chainability) + */ + + + Arg.prototype.val = Opt.prototype.val; + + /** + Set a default value for argument. + Default value passed through validation function as ordinary value. + @param {Object} _def + @returns {COA.Arg} this instance (for chainability) + */ + + + Arg.prototype.def = Opt.prototype.def; + + /** + Set custom additional completion for current argument. + @param {Function} completion generation function, + invoked in the context of argument instance. + Accepts parameters: + - {Object} opts completion options + It can return promise or any other value treated as result. + @returns {COA.Arg} this instance (for chainability) + */ + + + Arg.prototype.comp = Cmd.prototype.comp; + + /** + Make argument value inputting stream. + It's add useful validation and shortcut for STDIN. + @returns {COA.Arg} this instance (for chainability) + */ + + + Arg.prototype.input = Opt.prototype.input; + + /** + Make argument value outputing stream. + It's add useful validation and shortcut for STDOUT. + @returns {COA.Arg} this instance (for chainability) + */ + + + Arg.prototype.output = Opt.prototype.output; + + Arg.prototype._parse = function(arg, args) { + return this._saveVal(args, arg); + }; + + Arg.prototype._saveVal = Opt.prototype._saveVal; + + Arg.prototype._checkParsed = function(opts, args) { + return !args.hasOwnProperty(this._name); + }; + + Arg.prototype._usage = function() { + var res; + res = []; + res.push(Color('lpurple', this._name.toUpperCase()), ' : ', this._title); + if (this._req) { + res.push(' ', Color('lred', '(required)')); } + return res.join(''); + }; - _saveVal(args, val) { - this._val && (val = this._val(val)); + Arg.prototype._requiredText = function() { + return 'Missing required argument:\n ' + this._usage(); + }; - const name = this._name; - this._arr - ? (args[name] || (args[name] = [])).push(val) - : (args[name] = val); + /** + Return rejected promise with error code. + Use in .val() for return with error. + @param {Object} reject reason + You can customize toString() method and exitCode property + of reason object. + @returns {Q.promise} rejected promise + */ - return val; - } - _parse(arg, args) { - return this._saveVal(args, arg); - } + Arg.prototype.reject = Cmd.prototype.reject; - _checkParsed(opts, args) { - return !args.hasOwnProperty(this._name); - } + /** + Finish chain for current option and return parent command instance. + @returns {COA.Cmd} parent command + */ - _usage() { - const res = []; - res.push(chalk.magentaBright(this._name.toUpperCase()), ' : ', this._title); + Arg.prototype.end = Cmd.prototype.end; - this._req && res.push(' ', chalk.redBright('(required)')); + /** + Apply function with arguments in context of arg instance. + @param {Function} fn + @param {Array} args + @returns {COA.Arg} this instance (for chainability) + */ - return res.join(''); - } - _requiredText() { - return `Missing required argument:\n ${this._usage()}`; - } -}; + Arg.prototype.apply = Cmd.prototype.apply; + + return Arg; + +})(); diff --git a/node_modules/coa/lib/cmd.js b/node_modules/coa/lib/cmd.js index 919564e8..b53c2541 100644 --- a/node_modules/coa/lib/cmd.js +++ b/node_modules/coa/lib/cmd.js @@ -1,493 +1,605 @@ -/* eslint-disable class-methods-use-this */ -'use strict'; +// Generated by CoffeeScript 1.6.3 +var Cmd, Color, PATH, Q, UTIL, + __slice = [].slice; -const - UTIL = require('util'), - PATH = require('path'), - EOL = require('os').EOL, +UTIL = require('util'); - Q = require('q'), - chalk = require('chalk'), +PATH = require('path'); - CoaObject = require('./coaobject'), - Opt = require('./opt'), - Arg = require('./arg'), - completion = require('./completion'); +Color = require('./color').Color; + +Q = require('q'); /** - * Command - * - * Top level entity. Commands may have options and arguments. - * - * @namespace - * @class Cmd - * @extends CoaObject - */ -class Cmd extends CoaObject { - /** - * @constructs - * @param {COA.Cmd} [cmd] parent command - */ - constructor(cmd) { - super(cmd); +Command - this._parent(cmd); - this._cmds = []; - this._cmdsByName = {}; - this._opts = []; - this._optsByKey = {}; - this._args = []; - this._api = null; - this._ext = false; +Top level entity. Commands may have options and arguments. +@namespace +@class Presents command +*/ + + +exports.Cmd = Cmd = (function() { + /** + @constructs + @param {COA.Cmd} [cmd] parent command + */ + + function Cmd(cmd) { + if (!(this instanceof Cmd)) { + return new Cmd(cmd); } + this._parent(cmd); + this._cmds = []; + this._cmdsByName = {}; + this._opts = []; + this._optsByKey = {}; + this._args = []; + this._ext = false; + } - static create(cmd) { - return new Cmd(cmd); + Cmd.get = function(propertyName, func) { + return Object.defineProperty(this.prototype, propertyName, { + configurable: true, + enumerable: true, + get: func + }); + }; + + /** + Returns object containing all its subcommands as methods + to use from other programs. + @returns {Object} + */ + + + Cmd.get('api', function() { + var c, _fn, + _this = this; + if (!this._api) { + this._api = function() { + return _this.invoke.apply(_this, arguments); + }; } - - /** - * Returns object containing all its subcommands as methods - * to use from other programs. - * - * @returns {Object} - */ - get api() { - // Need _this here because of passed arguments into _api - const _this = this; - this._api || (this._api = function () { - return _this.invoke.apply(_this, arguments); - }); - - const cmds = this._cmdsByName; - Object.keys(cmds).forEach(cmd => { this._api[cmd] = cmds[cmd].api; }); - - return this._api; + _fn = function(c) { + return _this._api[c] = _this._cmdsByName[c].api; + }; + for (c in this._cmdsByName) { + _fn(c); } + return this._api; + }); - _parent(cmd) { - this._cmd = cmd || this; - - this.isRootCmd || - cmd._cmds.push(this) && - this._name && - (this._cmd._cmdsByName[this._name] = this); - - return this; + Cmd.prototype._parent = function(cmd) { + this._cmd = cmd || this; + if (cmd) { + cmd._cmds.push(this); + if (this._name) { + this._cmd._cmdsByName[this._name] = this; + } } + return this; + }; - get isRootCmd() { - return this._cmd === this; + /** + Set a canonical command identifier to be used anywhere in the API. + @param {String} _name command name + @returns {COA.Cmd} this instance (for chainability) + */ + + + Cmd.prototype.name = function(_name) { + this._name = _name; + if (this._cmd !== this) { + this._cmd._cmdsByName[_name] = this; } + return this; + }; - /** - * Set a canonical command identifier to be used anywhere in the API. - * - * @param {String} name - command name - * @returns {COA.Cmd} - this instance (for chainability) - */ - name(name) { - super.name(name); + /** + Set a long description for command to be used anywhere in text messages. + @param {String} _title command title + @returns {COA.Cmd} this instance (for chainability) + */ - this.isRootCmd || - (this._cmd._cmdsByName[name] = this); - return this; + Cmd.prototype.title = function(_title) { + this._title = _title; + return this; + }; + + /** + Create new or add existing subcommand for current command. + @param {COA.Cmd} [cmd] existing command instance + @returns {COA.Cmd} new subcommand instance + */ + + + Cmd.prototype.cmd = function(cmd) { + if (cmd) { + return cmd._parent(this); + } else { + return new Cmd(this); } + }; - /** - * Create new or add existing subcommand for current command. - * - * @param {COA.Cmd} [cmd] existing command instance - * @returns {COA.Cmd} new subcommand instance - */ - cmd(cmd) { - return cmd? - cmd._parent(this) - : new Cmd(this); + /** + Create option for current command. + @returns {COA.Opt} new option instance + */ + + + Cmd.prototype.opt = function() { + return new (require('./opt').Opt)(this); + }; + + /** + Create argument for current command. + @returns {COA.Opt} new argument instance + */ + + + Cmd.prototype.arg = function() { + return new (require('./arg').Arg)(this); + }; + + /** + Add (or set) action for current command. + @param {Function} act action function, + invoked in the context of command instance + and has the parameters: + - {Object} opts parsed options + - {Array} args parsed arguments + - {Object} res actions result accumulator + It can return rejected promise by Cmd.reject (in case of error) + or any other value treated as result. + @param {Boolean} [force=false] flag for set action instead add to existings + @returns {COA.Cmd} this instance (for chainability) + */ + + + Cmd.prototype.act = function(act, force) { + if (!act) { + return this; } - - /** - * Create option for current command. - * - * @returns {COA.Opt} new option instance - */ - opt() { - return new Opt(this); + if (!force && this._act) { + this._act.push(act); + } else { + this._act = [act]; } + return this; + }; - /** - * Create argument for current command. - * - * @returns {COA.Opt} new argument instance - */ - arg() { - return new Arg(this); + /** + Set custom additional completion for current command. + @param {Function} completion generation function, + invoked in the context of command instance. + Accepts parameters: + - {Object} opts completion options + It can return promise or any other value treated as result. + @returns {COA.Cmd} this instance (for chainability) + */ + + + Cmd.prototype.comp = function(_comp) { + this._comp = _comp; + return this; + }; + + /** + Apply function with arguments in context of command instance. + @param {Function} fn + @param {Array} args + @returns {COA.Cmd} this instance (for chainability) + */ + + + Cmd.prototype.apply = function() { + var args, fn; + fn = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; + fn.apply(this, args); + return this; + }; + + /** + Make command "helpful", i.e. add -h --help flags for print usage. + @returns {COA.Cmd} this instance (for chainability) + */ + + + Cmd.prototype.helpful = function() { + return this.opt().name('help').title('Help').short('h').long('help').flag().only().act(function() { + return this.usage(); + }).end(); + }; + + /** + Adds shell completion to command, adds "completion" subcommand, + that makes all the magic. + Must be called only on root command. + @returns {COA.Cmd} this instance (for chainability) + */ + + + Cmd.prototype.completable = function() { + return this.cmd().name('completion').apply(require('./completion')).end(); + }; + + /** + Allow command to be extendable by external node.js modules. + @param {String} [pattern] Pattern of node.js module to find subcommands at. + @returns {COA.Cmd} this instance (for chainability) + */ + + + Cmd.prototype.extendable = function(pattern) { + this._ext = pattern || true; + return this; + }; + + Cmd.prototype._exit = function(msg, code) { + return process.once('exit', function() { + if (msg) { + console.error(msg); + } + return process.exit(code || 0); + }); + }; + + /** + Build full usage text for current command instance. + @returns {String} usage text + */ + + + Cmd.prototype.usage = function() { + var res; + res = []; + if (this._title) { + res.push(this._fullTitle()); } - - /** - * Add (or set) action for current command. - * - * @param {Function} act - action function, - * invoked in the context of command instance - * and has the parameters: - * - {Object} opts - parsed options - * - {String[]} args - parsed arguments - * - {Object} res - actions result accumulator - * It can return rejected promise by Cmd.reject (in case of error) - * or any other value treated as result. - * @param {Boolean} [force=false] flag for set action instead add to existings - * @returns {COA.Cmd} - this instance (for chainability) - */ - act(act, force) { - if(!act) return this; - - (!this._act || force) && (this._act = []); - this._act.push(act); - - return this; + res.push('', 'Usage:'); + if (this._cmds.length) { + res.push(['', '', Color('lred', this._fullName()), Color('lblue', 'COMMAND'), Color('lgreen', '[OPTIONS]'), Color('lpurple', '[ARGS]')].join(' ')); } - - /** - * Make command "helpful", i.e. add -h --help flags for print usage. - * - * @returns {COA.Cmd} - this instance (for chainability) - */ - helpful() { - return this.opt() - .name('help') - .title('Help') - .short('h') - .long('help') - .flag() - .only() - .act(function() { - return this.usage(); - }) - .end(); + if (this._opts.length + this._args.length) { + res.push(['', '', Color('lred', this._fullName()), Color('lgreen', '[OPTIONS]'), Color('lpurple', '[ARGS]')].join(' ')); } + res.push(this._usages(this._cmds, 'Commands'), this._usages(this._opts, 'Options'), this._usages(this._args, 'Arguments')); + return res.join('\n'); + }; - /** - * Adds shell completion to command, adds "completion" subcommand, - * that makes all the magic. - * Must be called only on root command. - * - * @returns {COA.Cmd} - this instance (for chainability) - */ - completable() { - return this.cmd() - .name('completion') - .apply(completion) - .end(); + Cmd.prototype._usage = function() { + return Color('lblue', this._name) + ' : ' + this._title; + }; + + Cmd.prototype._usages = function(os, title) { + var o, res, _i, _len; + if (!os.length) { + return; } - - /** - * Allow command to be extendable by external node.js modules. - * - * @param {String} [pattern] Pattern of node.js module to find subcommands at. - * @returns {COA.Cmd} - this instance (for chainability) - */ - extendable(pattern) { - this._ext = pattern || true; - return this; + res = ['', title + ':']; + for (_i = 0, _len = os.length; _i < _len; _i++) { + o = os[_i]; + res.push(' ' + o._usage()); } + return res.join('\n'); + }; - _exit(msg, code) { - return process.once('exit', function(exitCode) { - msg && console[code === 0 ? 'log' : 'error'](msg); - process.exit(code || exitCode || 0); - }); + Cmd.prototype._fullTitle = function() { + return (this._cmd === this ? '' : this._cmd._fullTitle() + '\n') + this._title; + }; + + Cmd.prototype._fullName = function() { + return (this._cmd === this ? '' : this._cmd._fullName() + ' ') + PATH.basename(this._name); + }; + + Cmd.prototype._ejectOpt = function(opts, opt) { + var pos; + if ((pos = opts.indexOf(opt)) >= 0) { + if (opts[pos]._arr) { + return opts[pos]; + } else { + return opts.splice(pos, 1)[0]; + } } + }; - /** - * Build full usage text for current command instance. - * - * @returns {String} usage text - */ - usage() { - const res = []; - - this._title && res.push(this._fullTitle()); - - res.push('', 'Usage:'); - - this._cmds.length - && res.push([ - '', '', chalk.redBright(this._fullName()), chalk.blueBright('COMMAND'), - chalk.greenBright('[OPTIONS]'), chalk.magentaBright('[ARGS]') - ].join(' ')); - - (this._opts.length + this._args.length) - && res.push([ - '', '', chalk.redBright(this._fullName()), - chalk.greenBright('[OPTIONS]'), chalk.magentaBright('[ARGS]') - ].join(' ')); - - res.push( - this._usages(this._cmds, 'Commands'), - this._usages(this._opts, 'Options'), - this._usages(this._args, 'Arguments') - ); - - return res.join(EOL); - } - - _usage() { - return chalk.blueBright(this._name) + ' : ' + this._title; - } - - _usages(os, title) { - if(!os.length) return; - - return ['', title + ':'] - .concat(os.map(o => ` ${o._usage()}`)) - .join(EOL); - } - - _fullTitle() { - return `${this.isRootCmd? '' : this._cmd._fullTitle() + EOL}${this._title}`; - } - - _fullName() { - return `${this.isRootCmd? '' : this._cmd._fullName() + ' '}${PATH.basename(this._name)}`; - } - - _ejectOpt(opts, opt) { - const pos = opts.indexOf(opt); - if(pos === -1) return; - - return opts[pos]._arr? - opts[pos] : - opts.splice(pos, 1)[0]; - } - - _checkRequired(opts, args) { - if(this._opts.some(opt => opt._only && opts.hasOwnProperty(opt._name))) return; - - const all = this._opts.concat(this._args); - let i; - while(i = all.shift()) - if(i._req && i._checkParsed(opts, args)) - return this.reject(i._requiredText()); - } - - _parseCmd(argv, unparsed) { - unparsed || (unparsed = []); - - let i, - optSeen = false; - while(i = argv.shift()) { - i.indexOf('-') || (optSeen = true); - - if(optSeen || !/^\w[\w-_]*$/.test(i)) { - unparsed.push(i); - continue; - } - - let pkg, cmd = this._cmdsByName[i]; - if(!cmd && this._ext) { - if(this._ext === true) { - pkg = i; - let c = this; - while(true) { // eslint-disable-line - pkg = c._name + '-' + pkg; - if(c.isRootCmd) break; - c = c._cmd; - } - } else if(typeof this._ext === 'string') - pkg = ~this._ext.indexOf('%s')? - UTIL.format(this._ext, i) : - this._ext + i; - - let cmdDesc; - try { - cmdDesc = require(pkg); - } catch(e) { - // Dummy - } - - if(cmdDesc) { - if(typeof cmdDesc === 'function') { - this.cmd().name(i).apply(cmdDesc).end(); - } else if(typeof cmdDesc === 'object') { - this.cmd(cmdDesc); - cmdDesc.name(i); - } else throw new Error('Error: Unsupported command declaration type, ' - + 'should be a function or COA.Cmd() object'); - - cmd = this._cmdsByName[i]; - } - } - - if(cmd) return cmd._parseCmd(argv, unparsed); - - unparsed.push(i); + Cmd.prototype._checkRequired = function(opts, args) { + var all, i; + if (!(this._opts.filter(function(o) { + return o._only && o._name in opts; + })).length) { + all = this._opts.concat(this._args); + while (i = all.shift()) { + if (i._req && i._checkParsed(opts, args)) { + return this.reject(i._requiredText()); } - - return { cmd : this, argv : unparsed }; + } } + }; - _parseOptsAndArgs(argv) { - const opts = {}, - args = {}, - nonParsedOpts = this._opts.concat(), - nonParsedArgs = this._args.concat(); - - let res, i; - while(i = argv.shift()) { - if(i !== '--' && i[0] === '-') { - const m = i.match(/^(--\w[\w-_]*)=(.*)$/); - if(m) { - i = m[1]; - this._optsByKey[i]._flag || argv.unshift(m[2]); - } - - const opt = this._ejectOpt(nonParsedOpts, this._optsByKey[i]); - if(!opt) return this.reject(`Unknown option: ${i}`); - - if(Q.isRejected(res = opt._parse(argv, opts))) return res; - - continue; + Cmd.prototype._parseCmd = function(argv, unparsed) { + var c, cmd, cmdDesc, e, i, optSeen, pkg; + if (unparsed == null) { + unparsed = []; + } + argv = argv.concat(); + optSeen = false; + while (i = argv.shift()) { + if (!i.indexOf('-')) { + optSeen = true; + } + if (!optSeen && /^\w[\w-_]*$/.test(i)) { + cmd = this._cmdsByName[i]; + if (!cmd && this._ext) { + if (typeof this._ext === 'string') { + if (~this._ext.indexOf('%s')) { + pkg = UTIL.format(this._ext, i); + } else { + pkg = this._ext + i; } - - i === '--' && (i = argv.splice(0)); - Array.isArray(i) || (i = [i]); - - let a; - while(a = i.shift()) { - let arg = nonParsedArgs.shift(); - if(!arg) return this.reject(`Unknown argument: ${a}`); - - arg._arr && nonParsedArgs.unshift(arg); - if(Q.isRejected(res = arg._parse(a, args))) return res; + } else if (this._ext === true) { + pkg = i; + c = this; + while (true) { + pkg = c._name + '-' + pkg; + if (c._cmd === c) { + break; + } + c = c._cmd; } + } + try { + cmdDesc = require(pkg); + } catch (_error) { + e = _error; + } + if (cmdDesc) { + if (typeof cmdDesc === 'function') { + this.cmd().name(i).apply(cmdDesc).end(); + } else if (typeof cmdDesc === 'object') { + this.cmd(cmdDesc); + cmdDesc.name(i); + } else { + throw new Error('Error: Unsupported command declaration type, ' + 'should be function or COA.Cmd() object'); + } + cmd = this._cmdsByName[i]; + } } + if (cmd) { + return cmd._parseCmd(argv, unparsed); + } + } + unparsed.push(i); + } + return { + cmd: this, + argv: unparsed + }; + }; + Cmd.prototype._parseOptsAndArgs = function(argv) { + var a, arg, args, i, m, nonParsedArgs, nonParsedOpts, opt, opts, res; + opts = {}; + args = {}; + nonParsedOpts = this._opts.concat(); + nonParsedArgs = this._args.concat(); + while (i = argv.shift()) { + if (i !== '--' && !i.indexOf('-')) { + if (m = i.match(/^(--\w[\w-_]*)=(.*)$/)) { + i = m[1]; + if (!this._optsByKey[i]._flag) { + argv.unshift(m[2]); + } + } + if (opt = this._ejectOpt(nonParsedOpts, this._optsByKey[i])) { + if (Q.isRejected(res = opt._parse(argv, opts))) { + return res; + } + } else { + return this.reject("Unknown option: " + i); + } + } else { + if (i === '--') { + i = argv.splice(0); + } + i = Array.isArray(i) ? i : [i]; + while (a = i.shift()) { + if (arg = nonParsedArgs.shift()) { + if (arg._arr) { + nonParsedArgs.unshift(arg); + } + if (Q.isRejected(res = arg._parse(a, args))) { + return res; + } + } else { + return this.reject("Unknown argument: " + a); + } + } + } + } + return { + opts: this._setDefaults(opts, nonParsedOpts), + args: this._setDefaults(args, nonParsedArgs) + }; + }; + + Cmd.prototype._setDefaults = function(params, desc) { + var i, _i, _len; + for (_i = 0, _len = desc.length; _i < _len; _i++) { + i = desc[_i]; + if (!(i._name in params) && '_def' in i) { + i._saveVal(params, i._def); + } + } + return params; + }; + + Cmd.prototype._processParams = function(params, desc) { + var i, n, notExists, res, v, vals, _i, _j, _len, _len1; + notExists = []; + for (_i = 0, _len = desc.length; _i < _len; _i++) { + i = desc[_i]; + n = i._name; + if (!(n in params)) { + notExists.push(i); + continue; + } + vals = params[n]; + delete params[n]; + if (!Array.isArray(vals)) { + vals = [vals]; + } + for (_j = 0, _len1 = vals.length; _j < _len1; _j++) { + v = vals[_j]; + if (Q.isRejected(res = i._saveVal(params, v))) { + return res; + } + } + } + return this._setDefaults(params, notExists); + }; + + Cmd.prototype._parseArr = function(argv) { + return Q.when(this._parseCmd(argv), function(p) { + return Q.when(p.cmd._parseOptsAndArgs(p.argv), function(r) { return { - opts : this._setDefaults(opts, nonParsedOpts), - args : this._setDefaults(args, nonParsedArgs) + cmd: p.cmd, + opts: r.opts, + args: r.args }; - } + }); + }); + }; - _setDefaults(params, desc) { - for(const item of desc) - item._def !== undefined && - !params.hasOwnProperty(item._name) && - item._saveVal(params, item._def); - - return params; - } - - _processParams(params, desc) { - const notExists = []; - - for(const item of desc) { - const n = item._name; - - if(!params.hasOwnProperty(n)) { - notExists.push(item); - continue; - } - - const vals = Array.isArray(params[n])? params[n] : [params[n]]; - delete params[n]; - - let res; - for(const v of vals) - if(Q.isRejected(res = item._saveVal(params, v))) - return res; - } - - return this._setDefaults(params, notExists); - } - - _parseArr(argv) { - return Q.when(this._parseCmd(argv), p => - Q.when(p.cmd._parseOptsAndArgs(p.argv), r => ({ - cmd : p.cmd, - opts : r.opts, - args : r.args - }))); - } - - _do(inputPromise) { - return Q.when(inputPromise, input => { - return [this._checkRequired] - .concat(input.cmd._act || []) - .reduce((res, act) => - Q.when(res, prev => act.call(input.cmd, input.opts, input.args, prev)), - undefined); + Cmd.prototype._do = function(input) { + var _this = this; + return Q.when(input, function(input) { + var cmd; + cmd = input.cmd; + return [_this._checkRequired].concat(cmd._act || []).reduce(function(res, act) { + return Q.when(res, function(res) { + return act.call(cmd, input.opts, input.args, res); }); + }, void 0); + }); + }; + + /** + Parse arguments from simple format like NodeJS process.argv + and run ahead current program, i.e. call process.exit when all actions done. + @param {Array} argv + @returns {COA.Cmd} this instance (for chainability) + */ + + + Cmd.prototype.run = function(argv) { + var cb, + _this = this; + if (argv == null) { + argv = process.argv.slice(2); } - - /** - * Parse arguments from simple format like NodeJS process.argv - * and run ahead current program, i.e. call process.exit when all actions done. - * - * @param {String[]} argv - arguments - * @returns {COA.Cmd} - this instance (for chainability) - */ - run(argv) { - argv || (argv = process.argv.slice(2)); - - const cb = code => - res => res? - this._exit(res.stack || res.toString(), (res.hasOwnProperty('exitCode')? res.exitCode : code) || 0) : - this._exit(); - - Q.when(this.do(argv), cb(0), cb(1)).done(); - - return this; - } - - /** - * Invoke specified (or current) command using provided - * options and arguments. - * - * @param {String|String[]} [cmds] - subcommand to invoke (optional) - * @param {Object} [opts] - command options (optional) - * @param {Object} [args] - command arguments (optional) - * @returns {Q.Promise} - */ - invoke(cmds, opts, args) { - cmds || (cmds = []); - opts || (opts = {}); - args || (args = {}); - typeof cmds === 'string' && (cmds = cmds.split(' ')); - - if(arguments.length < 3 && !Array.isArray(cmds)) { - args = opts; - opts = cmds; - cmds = []; + cb = function(code) { + return function(res) { + var _ref, _ref1; + if (res) { + return _this._exit((_ref = res.stack) != null ? _ref : res.toString(), (_ref1 = res.exitCode) != null ? _ref1 : code); + } else { + return _this._exit(); } + }; + }; + Q.when(this["do"](argv), cb(0), cb(1)).done(); + return this; + }; - return Q.when(this._parseCmd(cmds), p => { - if(p.argv.length) - return this.reject(`Unknown command: ${cmds.join(' ')}`); + /** + Convenient function to run command from tests. + @param {Array} argv + @returns {Q.Promise} + */ - return Q.all([ - this._processParams(opts, this._opts), - this._processParams(args, this._args) - ]).spread((_opts, _args) => - this._do({ - cmd : p.cmd, - opts : _opts, - args : _args - }) - .fail(res => (res && res.exitCode === 0)? - res.toString() : - this.reject(res))); - }); - } -} -/** - * Convenient function to run command from tests. - * - * @param {String[]} argv - arguments - * @returns {Q.Promise} - */ -Cmd.prototype.do = function(argv) { + Cmd.prototype["do"] = function(argv) { return this._do(this._parseArr(argv || [])); -}; + }; -module.exports = Cmd; + /** + Invoke specified (or current) command using provided + options and arguments. + @param {String|Array} cmds subcommand to invoke (optional) + @param {Object} opts command options (optional) + @param {Object} args command arguments (optional) + @returns {Q.Promise} + */ + + + Cmd.prototype.invoke = function(cmds, opts, args) { + var _this = this; + if (cmds == null) { + cmds = []; + } + if (opts == null) { + opts = {}; + } + if (args == null) { + args = {}; + } + if (typeof cmds === 'string') { + cmds = cmds.split(' '); + } + if (arguments.length < 3) { + if (!Array.isArray(cmds)) { + args = opts; + opts = cmds; + cmds = []; + } + } + return Q.when(this._parseCmd(cmds), function(p) { + if (p.argv.length) { + return _this.reject("Unknown command: " + cmds.join(' ')); + } + return Q.all([_this._processParams(opts, _this._opts), _this._processParams(args, _this._args)]).spread(function(opts, args) { + return _this._do({ + cmd: p.cmd, + opts: opts, + args: args + }).fail(function(res) { + if (res && res.exitCode === 0) { + return res.toString(); + } else { + return _this.reject(res); + } + }); + }); + }); + }; + + /** + Return reject of actions results promise with error code. + Use in .act() for return with error. + @param {Object} reject reason + You can customize toString() method and exitCode property + of reason object. + @returns {Q.promise} rejected promise + */ + + + Cmd.prototype.reject = function(reason) { + return Q.reject(reason); + }; + + /** + Finish chain for current subcommand and return parent command instance. + @returns {COA.Cmd} parent command + */ + + + Cmd.prototype.end = function() { + return this._cmd; + }; + + return Cmd; + +})(); diff --git a/node_modules/coa/lib/coaobject.js b/node_modules/coa/lib/coaobject.js deleted file mode 100644 index 4601fcdc..00000000 --- a/node_modules/coa/lib/coaobject.js +++ /dev/null @@ -1,101 +0,0 @@ -/* eslint-disable class-methods-use-this */ -'use strict'; - -const Q = require('q'); - -/** - * COA Object - * - * Base class for all COA-related objects - * - * --------|-----|-----|----- - * | Cmd | Opt | Arg - * --------|-----|-----|----- - * name | ✓ | ✓ | ✓ - * title | ✓ | ✓ | ✓ - * comp | ✓ | ✓ | ✓ - * reject | ✓ | ✓ | ✓ - * end | ✓ | ✓ | ✓ - * apply | ✓ | ✓ | ✓ - * - * @class CoaObject - */ -module.exports = class CoaObject { - constructor(cmd) { - this._cmd = cmd; - this._name = null; - this._title = null; - this._comp = null; - } - - /** - * Set a canonical identifier to be used anywhere in the API. - * - * @param {String} name - command, option or argument name - * @returns {COA.CoaObject} - this instance (for chainability) - */ - name(name) { - this._name = name; - return this; - } - - /** - * Set a long description to be used anywhere in text messages. - * @param {String} title - human readable entity title - * @returns {COA.CoaObject} - this instance (for chainability) - */ - title(title) { - this._title = title; - return this; - } - - /** - * Set custom additional completion for current object. - * - * @param {Function} comp - completion generation function, - * invoked in the context of object instance. - * Accepts parameters: - * - {Object} opts - completion options - * It can return promise or any other value threated as a result. - * @returns {COA.CoaObject} - this instance (for chainability) - */ - comp(comp) { - this._comp = comp; - return this; - } - - /** - * Apply function with arguments in a context of object instance. - * - * @param {Function} fn - body - * @param {Array.<*>} args... - arguments - * @returns {COA.CoaObject} - this instance (for chainability) - */ - apply(fn) { - arguments.length > 1? - fn.apply(this, [].slice.call(arguments, 1)) - : fn.call(this); - - return this; - } - - /** - * Return reject of actions results promise with error code. - * Use in .act() for return with error. - * @param {Object} reason - reject reason - * You can customize toString() method and exitCode property - * of reason object. - * @returns {Q.promise} rejected promise - */ - reject(reason) { - return Q.reject(reason); - } - - /** - * Finish chain for current subcommand and return parent command instance. - * @returns {COA.Cmd} parent command - */ - end() { - return this._cmd; - } -}; diff --git a/node_modules/coa/lib/coaparam.js b/node_modules/coa/lib/coaparam.js deleted file mode 100644 index e53f9f45..00000000 --- a/node_modules/coa/lib/coaparam.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict'; - -const fs = require('fs'); - -const CoaObject = require('./coaobject'); - -/** - * COA Parameter - * - * Base class for options and arguments - * - * --------|-----|-----|----- - * | Cmd | Opt | Arg - * --------|-----|-----|----- - * arr | | ✓ | ✓ - * req | | ✓ | ✓ - * val | | ✓ | ✓ - * def | | ✓ | ✓ - * input | | ✓ | ✓ - * output | | ✓ | ✓ - * - * @class CoaParam - * @extends CoaObject - */ -module.exports = class CoaParam extends CoaObject { - constructor(cmd) { - super(cmd); - - this._arr = false; - this._req = false; - this._val = undefined; - this._def = undefined; - } - - /** - * Makes a param accepts multiple values. - * Otherwise, the value will be used by the latter passed. - * - * @returns {COA.CoaParam} - this instance (for chainability) - */ - arr() { - this._arr = true; - return this; - } - - /** - * Makes a param required. - * - * @returns {COA.CoaParam} - this instance (for chainability) - */ - req() { - this._req = true; - return this; - } - - /** - * Set a validation (or value) function for param. - * Value from command line passes through before becoming available from API. - * Using for validation and convertion simple types to any values. - * - * @param {Function} val - validating function, - * invoked in the context of option instance - * and has one parameter with value from command line. - * @returns {COA.CoaParam} - this instance (for chainability) - */ - val(val) { - this._val = val; - return this; - } - - /** - * Set a default value for param. - * Default value passed through validation function as ordinary value. - * - * @param {*} def - default value of function generator - * @returns {COA.CoaParam} - this instance (for chainability) - */ - def(def) { - this._def = def; - return this; - } - - /** - * Make option value inputting stream. - * It's add useful validation and shortcut for STDIN. - * - * @returns {COA.CoaParam} - this instance (for chainability) - */ - input() { - process.stdin.pause(); - return this - .def(process.stdin) - .val(function(v) { - if(typeof v !== 'string') - return v; - - if(v === '-') - return process.stdin; - - const s = fs.createReadStream(v, { encoding : 'utf8' }); - s.pause(); - return s; - }); - } - - /** - * Make option value outputing stream. - * It's add useful validation and shortcut for STDOUT. - * - * @returns {COA.CoaParam} - this instance (for chainability) - */ - output() { - return this - .def(process.stdout) - .val(function(v) { - if(typeof v !== 'string') - return v; - - if(v === '-') - return process.stdout; - - return fs.createWriteStream(v, { encoding : 'utf8' }); - }); - } -}; diff --git a/node_modules/coa/lib/color.js b/node_modules/coa/lib/color.js new file mode 100644 index 00000000..7271c8c8 --- /dev/null +++ b/node_modules/coa/lib/color.js @@ -0,0 +1,25 @@ +// Generated by CoffeeScript 1.6.3 +var colors; + +colors = { + black: '30', + dgray: '1;30', + red: '31', + lred: '1;31', + green: '32', + lgreen: '1;32', + brown: '33', + yellow: '1;33', + blue: '34', + lblue: '1;34', + purple: '35', + lpurple: '1;35', + cyan: '36', + lcyan: '1;36', + lgray: '37', + white: '1;37' +}; + +exports.Color = function(c, str) { + return ['\x1B[', colors[c], 'm', str, '\x1B[m'].join(''); +}; diff --git a/node_modules/coa/lib/completion.js b/node_modules/coa/lib/completion.js index ed6eb1c2..a4b1edcb 100644 --- a/node_modules/coa/lib/completion.js +++ b/node_modules/coa/lib/completion.js @@ -1,176 +1,134 @@ -'use strict'; - -const constants = require('constants'); -const fs = require('fs'); -const path = require('path'); - -const Q = require('q'); - -const shell = require('./shell'); -const escape = shell.escape; -const unescape = shell.unescape; - +// Generated by CoffeeScript 1.6.3 /** - * Most of the code adopted from the npm package shell completion code. - * See https://github.com/isaacs/npm/blob/master/lib/completion.js - * - * @returns {COA.CoaObject} - */ -module.exports = function completion() { - return this - .title('Shell completion') - .helpful() - .arg() - .name('raw') - .title('Completion words') - .arr() - .end() - .act((opts, args) => { - if(process.platform === 'win32') { - const e = new Error('shell completion not supported on windows'); - e.code = 'ENOTSUP'; - e.errno = constants.ENOTSUP; - return this.reject(e); - } +Most of the code adopted from the npm package shell completion code. +See https://github.com/isaacs/npm/blob/master/lib/completion.js +*/ - // if the COMP_* isn't in the env, then just dump the script - if((process.env.COMP_CWORD == null) - || (process.env.COMP_LINE == null) - || (process.env.COMP_POINT == null)) { - return dumpScript(this._cmd._name); - } +var Q, complete, dumpScript, escape, getOpts, unescape; - console.error('COMP_LINE: %s', process.env.COMP_LINE); - console.error('COMP_CWORD: %s', process.env.COMP_CWORD); - console.error('COMP_POINT: %s', process.env.COMP_POINT); - console.error('args: %j', args.raw); +Q = require('q'); - // completion opts - opts = getOpts(args.raw); +escape = require('./shell').escape; - // cmd - const parsed = this._cmd._parseCmd(opts.partialWords); - return Q.when(complete(parsed.cmd, parsed.opts), compls => { - console.error('filtered: %j', compls); - return console.log(compls.map(escape).join('\n')); - }); - }); +unescape = require('./shell').unescape; + +module.exports = function() { + return this.title('Shell completion').helpful().arg().name('raw').title('Completion words').arr().end().act(function(opts, args) { + var argv, cmd, e, _ref; + if (process.platform === 'win32') { + e = new Error('shell completion not supported on windows'); + e.code = 'ENOTSUP'; + e.errno = require('constants').ENOTSUP; + return this.reject(e); + } + if ((process.env.COMP_CWORD == null) || (process.env.COMP_LINE == null) || (process.env.COMP_POINT == null)) { + return dumpScript(this._cmd._name); + } + console.error('COMP_LINE: %s', process.env.COMP_LINE); + console.error('COMP_CWORD: %s', process.env.COMP_CWORD); + console.error('COMP_POINT: %s', process.env.COMP_POINT); + console.error('args: %j', args.raw); + opts = getOpts(args.raw); + _ref = this._cmd._parseCmd(opts.partialWords), cmd = _ref.cmd, argv = _ref.argv; + return Q.when(complete(cmd, opts), function(compls) { + console.error('filtered: %j', compls); + return console.log(compls.map(escape).join('\n')); + }); + }); }; -function dumpScript(name) { - const defer = Q.defer(); - - fs.readFile(path.resolve(__dirname, 'completion.sh'), 'utf8', function(err, d) { - if(err) return defer.reject(err); - d = d.replace(/{{cmd}}/g, path.basename(name)).replace(/^#!.*?\n/, ''); - - process.stdout.on('error', onError); - process.stdout.write(d, () => defer.resolve()); - }); - - return defer.promise; - - function onError(err) { - // Darwin is a real dick sometimes. - // - // This is necessary because the "source" or "." program in - // bash on OS X closes its file argument before reading - // from it, meaning that you get exactly 1 write, which will - // work most of the time, and will always raise an EPIPE. - // - // Really, one should not be tossing away EPIPE errors, or any - // errors, so casually. But, without this, `. <(cmd completion)` - // can never ever work on OS X. - if(err.errno !== constants.EPIPE) return defer.reject(err); +dumpScript = function(name) { + var defer, fs, path; + fs = require('fs'); + path = require('path'); + defer = Q.defer(); + fs.readFile(path.resolve(__dirname, 'completion.sh'), 'utf8', function(err, d) { + var onError; + if (err) { + return defer.reject(err); + } + d = d.replace(/{{cmd}}/g, path.basename(name)).replace(/^\#\!.*?\n/, ''); + onError = function(err) { + if (err.errno === require('constants').EPIPE) { process.stdout.removeListener('error', onError); return defer.resolve(); - } -} - -function getOpts(argv) { - // get the partial line and partial word, if the point isn't at the end - // ie, tabbing at: cmd foo b|ar - const line = process.env.COMP_LINE; - const w = +process.env.COMP_CWORD; - const point = +process.env.COMP_POINT; - const words = argv.map(unescape); - const word = words[w]; - const partialLine = line.substr(0, point); - const partialWords = words.slice(0, w); - - // figure out where in that last word the point is - let partialWord = argv[w] || ''; - let i = partialWord.length; - while(partialWord.substr(0, i) !== partialLine.substr(-1 * i) && i > 0) i--; - - partialWord = unescape(partialWord.substr(0, i)); - partialWord && partialWords.push(partialWord); - - return { - line, - w, - point, - words, - word, - partialLine, - partialWords, - partialWord + } else { + return defer.reject(err); + } }; -} - -function complete(cmd, opts) { - let optWord, optPrefix, - compls = []; - - // Complete on cmds - if(opts.partialWord.indexOf('-')) - compls = Object.keys(cmd._cmdsByName); - // Complete on required opts without '-' in last partial word - // (if required not already specified) - // - // Commented out because of uselessness: - // -b, --block suggest results in '-' on cmd line; - // next completion suggest all options, because of '-' - //.concat Object.keys(cmd._optsByKey).filter (v) -> cmd._optsByKey[v]._req - else { - // complete on opt values: --opt=| case - const m = opts.partialWord.match(/^(--\w[\w-_]*)=(.*)$/); - if(m) { - optWord = m[1]; - optPrefix = optWord + '='; - } else - // complete on opts - // don't complete on opts in case of --opt=val completion - // TODO: don't complete on opts in case of unknown arg after commands - // TODO: complete only on opts with arr() or not already used - // TODO: complete only on full opts? - compls = Object.keys(cmd._optsByKey); - } - - // complete on opt values: next arg case - opts.partialWords[opts.w - 1].indexOf('-') || (optWord = opts.partialWords[opts.w - 1]); - - // complete on opt values: completion - let opt; - optWord - && (opt = cmd._optsByKey[optWord]) - && !opt._flag - && opt._comp - && (compls = Q.join(compls, - Q.when(opt._comp(opts), - (c, o) => c.concat(o.map(v => (optPrefix || '') + v))))); - - // TODO: complete on args values (context aware, custom completion?) - - // custom completion on cmds - cmd._comp && (compls = Q.join(compls, Q.when(cmd._comp(opts)), (c, o) => c.concat(o))); - - // TODO: context aware custom completion on cmds, opts and args - // (can depend on already entered values, especially options) - - return Q.when(compls, complitions => { - console.error('partialWord: %s', opts.partialWord); - console.error('compls: %j', complitions); - return compls.filter(c => c.indexOf(opts.partialWord) === 0); + process.stdout.on('error', onError); + return process.stdout.write(d, function() { + return defer.resolve(); }); -} + }); + return defer.promise; +}; + +getOpts = function(argv) { + var i, line, partialLine, partialWord, partialWords, point, w, word, words; + line = process.env.COMP_LINE; + w = +process.env.COMP_CWORD; + point = +process.env.COMP_POINT; + words = argv.map(unescape); + word = words[w]; + partialLine = line.substr(0, point); + partialWords = words.slice(0, w); + partialWord = argv[w] || ''; + i = partialWord.length; + while (partialWord.substr(0, i) !== partialLine.substr(-1 * i) && i > 0) { + i--; + } + partialWord = unescape(partialWord.substr(0, i)); + if (partialWord) { + partialWords.push(partialWord); + } + return { + line: line, + w: w, + point: point, + words: words, + word: word, + partialLine: partialLine, + partialWords: partialWords, + partialWord: partialWord + }; +}; + +complete = function(cmd, opts) { + var compls, m, o, opt, optPrefix, optWord; + compls = []; + if (opts.partialWord.indexOf('-')) { + compls = Object.keys(cmd._cmdsByName); + } else { + if (m = opts.partialWord.match(/^(--\w[\w-_]*)=(.*)$/)) { + optWord = m[1]; + optPrefix = optWord + '='; + } else { + compls = Object.keys(cmd._optsByKey); + } + } + if (!(o = opts.partialWords[opts.w - 1]).indexOf('-')) { + optWord = o; + } + if (optWord && (opt = cmd._optsByKey[optWord])) { + if (!opt._flag && opt._comp) { + compls = Q.join(compls, Q.when(opt._comp(opts), function(c, o) { + return c.concat(o.map(function(v) { + return (optPrefix || '') + v; + })); + })); + } + } + if (cmd._comp) { + compls = Q.join(compls, Q.when(cmd._comp(opts)), function(c, o) { + return c.concat(o); + }); + } + return Q.when(compls, function(compls) { + console.error('partialWord: %s', opts.partialWord); + console.error('compls: %j', compls); + return compls.filter(function(c) { + return c.indexOf(opts.partialWord) === 0; + }); + }); +}; diff --git a/node_modules/coa/lib/index.js b/node_modules/coa/lib/index.js index 163c2d56..05b89221 100644 --- a/node_modules/coa/lib/index.js +++ b/node_modules/coa/lib/index.js @@ -1,14 +1,10 @@ -const - Cmd = require('./cmd'), - Opt = require('./opt'), - Arg = require('./arg'), - shell = require('./shell'); +// Generated by CoffeeScript 1.6.3 +exports.Cmd = require('./cmd').Cmd; -module.exports = { - Cmd : Cmd.create, - Opt : Opt.create, - Arg : Arg.create, - classes : { Cmd, Opt, Arg }, - shell, - require -}; +exports.Opt = require('./cmd').Opt; + +exports.Arg = require('./cmd').Arg; + +exports.shell = require('./shell'); + +exports.require = require; diff --git a/node_modules/coa/lib/opt.js b/node_modules/coa/lib/opt.js index 8b59235f..9aaca543 100644 --- a/node_modules/coa/lib/opt.js +++ b/node_modules/coa/lib/opt.js @@ -1,155 +1,338 @@ -'use strict'; +// Generated by CoffeeScript 1.6.3 +var Cmd, Color, Opt, Q, fs; -const - Q = require('q'), +fs = require('fs'); - CoaParam = require('./coaparam'), - chalk = require('chalk'); +Q = require('q'); + +Color = require('./color').Color; + +Cmd = require('./cmd').Cmd; /** - * Option - * - * Named entity. Options may have short and long keys for use from command line. - * - * @namespace - * @class Opt - * @extends CoaParam - */ -module.exports = class Opt extends CoaParam { - /** - * @constructs - * @param {COA.Cmd} cmd - parent command - */ - constructor(cmd) { - super(cmd); +Option - this._short = null; - this._long = null; - this._flag = false; - this._only = false; - this._cmd._opts.push(this); - } +Named entity. Options may have short and long keys for use from command line. +@namespace +@class Presents option +*/ - /** - * Set a short key for option to be used with one hyphen from command line. - * - * @param {String} short - short name - * @returns {COA.Opt} - this instance (for chainability) - */ - short(short) { - this._short = short; - this._cmd._optsByKey[`-${short}`] = this; - return this; - } - /** - * Set a short key for option to be used with double hyphens from command line. - * - * @param {String} long - long name - * @returns {COA.Opt} - this instance (for chainability) - */ - long(long) { - this._long = long; - this._cmd._optsByKey[`--${long}`] = this; - return this; - } +exports.Opt = Opt = (function() { + /** + @constructs + @param {COA.Cmd} cmd parent command + */ - /** - * Make an option boolean, i.e. option without value. - * - * @returns {COA.Opt} - this instance (for chainability) - */ - flag() { - this._flag = true; - return this; - } + function Opt(_cmd) { + this._cmd = _cmd; + this._cmd._opts.push(this); + } - /** - * Makes an option to act as a command, - * i.e. program will exit just after option action. - * - * @returns {COA.Opt} - this instance (for chainability) - */ - only() { - this._only = true; - return this; - } + /** + Set a canonical option identifier to be used anywhere in the API. + @param {String} _name option name + @returns {COA.Opt} this instance (for chainability) + */ - /** - * Add action for current option command. - * This action is performed if the current option - * is present in parsed options (with any value). - * - * @param {Function} act - action function, - * invoked in the context of command instance - * and has the parameters: - * - {Object} opts - parsed options - * - {Array} args - parsed arguments - * - {Object} res - actions result accumulator - * It can return rejected promise by Cmd.reject (in case of error) - * or any other value treated as result. - * @returns {COA.Opt} - this instance (for chainability) - */ - act(act) { - // Need function here for arguments - const opt = this; - this._cmd.act(function(opts) { - if(!opts.hasOwnProperty(opt._name)) return; - const res = act.apply(this, arguments); - if(!opt._only) return res; + Opt.prototype.name = function(_name) { + this._name = _name; + return this; + }; - return Q.when(res, out => this.reject({ - toString : () => out.toString(), - exitCode : 0 - })); - }); + /** + Set a long description for option to be used anywhere in text messages. + @param {String} _title option title + @returns {COA.Opt} this instance (for chainability) + */ - return this; - } - _saveVal(opts, val) { - this._val && (val = this._val(val)); + Opt.prototype.title = Cmd.prototype.title; - const name = this._name; - this._arr - ? (opts[name] || (opts[name] = [])).push(val) - : (opts[name] = val); + /** + Set a short key for option to be used with one hyphen from command line. + @param {String} _short + @returns {COA.Opt} this instance (for chainability) + */ - return val; - } - _parse(argv, opts) { - return this._saveVal(opts, this._flag ? true : argv.shift()); - } + Opt.prototype.short = function(_short) { + this._short = _short; + return this._cmd._optsByKey['-' + _short] = this; + }; - _checkParsed(opts) { - return !opts.hasOwnProperty(this._name); - } + /** + Set a short key for option to be used with double hyphens from command line. + @param {String} _long + @returns {COA.Opt} this instance (for chainability) + */ - _usage() { - const res = [], - nameStr = this._name.toUpperCase(); - if(this._short) { - res.push('-', chalk.greenBright(this._short)); - this._flag || res.push(' ' + nameStr); - res.push(', '); + Opt.prototype.long = function(_long) { + this._long = _long; + return this._cmd._optsByKey['--' + _long] = this; + }; + + /** + Make an option boolean, i.e. option without value. + @returns {COA.Opt} this instance (for chainability) + */ + + + Opt.prototype.flag = function() { + this._flag = true; + return this; + }; + + /** + Makes an option accepts multiple values. + Otherwise, the value will be used by the latter passed. + @returns {COA.Opt} this instance (for chainability) + */ + + + Opt.prototype.arr = function() { + this._arr = true; + return this; + }; + + /** + Makes an option required. + @returns {COA.Opt} this instance (for chainability) + */ + + + Opt.prototype.req = function() { + this._req = true; + return this; + }; + + /** + Makes an option to act as a command, + i.e. program will exit just after option action. + @returns {COA.Opt} this instance (for chainability) + */ + + + Opt.prototype.only = function() { + this._only = true; + return this; + }; + + /** + Set a validation (or value) function for option. + Value from command line passes through before becoming available from API. + Using for validation and convertion simple types to any values. + @param {Function} _val validating function, + invoked in the context of option instance + and has one parameter with value from command line + @returns {COA.Opt} this instance (for chainability) + */ + + + Opt.prototype.val = function(_val) { + this._val = _val; + return this; + }; + + /** + Set a default value for option. + Default value passed through validation function as ordinary value. + @param {Object} _def + @returns {COA.Opt} this instance (for chainability) + */ + + + Opt.prototype.def = function(_def) { + this._def = _def; + return this; + }; + + /** + Make option value inputting stream. + It's add useful validation and shortcut for STDIN. + @returns {COA.Opt} this instance (for chainability) + */ + + + Opt.prototype.input = function() { + process.stdin.pause(); + return this.def(process.stdin).val(function(v) { + var s; + if (typeof v === 'string') { + if (v === '-') { + return process.stdin; + } else { + s = fs.createReadStream(v, { + encoding: 'utf8' + }); + s.pause(); + return s; } + } else { + return v; + } + }); + }; - if(this._long) { - res.push('--', chalk.green(this._long)); - this._flag || res.push('=' + nameStr); + /** + Make option value outputing stream. + It's add useful validation and shortcut for STDOUT. + @returns {COA.Opt} this instance (for chainability) + */ + + + Opt.prototype.output = function() { + return this.def(process.stdout).val(function(v) { + if (typeof v === 'string') { + if (v === '-') { + return process.stdout; + } else { + return fs.createWriteStream(v, { + encoding: 'utf8' + }); } + } else { + return v; + } + }); + }; - res.push(' : ', this._title); + /** + Add action for current option command. + This action is performed if the current option + is present in parsed options (with any value). + @param {Function} act action function, + invoked in the context of command instance + and has the parameters: + - {Object} opts parsed options + - {Array} args parsed arguments + - {Object} res actions result accumulator + It can return rejected promise by Cmd.reject (in case of error) + or any other value treated as result. + @returns {COA.Opt} this instance (for chainability) + */ - this._req && res.push(' ', chalk.redBright('(required)')); - return res.join(''); + Opt.prototype.act = function(act) { + var name, opt; + opt = this; + name = this._name; + this._cmd.act(function(opts) { + var res, + _this = this; + if (name in opts) { + res = act.apply(this, arguments); + if (opt._only) { + return Q.when(res, function(res) { + return _this.reject({ + toString: function() { + return res.toString(); + }, + exitCode: 0 + }); + }); + } else { + return res; + } + } + }); + return this; + }; + + /** + Set custom additional completion for current option. + @param {Function} completion generation function, + invoked in the context of option instance. + Accepts parameters: + - {Object} opts completion options + It can return promise or any other value treated as result. + @returns {COA.Opt} this instance (for chainability) + */ + + + Opt.prototype.comp = Cmd.prototype.comp; + + Opt.prototype._saveVal = function(opts, val) { + var _name; + if (this._val) { + val = this._val(val); } - - _requiredText() { - return `Missing required option:\n ${this._usage()}`; + if (this._arr) { + (opts[_name = this._name] || (opts[_name] = [])).push(val); + } else { + opts[this._name] = val; } -}; + return val; + }; + + Opt.prototype._parse = function(argv, opts) { + return this._saveVal(opts, this._flag ? true : argv.shift()); + }; + + Opt.prototype._checkParsed = function(opts, args) { + return !opts.hasOwnProperty(this._name); + }; + + Opt.prototype._usage = function() { + var nameStr, res; + res = []; + nameStr = this._name.toUpperCase(); + if (this._short) { + res.push('-', Color('lgreen', this._short)); + if (!this._flag) { + res.push(' ' + nameStr); + } + res.push(', '); + } + if (this._long) { + res.push('--', Color('green', this._long)); + if (!this._flag) { + res.push('=' + nameStr); + } + } + res.push(' : ', this._title); + if (this._req) { + res.push(' ', Color('lred', '(required)')); + } + return res.join(''); + }; + + Opt.prototype._requiredText = function() { + return 'Missing required option:\n ' + this._usage(); + }; + + /** + Return rejected promise with error code. + Use in .val() for return with error. + @param {Object} reject reason + You can customize toString() method and exitCode property + of reason object. + @returns {Q.promise} rejected promise + */ + + + Opt.prototype.reject = Cmd.prototype.reject; + + /** + Finish chain for current option and return parent command instance. + @returns {COA.Cmd} parent command + */ + + + Opt.prototype.end = Cmd.prototype.end; + + /** + Apply function with arguments in context of option instance. + @param {Function} fn + @param {Array} args + @returns {COA.Opt} this instance (for chainability) + */ + + + Opt.prototype.apply = Cmd.prototype.apply; + + return Opt; + +})(); diff --git a/node_modules/coa/lib/shell.js b/node_modules/coa/lib/shell.js index 3f510e9b..f3d49662 100644 --- a/node_modules/coa/lib/shell.js +++ b/node_modules/coa/lib/shell.js @@ -1,14 +1,14 @@ -module.exports = { escape, unescape }; +// Generated by CoffeeScript 1.6.3 +exports.unescape = function(w) { + w = w.charAt(0) === '"' ? w.replace(/^"|([^\\])"$/g, '$1') : w.replace(/\\ /g, ' '); + return w.replace(/\\("|'|\$|`|\\)/g, '$1'); +}; -function unescape(w) { - w = w.charAt(0) === '"' - ? w.replace(/^"|([^\\])"$/g, '$1') - : w.replace(/\\ /g, ' '); - - return w.replace(/\\("|'|\$|`|\\)/g, '$1'); -} - -function escape(w) { - w = w.replace(/(["'$`\\])/g,'\\$1'); - return w.match(/\s+/) ? `"${w}"` : w; -} +exports.escape = function(w) { + w = w.replace(/(["'$`\\])/g, '\\$1'); + if (w.match(/\s+/)) { + return '"' + w + '"'; + } else { + return w; + } +}; diff --git a/node_modules/coa/package.json b/node_modules/coa/package.json index e2da5765..925b4859 100644 --- a/node_modules/coa/package.json +++ b/node_modules/coa/package.json @@ -1,7 +1,7 @@ { "name": "coa", "description": "Command-Option-Argument: Yet another parser for command line options.", - "version": "2.0.2", + "version": "1.0.4", "homepage": "http://github.com/veged/coa", "author": "Sergey Berezhnoy (http://github.com/veged)", "maintainers": [ @@ -11,12 +11,6 @@ "contributors": [ "Sergey Belov (http://github.com/arikon)" ], - "files": [ - "lib/", - "index.js", - "coa.d.ts", - "README.ru.md" - ], "repository": { "type": "git", "url": "git://github.com/veged/coa.git" @@ -25,29 +19,26 @@ "lib": "./lib" }, "dependencies": { - "@types/q": "^1.5.1", - "chalk": "^2.4.1", "q": "^1.1.2" }, "devDependencies": { - "chai": "~1.7.2", - "coveralls": "^2.11.16", - "eslint": "^4.15.0", - "eslint-config-pedant": "^1.0.0", + "coffee-script": "~1.6.3", + "istanbul": "~0.1.40", + "mocha-istanbul": "*", "mocha": "~1.21.4", - "nyc": "^10.1.2" + "chai": "~1.7.2" }, "scripts": { - "clean": "rm -r .nyc_output coverage", - "coverage": "nyc --reporter=text --reporter=html mocha; echo; echo 'Open coverage/index.html file in your browser'", - "coveralls": "nyc report --reporter=text-lcov | coveralls", - "lint": "eslint .", - "pretest": "npm run lint", - "test": "nyc mocha" + "test": "make test", + "coverage": "make coverage" }, "engines": { - "node": ">= 4.0" + "node": ">= 0.8.0" }, - "types": "./coa.d.ts", - "license": "MIT" + "licenses": [ + { + "type": "MIT" + } + ], + "optionalDependencies": {} } diff --git a/node_modules/coa/qq.js b/node_modules/coa/qq.js new file mode 100644 index 00000000..4aeb9844 --- /dev/null +++ b/node_modules/coa/qq.js @@ -0,0 +1,17 @@ +const run = require('./test/util').run; + +// run(cmd => cmd.arg().name('qwe').end().arg().name('zxc').end().act(function(opts, args) { console.log({opts, args}); }), ['qwe', 'zxc']) // cmd and args +// .then(res => { +// // code +// // stdout +// // stderr +// console.log(res); +// }); + +run(cmd => cmd.opt().name('version').short('v').only().flag().act((opts) => { return 'aasd'; }), ['-v']) // cmd and args + .then(res => { + // code + // stdout + // stderr + console.log(res); + }); diff --git a/node_modules/coa/src/arg.coffee b/node_modules/coa/src/arg.coffee new file mode 100644 index 00000000..da57dff0 --- /dev/null +++ b/node_modules/coa/src/arg.coffee @@ -0,0 +1,130 @@ +Color = require('./color').Color +Cmd = require('./cmd').Cmd +Opt = require('./opt').Opt + +###* +Argument + +Unnamed entity. From command line arguments passed as list of unnamed values. +@namespace +@class Presents argument +### +exports.Arg = class Arg + + ###* + @constructs + @param {COA.Cmd} cmd parent command + ### + constructor: (@_cmd) -> @_cmd._args.push @ + + ###* + Set a canonical argument identifier to be used anywhere in text messages. + @param {String} _name argument name + @returns {COA.Arg} this instance (for chainability) + ### + name: Opt::name + + ###* + Set a long description for argument to be used anywhere in text messages. + @param {String} _title argument title + @returns {COA.Arg} this instance (for chainability) + ### + title: Cmd::title + + ###* + Makes an argument accepts multiple values. + Otherwise, the value will be used by the latter passed. + @returns {COA.Arg} this instance (for chainability) + ### + arr: Opt::arr + + ###* + Makes an argument required. + @returns {COA.Arg} this instance (for chainability) + ### + req: Opt::req + + ###* + Set a validation (or value) function for argument. + Value from command line passes through before becoming available from API. + Using for validation and convertion simple types to any values. + @param {Function} _val validating function, + invoked in the context of argument instance + and has one parameter with value from command line + @returns {COA.Arg} this instance (for chainability) + ### + val: Opt::val + + ###* + Set a default value for argument. + Default value passed through validation function as ordinary value. + @param {Object} _def + @returns {COA.Arg} this instance (for chainability) + ### + def: Opt::def + + ###* + Set custom additional completion for current argument. + @param {Function} completion generation function, + invoked in the context of argument instance. + Accepts parameters: + - {Object} opts completion options + It can return promise or any other value treated as result. + @returns {COA.Arg} this instance (for chainability) + ### + comp: Cmd::comp + + ###* + Make argument value inputting stream. + It's add useful validation and shortcut for STDIN. + @returns {COA.Arg} this instance (for chainability) + ### + input: Opt::input + + ###* + Make argument value outputing stream. + It's add useful validation and shortcut for STDOUT. + @returns {COA.Arg} this instance (for chainability) + ### + output: Opt::output + + _parse: (arg, args) -> + @_saveVal(args, arg) + + _saveVal: Opt::_saveVal + + _checkParsed: (opts, args) -> not args.hasOwnProperty(@_name) + + _usage: -> + res = [] + + res.push Color('lpurple', @_name.toUpperCase()), ' : ', @_title + if @_req then res.push ' ', Color('lred', '(required)') + + res.join '' + + _requiredText: -> 'Missing required argument:\n ' + @_usage() + + ###* + Return rejected promise with error code. + Use in .val() for return with error. + @param {Object} reject reason + You can customize toString() method and exitCode property + of reason object. + @returns {Q.promise} rejected promise + ### + reject: Cmd::reject + + ###* + Finish chain for current option and return parent command instance. + @returns {COA.Cmd} parent command + ### + end: Cmd::end + + ###* + Apply function with arguments in context of arg instance. + @param {Function} fn + @param {Array} args + @returns {COA.Arg} this instance (for chainability) + ### + apply: Cmd::apply diff --git a/node_modules/coa/src/cmd.coffee b/node_modules/coa/src/cmd.coffee new file mode 100644 index 00000000..bde16248 --- /dev/null +++ b/node_modules/coa/src/cmd.coffee @@ -0,0 +1,456 @@ +UTIL = require 'util' +PATH = require 'path' +Color = require('./color').Color +Q = require('q') + +#inspect = require('eyes').inspector { maxLength: 99999, stream: process.stderr } + +###* +Command + +Top level entity. Commands may have options and arguments. +@namespace +@class Presents command +### +exports.Cmd = class Cmd + + ###* + @constructs + @param {COA.Cmd} [cmd] parent command + ### + constructor: (cmd) -> + if this not instanceof Cmd + return new Cmd cmd + + @_parent cmd + + @_cmds = [] + @_cmdsByName = {} + + @_opts = [] + @_optsByKey = {} + + @_args = [] + + @_ext = false + + @get: (propertyName, func) -> + Object.defineProperty @::, propertyName, + configurable: true + enumerable: true + get: func + + ###* + Returns object containing all its subcommands as methods + to use from other programs. + @returns {Object} + ### + @get 'api', () -> + if not @_api + @_api = => @invoke.apply @, arguments + for c of @_cmdsByName + do (c) => + @_api[c] = @_cmdsByName[c].api + @_api + + _parent: (cmd) -> + @_cmd = cmd or this + if cmd + cmd._cmds.push @ + if @_name then @_cmd._cmdsByName[@_name] = @ + @ + + ###* + Set a canonical command identifier to be used anywhere in the API. + @param {String} _name command name + @returns {COA.Cmd} this instance (for chainability) + ### + name: (@_name) -> + if @_cmd isnt @ then @_cmd._cmdsByName[_name] = @ + @ + + ###* + Set a long description for command to be used anywhere in text messages. + @param {String} _title command title + @returns {COA.Cmd} this instance (for chainability) + ### + title: (@_title) -> @ + + ###* + Create new or add existing subcommand for current command. + @param {COA.Cmd} [cmd] existing command instance + @returns {COA.Cmd} new subcommand instance + ### + cmd: (cmd) -> + if cmd then cmd._parent @ + else new Cmd @ + + ###* + Create option for current command. + @returns {COA.Opt} new option instance + ### + opt: -> new (require('./opt').Opt) @ + + ###* + Create argument for current command. + @returns {COA.Opt} new argument instance + ### + arg: -> new (require('./arg').Arg) @ + + ###* + Add (or set) action for current command. + @param {Function} act action function, + invoked in the context of command instance + and has the parameters: + - {Object} opts parsed options + - {Array} args parsed arguments + - {Object} res actions result accumulator + It can return rejected promise by Cmd.reject (in case of error) + or any other value treated as result. + @param {Boolean} [force=false] flag for set action instead add to existings + @returns {COA.Cmd} this instance (for chainability) + ### + act: (act, force) -> + return @ unless act + + if not force and @_act + @_act.push act + else + @_act = [act] + + @ + + ###* + Set custom additional completion for current command. + @param {Function} completion generation function, + invoked in the context of command instance. + Accepts parameters: + - {Object} opts completion options + It can return promise or any other value treated as result. + @returns {COA.Cmd} this instance (for chainability) + ### + comp: (@_comp) -> @ + + ###* + Apply function with arguments in context of command instance. + @param {Function} fn + @param {Array} args + @returns {COA.Cmd} this instance (for chainability) + ### + apply: (fn, args...) -> + fn.apply this, args + @ + + ###* + Make command "helpful", i.e. add -h --help flags for print usage. + @returns {COA.Cmd} this instance (for chainability) + ### + helpful: -> + @opt() + .name('help').title('Help') + .short('h').long('help') + .flag() + .only() + .act -> + return @usage() + .end() + + ###* + Adds shell completion to command, adds "completion" subcommand, + that makes all the magic. + Must be called only on root command. + @returns {COA.Cmd} this instance (for chainability) + ### + completable: -> + @cmd() + .name('completion') + .apply(require './completion') + .end() + + ###* + Allow command to be extendable by external node.js modules. + @param {String} [pattern] Pattern of node.js module to find subcommands at. + @returns {COA.Cmd} this instance (for chainability) + ### + extendable: (pattern) -> + @_ext = pattern or true + @ + + _exit: (msg, code) -> + process.once 'exit', -> + if msg then console.error msg + process.exit code or 0 + + ###* + Build full usage text for current command instance. + @returns {String} usage text + ### + usage: -> + res = [] + + if @_title then res.push @_fullTitle() + + res.push('', 'Usage:') + + if @_cmds.length then res.push(['', '', + Color('lred', @_fullName()), + Color('lblue', 'COMMAND'), + Color('lgreen', '[OPTIONS]'), + Color('lpurple', '[ARGS]')].join ' ') + + if @_opts.length + @_args.length then res.push(['', '', + Color('lred', @_fullName()), + Color('lgreen', '[OPTIONS]'), + Color('lpurple', '[ARGS]')].join ' ') + + res.push( + @_usages(@_cmds, 'Commands'), + @_usages(@_opts, 'Options'), + @_usages(@_args, 'Arguments')) + + res.join '\n' + + _usage: -> + Color('lblue', @_name) + ' : ' + @_title + + _usages: (os, title) -> + unless os.length then return + res = ['', title + ':'] + for o in os + res.push ' ' + o._usage() + res.join '\n' + + _fullTitle: -> + (if @_cmd is this then '' else @_cmd._fullTitle() + '\n') + @_title + + _fullName: -> + (if this._cmd is this then '' else @_cmd._fullName() + ' ') + PATH.basename(@_name) + + _ejectOpt: (opts, opt) -> + if (pos = opts.indexOf(opt)) >= 0 + if opts[pos]._arr + opts[pos] + else + opts.splice(pos, 1)[0] + + _checkRequired: (opts, args) -> + if not (@_opts.filter (o) -> o._only and o._name of opts).length + all = @_opts.concat @_args + while i = all.shift() + if i._req and i._checkParsed opts, args + return @reject i._requiredText() + + _parseCmd: (argv, unparsed = []) -> + argv = argv.concat() + optSeen = false + while i = argv.shift() + if not i.indexOf '-' + optSeen = true + if not optSeen and /^\w[\w-_]*$/.test(i) + cmd = @_cmdsByName[i] + + if not cmd and @_ext + # construct package name to require + if typeof @_ext is 'string' + if ~@_ext.indexOf('%s') + # use formatted string + pkg = UTIL.format(@_ext, i) + else + # just append subcommand name to the prefix + pkg = @_ext + i + else if @_ext is true + # use default scheme: -- and so on + pkg = i + c = @ + loop + pkg = c._name + '-' + pkg + if c._cmd is c then break + c = c._cmd + + try + cmdDesc = require(pkg) + catch e + + if cmdDesc + if typeof cmdDesc == 'function' + # set create subcommand, set its name and apply imported function + @cmd() + .name(i) + .apply(cmdDesc) + .end() + else if typeof cmdDesc == 'object' + # register subcommand + @cmd(cmdDesc) + # set command name + cmdDesc.name(i) + else + throw new Error 'Error: Unsupported command declaration type, ' + + 'should be function or COA.Cmd() object' + cmd = @_cmdsByName[i] + if cmd + return cmd._parseCmd argv, unparsed + + unparsed.push i + + { cmd: @, argv: unparsed } + + _parseOptsAndArgs: (argv) -> + opts = {} + args = {} + + nonParsedOpts = @_opts.concat() + nonParsedArgs = @_args.concat() + + while i = argv.shift() + # opt + if i isnt '--' and not i.indexOf '-' + + if m = i.match /^(--\w[\w-_]*)=(.*)$/ + i = m[1] + + # suppress 'unknown argument' error for flag options with values + if not @_optsByKey[i]._flag + argv.unshift m[2] + + if opt = @_ejectOpt nonParsedOpts, @_optsByKey[i] + if Q.isRejected(res = opt._parse argv, opts) + return res + else + return @reject "Unknown option: #{ i }" + + # arg + else + if i is '--' + i = argv.splice(0) + + i = if Array.isArray(i) then i else [i] + + while a = i.shift() + if arg = nonParsedArgs.shift() + if arg._arr then nonParsedArgs.unshift arg + if Q.isRejected(res = arg._parse a, args) + return res + else + return @reject "Unknown argument: #{ a }" + + # set defaults + { + opts: @_setDefaults(opts, nonParsedOpts), + args: @_setDefaults(args, nonParsedArgs) + } + + _setDefaults: (params, desc) -> + for i in desc + if i._name not of params and '_def' of i + i._saveVal params, i._def + params + + _processParams: (params, desc) -> + notExists = [] + for i in desc + n = i._name + if n not of params + notExists.push i + continue + + vals = params[n] + delete params[n] + if not Array.isArray vals + vals = [vals] + + for v in vals + if Q.isRejected(res = i._saveVal(params, v)) + return res + + # set defaults + @_setDefaults params, notExists + + _parseArr: (argv) -> + Q.when @_parseCmd(argv), (p) -> + Q.when p.cmd._parseOptsAndArgs(p.argv), (r) -> + { cmd: p.cmd, opts: r.opts, args: r.args } + + _do: (input) -> + Q.when input, (input) => + cmd = input.cmd + [@_checkRequired].concat(cmd._act or []).reduce( + (res, act) -> + Q.when res, (res) -> + act.call( + cmd + input.opts + input.args + res) + undefined + ) + + ###* + Parse arguments from simple format like NodeJS process.argv + and run ahead current program, i.e. call process.exit when all actions done. + @param {Array} argv + @returns {COA.Cmd} this instance (for chainability) + ### + run: (argv = process.argv.slice(2)) -> + cb = (code) => (res) => + if res + @_exit res.stack ? res.toString(), res.exitCode ? code + else + @_exit() + Q.when(@do(argv), cb(0), cb(1)).done() + @ + + ###* + Convenient function to run command from tests. + @param {Array} argv + @returns {Q.Promise} + ### + do: (argv) -> + @_do(@_parseArr argv || []) + + ###* + Invoke specified (or current) command using provided + options and arguments. + @param {String|Array} cmds subcommand to invoke (optional) + @param {Object} opts command options (optional) + @param {Object} args command arguments (optional) + @returns {Q.Promise} + ### + invoke: (cmds = [], opts = {}, args = {}) -> + if typeof cmds == 'string' + cmds = cmds.split(' ') + + if arguments.length < 3 + if not Array.isArray cmds + args = opts + opts = cmds + cmds = [] + + Q.when @_parseCmd(cmds), (p) => + if p.argv.length + return @reject "Unknown command: " + cmds.join ' ' + + Q.all([@_processParams(opts, @_opts), @_processParams(args, @_args)]) + .spread (opts, args) => + @_do({ cmd: p.cmd, opts: opts, args: args }) + # catch fails from .only() options + .fail (res) => + if res and res.exitCode is 0 + res.toString() + else + @reject(res) + + ###* + Return reject of actions results promise with error code. + Use in .act() for return with error. + @param {Object} reject reason + You can customize toString() method and exitCode property + of reason object. + @returns {Q.promise} rejected promise + ### + reject: (reason) -> Q.reject(reason) + + ###* + Finish chain for current subcommand and return parent command instance. + @returns {COA.Cmd} parent command + ### + end: -> @_cmd diff --git a/node_modules/coa/src/color.coffee b/node_modules/coa/src/color.coffee new file mode 100644 index 00000000..f07a3a57 --- /dev/null +++ b/node_modules/coa/src/color.coffee @@ -0,0 +1,25 @@ +colors = + black: '30' + dgray: '1;30' + red: '31' + lred: '1;31' + green: '32' + lgreen: '1;32' + brown: '33' + yellow: '1;33' + blue: '34' + lblue: '1;34' + purple: '35' + lpurple: '1;35' + cyan: '36' + lcyan: '1;36' + lgray: '37' + white: '1;37' + +exports.Color = (c, str) -> + # Use \x1B instead of \033 because of CoffeeScript 1.3.x compilation error + [ + '\x1B[', colors[c], 'm' + str + '\x1B[m' + ].join '' diff --git a/node_modules/coa/src/completion.coffee b/node_modules/coa/src/completion.coffee new file mode 100644 index 00000000..2c1e358d --- /dev/null +++ b/node_modules/coa/src/completion.coffee @@ -0,0 +1,156 @@ +###* +Most of the code adopted from the npm package shell completion code. +See https://github.com/isaacs/npm/blob/master/lib/completion.js +### + +Q = require 'q' +escape = require('./shell').escape +unescape = require('./shell').unescape + +module.exports = -> + @title('Shell completion') + .helpful() + .arg() + .name('raw') + .title('Completion words') + .arr() + .end() + .act (opts, args) -> + if process.platform == 'win32' + e = new Error 'shell completion not supported on windows' + e.code = 'ENOTSUP' + e.errno = require('constants').ENOTSUP + return @reject(e) + + # if the COMP_* isn't in the env, then just dump the script + if !process.env.COMP_CWORD? or !process.env.COMP_LINE? or !process.env.COMP_POINT? + return dumpScript(@_cmd._name) + + console.error 'COMP_LINE: %s', process.env.COMP_LINE + console.error 'COMP_CWORD: %s', process.env.COMP_CWORD + console.error 'COMP_POINT: %s', process.env.COMP_POINT + console.error 'args: %j', args.raw + + # completion opts + opts = getOpts args.raw + + # cmd + { cmd, argv } = @_cmd._parseCmd opts.partialWords + Q.when complete(cmd, opts), (compls) -> + console.error 'filtered: %j', compls + console.log compls.map(escape).join('\n') + + +dumpScript = (name) -> + fs = require 'fs' + path = require 'path' + defer = Q.defer() + + fs.readFile path.resolve(__dirname, 'completion.sh'), 'utf8', (err, d) -> + if err then return defer.reject err + d = d.replace(/{{cmd}}/g, path.basename name).replace(/^\#\!.*?\n/, '') + + onError = (err) -> + # Darwin is a real dick sometimes. + # + # This is necessary because the "source" or "." program in + # bash on OS X closes its file argument before reading + # from it, meaning that you get exactly 1 write, which will + # work most of the time, and will always raise an EPIPE. + # + # Really, one should not be tossing away EPIPE errors, or any + # errors, so casually. But, without this, `. <(cmd completion)` + # can never ever work on OS X. + if err.errno == require('constants').EPIPE + process.stdout.removeListener 'error', onError + defer.resolve() + else + defer.reject(err) + + process.stdout.on 'error', onError + process.stdout.write d, -> defer.resolve() + + defer.promise + + +getOpts = (argv) -> + # get the partial line and partial word, if the point isn't at the end + # ie, tabbing at: cmd foo b|ar + line = process.env.COMP_LINE + w = +process.env.COMP_CWORD + point = +process.env.COMP_POINT + words = argv.map unescape + word = words[w] + partialLine = line.substr 0, point + partialWords = words.slice 0, w + + # figure out where in that last word the point is + partialWord = argv[w] or '' + i = partialWord.length + while partialWord.substr(0, i) isnt partialLine.substr(-1 * i) and i > 0 + i-- + partialWord = unescape partialWord.substr 0, i + if partialWord then partialWords.push partialWord + + { + line: line + w: w + point: point + words: words + word: word + partialLine: partialLine + partialWords: partialWords + partialWord: partialWord + } + + +complete = (cmd, opts) -> + compls = [] + + # complete on cmds + if opts.partialWord.indexOf('-') + compls = Object.keys(cmd._cmdsByName) + # Complete on required opts without '-' in last partial word + # (if required not already specified) + # + # Commented out because of uselessness: + # -b, --block suggest results in '-' on cmd line; + # next completion suggest all options, because of '-' + #.concat Object.keys(cmd._optsByKey).filter (v) -> cmd._optsByKey[v]._req + else + # complete on opt values: --opt=| case + if m = opts.partialWord.match /^(--\w[\w-_]*)=(.*)$/ + optWord = m[1] + optPrefix = optWord + '=' + else + # complete on opts + # don't complete on opts in case of --opt=val completion + # TODO: don't complete on opts in case of unknown arg after commands + # TODO: complete only on opts with arr() or not already used + # TODO: complete only on full opts? + compls = Object.keys cmd._optsByKey + + # complete on opt values: next arg case + if not (o = opts.partialWords[opts.w - 1]).indexOf '-' + optWord = o + + # complete on opt values: completion + if optWord and opt = cmd._optsByKey[optWord] + if not opt._flag and opt._comp + compls = Q.join compls, Q.when opt._comp(opts), (c, o) -> + c.concat o.map (v) -> (optPrefix or '') + v + + # TODO: complete on args values (context aware, custom completion?) + + # custom completion on cmds + if cmd._comp + compls = Q.join compls, Q.when(cmd._comp(opts)), (c, o) -> + c.concat o + + # TODO: context aware custom completion on cmds, opts and args + # (can depend on already entered values, especially options) + + Q.when compls, (compls) -> + console.error 'partialWord: %s', opts.partialWord + console.error 'compls: %j', compls + compls.filter (c) -> c.indexOf(opts.partialWord) is 0 diff --git a/node_modules/coa/src/index.coffee b/node_modules/coa/src/index.coffee new file mode 100644 index 00000000..ae594be3 --- /dev/null +++ b/node_modules/coa/src/index.coffee @@ -0,0 +1,5 @@ +exports.Cmd = require('./cmd').Cmd +exports.Opt = require('./cmd').Opt +exports.Arg = require('./cmd').Arg +exports.shell = require('./shell') +exports.require = require; diff --git a/node_modules/coa/src/opt.coffee b/node_modules/coa/src/opt.coffee new file mode 100644 index 00000000..466383df --- /dev/null +++ b/node_modules/coa/src/opt.coffee @@ -0,0 +1,243 @@ +fs = require 'fs' +Q = require 'q' +Color = require('./color').Color +Cmd = require('./cmd').Cmd + +###* +Option + +Named entity. Options may have short and long keys for use from command line. +@namespace +@class Presents option +### +exports.Opt = class Opt + + ###* + @constructs + @param {COA.Cmd} cmd parent command + ### + constructor: (@_cmd) -> @_cmd._opts.push @ + + ###* + Set a canonical option identifier to be used anywhere in the API. + @param {String} _name option name + @returns {COA.Opt} this instance (for chainability) + ### + name: (@_name) -> @ + + ###* + Set a long description for option to be used anywhere in text messages. + @param {String} _title option title + @returns {COA.Opt} this instance (for chainability) + ### + title: Cmd::title + + ###* + Set a short key for option to be used with one hyphen from command line. + @param {String} _short + @returns {COA.Opt} this instance (for chainability) + ### + short: (@_short) -> @_cmd._optsByKey['-' + _short] = @ + + ###* + Set a short key for option to be used with double hyphens from command line. + @param {String} _long + @returns {COA.Opt} this instance (for chainability) + ### + long: (@_long) -> @_cmd._optsByKey['--' + _long] = @ + + ###* + Make an option boolean, i.e. option without value. + @returns {COA.Opt} this instance (for chainability) + ### + flag: () -> + @_flag = true + @ + + ###* + Makes an option accepts multiple values. + Otherwise, the value will be used by the latter passed. + @returns {COA.Opt} this instance (for chainability) + ### + arr: -> + @_arr = true + @ + + ###* + Makes an option required. + @returns {COA.Opt} this instance (for chainability) + ### + req: -> + @_req = true + @ + + ###* + Makes an option to act as a command, + i.e. program will exit just after option action. + @returns {COA.Opt} this instance (for chainability) + ### + only: -> + @_only = true + @ + + ###* + Set a validation (or value) function for option. + Value from command line passes through before becoming available from API. + Using for validation and convertion simple types to any values. + @param {Function} _val validating function, + invoked in the context of option instance + and has one parameter with value from command line + @returns {COA.Opt} this instance (for chainability) + ### + val: (@_val) -> @ + + ###* + Set a default value for option. + Default value passed through validation function as ordinary value. + @param {Object} _def + @returns {COA.Opt} this instance (for chainability) + ### + def: (@_def) -> @ + + ###* + Make option value inputting stream. + It's add useful validation and shortcut for STDIN. + @returns {COA.Opt} this instance (for chainability) + ### + input: -> + # XXX: hack to workaround a bug in node 0.6.x, + # see https://github.com/joyent/node/issues/2130 + process.stdin.pause(); + + @ + .def(process.stdin) + .val (v) -> + if typeof v is 'string' + if v is '-' + process.stdin + else + s = fs.createReadStream v, { encoding: 'utf8' } + s.pause() + s + else v + + ###* + Make option value outputing stream. + It's add useful validation and shortcut for STDOUT. + @returns {COA.Opt} this instance (for chainability) + ### + output: -> + @ + .def(process.stdout) + .val (v) -> + if typeof v is 'string' + if v is '-' + process.stdout + else + fs.createWriteStream v, { encoding: 'utf8' } + else v + + ###* + Add action for current option command. + This action is performed if the current option + is present in parsed options (with any value). + @param {Function} act action function, + invoked in the context of command instance + and has the parameters: + - {Object} opts parsed options + - {Array} args parsed arguments + - {Object} res actions result accumulator + It can return rejected promise by Cmd.reject (in case of error) + or any other value treated as result. + @returns {COA.Opt} this instance (for chainability) + ### + act: (act) -> + opt = @ + name = @_name + @_cmd.act (opts) -> + if name of opts + res = act.apply @, arguments + if opt._only + Q.when res, (res) => + @reject { + toString: -> res.toString() + exitCode: 0 + } + else + res + @ + + ###* + Set custom additional completion for current option. + @param {Function} completion generation function, + invoked in the context of option instance. + Accepts parameters: + - {Object} opts completion options + It can return promise or any other value treated as result. + @returns {COA.Opt} this instance (for chainability) + ### + comp: Cmd::comp + + _saveVal: (opts, val) -> + if @_val then val = @_val val + if @_arr + (opts[@_name] or= []).push val + else + opts[@_name] = val + val + + _parse: (argv, opts) -> + @_saveVal( + opts, + if @_flag + true + else + argv.shift() + ) + + _checkParsed: (opts, args) -> not opts.hasOwnProperty @_name + + _usage: -> + res = [] + nameStr = @_name.toUpperCase() + + if @_short + res.push '-', Color 'lgreen', @_short + unless @_flag then res.push ' ' + nameStr + res.push ', ' + + if @_long + res.push '--', Color 'green', @_long + unless @_flag then res.push '=' + nameStr + + res.push ' : ', @_title + + if @_req then res.push ' ', Color('lred', '(required)') + + res.join '' + + _requiredText: -> 'Missing required option:\n ' + @_usage() + + ###* + Return rejected promise with error code. + Use in .val() for return with error. + @param {Object} reject reason + You can customize toString() method and exitCode property + of reason object. + @returns {Q.promise} rejected promise + ### + reject: Cmd::reject + + ###* + Finish chain for current option and return parent command instance. + @returns {COA.Cmd} parent command + ### + end: Cmd::end + + ###* + Apply function with arguments in context of option instance. + @param {Function} fn + @param {Array} args + @returns {COA.Opt} this instance (for chainability) + ### + apply: Cmd::apply diff --git a/node_modules/coa/src/shell.coffee b/node_modules/coa/src/shell.coffee new file mode 100644 index 00000000..efad108d --- /dev/null +++ b/node_modules/coa/src/shell.coffee @@ -0,0 +1,10 @@ +exports.unescape = (w) -> + w = if w.charAt(0) is '"' + w.replace(/^"|([^\\])"$/g, '$1') + else + w.replace(/\\ /g, ' ') + w.replace(/\\("|'|\$|`|\\)/g, '$1') + +exports.escape = (w) -> + w = w.replace(/(["'$`\\])/g,'\\$1') + if w.match(/\s+/) then '"' + w + '"' else w diff --git a/node_modules/coa/test/coa.js b/node_modules/coa/test/coa.js new file mode 100644 index 00000000..4277321a --- /dev/null +++ b/node_modules/coa/test/coa.js @@ -0,0 +1,496 @@ +var assert = require('chai').assert, + COA = require('..'); + +/** + * Mocha BDD interface. + */ +/** @name describe @function */ +/** @name it @function */ +/** @name before @function */ +/** @name after @function */ +/** @name beforeEach @function */ +/** @name afterEach @function */ + +describe('Opt', function() { + + describe('Unknown option', function() { + + var cmd = COA.Cmd(); + + it('should fail', function() { + return cmd.do(['-a']) + .then(assert.fail, emptyFn); + }); + + }); + + describe('Short options', function() { + + var cmd = COA.Cmd() + .opt() + .name('a') + .short('a') + .end() + .opt() + .name('b') + .short('b') + .end() + .act(function(opts) { + return opts; + }); + + it('should return passed values', function() { + return cmd.do(['-a', 'a', '-b', 'b']) + .then(function(res) { + assert.deepEqual(res, { a: 'a', b: 'b' }); + }); + }); + + }); + + describe('Long options', function() { + + var cmd = COA.Cmd() + .opt() + .name('long1') + .long('long1') + .end() + .opt() + .name('long2') + .long('long2') + .end() + .act(function(opts) { + return opts; + }); + + it('should return passed values', function() { + return cmd.do(['--long1', 'long value', '--long2=another long value']) + .then(function(res) { + assert.deepEqual(res, { long1: 'long value', long2: 'another long value' }); + }); + }); + + }); + + describe('Array option', function() { + + var cmd = COA.Cmd() + .opt() + .name('a') + .short('a') + .arr() + .end() + .act(function(opts) { + return opts; + }); + + it('should return array of passed values', function() { + return cmd.do(['-a', '1', '-a', '2']) + .then(function(res) { + assert.deepEqual(res, { a: ['1', '2'] }); + }); + }); + + }); + + describe('Required option', function() { + + var cmd = COA.Cmd() + .opt() + .name('a') + .short('a') + .req() + .end() + .act(function(opts) { + return opts; + }); + + it('should fail if not specified', function() { + return cmd.do() + .then(assert.fail, emptyFn); + }); + + it('should return passed value if specified', function() { + return cmd.do(['-a', 'test']) + .then(function(opts) { + assert.equal(opts.a, 'test'); + }); + }); + + }); + + describe('Option with default value', function() { + + var cmd = COA.Cmd() + .opt() + .name('a') + .short('a') + .def('aaa') + .end() + .act(function(opts) { + return opts; + }); + + it('should return default value if not specified', function() { + return cmd.do() + .then(function(opts) { + assert.equal(opts.a, 'aaa'); + }); + }); + + it('should return passed value if specified', function() { + return cmd.do(['-a', 'test']) + .then(function(opts) { + assert.equal(opts.a, 'test'); + }); + }); + + }); + + describe('Validated / transformed option', function() { + + var cmd = COA.Cmd() + .opt() + .name('a') + .short('a') + .val(function(v) { + if (v === 'invalid') return this.reject('fail'); + return { value: v }; + }) + .end() + .act(function(opts) { + return opts; + }); + + it('should fail if custom checks suppose to do so', function() { + return cmd.do(['-a', 'invalid']) + .then(assert.fail, emptyFn); + }); + + it('should return transformed value', function() { + return cmd.do(['-a', 'test']) + .then(function(opts) { + assert.deepEqual(opts.a, { value: 'test' }); + }); + }); + + }); + + describe('Only option (--version case)', function() { + + var ver = require('../package.json').version, + cmd = COA.Cmd() + .opt() + .name('version') + .long('version') + .flag() + .only() + .act(function() { + return ver; + }) + .end() + .opt() + .name('req') + .short('r') + .req() + .end(); + + it('should process the only() option', function() { + return cmd.do(['--version']) + .then(assert.fail, function(res) { + assert.equal(res, ver); + }); + }); + + }); + + it('input()'); + it('output()'); + +}); + +describe('Arg', function() { + + describe('Unknown arg', function() { + + var cmd = COA.Cmd(); + + it('should fail', function() { + return cmd.do(['test']) + .then(assert.fail, emptyFn); + }); + + }); + + describe('Unknown arg after known', function() { + + var cmd = COA.Cmd() + .arg() + .name('a') + .end(); + + it('should fail', function() { + return cmd.do(['test', 'unknown']) + .then(assert.fail, emptyFn); + }); + + }); + + describe('Array arg', function() { + + var cmd = COA.Cmd() + .arg() + .name('a') + .arr() + .end() + .act(function(opts, args) { + return args; + }); + + it('should return array of passed values', function() { + return cmd.do(['value 1', 'value 2']) + .then(function(args) { + assert.deepEqual(args, { a: ['value 1', 'value 2'] }); + }); + }); + + }); + + describe('Required arg', function() { + + var cmd = COA.Cmd() + .arg() + .name('a') + .req() + .end() + .act(function(opts, args) { + return args; + }); + + it('should fail if not specified', function() { + return cmd.do() + .then(assert.fail, emptyFn); + }); + + it('should return passed value if specified', function() { + return cmd.do(['value']) + .then(function(args) { + assert.equal(args.a, 'value'); + }); + }); + + }); + + describe('Args after options', function() { + + var cmd = COA.Cmd() + .opt() + .name('opt') + .long('opt') + .end() + .arg() + .name('arg1') + .end() + .arg() + .name('arg2') + .arr() + .end() + .act(function(opts, args) { + return { opts: opts, args: args }; + }); + + it('should return passed values', function() { + return cmd.do(['--opt', 'value', 'value', 'value 1', 'value 2']) + .then(function(o) { + assert.deepEqual(o, { + opts: { opt: 'value' }, + args: { + arg1: 'value', + arg2: ['value 1', 'value 2'] + } + }); + }); + }); + + }); + + describe('Raw args', function() { + + var cmd = COA.Cmd() + .arg() + .name('raw') + .arr() + .end() + .act(function(opts, args) { + return args; + }); + + it('should return passed arg values', function() { + return cmd.do(['--', 'raw', 'arg', 'values']) + .then(function(args) { + assert.deepEqual(args, { raw: ['raw', 'arg', 'values'] }); + }); + }); + + }); + +}); + +describe('Cmd', function() { + + var doTest = function(o) { + assert.deepEqual(o, { + opts: { opt: 'value' }, + args: { + arg1: 'value', + arg2: ['value 1', 'value 2'] + } + }); + }, + + invokeOpts = { opt: 'value' }, + invokeArgs = { + arg1: 'value', + arg2: ['value 1', 'value 2'] + }; + + describe('Subcommand', function() { + + var cmd = COA.Cmd() + .cmd() + .name('command') + .opt() + .name('opt') + .long('opt') + .end() + .arg() + .name('arg1') + .end() + .arg() + .name('arg2') + .arr() + .end() + .act(function(opts, args) { + return { opts: opts, args: args }; + }) + .end(); + + describe('when specified on command line', function() { + + it('should be invoked and accept passed opts and args', function() { + return cmd.do(['command', '--opt', 'value', 'value', 'value 1', 'value 2']) + .then(doTest); + }); + + }); + + describe('when invoked using api', function() { + + it('should be invoked and accept passed opts and args', function() { + return cmd.api.command(invokeOpts, invokeArgs) + .then(doTest); + }); + + }); + + describe('when invoked using invoke()', function() { + + it('should be invoked and accept passed opts and args', function() { + return cmd.invoke('command', invokeOpts, invokeArgs) + .then(doTest); + }); + + }); + + describe('when unexisting command invoked using invoke()', function() { + + it('should fail', function() { + return cmd.invoke('unexistent') + .then(assert.fail, emptyFn); + }); + + }); + + }); + + describe('External subcommand', function() { + + describe('default scheme: cmd.extendable()', function() { + + describe('when described as a function', function() { + var cmd = COA.Cmd() + .name('coa') + .extendable(); + + it('should be invoked and accept passed opts and args', function() { + return cmd.do(['test', '--opt', 'value', 'value', 'value 1', 'value 2']) + .then(doTest); + }); + }); + + describe('when described as an COA.Cmd() object', function() { + var cmd = COA.Cmd() + .name('coa') + .extendable(); + + it('should be invoked and accept passed opts and args', function() { + return cmd.do(['test-obj', '--opt', 'value', 'value', 'value 1', 'value 2']) + .then(doTest); + }); + }); + + describe('2nd level subcommand', function() { + var cmd = COA.Cmd() + .name('coa') + .cmd() + .name('test') + .extendable() + .end(); + + it('should be invoked and accept passed opts and args', function() { + return cmd.do(['test', 'obj', '--opt', 'value', 'value', 'value 1', 'value 2']) + .then(doTest); + }); + }); + + }); + + describe("common prefix: cmd.extendable('coa-')", function() { + + describe('when described as a function', function() { + var cmd = COA.Cmd() + .name('coa') + .extendable('coa-'); + + it('should be invoked and accept passed opts and args', function() { + return cmd.do(['test', '--opt', 'value', 'value', 'value 1', 'value 2']) + .then(doTest); + }); + }); + + }); + + describe("format string: cmd.extendable('coa-%s')", function() { + + describe('when described as a function', function() { + var cmd = COA.Cmd() + .name('coa') + .extendable('coa-%s'); + + it('should be invoked and accept passed opts and args', function() { + return cmd.do(['test', '--opt', 'value', 'value', 'value 1', 'value 2']) + .then(doTest); + }); + }); + + }); + + }); + + it('helpful(), name(), title()'); + +}); + +function emptyFn() { + // empty function +} diff --git a/node_modules/coa/test/mocha.opts b/node_modules/coa/test/mocha.opts new file mode 100644 index 00000000..78e17754 --- /dev/null +++ b/node_modules/coa/test/mocha.opts @@ -0,0 +1,2 @@ +--reporter spec +--timeout 20 diff --git a/node_modules/coa/test/shell-test.js b/node_modules/coa/test/shell-test.js new file mode 100644 index 00000000..7291a53d --- /dev/null +++ b/node_modules/coa/test/shell-test.js @@ -0,0 +1,60 @@ +var assert = require('chai').assert, + shell = require('..').shell; + +/** + * Mocha BDD interface. + */ +/** @name describe @function */ +/** @name it @function */ +/** @name before @function */ +/** @name after @function */ +/** @name beforeEach @function */ +/** @name afterEach @function */ + +describe('shell', function() { + + describe('escape()', function() { + + var escape = shell.escape; + + it('Should wrap values with spaces in double quotes', function() { + assert.equal(escape('asd abc'), '"asd abc"'); + }); + + it('Should escape double quote "', function() { + assert.equal(escape('"asd'), '\\"asd'); + }); + + it("Should escape single quote '", function() { + assert.equal(escape("'asd"), "\\'asd"); + }); + + it('Should escape backslash \\', function() { + assert.equal(escape('\\asd'), '\\\\asd'); + }); + + it('Should escape dollar $', function() { + assert.equal(escape('$asd'), '\\$asd'); + }); + + it('Should escape backtick `', function() { + assert.equal(escape('`asd'), '\\`asd'); + }); + + }); + + describe('unescape()', function() { + + var unescape = shell.unescape; + + it('Should strip double quotes at the both ends', function() { + assert.equal(unescape('"asd"'), 'asd'); + }); + + it('Should not strip escaped double quotes at the both ends', function() { + assert.equal(unescape('\\"asd\\"'), '"asd"'); + }); + + }); + +}); diff --git a/node_modules/coa/tests/api-h.js b/node_modules/coa/tests/api-h.js new file mode 100644 index 00000000..c343fa06 --- /dev/null +++ b/node_modules/coa/tests/api-h.js @@ -0,0 +1,9 @@ +require('..').Cmd() + .name('bla') + .title('Bla bla bla') + .helpful() + .invoke({ help: true }) + .then(function(res) { + console.log(res); + }) + .done(); // Q.done() diff --git a/node_modules/coa/tests/h.js b/node_modules/coa/tests/h.js new file mode 100644 index 00000000..b8e2c768 --- /dev/null +++ b/node_modules/coa/tests/h.js @@ -0,0 +1,6 @@ +var argv = process.argv.slice(2); +require('..').Cmd() + .name('bla') + .title('Bla bla bla') + .helpful() + .run(argv.length? argv : ['-h']); diff --git a/node_modules/colors/LICENSE b/node_modules/colors/LICENSE new file mode 100644 index 00000000..3de4e33b --- /dev/null +++ b/node_modules/colors/LICENSE @@ -0,0 +1,23 @@ +Original Library + - Copyright (c) Marak Squires + +Additional Functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/colors/ReadMe.md b/node_modules/colors/ReadMe.md new file mode 100644 index 00000000..0326aab3 --- /dev/null +++ b/node_modules/colors/ReadMe.md @@ -0,0 +1,178 @@ +# colors.js [![Build Status](https://travis-ci.org/Marak/colors.js.svg?branch=master)](https://travis-ci.org/Marak/colors.js) + +## get color and style in your node.js console + +![Demo](https://raw.githubusercontent.com/Marak/colors.js/master/screenshots/colors.png) + +## Installation + + npm install colors + +## colors and styles! + +### text colors + + - black + - red + - green + - yellow + - blue + - magenta + - cyan + - white + - gray + - grey + +### background colors + + - bgBlack + - bgRed + - bgGreen + - bgYellow + - bgBlue + - bgMagenta + - bgCyan + - bgWhite + +### styles + + - reset + - bold + - dim + - italic + - underline + - inverse + - hidden + - strikethrough + +### extras + + - rainbow + - zebra + - america + - trap + - random + + +## Usage + +By popular demand, `colors` now ships with two types of usages! + +The super nifty way + +```js +var colors = require('colors'); + +console.log('hello'.green); // outputs green text +console.log('i like cake and pies'.underline.red) // outputs red underlined text +console.log('inverse the color'.inverse); // inverses the color +console.log('OMG Rainbows!'.rainbow); // rainbow +console.log('Run the trap'.trap); // Drops the bass + +``` + +or a slightly less nifty way which doesn't extend `String.prototype` + +```js +var colors = require('colors/safe'); + +console.log(colors.green('hello')); // outputs green text +console.log(colors.red.underline('i like cake and pies')) // outputs red underlined text +console.log(colors.inverse('inverse the color')); // inverses the color +console.log(colors.rainbow('OMG Rainbows!')); // rainbow +console.log(colors.trap('Run the trap')); // Drops the bass + +``` + +I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way. + +If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object. + +## Disabling Colors + +To disable colors you can pass the following arguments in the command line to your application: + +```bash +node myapp.js --no-color +``` + +## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data) + +```js +var name = 'Marak'; +console.log(colors.green('Hello %s'), name); +// outputs -> 'Hello Marak' +``` + +## Custom themes + +### Using standard API + +```js + +var colors = require('colors'); + +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); +``` + +### Using string safe API + +```js +var colors = require('colors/safe'); + +// set single property +var error = colors.red; +error('this is red'); + +// set theme +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); + +``` + +You can also combine them: + +```javascript +var colors = require('colors'); + +colors.setTheme({ + custom: ['red', 'underline'] +}); + +console.log('test'.custom); +``` + +*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.* diff --git a/node_modules/colors/examples/normal-usage.js b/node_modules/colors/examples/normal-usage.js new file mode 100644 index 00000000..2818741e --- /dev/null +++ b/node_modules/colors/examples/normal-usage.js @@ -0,0 +1,74 @@ +var colors = require('../lib/index'); + +console.log("First some yellow text".yellow); + +console.log("Underline that text".yellow.underline); + +console.log("Make it bold and red".red.bold); + +console.log(("Double Raindows All Day Long").rainbow) + +console.log("Drop the bass".trap) + +console.log("DROP THE RAINBOW BASS".trap.rainbow) + + +console.log('Chains are also cool.'.bold.italic.underline.red); // styles not widely supported + +console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse + ' styles! '.yellow.bold); // styles not widely supported +console.log("Zebras are so fun!".zebra); + +// +// Remark: .strikethrough may not work with Mac OS Terminal App +// +console.log("This is " + "not".strikethrough + " fun."); + +console.log('Background color attack!'.black.bgWhite) +console.log('Use random styles on everything!'.random) +console.log('America, Heck Yeah!'.america) + + +console.log('Setting themes is useful') + +// +// Custom themes +// +console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); + +// outputs grey text +console.log("this is an input".input); + +console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +colors.setTheme(__dirname + '/../themes/generic-logging.js'); + +// outputs red text +console.log("this is an error".error); + +// outputs yellow text +console.log("this is a warning".warn); + +// outputs grey text +console.log("this is an input".input); + +//console.log("Don't summon".zalgo) \ No newline at end of file diff --git a/node_modules/colors/examples/safe-string.js b/node_modules/colors/examples/safe-string.js new file mode 100644 index 00000000..111b363a --- /dev/null +++ b/node_modules/colors/examples/safe-string.js @@ -0,0 +1,76 @@ +var colors = require('../safe'); + +console.log(colors.yellow("First some yellow text")); + +console.log(colors.yellow.underline("Underline that text")); + +console.log(colors.red.bold("Make it bold and red")); + +console.log(colors.rainbow("Double Raindows All Day Long")) + +console.log(colors.trap("Drop the bass")) + +console.log(colors.rainbow(colors.trap("DROP THE RAINBOW BASS"))); + +console.log(colors.bold.italic.underline.red('Chains are also cool.')); // styles not widely supported + + +console.log(colors.green('So ') + colors.underline('are') + ' ' + colors.inverse('inverse') + colors.yellow.bold(' styles! ')); // styles not widely supported + +console.log(colors.zebra("Zebras are so fun!")); + +console.log("This is " + colors.strikethrough("not") + " fun."); + + +console.log(colors.black.bgWhite('Background color attack!')); +console.log(colors.random('Use random styles on everything!')) +console.log(colors.america('America, Heck Yeah!')); + +console.log('Setting themes is useful') + +// +// Custom themes +// +//console.log('Generic logging theme as JSON'.green.bold.underline); +// Load theme with JSON literal +colors.setTheme({ + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); + +// outputs grey text +console.log(colors.input("this is an input")); + + +// console.log('Generic logging theme as file'.green.bold.underline); + +// Load a theme from file +colors.setTheme(__dirname + '/../themes/generic-logging.js'); + +// outputs red text +console.log(colors.error("this is an error")); + +// outputs yellow text +console.log(colors.warn("this is a warning")); + +// outputs grey text +console.log(colors.input("this is an input")); + +// console.log(colors.zalgo("Don't summon him")) + + + diff --git a/node_modules/colors/lib/colors.js b/node_modules/colors/lib/colors.js new file mode 100644 index 00000000..790ffd43 --- /dev/null +++ b/node_modules/colors/lib/colors.js @@ -0,0 +1,187 @@ +/* + +The MIT License (MIT) + +Original Library + - Copyright (c) Marak Squires + +Additional functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var colors = {}; +module['exports'] = colors; + +colors.themes = {}; + +var ansiStyles = colors.styles = require('./styles'); +var defineProps = Object.defineProperties; + +colors.supportsColor = require('./system/supports-colors'); + +if (typeof colors.enabled === "undefined") { + colors.enabled = colors.supportsColor; +} + +colors.stripColors = colors.strip = function(str){ + return ("" + str).replace(/\x1B\[\d+m/g, ''); +}; + + +var stylize = colors.stylize = function stylize (str, style) { + if (!colors.enabled) { + return str+''; + } + + return ansiStyles[style].open + str + ansiStyles[style].close; +} + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +var escapeStringRegexp = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +} + +function build(_styles) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + builder.__proto__ = proto; + return builder; +} + +var styles = (function () { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function (key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + ret[key] = { + get: function () { + return build(this._styles.concat(key)); + } + }; + }); + return ret; +})(); + +var proto = defineProps(function colors() {}, styles); + +function applyStyle() { + var args = arguments; + var argsLen = args.length; + var str = argsLen !== 0 && String(arguments[0]); + if (argsLen > 1) { + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!colors.enabled || !str) { + return str; + } + + var nestedStyles = this._styles; + + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + } + + return str; +} + +function applyTheme (theme) { + for (var style in theme) { + (function(style){ + colors[style] = function(str){ + if (typeof theme[style] === 'object'){ + var out = str; + for (var i in theme[style]){ + out = colors[theme[style][i]](out); + } + return out; + } + return colors[theme[style]](str); + }; + })(style) + } +} + +colors.setTheme = function (theme) { + if (typeof theme === 'string') { + try { + colors.themes[theme] = require(theme); + applyTheme(colors.themes[theme]); + return colors.themes[theme]; + } catch (err) { + console.log(err); + return err; + } + } else { + applyTheme(theme); + } +}; + +function init() { + var ret = {}; + Object.keys(styles).forEach(function (name) { + ret[name] = { + get: function () { + return build([name]); + } + }; + }); + return ret; +} + +var sequencer = function sequencer (map, str) { + var exploded = str.split(""), i = 0; + exploded = exploded.map(map); + return exploded.join(""); +}; + +// custom formatter methods +colors.trap = require('./custom/trap'); +colors.zalgo = require('./custom/zalgo'); + +// maps +colors.maps = {}; +colors.maps.america = require('./maps/america'); +colors.maps.zebra = require('./maps/zebra'); +colors.maps.rainbow = require('./maps/rainbow'); +colors.maps.random = require('./maps/random') + +for (var map in colors.maps) { + (function(map){ + colors[map] = function (str) { + return sequencer(colors.maps[map], str); + } + })(map) +} + +defineProps(colors, init()); \ No newline at end of file diff --git a/node_modules/colors/lib/custom/trap.js b/node_modules/colors/lib/custom/trap.js new file mode 100644 index 00000000..3f091437 --- /dev/null +++ b/node_modules/colors/lib/custom/trap.js @@ -0,0 +1,45 @@ +module['exports'] = function runTheTrap (text, options) { + var result = ""; + text = text || "Run the trap, drop the bass"; + text = text.split(''); + var trap = { + a: ["\u0040", "\u0104", "\u023a", "\u0245", "\u0394", "\u039b", "\u0414"], + b: ["\u00df", "\u0181", "\u0243", "\u026e", "\u03b2", "\u0e3f"], + c: ["\u00a9", "\u023b", "\u03fe"], + d: ["\u00d0", "\u018a", "\u0500" , "\u0501" ,"\u0502", "\u0503"], + e: ["\u00cb", "\u0115", "\u018e", "\u0258", "\u03a3", "\u03be", "\u04bc", "\u0a6c"], + f: ["\u04fa"], + g: ["\u0262"], + h: ["\u0126", "\u0195", "\u04a2", "\u04ba", "\u04c7", "\u050a"], + i: ["\u0f0f"], + j: ["\u0134"], + k: ["\u0138", "\u04a0", "\u04c3", "\u051e"], + l: ["\u0139"], + m: ["\u028d", "\u04cd", "\u04ce", "\u0520", "\u0521", "\u0d69"], + n: ["\u00d1", "\u014b", "\u019d", "\u0376", "\u03a0", "\u048a"], + o: ["\u00d8", "\u00f5", "\u00f8", "\u01fe", "\u0298", "\u047a", "\u05dd", "\u06dd", "\u0e4f"], + p: ["\u01f7", "\u048e"], + q: ["\u09cd"], + r: ["\u00ae", "\u01a6", "\u0210", "\u024c", "\u0280", "\u042f"], + s: ["\u00a7", "\u03de", "\u03df", "\u03e8"], + t: ["\u0141", "\u0166", "\u0373"], + u: ["\u01b1", "\u054d"], + v: ["\u05d8"], + w: ["\u0428", "\u0460", "\u047c", "\u0d70"], + x: ["\u04b2", "\u04fe", "\u04fc", "\u04fd"], + y: ["\u00a5", "\u04b0", "\u04cb"], + z: ["\u01b5", "\u0240"] + } + text.forEach(function(c){ + c = c.toLowerCase(); + var chars = trap[c] || [" "]; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap[c] !== "undefined") { + result += trap[c][rand]; + } else { + result += c; + } + }); + return result; + +} diff --git a/node_modules/colors/lib/custom/zalgo.js b/node_modules/colors/lib/custom/zalgo.js new file mode 100644 index 00000000..1538c3b4 --- /dev/null +++ b/node_modules/colors/lib/custom/zalgo.js @@ -0,0 +1,104 @@ +// please no +module['exports'] = function zalgo(text, options) { + text = text || " he is here "; + var soul = { + "up" : [ + '̍', '̎', '̄', '̅', + '̿', '̑', '̆', '̐', + '͒', '͗', '͑', '̇', + '̈', '̊', '͂', '̓', + '̈', '͊', '͋', '͌', + '̃', '̂', '̌', '͐', + '̀', '́', '̋', '̏', + '̒', '̓', '̔', '̽', + '̉', 'ͣ', 'ͤ', 'ͥ', + 'ͦ', 'ͧ', 'ͨ', 'ͩ', + 'ͪ', 'ͫ', 'ͬ', 'ͭ', + 'ͮ', 'ͯ', '̾', '͛', + '͆', '̚' + ], + "down" : [ + '̖', '̗', '̘', '̙', + '̜', '̝', '̞', '̟', + '̠', '̤', '̥', '̦', + '̩', '̪', '̫', '̬', + '̭', '̮', '̯', '̰', + '̱', '̲', '̳', '̹', + '̺', '̻', '̼', 'ͅ', + '͇', '͈', '͉', '͍', + '͎', '͓', '͔', '͕', + '͖', '͙', '͚', '̣' + ], + "mid" : [ + '̕', '̛', '̀', '́', + '͘', '̡', '̢', '̧', + '̨', '̴', '̵', '̶', + '͜', '͝', '͞', + '͟', '͠', '͢', '̸', + '̷', '͡', ' ҉' + ] + }, + all = [].concat(soul.up, soul.down, soul.mid), + zalgo = {}; + + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } + + function is_char(character) { + var bool = false; + all.filter(function (i) { + bool = (i === character); + }); + return bool; + } + + + function heComes(text, options) { + var result = '', counts, l; + options = options || {}; + options["up"] = typeof options["up"] !== 'undefined' ? options["up"] : true; + options["mid"] = typeof options["mid"] !== 'undefined' ? options["mid"] : true; + options["down"] = typeof options["down"] !== 'undefined' ? options["down"] : true; + options["size"] = typeof options["size"] !== 'undefined' ? options["size"] : "maxi"; + text = text.split(''); + for (l in text) { + if (is_char(l)) { + continue; + } + result = result + text[l]; + counts = {"up" : 0, "down" : 0, "mid" : 0}; + switch (options.size) { + case 'mini': + counts.up = randomNumber(8); + counts.mid = randomNumber(2); + counts.down = randomNumber(8); + break; + case 'maxi': + counts.up = randomNumber(16) + 3; + counts.mid = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } + + var arr = ["up", "mid", "down"]; + for (var d in arr) { + var index = arr[d]; + for (var i = 0 ; i <= counts[index]; i++) { + if (options[index]) { + result = result + soul[index][randomNumber(soul[index].length)]; + } + } + } + } + return result; + } + // don't summon him + return heComes(text, options); +} diff --git a/node_modules/colors/lib/extendStringPrototype.js b/node_modules/colors/lib/extendStringPrototype.js new file mode 100644 index 00000000..67374a1c --- /dev/null +++ b/node_modules/colors/lib/extendStringPrototype.js @@ -0,0 +1,113 @@ +var colors = require('./colors'); + +module['exports'] = function () { + + // + // Extends prototype of native string object to allow for "foo".red syntax + // + var addProperty = function (color, func) { + String.prototype.__defineGetter__(color, func); + }; + + var sequencer = function sequencer (map, str) { + return function () { + var exploded = this.split(""), i = 0; + exploded = exploded.map(map); + return exploded.join(""); + } + }; + + addProperty('strip', function () { + return colors.strip(this); + }); + + addProperty('stripColors', function () { + return colors.strip(this); + }); + + addProperty("trap", function(){ + return colors.trap(this); + }); + + addProperty("zalgo", function(){ + return colors.zalgo(this); + }); + + addProperty("zebra", function(){ + return colors.zebra(this); + }); + + addProperty("rainbow", function(){ + return colors.rainbow(this); + }); + + addProperty("random", function(){ + return colors.random(this); + }); + + addProperty("america", function(){ + return colors.america(this); + }); + + // + // Iterate through all default styles and colors + // + var x = Object.keys(colors.styles); + x.forEach(function (style) { + addProperty(style, function () { + return colors.stylize(this, style); + }); + }); + + function applyTheme(theme) { + // + // Remark: This is a list of methods that exist + // on String that you should not overwrite. + // + var stringPrototypeBlacklist = [ + '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'charAt', 'constructor', + 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', 'charCodeAt', + 'indexOf', 'lastIndexof', 'length', 'localeCompare', 'match', 'replace', 'search', 'slice', 'split', 'substring', + 'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight' + ]; + + Object.keys(theme).forEach(function (prop) { + if (stringPrototypeBlacklist.indexOf(prop) !== -1) { + console.log('warn: '.red + ('String.prototype' + prop).magenta + ' is probably something you don\'t want to override. Ignoring style name'); + } + else { + if (typeof(theme[prop]) === 'string') { + colors[prop] = colors[theme[prop]]; + addProperty(prop, function () { + return colors[theme[prop]](this); + }); + } + else { + addProperty(prop, function () { + var ret = this; + for (var t = 0; t < theme[prop].length; t++) { + ret = colors[theme[prop][t]](ret); + } + return ret; + }); + } + } + }); + } + + colors.setTheme = function (theme) { + if (typeof theme === 'string') { + try { + colors.themes[theme] = require(theme); + applyTheme(colors.themes[theme]); + return colors.themes[theme]; + } catch (err) { + console.log(err); + return err; + } + } else { + applyTheme(theme); + } + }; + +}; \ No newline at end of file diff --git a/node_modules/colors/lib/index.js b/node_modules/colors/lib/index.js new file mode 100644 index 00000000..fd0956d0 --- /dev/null +++ b/node_modules/colors/lib/index.js @@ -0,0 +1,12 @@ +var colors = require('./colors'); +module['exports'] = colors; + +// Remark: By default, colors will add style properties to String.prototype +// +// If you don't wish to extend String.prototype you can do this instead and native String will not be touched +// +// var colors = require('colors/safe); +// colors.red("foo") +// +// +require('./extendStringPrototype')(); \ No newline at end of file diff --git a/node_modules/colors/lib/maps/america.js b/node_modules/colors/lib/maps/america.js new file mode 100644 index 00000000..a07d8327 --- /dev/null +++ b/node_modules/colors/lib/maps/america.js @@ -0,0 +1,12 @@ +var colors = require('../colors'); + +module['exports'] = (function() { + return function (letter, i, exploded) { + if(letter === " ") return letter; + switch(i%3) { + case 0: return colors.red(letter); + case 1: return colors.white(letter) + case 2: return colors.blue(letter) + } + } +})(); \ No newline at end of file diff --git a/node_modules/colors/lib/maps/rainbow.js b/node_modules/colors/lib/maps/rainbow.js new file mode 100644 index 00000000..a7ce24e6 --- /dev/null +++ b/node_modules/colors/lib/maps/rainbow.js @@ -0,0 +1,13 @@ +var colors = require('../colors'); + +module['exports'] = (function () { + var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV + return function (letter, i, exploded) { + if (letter === " ") { + return letter; + } else { + return colors[rainbowColors[i++ % rainbowColors.length]](letter); + } + }; +})(); + diff --git a/node_modules/colors/lib/maps/random.js b/node_modules/colors/lib/maps/random.js new file mode 100644 index 00000000..5cd101fa --- /dev/null +++ b/node_modules/colors/lib/maps/random.js @@ -0,0 +1,8 @@ +var colors = require('../colors'); + +module['exports'] = (function () { + var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta']; + return function(letter, i, exploded) { + return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 1))]](letter); + }; +})(); \ No newline at end of file diff --git a/node_modules/colors/lib/maps/zebra.js b/node_modules/colors/lib/maps/zebra.js new file mode 100644 index 00000000..bf7dcdea --- /dev/null +++ b/node_modules/colors/lib/maps/zebra.js @@ -0,0 +1,5 @@ +var colors = require('../colors'); + +module['exports'] = function (letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); +}; \ No newline at end of file diff --git a/node_modules/colors/lib/styles.js b/node_modules/colors/lib/styles.js new file mode 100644 index 00000000..067d5907 --- /dev/null +++ b/node_modules/colors/lib/styles.js @@ -0,0 +1,77 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var styles = {}; +module['exports'] = styles; + +var codes = { + reset: [0, 0], + + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], + + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49] + +}; + +Object.keys(codes).forEach(function (key) { + var val = codes[key]; + var style = styles[key] = []; + style.open = '\u001b[' + val[0] + 'm'; + style.close = '\u001b[' + val[1] + 'm'; +}); \ No newline at end of file diff --git a/node_modules/colors/lib/system/supports-colors.js b/node_modules/colors/lib/system/supports-colors.js new file mode 100644 index 00000000..3e008aa9 --- /dev/null +++ b/node_modules/colors/lib/system/supports-colors.js @@ -0,0 +1,61 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var argv = process.argv; + +module.exports = (function () { + if (argv.indexOf('--no-color') !== -1 || + argv.indexOf('--color=false') !== -1) { + return false; + } + + if (argv.indexOf('--color') !== -1 || + argv.indexOf('--color=true') !== -1 || + argv.indexOf('--color=always') !== -1) { + return true; + } + + if (process.stdout && !process.stdout.isTTY) { + return false; + } + + if (process.platform === 'win32') { + return true; + } + + if ('COLORTERM' in process.env) { + return true; + } + + if (process.env.TERM === 'dumb') { + return false; + } + + if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { + return true; + } + + return false; +})(); \ No newline at end of file diff --git a/node_modules/colors/package.json b/node_modules/colors/package.json new file mode 100644 index 00000000..c3650644 --- /dev/null +++ b/node_modules/colors/package.json @@ -0,0 +1,28 @@ +{ + "name": "colors", + "description": "get colors in your node.js console", + "version": "1.1.2", + "author": "Marak Squires", + "homepage": "https://github.com/Marak/colors.js", + "bugs": "https://github.com/Marak/colors.js/issues", + "keywords": [ "ansi", "terminal", "colors" ], + "repository": { + "type": "git", + "url": "http://github.com/Marak/colors.js.git" + }, + "license": "MIT", + "scripts": { + "test": "node tests/basic-test.js && node tests/safe-test.js" + }, + "engines": { + "node": ">=0.1.90" + }, + "main": "lib", + "files": [ + "examples", + "lib", + "LICENSE", + "safe.js", + "themes" + ] +} diff --git a/node_modules/colors/safe.js b/node_modules/colors/safe.js new file mode 100644 index 00000000..a6a1f3ab --- /dev/null +++ b/node_modules/colors/safe.js @@ -0,0 +1,9 @@ +// +// Remark: Requiring this file will use the "safe" colors API which will not touch String.prototype +// +// var colors = require('colors/safe); +// colors.red("foo") +// +// +var colors = require('./lib/colors'); +module['exports'] = colors; \ No newline at end of file diff --git a/node_modules/colors/themes/generic-logging.js b/node_modules/colors/themes/generic-logging.js new file mode 100644 index 00000000..571972c1 --- /dev/null +++ b/node_modules/colors/themes/generic-logging.js @@ -0,0 +1,12 @@ +module['exports'] = { + silly: 'rainbow', + input: 'grey', + verbose: 'cyan', + prompt: 'grey', + info: 'green', + data: 'grey', + help: 'cyan', + warn: 'yellow', + debug: 'blue', + error: 'red' +}; \ No newline at end of file diff --git a/node_modules/config-chain/LICENCE b/node_modules/config-chain/LICENCE deleted file mode 100644 index 171dd970..00000000 --- a/node_modules/config-chain/LICENCE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2011 Dominic Tarr - -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. \ No newline at end of file diff --git a/node_modules/config-chain/index.js b/node_modules/config-chain/index.js deleted file mode 100755 index 0ef3a91f..00000000 --- a/node_modules/config-chain/index.js +++ /dev/null @@ -1,282 +0,0 @@ -var ProtoList = require('proto-list') - , path = require('path') - , fs = require('fs') - , ini = require('ini') - , EE = require('events').EventEmitter - , url = require('url') - , http = require('http') - -var exports = module.exports = function () { - var args = [].slice.call(arguments) - , conf = new ConfigChain() - - while(args.length) { - var a = args.shift() - if(a) conf.push - ( 'string' === typeof a - ? json(a) - : a ) - } - - return conf -} - -//recursively find a file... - -var find = exports.find = function () { - var rel = path.join.apply(null, [].slice.call(arguments)) - - function find(start, rel) { - var file = path.join(start, rel) - try { - fs.statSync(file) - return file - } catch (err) { - if(path.dirname(start) !== start) // root - return find(path.dirname(start), rel) - } - } - return find(__dirname, rel) -} - -var parse = exports.parse = function (content, file, type) { - content = '' + content - // if we don't know what it is, try json and fall back to ini - // if we know what it is, then it must be that. - if (!type) { - try { return JSON.parse(content) } - catch (er) { return ini.parse(content) } - } else if (type === 'json') { - if (this.emit) { - try { return JSON.parse(content) } - catch (er) { this.emit('error', er) } - } else { - return JSON.parse(content) - } - } else { - return ini.parse(content) - } -} - -var json = exports.json = function () { - var args = [].slice.call(arguments).filter(function (arg) { return arg != null }) - var file = path.join.apply(null, args) - var content - try { - content = fs.readFileSync(file,'utf-8') - } catch (err) { - return - } - return parse(content, file, 'json') -} - -var env = exports.env = function (prefix, env) { - env = env || process.env - var obj = {} - var l = prefix.length - for(var k in env) { - if(k.indexOf(prefix) === 0) - obj[k.substring(l)] = env[k] - } - - return obj -} - -exports.ConfigChain = ConfigChain -function ConfigChain () { - EE.apply(this) - ProtoList.apply(this, arguments) - this._awaiting = 0 - this._saving = 0 - this.sources = {} -} - -// multi-inheritance-ish -var extras = { - constructor: { value: ConfigChain } -} -Object.keys(EE.prototype).forEach(function (k) { - extras[k] = Object.getOwnPropertyDescriptor(EE.prototype, k) -}) -ConfigChain.prototype = Object.create(ProtoList.prototype, extras) - -ConfigChain.prototype.del = function (key, where) { - // if not specified where, then delete from the whole chain, scorched - // earth style - if (where) { - var target = this.sources[where] - target = target && target.data - if (!target) { - return this.emit('error', new Error('not found '+where)) - } - delete target[key] - } else { - for (var i = 0, l = this.list.length; i < l; i ++) { - delete this.list[i][key] - } - } - return this -} - -ConfigChain.prototype.set = function (key, value, where) { - var target - - if (where) { - target = this.sources[where] - target = target && target.data - if (!target) { - return this.emit('error', new Error('not found '+where)) - } - } else { - target = this.list[0] - if (!target) { - return this.emit('error', new Error('cannot set, no confs!')) - } - } - target[key] = value - return this -} - -ConfigChain.prototype.get = function (key, where) { - if (where) { - where = this.sources[where] - if (where) where = where.data - if (where && Object.hasOwnProperty.call(where, key)) return where[key] - return undefined - } - return this.list[0][key] -} - -ConfigChain.prototype.save = function (where, type, cb) { - if (typeof type === 'function') cb = type, type = null - var target = this.sources[where] - if (!target || !(target.path || target.source) || !target.data) { - // TODO: maybe save() to a url target could be a PUT or something? - // would be easy to swap out with a reddis type thing, too - return this.emit('error', new Error('bad save target: '+where)) - } - - if (target.source) { - var pref = target.prefix || '' - Object.keys(target.data).forEach(function (k) { - target.source[pref + k] = target.data[k] - }) - return this - } - - var type = type || target.type - var data = target.data - if (target.type === 'json') { - data = JSON.stringify(data) - } else { - data = ini.stringify(data) - } - - this._saving ++ - fs.writeFile(target.path, data, 'utf8', function (er) { - this._saving -- - if (er) { - if (cb) return cb(er) - else return this.emit('error', er) - } - if (this._saving === 0) { - if (cb) cb() - this.emit('save') - } - }.bind(this)) - return this -} - -ConfigChain.prototype.addFile = function (file, type, name) { - name = name || file - var marker = {__source__:name} - this.sources[name] = { path: file, type: type } - this.push(marker) - this._await() - fs.readFile(file, 'utf8', function (er, data) { - if (er) this.emit('error', er) - this.addString(data, file, type, marker) - }.bind(this)) - return this -} - -ConfigChain.prototype.addEnv = function (prefix, env, name) { - name = name || 'env' - var data = exports.env(prefix, env) - this.sources[name] = { data: data, source: env, prefix: prefix } - return this.add(data, name) -} - -ConfigChain.prototype.addUrl = function (req, type, name) { - this._await() - var href = url.format(req) - name = name || href - var marker = {__source__:name} - this.sources[name] = { href: href, type: type } - this.push(marker) - http.request(req, function (res) { - var c = [] - var ct = res.headers['content-type'] - if (!type) { - type = ct.indexOf('json') !== -1 ? 'json' - : ct.indexOf('ini') !== -1 ? 'ini' - : href.match(/\.json$/) ? 'json' - : href.match(/\.ini$/) ? 'ini' - : null - marker.type = type - } - - res.on('data', c.push.bind(c)) - .on('end', function () { - this.addString(Buffer.concat(c), href, type, marker) - }.bind(this)) - .on('error', this.emit.bind(this, 'error')) - - }.bind(this)) - .on('error', this.emit.bind(this, 'error')) - .end() - - return this -} - -ConfigChain.prototype.addString = function (data, file, type, marker) { - data = this.parse(data, file, type) - this.add(data, marker) - return this -} - -ConfigChain.prototype.add = function (data, marker) { - if (marker && typeof marker === 'object') { - var i = this.list.indexOf(marker) - if (i === -1) { - return this.emit('error', new Error('bad marker')) - } - this.splice(i, 1, data) - marker = marker.__source__ - this.sources[marker] = this.sources[marker] || {} - this.sources[marker].data = data - // we were waiting for this. maybe emit 'load' - this._resolve() - } else { - if (typeof marker === 'string') { - this.sources[marker] = this.sources[marker] || {} - this.sources[marker].data = data - } - // trigger the load event if nothing was already going to do so. - this._await() - this.push(data) - process.nextTick(this._resolve.bind(this)) - } - return this -} - -ConfigChain.prototype.parse = exports.parse - -ConfigChain.prototype._await = function () { - this._awaiting++ -} - -ConfigChain.prototype._resolve = function () { - this._awaiting-- - if (this._awaiting === 0) this.emit('load', this) -} diff --git a/node_modules/config-chain/package.json b/node_modules/config-chain/package.json deleted file mode 100644 index 17b8a47c..00000000 --- a/node_modules/config-chain/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "config-chain", - "version": "1.1.13", - "license": { - "type": "MIT", - "url": "https://raw.githubusercontent.com/dominictarr/config-chain/master/LICENCE" - }, - "description": "HANDLE CONFIGURATION ONCE AND FOR ALL", - "homepage": "http://github.com/dominictarr/config-chain", - "repository": { - "type": "git", - "url": "https://github.com/dominictarr/config-chain.git" - }, - "files": [ - "index.js" - ], - "dependencies": { - "proto-list": "~1.2.1", - "ini": "^1.3.4" - }, - "devDependencies": { - "tap": "0.3.0" - }, - "author": "Dominic Tarr (http://dominictarr.com)", - "scripts": { - "test": "tap test/*" - } -} diff --git a/node_modules/config-chain/readme.markdown b/node_modules/config-chain/readme.markdown deleted file mode 100644 index 47f894c7..00000000 --- a/node_modules/config-chain/readme.markdown +++ /dev/null @@ -1,257 +0,0 @@ -# config-chain - -A module for loading custom configurations - -## NOTE: Feature Freeze - -[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) - -This module is frozen. - -In general, we recommend using [rc](https://github.com/dominictarr/rc) instead, -but as [npm](https://github.com/npmjs/npm) depends on this, it cannot be changed. - - -## Install - -```sh -yarn add config-chain - -# npm users -npm install --save config-chain -``` - -## Usage - -```js -const cc = require('config-chain'); - -console.log(cc.env('TERM_', process.env)); -/* -{ SESSION_ID: 'w1:5F38', - PROGRAM_VERSION: '3.1.2', - PROGRAM: 'iTerm.app' } -*/ -``` - -The `.env` function gets all the keys on the provided object which are -prefixed by the specified prefix, removes the prefix, and puts the values on a new object. - -
- -## Full Usage - -``` js - - // npm install config-chain - - var cc = require('config-chain') - , opts = require('optimist').argv //ALWAYS USE OPTIMIST FOR COMMAND LINE OPTIONS. - , env = opts.env || process.env.YOUR_APP_ENV || 'dev' //SET YOUR ENV LIKE THIS. - - // EACH ARG TO CONFIGURATOR IS LOADED INTO CONFIGURATION CHAIN - // EARLIER ITEMS OVERIDE LATER ITEMS - // PUTS COMMAND LINE OPTS FIRST, AND DEFAULTS LAST! - - //strings are interpereted as filenames. - //will be loaded synchronously - - var conf = - cc( - //OVERRIDE SETTINGS WITH COMMAND LINE OPTS - opts, - - //ENV VARS IF PREFIXED WITH 'myApp_' - - cc.env('myApp_'), //myApp_foo = 'like this' - - //FILE NAMED BY ENV - path.join(__dirname, 'config.' + env + '.json'), - - //IF `env` is PRODUCTION - env === 'prod' - ? path.join(__dirname, 'special.json') //load a special file - : null //NULL IS IGNORED! - - //SUBDIR FOR ENV CONFIG - path.join(__dirname, 'config', env, 'config.json'), - - //SEARCH PARENT DIRECTORIES FROM CURRENT DIR FOR FILE - cc.find('config.json'), - - //PUT DEFAULTS LAST - { - host: 'localhost' - port: 8000 - }) - - var host = conf.get('host') - - // or - - var host = conf.store.host - -``` - -Finally, flexible configurations! 👌 - -## Custom Configuations - -```javascript -var cc = require('config-chain') - -// all the stuff you did before -var config = cc({ - some: 'object' - }, - cc.find('config.json'), - cc.env('myApp_') - ) - // CONFIGS AS A SERVICE, aka "CaaS", aka EVERY DEVOPS DREAM OMG! - .addUrl('http://configurator:1234/my-configs') - // ASYNC FTW! - .addFile('/path/to/file.json') - - // OBJECTS ARE OK TOO, they're SYNC but they still ORDER RIGHT - // BECAUSE PROMISES ARE USED BUT NO, NOT *THOSE* PROMISES, JUST - // ACTUAL PROMISES LIKE YOU MAKE TO YOUR MOM, KEPT OUT OF LOVE - .add({ another: 'object' }) - - // DIE A THOUSAND DEATHS IF THIS EVER HAPPENS!! - .on('error', function (er) { - // IF ONLY THERE WAS SOMETHIGN HARDER THAN THROW - // MY SORROW COULD BE ADEQUATELY EXPRESSED. /o\ - throw er - }) - - // THROW A PARTY IN YOUR FACE WHEN ITS ALL LOADED!! - .on('load', function (config) { - console.awesome('HOLY SHIT!') - }) -``` - -# API Docs - -## cc(...args) - -MAKE A CHAIN AND ADD ALL THE ARGS. - -If the arg is a STRING, then it shall be a JSON FILENAME. - -RETURN THE CHAIN! - -## cc.json(...args) - -Join the args into a JSON filename! - -SYNC I/O! - -## cc.find(relativePath) - -SEEK the RELATIVE PATH by climbing the TREE OF DIRECTORIES. - -RETURN THE FOUND PATH! - -SYNC I/O! - -## cc.parse(content, file, type) - -Parse the content string, and guess the type from either the -specified type or the filename. - -RETURN THE RESULTING OBJECT! - -NO I/O! - -## cc.env(prefix, env=process.env) - -Get all the keys on the provided object which are -prefixed by the specified prefix, removes the prefix, and puts the values on a new object. - -RETURN THE RESULTING OBJECT! - -NO I/O! - -## cc.ConfigChain() - -The ConfigChain class for CRAY CRAY JQUERY STYLE METHOD CHAINING! - -One of these is returned by the main exported function, as well. - -It inherits (prototypically) from -[ProtoList](https://github.com/isaacs/proto-list/), and also inherits -(parasitically) from -[EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter) - -It has all the methods from both, and except where noted, they are -unchanged. - -### LET IT BE KNOWN THAT chain IS AN INSTANCE OF ConfigChain. - -## chain.sources - -A list of all the places where it got stuff. The keys are the names -passed to addFile or addUrl etc, and the value is an object with some -info about the data source. - -## chain.addFile(filename, type, [name=filename]) - -Filename is the name of the file. Name is an arbitrary string to be -used later if you desire. Type is either 'ini' or 'json', and will -try to guess intelligently if omitted. - -Loaded files can be saved later. - -## chain.addUrl(url, type, [name=url]) - -Same as the filename thing, but with a url. - -Can't be saved later. - -## chain.addEnv(prefix, env, [name='env']) - -Add all the keys from the env object that start with the prefix. - -## chain.addString(data, file, type, [name]) - -Parse the string and add it to the set. (Mainly used internally.) - -## chain.add(object, [name]) - -Add the object to the set. - -## chain.root {Object} - -The root from which all the other config objects in the set descend -prototypically. - -Put your defaults here. - -## chain.set(key, value, name) - -Set the key to the value on the named config object. If name is -unset, then set it on the first config object in the set. (That is, -the one with the highest priority, which was added first.) - -## chain.get(key, [name]) - -Get the key from the named config object explicitly, or from the -resolved configs if not specified. - -## chain.save(name, type) - -Write the named config object back to its origin. - -Currently only supported for env and file config types. - -For files, encode the data according to the type. - -## chain.on('save', function () {}) - -When one or more files are saved, emits `save` event when they're all -saved. - -## chain.on('load', function (chain) {}) - -When the config chain has loaded all the specified files and urls and -such, the 'load' event fires. diff --git a/node_modules/content-disposition/HISTORY.md b/node_modules/content-disposition/HISTORY.md deleted file mode 100644 index 63a3d08c..00000000 --- a/node_modules/content-disposition/HISTORY.md +++ /dev/null @@ -1,55 +0,0 @@ -0.5.3 / 2018-12-17 -================== - - * Use `safe-buffer` for improved Buffer API - -0.5.2 / 2016-12-08 -================== - - * Fix `parse` to accept any linear whitespace character - -0.5.1 / 2016-01-17 -================== - - * perf: enable strict mode - -0.5.0 / 2014-10-11 -================== - - * Add `parse` function - -0.4.0 / 2014-09-21 -================== - - * Expand non-Unicode `filename` to the full ISO-8859-1 charset - -0.3.0 / 2014-09-20 -================== - - * Add `fallback` option - * Add `type` option - -0.2.0 / 2014-09-19 -================== - - * Reduce ambiguity of file names with hex escape in buggy browsers - -0.1.2 / 2014-09-19 -================== - - * Fix periodic invalid Unicode filename header - -0.1.1 / 2014-09-19 -================== - - * Fix invalid characters appearing in `filename*` parameter - -0.1.0 / 2014-09-18 -================== - - * Make the `filename` argument optional - -0.0.0 / 2014-09-18 -================== - - * Initial release diff --git a/node_modules/content-disposition/LICENSE b/node_modules/content-disposition/LICENSE deleted file mode 100644 index 84441fbb..00000000 --- a/node_modules/content-disposition/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2014-2017 Douglas Christopher Wilson - -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. diff --git a/node_modules/content-disposition/README.md b/node_modules/content-disposition/README.md deleted file mode 100644 index eebef13d..00000000 --- a/node_modules/content-disposition/README.md +++ /dev/null @@ -1,148 +0,0 @@ -# content-disposition - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Create and parse HTTP `Content-Disposition` header - -## Installation - -```sh -$ npm install content-disposition -``` - -## API - - - -```js -var contentDisposition = require('content-disposition') -``` - -### contentDisposition(filename, options) - -Create an attachment `Content-Disposition` header value using the given file name, -if supplied. The `filename` is optional and if no file name is desired, but you -want to specify `options`, set `filename` to `undefined`. - - - -```js -res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) -``` - -**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this -header through a means different from `setHeader` in Node.js, you'll want to specify -the `'binary'` encoding in Node.js. - -#### Options - -`contentDisposition` accepts these properties in the options object. - -##### fallback - -If the `filename` option is outside ISO-8859-1, then the file name is actually -stored in a supplemental field for clients that support Unicode file names and -a ISO-8859-1 version of the file name is automatically generated. - -This specifies the ISO-8859-1 file name to override the automatic generation or -disables the generation all together, defaults to `true`. - - - A string will specify the ISO-8859-1 file name to use in place of automatic - generation. - - `false` will disable including a ISO-8859-1 file name and only include the - Unicode version (unless the file name is already ISO-8859-1). - - `true` will enable automatic generation if the file name is outside ISO-8859-1. - -If the `filename` option is ISO-8859-1 and this option is specified and has a -different value, then the `filename` option is encoded in the extended field -and this set as the fallback field, even though they are both ISO-8859-1. - -##### type - -Specifies the disposition type, defaults to `"attachment"`. This can also be -`"inline"`, or any other value (all values except inline are treated like -`attachment`, but can convey additional information if both parties agree to -it). The type is normalized to lower-case. - -### contentDisposition.parse(string) - - - -```js -var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt') -``` - -Parse a `Content-Disposition` header string. This automatically handles extended -("Unicode") parameters by decoding them and providing them under the standard -parameter name. This will return an object with the following properties (examples -are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): - - - `type`: The disposition type (always lower case). Example: `'attachment'` - - - `parameters`: An object of the parameters in the disposition (name of parameter - always lower case and extended versions replace non-extended versions). Example: - `{filename: "€ rates.txt"}` - -## Examples - -### Send a file for download - -```js -var contentDisposition = require('content-disposition') -var destroy = require('destroy') -var fs = require('fs') -var http = require('http') -var onFinished = require('on-finished') - -var filePath = '/path/to/public/plans.pdf' - -http.createServer(function onRequest (req, res) { - // set headers - res.setHeader('Content-Type', 'application/pdf') - res.setHeader('Content-Disposition', contentDisposition(filePath)) - - // send file - var stream = fs.createReadStream(filePath) - stream.pipe(res) - onFinished(res, function () { - destroy(stream) - }) -}) -``` - -## Testing - -```sh -$ npm test -``` - -## References - -- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] -- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] -- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] -- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] - -[rfc-2616]: https://tools.ietf.org/html/rfc2616 -[rfc-5987]: https://tools.ietf.org/html/rfc5987 -[rfc-6266]: https://tools.ietf.org/html/rfc6266 -[tc-2231]: http://greenbytes.de/tech/tc2231/ - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/content-disposition.svg -[npm-url]: https://npmjs.org/package/content-disposition -[node-version-image]: https://img.shields.io/node/v/content-disposition.svg -[node-version-url]: https://nodejs.org/en/download -[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg -[travis-url]: https://travis-ci.org/jshttp/content-disposition -[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg -[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master -[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg -[downloads-url]: https://npmjs.org/package/content-disposition diff --git a/node_modules/content-disposition/index.js b/node_modules/content-disposition/index.js deleted file mode 100644 index 3092a4dc..00000000 --- a/node_modules/content-disposition/index.js +++ /dev/null @@ -1,458 +0,0 @@ -/*! - * content-disposition - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module exports. - * @public - */ - -module.exports = contentDisposition -module.exports.parse = parse - -/** - * Module dependencies. - * @private - */ - -var basename = require('path').basename -var Buffer = require('safe-buffer').Buffer - -/** - * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") - * @private - */ - -var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex - -/** - * RegExp to match percent encoding escape. - * @private - */ - -var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ -var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g - -/** - * RegExp to match non-latin1 characters. - * @private - */ - -var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g - -/** - * RegExp to match quoted-pair in RFC 2616 - * - * quoted-pair = "\" CHAR - * CHAR = - * @private - */ - -var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex - -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - * @private - */ - -var QUOTE_REGEXP = /([\\"])/g - -/** - * RegExp for various RFC 2616 grammar - * - * parameter = token "=" ( token | quoted-string ) - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - * qdtext = > - * quoted-pair = "\" CHAR - * CHAR = - * TEXT = - * LWS = [CRLF] 1*( SP | HT ) - * CRLF = CR LF - * CR = - * LF = - * SP = - * HT = - * CTL = - * OCTET = - * @private - */ - -var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex -var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ - -/** - * RegExp for various RFC 5987 grammar - * - * ext-value = charset "'" [ language ] "'" value-chars - * charset = "UTF-8" / "ISO-8859-1" / mime-charset - * mime-charset = 1*mime-charsetc - * mime-charsetc = ALPHA / DIGIT - * / "!" / "#" / "$" / "%" / "&" - * / "+" / "-" / "^" / "_" / "`" - * / "{" / "}" / "~" - * language = ( 2*3ALPHA [ extlang ] ) - * / 4ALPHA - * / 5*8ALPHA - * extlang = *3( "-" 3ALPHA ) - * value-chars = *( pct-encoded / attr-char ) - * pct-encoded = "%" HEXDIG HEXDIG - * attr-char = ALPHA / DIGIT - * / "!" / "#" / "$" / "&" / "+" / "-" / "." - * / "^" / "_" / "`" / "|" / "~" - * @private - */ - -var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ - -/** - * RegExp for various RFC 6266 grammar - * - * disposition-type = "inline" | "attachment" | disp-ext-type - * disp-ext-type = token - * disposition-parm = filename-parm | disp-ext-parm - * filename-parm = "filename" "=" value - * | "filename*" "=" ext-value - * disp-ext-parm = token "=" value - * | ext-token "=" ext-value - * ext-token = - * @private - */ - -var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex - -/** - * Create an attachment Content-Disposition header. - * - * @param {string} [filename] - * @param {object} [options] - * @param {string} [options.type=attachment] - * @param {string|boolean} [options.fallback=true] - * @return {string} - * @public - */ - -function contentDisposition (filename, options) { - var opts = options || {} - - // get type - var type = opts.type || 'attachment' - - // get parameters - var params = createparams(filename, opts.fallback) - - // format into string - return format(new ContentDisposition(type, params)) -} - -/** - * Create parameters object from filename and fallback. - * - * @param {string} [filename] - * @param {string|boolean} [fallback=true] - * @return {object} - * @private - */ - -function createparams (filename, fallback) { - if (filename === undefined) { - return - } - - var params = {} - - if (typeof filename !== 'string') { - throw new TypeError('filename must be a string') - } - - // fallback defaults to true - if (fallback === undefined) { - fallback = true - } - - if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { - throw new TypeError('fallback must be a string or boolean') - } - - if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError('fallback must be ISO-8859-1 string') - } - - // restrict to file base name - var name = basename(filename) - - // determine if name is suitable for quoted string - var isQuotedString = TEXT_REGEXP.test(name) - - // generate fallback name - var fallbackName = typeof fallback !== 'string' - ? fallback && getlatin1(name) - : basename(fallback) - var hasFallback = typeof fallbackName === 'string' && fallbackName !== name - - // set extended filename parameter - if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { - params['filename*'] = name - } - - // set filename parameter - if (isQuotedString || hasFallback) { - params.filename = hasFallback - ? fallbackName - : name - } - - return params -} - -/** - * Format object to Content-Disposition header. - * - * @param {object} obj - * @param {string} obj.type - * @param {object} [obj.parameters] - * @return {string} - * @private - */ - -function format (obj) { - var parameters = obj.parameters - var type = obj.type - - if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { - throw new TypeError('invalid type') - } - - // start with normalized type - var string = String(type).toLowerCase() - - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() - - for (var i = 0; i < params.length; i++) { - param = params[i] - - var val = param.substr(-1) === '*' - ? ustring(parameters[param]) - : qstring(parameters[param]) - - string += '; ' + param + '=' + val - } - } - - return string -} - -/** - * Decode a RFC 6987 field value (gracefully). - * - * @param {string} str - * @return {string} - * @private - */ - -function decodefield (str) { - var match = EXT_VALUE_REGEXP.exec(str) - - if (!match) { - throw new TypeError('invalid extended field value') - } - - var charset = match[1].toLowerCase() - var encoded = match[2] - var value - - // to binary string - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) - - switch (charset) { - case 'iso-8859-1': - value = getlatin1(binary) - break - case 'utf-8': - value = Buffer.from(binary, 'binary').toString('utf8') - break - default: - throw new TypeError('unsupported charset in extended field') - } - - return value -} - -/** - * Get ISO-8859-1 version of string. - * - * @param {string} val - * @return {string} - * @private - */ - -function getlatin1 (val) { - // simple Unicode -> ISO-8859-1 transformation - return String(val).replace(NON_LATIN1_REGEXP, '?') -} - -/** - * Parse Content-Disposition header string. - * - * @param {string} string - * @return {object} - * @public - */ - -function parse (string) { - if (!string || typeof string !== 'string') { - throw new TypeError('argument string is required') - } - - var match = DISPOSITION_TYPE_REGEXP.exec(string) - - if (!match) { - throw new TypeError('invalid type format') - } - - // normalize type - var index = match[0].length - var type = match[1].toLowerCase() - - var key - var names = [] - var params = {} - var value - - // calculate index to start at - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' - ? index - 1 - : index - - // match parameters - while ((match = PARAM_REGEXP.exec(string))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } - - index += match[0].length - key = match[1].toLowerCase() - value = match[2] - - if (names.indexOf(key) !== -1) { - throw new TypeError('invalid duplicate parameter') - } - - names.push(key) - - if (key.indexOf('*') + 1 === key.length) { - // decode extended value - key = key.slice(0, -1) - value = decodefield(value) - - // overwrite existing value - params[key] = value - continue - } - - if (typeof params[key] === 'string') { - continue - } - - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } - - params[key] = value - } - - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') - } - - return new ContentDisposition(type, params) -} - -/** - * Percent decode a single character. - * - * @param {string} str - * @param {string} hex - * @return {string} - * @private - */ - -function pdecode (str, hex) { - return String.fromCharCode(parseInt(hex, 16)) -} - -/** - * Percent encode a single character. - * - * @param {string} char - * @return {string} - * @private - */ - -function pencode (char) { - return '%' + String(char) - .charCodeAt(0) - .toString(16) - .toUpperCase() -} - -/** - * Quote a string for HTTP. - * - * @param {string} val - * @return {string} - * @private - */ - -function qstring (val) { - var str = String(val) - - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} - -/** - * Encode a Unicode string for HTTP (RFC 5987). - * - * @param {string} val - * @return {string} - * @private - */ - -function ustring (val) { - var str = String(val) - - // percent encode as UTF-8 - var encoded = encodeURIComponent(str) - .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) - - return 'UTF-8\'\'' + encoded -} - -/** - * Class for parsed Content-Disposition header for v8 optimization - * - * @public - * @param {string} type - * @param {object} parameters - * @constructor - */ - -function ContentDisposition (type, parameters) { - this.type = type - this.parameters = parameters -} diff --git a/node_modules/content-disposition/package.json b/node_modules/content-disposition/package.json deleted file mode 100644 index 73d2fb7e..00000000 --- a/node_modules/content-disposition/package.json +++ /dev/null @@ -1,80 +0,0 @@ -{ - "_from": "content-disposition@^0.5.2", - "_id": "content-disposition@0.5.3", - "_inBundle": false, - "_integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", - "_location": "/content-disposition", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "content-disposition@^0.5.2", - "name": "content-disposition", - "escapedName": "content-disposition", - "rawSpec": "^0.5.2", - "saveSpec": null, - "fetchSpec": "^0.5.2" - }, - "_requiredBy": [ - "/bin-wrapper/download", - "/download" - ], - "_resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", - "_shasum": "e130caf7e7279087c5616c2007d0485698984fbd", - "_spec": "content-disposition@^0.5.2", - "_where": "/var/www/html/jason/WeihnachtenMelly/node_modules/download", - "author": { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - "bugs": { - "url": "https://github.com/jshttp/content-disposition/issues" - }, - "bundleDependencies": false, - "dependencies": { - "safe-buffer": "5.1.2" - }, - "deprecated": false, - "description": "Create and parse Content-Disposition header", - "devDependencies": { - "deep-equal": "1.0.1", - "eslint": "5.10.0", - "eslint-config-standard": "12.0.0", - "eslint-plugin-import": "2.14.0", - "eslint-plugin-markdown": "1.0.0-rc.1", - "eslint-plugin-node": "7.0.1", - "eslint-plugin-promise": "4.0.1", - "eslint-plugin-standard": "4.0.0", - "istanbul": "0.4.5", - "mocha": "5.2.0" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "LICENSE", - "HISTORY.md", - "README.md", - "index.js" - ], - "homepage": "https://github.com/jshttp/content-disposition#readme", - "keywords": [ - "content-disposition", - "http", - "rfc6266", - "res" - ], - "license": "MIT", - "name": "content-disposition", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/content-disposition.git" - }, - "scripts": { - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec --bail --check-leaks test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" - }, - "version": "0.5.3" -} diff --git a/node_modules/create-error-class/index.js b/node_modules/create-error-class/index.js new file mode 100644 index 00000000..e415aa7e --- /dev/null +++ b/node_modules/create-error-class/index.js @@ -0,0 +1,44 @@ +'use strict'; +var captureStackTrace = require('capture-stack-trace'); + +function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); +} + +module.exports = function createErrorClass(className, setup) { + if (typeof className !== 'string') { + throw new TypeError('Expected className to be a string'); + } + + if (/[^0-9a-zA-Z_$]/.test(className)) { + throw new Error('className contains invalid characters'); + } + + setup = setup || function (message) { + this.message = message; + }; + + var ErrorClass = function () { + Object.defineProperty(this, 'name', { + configurable: true, + value: className, + writable: true + }); + + captureStackTrace(this, this.constructor); + + setup.apply(this, arguments); + }; + + inherits(ErrorClass, Error); + + return ErrorClass; +}; diff --git a/node_modules/create-error-class/license b/node_modules/create-error-class/license new file mode 100644 index 00000000..1aeb74fd --- /dev/null +++ b/node_modules/create-error-class/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Vsevolod Strukchinsky (github.com/floatdrop) + +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. diff --git a/node_modules/create-error-class/package.json b/node_modules/create-error-class/package.json new file mode 100644 index 00000000..b304012c --- /dev/null +++ b/node_modules/create-error-class/package.json @@ -0,0 +1,30 @@ +{ + "name": "create-error-class", + "version": "3.0.2", + "description": "Create Error classes", + "license": "MIT", + "repository": "floatdrop/create-error-class", + "author": { + "name": "Vsevolod Strukchinsky", + "email": "floatdrop@gmail.com", + "url": "github.com/floatdrop" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "files": [ + "index.js" + ], + "keywords": [ + "" + ], + "dependencies": { + "capture-stack-trace": "^1.0.0" + }, + "devDependencies": { + "mocha": "*" + } +} diff --git a/node_modules/create-error-class/readme.md b/node_modules/create-error-class/readme.md new file mode 100644 index 00000000..d993cea3 --- /dev/null +++ b/node_modules/create-error-class/readme.md @@ -0,0 +1,54 @@ +# create-error-class [![Build Status](https://travis-ci.org/floatdrop/create-error-class.svg?branch=master)](https://travis-ci.org/floatdrop/create-error-class) + +> Create error class + + +## Install + +``` +$ npm install --save create-error-class +``` + + +## Usage + +```js +var createErrorClass = require('create-error-class'); + +var HTTPError = createErrorClass('HTTPError', function (props) { + this.message = 'Status code is ' + props.statusCode; +}); + +throw new HTTPError({statusCode: 404}); +``` + + +## API + +### createErrorClass(className, [setup]) + +Return constructor of Errors with `className`. + +#### className + +*Required* +Type: `string` + +Class name of Error Object. Should contain characters from `[0-9a-zA-Z_$]` range. + +#### setup +Type: `function` + +Setup function, that will be called after each Error object is created from constructor with context of Error object. + +By default `setup` function sets `this.message` as first argument: + +```js +var MyError = createErrorClass('MyError'); + +new MyError('Something gone wrong!').message; // => 'Something gone wrong!' +``` + +## License + +MIT © [Vsevolod Strukchinsky](http://github.com/floatdrop) diff --git a/node_modules/cross-spawn/CHANGELOG.md b/node_modules/cross-spawn/CHANGELOG.md deleted file mode 100644 index f1298a82..00000000 --- a/node_modules/cross-spawn/CHANGELOG.md +++ /dev/null @@ -1,6 +0,0 @@ -## 5.0.0 - 2016-10-30 - -- Add support for `options.shell` -- Improve parsing of shebangs by using [`shebang-command`](https://github.com/kevva/shebang-command) module -- Refactor some code to make it more clear -- Update README caveats diff --git a/node_modules/cross-spawn/LICENSE b/node_modules/cross-spawn/LICENSE deleted file mode 100644 index db5e914d..00000000 --- a/node_modules/cross-spawn/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014 IndigoUnited - -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. diff --git a/node_modules/cross-spawn/README.md b/node_modules/cross-spawn/README.md deleted file mode 100644 index dde730df..00000000 --- a/node_modules/cross-spawn/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# cross-spawn - -[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] - -[npm-url]:https://npmjs.org/package/cross-spawn -[downloads-image]:http://img.shields.io/npm/dm/cross-spawn.svg -[npm-image]:http://img.shields.io/npm/v/cross-spawn.svg -[travis-url]:https://travis-ci.org/IndigoUnited/node-cross-spawn -[travis-image]:http://img.shields.io/travis/IndigoUnited/node-cross-spawn/master.svg -[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn -[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg -[david-dm-url]:https://david-dm.org/IndigoUnited/node-cross-spawn -[david-dm-image]:https://img.shields.io/david/IndigoUnited/node-cross-spawn.svg -[david-dm-dev-url]:https://david-dm.org/IndigoUnited/node-cross-spawn#info=devDependencies -[david-dm-dev-image]:https://img.shields.io/david/dev/IndigoUnited/node-cross-spawn.svg - -A cross platform solution to node's spawn and spawnSync. - - -## Installation - -`$ npm install cross-spawn` - -If you are using `spawnSync` on node 0.10 or older, you will also need to install `spawn-sync`: - -`$ npm install spawn-sync` - - -## Why - -Node has issues when using spawn on Windows: - -- It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) -- It does not support [shebangs](http://pt.wikipedia.org/wiki/Shebang) -- No `options.shell` support on node < v6 -- It does not allow you to run `del` or `dir` - -All these issues are handled correctly by `cross-spawn`. -There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments. - - -## Usage - -Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement. - - -```js -var spawn = require('cross-spawn'); - -// Spawn NPM asynchronously -var child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); - -// Spawn NPM synchronously -var results = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); -``` - - -## Caveats - -#### `options.shell` as an alternative to `cross-spawn` - -Starting from node v6, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves most of the problems that `cross-spawn` attempts to solve, but: - -- It's not supported in node < v6 -- It has no support for shebangs on Windows -- You must manually escape the command and arguments which is very error prone, specially when passing user input - -If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned. - - -#### Shebangs - -While `cross-spawn` handles shebangs on Windows, its support is limited: e.g.: it doesn't handle arguments after the path, e.g.: `#!/bin/bash -e`. - -Remember to always test your code on Windows! - - -## Tests - -`$ npm test` - - -## License - -Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). diff --git a/node_modules/cross-spawn/index.js b/node_modules/cross-spawn/index.js deleted file mode 100644 index 7814a969..00000000 --- a/node_modules/cross-spawn/index.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -var cp = require('child_process'); -var parse = require('./lib/parse'); -var enoent = require('./lib/enoent'); - -var cpSpawnSync = cp.spawnSync; - -function spawn(command, args, options) { - var parsed; - var spawned; - - // Parse the arguments - parsed = parse(command, args, options); - - // Spawn the child process - spawned = cp.spawn(parsed.command, parsed.args, parsed.options); - - // Hook into child process "exit" event to emit an error if the command - // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - enoent.hookChildProcess(spawned, parsed); - - return spawned; -} - -function spawnSync(command, args, options) { - var parsed; - var result; - - if (!cpSpawnSync) { - try { - cpSpawnSync = require('spawn-sync'); // eslint-disable-line global-require - } catch (ex) { - throw new Error( - 'In order to use spawnSync on node 0.10 or older, you must ' + - 'install spawn-sync:\n\n' + - ' npm install spawn-sync --save' - ); - } - } - - // Parse the arguments - parsed = parse(command, args, options); - - // Spawn the child process - result = cpSpawnSync(parsed.command, parsed.args, parsed.options); - - // Analyze if the command does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); - - return result; -} - -module.exports = spawn; -module.exports.spawn = spawn; -module.exports.sync = spawnSync; - -module.exports._parse = parse; -module.exports._enoent = enoent; diff --git a/node_modules/cross-spawn/lib/enoent.js b/node_modules/cross-spawn/lib/enoent.js deleted file mode 100644 index d0a193ae..00000000 --- a/node_modules/cross-spawn/lib/enoent.js +++ /dev/null @@ -1,73 +0,0 @@ -'use strict'; - -var isWin = process.platform === 'win32'; -var resolveCommand = require('./util/resolveCommand'); - -var isNode10 = process.version.indexOf('v0.10.') === 0; - -function notFoundError(command, syscall) { - var err; - - err = new Error(syscall + ' ' + command + ' ENOENT'); - err.code = err.errno = 'ENOENT'; - err.syscall = syscall + ' ' + command; - - return err; -} - -function hookChildProcess(cp, parsed) { - var originalEmit; - - if (!isWin) { - return; - } - - originalEmit = cp.emit; - cp.emit = function (name, arg1) { - var err; - - // If emitting "exit" event and exit code is 1, we need to check if - // the command exists and emit an "error" instead - // See: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - if (name === 'exit') { - err = verifyENOENT(arg1, parsed, 'spawn'); - - if (err) { - return originalEmit.call(cp, 'error', err); - } - } - - return originalEmit.apply(cp, arguments); - }; -} - -function verifyENOENT(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawn'); - } - - return null; -} - -function verifyENOENTSync(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } - - // If we are in node 10, then we are using spawn-sync; if it exited - // with -1 it probably means that the command does not exist - if (isNode10 && status === -1) { - parsed.file = isWin ? parsed.file : resolveCommand(parsed.original); - - if (!parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } - } - - return null; -} - -module.exports.hookChildProcess = hookChildProcess; -module.exports.verifyENOENT = verifyENOENT; -module.exports.verifyENOENTSync = verifyENOENTSync; -module.exports.notFoundError = notFoundError; diff --git a/node_modules/cross-spawn/lib/parse.js b/node_modules/cross-spawn/lib/parse.js deleted file mode 100644 index 10a01362..00000000 --- a/node_modules/cross-spawn/lib/parse.js +++ /dev/null @@ -1,113 +0,0 @@ -'use strict'; - -var resolveCommand = require('./util/resolveCommand'); -var hasEmptyArgumentBug = require('./util/hasEmptyArgumentBug'); -var escapeArgument = require('./util/escapeArgument'); -var escapeCommand = require('./util/escapeCommand'); -var readShebang = require('./util/readShebang'); - -var isWin = process.platform === 'win32'; -var skipShellRegExp = /\.(?:com|exe)$/i; - -// Supported in Node >= 6 and >= 4.8 -var supportsShellOption = parseInt(process.version.substr(1).split('.')[0], 10) >= 6 || - parseInt(process.version.substr(1).split('.')[0], 10) === 4 && parseInt(process.version.substr(1).split('.')[1], 10) >= 8; - -function parseNonShell(parsed) { - var shebang; - var needsShell; - var applyQuotes; - - if (!isWin) { - return parsed; - } - - // Detect & add support for shebangs - parsed.file = resolveCommand(parsed.command); - parsed.file = parsed.file || resolveCommand(parsed.command, true); - shebang = parsed.file && readShebang(parsed.file); - - if (shebang) { - parsed.args.unshift(parsed.file); - parsed.command = shebang; - needsShell = hasEmptyArgumentBug || !skipShellRegExp.test(resolveCommand(shebang) || resolveCommand(shebang, true)); - } else { - needsShell = hasEmptyArgumentBug || !skipShellRegExp.test(parsed.file); - } - - // If a shell is required, use cmd.exe and take care of escaping everything correctly - if (needsShell) { - // Escape command & arguments - applyQuotes = (parsed.command !== 'echo'); // Do not quote arguments for the special "echo" command - parsed.command = escapeCommand(parsed.command); - parsed.args = parsed.args.map(function (arg) { - return escapeArgument(arg, applyQuotes); - }); - - // Make use of cmd.exe - parsed.args = ['/d', '/s', '/c', '"' + parsed.command + (parsed.args.length ? ' ' + parsed.args.join(' ') : '') + '"']; - parsed.command = process.env.comspec || 'cmd.exe'; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } - - return parsed; -} - -function parseShell(parsed) { - var shellCommand; - - // If node supports the shell option, there's no need to mimic its behavior - if (supportsShellOption) { - return parsed; - } - - // Mimic node shell option, see: https://github.com/nodejs/node/blob/b9f6a2dc059a1062776133f3d4fd848c4da7d150/lib/child_process.js#L335 - shellCommand = [parsed.command].concat(parsed.args).join(' '); - - if (isWin) { - parsed.command = typeof parsed.options.shell === 'string' ? parsed.options.shell : process.env.comspec || 'cmd.exe'; - parsed.args = ['/d', '/s', '/c', '"' + shellCommand + '"']; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } else { - if (typeof parsed.options.shell === 'string') { - parsed.command = parsed.options.shell; - } else if (process.platform === 'android') { - parsed.command = '/system/bin/sh'; - } else { - parsed.command = '/bin/sh'; - } - - parsed.args = ['-c', shellCommand]; - } - - return parsed; -} - -// ------------------------------------------------ - -function parse(command, args, options) { - var parsed; - - // Normalize arguments, similar to nodejs - if (args && !Array.isArray(args)) { - options = args; - args = null; - } - - args = args ? args.slice(0) : []; // Clone array to avoid changing the original - options = options || {}; - - // Build our parsed object - parsed = { - command: command, - args: args, - options: options, - file: undefined, - original: command, - }; - - // Delegate further parsing to shell or non-shell - return options.shell ? parseShell(parsed) : parseNonShell(parsed); -} - -module.exports = parse; diff --git a/node_modules/cross-spawn/lib/util/escapeArgument.js b/node_modules/cross-spawn/lib/util/escapeArgument.js deleted file mode 100644 index 367263f6..00000000 --- a/node_modules/cross-spawn/lib/util/escapeArgument.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -function escapeArgument(arg, quote) { - // Convert to string - arg = '' + arg; - - // If we are not going to quote the argument, - // escape shell metacharacters, including double and single quotes: - if (!quote) { - arg = arg.replace(/([()%!^<>&|;,"'\s])/g, '^$1'); - } else { - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/g, '$1$1\\"'); - - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(\\*)$/, '$1$1'); - - // All other backslashes occur literally - - // Quote the whole thing: - arg = '"' + arg + '"'; - } - - return arg; -} - -module.exports = escapeArgument; diff --git a/node_modules/cross-spawn/lib/util/escapeCommand.js b/node_modules/cross-spawn/lib/util/escapeCommand.js deleted file mode 100644 index d9c25b26..00000000 --- a/node_modules/cross-spawn/lib/util/escapeCommand.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict'; - -var escapeArgument = require('./escapeArgument'); - -function escapeCommand(command) { - // Do not escape if this command is not dangerous.. - // We do this so that commands like "echo" or "ifconfig" work - // Quoting them, will make them unaccessible - return /^[a-z0-9_-]+$/i.test(command) ? command : escapeArgument(command, true); -} - -module.exports = escapeCommand; diff --git a/node_modules/cross-spawn/lib/util/hasEmptyArgumentBug.js b/node_modules/cross-spawn/lib/util/hasEmptyArgumentBug.js deleted file mode 100644 index 9f2eba63..00000000 --- a/node_modules/cross-spawn/lib/util/hasEmptyArgumentBug.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -// See: https://github.com/IndigoUnited/node-cross-spawn/pull/34#issuecomment-221623455 -function hasEmptyArgumentBug() { - var nodeVer; - - if (process.platform !== 'win32') { - return false; - } - - nodeVer = process.version.substr(1).split('.').map(function (num) { - return parseInt(num, 10); - }); - - return (nodeVer[0] === 0 && nodeVer[1] < 12); -} - -module.exports = hasEmptyArgumentBug(); diff --git a/node_modules/cross-spawn/lib/util/readShebang.js b/node_modules/cross-spawn/lib/util/readShebang.js deleted file mode 100644 index 2cf3541c..00000000 --- a/node_modules/cross-spawn/lib/util/readShebang.js +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var fs = require('fs'); -var LRU = require('lru-cache'); -var shebangCommand = require('shebang-command'); - -var shebangCache = new LRU({ max: 50, maxAge: 30 * 1000 }); // Cache just for 30sec - -function readShebang(command) { - var buffer; - var fd; - var shebang; - - // Check if it is in the cache first - if (shebangCache.has(command)) { - return shebangCache.get(command); - } - - // Read the first 150 bytes from the file - buffer = new Buffer(150); - - try { - fd = fs.openSync(command, 'r'); - fs.readSync(fd, buffer, 0, 150, 0); - fs.closeSync(fd); - } catch (e) { /* empty */ } - - // Attempt to extract shebang (null is returned if not a shebang) - shebang = shebangCommand(buffer.toString()); - - // Store the shebang in the cache - shebangCache.set(command, shebang); - - return shebang; -} - -module.exports = readShebang; diff --git a/node_modules/cross-spawn/lib/util/resolveCommand.js b/node_modules/cross-spawn/lib/util/resolveCommand.js deleted file mode 100644 index b7a94909..00000000 --- a/node_modules/cross-spawn/lib/util/resolveCommand.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var path = require('path'); -var which = require('which'); -var LRU = require('lru-cache'); - -var commandCache = new LRU({ max: 50, maxAge: 30 * 1000 }); // Cache just for 30sec - -function resolveCommand(command, noExtension) { - var resolved; - - noExtension = !!noExtension; - resolved = commandCache.get(command + '!' + noExtension); - - // Check if its resolved in the cache - if (commandCache.has(command)) { - return commandCache.get(command); - } - - try { - resolved = !noExtension ? - which.sync(command) : - which.sync(command, { pathExt: path.delimiter + (process.env.PATHEXT || '') }); - } catch (e) { /* empty */ } - - commandCache.set(command + '!' + noExtension, resolved); - - return resolved; -} - -module.exports = resolveCommand; diff --git a/node_modules/cross-spawn/package.json b/node_modules/cross-spawn/package.json deleted file mode 100644 index 7c10c972..00000000 --- a/node_modules/cross-spawn/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "cross-spawn", - "version": "5.1.0", - "description": "Cross platform child_process#spawn and child_process#spawnSync", - "main": "index.js", - "scripts": { - "test": "node test/prepare && mocha --bail test/test", - "lint": "eslint '{*.js,lib/**/*.js,test/**/*.js}'" - }, - "bugs": { - "url": "https://github.com/IndigoUnited/node-cross-spawn/issues/" - }, - "repository": { - "type": "git", - "url": "git://github.com/IndigoUnited/node-cross-spawn.git" - }, - "files": [ - "index.js", - "lib" - ], - "keywords": [ - "spawn", - "spawnSync", - "windows", - "cross", - "platform", - "path", - "ext", - "path-ext", - "path_ext", - "shebang", - "hashbang", - "cmd", - "execute" - ], - "author": "IndigoUnited (http://indigounited.com)", - "license": "MIT", - "dependencies": { - "lru-cache": "^4.0.1", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - }, - "devDependencies": { - "@satazor/eslint-config": "^3.0.0", - "eslint": "^3.0.0", - "expect.js": "^0.3.0", - "glob": "^7.0.0", - "mkdirp": "^0.5.1", - "mocha": "^3.0.2", - "once": "^1.4.0", - "rimraf": "^2.5.0" - } -} diff --git a/node_modules/css-select-base-adapter/.gitattributes b/node_modules/css-select-base-adapter/.gitattributes deleted file mode 100644 index bdb0cabc..00000000 --- a/node_modules/css-select-base-adapter/.gitattributes +++ /dev/null @@ -1,17 +0,0 @@ -# Auto detect text files and perform LF normalization -* text=auto - -# Custom for Visual Studio -*.cs diff=csharp - -# Standard to msysgit -*.doc diff=astextplain -*.DOC diff=astextplain -*.docx diff=astextplain -*.DOCX diff=astextplain -*.dot diff=astextplain -*.DOT diff=astextplain -*.pdf diff=astextplain -*.PDF diff=astextplain -*.rtf diff=astextplain -*.RTF diff=astextplain diff --git a/node_modules/css-select-base-adapter/LICENSE b/node_modules/css-select-base-adapter/LICENSE deleted file mode 100644 index 649145dc..00000000 --- a/node_modules/css-select-base-adapter/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Nik Coughlin - -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. \ No newline at end of file diff --git a/node_modules/css-select-base-adapter/index.js b/node_modules/css-select-base-adapter/index.js deleted file mode 100644 index 6394cbd0..00000000 --- a/node_modules/css-select-base-adapter/index.js +++ /dev/null @@ -1,131 +0,0 @@ -'use strict' - -module.exports = adapterFactory; - -function adapterFactory(implementation){ - ensureImplementation(implementation); - - var adapter = {} - - var baseAdapter = { - removeSubsets: function (nodes){ - return removeSubsets(adapter, nodes); - }, - existsOne: function(test, elems){ - return existsOne(adapter, test, elems); - }, - getSiblings: function(elem){ - return getSiblings(adapter, elem); - }, - hasAttrib: function(elem, name){ - return hasAttrib(adapter, elem, name); - }, - findOne: function(test, arr){ - return findOne(adapter, test, arr); - }, - findAll: function(test, elems){ - return findAll(adapter, test, elems) - } - }; - - Object.assign(adapter, baseAdapter, implementation); - - return adapter; -} - -var expectImplemented = [ - "isTag", "getAttributeValue", "getChildren", "getName", "getParent", - "getText" -]; - -function ensureImplementation(implementation){ - if(!implementation) throw new TypeError("Expected implementation") - - var notImplemented = expectImplemented.filter(function(fname){ - return typeof implementation[fname] !== "function"; - }); - - if(notImplemented.length){ - var notList = "(" + notImplemented.join(", ") + ")"; - var message = "Expected functions " + notList + " to be implemented"; - throw new Error(message); - } -} - -function removeSubsets(adapter, nodes){ - var idx = nodes.length, node, ancestor, replace; - - // Check if each node (or one of its ancestors) is already contained in the - // array. - while(--idx > -1){ - node = ancestor = nodes[idx]; - - // Temporarily remove the node under consideration - nodes[idx] = null; - replace = true; - - while(ancestor){ - if(nodes.indexOf(ancestor) > -1){ - replace = false; - nodes.splice(idx, 1); - break; - } - ancestor = adapter.getParent(ancestor) - } - - // If the node has been found to be unique, re-insert it. - if(replace){ - nodes[idx] = node; - } - } - - return nodes; -} - -function existsOne(adapter, test, elems){ - return elems.some(function(elem){ - return adapter.isTag(elem) ? - test(elem) || adapter.existsOne(test, adapter.getChildren(elem)) : - false; - }); -} - -function getSiblings(adapter, elem){ - var parent = adapter.getParent(elem); - return parent && adapter.getChildren(parent); -} - - -function hasAttrib(adapter, elem, name){ - return adapter.getAttributeValue(elem,name) !== undefined -} - -function findOne(adapter, test, arr){ - var elem = null; - - for(var i = 0, l = arr.length; i < l && !elem; i++){ - if(test(arr[i])){ - elem = arr[i]; - } else { - var childs = adapter.getChildren(arr[i]); - if(childs && childs.length > 0){ - elem = adapter.findOne(test, childs); - } - } - } - - return elem; -} - -function findAll(adapter, test, elems){ - var result = []; - - for(var i = 0, j = elems.length; i < j; i++){ - if(!adapter.isTag(elems[i])) continue; - if(test(elems[i])) result.push(elems[i]); - var childs = adapter.getChildren(elems[i]); - if(childs) result = result.concat(adapter.findAll(test, childs)); - } - - return result; -} diff --git a/node_modules/css-select-base-adapter/package.json b/node_modules/css-select-base-adapter/package.json deleted file mode 100644 index f32e5eba..00000000 --- a/node_modules/css-select-base-adapter/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "css-select-base-adapter", - "version": "0.1.1", - "description": "Provides some base functions needed by a css-select adapter so that you don't have to implement the whole thing.", - "main": "index.js", - "scripts": { - "test": "mocha" - }, - "repository": { - "type": "git", - "url": "https://github.com/nrkn/css-select-base-adapter.git" - }, - "keywords": [ - "css", - "select", - "adapter", - "css-select" - ], - "bugs": { - "url": "https://github.com/nrkn/css-select-base-adapter/issues" - }, - "homepage": "https://github.com/nrkn/css-select-base-adapter#readme", - "author": "Nik Coughlin ", - "license": "MIT" -} diff --git a/node_modules/css-select-base-adapter/readme.md b/node_modules/css-select-base-adapter/readme.md deleted file mode 100644 index c7423433..00000000 --- a/node_modules/css-select-base-adapter/readme.md +++ /dev/null @@ -1,70 +0,0 @@ -# css-select-base-adapter - -Provides some base functions needed by a -[`css-select`](https://github.com/fb55/css-select) adapter so that you don't -have to implement the whole thing. - -## usage - -`npm install css-select-base-adapter --save` - -```javascript -var baseAdapter = require('css-select-base-adapter'); - -var myAdapter = { - // your partial implementation here -}; - -// get an adapter with everything needed by css-select -var adapter = baseAdapter(myAdapter); - -// use adapter with css-select... -``` - -## how it works - -An adapter for `css-select` requires the following functions to be implemented: - -``` -isTag, existsOne, getAttributeValue, getChildren, getName, getParent, -getSiblings, getText, hasAttrib, removeSubsets, findAll, findOne -``` - -You can pass this module a more minimal implementation and it will return a full -adapter that fills in any missing functions, provided that you implement at -least: - -``` -isTag, getAttributeValue, getChildren, getName, getParent, getText -``` - -If you provide any of the other methods required of an adapter, the base adapter -will use your implementation instead of its own. - -See the -[`css-select` readme](https://github.com/fb55/css-select/blob/master/README.md) -for more information on the required function signatures. - -## license - -MIT License - -Copyright (c) 2018 Nik Coughlin - -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. \ No newline at end of file diff --git a/node_modules/css-select-base-adapter/test/data.js b/node_modules/css-select-base-adapter/test/data.js deleted file mode 100644 index c16dfd63..00000000 --- a/node_modules/css-select-base-adapter/test/data.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict' - -const walk = ( node, parent, cb ) => { - cb( node, parent ) - - if( Array.isArray( node.children ) ) - node.children.forEach( child => walk( child, node, cb ) ) -} - -const data = { - name: 'div', - attribs: { - id: 'container', - class: 'message' - }, - children: [ - { - name: 'strong', - attribs: { - class: 'message' - }, - children: [ - { text: 'Hello' } - ] - }, - { text: ', World!' } - ] -} - -walk( data, null, ( node, parent ) => { - if( parent ) node.parent = parent -}) - -module.exports = [ data ] diff --git a/node_modules/css-select-base-adapter/test/implementation.js b/node_modules/css-select-base-adapter/test/implementation.js deleted file mode 100644 index c88985b8..00000000 --- a/node_modules/css-select-base-adapter/test/implementation.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict' - -const implementation = { - isTag: node => node !== undefined && 'name' in node, - getAttributeValue: ( elem, name ) => { - if( implementation.isTag( elem ) && elem.attribs ) return elem.attribs[ name ] - }, - getChildren: node => node.children, - getName: elem => { - if( implementation.isTag( elem ) ) return elem.name - }, - getParent: node => node.parent, - getText: node => node.children.map( child => { - if( child.text ) return child.text - - if( implementation.isTag( child ) ) return implementation.getText( child ) - - return '' - }).join( '' ) -} - -module.exports = implementation diff --git a/node_modules/css-select-base-adapter/test/index.js b/node_modules/css-select-base-adapter/test/index.js deleted file mode 100644 index fc73b3e8..00000000 --- a/node_modules/css-select-base-adapter/test/index.js +++ /dev/null @@ -1,103 +0,0 @@ -'use strict' - -const assert = require( 'assert' ) -const data = require( './data' ) -const implementation = require( './implementation' ) -const baseAdapter = require( '../' ) - -const adapter = baseAdapter( implementation ) - -const getById = id => adapter.findOne( - node => adapter.getAttributeValue( node, 'id' ) === id, - data -) - -const getByName = name => adapter.findAll( - node => adapter.getName( node ) === name, - data -) - -const getByClass = className => adapter.findAll( - node => adapter.getAttributeValue( node, 'class' ) === className, - data -) - -const existsName = name => adapter.existsOne( - node => adapter.getName( node ) === name, - data -) - -const container = getById( 'container' ) -const strong = getByName( 'strong' )[ 0 ] -const hello = strong.children[ 0 ] -const world = container.children[ 1 ] - -describe( 'css-select-base-adapter', () => { - it( 'getAttributeValue', () => { - assert( container ) - }) - - it( 'getName', () => { - assert( strong ) - }) - - it( 'findOne', () => { - assert( container ) - }) - - it( 'findAll', () => { - const messages = getByClass( 'message' ) - - assert.equal( messages.length, 2 ) - assert.equal( messages[ 0 ], container ) - assert.equal( messages[ 1 ], strong ) - }) - - it( 'getParent', () => { - const parent = adapter.getParent( strong ) - - assert.equal( parent, container ) - }) - - it( 'getSiblings', () => { - const siblings = adapter.getSiblings( strong ) - - assert.equal( siblings[ 0 ], strong ) - assert.equal( siblings[ 1 ], world ) - }) - - it( 'getChildren', () => { - const children = adapter.getChildren( container ) - - assert.equal( children[ 0 ], strong ) - }) - - it( 'getText', () => { - const text = adapter.getText( container ) - - assert.equal( text, 'Hello, World!' ) - }) - - it( 'isTag', () => { - assert( adapter.isTag( container ) ) - assert( adapter.isTag( strong ) ) - assert( !adapter.isTag( hello ) ) - }) - - it( 'hasAttrib', () => { - assert( adapter.hasAttrib( container, 'id' ) ) - assert( !adapter.hasAttrib( strong, 'id' ) ) - }) - - it( 'existsOne', () => { - assert( existsName( 'strong' ) ) - assert( !existsName( 'blink' ) ) - }) - - it( 'removeSubsets', () => { - const removed = adapter.removeSubsets([ container, strong, container ]) - - assert.equal( removed.length, 1 ) - assert.equal( removed[ 0 ], container ) - }) -}) diff --git a/node_modules/css-select/LICENSE b/node_modules/css-select/LICENSE deleted file mode 100644 index c464f863..00000000 --- a/node_modules/css-select/LICENSE +++ /dev/null @@ -1,11 +0,0 @@ -Copyright (c) Felix Böhm -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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, -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/css-select/README.md b/node_modules/css-select/README.md deleted file mode 100644 index b96768ec..00000000 --- a/node_modules/css-select/README.md +++ /dev/null @@ -1,221 +0,0 @@ -# css-select [![NPM version](http://img.shields.io/npm/v/css-select.svg)](https://npmjs.org/package/css-select) [![Build Status](https://travis-ci.org/fb55/css-select.svg?branch=master)](http://travis-ci.org/fb55/css-select) [![Downloads](https://img.shields.io/npm/dm/css-select.svg)](https://npmjs.org/package/css-select) [![Coverage](https://coveralls.io/repos/fb55/css-select/badge.svg?branch=master)](https://coveralls.io/r/fb55/css-select) - -a CSS selector compiler/engine - -## What? - -css-select turns CSS selectors into functions that tests if elements match them. When searching for elements, testing is executed "from the top", similar to how browsers execute CSS selectors. - -In its default configuration, css-select queries the DOM structure of the [`domhandler`](https://github.com/fb55/domhandler) module (also known as htmlparser2 DOM). -It uses [`domutils`](https://github.com/fb55/domutils) as its default adapter over the DOM structure. See Options below for details on querying alternative DOM structures. - -__Features:__ - -- Full implementation of CSS3 selectors -- Partial implementation of jQuery/Sizzle extensions -- Very high test coverage -- Pretty good performance - -## Why? - -The traditional approach of executing CSS selectors, named left-to-right execution, is to execute every component of the selector in order, from left to right _(duh)_. The execution of the selector `a b` for example will first query for `a` elements, then search these for `b` elements. (That's the approach of eg. [`Sizzle`](https://github.com/jquery/sizzle), [`nwmatcher`](https://github.com/dperini/nwmatcher/) and [`qwery`](https://github.com/ded/qwery).) - -While this works, it has some downsides: Children of `a`s will be checked multiple times; first, to check if they are also `a`s, then, for every superior `a` once, if they are `b`s. Using [Big O notation](http://en.wikipedia.org/wiki/Big_O_notation), that would be `O(n^(k+1))`, where `k` is the number of descendant selectors (that's the space in the example above). - -The far more efficient approach is to first look for `b` elements, then check if they have superior `a` elements: Using big O notation again, that would be `O(n)`. That's called right-to-left execution. - -And that's what css-select does – and why it's quite performant. - -## How does it work? - -By building a stack of functions. - -_Wait, what?_ - -Okay, so let's suppose we want to compile the selector `a b` again, for right-to-left execution. We start by _parsing_ the selector, which means we turn the selector into an array of the building-blocks of the selector, so we can distinguish them easily. That's what the [`css-what`](https://github.com/fb55/css-what) module is for, if you want to have a look. - -Anyway, after parsing, we end up with an array like this one: - -```js -[ - { type: 'tag', name: 'a' }, - { type: 'descendant' }, - { type: 'tag', name: 'b' } -] -``` - -Actually, this array is wrapped in another array, but that's another story (involving commas in selectors). - -Now that we know the meaning of every part of the selector, we can compile it. That's where it becomes interesting. - -The basic idea is to turn every part of the selector into a function, which takes an element as its only argument. The function checks whether a passed element matches its part of the selector: If it does, the element is passed to the next turned-into-a-function part of the selector, which does the same. If an element is accepted by all parts of the selector, it _matches_ the selector and double rainbow ALL THE WAY. - -As said before, we want to do right-to-left execution with all the big O improvements nonsense, so elements are passed from the rightmost part of the selector (`b` in our example) to the leftmost (~~which would be `c`~~ of course `a`). - -_//TODO: More in-depth description. Implementation details. Build a spaceship._ - -## API - -```js -const CSSselect = require("css-select"); -``` - -__Note:__ css-select throws errors when invalid selectors are passed to it, contrary to the behavior in browsers, which swallow them. This is done to aid with writing css selectors, but can be unexpected when processing arbitrary strings. - -#### `CSSselect(query, elems, options)` - -Queries `elems`, returns an array containing all matches. - -- `query` can be either a CSS selector or a function. -- `elems` can be either an array of elements, or a single element. If it is an element, its children will be queried. -- `options` is described below. - -Aliases: `CSSselect.selectAll(query, elems)`, `CSSselect.iterate(query, elems)`. - -#### `CSSselect.compile(query)` - -Compiles the query, returns a function. - -#### `CSSselect.is(elem, query, options)` - -Tests whether or not an element is matched by `query`. `query` can be either a CSS selector or a function. - -#### `CSSselect.selectOne(query, elems, options)` - -Arguments are the same as for `CSSselect(query, elems)`. Only returns the first match, or `null` if there was no match. - -### Options - -- `xmlMode`: When enabled, tag names will be case-sensitive. Default: `false`. -- `strict`: Limits the module to only use CSS3 selectors. Default: `false`. -- `rootFunc`: The last function in the stack, will be called with the last element that's looked at. Should return `true`. -- `adapter`: The adapter to use when interacting with the backing DOM structure. By default it uses [`domutils`](https://github.com/fb55/domutils). - -#### Custom Adapters - -A custom adapter must implement the following functions: - -``` -isTag, existsOne, getAttributeValue, getChildren, getName, getParent, -getSiblings, getText, hasAttrib, removeSubsets, findAll, findOne -``` - -The method signature notation used below should be fairly intuitive - if not, -see the [`rtype`](https://github.com/ericelliott/rtype) or -[`TypeScript`](https://www.typescriptlang.org/) docs, as it is very similar to -both of those. You may also want to look at --[`domutils`](https://github.com/fb55/domutils) to see the default --implementation, or at --[`css-select-browser-adapter`](https://github.com/nrkn/css-select-browser-adapter/blob/master/index.js) --for an implementation backed by the DOM. - -```ts -{ - // is the node a tag? - isTag: ( node:Node ) => isTag:Boolean, - - // does at least one of passed element nodes pass the test predicate? - existsOne: ( test:Predicate, elems:[ElementNode] ) => existsOne:Boolean, - - // get the attribute value - getAttributeValue: ( elem:ElementNode, name:String ) => value:String, - - // get the node's children - getChildren: ( node:Node ) => children:[Node], - - // get the name of the tag - getName: ( elem:ElementNode ) => tagName:String, - - // get the parent of the node - getParent: ( node:Node ) => parentNode:Node, - - /* - get the siblings of the node. Note that unlike jQuery's `siblings` method, - this is expected to include the current node as well - */ - getSiblings: ( node:Node ) => siblings:[Node], - - // get the text content of the node, and its children if it has any - getText: ( node:Node ) => text:String, - - // does the element have the named attribute? - hasAttrib: ( elem:ElementNode, name:String ) => hasAttrib:Boolean, - - // takes an array of nodes, and removes any duplicates, as well as any nodes - // whose ancestors are also in the array - removeSubsets: ( nodes:[Node] ) => unique:[Node], - - // finds all of the element nodes in the array that match the test predicate, - // as well as any of their children that match it - findAll: ( test:Predicate, nodes:[Node] ) => elems:[ElementNode], - - // finds the first node in the array that matches the test predicate, or one - // of its children - findOne: ( test:Predicate, elems:[ElementNode] ) => findOne:ElementNode, - - /* - The adapter can also optionally include an equals method, if your DOM - structure needs a custom equality test to compare two objects which refer - to the same underlying node. If not provided, `css-select` will fall back to - `a === b`. - */ - equals: ( a:Node, b:Node ) => Boolean -} -``` - -## Supported selectors - -_As defined by CSS 4 and / or jQuery._ - -* Universal (`*`) -* Tag (``) -* Descendant (` `) -* Child (`>`) -* Parent (`<`) * -* Sibling (`+`) -* Adjacent (`~`) -* Attribute (`[attr=foo]`), with supported comparisons: - * `[attr]` (existential) - * `=` - * `~=` - * `|=` - * `*=` - * `^=` - * `$=` - * `!=` * - * Also, `i` can be added after the comparison to make the comparison case-insensitive (eg. `[attr=foo i]`) * -* Pseudos: - * `:not` - * `:contains` * - * `:icontains` * (case-insensitive version of `:contains`) - * `:has` * - * `:root` - * `:empty` - * `:parent` * - * `:[first|last]-child[-of-type]` - * `:only-of-type`, `:only-child` - * `:nth-[last-]child[-of-type]` - * `:link` - * `:visited`, `:hover`, `:active` * (these depend on optional Adapter methods, so these will work only if implemented in Adapter) - * `:selected` *, `:checked` - * `:enabled`, `:disabled` - * `:required`, `:optional` - * `:header`, `:button`, `:input`, `:text`, `:checkbox`, `:file`, `:password`, `:reset`, `:radio` etc. * - * `:matches` * - -__*__: Not part of CSS3 - ---- - -License: BSD-2-Clause - -## Security contact information - -To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). -Tidelift will coordinate the fix and disclosure. - -## `css-select` for enterprise - -Available as part of the Tidelift Subscription - -The maintainers of `css-select` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-css-select?utm_source=npm-css-select&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/css-select/index.d.ts b/node_modules/css-select/index.d.ts deleted file mode 100644 index 81f1f391..00000000 --- a/node_modules/css-select/index.d.ts +++ /dev/null @@ -1,219 +0,0 @@ -export = CSSselect; - -/** - * Alias for CSSselect.selectAll(query, elems, options). - * @see [CSSselect.compile] for supported selector queries. - */ -declare function CSSselect( - query: CSSselect.Query, - elems: Array | ElementNode, - options?: CSSselect.Options - ): Array; - -declare namespace CSSselect { - type Predicate = (v: Value) => boolean; - interface Adapter { - /** - * is the node a tag? - */ - isTag(node: Node): node is ElementNode; - - /** - * Does at least one of passed element nodes pass the test predicate? - */ - existsOne(test: Predicate, elems: Array): boolean; - - /** - * get the attribute value. - */ - getAttributeValue(elem: ElementNode, name: string): string; - - /** - * get the node's children - */ - getChildren(node: Node): Array; - - /** - * get the name of the tag - */ - getName(elem: ElementNode): string; - - /** - * get the parent of the node - */ - getParent(node: Node): Node; - - /* - Get the siblings of the node. Note that unlike jQuery's `siblings` method, - this is expected to include the current node as well - */ - getSiblings(node: Node): Array; - - /* - * Get the text content of the node, and its children if it has any. - */ - getText(node: Node): string; - - /** - * Does the element have the named attribute? - */ - hasAttrib(elem: ElementNode, name: string): boolean; - - /** - * takes an array of nodes, and removes any duplicates, as well as any - * nodes whose ancestors are also in the array. - */ - removeSubsets(nodes: Array): Array; - - /** - * finds all of the element nodes in the array that match the test predicate, - * as well as any of their children that match it. - */ - findAll(test: Predicate, nodes: Array): Array; - - /** - * finds the first node in the array that matches the test predicate, or one - * of its children. - */ - findOne(test: Predicate, elems: Array): ElementNode | undefined, - - /** - The adapter can also optionally include an equals method, if your DOM - structure needs a custom equality test to compare two objects which refer - to the same underlying node. If not provided, `css-select` will fall back to - `a === b`. - */ - equals?: (a: Node, b: Node) => boolean; - - /** - * is the element in hovered state? - */ - isHovered?: (elem: ElementNode) => boolean; - - /** - * is the element in visited state? - */ - isVisited?: (elem: ElementNode) => boolean; - - /** - * is the element in active state? - */ - isActive?: (elem: ElementNode) => boolean; - } - - // TODO default types to the domutil/httpparser2 types - interface Options { - /** - * When enabled, tag names will be case-sensitive. Default: false. - */ - xmlMode?: boolean; - /** - * Limits the module to only use CSS3 selectors. Default: false. - */ - strict?: boolean; - /** - * The last function in the stack, will be called with the last element - * that's looked at. Should return true. - */ - rootFunc?: (element: ElementNode) => true; - /** - * The adapter to use when interacting with the backing DOM structure. By - * default it uses domutils. - */ - adapter?: Adapter; - } - - type CompiledQuery = (node: any) => boolean; - type Query = string | CompiledQuery; - - /** - * Compiles the query, returns a function. - * - * Supported simple selectors: - * * Universal (*) - * * Tag () - * * Attribute ([attr=foo]), with supported comparisons: - * * [attr] (existential) - * * = - * * ~= - * * |= - * * *= - * * ^= - * * $= - * * != - * * Can be case insensitive (E.g. [attr=foo i]) - * * Pseudos: - * * :not - * * :root - * * :empty - * * :[first|last]-child[-of-type] - * * :only-of-type, :only-child - * * :nth-[last-]child[-of-type] - * * :link, :visited (the latter doesn't match any elements) - * * :checked - * * :enabled, :disabled - * * :required, :optional - * * Nonstandard Pseudos (available when strict mode is not enabled): - * * `:contains` - * * `:icontains` (case-insensitive version of :contains) - * * `:has` - * * `:parent` - * * `:selected` - * * `:header, :button, :input, :text, :checkbox, :file, :password, :reset, :radio etc. - * * :matches - * - * Supported Combinators: - * - * * Descendant (` `) - * * Child (`>`) - * * Parent (`<`) (when strict mode is not enabled) - * * Sibling (`~`) - * * Adjacent (`+`) - */ - function compile(query: string): CompiledQuery; - /** - * @template Node The generic Node type for the DOM adapter being used. - * @template ElementNode The Node type for elements for the DOM adapter being used. - * @param elems Elements to query. If it is an element, its children will be queried.. - * @param query can be either a CSS selector string or a compiled query function. - * @param [options] options for querying the document. - * @see CSSselect.compile for supported selector queries. - * @returns All matching elements. - */ - function selectAll( - query: Query, - elems: Array | ElementNode, - options?: Options - ): Array; - /** - * @template Node The generic Node type for the DOM adapter being used. - * @template ElementNode The Node type for elements for the DOM adapter being used. - * @param elems Elements to query. If it is an element, its children will be queried.. - * @param query can be either a CSS selector string or a compiled query function. - * @param [options] options for querying the document. - * @see CSSselect.compile for supported selector queries. - * @returns the first match, or null if there was no match. - */ - function selectOne( - query: Query, - elems: Array | ElementNode, - options?: Options - ): ElementNode | null; - - /** - * Tests whether or not an element is matched by query. - * - * @template Node The generic Node type for the DOM adapter being used. - * @template ElementNode The Node type for elements for the DOM adapter being used. - * @param elem The element to test if it matches the query. - * @param query can be either a CSS selector string or a compiled query function. - * @param [options] options for querying the document. - * @see CSSselect.compile for supported selector queries. - * @returns - */ - function is( - elem: ElementNode, - query: Query, - options?: Options - ): boolean; -} \ No newline at end of file diff --git a/node_modules/css-select/index.js b/node_modules/css-select/index.js deleted file mode 100644 index 93c6ebde..00000000 --- a/node_modules/css-select/index.js +++ /dev/null @@ -1,94 +0,0 @@ -"use strict"; - -module.exports = CSSselect; - -var DomUtils = require("domutils"); -var falseFunc = require("boolbase").falseFunc; -var compileRaw = require("./lib/compile.js"); - -function wrapCompile(func) { - return function addAdapter(selector, options, context) { - options = options || {}; - options.adapter = options.adapter || DomUtils; - - return func(selector, options, context); - }; -} - -var compile = wrapCompile(compileRaw); -var compileUnsafe = wrapCompile(compileRaw.compileUnsafe); - -function getSelectorFunc(searchFunc) { - return function select(query, elems, options) { - options = options || {}; - options.adapter = options.adapter || DomUtils; - - if (typeof query !== "function") { - query = compileUnsafe(query, options, elems); - } - if (query.shouldTestNextSiblings) { - elems = appendNextSiblings((options && options.context) || elems, options.adapter); - } - if (!Array.isArray(elems)) elems = options.adapter.getChildren(elems); - else elems = options.adapter.removeSubsets(elems); - return searchFunc(query, elems, options); - }; -} - -function getNextSiblings(elem, adapter) { - var siblings = adapter.getSiblings(elem); - if (!Array.isArray(siblings)) return []; - siblings = siblings.slice(0); - while (siblings.shift() !== elem); - return siblings; -} - -function appendNextSiblings(elems, adapter) { - // Order matters because jQuery seems to check the children before the siblings - if (!Array.isArray(elems)) elems = [elems]; - var newElems = elems.slice(0); - - for (var i = 0, len = elems.length; i < len; i++) { - var nextSiblings = getNextSiblings(newElems[i], adapter); - newElems.push.apply(newElems, nextSiblings); - } - return newElems; -} - -var selectAll = getSelectorFunc(function selectAll(query, elems, options) { - return query === falseFunc || !elems || elems.length === 0 ? [] : options.adapter.findAll(query, elems); -}); - -var selectOne = getSelectorFunc(function selectOne(query, elems, options) { - return query === falseFunc || !elems || elems.length === 0 ? null : options.adapter.findOne(query, elems); -}); - -function is(elem, query, options) { - options = options || {}; - options.adapter = options.adapter || DomUtils; - return (typeof query === "function" ? query : compile(query, options))(elem); -} - -/* - the exported interface -*/ -function CSSselect(query, elems, options) { - return selectAll(query, elems, options); -} - -CSSselect.compile = compile; -CSSselect.filters = compileRaw.Pseudos.filters; -CSSselect.pseudos = compileRaw.Pseudos.pseudos; - -CSSselect.selectAll = selectAll; -CSSselect.selectOne = selectOne; - -CSSselect.is = is; - -//legacy methods (might be removed) -CSSselect.parse = compile; -CSSselect.iterate = selectAll; - -//hooks -CSSselect._compileUnsafe = compileUnsafe; -CSSselect._compileToken = compileRaw.compileToken; diff --git a/node_modules/css-select/lib/attributes.js b/node_modules/css-select/lib/attributes.js deleted file mode 100644 index 9d715914..00000000 --- a/node_modules/css-select/lib/attributes.js +++ /dev/null @@ -1,190 +0,0 @@ -var falseFunc = require("boolbase").falseFunc; - -//https://github.com/slevithan/XRegExp/blob/master/src/xregexp.js#L469 -var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g; - -/* - attribute selectors -*/ -var attributeRules = { - __proto__: null, - equals: function(next, data, options) { - var name = data.name; - var value = data.value; - var adapter = options.adapter; - - if (data.ignoreCase) { - value = value.toLowerCase(); - - return function equalsIC(elem) { - var attr = adapter.getAttributeValue(elem, name); - return attr != null && attr.toLowerCase() === value && next(elem); - }; - } - - return function equals(elem) { - return adapter.getAttributeValue(elem, name) === value && next(elem); - }; - }, - hyphen: function(next, data, options) { - var name = data.name; - var value = data.value; - var len = value.length; - var adapter = options.adapter; - - if (data.ignoreCase) { - value = value.toLowerCase(); - - return function hyphenIC(elem) { - var attr = adapter.getAttributeValue(elem, name); - return ( - attr != null && - (attr.length === len || attr.charAt(len) === "-") && - attr.substr(0, len).toLowerCase() === value && - next(elem) - ); - }; - } - - return function hyphen(elem) { - var attr = adapter.getAttributeValue(elem, name); - return ( - attr != null && - attr.substr(0, len) === value && - (attr.length === len || attr.charAt(len) === "-") && - next(elem) - ); - }; - }, - element: function(next, data, options) { - var name = data.name; - var value = data.value; - var adapter = options.adapter; - - if (/\s/.test(value)) { - return falseFunc; - } - - value = value.replace(reChars, "\\$&"); - - var pattern = "(?:^|\\s)" + value + "(?:$|\\s)", - flags = data.ignoreCase ? "i" : "", - regex = new RegExp(pattern, flags); - - return function element(elem) { - var attr = adapter.getAttributeValue(elem, name); - return attr != null && regex.test(attr) && next(elem); - }; - }, - exists: function(next, data, options) { - var name = data.name; - var adapter = options.adapter; - - return function exists(elem) { - return adapter.hasAttrib(elem, name) && next(elem); - }; - }, - start: function(next, data, options) { - var name = data.name; - var value = data.value; - var len = value.length; - var adapter = options.adapter; - - if (len === 0) { - return falseFunc; - } - - if (data.ignoreCase) { - value = value.toLowerCase(); - - return function startIC(elem) { - var attr = adapter.getAttributeValue(elem, name); - return attr != null && attr.substr(0, len).toLowerCase() === value && next(elem); - }; - } - - return function start(elem) { - var attr = adapter.getAttributeValue(elem, name); - return attr != null && attr.substr(0, len) === value && next(elem); - }; - }, - end: function(next, data, options) { - var name = data.name; - var value = data.value; - var len = -value.length; - var adapter = options.adapter; - - if (len === 0) { - return falseFunc; - } - - if (data.ignoreCase) { - value = value.toLowerCase(); - - return function endIC(elem) { - var attr = adapter.getAttributeValue(elem, name); - return attr != null && attr.substr(len).toLowerCase() === value && next(elem); - }; - } - - return function end(elem) { - var attr = adapter.getAttributeValue(elem, name); - return attr != null && attr.substr(len) === value && next(elem); - }; - }, - any: function(next, data, options) { - var name = data.name; - var value = data.value; - var adapter = options.adapter; - - if (value === "") { - return falseFunc; - } - - if (data.ignoreCase) { - var regex = new RegExp(value.replace(reChars, "\\$&"), "i"); - - return function anyIC(elem) { - var attr = adapter.getAttributeValue(elem, name); - return attr != null && regex.test(attr) && next(elem); - }; - } - - return function any(elem) { - var attr = adapter.getAttributeValue(elem, name); - return attr != null && attr.indexOf(value) >= 0 && next(elem); - }; - }, - not: function(next, data, options) { - var name = data.name; - var value = data.value; - var adapter = options.adapter; - - if (value === "") { - return function notEmpty(elem) { - return !!adapter.getAttributeValue(elem, name) && next(elem); - }; - } else if (data.ignoreCase) { - value = value.toLowerCase(); - - return function notIC(elem) { - var attr = adapter.getAttributeValue(elem, name); - return attr != null && attr.toLowerCase() !== value && next(elem); - }; - } - - return function not(elem) { - return adapter.getAttributeValue(elem, name) !== value && next(elem); - }; - } -}; - -module.exports = { - compile: function(next, data, options) { - if (options && options.strict && (data.ignoreCase || data.action === "not")) { - throw new Error("Unsupported attribute selector"); - } - return attributeRules[data.action](next, data, options); - }, - rules: attributeRules -}; diff --git a/node_modules/css-select/lib/compile.js b/node_modules/css-select/lib/compile.js deleted file mode 100644 index 86d2d131..00000000 --- a/node_modules/css-select/lib/compile.js +++ /dev/null @@ -1,219 +0,0 @@ -/* - compiles a selector to an executable function -*/ - -module.exports = compile; - -var parse = require("css-what").parse; -var BaseFuncs = require("boolbase"); -var sortRules = require("./sort.js"); -var procedure = require("./procedure.json"); -var Rules = require("./general.js"); -var Pseudos = require("./pseudos.js"); -var trueFunc = BaseFuncs.trueFunc; -var falseFunc = BaseFuncs.falseFunc; - -var filters = Pseudos.filters; - -function compile(selector, options, context) { - var next = compileUnsafe(selector, options, context); - return wrap(next, options); -} - -function wrap(next, options) { - var adapter = options.adapter; - - return function base(elem) { - return adapter.isTag(elem) && next(elem); - }; -} - -function compileUnsafe(selector, options, context) { - var token = parse(selector, options); - return compileToken(token, options, context); -} - -function includesScopePseudo(t) { - return ( - t.type === "pseudo" && - (t.name === "scope" || - (Array.isArray(t.data) && - t.data.some(function(data) { - return data.some(includesScopePseudo); - }))) - ); -} - -var DESCENDANT_TOKEN = { type: "descendant" }; -var FLEXIBLE_DESCENDANT_TOKEN = { type: "_flexibleDescendant" }; -var SCOPE_TOKEN = { type: "pseudo", name: "scope" }; -var PLACEHOLDER_ELEMENT = {}; - -//CSS 4 Spec (Draft): 3.3.1. Absolutizing a Scope-relative Selector -//http://www.w3.org/TR/selectors4/#absolutizing -function absolutize(token, options, context) { - var adapter = options.adapter; - - //TODO better check if context is document - var hasContext = - !!context && - !!context.length && - context.every(function(e) { - return e === PLACEHOLDER_ELEMENT || !!adapter.getParent(e); - }); - - token.forEach(function(t) { - if (t.length > 0 && isTraversal(t[0]) && t[0].type !== "descendant") { - //don't return in else branch - } else if (hasContext && !(Array.isArray(t) ? t.some(includesScopePseudo) : includesScopePseudo(t))) { - t.unshift(DESCENDANT_TOKEN); - } else { - return; - } - - t.unshift(SCOPE_TOKEN); - }); -} - -function compileToken(token, options, context) { - token = token.filter(function(t) { - return t.length > 0; - }); - - token.forEach(sortRules); - - var isArrayContext = Array.isArray(context); - - context = (options && options.context) || context; - - if (context && !isArrayContext) context = [context]; - - absolutize(token, options, context); - - var shouldTestNextSiblings = false; - - var query = token - .map(function(rules) { - if (rules[0] && rules[1] && rules[0].name === "scope") { - var ruleType = rules[1].type; - if (isArrayContext && ruleType === "descendant") { - rules[1] = FLEXIBLE_DESCENDANT_TOKEN; - } else if (ruleType === "adjacent" || ruleType === "sibling") { - shouldTestNextSiblings = true; - } - } - return compileRules(rules, options, context); - }) - .reduce(reduceRules, falseFunc); - - query.shouldTestNextSiblings = shouldTestNextSiblings; - - return query; -} - -function isTraversal(t) { - return procedure[t.type] < 0; -} - -function compileRules(rules, options, context) { - return rules.reduce(function(func, rule) { - if (func === falseFunc) return func; - - if (!(rule.type in Rules)) { - throw new Error("Rule type " + rule.type + " is not supported by css-select"); - } - - return Rules[rule.type](func, rule, options, context); - }, (options && options.rootFunc) || trueFunc); -} - -function reduceRules(a, b) { - if (b === falseFunc || a === trueFunc) { - return a; - } - if (a === falseFunc || b === trueFunc) { - return b; - } - - return function combine(elem) { - return a(elem) || b(elem); - }; -} - -function containsTraversal(t) { - return t.some(isTraversal); -} - -//:not, :has and :matches have to compile selectors -//doing this in lib/pseudos.js would lead to circular dependencies, -//so we add them here -filters.not = function(next, token, options, context) { - var opts = { - xmlMode: !!(options && options.xmlMode), - strict: !!(options && options.strict), - adapter: options.adapter - }; - - if (opts.strict) { - if (token.length > 1 || token.some(containsTraversal)) { - throw new Error("complex selectors in :not aren't allowed in strict mode"); - } - } - - var func = compileToken(token, opts, context); - - if (func === falseFunc) return next; - if (func === trueFunc) return falseFunc; - - return function not(elem) { - return !func(elem) && next(elem); - }; -}; - -filters.has = function(next, token, options) { - var adapter = options.adapter; - var opts = { - xmlMode: !!(options && options.xmlMode), - strict: !!(options && options.strict), - adapter: adapter - }; - - //FIXME: Uses an array as a pointer to the current element (side effects) - var context = token.some(containsTraversal) ? [PLACEHOLDER_ELEMENT] : null; - - var func = compileToken(token, opts, context); - - if (func === falseFunc) return falseFunc; - if (func === trueFunc) { - return function hasChild(elem) { - return adapter.getChildren(elem).some(adapter.isTag) && next(elem); - }; - } - - func = wrap(func, options); - - if (context) { - return function has(elem) { - return next(elem) && ((context[0] = elem), adapter.existsOne(func, adapter.getChildren(elem))); - }; - } - - return function has(elem) { - return next(elem) && adapter.existsOne(func, adapter.getChildren(elem)); - }; -}; - -filters.matches = function(next, token, options, context) { - var opts = { - xmlMode: !!(options && options.xmlMode), - strict: !!(options && options.strict), - rootFunc: next, - adapter: options.adapter - }; - - return compileToken(token, opts, context); -}; - -compile.compileToken = compileToken; -compile.compileUnsafe = compileUnsafe; -compile.Pseudos = Pseudos; diff --git a/node_modules/css-select/lib/general.js b/node_modules/css-select/lib/general.js deleted file mode 100644 index b2e42771..00000000 --- a/node_modules/css-select/lib/general.js +++ /dev/null @@ -1,117 +0,0 @@ -var attributes = require("./attributes.js"); -var Pseudos = require("./pseudos"); - -/* - all available rules -*/ -module.exports = { - __proto__: null, - - attribute: attributes.compile, - pseudo: Pseudos.compile, - - //tags - tag: function(next, data, options) { - var name = data.name; - var adapter = options.adapter; - - return function tag(elem) { - return adapter.getName(elem) === name && next(elem); - }; - }, - - //traversal - descendant: function(next, data, options) { - // eslint-disable-next-line no-undef - var isFalseCache = typeof WeakSet !== "undefined" ? new WeakSet() : null; - var adapter = options.adapter; - - return function descendant(elem) { - var found = false; - - while (!found && (elem = adapter.getParent(elem))) { - if (!isFalseCache || !isFalseCache.has(elem)) { - found = next(elem); - if (!found && isFalseCache) { - isFalseCache.add(elem); - } - } - } - - return found; - }; - }, - _flexibleDescendant: function(next, data, options) { - var adapter = options.adapter; - - // Include element itself, only used while querying an array - return function descendant(elem) { - var found = next(elem); - - while (!found && (elem = adapter.getParent(elem))) { - found = next(elem); - } - - return found; - }; - }, - parent: function(next, data, options) { - if (options && options.strict) { - throw new Error("Parent selector isn't part of CSS3"); - } - - var adapter = options.adapter; - - return function parent(elem) { - return adapter.getChildren(elem).some(test); - }; - - function test(elem) { - return adapter.isTag(elem) && next(elem); - } - }, - child: function(next, data, options) { - var adapter = options.adapter; - - return function child(elem) { - var parent = adapter.getParent(elem); - return !!parent && next(parent); - }; - }, - sibling: function(next, data, options) { - var adapter = options.adapter; - - return function sibling(elem) { - var siblings = adapter.getSiblings(elem); - - for (var i = 0; i < siblings.length; i++) { - if (adapter.isTag(siblings[i])) { - if (siblings[i] === elem) break; - if (next(siblings[i])) return true; - } - } - - return false; - }; - }, - adjacent: function(next, data, options) { - var adapter = options.adapter; - - return function adjacent(elem) { - var siblings = adapter.getSiblings(elem), - lastElement; - - for (var i = 0; i < siblings.length; i++) { - if (adapter.isTag(siblings[i])) { - if (siblings[i] === elem) break; - lastElement = siblings[i]; - } - } - - return !!lastElement && next(lastElement); - }; - }, - universal: function(next) { - return next; - } -}; diff --git a/node_modules/css-select/lib/procedure.json b/node_modules/css-select/lib/procedure.json deleted file mode 100644 index c74b1b6f..00000000 --- a/node_modules/css-select/lib/procedure.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "universal": 50, - "tag": 30, - "attribute": 1, - "pseudo": 0, - "descendant": -1, - "child": -1, - "parent": -1, - "sibling": -1, - "adjacent": -1 -} diff --git a/node_modules/css-select/lib/pseudos.js b/node_modules/css-select/lib/pseudos.js deleted file mode 100644 index 93eb6bf5..00000000 --- a/node_modules/css-select/lib/pseudos.js +++ /dev/null @@ -1,453 +0,0 @@ -/* - pseudo selectors - - --- - - they are available in two forms: - * filters called when the selector - is compiled and return a function - that needs to return next() - * pseudos get called on execution - they need to return a boolean -*/ - -var getNCheck = require("nth-check"); -var BaseFuncs = require("boolbase"); -var attributes = require("./attributes.js"); -var trueFunc = BaseFuncs.trueFunc; -var falseFunc = BaseFuncs.falseFunc; - -var checkAttrib = attributes.rules.equals; - -function getAttribFunc(name, value) { - var data = { name: name, value: value }; - return function attribFunc(next, rule, options) { - return checkAttrib(next, data, options); - }; -} - -function getChildFunc(next, adapter) { - return function(elem) { - return !!adapter.getParent(elem) && next(elem); - }; -} - -var filters = { - contains: function(next, text, options) { - var adapter = options.adapter; - - return function contains(elem) { - return next(elem) && adapter.getText(elem).indexOf(text) >= 0; - }; - }, - icontains: function(next, text, options) { - var itext = text.toLowerCase(); - var adapter = options.adapter; - - return function icontains(elem) { - return ( - next(elem) && - adapter - .getText(elem) - .toLowerCase() - .indexOf(itext) >= 0 - ); - }; - }, - - //location specific methods - "nth-child": function(next, rule, options) { - var func = getNCheck(rule); - var adapter = options.adapter; - - if (func === falseFunc) return func; - if (func === trueFunc) return getChildFunc(next, adapter); - - return function nthChild(elem) { - var siblings = adapter.getSiblings(elem); - - for (var i = 0, pos = 0; i < siblings.length; i++) { - if (adapter.isTag(siblings[i])) { - if (siblings[i] === elem) break; - else pos++; - } - } - - return func(pos) && next(elem); - }; - }, - "nth-last-child": function(next, rule, options) { - var func = getNCheck(rule); - var adapter = options.adapter; - - if (func === falseFunc) return func; - if (func === trueFunc) return getChildFunc(next, adapter); - - return function nthLastChild(elem) { - var siblings = adapter.getSiblings(elem); - - for (var pos = 0, i = siblings.length - 1; i >= 0; i--) { - if (adapter.isTag(siblings[i])) { - if (siblings[i] === elem) break; - else pos++; - } - } - - return func(pos) && next(elem); - }; - }, - "nth-of-type": function(next, rule, options) { - var func = getNCheck(rule); - var adapter = options.adapter; - - if (func === falseFunc) return func; - if (func === trueFunc) return getChildFunc(next, adapter); - - return function nthOfType(elem) { - var siblings = adapter.getSiblings(elem); - - for (var pos = 0, i = 0; i < siblings.length; i++) { - if (adapter.isTag(siblings[i])) { - if (siblings[i] === elem) break; - if (adapter.getName(siblings[i]) === adapter.getName(elem)) pos++; - } - } - - return func(pos) && next(elem); - }; - }, - "nth-last-of-type": function(next, rule, options) { - var func = getNCheck(rule); - var adapter = options.adapter; - - if (func === falseFunc) return func; - if (func === trueFunc) return getChildFunc(next, adapter); - - return function nthLastOfType(elem) { - var siblings = adapter.getSiblings(elem); - - for (var pos = 0, i = siblings.length - 1; i >= 0; i--) { - if (adapter.isTag(siblings[i])) { - if (siblings[i] === elem) break; - if (adapter.getName(siblings[i]) === adapter.getName(elem)) pos++; - } - } - - return func(pos) && next(elem); - }; - }, - - //TODO determine the actual root element - root: function(next, rule, options) { - var adapter = options.adapter; - - return function(elem) { - return !adapter.getParent(elem) && next(elem); - }; - }, - - scope: function(next, rule, options, context) { - var adapter = options.adapter; - - if (!context || context.length === 0) { - //equivalent to :root - return filters.root(next, rule, options); - } - - function equals(a, b) { - if (typeof adapter.equals === "function") return adapter.equals(a, b); - - return a === b; - } - - if (context.length === 1) { - //NOTE: can't be unpacked, as :has uses this for side-effects - return function(elem) { - return equals(context[0], elem) && next(elem); - }; - } - - return function(elem) { - return context.indexOf(elem) >= 0 && next(elem); - }; - }, - - //jQuery extensions (others follow as pseudos) - checkbox: getAttribFunc("type", "checkbox"), - file: getAttribFunc("type", "file"), - password: getAttribFunc("type", "password"), - radio: getAttribFunc("type", "radio"), - reset: getAttribFunc("type", "reset"), - image: getAttribFunc("type", "image"), - submit: getAttribFunc("type", "submit"), - - //dynamic state pseudos. These depend on optional Adapter methods. - hover: function(next, rule, options) { - var adapter = options.adapter; - - if (typeof adapter.isHovered === 'function') { - return function hover(elem) { - return next(elem) && adapter.isHovered(elem); - }; - } - - return falseFunc; - }, - visited: function(next, rule, options) { - var adapter = options.adapter; - - if (typeof adapter.isVisited === 'function') { - return function visited(elem) { - return next(elem) && adapter.isVisited(elem); - }; - } - - return falseFunc; - }, - active: function(next, rule, options) { - var adapter = options.adapter; - - if (typeof adapter.isActive === 'function') { - return function active(elem) { - return next(elem) && adapter.isActive(elem); - }; - } - - return falseFunc; - } -}; - -//helper methods -function getFirstElement(elems, adapter) { - for (var i = 0; elems && i < elems.length; i++) { - if (adapter.isTag(elems[i])) return elems[i]; - } -} - -//while filters are precompiled, pseudos get called when they are needed -var pseudos = { - empty: function(elem, adapter) { - return !adapter.getChildren(elem).some(function(elem) { - return adapter.isTag(elem) || elem.type === "text"; - }); - }, - - "first-child": function(elem, adapter) { - return getFirstElement(adapter.getSiblings(elem), adapter) === elem; - }, - "last-child": function(elem, adapter) { - var siblings = adapter.getSiblings(elem); - - for (var i = siblings.length - 1; i >= 0; i--) { - if (siblings[i] === elem) return true; - if (adapter.isTag(siblings[i])) break; - } - - return false; - }, - "first-of-type": function(elem, adapter) { - var siblings = adapter.getSiblings(elem); - - for (var i = 0; i < siblings.length; i++) { - if (adapter.isTag(siblings[i])) { - if (siblings[i] === elem) return true; - if (adapter.getName(siblings[i]) === adapter.getName(elem)) break; - } - } - - return false; - }, - "last-of-type": function(elem, adapter) { - var siblings = adapter.getSiblings(elem); - - for (var i = siblings.length - 1; i >= 0; i--) { - if (adapter.isTag(siblings[i])) { - if (siblings[i] === elem) return true; - if (adapter.getName(siblings[i]) === adapter.getName(elem)) break; - } - } - - return false; - }, - "only-of-type": function(elem, adapter) { - var siblings = adapter.getSiblings(elem); - - for (var i = 0, j = siblings.length; i < j; i++) { - if (adapter.isTag(siblings[i])) { - if (siblings[i] === elem) continue; - if (adapter.getName(siblings[i]) === adapter.getName(elem)) { - return false; - } - } - } - - return true; - }, - "only-child": function(elem, adapter) { - var siblings = adapter.getSiblings(elem); - - for (var i = 0; i < siblings.length; i++) { - if (adapter.isTag(siblings[i]) && siblings[i] !== elem) return false; - } - - return true; - }, - - //:matches(a, area, link)[href] - link: function(elem, adapter) { - return adapter.hasAttrib(elem, "href"); - }, - //TODO: :any-link once the name is finalized (as an alias of :link) - - //forms - //to consider: :target - - //:matches([selected], select:not([multiple]):not(> option[selected]) > option:first-of-type) - selected: function(elem, adapter) { - if (adapter.hasAttrib(elem, "selected")) return true; - else if (adapter.getName(elem) !== "option") return false; - - //the first