diff options
author | Minteck <contact@minteck.org> | 2021-12-21 16:50:49 +0100 |
---|---|---|
committer | Minteck <contact@minteck.org> | 2021-12-21 16:50:49 +0100 |
commit | 20204baf1807825af4798ad03bfb329e4da05bc5 (patch) | |
tree | 1568515fa1e4592206ed5d2327b39e6b443cbd03 | |
download | bingoloto-remote-20204baf1807825af4798ad03bfb329e4da05bc5.tar.gz bingoloto-remote-20204baf1807825af4798ad03bfb329e4da05bc5.tar.bz2 bingoloto-remote-20204baf1807825af4798ad03bfb329e4da05bc5.zip |
Commit
462 files changed, 44913 insertions, 0 deletions
diff --git a/auth.json b/auth.json new file mode 100644 index 0000000..bc77b0a --- /dev/null +++ b/auth.json @@ -0,0 +1,4 @@ +{ + "host": "192.168.192.235", + "key": "03300eff3f598d76ba1f8d41b4c4eec703ee89913b08a5609fb30bc94a86a2c0" +} diff --git a/help.txt b/help.txt new file mode 100644 index 0000000..7fea19c --- /dev/null +++ b/help.txt @@ -0,0 +1,21 @@ + +Welcome to Bingoloto Remote! + +This tool helps you monitor a Bingoloto server without physically having access to it. It uses a secure TCP protocol to ensure security and integrity. + +NOTICE: This tool is not meant to be used for illegal purposes, the people using the Bingoloto client WILL know that you are connecting to them and may close the program in case of unwanted connection. + +Available commands: + h Get help + q Close connection and quit + l Get list of already picked numbers + n <number> Set the number as picked + u Undo last picked number from current mode + t [message] Get or set the tagline + m [mode] Get the current or switch mode + s Get system info + p <number> Check if a number has already been picked + d <code> Run raw JS code + x Stop the server + e Enable or disable the display + g Get server logs diff --git a/index.js b/index.js new file mode 100644 index 0000000..8557f34 --- /dev/null +++ b/index.js @@ -0,0 +1,237 @@ +const ora = require('ora'); +const chalk = require('chalk'); +const config = require('./auth.json'); +const net = require('net'); +const readline = require("readline"); +const fs = require("fs"); +global.connected = false; + +function commandline() { + rl.question(chalk.gray("bingoloto> "), function(cmd) { + if (cmd.trim() == "") { + commandline(); + return; + } + + args = cmd.split(" "); + command = args[0]; + args.shift(); + + switch (command) { + case "q": + console.log("Bye!"); + connected = false; + client.destroy(); + process.exit(); + break; + case "h": + console.log(fs.readFileSync("help.txt").toString()); + break; + case "n": + if (args[0] != undefined) { + if (args[0].trim() > 90 || isNaN(args[0].trim())) { + console.log(chalk.red("invalid number")); + commandline() + } else { + client.write("pick|" + args[0].trim()); + } + } else { + console.log(chalk.red("missing operand")); + commandline() + } + return; + case "p": + if (args[0] != undefined) { + if (args[0].trim() > 90 || isNaN(args[0].trim())) { + console.log(chalk.red("invalid number")); + commandline() + } else { + global.lmode = args[0].trim(); + client.write("list") + return; + } + } else { + console.log(chalk.red("missing operand")); + commandline() + } + return; + case "d": + if (args[0] != undefined) { + client.write("jsae|" + args.join(" ").trim()) + } else { + console.log(chalk.red("missing operand")); + commandline() + } + return; + case "l": + global.lmode = false; + client.write("list") + return; + case "g": + client.write("glog") + return; + case "x": + client.write("stop") + return; + case "s": + client.write("sysi") + return; + case "u": + client.write("undo") + return; + case "e": + client.write("stat") + return; + case "t": + if (args[0] != undefined) { + client.write("stag|" + args.join(" ").trim() + " ") + } else { + client.write("gtag") + } + return; + case "m": + if (args[0] != undefined) { + if (args[0] == "bingo" || args[0] == "loto" || args[0] == "l" || args[0] == "b") { + client.write("smod|" + args[0].trim()); + } else { + console.log(chalk.red("unknown mode")); + commandline(); + } + } else { + client.write("gmod") + } + return; + default: + console.log(chalk.red("unknown command")); + } + + commandline(); + }); +} + +process.on('uncaughtException', (err) => { + if (err.stack.includes("ECONNREFUSED")) { + console.log(chalk.red("\nUnable to connect to server, retrying")); + joinsrv(); + } else { + console.log("\n" + chalk.red(err.stack) + "\n"); + process.exit(255); + } +}) + +const spinner = ora('Connecting to ' + config.host + ":7441").start(); + +var client = new net.Socket(); +function joinsrv() { + try { + client.connect(7441, config.host, function() { + spinner.succeed() + connected = true; + console.log(chalk.green('Connected to server')); + }); + } catch (e) { + console.log(chalk.red("\nUnable to connect to server, retrying")); + joinsrv(); + } +} +joinsrv() + +authent = false; + +client.on('data', function(data) { + if (data.toString().startsWith("connected|")) { + global.ver = data.toString().split("|")[1]; + global.authspin = ora('Authenticating').start(); + authent = true; + client.write("auth|" + config.key); + return; + } + if (data.toString().startsWith("raw|")) { + console.log(data.toString().split("|")[1]); + return; + } + if (data.toString().startsWith("list|")) { + if (lmode != false) { + list = data.toString().split("|")[1].split(", "); + if (list.includes(lmode)) { + console.log(chalk.green("yes")); + } else { + console.log(chalk.yellow("no")); + } + } else { + console.log(data.toString().split("|")[1]); + } + commandline(); + return; + } + if (data.toString().startsWith("tagg|")) { + console.log(data.toString().split("|")[1]); + commandline(); + return; + } + if (data.toString().startsWith("aerp|")) { + console.log(data.toString().split("|")[1]); + commandline(); + return; + } + if (data.toString().startsWith("rlog|")) { + console.log(data.toString().split("|")[1]); + commandline(); + return; + } + if (data.toString().startsWith("srvo|")) { + parts = data.toString().split("|"); + parts.shift(); + + console.log(chalk.cyan.bold("os: ") + parts[0] + chalk.gray(" (" + parts[1] + ") ") + parts[2] + chalk.blue.bold(" @ " + parts[3])); + console.log(chalk.cyan.bold("ver: ") + chalk.magenta.bold("node: ") + parts[4] + "," + chalk.magenta.bold(" loto: ") + ver); + console.log(chalk.cyan.bold("mem: ") + chalk.magenta.bold("heap: ") + (parts[5] / 1024).toFixed(2) + "K/" + (parts[6] / 1024) + "K," + chalk.magenta.bold(" rss: ") + (parts[5] / 1024).toFixed(2) + "K"); + + commandline(); + return; + } + if (data.toString().startsWith("modc|")) { + console.log(data.toString().split("|")[1]); + commandline(); + return; + } + if (data.toString().startsWith("pok")) { + console.log(chalk.green("success")); + commandline(); + return; + } + if (data.toString().startsWith("sok")) { + connected = false; + console.log(chalk.green("Successfully stopped the server")); + process.exit(); + return; + } + if (data.toString().startsWith("stok") || data.toString().startsWith("msok") || data.toString().startsWith("stok") || data.toString().startsWith("udok")) { + console.log(chalk.green("success")); + commandline(); + return; + } + if (data.toString() == "ok" && authent) { + authent = false; + authspin.stop(); + console.log(chalk.blue.bold("I:") + " This server is running Bingoloto " + ver); + console.log("\nWelcome to Bingoloto shell!\nEnter 'h' to get help.\nEnter 'q' to close connection.\n"); + global.rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + commandline(); + return; + } else if (authent) { + console.log(chalk.red("\nFailed to authenticate, the server returned " + data.toString())); + process.exit(255); + return; + } +}); + +client.on('close', function() { + if (connected) { + console.log(chalk.red('\nConnection closed by remote peer')); + process.exit() + } +}); diff --git a/node_modules/@types/color-name/LICENSE b/node_modules/@types/color-name/LICENSE new file mode 100644 index 0000000..4b1ad51 --- /dev/null +++ b/node_modules/@types/color-name/LICENSE @@ -0,0 +1,21 @@ + MIT License
+
+ Copyright (c) Microsoft Corporation. All rights reserved.
+
+ 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/@types/color-name/README.md b/node_modules/@types/color-name/README.md new file mode 100644 index 0000000..5c77cba --- /dev/null +++ b/node_modules/@types/color-name/README.md @@ -0,0 +1,16 @@ +# Installation
+> `npm install --save @types/color-name`
+
+# Summary
+This package contains type definitions for color-name ( https://github.com/colorjs/color-name ).
+
+# Details
+Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/color-name
+
+Additional Details
+ * Last updated: Wed, 13 Feb 2019 16:16:48 GMT
+ * Dependencies: none
+ * Global values: none
+
+# Credits
+These definitions were written by Junyoung Clare Jang <https://github.com/Ailrun>.
diff --git a/node_modules/@types/color-name/index.d.ts b/node_modules/@types/color-name/index.d.ts new file mode 100644 index 0000000..b5bff47 --- /dev/null +++ b/node_modules/@types/color-name/index.d.ts @@ -0,0 +1,161 @@ +// Type definitions for color-name 1.1 +// Project: https://github.com/colorjs/color-name +// Definitions by: Junyoung Clare Jang <https://github.com/Ailrun> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Tuple of Red, Green, and Blue + * @example + * // Red = 55, Green = 70, Blue = 0 + * const rgb: RGB = [55, 70, 0]; + */ +export type RGB = [number, number, number]; + +export const aliceblue: RGB; +export const antiquewhite: RGB; +export const aqua: RGB; +export const aquamarine: RGB; +export const azure: RGB; +export const beige: RGB; +export const bisque: RGB; +export const black: RGB; +export const blanchedalmond: RGB; +export const blue: RGB; +export const blueviolet: RGB; +export const brown: RGB; +export const burlywood: RGB; +export const cadetblue: RGB; +export const chartreuse: RGB; +export const chocolate: RGB; +export const coral: RGB; +export const cornflowerblue: RGB; +export const cornsilk: RGB; +export const crimson: RGB; +export const cyan: RGB; +export const darkblue: RGB; +export const darkcyan: RGB; +export const darkgoldenrod: RGB; +export const darkgray: RGB; +export const darkgreen: RGB; +export const darkgrey: RGB; +export const darkkhaki: RGB; +export const darkmagenta: RGB; +export const darkolivegreen: RGB; +export const darkorange: RGB; +export const darkorchid: RGB; +export const darkred: RGB; +export const darksalmon: RGB; +export const darkseagreen: RGB; +export const darkslateblue: RGB; +export const darkslategray: RGB; +export const darkslategrey: RGB; +export const darkturquoise: RGB; +export const darkviolet: RGB; +export const deeppink: RGB; +export const deepskyblue: RGB; +export const dimgray: RGB; +export const dimgrey: RGB; +export const dodgerblue: RGB; +export const firebrick: RGB; +export const floralwhite: RGB; +export const forestgreen: RGB; +export const fuchsia: RGB; +export const gainsboro: RGB; +export const ghostwhite: RGB; +export const gold: RGB; +export const goldenrod: RGB; +export const gray: RGB; +export const green: RGB; +export const greenyellow: RGB; +export const grey: RGB; +export const honeydew: RGB; +export const hotpink: RGB; +export const indianred: RGB; +export const indigo: RGB; +export const ivory: RGB; +export const khaki: RGB; +export const lavender: RGB; +export const lavenderblush: RGB; +export const lawngreen: RGB; +export const lemonchiffon: RGB; +export const lightblue: RGB; +export const lightcoral: RGB; +export const lightcyan: RGB; +export const lightgoldenrodyellow: RGB; +export const lightgray: RGB; +export const lightgreen: RGB; +export const lightgrey: RGB; +export const lightpink: RGB; +export const lightsalmon: RGB; +export const lightseagreen: RGB; +export const lightskyblue: RGB; +export const lightslategray: RGB; +export const lightslategrey: RGB; +export const lightsteelblue: RGB; +export const lightyellow: RGB; +export const lime: RGB; +export const limegreen: RGB; +export const linen: RGB; +export const magenta: RGB; +export const maroon: RGB; +export const mediumaquamarine: RGB; +export const mediumblue: RGB; +export const mediumorchid: RGB; +export const mediumpurple: RGB; +export const mediumseagreen: RGB; +export const mediumslateblue: RGB; +export const mediumspringgreen: RGB; +export const mediumturquoise: RGB; +export const mediumvioletred: RGB; +export const midnightblue: RGB; +export const mintcream: RGB; +export const mistyrose: RGB; +export const moccasin: RGB; +export const navajowhite: RGB; +export const navy: RGB; +export const oldlace: RGB; +export const olive: RGB; +export const olivedrab: RGB; +export const orange: RGB; +export const orangered: RGB; +export const orchid: RGB; +export const palegoldenrod: RGB; +export const palegreen: RGB; +export const paleturquoise: RGB; +export const palevioletred: RGB; +export const papayawhip: RGB; +export const peachpuff: RGB; +export const peru: RGB; +export const pink: RGB; +export const plum: RGB; +export const powderblue: RGB; +export const purple: RGB; +export const rebeccapurple: RGB; +export const red: RGB; +export const rosybrown: RGB; +export const royalblue: RGB; +export const saddlebrown: RGB; +export const salmon: RGB; +export const sandybrown: RGB; +export const seagreen: RGB; +export const seashell: RGB; +export const sienna: RGB; +export const silver: RGB; +export const skyblue: RGB; +export const slateblue: RGB; +export const slategray: RGB; +export const slategrey: RGB; +export const snow: RGB; +export const springgreen: RGB; +export const steelblue: RGB; +export const tan: RGB; +export const teal: RGB; +export const thistle: RGB; +export const tomato: RGB; +export const turquoise: RGB; +export const violet: RGB; +export const wheat: RGB; +export const white: RGB; +export const whitesmoke: RGB; +export const yellow: RGB; +export const yellowgreen: RGB; diff --git a/node_modules/@types/color-name/package.json b/node_modules/@types/color-name/package.json new file mode 100644 index 0000000..e86d0db --- /dev/null +++ b/node_modules/@types/color-name/package.json @@ -0,0 +1,52 @@ +{ + "_from": "@types/color-name@^1.1.1", + "_id": "@types/color-name@1.1.1", + "_inBundle": false, + "_integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==", + "_location": "/@types/color-name", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "@types/color-name@^1.1.1", + "name": "@types/color-name", + "escapedName": "@types%2fcolor-name", + "scope": "@types", + "rawSpec": "^1.1.1", + "saveSpec": null, + "fetchSpec": "^1.1.1" + }, + "_requiredBy": [ + "/ansi-styles" + ], + "_resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", + "_shasum": "1c1261bbeaa10a8055bbc5d8ab84b7b2afc846a0", + "_spec": "@types/color-name@^1.1.1", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/ansi-styles", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Junyoung Clare Jang", + "url": "https://github.com/Ailrun" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "TypeScript definitions for color-name", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/color-name", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git" + }, + "scripts": {}, + "typeScriptVersion": "2.0", + "types": "index", + "typesPublisherContentHash": "e22c6881e2dcf766e32142cbb82d9acf9c08258bdf0da8e76c8a448d1be44ac7", + "version": "1.1.1" +} diff --git a/node_modules/ansi-regex/index.d.ts b/node_modules/ansi-regex/index.d.ts new file mode 100644 index 0000000..2dbf6af --- /dev/null +++ b/node_modules/ansi-regex/index.d.ts @@ -0,0 +1,37 @@ +declare namespace ansiRegex { + interface Options { + /** + Match only the first ANSI escape. + + @default false + */ + onlyFirst: boolean; + } +} + +/** +Regular expression for matching ANSI escape codes. + +@example +``` +import ansiRegex = require('ansi-regex'); + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` +*/ +declare function ansiRegex(options?: ansiRegex.Options): RegExp; + +export = ansiRegex; diff --git a/node_modules/ansi-regex/index.js b/node_modules/ansi-regex/index.js new file mode 100644 index 0000000..35054aa --- /dev/null +++ b/node_modules/ansi-regex/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = ({onlyFirst = false} = {}) => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +}; diff --git a/node_modules/ansi-regex/license b/node_modules/ansi-regex/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/ansi-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ansi-regex/package.json b/node_modules/ansi-regex/package.json new file mode 100644 index 0000000..2675c08 --- /dev/null +++ b/node_modules/ansi-regex/package.json @@ -0,0 +1,87 @@ +{ + "_from": "ansi-regex@^5.0.0", + "_id": "ansi-regex@5.0.0", + "_inBundle": false, + "_integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==", + "_location": "/ansi-regex", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "ansi-regex@^5.0.0", + "name": "ansi-regex", + "escapedName": "ansi-regex", + "rawSpec": "^5.0.0", + "saveSpec": null, + "fetchSpec": "^5.0.0" + }, + "_requiredBy": [ + "/strip-ansi" + ], + "_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "_shasum": "388539f55179bf39339c81af30a654d69f87cb75", + "_spec": "ansi-regex@^5.0.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/strip-ansi", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/chalk/ansi-regex/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Regular expression for matching ANSI escape codes", + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.9.0", + "xo": "^0.25.3" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/chalk/ansi-regex#readme", + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "license": "MIT", + "name": "ansi-regex", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/ansi-regex.git" + }, + "scripts": { + "test": "xo && ava && tsd", + "view-supported": "node fixtures/view-codes.js" + }, + "version": "5.0.0" +} diff --git a/node_modules/ansi-regex/readme.md b/node_modules/ansi-regex/readme.md new file mode 100644 index 0000000..3c2b77c --- /dev/null +++ b/node_modules/ansi-regex/readme.md @@ -0,0 +1,78 @@ +# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex) + +> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) + + +## Install + +``` +$ npm install ansi-regex +``` + + +## Usage + +```js +const ansiRegex = require('ansi-regex'); + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` + + +## API + +### ansiRegex(options?) + +Returns a regex for matching ANSI escape codes. + +#### options + +Type: `object` + +##### onlyFirst + +Type: `boolean`<br> +Default: `false` *(Matches any ANSI escape codes in a string)* + +Match only the first ANSI escape. + + +## FAQ + +### Why do you test for codes not in the ECMA 48 standard? + +Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. + +On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +--- + +<div align="center"> + <b> + <a href="https://tidelift.com/subscription/pkg/npm-ansi-regex?utm_source=npm-ansi-regex&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> + </b> + <br> + <sub> + Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. + </sub> +</div> diff --git a/node_modules/ansi-styles/index.d.ts b/node_modules/ansi-styles/index.d.ts new file mode 100644 index 0000000..7e9b2b7 --- /dev/null +++ b/node_modules/ansi-styles/index.d.ts @@ -0,0 +1,197 @@ +import * as cssColors from 'color-name'; + +declare namespace ansiStyles { + interface ColorConvert { + /** + The RGB color space. + + @param red - (`0`-`255`) + @param green - (`0`-`255`) + @param blue - (`0`-`255`) + */ + rgb(red: number, green: number, blue: number): string; + + /** + The RGB HEX color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hex(hex: string): string; + + /** + @param keyword - A CSS color name. + */ + keyword(keyword: keyof typeof cssColors): string; + + /** + The HSL color space. + + @param hue - (`0`-`360`) + @param saturation - (`0`-`100`) + @param lightness - (`0`-`100`) + */ + hsl(hue: number, saturation: number, lightness: number): string; + + /** + The HSV color space. + + @param hue - (`0`-`360`) + @param saturation - (`0`-`100`) + @param value - (`0`-`100`) + */ + hsv(hue: number, saturation: number, value: number): string; + + /** + The HSV color space. + + @param hue - (`0`-`360`) + @param whiteness - (`0`-`100`) + @param blackness - (`0`-`100`) + */ + hwb(hue: number, whiteness: number, blackness: number): string; + + /** + Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color. + */ + ansi(ansi: number): string; + + /** + Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. + */ + ansi256(ansi: number): string; + } + + interface CSPair { + /** + The ANSI terminal control sequence for starting this style. + */ + readonly open: string; + + /** + The ANSI terminal control sequence for ending this style. + */ + readonly close: string; + } + + interface ColorBase { + readonly ansi: ColorConvert; + readonly ansi256: ColorConvert; + readonly ansi16m: ColorConvert; + + /** + The ANSI terminal control sequence for ending this color. + */ + readonly close: string; + } + + interface Modifier { + /** + Resets the current color chain. + */ + readonly reset: CSPair; + + /** + Make text bold. + */ + readonly bold: CSPair; + + /** + Emitting only a small amount of light. + */ + readonly dim: CSPair; + + /** + Make text italic. (Not widely supported) + */ + readonly italic: CSPair; + + /** + Make text underline. (Not widely supported) + */ + readonly underline: CSPair; + + /** + Inverse background and foreground colors. + */ + readonly inverse: CSPair; + + /** + Prints the text, but makes it invisible. + */ + readonly hidden: CSPair; + + /** + Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: CSPair; + } + + interface ForegroundColor { + readonly black: CSPair; + readonly red: CSPair; + readonly green: CSPair; + readonly yellow: CSPair; + readonly blue: CSPair; + readonly cyan: CSPair; + readonly magenta: CSPair; + readonly white: CSPair; + + /** + Alias for `blackBright`. + */ + readonly gray: CSPair; + + /** + Alias for `blackBright`. + */ + readonly grey: CSPair; + + readonly blackBright: CSPair; + readonly redBright: CSPair; + readonly greenBright: CSPair; + readonly yellowBright: CSPair; + readonly blueBright: CSPair; + readonly cyanBright: CSPair; + readonly magentaBright: CSPair; + readonly whiteBright: CSPair; + } + + interface BackgroundColor { + readonly bgBlack: CSPair; + readonly bgRed: CSPair; + readonly bgGreen: CSPair; + readonly bgYellow: CSPair; + readonly bgBlue: CSPair; + readonly bgCyan: CSPair; + readonly bgMagenta: CSPair; + readonly bgWhite: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGray: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGrey: CSPair; + + readonly bgBlackBright: CSPair; + readonly bgRedBright: CSPair; + readonly bgGreenBright: CSPair; + readonly bgYellowBright: CSPair; + readonly bgBlueBright: CSPair; + readonly bgCyanBright: CSPair; + readonly bgMagentaBright: CSPair; + readonly bgWhiteBright: CSPair; + } +} + +declare const ansiStyles: { + readonly modifier: ansiStyles.Modifier; + readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase; + readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase; + readonly codes: ReadonlyMap<number, number>; +} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier; + +export = ansiStyles; diff --git a/node_modules/ansi-styles/index.js b/node_modules/ansi-styles/index.js new file mode 100644 index 0000000..5d82581 --- /dev/null +++ b/node_modules/ansi-styles/index.js @@ -0,0 +1,163 @@ +'use strict'; + +const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +const ansi2ansi = n => n; +const rgb2rgb = (r, g, b) => [r, g, b]; + +const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); + + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + + return value; + }, + enumerable: true, + configurable: true + }); +}; + +/** @type {typeof import('color-convert')} */ +let colorConvert; +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = require('color-convert'); + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } + + return styles; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); diff --git a/node_modules/ansi-styles/license b/node_modules/ansi-styles/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/ansi-styles/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/ansi-styles/package.json b/node_modules/ansi-styles/package.json new file mode 100644 index 0000000..81fff57 --- /dev/null +++ b/node_modules/ansi-styles/package.json @@ -0,0 +1,89 @@ +{ + "_from": "ansi-styles@^4.1.0", + "_id": "ansi-styles@4.2.1", + "_inBundle": false, + "_integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "_location": "/ansi-styles", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "ansi-styles@^4.1.0", + "name": "ansi-styles", + "escapedName": "ansi-styles", + "rawSpec": "^4.1.0", + "saveSpec": null, + "fetchSpec": "^4.1.0" + }, + "_requiredBy": [ + "/chalk" + ], + "_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "_shasum": "90ae75c424d008d2624c5bf29ead3177ebfcf359", + "_spec": "ansi-styles@^4.1.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/chalk", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/chalk/ansi-styles/issues" + }, + "bundleDependencies": false, + "dependencies": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + }, + "deprecated": false, + "description": "ANSI escape codes for styling strings in the terminal", + "devDependencies": { + "@types/color-convert": "^1.9.0", + "ava": "^2.3.0", + "svg-term-cli": "^2.1.1", + "tsd": "^0.11.0", + "xo": "^0.25.3" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "funding": "https://github.com/chalk/ansi-styles?sponsor=1", + "homepage": "https://github.com/chalk/ansi-styles#readme", + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "license": "MIT", + "name": "ansi-styles", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/ansi-styles.git" + }, + "scripts": { + "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor", + "test": "xo && ava && tsd" + }, + "version": "4.2.1" +} diff --git a/node_modules/ansi-styles/readme.md b/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000..2a1ef65 --- /dev/null +++ b/node_modules/ansi-styles/readme.md @@ -0,0 +1,158 @@ +# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) + +> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. + +<img src="screenshot.svg" width="900"> + +## Install + +``` +$ npm install ansi-styles +``` + +## Usage + +```js +const style = require('ansi-styles'); + +console.log(`${style.green.open}Hello world!${style.green.close}`); + + +// Color conversion between 16/256/truecolor +// NOTE: If conversion goes to 16 colors or 256 colors, the original color +// may be degraded to fit that color palette. This means terminals +// that do not support 16 million colors will best-match the +// original color. +console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); +console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); +console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close); +``` + +## API + +Each style has an `open` and `close` property. + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(Not widely supported)* +- `underline` +- `inverse` +- `hidden` +- `strikethrough` *(Not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `blackBright` (alias: `gray`, `grey`) +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` (alias: `bgGray`, `bgGrey`) +- `bgRedBright` +- `bgGreenBright` +- `bgYellowBright` +- `bgBlueBright` +- `bgMagentaBright` +- `bgCyanBright` +- `bgWhiteBright` + +## Advanced usage + +By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `style.modifier` +- `style.color` +- `style.bgColor` + +###### Example + +```js +console.log(style.color.green.open); +``` + +Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. + +###### Example + +```js +console.log(style.codes.get(36)); +//=> 39 +``` + +## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) + +`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. + +The following color spaces from `color-convert` are supported: + +- `rgb` +- `hex` +- `keyword` +- `hsl` +- `hsv` +- `hwb` +- `ansi` +- `ansi256` + +To use these, call the associated conversion function with the intended output, for example: + +```js +style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code +style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code + +style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code +style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code + +style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code +style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code +``` + +## Related + +- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + +--- + +<div align="center"> + <b> + <a href="https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> + </b> + <br> + <sub> + Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. + </sub> +</div> diff --git a/node_modules/async/.travis.yml b/node_modules/async/.travis.yml new file mode 100644 index 0000000..6064ca0 --- /dev/null +++ b/node_modules/async/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/async/LICENSE b/node_modules/async/LICENSE new file mode 100644 index 0000000..8f29698 --- /dev/null +++ b/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-2014 Caolan McMahon + +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/async/README.md b/node_modules/async/README.md new file mode 100644 index 0000000..6cfb922 --- /dev/null +++ b/node_modules/async/README.md @@ -0,0 +1,1647 @@ +# Async.js + +[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async) + + +Async is a utility module which provides straight-forward, powerful functions +for working with asynchronous JavaScript. Although originally designed for +use with [Node.js](http://nodejs.org) and installable via `npm install async`, +it can also be used directly in the browser. + +Async is also installable via: + +- [bower](http://bower.io/): `bower install async` +- [component](https://github.com/component/component): `component install + caolan/async` +- [jam](http://jamjs.org/): `jam install async` +- [spm](http://spmjs.io/): `spm install async` + +Async provides around 20 functions that include the usual 'functional' +suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns +for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these +functions assume you follow the Node.js convention of providing a single +callback as the last argument of your `async` function. + + +## Quick Examples + +```javascript +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); + +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); + +async.parallel([ + function(){ ... }, + function(){ ... } +], callback); + +async.series([ + function(){ ... }, + function(){ ... } +]); +``` + +There are many more functions available so take a look at the docs below for a +full list. This module aims to be comprehensive, so if you feel anything is +missing please create a GitHub issue for it. + +## Common Pitfalls + +### Binding a context to an iterator + +This section is really about `bind`, not about `async`. If you are wondering how to +make `async` execute your iterators in a given context, or are confused as to why +a method of another library isn't working as an iterator, study this example: + +```js +// Here is a simple object with an (unnecessarily roundabout) squaring method +var AsyncSquaringLibrary = { + squareExponent: 2, + square: function(number, callback){ + var result = Math.pow(number, this.squareExponent); + setTimeout(function(){ + callback(null, result); + }, 200); + } +}; + +async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){ + // result is [NaN, NaN, NaN] + // This fails because the `this.squareExponent` expression in the square + // function is not evaluated in the context of AsyncSquaringLibrary, and is + // therefore undefined. +}); + +async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){ + // result is [1, 4, 9] + // With the help of bind we can attach a context to the iterator before + // passing it to async. Now the square function will be executed in its + // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent` + // will be as expected. +}); +``` + +## Download + +The source is available for download from +[GitHub](http://github.com/caolan/async). +Alternatively, you can install using Node Package Manager (`npm`): + + npm install async + +__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed + +## In the Browser + +So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. + +Usage: + +```html +<script type="text/javascript" src="async.js"></script> +<script type="text/javascript"> + + async.map(data, asyncProcess, function(err, results){ + alert(results); + }); + +</script> +``` + +## Documentation + +### Collections + +* [`each`](#each) +* [`eachSeries`](#eachSeries) +* [`eachLimit`](#eachLimit) +* [`map`](#map) +* [`mapSeries`](#mapSeries) +* [`mapLimit`](#mapLimit) +* [`filter`](#filter) +* [`filterSeries`](#filterSeries) +* [`reject`](#reject) +* [`rejectSeries`](#rejectSeries) +* [`reduce`](#reduce) +* [`reduceRight`](#reduceRight) +* [`detect`](#detect) +* [`detectSeries`](#detectSeries) +* [`sortBy`](#sortBy) +* [`some`](#some) +* [`every`](#every) +* [`concat`](#concat) +* [`concatSeries`](#concatSeries) + +### Control Flow + +* [`series`](#seriestasks-callback) +* [`parallel`](#parallel) +* [`parallelLimit`](#parallellimittasks-limit-callback) +* [`whilst`](#whilst) +* [`doWhilst`](#doWhilst) +* [`until`](#until) +* [`doUntil`](#doUntil) +* [`forever`](#forever) +* [`waterfall`](#waterfall) +* [`compose`](#compose) +* [`seq`](#seq) +* [`applyEach`](#applyEach) +* [`applyEachSeries`](#applyEachSeries) +* [`queue`](#queue) +* [`priorityQueue`](#priorityQueue) +* [`cargo`](#cargo) +* [`auto`](#auto) +* [`retry`](#retry) +* [`iterator`](#iterator) +* [`apply`](#apply) +* [`nextTick`](#nextTick) +* [`times`](#times) +* [`timesSeries`](#timesSeries) + +### Utils + +* [`memoize`](#memoize) +* [`unmemoize`](#unmemoize) +* [`log`](#log) +* [`dir`](#dir) +* [`noConflict`](#noConflict) + + +## Collections + +<a name="forEach" /> +<a name="each" /> +### each(arr, iterator, callback) + +Applies the function `iterator` to each item in `arr`, in parallel. +The `iterator` is called with an item from the list, and a callback for when it +has finished. If the `iterator` passes an error to its `callback`, the main +`callback` (for the `each` function) is immediately called with the error. + +Note, that since this function applies `iterator` to each item in parallel, +there is no guarantee that the iterator functions will complete in order. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the `callback` should be run without + arguments or with an explicit `null` argument. +* `callback(err)` - A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Examples__ + + +```js +// assuming openFiles is an array of file names and saveFile is a function +// to save the modified contents of that file: + +async.each(openFiles, saveFile, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +```js +// assuming openFiles is an array of file names + +async.each(openFiles, function(file, callback) { + + // Perform operation on file here. + console.log('Processing file ' + file); + + if( file.length > 32 ) { + console.log('This file name is too long'); + callback('File name too long'); + } else { + // Do work to process file here + console.log('File processed'); + callback(); + } +}, function(err){ + // if any of the file processing produced an error, err would equal that error + if( err ) { + // One of the iterations produced an error. + // All processing will now stop. + console.log('A file failed to process'); + } else { + console.log('All files have been processed successfully'); + } +}); +``` + +--------------------------------------- + +<a name="forEachSeries" /> +<a name="eachSeries" /> +### eachSeries(arr, iterator, callback) + +The same as [`each`](#each), only `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +This means the `iterator` functions will complete in order. + + +--------------------------------------- + +<a name="forEachLimit" /> +<a name="eachLimit" /> +### eachLimit(arr, limit, iterator, callback) + +The same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously +running at any time. + +Note that the items in `arr` are not processed in batches, so there is no guarantee that +the first `limit` `iterator` functions will complete before any others are started. + +__Arguments__ + +* `arr` - An array to iterate over. +* `limit` - The maximum number of `iterator`s to run at any time. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the callback should be run without + arguments or with an explicit `null` argument. +* `callback(err)` - A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Example__ + +```js +// Assume documents is an array of JSON objects and requestApi is a +// function that interacts with a rate-limited REST api. + +async.eachLimit(documents, 20, requestApi, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +--------------------------------------- + +<a name="map" /> +### map(arr, iterator, callback) + +Produces a new array of values by mapping each value in `arr` through +the `iterator` function. The `iterator` is called with an item from `arr` and a +callback for when it has finished processing. Each of these callback takes 2 arguments: +an `error`, and the transformed item from `arr`. If `iterator` passes an error to his +callback, the main `callback` (for the `map` function) is immediately called with the error. + +Note, that since this function applies the `iterator` to each item in parallel, +there is no guarantee that the `iterator` functions will complete in order. +However, the results array will be in the same order as the original `arr`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - A callback which is called when all `iterator` + functions have finished, or an error occurs. Results is an array of the + transformed items from the `arr`. + +__Example__ + +```js +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +--------------------------------------- + +<a name="mapSeries" /> +### mapSeries(arr, iterator, callback) + +The same as [`map`](#map), only the `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + + +--------------------------------------- + +<a name="mapLimit" /> +### mapLimit(arr, limit, iterator, callback) + +The same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously +running at any time. + +Note that the items are not processed in batches, so there is no guarantee that +the first `limit` `iterator` functions will complete before any others are started. + +__Arguments__ + +* `arr` - An array to iterate over. +* `limit` - The maximum number of `iterator`s to run at any time. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - A callback which is called when all `iterator` + calls have finished, or an error occurs. The result is an array of the + transformed items from the original `arr`. + +__Example__ + +```js +async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +--------------------------------------- + +<a name="select" /> +<a name="filter" /> +### filter(arr, iterator, callback) + +__Alias:__ `select` + +Returns a new array of all the values in `arr` which pass an async truth test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. This operation is +performed in parallel, but the results array will be in the same order as the +original. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The `iterator` is passed a `callback(truthValue)`, which must be called with a + boolean argument once it has completed. +* `callback(results)` - A callback which is called after all the `iterator` + functions have finished. + +__Example__ + +```js +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); +``` + +--------------------------------------- + +<a name="selectSeries" /> +<a name="filterSeries" /> +### filterSeries(arr, iterator, callback) + +__Alias:__ `selectSeries` + +The same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + +--------------------------------------- + +<a name="reject" /> +### reject(arr, iterator, callback) + +The opposite of [`filter`](#filter). Removes values that pass an `async` truth test. + +--------------------------------------- + +<a name="rejectSeries" /> +### rejectSeries(arr, iterator, callback) + +The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr` +in series. + + +--------------------------------------- + +<a name="reduce" /> +### reduce(arr, memo, iterator, callback) + +__Aliases:__ `inject`, `foldl` + +Reduces `arr` into a single value using an async `iterator` to return +each successive step. `memo` is the initial state of the reduction. +This function only operates in series. + +For performance reasons, it may make sense to split a call to this function into +a parallel map, and then use the normal `Array.prototype.reduce` on the results. +This function is for situations where each step in the reduction needs to be async; +if you can get the data before reducing it, then it's probably a good idea to do so. + +__Arguments__ + +* `arr` - An array to iterate over. +* `memo` - The initial state of the reduction. +* `iterator(memo, item, callback)` - A function applied to each item in the + array to produce the next step in the reduction. The `iterator` is passed a + `callback(err, reduction)` which accepts an optional error as its first + argument, and the state of the reduction as the second. If an error is + passed to the callback, the reduction is stopped and the main `callback` is + immediately called with the error. +* `callback(err, result)` - A callback which is called after all the `iterator` + functions have finished. Result is the reduced value. + +__Example__ + +```js +async.reduce([1,2,3], 0, function(memo, item, callback){ + // pointless async: + process.nextTick(function(){ + callback(null, memo + item) + }); +}, function(err, result){ + // result is now equal to the last value of memo, which is 6 +}); +``` + +--------------------------------------- + +<a name="reduceRight" /> +### reduceRight(arr, memo, iterator, callback) + +__Alias:__ `foldr` + +Same as [`reduce`](#reduce), only operates on `arr` in reverse order. + + +--------------------------------------- + +<a name="detect" /> +### detect(arr, iterator, callback) + +Returns the first value in `arr` that passes an async truth test. The +`iterator` is applied in parallel, meaning the first iterator to return `true` will +fire the detect `callback` with that result. That means the result might not be +the first item in the original `arr` (in terms of order) that passes the test. + +If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries). + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The iterator is passed a `callback(truthValue)` which must be called with a + boolean argument once it has completed. +* `callback(result)` - A callback which is called as soon as any iterator returns + `true`, or after all the `iterator` functions have finished. Result will be + the first item in the array that passes the truth test (iterator) or the + value `undefined` if none passed. + +__Example__ + +```js +async.detect(['file1','file2','file3'], fs.exists, function(result){ + // result now equals the first file in the list that exists +}); +``` + +--------------------------------------- + +<a name="detectSeries" /> +### detectSeries(arr, iterator, callback) + +The same as [`detect`](#detect), only the `iterator` is applied to each item in `arr` +in series. This means the result is always the first in the original `arr` (in +terms of array order) that passes the truth test. + + +--------------------------------------- + +<a name="sortBy" /> +### sortBy(arr, iterator, callback) + +Sorts a list by the results of running each `arr` value through an async `iterator`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, sortValue)` which must be called once it + has completed with an error (which can be `null`) and a value to use as the sort + criteria. +* `callback(err, results)` - A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is the items from + the original `arr` sorted by the values returned by the `iterator` calls. + +__Example__ + +```js +async.sortBy(['file1','file2','file3'], function(file, callback){ + fs.stat(file, function(err, stats){ + callback(err, stats.mtime); + }); +}, function(err, results){ + // results is now the original array of files sorted by + // modified date +}); +``` + +__Sort Order__ + +By modifying the callback parameter the sorting order can be influenced: + +```js +//ascending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x); +}, function(err,result){ + //result callback +} ); + +//descending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x*-1); //<- x*-1 instead of x, turns the order around +}, function(err,result){ + //result callback +} ); +``` + +--------------------------------------- + +<a name="some" /> +### some(arr, iterator, callback) + +__Alias:__ `any` + +Returns `true` if at least one element in the `arr` satisfies an async test. +_The callback for each iterator call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. Once any iterator +call returns `true`, the main `callback` is immediately called. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a callback(truthValue) which must be + called with a boolean argument once it has completed. +* `callback(result)` - A callback which is called as soon as any iterator returns + `true`, or after all the iterator functions have finished. Result will be + either `true` or `false` depending on the values of the async tests. + +__Example__ + +```js +async.some(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then at least one of the files exists +}); +``` + +--------------------------------------- + +<a name="every" /> +### every(arr, iterator, callback) + +__Alias:__ `all` + +Returns `true` if every element in `arr` satisfies an async test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a callback(truthValue) which must be + called with a boolean argument once it has completed. +* `callback(result)` - A callback which is called after all the `iterator` + functions have finished. Result will be either `true` or `false` depending on + the values of the async tests. + +__Example__ + +```js +async.every(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then every file exists +}); +``` + +--------------------------------------- + +<a name="concat" /> +### concat(arr, iterator, callback) + +Applies `iterator` to each item in `arr`, concatenating the results. Returns the +concatenated list. The `iterator`s are called in parallel, and the results are +concatenated as they return. There is no guarantee that the results array will +be returned in the original order of `arr` passed to the `iterator` function. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, results)` which must be called once it + has completed with an error (which can be `null`) and an array of results. +* `callback(err, results)` - A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is an array containing + the concatenated results of the `iterator` function. + +__Example__ + +```js +async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ + // files is now a list of filenames that exist in the 3 directories +}); +``` + +--------------------------------------- + +<a name="concatSeries" /> +### concatSeries(arr, iterator, callback) + +Same as [`concat`](#concat), but executes in series instead of parallel. + + +## Control Flow + +<a name="series" /> +### series(tasks, [callback]) + +Run the functions in the `tasks` array in series, each one running once the previous +function has completed. If any functions in the series pass an error to its +callback, no more functions are run, and `callback` is immediately called with the value of the error. +Otherwise, `callback` receives an array of results when `tasks` have completed. + +It is also possible to use an object instead of an array. Each property will be +run as a function, and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`series`](#series). + +**Note** that while many implementations preserve the order of object properties, the +[ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) +explicitly states that + +> The mechanics and order of enumerating the properties is not specified. + +So if you rely on the order in which your series of functions are executed, and want +this to work on all platforms, consider using an array. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +__Example__ + +```js +async.series([ + function(callback){ + // do some stuff ... + callback(null, 'one'); + }, + function(callback){ + // do some more stuff ... + callback(null, 'two'); + } +], +// optional callback +function(err, results){ + // results is now equal to ['one', 'two'] +}); + + +// an example using an object instead of an array +async.series({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equal to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + +<a name="parallel" /> +### parallel(tasks, [callback]) + +Run the `tasks` array of functions in parallel, without waiting until the previous +function has completed. If any of the functions pass an error to its +callback, the main `callback` is immediately called with the value of the error. +Once the `tasks` have completed, the results are passed to the final `callback` as an +array. + +It is also possible to use an object instead of an array. Each property will be +run as a function and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`parallel`](#parallel). + + +__Arguments__ + +* `tasks` - An array or object containing functions to run. Each function is passed + a `callback(err, result)` which it must call on completion with an error `err` + (which can be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the task callbacks. + +__Example__ + +```js +async.parallel([ + function(callback){ + setTimeout(function(){ + callback(null, 'one'); + }, 200); + }, + function(callback){ + setTimeout(function(){ + callback(null, 'two'); + }, 100); + } +], +// optional callback +function(err, results){ + // the results array will equal ['one','two'] even though + // the second function had a shorter timeout. +}); + + +// an example using an object instead of an array +async.parallel({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equals to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + +<a name="parallelLimit" /> +### parallelLimit(tasks, limit, [callback]) + +The same as [`parallel`](#parallel), only `tasks` are executed in parallel +with a maximum of `limit` tasks executing at any time. + +Note that the `tasks` are not executed in batches, so there is no guarantee that +the first `limit` tasks will complete before any others are started. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `limit` - The maximum number of `tasks` to run at any time. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +--------------------------------------- + +<a name="whilst" /> +### whilst(test, fn, callback) + +Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +__Arguments__ + +* `test()` - synchronous truth test to perform before each execution of `fn`. +* `fn(callback)` - A function which is called each time `test` passes. The function is + passed a `callback(err)`, which must be called once it has completed with an + optional `err` argument. +* `callback(err)` - A callback which is called after the test fails and repeated + execution of `fn` has stopped. + +__Example__ + +```js +var count = 0; + +async.whilst( + function () { return count < 5; }, + function (callback) { + count++; + setTimeout(callback, 1000); + }, + function (err) { + // 5 seconds have passed + } +); +``` + +--------------------------------------- + +<a name="doWhilst" /> +### doWhilst(fn, test, callback) + +The post-check version of [`whilst`](#whilst). To reflect the difference in +the order of operations, the arguments `test` and `fn` are switched. + +`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + +--------------------------------------- + +<a name="until" /> +### until(test, fn, callback) + +Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +The inverse of [`whilst`](#whilst). + +--------------------------------------- + +<a name="doUntil" /> +### doUntil(fn, test, callback) + +Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`. + +--------------------------------------- + +<a name="forever" /> +### forever(fn, errback) + +Calls the asynchronous function `fn` with a callback parameter that allows it to +call itself again, in series, indefinitely. + +If an error is passed to the callback then `errback` is called with the +error, and execution stops, otherwise it will never be called. + +```js +async.forever( + function(next) { + // next is suitable for passing to things that need a callback(err [, whatever]); + // it will result in this function being called again. + }, + function(err) { + // if next is called with a value in its first parameter, it will appear + // in here as 'err', and execution will stop. + } +); +``` + +--------------------------------------- + +<a name="waterfall" /> +### waterfall(tasks, [callback]) + +Runs the `tasks` array of functions in series, each passing their results to the next in +the array. However, if any of the `tasks` pass an error to their own callback, the +next function is not executed, and the main `callback` is immediately called with +the error. + +__Arguments__ + +* `tasks` - An array of functions to run, each function is passed a + `callback(err, result1, result2, ...)` it must call on completion. The first + argument is an error (which can be `null`) and any further arguments will be + passed as arguments in order to the next task. +* `callback(err, [results])` - An optional callback to run once all the functions + have completed. This will be passed the results of the last task's callback. + + + +__Example__ + +```js +async.waterfall([ + function(callback) { + callback(null, 'one', 'two'); + }, + function(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); + }, + function(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); + } +], function (err, result) { + // result now equals 'done' +}); +``` + +--------------------------------------- +<a name="compose" /> +### compose(fn1, fn2...) + +Creates a function which is a composition of the passed asynchronous +functions. Each function consumes the return value of the function that +follows. Composing functions `f()`, `g()`, and `h()` would produce the result of +`f(g(h()))`, only this version uses callbacks to obtain the return values. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* `functions...` - the asynchronous functions to compose + + +__Example__ + +```js +function add1(n, callback) { + setTimeout(function () { + callback(null, n + 1); + }, 10); +} + +function mul3(n, callback) { + setTimeout(function () { + callback(null, n * 3); + }, 10); +} + +var add1mul3 = async.compose(mul3, add1); + +add1mul3(4, function (err, result) { + // result now equals 15 +}); +``` + +--------------------------------------- +<a name="seq" /> +### seq(fn1, fn2...) + +Version of the compose function that is more natural to read. +Each function consumes the return value of the previous function. +It is the equivalent of [`compose`](#compose) with the arguments reversed. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* functions... - the asynchronous functions to compose + + +__Example__ + +```js +// Requires lodash (or underscore), express3 and dresende's orm2. +// Part of an app, that fetches cats of the logged user. +// This example uses `seq` function to avoid overnesting and error +// handling clutter. +app.get('/cats', function(request, response) { + var User = request.models.User; + async.seq( + _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + function(user, fn) { + user.getCats(fn); // 'getCats' has signature (callback(err, data)) + } + )(req.session.user_id, function (err, cats) { + if (err) { + console.error(err); + response.json({ status: 'error', message: err.message }); + } else { + response.json({ status: 'ok', message: 'Cats found', data: cats }); + } + }); +}); +``` + +--------------------------------------- +<a name="applyEach" /> +### applyEach(fns, args..., callback) + +Applies the provided arguments to each function in the array, calling +`callback` after all functions have completed. If you only provide the first +argument, then it will return a function which lets you pass in the +arguments as if it were a single function call. + +__Arguments__ + +* `fns` - the asynchronous functions to all call with the same arguments +* `args...` - any number of separate arguments to pass to the function +* `callback` - the final argument should be the callback, called when all + functions have completed processing + + +__Example__ + +```js +async.applyEach([enableSearch, updateSchema], 'bucket', callback); + +// partial application example: +async.each( + buckets, + async.applyEach([enableSearch, updateSchema]), + callback +); +``` + +--------------------------------------- + +<a name="applyEachSeries" /> +### applyEachSeries(arr, iterator, callback) + +The same as [`applyEach`](#applyEach) only the functions are applied in series. + +--------------------------------------- + +<a name="queue" /> +### queue(worker, concurrency) + +Creates a `queue` object with the specified `concurrency`. Tasks added to the +`queue` are processed in parallel (up to the `concurrency` limit). If all +`worker`s are in progress, the task is queued until one becomes available. +Once a `worker` completes a `task`, that `task`'s callback is called. + +__Arguments__ + +* `worker(task, callback)` - An asynchronous function for processing a queued + task, which must call its `callback(err)` argument when finished, with an + optional `error` as an argument. +* `concurrency` - An `integer` for determining how many `worker` functions should be + run in parallel. + +__Queue objects__ + +The `queue` object returned by this function has the following properties and +methods: + +* `length()` - a function returning the number of items waiting to be processed. +* `started` - a function returning whether or not any items have been pushed and processed by the queue +* `running()` - a function returning the number of items currently being processed. +* `idle()` - a function returning false if there are items waiting or being processed, or true if not. +* `concurrency` - an integer for determining how many `worker` functions should be + run in parallel. This property can be changed after a `queue` is created to + alter the concurrency on-the-fly. +* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once + the `worker` has finished processing the task. Instead of a single task, a `tasks` array + can be submitted. The respective callback is used for every task in the list. +* `unshift(task, [callback])` - add a new task to the front of the `queue`. +* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, + and further tasks will be queued. +* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`. +* `paused` - a boolean for determining whether the queue is in a paused state +* `pause()` - a function that pauses the processing of tasks until `resume()` is called. +* `resume()` - a function that resumes the processing of queued tasks when the queue is paused. +* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle. + +__Example__ + +```js +// create a queue object with concurrency 2 + +var q = async.queue(function (task, callback) { + console.log('hello ' + task.name); + callback(); +}, 2); + + +// assign a callback +q.drain = function() { + console.log('all items have been processed'); +} + +// add some items to the queue + +q.push({name: 'foo'}, function (err) { + console.log('finished processing foo'); +}); +q.push({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); + +// add some items to the queue (batch-wise) + +q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { + console.log('finished processing item'); +}); + +// add some items to the front of the queue + +q.unshift({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); +``` + + +--------------------------------------- + +<a name="priorityQueue" /> +### priorityQueue(worker, concurrency) + +The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects: + +* `push(task, priority, [callback])` - `priority` should be a number. If an array of + `tasks` is given, all tasks will be assigned the same priority. +* The `unshift` method was removed. + +--------------------------------------- + +<a name="cargo" /> +### cargo(worker, [payload]) + +Creates a `cargo` object with the specified payload. Tasks added to the +cargo will be processed altogether (up to the `payload` limit). If the +`worker` is in progress, the task is queued until it becomes available. Once +the `worker` has completed some tasks, each callback of those tasks is called. +Check out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work. + +While [queue](#queue) passes only one task to one of a group of workers +at a time, cargo passes an array of tasks to a single worker, repeating +when the worker is finished. + +__Arguments__ + +* `worker(tasks, callback)` - An asynchronous function for processing an array of + queued tasks, which must call its `callback(err)` argument when finished, with + an optional `err` argument. +* `payload` - An optional `integer` for determining how many tasks should be + processed per round; if omitted, the default is unlimited. + +__Cargo objects__ + +The `cargo` object returned by this function has the following properties and +methods: + +* `length()` - A function returning the number of items waiting to be processed. +* `payload` - An `integer` for determining how many tasks should be + process per round. This property can be changed after a `cargo` is created to + alter the payload on-the-fly. +* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called + once the `worker` has finished processing the task. Instead of a single task, an array of `tasks` + can be submitted. The respective callback is used for every task in the list. +* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued. +* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`. + +__Example__ + +```js +// create a cargo object with payload 2 + +var cargo = async.cargo(function (tasks, callback) { + for(var i=0; i<tasks.length; i++){ + console.log('hello ' + tasks[i].name); + } + callback(); +}, 2); + + +// add some items + +cargo.push({name: 'foo'}, function (err) { + console.log('finished processing foo'); +}); +cargo.push({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); +cargo.push({name: 'baz'}, function (err) { + console.log('finished processing baz'); +}); +``` + +--------------------------------------- + +<a name="auto" /> +### auto(tasks, [callback]) + +Determines the best order for running the functions in `tasks`, based on their +requirements. Each function can optionally depend on other functions being completed +first, and each function is run as soon as its requirements are satisfied. + +If any of the functions pass an error to their callback, it will not +complete (so any other functions depending on it will not run), and the main +`callback` is immediately called with the error. Functions also receive an +object containing the results of functions which have completed so far. + +Note, all functions are called with a `results` object as a second argument, +so it is unsafe to pass functions in the `tasks` object which cannot handle the +extra argument. + +For example, this snippet of code: + +```js +async.auto({ + readData: async.apply(fs.readFile, 'data.txt', 'utf-8') +}, callback); +``` + +will have the effect of calling `readFile` with the results object as the last +argument, which will fail: + +```js +fs.readFile('data.txt', 'utf-8', cb, {}); +``` + +Instead, wrap the call to `readFile` in a function which does not forward the +`results` object: + +```js +async.auto({ + readData: function(cb, results){ + fs.readFile('data.txt', 'utf-8', cb); + } +}, callback); +``` + +__Arguments__ + +* `tasks` - An object. Each of its properties is either a function or an array of + requirements, with the function itself the last item in the array. The object's key + of a property serves as the name of the task defined by that property, + i.e. can be used when specifying requirements for other tasks. + The function receives two arguments: (1) a `callback(err, result)` which must be + called when finished, passing an `error` (which can be `null`) and the result of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions. +* `callback(err, results)` - An optional callback which is called when all the + tasks have been completed. It receives the `err` argument if any `tasks` + pass an error to their callback. Results are always returned; however, if + an error occurs, no further `tasks` will be performed, and the results + object will only contain partial results. + + +__Example__ + +```js +async.auto({ + get_data: function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + make_folder: function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + }, + write_file: ['get_data', 'make_folder', function(callback, results){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + callback(null, 'filename'); + }], + email_link: ['write_file', function(callback, results){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + // results.write_file contains the filename returned by write_file. + callback(null, {'file':results.write_file, 'email':'user@example.com'}); + }] +}, function(err, results) { + console.log('err = ', err); + console.log('results = ', results); +}); +``` + +This is a fairly trivial example, but to do this using the basic parallel and +series functions would look like this: + +```js +async.parallel([ + function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + } +], +function(err, results){ + async.series([ + function(callback){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + results.push('filename'); + callback(null); + }, + function(callback){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + callback(null, {'file':results.pop(), 'email':'user@example.com'}); + } + ]); +}); +``` + +For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding +new tasks much easier (and the code more readable). + + +--------------------------------------- + +<a name="retry" /> +### retry([times = 5], task, [callback]) + +Attempts to get a successful response from `task` no more than `times` times before +returning an error. If the task is successful, the `callback` will be passed the result +of the successful task. If all attempts fail, the callback will be passed the error and +result (if any) of the final attempt. + +__Arguments__ + +* `times` - An integer indicating how many times to attempt the `task` before giving up. Defaults to 5. +* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)` + which must be called when finished, passing `err` (which can be `null`) and the `result` of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions (if nested inside another control flow). +* `callback(err, results)` - An optional callback which is called when the + task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`. + +The [`retry`](#retry) function can be used as a stand-alone control flow by passing a +callback, as shown below: + +```js +async.retry(3, apiMethod, function(err, result) { + // do something with the result +}); +``` + +It can also be embeded within other control flow functions to retry individual methods +that are not as reliable, like this: + +```js +async.auto({ + users: api.getUsers.bind(api), + payments: async.retry(3, api.getPayments.bind(api)) +}, function(err, results) { + // do something with the results +}); +``` + + +--------------------------------------- + +<a name="iterator" /> +### iterator(tasks) + +Creates an iterator function which calls the next function in the `tasks` array, +returning a continuation to call the next one after that. It's also possible to +“peek” at the next iterator with `iterator.next()`. + +This function is used internally by the `async` module, but can be useful when +you want to manually control the flow of functions in series. + +__Arguments__ + +* `tasks` - An array of functions to run. + +__Example__ + +```js +var iterator = async.iterator([ + function(){ sys.p('one'); }, + function(){ sys.p('two'); }, + function(){ sys.p('three'); } +]); + +node> var iterator2 = iterator(); +'one' +node> var iterator3 = iterator2(); +'two' +node> iterator3(); +'three' +node> var nextfn = iterator2.next(); +node> nextfn(); +'three' +``` + +--------------------------------------- + +<a name="apply" /> +### apply(function, arguments..) + +Creates a continuation function with some arguments already applied. + +Useful as a shorthand when combined with other control flow functions. Any arguments +passed to the returned function are added to the arguments originally passed +to apply. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to automatically apply when the + continuation is called. + +__Example__ + +```js +// using apply + +async.parallel([ + async.apply(fs.writeFile, 'testfile1', 'test1'), + async.apply(fs.writeFile, 'testfile2', 'test2'), +]); + + +// the same process without using apply + +async.parallel([ + function(callback){ + fs.writeFile('testfile1', 'test1', callback); + }, + function(callback){ + fs.writeFile('testfile2', 'test2', callback); + } +]); +``` + +It's possible to pass any number of additional arguments when calling the +continuation: + +```js +node> var fn = async.apply(sys.puts, 'one'); +node> fn('two', 'three'); +one +two +three +``` + +--------------------------------------- + +<a name="nextTick" /> +### nextTick(callback), setImmediate(callback) + +Calls `callback` on a later loop around the event loop. In Node.js this just +calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)` +if available, otherwise `setTimeout(callback, 0)`, which means other higher priority +events may precede the execution of `callback`. + +This is used internally for browser-compatibility purposes. + +__Arguments__ + +* `callback` - The function to call on a later loop around the event loop. + +__Example__ + +```js +var call_order = []; +async.nextTick(function(){ + call_order.push('two'); + // call_order now equals ['one','two'] +}); +call_order.push('one') +``` + +<a name="times" /> +### times(n, callback) + +Calls the `callback` function `n` times, and accumulates results in the same manner +you would use with [`map`](#map). + +__Arguments__ + +* `n` - The number of times to run the function. +* `callback` - The function to call `n` times. + +__Example__ + +```js +// Pretend this is some complicated async factory +var createUser = function(id, callback) { + callback(null, { + id: 'user' + id + }) +} +// generate 5 users +async.times(5, function(n, next){ + createUser(n, function(err, user) { + next(err, user) + }) +}, function(err, users) { + // we should now have 5 users +}); +``` + +<a name="timesSeries" /> +### timesSeries(n, callback) + +The same as [`times`](#times), only the iterator is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + + +## Utils + +<a name="memoize" /> +### memoize(fn, [hasher]) + +Caches the results of an `async` function. When creating a hash to store function +results against, the callback is omitted from the hash and an optional hash +function can be used. + +The cache of results is exposed as the `memo` property of the function returned +by `memoize`. + +__Arguments__ + +* `fn` - The function to proxy and cache results from. +* `hasher` - Tn optional function for generating a custom hash for storing + results. It has all the arguments applied to it apart from the callback, and + must be synchronous. + +__Example__ + +```js +var slow_fn = function (name, callback) { + // do something + callback(null, result); +}; +var fn = async.memoize(slow_fn); + +// fn can now be used as if it were slow_fn +fn('some name', function () { + // callback +}); +``` + +<a name="unmemoize" /> +### unmemoize(fn) + +Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized +form. Handy for testing. + +__Arguments__ + +* `fn` - the memoized function + +<a name="log" /> +### log(function, arguments) + +Logs the result of an `async` function to the `console`. Only works in Node.js or +in browsers that support `console.log` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.log` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, 'hello ' + name); + }, 1000); +}; +``` +```js +node> async.log(hello, 'world'); +'hello world' +``` + +--------------------------------------- + +<a name="dir" /> +### dir(function, arguments) + +Logs the result of an `async` function to the `console` using `console.dir` to +display the properties of the resulting object. Only works in Node.js or +in browsers that support `console.dir` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.dir` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, {hello: name}); + }, 1000); +}; +``` +```js +node> async.dir(hello, 'world'); +{hello: 'world'} +``` + +--------------------------------------- + +<a name="noConflict" /> +### noConflict() + +Changes the value of `async` back to its original value, returning a reference to the +`async` object. diff --git a/node_modules/async/bower.json b/node_modules/async/bower.json new file mode 100644 index 0000000..1817688 --- /dev/null +++ b/node_modules/async/bower.json @@ -0,0 +1,38 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "0.9.2", + "main": "lib/async.js", + "keywords": [ + "async", + "callback", + "utility", + "module" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/caolan/async.git" + }, + "devDependencies": { + "nodeunit": ">0.0.0", + "uglify-js": "1.2.x", + "nodelint": ">0.0.0", + "lodash": ">=2.4.1" + }, + "moduleType": [ + "amd", + "globals", + "node" + ], + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ], + "authors": [ + "Caolan McMahon" + ] +}
\ No newline at end of file diff --git a/node_modules/async/component.json b/node_modules/async/component.json new file mode 100644 index 0000000..5003a7c --- /dev/null +++ b/node_modules/async/component.json @@ -0,0 +1,16 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "0.9.2", + "keywords": [ + "async", + "callback", + "utility", + "module" + ], + "license": "MIT", + "repository": "caolan/async", + "scripts": [ + "lib/async.js" + ] +}
\ No newline at end of file diff --git a/node_modules/async/lib/async.js b/node_modules/async/lib/async.js new file mode 100644 index 0000000..394c41c --- /dev/null +++ b/node_modules/async/lib/async.js @@ -0,0 +1,1123 @@ +/*! + * async + * https://github.com/caolan/async + * + * Copyright 2010-2014 Caolan McMahon + * Released under the MIT license + */ +/*jshint onevar: false, indent:4 */ +/*global setImmediate: false, setTimeout: false, console: false */ +(function () { + + var async = {}; + + // global on the server, window in the browser + var root, previous_async; + + root = this; + if (root != null) { + previous_async = root.async; + } + + async.noConflict = function () { + root.async = previous_async; + return async; + }; + + function only_once(fn) { + var called = false; + return function() { + if (called) throw new Error("Callback was already called."); + called = true; + fn.apply(root, arguments); + } + } + + //// cross-browser compatiblity functions //// + + var _toString = Object.prototype.toString; + + var _isArray = Array.isArray || function (obj) { + return _toString.call(obj) === '[object Array]'; + }; + + var _each = function (arr, iterator) { + for (var i = 0; i < arr.length; i += 1) { + iterator(arr[i], i, arr); + } + }; + + var _map = function (arr, iterator) { + if (arr.map) { + return arr.map(iterator); + } + var results = []; + _each(arr, function (x, i, a) { + results.push(iterator(x, i, a)); + }); + return results; + }; + + var _reduce = function (arr, iterator, memo) { + if (arr.reduce) { + return arr.reduce(iterator, memo); + } + _each(arr, function (x, i, a) { + memo = iterator(memo, x, i, a); + }); + return memo; + }; + + var _keys = function (obj) { + if (Object.keys) { + return Object.keys(obj); + } + var keys = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + }; + + //// exported async module functions //// + + //// nextTick implementation with browser-compatible fallback //// + if (typeof process === 'undefined' || !(process.nextTick)) { + if (typeof setImmediate === 'function') { + async.nextTick = function (fn) { + // not a direct alias for IE10 compatibility + setImmediate(fn); + }; + async.setImmediate = async.nextTick; + } + else { + async.nextTick = function (fn) { + setTimeout(fn, 0); + }; + async.setImmediate = async.nextTick; + } + } + else { + async.nextTick = process.nextTick; + if (typeof setImmediate !== 'undefined') { + async.setImmediate = function (fn) { + // not a direct alias for IE10 compatibility + setImmediate(fn); + }; + } + else { + async.setImmediate = async.nextTick; + } + } + + async.each = function (arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length) { + return callback(); + } + var completed = 0; + _each(arr, function (x) { + iterator(x, only_once(done) ); + }); + function done(err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(); + } + } + } + }; + async.forEach = async.each; + + async.eachSeries = function (arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length) { + return callback(); + } + var completed = 0; + var iterate = function () { + iterator(arr[completed], function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(); + } + else { + iterate(); + } + } + }); + }; + iterate(); + }; + async.forEachSeries = async.eachSeries; + + async.eachLimit = function (arr, limit, iterator, callback) { + var fn = _eachLimit(limit); + fn.apply(null, [arr, iterator, callback]); + }; + async.forEachLimit = async.eachLimit; + + var _eachLimit = function (limit) { + + return function (arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length || limit <= 0) { + return callback(); + } + var completed = 0; + var started = 0; + var running = 0; + + (function replenish () { + if (completed >= arr.length) { + return callback(); + } + + while (running < limit && started < arr.length) { + started += 1; + running += 1; + iterator(arr[started - 1], function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + running -= 1; + if (completed >= arr.length) { + callback(); + } + else { + replenish(); + } + } + }); + } + })(); + }; + }; + + + var doParallel = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [async.each].concat(args)); + }; + }; + var doParallelLimit = function(limit, fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [_eachLimit(limit)].concat(args)); + }; + }; + var doSeries = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [async.eachSeries].concat(args)); + }; + }; + + + var _asyncMap = function (eachfn, arr, iterator, callback) { + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + if (!callback) { + eachfn(arr, function (x, callback) { + iterator(x.value, function (err) { + callback(err); + }); + }); + } else { + var results = []; + eachfn(arr, function (x, callback) { + iterator(x.value, function (err, v) { + results[x.index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + async.map = doParallel(_asyncMap); + async.mapSeries = doSeries(_asyncMap); + async.mapLimit = function (arr, limit, iterator, callback) { + return _mapLimit(limit)(arr, iterator, callback); + }; + + var _mapLimit = function(limit) { + return doParallelLimit(limit, _asyncMap); + }; + + // reduce only has a series version, as doing reduce in parallel won't + // work in many situations. + async.reduce = function (arr, memo, iterator, callback) { + async.eachSeries(arr, function (x, callback) { + iterator(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); + }; + // inject alias + async.inject = async.reduce; + // foldl alias + async.foldl = async.reduce; + + async.reduceRight = function (arr, memo, iterator, callback) { + var reversed = _map(arr, function (x) { + return x; + }).reverse(); + async.reduce(reversed, memo, iterator, callback); + }; + // foldr alias + async.foldr = async.reduceRight; + + var _filter = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.filter = doParallel(_filter); + async.filterSeries = doSeries(_filter); + // select alias + async.select = async.filter; + async.selectSeries = async.filterSeries; + + var _reject = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (!v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.reject = doParallel(_reject); + async.rejectSeries = doSeries(_reject); + + var _detect = function (eachfn, arr, iterator, main_callback) { + eachfn(arr, function (x, callback) { + iterator(x, function (result) { + if (result) { + main_callback(x); + main_callback = function () {}; + } + else { + callback(); + } + }); + }, function (err) { + main_callback(); + }); + }; + async.detect = doParallel(_detect); + async.detectSeries = doSeries(_detect); + + async.some = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (v) { + main_callback(true); + main_callback = function () {}; + } + callback(); + }); + }, function (err) { + main_callback(false); + }); + }; + // any alias + async.any = async.some; + + async.every = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (!v) { + main_callback(false); + main_callback = function () {}; + } + callback(); + }); + }, function (err) { + main_callback(true); + }); + }; + // all alias + async.all = async.every; + + async.sortBy = function (arr, iterator, callback) { + async.map(arr, function (x, callback) { + iterator(x, function (err, criteria) { + if (err) { + callback(err); + } + else { + callback(null, {value: x, criteria: criteria}); + } + }); + }, function (err, results) { + if (err) { + return callback(err); + } + else { + var fn = function (left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }; + callback(null, _map(results.sort(fn), function (x) { + return x.value; + })); + } + }); + }; + + async.auto = function (tasks, callback) { + callback = callback || function () {}; + var keys = _keys(tasks); + var remainingTasks = keys.length + if (!remainingTasks) { + return callback(); + } + + var results = {}; + + var listeners = []; + var addListener = function (fn) { + listeners.unshift(fn); + }; + var removeListener = function (fn) { + for (var i = 0; i < listeners.length; i += 1) { + if (listeners[i] === fn) { + listeners.splice(i, 1); + return; + } + } + }; + var taskComplete = function () { + remainingTasks-- + _each(listeners.slice(0), function (fn) { + fn(); + }); + }; + + addListener(function () { + if (!remainingTasks) { + var theCallback = callback; + // prevent final callback from calling itself if it errors + callback = function () {}; + + theCallback(null, results); + } + }); + + _each(keys, function (k) { + var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; + var taskCallback = function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + if (err) { + var safeResults = {}; + _each(_keys(results), function(rkey) { + safeResults[rkey] = results[rkey]; + }); + safeResults[k] = args; + callback(err, safeResults); + // stop subsequent errors hitting callback multiple times + callback = function () {}; + } + else { + results[k] = args; + async.setImmediate(taskComplete); + } + }; + var requires = task.slice(0, Math.abs(task.length - 1)) || []; + var ready = function () { + return _reduce(requires, function (a, x) { + return (a && results.hasOwnProperty(x)); + }, true) && !results.hasOwnProperty(k); + }; + if (ready()) { + task[task.length - 1](taskCallback, results); + } + else { + var listener = function () { + if (ready()) { + removeListener(listener); + task[task.length - 1](taskCallback, results); + } + }; + addListener(listener); + } + }); + }; + + async.retry = function(times, task, callback) { + var DEFAULT_TIMES = 5; + var attempts = []; + // Use defaults if times not passed + if (typeof times === 'function') { + callback = task; + task = times; + times = DEFAULT_TIMES; + } + // Make sure times is a number + times = parseInt(times, 10) || DEFAULT_TIMES; + var wrappedTask = function(wrappedCallback, wrappedResults) { + var retryAttempt = function(task, finalAttempt) { + return function(seriesCallback) { + task(function(err, result){ + seriesCallback(!err || finalAttempt, {err: err, result: result}); + }, wrappedResults); + }; + }; + while (times) { + attempts.push(retryAttempt(task, !(times-=1))); + } + async.series(attempts, function(done, data){ + data = data[data.length - 1]; + (wrappedCallback || callback)(data.err, data.result); + }); + } + // If a callback is passed, run this as a controll flow + return callback ? wrappedTask() : wrappedTask + }; + + async.waterfall = function (tasks, callback) { + callback = callback || function () {}; + if (!_isArray(tasks)) { + var err = new Error('First argument to waterfall must be an array of functions'); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + var wrapIterator = function (iterator) { + return function (err) { + if (err) { + callback.apply(null, arguments); + callback = function () {}; + } + else { + var args = Array.prototype.slice.call(arguments, 1); + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } + else { + args.push(callback); + } + async.setImmediate(function () { + iterator.apply(null, args); + }); + } + }; + }; + wrapIterator(async.iterator(tasks))(); + }; + + var _parallel = function(eachfn, tasks, callback) { + callback = callback || function () {}; + if (_isArray(tasks)) { + eachfn.map(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + eachfn.each(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.parallel = function (tasks, callback) { + _parallel({ map: async.map, each: async.each }, tasks, callback); + }; + + async.parallelLimit = function(tasks, limit, callback) { + _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); + }; + + async.series = function (tasks, callback) { + callback = callback || function () {}; + if (_isArray(tasks)) { + async.mapSeries(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + async.eachSeries(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.iterator = function (tasks) { + var makeCallback = function (index) { + var fn = function () { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + }; + fn.next = function () { + return (index < tasks.length - 1) ? makeCallback(index + 1): null; + }; + return fn; + }; + return makeCallback(0); + }; + + async.apply = function (fn) { + var args = Array.prototype.slice.call(arguments, 1); + return function () { + return fn.apply( + null, args.concat(Array.prototype.slice.call(arguments)) + ); + }; + }; + + var _concat = function (eachfn, arr, fn, callback) { + var r = []; + eachfn(arr, function (x, cb) { + fn(x, function (err, y) { + r = r.concat(y || []); + cb(err); + }); + }, function (err) { + callback(err, r); + }); + }; + async.concat = doParallel(_concat); + async.concatSeries = doSeries(_concat); + + async.whilst = function (test, iterator, callback) { + if (test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.whilst(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doWhilst = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + var args = Array.prototype.slice.call(arguments, 1); + if (test.apply(null, args)) { + async.doWhilst(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.until = function (test, iterator, callback) { + if (!test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.until(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doUntil = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + var args = Array.prototype.slice.call(arguments, 1); + if (!test.apply(null, args)) { + async.doUntil(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.queue = function (worker, concurrency) { + if (concurrency === undefined) { + concurrency = 1; + } + function _insert(q, data, pos, callback) { + if (!q.started){ + q.started = true; + } + if (!_isArray(data)) { + data = [data]; + } + if(data.length == 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + if (q.drain) { + q.drain(); + } + }); + } + _each(data, function(task) { + var item = { + data: task, + callback: typeof callback === 'function' ? callback : null + }; + + if (pos) { + q.tasks.unshift(item); + } else { + q.tasks.push(item); + } + + if (q.saturated && q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + var workers = 0; + var q = { + tasks: [], + concurrency: concurrency, + saturated: null, + empty: null, + drain: null, + started: false, + paused: false, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + kill: function () { + q.drain = null; + q.tasks = []; + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + if (!q.paused && workers < q.concurrency && q.tasks.length) { + var task = q.tasks.shift(); + if (q.empty && q.tasks.length === 0) { + q.empty(); + } + workers += 1; + var next = function () { + workers -= 1; + if (task.callback) { + task.callback.apply(task, arguments); + } + if (q.drain && q.tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + var cb = only_once(next); + worker(task.data, cb); + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + }, + idle: function() { + return q.tasks.length + workers === 0; + }, + pause: function () { + if (q.paused === true) { return; } + q.paused = true; + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= q.concurrency; w++) { + async.setImmediate(q.process); + } + } + }; + return q; + }; + + async.priorityQueue = function (worker, concurrency) { + + function _compareTasks(a, b){ + return a.priority - b.priority; + }; + + function _binarySearch(sequence, item, compare) { + var beg = -1, + end = sequence.length - 1; + while (beg < end) { + var mid = beg + ((end - beg + 1) >>> 1); + if (compare(item, sequence[mid]) >= 0) { + beg = mid; + } else { + end = mid - 1; + } + } + return beg; + } + + function _insert(q, data, priority, callback) { + if (!q.started){ + q.started = true; + } + if (!_isArray(data)) { + data = [data]; + } + if(data.length == 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + if (q.drain) { + q.drain(); + } + }); + } + _each(data, function(task) { + var item = { + data: task, + priority: priority, + callback: typeof callback === 'function' ? callback : null + }; + + q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); + + if (q.saturated && q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + // Start with a normal queue + var q = async.queue(worker, concurrency); + + // Override push to accept second parameter representing priority + q.push = function (data, priority, callback) { + _insert(q, data, priority, callback); + }; + + // Remove unshift function + delete q.unshift; + + return q; + }; + + async.cargo = function (worker, payload) { + var working = false, + tasks = []; + + var cargo = { + tasks: tasks, + payload: payload, + saturated: null, + empty: null, + drain: null, + drained: true, + push: function (data, callback) { + if (!_isArray(data)) { + data = [data]; + } + _each(data, function(task) { + tasks.push({ + data: task, + callback: typeof callback === 'function' ? callback : null + }); + cargo.drained = false; + if (cargo.saturated && tasks.length === payload) { + cargo.saturated(); + } + }); + async.setImmediate(cargo.process); + }, + process: function process() { + if (working) return; + if (tasks.length === 0) { + if(cargo.drain && !cargo.drained) cargo.drain(); + cargo.drained = true; + return; + } + + var ts = typeof payload === 'number' + ? tasks.splice(0, payload) + : tasks.splice(0, tasks.length); + + var ds = _map(ts, function (task) { + return task.data; + }); + + if(cargo.empty) cargo.empty(); + working = true; + worker(ds, function () { + working = false; + + var args = arguments; + _each(ts, function (data) { + if (data.callback) { + data.callback.apply(null, args); + } + }); + + process(); + }); + }, + length: function () { + return tasks.length; + }, + running: function () { + return working; + } + }; + return cargo; + }; + + var _console_fn = function (name) { + return function (fn) { + var args = Array.prototype.slice.call(arguments, 1); + fn.apply(null, args.concat([function (err) { + var args = Array.prototype.slice.call(arguments, 1); + if (typeof console !== 'undefined') { + if (err) { + if (console.error) { + console.error(err); + } + } + else if (console[name]) { + _each(args, function (x) { + console[name](x); + }); + } + } + }])); + }; + }; + async.log = _console_fn('log'); + async.dir = _console_fn('dir'); + /*async.info = _console_fn('info'); + async.warn = _console_fn('warn'); + async.error = _console_fn('error');*/ + + async.memoize = function (fn, hasher) { + var memo = {}; + var queues = {}; + hasher = hasher || function (x) { + return x; + }; + var memoized = function () { + var args = Array.prototype.slice.call(arguments); + var callback = args.pop(); + var key = hasher.apply(null, args); + if (key in memo) { + async.nextTick(function () { + callback.apply(null, memo[key]); + }); + } + else if (key in queues) { + queues[key].push(callback); + } + else { + queues[key] = [callback]; + fn.apply(null, args.concat([function () { + memo[key] = arguments; + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, arguments); + } + }])); + } + }; + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + }; + + async.unmemoize = function (fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + }; + + async.times = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.map(counter, iterator, callback); + }; + + async.timesSeries = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.mapSeries(counter, iterator, callback); + }; + + async.seq = function (/* functions... */) { + var fns = arguments; + return function () { + var that = this; + var args = Array.prototype.slice.call(arguments); + var callback = args.pop(); + async.reduce(fns, args, function (newargs, fn, cb) { + fn.apply(that, newargs.concat([function () { + var err = arguments[0]; + var nextargs = Array.prototype.slice.call(arguments, 1); + cb(err, nextargs); + }])) + }, + function (err, results) { + callback.apply(that, [err].concat(results)); + }); + }; + }; + + async.compose = function (/* functions... */) { + return async.seq.apply(null, Array.prototype.reverse.call(arguments)); + }; + + var _applyEach = function (eachfn, fns /*args...*/) { + var go = function () { + var that = this; + var args = Array.prototype.slice.call(arguments); + var callback = args.pop(); + return eachfn(fns, function (fn, cb) { + fn.apply(that, args.concat([cb])); + }, + callback); + }; + if (arguments.length > 2) { + var args = Array.prototype.slice.call(arguments, 2); + return go.apply(this, args); + } + else { + return go; + } + }; + async.applyEach = doParallel(_applyEach); + async.applyEachSeries = doSeries(_applyEach); + + async.forever = function (fn, callback) { + function next(err) { + if (err) { + if (callback) { + return callback(err); + } + throw err; + } + fn(next); + } + next(); + }; + + // Node.js + if (typeof module !== 'undefined' && module.exports) { + module.exports = async; + } + // AMD / RequireJS + else if (typeof define !== 'undefined' && define.amd) { + define([], function () { + return async; + }); + } + // included directly via <script> tag + else { + root.async = async; + } + +}()); diff --git a/node_modules/async/package.json b/node_modules/async/package.json new file mode 100644 index 0000000..1c2e567 --- /dev/null +++ b/node_modules/async/package.json @@ -0,0 +1,82 @@ +{ + "_from": "async@~0.9.0", + "_id": "async@0.9.2", + "_inBundle": false, + "_integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=", + "_location": "/async", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "async@~0.9.0", + "name": "async", + "escapedName": "async", + "rawSpec": "~0.9.0", + "saveSpec": null, + "fetchSpec": "~0.9.0" + }, + "_requiredBy": [ + "/utile" + ], + "_resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", + "_shasum": "aea74d5e61c1f899613bf64bda66d4c78f2fd17d", + "_spec": "async@~0.9.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/utile", + "author": { + "name": "Caolan McMahon" + }, + "bugs": { + "url": "https://github.com/caolan/async/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Higher-order functions and common patterns for asynchronous code", + "devDependencies": { + "lodash": ">=2.4.1", + "nodelint": ">0.0.0", + "nodeunit": ">0.0.0", + "uglify-js": "1.2.x" + }, + "homepage": "https://github.com/caolan/async#readme", + "jam": { + "main": "lib/async.js", + "include": [ + "lib/async.js", + "README.md", + "LICENSE" + ], + "categories": [ + "Utilities" + ] + }, + "keywords": [ + "async", + "callback", + "utility", + "module" + ], + "license": "MIT", + "main": "lib/async.js", + "name": "async", + "repository": { + "type": "git", + "url": "git+https://github.com/caolan/async.git" + }, + "scripts": { + "test": "nodeunit test/test-async.js" + }, + "spm": { + "main": "lib/async.js" + }, + "version": "0.9.2", + "volo": { + "main": "lib/async.js", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] + } +} diff --git a/node_modules/async/support/sync-package-managers.js b/node_modules/async/support/sync-package-managers.js new file mode 100644 index 0000000..30cb7c2 --- /dev/null +++ b/node_modules/async/support/sync-package-managers.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node + +// This should probably be its own module but complaints about bower/etc. +// support keep coming up and I'd rather just enable the workflow here for now +// and figure out where this should live later. -- @beaugunderson + +var fs = require('fs'); +var _ = require('lodash'); + +var packageJson = require('../package.json'); + +var IGNORES = ['**/.*', 'node_modules', 'bower_components', 'test', 'tests']; +var INCLUDES = ['lib/async.js', 'README.md', 'LICENSE']; +var REPOSITORY_NAME = 'caolan/async'; + +packageJson.jam = { + main: packageJson.main, + include: INCLUDES, + categories: ['Utilities'] +}; + +packageJson.spm = { + main: packageJson.main +}; + +packageJson.volo = { + main: packageJson.main, + ignore: IGNORES +}; + +var bowerSpecific = { + moduleType: ['amd', 'globals', 'node'], + ignore: IGNORES, + authors: [packageJson.author] +}; + +var bowerInclude = ['name', 'description', 'version', 'main', 'keywords', + 'license', 'homepage', 'repository', 'devDependencies']; + +var componentSpecific = { + repository: REPOSITORY_NAME, + scripts: [packageJson.main] +}; + +var componentInclude = ['name', 'description', 'version', 'keywords', + 'license']; + +var bowerJson = _.merge({}, _.pick(packageJson, bowerInclude), bowerSpecific); +var componentJson = _.merge({}, _.pick(packageJson, componentInclude), componentSpecific); + +fs.writeFileSync('./bower.json', JSON.stringify(bowerJson, null, 2)); +fs.writeFileSync('./component.json', JSON.stringify(componentJson, null, 2)); +fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, 2)); diff --git a/node_modules/balanced-match/.npmignore b/node_modules/balanced-match/.npmignore new file mode 100644 index 0000000..ae5d8c3 --- /dev/null +++ b/node_modules/balanced-match/.npmignore @@ -0,0 +1,5 @@ +test +.gitignore +.travis.yml +Makefile +example.js diff --git a/node_modules/balanced-match/LICENSE.md b/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000..2cdc8e4 --- /dev/null +++ b/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. diff --git a/node_modules/balanced-match/README.md b/node_modules/balanced-match/README.md new file mode 100644 index 0000000..08e918c --- /dev/null +++ b/node_modules/balanced-match/README.md @@ -0,0 +1,91 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ <a index>, <b index> ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. diff --git a/node_modules/balanced-match/index.js b/node_modules/balanced-match/index.js new file mode 100644 index 0000000..1685a76 --- /dev/null +++ b/node_modules/balanced-match/index.js @@ -0,0 +1,59 @@ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/node_modules/balanced-match/package.json b/node_modules/balanced-match/package.json new file mode 100644 index 0000000..ea50a54 --- /dev/null +++ b/node_modules/balanced-match/package.json @@ -0,0 +1,77 @@ +{ + "_from": "balanced-match@^1.0.0", + "_id": "balanced-match@1.0.0", + "_inBundle": false, + "_integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "_location": "/balanced-match", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "balanced-match@^1.0.0", + "name": "balanced-match", + "escapedName": "balanced-match", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/brace-expansion" + ], + "_resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "_shasum": "89b4d199ab2bee49de164ea02b89ce462d71b767", + "_spec": "balanced-match@^1.0.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/brace-expansion", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/balanced-match/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "license": "MIT", + "main": "index.js", + "name": "balanced-match", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "scripts": { + "bench": "make bench", + "test": "make test" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.0.0" +} diff --git a/node_modules/brace-expansion/LICENSE b/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. diff --git a/node_modules/brace-expansion/README.md b/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..6b4e0e1 --- /dev/null +++ b/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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. diff --git a/node_modules/brace-expansion/index.js b/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..0478be8 --- /dev/null +++ b/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..135eb45 --- /dev/null +++ b/node_modules/brace-expansion/package.json @@ -0,0 +1,75 @@ +{ + "_from": "brace-expansion@^1.1.7", + "_id": "brace-expansion@1.1.11", + "_inBundle": false, + "_integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "_location": "/brace-expansion", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "brace-expansion@^1.1.7", + "name": "brace-expansion", + "escapedName": "brace-expansion", + "rawSpec": "^1.1.7", + "saveSpec": null, + "fetchSpec": "^1.1.7" + }, + "_requiredBy": [ + "/minimatch" + ], + "_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "_shasum": "3c7fcbf529d87226f3d2f52b966ff5271eb441dd", + "_spec": "brace-expansion@^1.1.7", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/minimatch", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/brace-expansion/issues" + }, + "bundleDependencies": false, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "deprecated": false, + "description": "Brace expansion as known from sh/bash", + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "keywords": [], + "license": "MIT", + "main": "index.js", + "name": "brace-expansion", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "scripts": { + "bench": "matcha test/perf/bench.js", + "gentest": "bash test/generate.sh", + "test": "tape test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.1.11" +} diff --git a/node_modules/chalk/index.d.ts b/node_modules/chalk/index.d.ts new file mode 100644 index 0000000..9cd88f3 --- /dev/null +++ b/node_modules/chalk/index.d.ts @@ -0,0 +1,415 @@ +/** +Basic foreground colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type ForegroundColor = + | 'black' + | 'red' + | 'green' + | 'yellow' + | 'blue' + | 'magenta' + | 'cyan' + | 'white' + | 'gray' + | 'grey' + | 'blackBright' + | 'redBright' + | 'greenBright' + | 'yellowBright' + | 'blueBright' + | 'magentaBright' + | 'cyanBright' + | 'whiteBright'; + +/** +Basic background colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type BackgroundColor = + | 'bgBlack' + | 'bgRed' + | 'bgGreen' + | 'bgYellow' + | 'bgBlue' + | 'bgMagenta' + | 'bgCyan' + | 'bgWhite' + | 'bgGray' + | 'bgGrey' + | 'bgBlackBright' + | 'bgRedBright' + | 'bgGreenBright' + | 'bgYellowBright' + | 'bgBlueBright' + | 'bgMagentaBright' + | 'bgCyanBright' + | 'bgWhiteBright'; + +/** +Basic colors. + +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support) +*/ +declare type Color = ForegroundColor | BackgroundColor; + +declare type Modifiers = + | 'reset' + | 'bold' + | 'dim' + | 'italic' + | 'underline' + | 'inverse' + | 'hidden' + | 'strikethrough' + | 'visible'; + +declare namespace chalk { + /** + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + type Level = 0 | 1 | 2 | 3; + + interface Options { + /** + Specify the color support for Chalk. + + By default, color support is automatically detected based on the environment. + + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + level?: Level; + } + + /** + Return a new Chalk instance. + */ + type Instance = new (options?: Options) => Chalk; + + /** + Detect whether the terminal supports color. + */ + interface ColorSupport { + /** + The color level used by Chalk. + */ + level: Level; + + /** + Return whether Chalk supports basic 16 colors. + */ + hasBasic: boolean; + + /** + Return whether Chalk supports ANSI 256 colors. + */ + has256: boolean; + + /** + Return whether Chalk supports Truecolor 16 million colors. + */ + has16m: boolean; + } + + interface ChalkFunction { + /** + Use a template string. + + @remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341)) + + @example + ``` + import chalk = require('chalk'); + + log(chalk` + CPU: {red ${cpu.totalPercent}%} + RAM: {green ${ram.used / ram.total * 100}%} + DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} + `); + ``` + + @example + ``` + import chalk = require('chalk'); + + log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`) + ``` + */ + (text: TemplateStringsArray, ...placeholders: unknown[]): string; + + (...text: unknown[]): string; + } + + interface Chalk extends ChalkFunction { + /** + Return a new Chalk instance. + */ + Instance: Instance; + + /** + The color support for Chalk. + + By default, color support is automatically detected based on the environment. + + Levels: + - `0` - All colors disabled. + - `1` - Basic 16 colors support. + - `2` - ANSI 256 colors support. + - `3` - Truecolor 16 million colors support. + */ + level: Level; + + /** + Use HEX value to set text color. + + @param color - Hexadecimal value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.hex('#DEADED'); + ``` + */ + hex(color: string): Chalk; + + /** + Use keyword color value to set text color. + + @param color - Keyword value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.keyword('orange'); + ``` + */ + keyword(color: string): Chalk; + + /** + Use RGB values to set text color. + */ + rgb(red: number, green: number, blue: number): Chalk; + + /** + Use HSL values to set text color. + */ + hsl(hue: number, saturation: number, lightness: number): Chalk; + + /** + Use HSV values to set text color. + */ + hsv(hue: number, saturation: number, value: number): Chalk; + + /** + Use HWB values to set text color. + */ + hwb(hue: number, whiteness: number, blackness: number): Chalk; + + /** + Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color. + + 30 <= code && code < 38 || 90 <= code && code < 98 + For example, 31 for red, 91 for redBright. + */ + ansi(code: number): Chalk; + + /** + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. + */ + ansi256(index: number): Chalk; + + /** + Use HEX value to set background color. + + @param color - Hexadecimal value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.bgHex('#DEADED'); + ``` + */ + bgHex(color: string): Chalk; + + /** + Use keyword color value to set background color. + + @param color - Keyword value representing the desired color. + + @example + ``` + import chalk = require('chalk'); + + chalk.bgKeyword('orange'); + ``` + */ + bgKeyword(color: string): Chalk; + + /** + Use RGB values to set background color. + */ + bgRgb(red: number, green: number, blue: number): Chalk; + + /** + Use HSL values to set background color. + */ + bgHsl(hue: number, saturation: number, lightness: number): Chalk; + + /** + Use HSV values to set background color. + */ + bgHsv(hue: number, saturation: number, value: number): Chalk; + + /** + Use HWB values to set background color. + */ + bgHwb(hue: number, whiteness: number, blackness: number): Chalk; + + /** + Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color. + + 30 <= code && code < 38 || 90 <= code && code < 98 + For example, 31 for red, 91 for redBright. + Use the foreground code, not the background code (for example, not 41, nor 101). + */ + bgAnsi(code: number): Chalk; + + /** + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color. + */ + bgAnsi256(index: number): Chalk; + + /** + Modifier: Resets the current color chain. + */ + readonly reset: Chalk; + + /** + Modifier: Make text bold. + */ + readonly bold: Chalk; + + /** + Modifier: Emitting only a small amount of light. + */ + readonly dim: Chalk; + + /** + Modifier: Make text italic. (Not widely supported) + */ + readonly italic: Chalk; + + /** + Modifier: Make text underline. (Not widely supported) + */ + readonly underline: Chalk; + + /** + Modifier: Inverse background and foreground colors. + */ + readonly inverse: Chalk; + + /** + Modifier: Prints the text, but makes it invisible. + */ + readonly hidden: Chalk; + + /** + Modifier: Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: Chalk; + + /** + Modifier: Prints the text only when Chalk has a color support level > 0. + Can be useful for things that are purely cosmetic. + */ + readonly visible: Chalk; + + readonly black: Chalk; + readonly red: Chalk; + readonly green: Chalk; + readonly yellow: Chalk; + readonly blue: Chalk; + readonly magenta: Chalk; + readonly cyan: Chalk; + readonly white: Chalk; + + /* + Alias for `blackBright`. + */ + readonly gray: Chalk; + + /* + Alias for `blackBright`. + */ + readonly grey: Chalk; + + readonly blackBright: Chalk; + readonly redBright: Chalk; + readonly greenBright: Chalk; + readonly yellowBright: Chalk; + readonly blueBright: Chalk; + readonly magentaBright: Chalk; + readonly cyanBright: Chalk; + readonly whiteBright: Chalk; + + readonly bgBlack: Chalk; + readonly bgRed: Chalk; + readonly bgGreen: Chalk; + readonly bgYellow: Chalk; + readonly bgBlue: Chalk; + readonly bgMagenta: Chalk; + readonly bgCyan: Chalk; + readonly bgWhite: Chalk; + + /* + Alias for `bgBlackBright`. + */ + readonly bgGray: Chalk; + + /* + Alias for `bgBlackBright`. + */ + readonly bgGrey: Chalk; + + readonly bgBlackBright: Chalk; + readonly bgRedBright: Chalk; + readonly bgGreenBright: Chalk; + readonly bgYellowBright: Chalk; + readonly bgBlueBright: Chalk; + readonly bgMagentaBright: Chalk; + readonly bgCyanBright: Chalk; + readonly bgWhiteBright: Chalk; + } +} + +/** +Main Chalk object that allows to chain styles together. +Call the last one as a method with a string argument. +Order doesn't matter, and later styles take precedent in case of a conflict. +This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. +*/ +declare const chalk: chalk.Chalk & chalk.ChalkFunction & { + supportsColor: chalk.ColorSupport | false; + Level: chalk.Level; + Color: Color; + ForegroundColor: ForegroundColor; + BackgroundColor: BackgroundColor; + Modifiers: Modifiers; + stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false}; +}; + +export = chalk; diff --git a/node_modules/chalk/license b/node_modules/chalk/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/chalk/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/chalk/package.json b/node_modules/chalk/package.json new file mode 100644 index 0000000..4f153b5 --- /dev/null +++ b/node_modules/chalk/package.json @@ -0,0 +1,103 @@ +{ + "_from": "chalk", + "_id": "chalk@4.1.0", + "_inBundle": false, + "_integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "_location": "/chalk", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "chalk", + "name": "chalk", + "escapedName": "chalk", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/", + "/log-symbols", + "/ora" + ], + "_resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "_shasum": "4e14870a618d9e2edd97dd8345fd9d9dc315646a", + "_spec": "chalk", + "_where": "/data/dev/Projets/Bingoloto Remote", + "bugs": { + "url": "https://github.com/chalk/chalk/issues" + }, + "bundleDependencies": false, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "deprecated": false, + "description": "Terminal string styling done right", + "devDependencies": { + "ava": "^2.4.0", + "coveralls": "^3.0.7", + "execa": "^4.0.0", + "import-fresh": "^3.1.0", + "matcha": "^0.7.0", + "nyc": "^15.0.0", + "resolve-from": "^5.0.0", + "tsd": "^0.7.4", + "xo": "^0.28.2" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "source", + "index.d.ts" + ], + "funding": "https://github.com/chalk/chalk?sponsor=1", + "homepage": "https://github.com/chalk/chalk#readme", + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "str", + "ansi", + "style", + "styles", + "tty", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "license": "MIT", + "main": "source", + "name": "chalk", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/chalk.git" + }, + "scripts": { + "bench": "matcha benchmark.js", + "test": "xo && nyc ava && tsd" + }, + "version": "4.1.0", + "xo": { + "rules": { + "unicorn/prefer-string-slice": "off", + "unicorn/prefer-includes": "off", + "@typescript-eslint/member-ordering": "off", + "no-redeclare": "off", + "unicorn/string-content": "off", + "unicorn/better-regex": "off" + } + } +} diff --git a/node_modules/chalk/readme.md b/node_modules/chalk/readme.md new file mode 100644 index 0000000..338f42c --- /dev/null +++ b/node_modules/chalk/readme.md @@ -0,0 +1,293 @@ +<h1 align="center"> + <br> + <br> + <img width="320" src="media/logo.svg" alt="Chalk"> + <br> + <br> + <br> +</h1> + +> Terminal string styling done right + +[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk) + +<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900"> + +## Highlights + +- Expressive API +- Highly performant +- Ability to nest styles +- [256/Truecolor color support](#256-and-truecolor-color-support) +- Auto-detects color support +- Doesn't extend `String.prototype` +- Clean and focused +- Actively maintained +- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020 + +## Install + +```console +$ npm install chalk +``` + +## Usage + +```js +const chalk = require('chalk'); + +console.log(chalk.blue('Hello world!')); +``` + +Chalk comes with an easy to use composable API where you just chain and nest the styles you want. + +```js +const chalk = require('chalk'); +const log = console.log; + +// Combine styled and normal strings +log(chalk.blue('Hello') + ' World' + chalk.red('!')); + +// Compose multiple styles using the chainable API +log(chalk.blue.bgRed.bold('Hello world!')); + +// Pass in multiple arguments +log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz')); + +// Nest styles +log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!')); + +// Nest styles of the same type even (color, underline, background) +log(chalk.green( + 'I am a green line ' + + chalk.blue.underline.bold('with a blue substring') + + ' that becomes green again!' +)); + +// ES2015 template literal +log(` +CPU: ${chalk.red('90%')} +RAM: ${chalk.green('40%')} +DISK: ${chalk.yellow('70%')} +`); + +// ES2015 tagged template literal +log(chalk` +CPU: {red ${cpu.totalPercent}%} +RAM: {green ${ram.used / ram.total * 100}%} +DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%} +`); + +// Use RGB colors in terminal emulators that support it. +log(chalk.keyword('orange')('Yay for orange colored text!')); +log(chalk.rgb(123, 45, 67).underline('Underlined reddish color')); +log(chalk.hex('#DEADED').bold('Bold gray!')); +``` + +Easily define your own themes: + +```js +const chalk = require('chalk'); + +const error = chalk.bold.red; +const warning = chalk.keyword('orange'); + +console.log(error('Error!')); +console.log(warning('Warning!')); +``` + +Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args): + +```js +const name = 'Sindre'; +console.log(chalk.green('Hello %s'), name); +//=> 'Hello Sindre' +``` + +## API + +### chalk.`<style>[.<style>...](string, [string...])` + +Example: `chalk.red.bold.underline('Hello', 'world');` + +Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`. + +Multiple arguments will be separated by space. + +### chalk.level + +Specifies the level of color support. + +Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers. + +If you need to change this in a reusable module, create a new instance: + +```js +const ctx = new chalk.Instance({level: 0}); +``` + +| Level | Description | +| :---: | :--- | +| `0` | All colors disabled | +| `1` | Basic color support (16 colors) | +| `2` | 256 color support | +| `3` | Truecolor support (16 million colors) | + +### chalk.supportsColor + +Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience. + +Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + +### chalk.stderr and chalk.stderr.supportsColor + +`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience. + +## Styles + +### Modifiers + +- `reset` - Resets the current color chain. +- `bold` - Make text bold. +- `dim` - Emitting only a small amount of light. +- `italic` - Make text italic. *(Not widely supported)* +- `underline` - Make text underline. *(Not widely supported)* +- `inverse`- Inverse background and foreground colors. +- `hidden` - Prints the text, but makes it invisible. +- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)* +- `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic. + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `blackBright` (alias: `gray`, `grey`) +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` (alias: `bgGray`, `bgGrey`) +- `bgRedBright` +- `bgGreenBright` +- `bgYellowBright` +- `bgBlueBright` +- `bgMagentaBright` +- `bgCyanBright` +- `bgWhiteBright` + +## Tagged template literal + +Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals). + +```js +const chalk = require('chalk'); + +const miles = 18; +const calculateFeet = miles => miles * 5280; + +console.log(chalk` + There are {bold 5280 feet} in a mile. + In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}. +`); +``` + +Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`). + +Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent: + +```js +console.log(chalk.bold.rgb(10, 100, 200)('Hello!')); +console.log(chalk.bold.rgb(10, 100, 200)`Hello!`); +console.log(chalk`{bold.rgb(10,100,200) Hello!}`); +``` + +Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters. + +All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped. + +## 256 and Truecolor color support + +Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps. + +Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red). + +Examples: + +- `chalk.hex('#DEADED').underline('Hello, world!')` +- `chalk.keyword('orange')('Some orange text')` +- `chalk.rgb(15, 100, 204).inverse('Hello!')` + +Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors). + +- `chalk.bgHex('#DEADED').underline('Hello, world!')` +- `chalk.bgKeyword('orange')('Some orange text')` +- `chalk.bgRgb(15, 100, 204).inverse('Hello!')` + +The following color models can be used: + +- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')` +- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')` +- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')` +- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')` +- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')` +- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')` +- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')` +- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')` + +## Windows + +If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`. + +## Origin story + +[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative. + +## chalk for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of chalk 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-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Related + +- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module +- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal +- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color +- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes +- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes +- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models +- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal +- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings +- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings +- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) diff --git a/node_modules/chalk/source/index.js b/node_modules/chalk/source/index.js new file mode 100644 index 0000000..75ec663 --- /dev/null +++ b/node_modules/chalk/source/index.js @@ -0,0 +1,229 @@ +'use strict'; +const ansiStyles = require('ansi-styles'); +const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color'); +const { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +} = require('./util'); + +const {isArray} = Array; + +// `supportsColor.level` → `ansiStyles.color[name]` mapping +const levelMapping = [ + 'ansi', + 'ansi', + 'ansi256', + 'ansi16m' +]; + +const styles = Object.create(null); + +const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } + + // Detect level if not set manually + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; + +class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } +} + +const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; + + chalk.template.Instance = ChalkClass; + + return chalk.template; +}; + +function Chalk(options) { + return chalkFactory(options); +} + +for (const [styleName, style] of Object.entries(ansiStyles)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, {value: builder}); + return builder; + } + }; +} + +styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', {value: builder}); + return builder; + } +}; + +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; + +for (const model of usedModels) { + styles[model] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} + +for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const {level} = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + }; +} + +const proto = Object.defineProperties(() => {}, { + ...styles, + level: { + enumerable: true, + get() { + return this._generator.level; + }, + set(level) { + this._generator.level = level; + } + } +}); + +const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + + return { + open, + close, + openAll, + closeAll, + parent + }; +}; + +const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } + + // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); + }; + + // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + Object.setPrototypeOf(builder, proto); + + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; + + return builder; +}; + +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } + + let styler = self._styler; + + if (styler === undefined) { + return string; + } + + const {openAll, closeAll} = styler; + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll(string, styler.close, styler.open); + + styler = styler.parent; + } + } + + // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + const lfIndex = string.indexOf('\n'); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } + + return openAll + string + closeAll; +}; + +let template; +const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; + + if (!isArray(firstString) || !isArray(firstString.raw)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } + + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; + + for (let i = 1; i < firstString.length; i++) { + parts.push( + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), + String(firstString.raw[i]) + ); + } + + if (template === undefined) { + template = require('./templates'); + } + + return template(chalk, parts.join('')); +}; + +Object.defineProperties(Chalk.prototype, styles); + +const chalk = Chalk(); // eslint-disable-line new-cap +chalk.supportsColor = stdoutColor; +chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap +chalk.stderr.supportsColor = stderrColor; + +module.exports = chalk; diff --git a/node_modules/chalk/source/templates.js b/node_modules/chalk/source/templates.js new file mode 100644 index 0000000..b130949 --- /dev/null +++ b/node_modules/chalk/source/templates.js @@ -0,0 +1,134 @@ +'use strict'; +const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; + +const ESCAPES = new Map([ + ['n', '\n'], + ['r', '\r'], + ['t', '\t'], + ['b', '\b'], + ['f', '\f'], + ['v', '\v'], + ['0', '\0'], + ['\\', '\\'], + ['e', '\u001B'], + ['a', '\u0007'] +]); + +function unescape(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; + + if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } + + return ESCAPES.get(c) || c; +} + +function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + const number = Number(chunk); + if (!Number.isNaN(number)) { + results.push(number); + } else if ((matches = chunk.match(STRING_REGEX))) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } + + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } + + return current; +} + +module.exports = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; + + // eslint-disable-next-line max-params + temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); + styles.push({inverse, styles: parseStyle(style)}); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); + + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMessage); + } + + return chunks.join(''); +}; diff --git a/node_modules/chalk/source/util.js b/node_modules/chalk/source/util.js new file mode 100644 index 0000000..ca466fd --- /dev/null +++ b/node_modules/chalk/source/util.js @@ -0,0 +1,39 @@ +'use strict'; + +const stringReplaceAll = (string, substring, replacer) => { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } + + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; +}; + +const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ''; + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; +}; + +module.exports = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +}; diff --git a/node_modules/cli-cursor/index.d.ts b/node_modules/cli-cursor/index.d.ts new file mode 100644 index 0000000..2b252d0 --- /dev/null +++ b/node_modules/cli-cursor/index.d.ts @@ -0,0 +1,45 @@ +/// <reference types="node"/> + +/** +Show cursor. + +@param stream - Default: `process.stderr`. + +@example +``` +import * as cliCursor from 'cli-cursor'; + +cliCursor.show(); +``` +*/ +export function show(stream?: NodeJS.WritableStream): void; + +/** +Hide cursor. + +@param stream - Default: `process.stderr`. + +@example +``` +import * as cliCursor from 'cli-cursor'; + +cliCursor.hide(); +``` +*/ +export function hide(stream?: NodeJS.WritableStream): void; + +/** +Toggle cursor visibility. + +@param force - Is useful to show or hide the cursor based on a boolean. +@param stream - Default: `process.stderr`. + +@example +``` +import * as cliCursor from 'cli-cursor'; + +const unicornsAreAwesome = true; +cliCursor.toggle(unicornsAreAwesome); +``` +*/ +export function toggle(force?: boolean, stream?: NodeJS.WritableStream): void; diff --git a/node_modules/cli-cursor/index.js b/node_modules/cli-cursor/index.js new file mode 100644 index 0000000..710c405 --- /dev/null +++ b/node_modules/cli-cursor/index.js @@ -0,0 +1,35 @@ +'use strict'; +const restoreCursor = require('restore-cursor'); + +let isHidden = false; + +exports.show = (writableStream = process.stderr) => { + if (!writableStream.isTTY) { + return; + } + + isHidden = false; + writableStream.write('\u001B[?25h'); +}; + +exports.hide = (writableStream = process.stderr) => { + if (!writableStream.isTTY) { + return; + } + + restoreCursor(); + isHidden = true; + writableStream.write('\u001B[?25l'); +}; + +exports.toggle = (force, writableStream) => { + if (force !== undefined) { + isHidden = force; + } + + if (isHidden) { + exports.show(writableStream); + } else { + exports.hide(writableStream); + } +}; diff --git a/node_modules/cli-cursor/license b/node_modules/cli-cursor/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/cli-cursor/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/cli-cursor/package.json b/node_modules/cli-cursor/package.json new file mode 100644 index 0000000..a6f76f6 --- /dev/null +++ b/node_modules/cli-cursor/package.json @@ -0,0 +1,78 @@ +{ + "_from": "cli-cursor@^3.1.0", + "_id": "cli-cursor@3.1.0", + "_inBundle": false, + "_integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "_location": "/cli-cursor", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "cli-cursor@^3.1.0", + "name": "cli-cursor", + "escapedName": "cli-cursor", + "rawSpec": "^3.1.0", + "saveSpec": null, + "fetchSpec": "^3.1.0" + }, + "_requiredBy": [ + "/ora" + ], + "_resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "_shasum": "264305a7ae490d1d03bf0c9ba7c925d1753af307", + "_spec": "cli-cursor@^3.1.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/ora", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/cli-cursor/issues" + }, + "bundleDependencies": false, + "dependencies": { + "restore-cursor": "^3.1.0" + }, + "deprecated": false, + "description": "Toggle the CLI cursor", + "devDependencies": { + "@types/node": "^12.0.7", + "ava": "^2.1.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/cli-cursor#readme", + "keywords": [ + "cli", + "cursor", + "ansi", + "toggle", + "display", + "show", + "hide", + "term", + "terminal", + "console", + "tty", + "shell", + "command-line" + ], + "license": "MIT", + "name": "cli-cursor", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/cli-cursor.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "3.1.0" +} diff --git a/node_modules/cli-cursor/readme.md b/node_modules/cli-cursor/readme.md new file mode 100644 index 0000000..3478ac8 --- /dev/null +++ b/node_modules/cli-cursor/readme.md @@ -0,0 +1,55 @@ +# cli-cursor [![Build Status](https://travis-ci.org/sindresorhus/cli-cursor.svg?branch=master)](https://travis-ci.org/sindresorhus/cli-cursor) + +> Toggle the CLI cursor + +The cursor is [gracefully restored](https://github.com/sindresorhus/restore-cursor) if the process exits. + + +## Install + +``` +$ npm install cli-cursor +``` + + +## Usage + +```js +const cliCursor = require('cli-cursor'); + +cliCursor.hide(); + +const unicornsAreAwesome = true; +cliCursor.toggle(unicornsAreAwesome); +``` + + +## API + +### .show(stream?) + +### .hide(stream?) + +### .toggle(force?, stream?) + +#### force + +Useful for showing or hiding the cursor based on a boolean. + +#### stream + +Type: `stream.Writable`<br> +Default: `process.stderr` + + +--- + +<div align="center"> + <b> + <a href="https://tidelift.com/subscription/pkg/npm-cli-cursor?utm_source=npm-cli-cursor&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> + </b> + <br> + <sub> + Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. + </sub> +</div> diff --git a/node_modules/cli-spinners/index.d.ts b/node_modules/cli-spinners/index.d.ts new file mode 100644 index 0000000..e9aeff0 --- /dev/null +++ b/node_modules/cli-spinners/index.d.ts @@ -0,0 +1,115 @@ +declare namespace cliSpinners { + type SpinnerName = + | 'dots' + | 'dots2' + | 'dots3' + | 'dots4' + | 'dots5' + | 'dots6' + | 'dots7' + | 'dots8' + | 'dots9' + | 'dots10' + | 'dots11' + | 'dots12' + | 'dots8Bit' + | 'line' + | 'line2' + | 'pipe' + | 'simpleDots' + | 'simpleDotsScrolling' + | 'star' + | 'star2' + | 'flip' + | 'hamburger' + | 'growVertical' + | 'growHorizontal' + | 'balloon' + | 'balloon2' + | 'noise' + | 'bounce' + | 'boxBounce' + | 'boxBounce2' + | 'triangle' + | 'arc' + | 'circle' + | 'squareCorners' + | 'circleQuarters' + | 'circleHalves' + | 'squish' + | 'toggle' + | 'toggle2' + | 'toggle3' + | 'toggle4' + | 'toggle5' + | 'toggle6' + | 'toggle7' + | 'toggle8' + | 'toggle9' + | 'toggle10' + | 'toggle11' + | 'toggle12' + | 'toggle13' + | 'arrow' + | 'arrow2' + | 'arrow3' + | 'bouncingBar' + | 'bouncingBall' + | 'smiley' + | 'monkey' + | 'hearts' + | 'clock' + | 'earth' + | 'material' + | 'moon' + | 'runner' + | 'pong' + | 'shark' + | 'dqpb' + | 'weather' + | 'christmas' + | 'grenade' + | 'point' + | 'layer' + | 'betaWave'; + + interface Spinner { + /** + Recommended interval. + */ + readonly interval: number; + + /** + A list of frames to show for the spinner. + */ + readonly frames: string[]; + } +} + +/** +70+ spinners for use in the terminal. + +@example +``` +import cliSpinners = require('cli-spinners'); + +console.log(cliSpinners.dots); +// { +// interval: 80, +// frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] +// } +``` +*/ +declare const cliSpinners: { + readonly [spinnerName in cliSpinners.SpinnerName]: cliSpinners.Spinner; +} & { + /** + Returns a random spinner each time it's called. + */ + readonly random: cliSpinners.Spinner; + + // TODO: Remove this for the next major release + default: typeof cliSpinners; +}; + +export = cliSpinners; diff --git a/node_modules/cli-spinners/index.js b/node_modules/cli-spinners/index.js new file mode 100644 index 0000000..38920a3 --- /dev/null +++ b/node_modules/cli-spinners/index.js @@ -0,0 +1,17 @@ +'use strict'; + +const spinners = Object.assign({}, require('./spinners.json')); + +const spinnersList = Object.keys(spinners); + +Object.defineProperty(spinners, 'random', { + get() { + const randomIndex = Math.floor(Math.random() * spinnersList.length); + const spinnerName = spinnersList[randomIndex]; + return spinners[spinnerName]; + } +}); + +module.exports = spinners; +// TODO: Remove this for the next major release +module.exports.default = spinners; diff --git a/node_modules/cli-spinners/license b/node_modules/cli-spinners/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/cli-spinners/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://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. diff --git a/node_modules/cli-spinners/package.json b/node_modules/cli-spinners/package.json new file mode 100644 index 0000000..7781577 --- /dev/null +++ b/node_modules/cli-spinners/package.json @@ -0,0 +1,80 @@ +{ + "_from": "cli-spinners@^2.4.0", + "_id": "cli-spinners@2.4.0", + "_inBundle": false, + "_integrity": "sha512-sJAofoarcm76ZGpuooaO0eDy8saEy+YoZBLjC4h8srt4jeBnkYeOgqxgsJQTpyt2LjI5PTfLJHSL+41Yu4fEJA==", + "_location": "/cli-spinners", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "cli-spinners@^2.4.0", + "name": "cli-spinners", + "escapedName": "cli-spinners", + "rawSpec": "^2.4.0", + "saveSpec": null, + "fetchSpec": "^2.4.0" + }, + "_requiredBy": [ + "/ora" + ], + "_resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.4.0.tgz", + "_shasum": "c6256db216b878cfba4720e719cec7cf72685d7f", + "_spec": "cli-spinners@^2.4.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/ora", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/cli-spinners/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Spinners for use in the terminal", + "devDependencies": { + "ava": "^1.4.1", + "log-update": "^3.2.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "index.js", + "index.d.ts", + "spinners.json" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/cli-spinners#readme", + "keywords": [ + "cli", + "spinner", + "spinners", + "terminal", + "term", + "console", + "ascii", + "unicode", + "loading", + "indicator", + "progress", + "busy", + "wait", + "idle", + "json" + ], + "license": "MIT", + "name": "cli-spinners", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/cli-spinners.git" + }, + "scripts": { + "asciicast": "asciinema rec --command='node example-all.js' --title='cli-spinner' --quiet", + "test": "xo && ava && tsd" + }, + "version": "2.4.0" +} diff --git a/node_modules/cli-spinners/readme.md b/node_modules/cli-spinners/readme.md new file mode 100644 index 0000000..44e06c7 --- /dev/null +++ b/node_modules/cli-spinners/readme.md @@ -0,0 +1,53 @@ +# cli-spinners [![Build Status](https://travis-ci.com/sindresorhus/cli-spinners.svg?branch=master)](https://travis-ci.com/github/sindresorhus/cli-spinners) + +> 70+ spinners for use in the terminal + +<p align="center"> + <br> + <img width="700" src="screenshot.svg"> + <br> + <br> +</p> + +The list of spinners is just a [JSON file](spinners.json) and can be used wherever. + +You probably want to use one of these spinners through the [`ora`](https://github.com/sindresorhus/ora) module. + +## Install + +``` +$ npm install cli-spinners +``` + +## Usage + +```js +const cliSpinners = require('cli-spinners'); + +console.log(cliSpinners.dots); +/* +{ + interval: 80, + frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'] +} +*/ +``` + +## Preview + +The header GIF is outdated. See all the [spinner at once](https://jsfiddle.net/sindresorhus/2eLtsbey/embedded/result/) or [one at the time](https://asciinema.org/a/95348?size=big). + +## API + +Each spinner comes with a recommended `interval` and an array of `frames`. + +[See the spinners.](spinners.json) + +The `random` spinner will return a random spinner each time it's called. + +## Related + +- [ora](https://github.com/sindresorhus/ora) - Elegant terminal spinner +- [CLISpinner](https://github.com/kiliankoe/CLISpinner) - Terminal spinners for Swift +- [py-spinners](https://github.com/ManrajGrover/py-spinners) - Python port +- [spinners](https://github.com/FGRibreau/spinners) - Terminal spinners for Rust diff --git a/node_modules/cli-spinners/spinners.json b/node_modules/cli-spinners/spinners.json new file mode 100644 index 0000000..f47fa27 --- /dev/null +++ b/node_modules/cli-spinners/spinners.json @@ -0,0 +1,1282 @@ +{ + "dots": { + "interval": 80, + "frames": [ + "⠋", + "⠙", + "⠹", + "⠸", + "⠼", + "⠴", + "⠦", + "⠧", + "⠇", + "⠏" + ] + }, + "dots2": { + "interval": 80, + "frames": [ + "⣾", + "⣽", + "⣻", + "⢿", + "⡿", + "⣟", + "⣯", + "⣷" + ] + }, + "dots3": { + "interval": 80, + "frames": [ + "⠋", + "⠙", + "⠚", + "⠞", + "⠖", + "⠦", + "⠴", + "⠲", + "⠳", + "⠓" + ] + }, + "dots4": { + "interval": 80, + "frames": [ + "⠄", + "⠆", + "⠇", + "⠋", + "⠙", + "⠸", + "⠰", + "⠠", + "⠰", + "⠸", + "⠙", + "⠋", + "⠇", + "⠆" + ] + }, + "dots5": { + "interval": 80, + "frames": [ + "⠋", + "⠙", + "⠚", + "⠒", + "⠂", + "⠂", + "⠒", + "⠲", + "⠴", + "⠦", + "⠖", + "⠒", + "⠐", + "⠐", + "⠒", + "⠓", + "⠋" + ] + }, + "dots6": { + "interval": 80, + "frames": [ + "⠁", + "⠉", + "⠙", + "⠚", + "⠒", + "⠂", + "⠂", + "⠒", + "⠲", + "⠴", + "⠤", + "⠄", + "⠄", + "⠤", + "⠴", + "⠲", + "⠒", + "⠂", + "⠂", + "⠒", + "⠚", + "⠙", + "⠉", + "⠁" + ] + }, + "dots7": { + "interval": 80, + "frames": [ + "⠈", + "⠉", + "⠋", + "⠓", + "⠒", + "⠐", + "⠐", + "⠒", + "⠖", + "⠦", + "⠤", + "⠠", + "⠠", + "⠤", + "⠦", + "⠖", + "⠒", + "⠐", + "⠐", + "⠒", + "⠓", + "⠋", + "⠉", + "⠈" + ] + }, + "dots8": { + "interval": 80, + "frames": [ + "⠁", + "⠁", + "⠉", + "⠙", + "⠚", + "⠒", + "⠂", + "⠂", + "⠒", + "⠲", + "⠴", + "⠤", + "⠄", + "⠄", + "⠤", + "⠠", + "⠠", + "⠤", + "⠦", + "⠖", + "⠒", + "⠐", + "⠐", + "⠒", + "⠓", + "⠋", + "⠉", + "⠈", + "⠈" + ] + }, + "dots9": { + "interval": 80, + "frames": [ + "⢹", + "⢺", + "⢼", + "⣸", + "⣇", + "⡧", + "⡗", + "⡏" + ] + }, + "dots10": { + "interval": 80, + "frames": [ + "⢄", + "⢂", + "⢁", + "⡁", + "⡈", + "⡐", + "⡠" + ] + }, + "dots11": { + "interval": 100, + "frames": [ + "⠁", + "⠂", + "⠄", + "⡀", + "⢀", + "⠠", + "⠐", + "⠈" + ] + }, + "dots12": { + "interval": 80, + "frames": [ + "⢀⠀", + "⡀⠀", + "⠄⠀", + "⢂⠀", + "⡂⠀", + "⠅⠀", + "⢃⠀", + "⡃⠀", + "⠍⠀", + "⢋⠀", + "⡋⠀", + "⠍⠁", + "⢋⠁", + "⡋⠁", + "⠍⠉", + "⠋⠉", + "⠋⠉", + "⠉⠙", + "⠉⠙", + "⠉⠩", + "⠈⢙", + "⠈⡙", + "⢈⠩", + "⡀⢙", + "⠄⡙", + "⢂⠩", + "⡂⢘", + "⠅⡘", + "⢃⠨", + "⡃⢐", + "⠍⡐", + "⢋⠠", + "⡋⢀", + "⠍⡁", + "⢋⠁", + "⡋⠁", + "⠍⠉", + "⠋⠉", + "⠋⠉", + "⠉⠙", + "⠉⠙", + "⠉⠩", + "⠈⢙", + "⠈⡙", + "⠈⠩", + "⠀⢙", + "⠀⡙", + "⠀⠩", + "⠀⢘", + "⠀⡘", + "⠀⠨", + "⠀⢐", + "⠀⡐", + "⠀⠠", + "⠀⢀", + "⠀⡀" + ] + }, + "dots8Bit": { + "interval": 80, + "frames": [ + "⠀", + "⠁", + "⠂", + "⠃", + "⠄", + "⠅", + "⠆", + "⠇", + "⡀", + "⡁", + "⡂", + "⡃", + "⡄", + "⡅", + "⡆", + "⡇", + "⠈", + "⠉", + "⠊", + "⠋", + "⠌", + "⠍", + "⠎", + "⠏", + "⡈", + "⡉", + "⡊", + "⡋", + "⡌", + "⡍", + "⡎", + "⡏", + "⠐", + "⠑", + "⠒", + "⠓", + "⠔", + "⠕", + "⠖", + "⠗", + "⡐", + "⡑", + "⡒", + "⡓", + "⡔", + "⡕", + "⡖", + "⡗", + "⠘", + "⠙", + "⠚", + "⠛", + "⠜", + "⠝", + "⠞", + "⠟", + "⡘", + "⡙", + "⡚", + "⡛", + "⡜", + "⡝", + "⡞", + "⡟", + "⠠", + "⠡", + "⠢", + "⠣", + "⠤", + "⠥", + "⠦", + "⠧", + "⡠", + "⡡", + "⡢", + "⡣", + "⡤", + "⡥", + "⡦", + "⡧", + "⠨", + "⠩", + "⠪", + "⠫", + "⠬", + "⠭", + "⠮", + "⠯", + "⡨", + "⡩", + "⡪", + "⡫", + "⡬", + "⡭", + "⡮", + "⡯", + "⠰", + "⠱", + "⠲", + "⠳", + "⠴", + "⠵", + "⠶", + "⠷", + "⡰", + "⡱", + "⡲", + "⡳", + "⡴", + "⡵", + "⡶", + "⡷", + "⠸", + "⠹", + "⠺", + "⠻", + "⠼", + "⠽", + "⠾", + "⠿", + "⡸", + "⡹", + "⡺", + "⡻", + "⡼", + "⡽", + "⡾", + "⡿", + "⢀", + "⢁", + "⢂", + "⢃", + "⢄", + "⢅", + "⢆", + "⢇", + "⣀", + "⣁", + "⣂", + "⣃", + "⣄", + "⣅", + "⣆", + "⣇", + "⢈", + "⢉", + "⢊", + "⢋", + "⢌", + "⢍", + "⢎", + "⢏", + "⣈", + "⣉", + "⣊", + "⣋", + "⣌", + "⣍", + "⣎", + "⣏", + "⢐", + "⢑", + "⢒", + "⢓", + "⢔", + "⢕", + "⢖", + "⢗", + "⣐", + "⣑", + "⣒", + "⣓", + "⣔", + "⣕", + "⣖", + "⣗", + "⢘", + "⢙", + "⢚", + "⢛", + "⢜", + "⢝", + "⢞", + "⢟", + "⣘", + "⣙", + "⣚", + "⣛", + "⣜", + "⣝", + "⣞", + "⣟", + "⢠", + "⢡", + "⢢", + "⢣", + "⢤", + "⢥", + "⢦", + "⢧", + "⣠", + "⣡", + "⣢", + "⣣", + "⣤", + "⣥", + "⣦", + "⣧", + "⢨", + "⢩", + "⢪", + "⢫", + "⢬", + "⢭", + "⢮", + "⢯", + "⣨", + "⣩", + "⣪", + "⣫", + "⣬", + "⣭", + "⣮", + "⣯", + "⢰", + "⢱", + "⢲", + "⢳", + "⢴", + "⢵", + "⢶", + "⢷", + "⣰", + "⣱", + "⣲", + "⣳", + "⣴", + "⣵", + "⣶", + "⣷", + "⢸", + "⢹", + "⢺", + "⢻", + "⢼", + "⢽", + "⢾", + "⢿", + "⣸", + "⣹", + "⣺", + "⣻", + "⣼", + "⣽", + "⣾", + "⣿" + ] + }, + "line": { + "interval": 130, + "frames": [ + "-", + "\\", + "|", + "/" + ] + }, + "line2": { + "interval": 100, + "frames": [ + "⠂", + "-", + "–", + "—", + "–", + "-" + ] + }, + "pipe": { + "interval": 100, + "frames": [ + "┤", + "┘", + "┴", + "└", + "├", + "┌", + "┬", + "┐" + ] + }, + "simpleDots": { + "interval": 400, + "frames": [ + ". ", + ".. ", + "...", + " " + ] + }, + "simpleDotsScrolling": { + "interval": 200, + "frames": [ + ". ", + ".. ", + "...", + " ..", + " .", + " " + ] + }, + "star": { + "interval": 70, + "frames": [ + "✶", + "✸", + "✹", + "✺", + "✹", + "✷" + ] + }, + "star2": { + "interval": 80, + "frames": [ + "+", + "x", + "*" + ] + }, + "flip": { + "interval": 70, + "frames": [ + "_", + "_", + "_", + "-", + "`", + "`", + "'", + "´", + "-", + "_", + "_", + "_" + ] + }, + "hamburger": { + "interval": 100, + "frames": [ + "☱", + "☲", + "☴" + ] + }, + "growVertical": { + "interval": 120, + "frames": [ + "▁", + "▃", + "▄", + "▅", + "▆", + "▇", + "▆", + "▅", + "▄", + "▃" + ] + }, + "growHorizontal": { + "interval": 120, + "frames": [ + "▏", + "▎", + "▍", + "▌", + "▋", + "▊", + "▉", + "▊", + "▋", + "▌", + "▍", + "▎" + ] + }, + "balloon": { + "interval": 140, + "frames": [ + " ", + ".", + "o", + "O", + "@", + "*", + " " + ] + }, + "balloon2": { + "interval": 120, + "frames": [ + ".", + "o", + "O", + "°", + "O", + "o", + "." + ] + }, + "noise": { + "interval": 100, + "frames": [ + "▓", + "▒", + "░" + ] + }, + "bounce": { + "interval": 120, + "frames": [ + "⠁", + "⠂", + "⠄", + "⠂" + ] + }, + "boxBounce": { + "interval": 120, + "frames": [ + "▖", + "▘", + "▝", + "▗" + ] + }, + "boxBounce2": { + "interval": 100, + "frames": [ + "▌", + "▀", + "▐", + "▄" + ] + }, + "triangle": { + "interval": 50, + "frames": [ + "◢", + "◣", + "◤", + "◥" + ] + }, + "arc": { + "interval": 100, + "frames": [ + "◜", + "◠", + "◝", + "◞", + "◡", + "◟" + ] + }, + "circle": { + "interval": 120, + "frames": [ + "◡", + "⊙", + "◠" + ] + }, + "squareCorners": { + "interval": 180, + "frames": [ + "◰", + "◳", + "◲", + "◱" + ] + }, + "circleQuarters": { + "interval": 120, + "frames": [ + "◴", + "◷", + "◶", + "◵" + ] + }, + "circleHalves": { + "interval": 50, + "frames": [ + "◐", + "◓", + "◑", + "◒" + ] + }, + "squish": { + "interval": 100, + "frames": [ + "╫", + "╪" + ] + }, + "toggle": { + "interval": 250, + "frames": [ + "⊶", + "⊷" + ] + }, + "toggle2": { + "interval": 80, + "frames": [ + "▫", + "▪" + ] + }, + "toggle3": { + "interval": 120, + "frames": [ + "□", + "■" + ] + }, + "toggle4": { + "interval": 100, + "frames": [ + "■", + "□", + "▪", + "▫" + ] + }, + "toggle5": { + "interval": 100, + "frames": [ + "▮", + "▯" + ] + }, + "toggle6": { + "interval": 300, + "frames": [ + "ဝ", + "၀" + ] + }, + "toggle7": { + "interval": 80, + "frames": [ + "⦾", + "⦿" + ] + }, + "toggle8": { + "interval": 100, + "frames": [ + "◍", + "◌" + ] + }, + "toggle9": { + "interval": 100, + "frames": [ + "◉", + "◎" + ] + }, + "toggle10": { + "interval": 100, + "frames": [ + "㊂", + "㊀", + "㊁" + ] + }, + "toggle11": { + "interval": 50, + "frames": [ + "⧇", + "⧆" + ] + }, + "toggle12": { + "interval": 120, + "frames": [ + "☗", + "☖" + ] + }, + "toggle13": { + "interval": 80, + "frames": [ + "=", + "*", + "-" + ] + }, + "arrow": { + "interval": 100, + "frames": [ + "←", + "↖", + "↑", + "↗", + "→", + "↘", + "↓", + "↙" + ] + }, + "arrow2": { + "interval": 80, + "frames": [ + "⬆️ ", + "↗️ ", + "➡️ ", + "↘️ ", + "⬇️ ", + "↙️ ", + "⬅️ ", + "↖️ " + ] + }, + "arrow3": { + "interval": 120, + "frames": [ + "▹▹▹▹▹", + "▸▹▹▹▹", + "▹▸▹▹▹", + "▹▹▸▹▹", + "▹▹▹▸▹", + "▹▹▹▹▸" + ] + }, + "bouncingBar": { + "interval": 80, + "frames": [ + "[ ]", + "[= ]", + "[== ]", + "[=== ]", + "[ ===]", + "[ ==]", + "[ =]", + "[ ]", + "[ =]", + "[ ==]", + "[ ===]", + "[====]", + "[=== ]", + "[== ]", + "[= ]" + ] + }, + "bouncingBall": { + "interval": 80, + "frames": [ + "( ● )", + "( ● )", + "( ● )", + "( ● )", + "( ●)", + "( ● )", + "( ● )", + "( ● )", + "( ● )", + "(● )" + ] + }, + "smiley": { + "interval": 200, + "frames": [ + "😄 ", + "😝 " + ] + }, + "monkey": { + "interval": 300, + "frames": [ + "🙈 ", + "🙈 ", + "🙉 ", + "🙊 " + ] + }, + "hearts": { + "interval": 100, + "frames": [ + "💛 ", + "💙 ", + "💜 ", + "💚 ", + "❤️ " + ] + }, + "clock": { + "interval": 100, + "frames": [ + "🕛 ", + "🕐 ", + "🕑 ", + "🕒 ", + "🕓 ", + "🕔 ", + "🕕 ", + "🕖 ", + "🕗 ", + "🕘 ", + "🕙 ", + "🕚 " + ] + }, + "earth": { + "interval": 180, + "frames": [ + "🌍 ", + "🌎 ", + "🌏 " + ] + }, + "material": { + "interval": 17, + "frames": [ + "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "███████▁▁▁▁▁▁▁▁▁▁▁▁▁", + "████████▁▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "██████████▁▁▁▁▁▁▁▁▁▁", + "███████████▁▁▁▁▁▁▁▁▁", + "█████████████▁▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁▁██████████████▁▁▁▁", + "▁▁▁██████████████▁▁▁", + "▁▁▁▁█████████████▁▁▁", + "▁▁▁▁██████████████▁▁", + "▁▁▁▁██████████████▁▁", + "▁▁▁▁▁██████████████▁", + "▁▁▁▁▁██████████████▁", + "▁▁▁▁▁██████████████▁", + "▁▁▁▁▁▁██████████████", + "▁▁▁▁▁▁██████████████", + "▁▁▁▁▁▁▁█████████████", + "▁▁▁▁▁▁▁█████████████", + "▁▁▁▁▁▁▁▁████████████", + "▁▁▁▁▁▁▁▁████████████", + "▁▁▁▁▁▁▁▁▁███████████", + "▁▁▁▁▁▁▁▁▁███████████", + "▁▁▁▁▁▁▁▁▁▁██████████", + "▁▁▁▁▁▁▁▁▁▁██████████", + "▁▁▁▁▁▁▁▁▁▁▁▁████████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", + "█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "██████▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "████████▁▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "█████████▁▁▁▁▁▁▁▁▁▁▁", + "███████████▁▁▁▁▁▁▁▁▁", + "████████████▁▁▁▁▁▁▁▁", + "████████████▁▁▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "██████████████▁▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁██████████████▁▁▁▁▁", + "▁▁▁█████████████▁▁▁▁", + "▁▁▁▁▁████████████▁▁▁", + "▁▁▁▁▁████████████▁▁▁", + "▁▁▁▁▁▁███████████▁▁▁", + "▁▁▁▁▁▁▁▁█████████▁▁▁", + "▁▁▁▁▁▁▁▁█████████▁▁▁", + "▁▁▁▁▁▁▁▁▁█████████▁▁", + "▁▁▁▁▁▁▁▁▁█████████▁▁", + "▁▁▁▁▁▁▁▁▁▁█████████▁", + "▁▁▁▁▁▁▁▁▁▁▁████████▁", + "▁▁▁▁▁▁▁▁▁▁▁████████▁", + "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", + "▁▁▁▁▁▁▁▁▁▁▁▁███████▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁███████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁", + "▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁" + ] + }, + "moon": { + "interval": 80, + "frames": [ + "🌑 ", + "🌒 ", + "🌓 ", + "🌔 ", + "🌕 ", + "🌖 ", + "🌗 ", + "🌘 " + ] + }, + "runner": { + "interval": 140, + "frames": [ + "🚶 ", + "🏃 " + ] + }, + "pong": { + "interval": 80, + "frames": [ + "▐⠂ ▌", + "▐⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂▌", + "▐ ⠠▌", + "▐ ⡀▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐ ⠠ ▌", + "▐ ⠂ ▌", + "▐ ⠈ ▌", + "▐ ⠂ ▌", + "▐ ⠠ ▌", + "▐ ⡀ ▌", + "▐⠠ ▌" + ] + }, + "shark": { + "interval": 120, + "frames": [ + "▐|\\____________▌", + "▐_|\\___________▌", + "▐__|\\__________▌", + "▐___|\\_________▌", + "▐____|\\________▌", + "▐_____|\\_______▌", + "▐______|\\______▌", + "▐_______|\\_____▌", + "▐________|\\____▌", + "▐_________|\\___▌", + "▐__________|\\__▌", + "▐___________|\\_▌", + "▐____________|\\▌", + "▐____________/|▌", + "▐___________/|_▌", + "▐__________/|__▌", + "▐_________/|___▌", + "▐________/|____▌", + "▐_______/|_____▌", + "▐______/|______▌", + "▐_____/|_______▌", + "▐____/|________▌", + "▐___/|_________▌", + "▐__/|__________▌", + "▐_/|___________▌", + "▐/|____________▌" + ] + }, + "dqpb": { + "interval": 100, + "frames": [ + "d", + "q", + "p", + "b" + ] + }, + "weather": { + "interval": 100, + "frames": [ + "☀️ ", + "☀️ ", + "☀️ ", + "🌤 ", + "⛅️ ", + "🌥 ", + "☁️ ", + "🌧 ", + "🌨 ", + "🌧 ", + "🌨 ", + "🌧 ", + "🌨 ", + "⛈ ", + "🌨 ", + "🌧 ", + "🌨 ", + "☁️ ", + "🌥 ", + "⛅️ ", + "🌤 ", + "☀️ ", + "☀️ " + ] + }, + "christmas": { + "interval": 400, + "frames": [ + "🌲", + "🎄" + ] + }, + "grenade": { + "interval": 80, + "frames": [ + "، ", + "′ ", + " ´ ", + " ‾ ", + " ⸌", + " ⸊", + " |", + " ⁎", + " ⁕", + " ෴ ", + " ⁓", + " ", + " ", + " " + ] + }, + "point": { + "interval": 125, + "frames": [ + "∙∙∙", + "●∙∙", + "∙●∙", + "∙∙●", + "∙∙∙" + ] + }, + "layer": { + "interval": 150, + "frames": [ + "-", + "=", + "≡" + ] + }, + "betaWave": { + "interval": 80, + "frames": [ + "ρββββββ", + "βρβββββ", + "ββρββββ", + "βββρβββ", + "ββββρββ", + "βββββρβ", + "ββββββρ" + ] + } +} diff --git a/node_modules/clone/.npmignore b/node_modules/clone/.npmignore new file mode 100644 index 0000000..c797cbf --- /dev/null +++ b/node_modules/clone/.npmignore @@ -0,0 +1,4 @@ +/node_modules/ +/test.js +/*.html +/.travis.yml diff --git a/node_modules/clone/LICENSE b/node_modules/clone/LICENSE new file mode 100644 index 0000000..cc3c87b --- /dev/null +++ b/node_modules/clone/LICENSE @@ -0,0 +1,18 @@ +Copyright © 2011-2015 Paul Vorbach <paul@vorba.ch> + +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, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/clone/README.md b/node_modules/clone/README.md new file mode 100644 index 0000000..0b6ceca --- /dev/null +++ b/node_modules/clone/README.md @@ -0,0 +1,126 @@ +# clone + +[![build status](https://secure.travis-ci.org/pvorb/node-clone.png)](http://travis-ci.org/pvorb/node-clone) + +[![info badge](https://nodei.co/npm/clone.png?downloads=true&downloadRank=true&stars=true)](http://npm-stat.com/charts.html?package=clone) + +offers foolproof _deep cloning_ of objects, arrays, numbers, strings etc. in JavaScript. + + +## Installation + + npm install clone + +(It also works with browserify, ender or standalone.) + + +## Example + +~~~ javascript +var clone = require('clone'); + +var a, b; + +a = { foo: { bar: 'baz' } }; // initial value of a + +b = clone(a); // clone a -> b +a.foo.bar = 'foo'; // change a + +console.log(a); // show a +console.log(b); // show b +~~~ + +This will print: + +~~~ javascript +{ foo: { bar: 'foo' } } +{ foo: { bar: 'baz' } } +~~~ + +**clone** masters cloning simple objects (even with custom prototype), arrays, +Date objects, and RegExp objects. Everything is cloned recursively, so that you +can clone dates in arrays in objects, for example. + + +## API + +`clone(val, circular, depth)` + + * `val` -- the value that you want to clone, any type allowed + * `circular` -- boolean + + Call `clone` with `circular` set to `false` if you are certain that `obj` + contains no circular references. This will give better performance if needed. + There is no error if `undefined` or `null` is passed as `obj`. + * `depth` -- depth to which the object is to be cloned (optional, + defaults to infinity) + +`clone.clonePrototype(obj)` + + * `obj` -- the object that you want to clone + +Does a prototype clone as +[described by Oran Looney](http://oranlooney.com/functional-javascript/). + + +## Circular References + +~~~ javascript +var a, b; + +a = { hello: 'world' }; + +a.myself = a; +b = clone(a); + +console.log(b); +~~~ + +This will print: + +~~~ javascript +{ hello: "world", myself: [Circular] } +~~~ + +So, `b.myself` points to `b`, not `a`. Neat! + + +## Test + + npm test + + +## Caveat + +Some special objects like a socket or `process.stdout`/`stderr` are known to not +be cloneable. If you find other objects that cannot be cloned, please [open an +issue](https://github.com/pvorb/node-clone/issues/new). + + +## Bugs and Issues + +If you encounter any bugs or issues, feel free to [open an issue at +github](https://github.com/pvorb/node-clone/issues) or send me an email to +<paul@vorba.ch>. I also always like to hear from you, if you’re using my code. + +## License + +Copyright © 2011-2015 [Paul Vorbach](http://paul.vorba.ch/) and +[contributors](https://github.com/pvorb/node-clone/graphs/contributors). + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the “Software”), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/clone/clone.iml b/node_modules/clone/clone.iml new file mode 100644 index 0000000..30de8ae --- /dev/null +++ b/node_modules/clone/clone.iml @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="UTF-8"?> +<module type="WEB_MODULE" version="4"> + <component name="NewModuleRootManager" inherit-compiler-output="true"> + <exclude-output /> + <content url="file://$MODULE_DIR$" /> + <orderEntry type="inheritedJdk" /> + <orderEntry type="sourceFolder" forTests="false" /> + <orderEntry type="library" name="clone node_modules" level="project" /> + </component> +</module>
\ No newline at end of file diff --git a/node_modules/clone/clone.js b/node_modules/clone/clone.js new file mode 100644 index 0000000..ba200c2 --- /dev/null +++ b/node_modules/clone/clone.js @@ -0,0 +1,166 @@ +var clone = (function() { +'use strict'; + +/** + * Clones (copies) an Object using deep copying. + * + * This function supports circular references by default, but if you are certain + * there are no circular references in your object, you can save some CPU time + * by calling clone(obj, false). + * + * Caution: if `circular` is false and `parent` contains circular references, + * your program may enter an infinite loop and crash. + * + * @param `parent` - the object to be cloned + * @param `circular` - set to true if the object to be cloned may contain + * circular references. (optional - true by default) + * @param `depth` - set to a number if the object is only to be cloned to + * a particular depth. (optional - defaults to Infinity) + * @param `prototype` - sets the prototype to be used when cloning an object. + * (optional - defaults to parent prototype). +*/ +function clone(parent, circular, depth, prototype) { + var filter; + if (typeof circular === 'object') { + depth = circular.depth; + prototype = circular.prototype; + filter = circular.filter; + circular = circular.circular + } + // maintain two arrays for circular references, where corresponding parents + // and children have the same index + var allParents = []; + var allChildren = []; + + var useBuffer = typeof Buffer != 'undefined'; + + if (typeof circular == 'undefined') + circular = true; + + if (typeof depth == 'undefined') + depth = Infinity; + + // recurse this function so we don't reset allParents and allChildren + function _clone(parent, depth) { + // cloning null always returns null + if (parent === null) + return null; + + if (depth == 0) + return parent; + + var child; + var proto; + if (typeof parent != 'object') { + return parent; + } + + if (clone.__isArray(parent)) { + child = []; + } else if (clone.__isRegExp(parent)) { + child = new RegExp(parent.source, __getRegExpFlags(parent)); + if (parent.lastIndex) child.lastIndex = parent.lastIndex; + } else if (clone.__isDate(parent)) { + child = new Date(parent.getTime()); + } else if (useBuffer && Buffer.isBuffer(parent)) { + if (Buffer.allocUnsafe) { + // Node.js >= 4.5.0 + child = Buffer.allocUnsafe(parent.length); + } else { + // Older Node.js versions + child = new Buffer(parent.length); + } + parent.copy(child); + return child; + } else { + if (typeof prototype == 'undefined') { + proto = Object.getPrototypeOf(parent); + child = Object.create(proto); + } + else { + child = Object.create(prototype); + proto = prototype; + } + } + + if (circular) { + var index = allParents.indexOf(parent); + + if (index != -1) { + return allChildren[index]; + } + allParents.push(parent); + allChildren.push(child); + } + + for (var i in parent) { + var attrs; + if (proto) { + attrs = Object.getOwnPropertyDescriptor(proto, i); + } + + if (attrs && attrs.set == null) { + continue; + } + child[i] = _clone(parent[i], depth - 1); + } + + return child; + } + + return _clone(parent, depth); +} + +/** + * Simple flat clone using prototype, accepts only objects, usefull for property + * override on FLAT configuration object (no nested props). + * + * USE WITH CAUTION! This may not behave as you wish if you do not know how this + * works. + */ +clone.clonePrototype = function clonePrototype(parent) { + if (parent === null) + return null; + + var c = function () {}; + c.prototype = parent; + return new c(); +}; + +// private utility functions + +function __objToStr(o) { + return Object.prototype.toString.call(o); +}; +clone.__objToStr = __objToStr; + +function __isDate(o) { + return typeof o === 'object' && __objToStr(o) === '[object Date]'; +}; +clone.__isDate = __isDate; + +function __isArray(o) { + return typeof o === 'object' && __objToStr(o) === '[object Array]'; +}; +clone.__isArray = __isArray; + +function __isRegExp(o) { + return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; +}; +clone.__isRegExp = __isRegExp; + +function __getRegExpFlags(re) { + var flags = ''; + if (re.global) flags += 'g'; + if (re.ignoreCase) flags += 'i'; + if (re.multiline) flags += 'm'; + return flags; +}; +clone.__getRegExpFlags = __getRegExpFlags; + +return clone; +})(); + +if (typeof module === 'object' && module.exports) { + module.exports = clone; +} diff --git a/node_modules/clone/package.json b/node_modules/clone/package.json new file mode 100644 index 0000000..70287cd --- /dev/null +++ b/node_modules/clone/package.json @@ -0,0 +1,137 @@ +{ + "_from": "clone@^1.0.2", + "_id": "clone@1.0.4", + "_inBundle": false, + "_integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", + "_location": "/clone", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "clone@^1.0.2", + "name": "clone", + "escapedName": "clone", + "rawSpec": "^1.0.2", + "saveSpec": null, + "fetchSpec": "^1.0.2" + }, + "_requiredBy": [ + "/defaults" + ], + "_resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "_shasum": "da309cc263df15994c688ca902179ca3c7cd7c7e", + "_spec": "clone@^1.0.2", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/defaults", + "author": { + "name": "Paul Vorbach", + "email": "paul@vorba.ch", + "url": "http://paul.vorba.ch/" + }, + "bugs": { + "url": "https://github.com/pvorb/node-clone/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Blake Miner", + "email": "miner.blake@gmail.com", + "url": "http://www.blakeminer.com/" + }, + { + "name": "Tian You", + "email": "axqd001@gmail.com", + "url": "http://blog.axqd.net/" + }, + { + "name": "George Stagas", + "email": "gstagas@gmail.com", + "url": "http://stagas.com/" + }, + { + "name": "Tobiasz Cudnik", + "email": "tobiasz.cudnik@gmail.com", + "url": "https://github.com/TobiaszCudnik" + }, + { + "name": "Pavel Lang", + "email": "langpavel@phpskelet.org", + "url": "https://github.com/langpavel" + }, + { + "name": "Dan MacTough", + "url": "http://yabfog.com/" + }, + { + "name": "w1nk", + "url": "https://github.com/w1nk" + }, + { + "name": "Hugh Kennedy", + "url": "http://twitter.com/hughskennedy" + }, + { + "name": "Dustin Diaz", + "url": "http://dustindiaz.com" + }, + { + "name": "Ilya Shaisultanov", + "url": "https://github.com/diversario" + }, + { + "name": "Nathan MacInnes", + "email": "nathan@macinn.es", + "url": "http://macinn.es/" + }, + { + "name": "Benjamin E. Coe", + "email": "ben@npmjs.com", + "url": "https://twitter.com/benjamincoe" + }, + { + "name": "Nathan Zadoks", + "url": "https://github.com/nathan7" + }, + { + "name": "Róbert Oroszi", + "email": "robert+gh@oroszi.net", + "url": "https://github.com/oroce" + }, + { + "name": "Aurélio A. Heckert", + "url": "http://softwarelivre.org/aurium" + }, + { + "name": "Guy Ellis", + "url": "http://www.guyellisrocks.com/" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "deep cloning of objects and arrays", + "devDependencies": { + "nodeunit": "~0.9.0" + }, + "engines": { + "node": ">=0.8" + }, + "homepage": "https://github.com/pvorb/node-clone#readme", + "license": "MIT", + "main": "clone.js", + "name": "clone", + "optionalDependencies": {}, + "repository": { + "type": "git", + "url": "git://github.com/pvorb/node-clone.git" + }, + "scripts": { + "test": "nodeunit test.js" + }, + "tags": [ + "clone", + "object", + "array", + "function", + "date" + ], + "version": "1.0.4" +} diff --git a/node_modules/color-convert/CHANGELOG.md b/node_modules/color-convert/CHANGELOG.md new file mode 100644 index 0000000..0a7bce4 --- /dev/null +++ b/node_modules/color-convert/CHANGELOG.md @@ -0,0 +1,54 @@ +# 1.0.0 - 2016-01-07 + +- Removed: unused speed test +- Added: Automatic routing between previously unsupported conversions +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Removed: `convert()` class +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Changed: all functions to lookup dictionary +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Changed: `ansi` to `ansi256` +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Fixed: argument grouping for functions requiring only one argument +([#27](https://github.com/Qix-/color-convert/pull/27)) + +# 0.6.0 - 2015-07-23 + +- Added: methods to handle +[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors: + - rgb2ansi16 + - rgb2ansi + - hsl2ansi16 + - hsl2ansi + - hsv2ansi16 + - hsv2ansi + - hwb2ansi16 + - hwb2ansi + - cmyk2ansi16 + - cmyk2ansi + - keyword2ansi16 + - keyword2ansi + - ansi162rgb + - ansi162hsl + - ansi162hsv + - ansi162hwb + - ansi162cmyk + - ansi162keyword + - ansi2rgb + - ansi2hsl + - ansi2hsv + - ansi2hwb + - ansi2cmyk + - ansi2keyword +([#18](https://github.com/harthur/color-convert/pull/18)) + +# 0.5.3 - 2015-06-02 + +- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]` +([#15](https://github.com/harthur/color-convert/issues/15)) + +--- + +Check out commit logs for older releases diff --git a/node_modules/color-convert/LICENSE b/node_modules/color-convert/LICENSE new file mode 100644 index 0000000..5b4c386 --- /dev/null +++ b/node_modules/color-convert/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011-2016 Heather Arthur <fayearthur@gmail.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. + diff --git a/node_modules/color-convert/README.md b/node_modules/color-convert/README.md new file mode 100644 index 0000000..d4b08fc --- /dev/null +++ b/node_modules/color-convert/README.md @@ -0,0 +1,68 @@ +# color-convert + +[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) + +Color-convert is a color conversion library for JavaScript and node. +It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): + +```js +var convert = require('color-convert'); + +convert.rgb.hsl(140, 200, 100); // [96, 48, 59] +convert.keyword.rgb('blue'); // [0, 0, 255] + +var rgbChannels = convert.rgb.channels; // 3 +var cmykChannels = convert.cmyk.channels; // 4 +var ansiChannels = convert.ansi16.channels; // 1 +``` + +# Install + +```console +$ npm install color-convert +``` + +# API + +Simply get the property of the _from_ and _to_ conversion that you're looking for. + +All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. + +All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). + +```js +var convert = require('color-convert'); + +// Hex to LAB +convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] +convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] + +// RGB to CMYK +convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] +convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] +``` + +### Arrays +All functions that accept multiple arguments also support passing an array. + +Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) + +```js +var convert = require('color-convert'); + +convert.rgb.hex(123, 45, 67); // '7B2D43' +convert.rgb.hex([123, 45, 67]); // '7B2D43' +``` + +## Routing + +Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). + +Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). + +# Contribute + +If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. + +# License +Copyright © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). diff --git a/node_modules/color-convert/conversions.js b/node_modules/color-convert/conversions.js new file mode 100644 index 0000000..2657f26 --- /dev/null +++ b/node_modules/color-convert/conversions.js @@ -0,0 +1,839 @@ +/* MIT license */ +/* eslint-disable no-mixed-operators */ +const cssKeywords = require('color-name'); + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +const reverseKeywords = {}; +for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; +} + +const convert = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +module.exports = convert; + +// Hide .channels and .labels properties +for (const model of Object.keys(convert)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + const {channels, labels} = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); +} + +convert.rgb.hsl = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + const l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +function comparativeDistance(x, y) { + /* + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + */ + return ( + ((x[0] - y[0]) ** 2) + + ((x[1] - y[1]) ** 2) + + ((x[2] - y[2]) ** 2) + ); +} + +convert.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + let currentClosestDistance = Infinity; + let currentClosestKeyword; + + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; + + // Compute comparative distance + const distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + + // Assume sRGB + r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); + g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); + b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); + + const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + const t1 = 2 * l - t2; + + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert.hsl.hsv = function (hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert.hsv.rgb = function (hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - (s * f)); + const t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert.hsv.hsl = function (hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; + + // Wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + const n = wh + f * (v - wh); // Linear interpolation + + let r; + let g; + let b; + /* eslint-disable max-statements-per-line,no-multi-spaces */ + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + /* eslint-enable max-statements-per-line,no-multi-spaces */ + + return [r * 255, g * 255, b * 255]; +}; + +convert.cmyk.rgb = function (cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.rgb = function (xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // Assume sRGB + r = r > 0.0031308 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + const c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert.lch.lab = function (lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + let ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; + +convert.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; + + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + const ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert.ansi16.rgb = function (args) { + let color = args % 10; + + // Handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + const mult = (~~(args > 50) + 1) * 0.5; + const r = ((color & 1) * mult) * 255; + const g = (((color >> 1) & 1) * mult) * 255; + const b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.hex.rgb = function (args) { + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + let colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } + + const integer = parseInt(colorString, 16); + const r = (integer >> 16) & 0xFF; + const g = (integer >> 8) & 0xFF; + const b = integer & 0xFF; + + return [r, g, b]; +}; + +convert.rgb.hcg = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = (max - min); + let grayscale; + let hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); + + let f = 0; + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + + const c = s * v; + let f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + const pure = [0, 0, 0]; + const hi = (h % 1) * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + + /* eslint-disable max-statements-per-line */ + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + /* eslint-enable max-statements-per-line */ + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const v = c + g * (1.0 - c); + let f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert.hcg.hwb = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert.hwb.hcg = function (hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert.gray.hsl = function (args) { + return [0, 0, args[0]]; +}; + +convert.gray.hsv = convert.gray.hsl; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; diff --git a/node_modules/color-convert/index.js b/node_modules/color-convert/index.js new file mode 100644 index 0000000..b648e57 --- /dev/null +++ b/node_modules/color-convert/index.js @@ -0,0 +1,81 @@ +const conversions = require('./conversions'); +const route = require('./route'); + +const convert = {}; + +const models = Object.keys(conversions); + +function wrapRaw(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + return fn(args); + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + const result = fn(args); + + // We're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(fromModel => { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + const routes = route(fromModel); + const routeModels = Object.keys(routes); + + routeModels.forEach(toModel => { + const fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +module.exports = convert; diff --git a/node_modules/color-convert/package.json b/node_modules/color-convert/package.json new file mode 100644 index 0000000..0c19037 --- /dev/null +++ b/node_modules/color-convert/package.json @@ -0,0 +1,83 @@ +{ + "_from": "color-convert@^2.0.1", + "_id": "color-convert@2.0.1", + "_inBundle": false, + "_integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "_location": "/color-convert", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "color-convert@^2.0.1", + "name": "color-convert", + "escapedName": "color-convert", + "rawSpec": "^2.0.1", + "saveSpec": null, + "fetchSpec": "^2.0.1" + }, + "_requiredBy": [ + "/ansi-styles" + ], + "_resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "_shasum": "72d3a68d598c9bdb3af2ad1e84f21d896abd4de3", + "_spec": "color-convert@^2.0.1", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/ansi-styles", + "author": { + "name": "Heather Arthur", + "email": "fayearthur@gmail.com" + }, + "bugs": { + "url": "https://github.com/Qix-/color-convert/issues" + }, + "bundleDependencies": false, + "dependencies": { + "color-name": "~1.1.4" + }, + "deprecated": false, + "description": "Plain color conversion functions", + "devDependencies": { + "chalk": "^2.4.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=7.0.0" + }, + "files": [ + "index.js", + "conversions.js", + "route.js" + ], + "homepage": "https://github.com/Qix-/color-convert#readme", + "keywords": [ + "color", + "colour", + "convert", + "converter", + "conversion", + "rgb", + "hsl", + "hsv", + "hwb", + "cmyk", + "ansi", + "ansi16" + ], + "license": "MIT", + "name": "color-convert", + "repository": { + "type": "git", + "url": "git+https://github.com/Qix-/color-convert.git" + }, + "scripts": { + "pretest": "xo", + "test": "node test/basic.js" + }, + "version": "2.0.1", + "xo": { + "rules": { + "default-case": 0, + "no-inline-comments": 0, + "operator-linebreak": 0 + } + } +} diff --git a/node_modules/color-convert/route.js b/node_modules/color-convert/route.js new file mode 100644 index 0000000..1a08521 --- /dev/null +++ b/node_modules/color-convert/route.js @@ -0,0 +1,97 @@ +const conversions = require('./conversions'); + +/* + This function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions); + + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; // Unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); + + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions[graph[toModel].parent][toModel]; + + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +module.exports = function (fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; + + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + diff --git a/node_modules/color-name/LICENSE b/node_modules/color-name/LICENSE new file mode 100644 index 0000000..c6b1001 --- /dev/null +++ b/node_modules/color-name/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT)
+Copyright (c) 2015 Dmitry Ivanov
+
+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/color-name/README.md b/node_modules/color-name/README.md new file mode 100644 index 0000000..932b979 --- /dev/null +++ b/node_modules/color-name/README.md @@ -0,0 +1,11 @@ +A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors.
+
+[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/)
+
+
+```js
+var colors = require('color-name');
+colors.red //[255,0,0]
+```
+
+<a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a>
diff --git a/node_modules/color-name/index.js b/node_modules/color-name/index.js new file mode 100644 index 0000000..b7c198a --- /dev/null +++ b/node_modules/color-name/index.js @@ -0,0 +1,152 @@ +'use strict'
+
+module.exports = {
+ "aliceblue": [240, 248, 255],
+ "antiquewhite": [250, 235, 215],
+ "aqua": [0, 255, 255],
+ "aquamarine": [127, 255, 212],
+ "azure": [240, 255, 255],
+ "beige": [245, 245, 220],
+ "bisque": [255, 228, 196],
+ "black": [0, 0, 0],
+ "blanchedalmond": [255, 235, 205],
+ "blue": [0, 0, 255],
+ "blueviolet": [138, 43, 226],
+ "brown": [165, 42, 42],
+ "burlywood": [222, 184, 135],
+ "cadetblue": [95, 158, 160],
+ "chartreuse": [127, 255, 0],
+ "chocolate": [210, 105, 30],
+ "coral": [255, 127, 80],
+ "cornflowerblue": [100, 149, 237],
+ "cornsilk": [255, 248, 220],
+ "crimson": [220, 20, 60],
+ "cyan": [0, 255, 255],
+ "darkblue": [0, 0, 139],
+ "darkcyan": [0, 139, 139],
+ "darkgoldenrod": [184, 134, 11],
+ "darkgray": [169, 169, 169],
+ "darkgreen": [0, 100, 0],
+ "darkgrey": [169, 169, 169],
+ "darkkhaki": [189, 183, 107],
+ "darkmagenta": [139, 0, 139],
+ "darkolivegreen": [85, 107, 47],
+ "darkorange": [255, 140, 0],
+ "darkorchid": [153, 50, 204],
+ "darkred": [139, 0, 0],
+ "darksalmon": [233, 150, 122],
+ "darkseagreen": [143, 188, 143],
+ "darkslateblue": [72, 61, 139],
+ "darkslategray": [47, 79, 79],
+ "darkslategrey": [47, 79, 79],
+ "darkturquoise": [0, 206, 209],
+ "darkviolet": [148, 0, 211],
+ "deeppink": [255, 20, 147],
+ "deepskyblue": [0, 191, 255],
+ "dimgray": [105, 105, 105],
+ "dimgrey": [105, 105, 105],
+ "dodgerblue": [30, 144, 255],
+ "firebrick": [178, 34, 34],
+ "floralwhite": [255, 250, 240],
+ "forestgreen": [34, 139, 34],
+ "fuchsia": [255, 0, 255],
+ "gainsboro": [220, 220, 220],
+ "ghostwhite": [248, 248, 255],
+ "gold": [255, 215, 0],
+ "goldenrod": [218, 165, 32],
+ "gray": [128, 128, 128],
+ "green": [0, 128, 0],
+ "greenyellow": [173, 255, 47],
+ "grey": [128, 128, 128],
+ "honeydew": [240, 255, 240],
+ "hotpink": [255, 105, 180],
+ "indianred": [205, 92, 92],
+ "indigo": [75, 0, 130],
+ "ivory": [255, 255, 240],
+ "khaki": [240, 230, 140],
+ "lavender": [230, 230, 250],
+ "lavenderblush": [255, 240, 245],
+ "lawngreen": [124, 252, 0],
+ "lemonchiffon": [255, 250, 205],
+ "lightblue": [173, 216, 230],
+ "lightcoral": [240, 128, 128],
+ "lightcyan": [224, 255, 255],
+ "lightgoldenrodyellow": [250, 250, 210],
+ "lightgray": [211, 211, 211],
+ "lightgreen": [144, 238, 144],
+ "lightgrey": [211, 211, 211],
+ "lightpink": [255, 182, 193],
+ "lightsalmon": [255, 160, 122],
+ "lightseagreen": [32, 178, 170],
+ "lightskyblue": [135, 206, 250],
+ "lightslategray": [119, 136, 153],
+ "lightslategrey": [119, 136, 153],
+ "lightsteelblue": [176, 196, 222],
+ "lightyellow": [255, 255, 224],
+ "lime": [0, 255, 0],
+ "limegreen": [50, 205, 50],
+ "linen": [250, 240, 230],
+ "magenta": [255, 0, 255],
+ "maroon": [128, 0, 0],
+ "mediumaquamarine": [102, 205, 170],
+ "mediumblue": [0, 0, 205],
+ "mediumorchid": [186, 85, 211],
+ "mediumpurple": [147, 112, 219],
+ "mediumseagreen": [60, 179, 113],
+ "mediumslateblue": [123, 104, 238],
+ "mediumspringgreen": [0, 250, 154],
+ "mediumturquoise": [72, 209, 204],
+ "mediumvioletred": [199, 21, 133],
+ "midnightblue": [25, 25, 112],
+ "mintcream": [245, 255, 250],
+ "mistyrose": [255, 228, 225],
+ "moccasin": [255, 228, 181],
+ "navajowhite": [255, 222, 173],
+ "navy": [0, 0, 128],
+ "oldlace": [253, 245, 230],
+ "olive": [128, 128, 0],
+ "olivedrab": [107, 142, 35],
+ "orange": [255, 165, 0],
+ "orangered": [255, 69, 0],
+ "orchid": [218, 112, 214],
+ "palegoldenrod": [238, 232, 170],
+ "palegreen": [152, 251, 152],
+ "paleturquoise": [175, 238, 238],
+ "palevioletred": [219, 112, 147],
+ "papayawhip": [255, 239, 213],
+ "peachpuff": [255, 218, 185],
+ "peru": [205, 133, 63],
+ "pink": [255, 192, 203],
+ "plum": [221, 160, 221],
+ "powderblue": [176, 224, 230],
+ "purple": [128, 0, 128],
+ "rebeccapurple": [102, 51, 153],
+ "red": [255, 0, 0],
+ "rosybrown": [188, 143, 143],
+ "royalblue": [65, 105, 225],
+ "saddlebrown": [139, 69, 19],
+ "salmon": [250, 128, 114],
+ "sandybrown": [244, 164, 96],
+ "seagreen": [46, 139, 87],
+ "seashell": [255, 245, 238],
+ "sienna": [160, 82, 45],
+ "silver": [192, 192, 192],
+ "skyblue": [135, 206, 235],
+ "slateblue": [106, 90, 205],
+ "slategray": [112, 128, 144],
+ "slategrey": [112, 128, 144],
+ "snow": [255, 250, 250],
+ "springgreen": [0, 255, 127],
+ "steelblue": [70, 130, 180],
+ "tan": [210, 180, 140],
+ "teal": [0, 128, 128],
+ "thistle": [216, 191, 216],
+ "tomato": [255, 99, 71],
+ "turquoise": [64, 224, 208],
+ "violet": [238, 130, 238],
+ "wheat": [245, 222, 179],
+ "white": [255, 255, 255],
+ "whitesmoke": [245, 245, 245],
+ "yellow": [255, 255, 0],
+ "yellowgreen": [154, 205, 50]
+};
diff --git a/node_modules/color-name/package.json b/node_modules/color-name/package.json new file mode 100644 index 0000000..cfea328 --- /dev/null +++ b/node_modules/color-name/package.json @@ -0,0 +1,56 @@ +{ + "_from": "color-name@~1.1.4", + "_id": "color-name@1.1.4", + "_inBundle": false, + "_integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "_location": "/color-name", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "color-name@~1.1.4", + "name": "color-name", + "escapedName": "color-name", + "rawSpec": "~1.1.4", + "saveSpec": null, + "fetchSpec": "~1.1.4" + }, + "_requiredBy": [ + "/color-convert" + ], + "_resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "_shasum": "c2a09a87acbde69543de6f63fa3995c826c536a2", + "_spec": "color-name@~1.1.4", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/color-convert", + "author": { + "name": "DY", + "email": "dfcreative@gmail.com" + }, + "bugs": { + "url": "https://github.com/colorjs/color-name/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A list of color names and its values", + "files": [ + "index.js" + ], + "homepage": "https://github.com/colorjs/color-name", + "keywords": [ + "color-name", + "color", + "color-keyword", + "keyword" + ], + "license": "MIT", + "main": "index.js", + "name": "color-name", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/colorjs/color-name.git" + }, + "scripts": { + "test": "node test.js" + }, + "version": "1.1.4" +} diff --git a/node_modules/colors/LICENSE b/node_modules/colors/LICENSE new file mode 100644 index 0000000..17880ff --- /dev/null +++ b/node_modules/colors/LICENSE @@ -0,0 +1,25 @@ +MIT License + +Original Library + - Copyright (c) Marak Squires + +Additional Functionality + - Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/colors/README.md b/node_modules/colors/README.md new file mode 100644 index 0000000..fabe558 --- /dev/null +++ b/node_modules/colors/README.md @@ -0,0 +1,221 @@ +# colors.js +[![Build Status](https://travis-ci.org/Marak/colors.js.svg?branch=master)](https://travis-ci.org/Marak/colors.js) +[![version](https://img.shields.io/npm/v/colors.svg)](https://www.npmjs.org/package/colors) +[![dependencies](https://david-dm.org/Marak/colors.js.svg)](https://david-dm.org/Marak/colors.js) +[![devDependencies](https://david-dm.org/Marak/colors.js/dev-status.svg)](https://david-dm.org/Marak/colors.js#info=devDependencies) + +Please check out the [roadmap](ROADMAP.md) for upcoming features and releases. Please open Issues to provide feedback, and check the `develop` branch for the latest bleeding-edge updates. + +## 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 + +### bright text colors + + - brightRed + - brightGreen + - brightYellow + - brightBlue + - brightMagenta + - brightCyan + - brightWhite + +### background colors + + - bgBlack + - bgRed + - bgGreen + - bgYellow + - bgBlue + - bgMagenta + - bgCyan + - bgWhite + - bgGray + - bgGrey + +### bright background colors + + - bgBrightRed + - bgBrightGreen + - bgBrightYellow + - bgBrightBlue + - bgBrightMagenta + - bgBrightCyan + - bgBrightWhite + +### 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. + +## Enabling/Disabling Colors + +The package will auto-detect whether your terminal can use colors and enable/disable accordingly. When colors are disabled, the color functions do nothing. You can override this with a command-line flag: + +```bash +node myapp.js --no-color +node myapp.js --color=false + +node myapp.js --color +node myapp.js --color=true +node myapp.js --color=always + +FORCE_COLOR=1 node myapp.js +``` + +Or in code: + +```javascript +var colors = require('colors'); +colors.enable(); +colors.disable(); +``` + +## 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")); + +``` + +### Combining Colors + +```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 0000000..822db1c --- /dev/null +++ b/node_modules/colors/examples/normal-usage.js @@ -0,0 +1,82 @@ +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); + +// styles not widely supported +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); +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('Blindingly '.brightCyan + 'bright? '.brightRed + 'Why '.brightYellow + 'not?!'.brightGreen); + +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 +try { + colors.setTheme(require(__dirname + '/../themes/generic-logging.js')); +} catch (err) { + console.log(err); +} + +// 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) + diff --git a/node_modules/colors/examples/safe-string.js b/node_modules/colors/examples/safe-string.js new file mode 100644 index 0000000..5bc0168 --- /dev/null +++ b/node_modules/colors/examples/safe-string.js @@ -0,0 +1,79 @@ +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'))); + +// styles not widely supported +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! ')); + +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(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!')); + +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: 'blue', + 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 blue 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(require(__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/index.d.ts b/node_modules/colors/index.d.ts new file mode 100644 index 0000000..baa7068 --- /dev/null +++ b/node_modules/colors/index.d.ts @@ -0,0 +1,136 @@ +// Type definitions for Colors.js 1.2 +// Project: https://github.com/Marak/colors.js +// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Staffan Eketorp <https://github.com/staeke> +// Definitions: https://github.com/Marak/colors.js + +export interface Color { + (text: string): string; + + strip: Color; + stripColors: Color; + + black: Color; + red: Color; + green: Color; + yellow: Color; + blue: Color; + magenta: Color; + cyan: Color; + white: Color; + gray: Color; + grey: Color; + + bgBlack: Color; + bgRed: Color; + bgGreen: Color; + bgYellow: Color; + bgBlue: Color; + bgMagenta: Color; + bgCyan: Color; + bgWhite: Color; + + reset: Color; + bold: Color; + dim: Color; + italic: Color; + underline: Color; + inverse: Color; + hidden: Color; + strikethrough: Color; + + rainbow: Color; + zebra: Color; + america: Color; + trap: Color; + random: Color; + zalgo: Color; +} + +export function enable(): void; +export function disable(): void; +export function setTheme(theme: any): void; + +export let enabled: boolean; + +export const strip: Color; +export const stripColors: Color; + +export const black: Color; +export const red: Color; +export const green: Color; +export const yellow: Color; +export const blue: Color; +export const magenta: Color; +export const cyan: Color; +export const white: Color; +export const gray: Color; +export const grey: Color; + +export const bgBlack: Color; +export const bgRed: Color; +export const bgGreen: Color; +export const bgYellow: Color; +export const bgBlue: Color; +export const bgMagenta: Color; +export const bgCyan: Color; +export const bgWhite: Color; + +export const reset: Color; +export const bold: Color; +export const dim: Color; +export const italic: Color; +export const underline: Color; +export const inverse: Color; +export const hidden: Color; +export const strikethrough: Color; + +export const rainbow: Color; +export const zebra: Color; +export const america: Color; +export const trap: Color; +export const random: Color; +export const zalgo: Color; + +declare global { + interface String { + strip: string; + stripColors: string; + + black: string; + red: string; + green: string; + yellow: string; + blue: string; + magenta: string; + cyan: string; + white: string; + gray: string; + grey: string; + + bgBlack: string; + bgRed: string; + bgGreen: string; + bgYellow: string; + bgBlue: string; + bgMagenta: string; + bgCyan: string; + bgWhite: string; + + reset: string; + // @ts-ignore + bold: string; + dim: string; + italic: string; + underline: string; + inverse: string; + hidden: string; + strikethrough: string; + + rainbow: string; + zebra: string; + america: string; + trap: string; + random: string; + zalgo: string; + } +} diff --git a/node_modules/colors/lib/colors.js b/node_modules/colors/lib/colors.js new file mode 100644 index 0000000..9c7f1d1 --- /dev/null +++ b/node_modules/colors/lib/colors.js @@ -0,0 +1,211 @@ +/* + +The MIT License (MIT) + +Original Library + - Copyright (c) Marak Squires + +Additional functionality + - Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var colors = {}; +module['exports'] = colors; + +colors.themes = {}; + +var util = require('util'); +var ansiStyles = colors.styles = require('./styles'); +var defineProps = Object.defineProperties; +var newLineRegex = new RegExp(/[\r\n]+/g); + +colors.supportsColor = require('./system/supports-colors').supportsColor; + +if (typeof colors.enabled === 'undefined') { + colors.enabled = colors.supportsColor() !== false; +} + +colors.enable = function() { + colors.enabled = true; +}; + +colors.disable = function() { + colors.enabled = false; +}; + +colors.stripColors = colors.strip = function(str) { + return ('' + str).replace(/\x1B\[\d+m/g, ''); +}; + +// eslint-disable-next-line no-unused-vars +var stylize = colors.stylize = function stylize(str, style) { + if (!colors.enabled) { + return str+''; + } + + var styleMap = ansiStyles[style]; + + // Stylize should work for non-ANSI styles, too + if(!styleMap && style in colors){ + // Style maps like trap operate as functions on strings; + // they don't have properties like open or close. + return colors[style](str); + } + + return styleMap.open + str + styleMap.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 = Array.prototype.slice.call(arguments); + + var str = args.map(function(arg) { + // Use weak equality check so we can colorize null/undefined in safe mode + if (arg != null && arg.constructor === String) { + return arg; + } else { + return util.inspect(arg); + } + }).join(' '); + + if (!colors.enabled || !str) { + return str; + } + + var newLinesPresent = str.indexOf('\n') != -1; + + 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; + if (newLinesPresent) { + str = str.replace(newLineRegex, function(match) { + return code.close + match + code.open; + }); + } + } + + return str; +} + +colors.setTheme = function(theme) { + if (typeof theme === 'string') { + console.log('colors.setTheme now only accepts an object, not a string. ' + + 'If you are trying to set a theme from a file, it is now your (the ' + + 'caller\'s) responsibility to require the file. The old syntax ' + + 'looked like colors.setTheme(__dirname + ' + + '\'/../themes/generic-logging.js\'); The new syntax looks like '+ + 'colors.setTheme(require(__dirname + ' + + '\'/../themes/generic-logging.js\'));'); + return; + } + 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); + } +}; + +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(''); + 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); +colors.maps.zebra = require('./maps/zebra')(colors); +colors.maps.rainbow = require('./maps/rainbow')(colors); +colors.maps.random = require('./maps/random')(colors); + +for (var map in colors.maps) { + (function(map) { + colors[map] = function(str) { + return sequencer(colors.maps[map], str); + }; + })(map); +} + +defineProps(colors, init()); diff --git a/node_modules/colors/lib/custom/trap.js b/node_modules/colors/lib/custom/trap.js new file mode 100644 index 0000000..fbccf88 --- /dev/null +++ b/node_modules/colors/lib/custom/trap.js @@ -0,0 +1,46 @@ +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 0000000..0ef2b01 --- /dev/null +++ b/node_modules/colors/lib/custom/zalgo.js @@ -0,0 +1,110 @@ +// please no +module['exports'] = function zalgo(text, options) { + text = text || ' he is here '; + var soul = { + 'up': [ + '̍', '̎', '̄', '̅', + '̿', '̑', '̆', '̐', + '͒', '͗', '͑', '̇', + '̈', '̊', '͂', '̓', + '̈', '͊', '͋', '͌', + '̃', '̂', '̌', '͐', + '̀', '́', '̋', '̏', + '̒', '̓', '̔', '̽', + '̉', 'ͣ', 'ͤ', 'ͥ', + 'ͦ', 'ͧ', 'ͨ', 'ͩ', + 'ͪ', 'ͫ', 'ͬ', 'ͭ', + 'ͮ', 'ͯ', '̾', '͛', + '͆', '̚', + ], + 'down': [ + '̖', '̗', '̘', '̙', + '̜', '̝', '̞', '̟', + '̠', '̤', '̥', '̦', + '̩', '̪', '̫', '̬', + '̭', '̮', '̯', '̰', + '̱', '̲', '̳', '̹', + '̺', '̻', '̼', 'ͅ', + '͇', '͈', '͉', '͍', + '͎', '͓', '͔', '͕', + '͖', '͙', '͚', '̣', + ], + 'mid': [ + '̕', '̛', '̀', '́', + '͘', '̡', '̢', '̧', + '̨', '̴', '̵', '̶', + '͜', '͝', '͞', + '͟', '͠', '͢', '̸', + '̷', '͡', ' ҉', + ], + }; + var all = [].concat(soul.up, soul.down, soul.mid); + + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } + + function isChar(character) { + var bool = false; + all.filter(function(i) { + bool = (i === character); + }); + return bool; + } + + + function heComes(text, options) { + var result = ''; + var counts; + var 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 (isChar(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 0000000..46fd386 --- /dev/null +++ b/node_modules/colors/lib/extendStringPrototype.js @@ -0,0 +1,110 @@ +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); + }; + + 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', 'repeat', '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[prop](this); + }); + } else { + var themePropApplicator = function(str) { + var ret = str || this; + for (var t = 0; t < theme[prop].length; t++) { + ret = colors[theme[prop][t]](ret); + } + return ret; + }; + addProperty(prop, themePropApplicator); + colors[prop] = function(str) { + return themePropApplicator(str); + }; + } + } + }); + } + + colors.setTheme = function(theme) { + if (typeof theme === 'string') { + console.log('colors.setTheme now only accepts an object, not a string. ' + + 'If you are trying to set a theme from a file, it is now your (the ' + + 'caller\'s) responsibility to require the file. The old syntax ' + + 'looked like colors.setTheme(__dirname + ' + + '\'/../themes/generic-logging.js\'); The new syntax looks like '+ + 'colors.setTheme(require(__dirname + ' + + '\'/../themes/generic-logging.js\'));'); + return; + } else { + applyTheme(theme); + } + }; +}; diff --git a/node_modules/colors/lib/index.js b/node_modules/colors/lib/index.js new file mode 100644 index 0000000..9df5ab7 --- /dev/null +++ b/node_modules/colors/lib/index.js @@ -0,0 +1,13 @@ +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')(); diff --git a/node_modules/colors/lib/maps/america.js b/node_modules/colors/lib/maps/america.js new file mode 100644 index 0000000..dc96903 --- /dev/null +++ b/node_modules/colors/lib/maps/america.js @@ -0,0 +1,10 @@ +module['exports'] = function(colors) { + 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); + } + }; +}; diff --git a/node_modules/colors/lib/maps/rainbow.js b/node_modules/colors/lib/maps/rainbow.js new file mode 100644 index 0000000..2b00ac0 --- /dev/null +++ b/node_modules/colors/lib/maps/rainbow.js @@ -0,0 +1,12 @@ +module['exports'] = function(colors) { + // RoY G BiV + var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; + 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 0000000..3d82a39 --- /dev/null +++ b/node_modules/colors/lib/maps/random.js @@ -0,0 +1,11 @@ +module['exports'] = function(colors) { + var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', + 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', + 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta']; + return function(letter, i, exploded) { + return letter === ' ' ? letter : + colors[ + available[Math.round(Math.random() * (available.length - 2))] + ](letter); + }; +}; diff --git a/node_modules/colors/lib/maps/zebra.js b/node_modules/colors/lib/maps/zebra.js new file mode 100644 index 0000000..fa73623 --- /dev/null +++ b/node_modules/colors/lib/maps/zebra.js @@ -0,0 +1,5 @@ +module['exports'] = function(colors) { + return function(letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); + }; +}; diff --git a/node_modules/colors/lib/styles.js b/node_modules/colors/lib/styles.js new file mode 100644 index 0000000..011dafd --- /dev/null +++ b/node_modules/colors/lib/styles.js @@ -0,0 +1,95 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +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], + + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 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], + bgGray: [100, 49], + bgGrey: [100, 49], + + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 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'; +}); diff --git a/node_modules/colors/lib/system/has-flag.js b/node_modules/colors/lib/system/has-flag.js new file mode 100644 index 0000000..a347dd4 --- /dev/null +++ b/node_modules/colors/lib/system/has-flag.js @@ -0,0 +1,35 @@ +/* +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +'use strict'; + +module.exports = function(flag, argv) { + argv = argv || process.argv; + + var terminatorPos = argv.indexOf('--'); + var prefix = /^-{1,2}/.test(flag) ? '' : '--'; + var pos = argv.indexOf(prefix + flag); + + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; 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 0000000..f1f9c8f --- /dev/null +++ b/node_modules/colors/lib/system/supports-colors.js @@ -0,0 +1,151 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +'use strict'; + +var os = require('os'); +var hasFlag = require('./has-flag.js'); + +var env = process.env; + +var forceColor = void 0; +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') + || hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 + || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') + || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + var min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first + // Windows release that supports 256 colors. Windows 10 build 14931 is the + // first release that supports 16m/TrueColor. + var osRelease = os.release().split('.'); + if (Number(process.versions.node.split('.')[0]) >= 8 + && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { + return sign in env; + }) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 + ); + } + + if ('TERM_PROGRAM' in env) { + var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Hyper': + return 3; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + var level = supportsColor(stream); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr), +}; diff --git a/node_modules/colors/package.json b/node_modules/colors/package.json new file mode 100644 index 0000000..b094538 --- /dev/null +++ b/node_modules/colors/package.json @@ -0,0 +1,74 @@ +{ + "_from": "colors@^1.1.2", + "_id": "colors@1.4.0", + "_inBundle": false, + "_integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==", + "_location": "/colors", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "colors@^1.1.2", + "name": "colors", + "escapedName": "colors", + "rawSpec": "^1.1.2", + "saveSpec": null, + "fetchSpec": "^1.1.2" + }, + "_requiredBy": [ + "/prompt" + ], + "_resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "_shasum": "c50491479d4c1bdaed2c9ced32cf7c7dc2360f78", + "_spec": "colors@^1.1.2", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/prompt", + "author": { + "name": "Marak Squires" + }, + "bugs": { + "url": "https://github.com/Marak/colors.js/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "DABH", + "url": "https://github.com/DABH" + } + ], + "deprecated": false, + "description": "get colors in your node.js console", + "devDependencies": { + "eslint": "^5.2.0", + "eslint-config-google": "^0.11.0" + }, + "engines": { + "node": ">=0.1.90" + }, + "files": [ + "examples", + "lib", + "LICENSE", + "safe.js", + "themes", + "index.d.ts", + "safe.d.ts" + ], + "homepage": "https://github.com/Marak/colors.js", + "keywords": [ + "ansi", + "terminal", + "colors" + ], + "license": "MIT", + "main": "lib/index.js", + "name": "colors", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Marak/colors.js.git" + }, + "scripts": { + "lint": "eslint . --fix", + "test": "node tests/basic-test.js && node tests/safe-test.js" + }, + "version": "1.4.0" +} diff --git a/node_modules/colors/safe.d.ts b/node_modules/colors/safe.d.ts new file mode 100644 index 0000000..2bafc27 --- /dev/null +++ b/node_modules/colors/safe.d.ts @@ -0,0 +1,48 @@ +// Type definitions for Colors.js 1.2 +// Project: https://github.com/Marak/colors.js +// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Staffan Eketorp <https://github.com/staeke> +// Definitions: https://github.com/Marak/colors.js + +export const enabled: boolean; +export function enable(): void; +export function disable(): void; +export function setTheme(theme: any): void; + +export function strip(str: string): string; +export function stripColors(str: string): string; + +export function black(str: string): string; +export function red(str: string): string; +export function green(str: string): string; +export function yellow(str: string): string; +export function blue(str: string): string; +export function magenta(str: string): string; +export function cyan(str: string): string; +export function white(str: string): string; +export function gray(str: string): string; +export function grey(str: string): string; + +export function bgBlack(str: string): string; +export function bgRed(str: string): string; +export function bgGreen(str: string): string; +export function bgYellow(str: string): string; +export function bgBlue(str: string): string; +export function bgMagenta(str: string): string; +export function bgCyan(str: string): string; +export function bgWhite(str: string): string; + +export function reset(str: string): string; +export function bold(str: string): string; +export function dim(str: string): string; +export function italic(str: string): string; +export function underline(str: string): string; +export function inverse(str: string): string; +export function hidden(str: string): string; +export function strikethrough(str: string): string; + +export function rainbow(str: string): string; +export function zebra(str: string): string; +export function america(str: string): string; +export function trap(str: string): string; +export function random(str: string): string; +export function zalgo(str: string): string; diff --git a/node_modules/colors/safe.js b/node_modules/colors/safe.js new file mode 100644 index 0000000..a013d54 --- /dev/null +++ b/node_modules/colors/safe.js @@ -0,0 +1,10 @@ +// +// 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; diff --git a/node_modules/colors/themes/generic-logging.js b/node_modules/colors/themes/generic-logging.js new file mode 100644 index 0000000..63adfe4 --- /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', +}; diff --git a/node_modules/concat-map/.travis.yml b/node_modules/concat-map/.travis.yml new file mode 100644 index 0000000..f1d0f13 --- /dev/null +++ b/node_modules/concat-map/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/node_modules/concat-map/LICENSE b/node_modules/concat-map/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/concat-map/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +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/concat-map/README.markdown b/node_modules/concat-map/README.markdown new file mode 100644 index 0000000..408f70a --- /dev/null +++ b/node_modules/concat-map/README.markdown @@ -0,0 +1,62 @@ +concat-map +========== + +Concatenative mapdashery. + +[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map) + +[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map) + +example +======= + +``` js +var concatMap = require('concat-map'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); +``` + +*** + +``` +[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ] +``` + +methods +======= + +``` js +var concatMap = require('concat-map') +``` + +concatMap(xs, fn) +----------------- + +Return an array of concatenated elements by calling `fn(x, i)` for each element +`x` and each index `i` in the array `xs`. + +When `fn(x, i)` returns an array, its result will be concatenated with the +result array. If `fn(x, i)` returns anything else, that value will be pushed +onto the end of the result array. + +install +======= + +With [npm](http://npmjs.org) do: + +``` +npm install concat-map +``` + +license +======= + +MIT + +notes +===== + +This module was written while sitting high above the ground in a tree. diff --git a/node_modules/concat-map/example/map.js b/node_modules/concat-map/example/map.js new file mode 100644 index 0000000..3365621 --- /dev/null +++ b/node_modules/concat-map/example/map.js @@ -0,0 +1,6 @@ +var concatMap = require('../'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); diff --git a/node_modules/concat-map/index.js b/node_modules/concat-map/index.js new file mode 100644 index 0000000..b29a781 --- /dev/null +++ b/node_modules/concat-map/index.js @@ -0,0 +1,13 @@ +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; diff --git a/node_modules/concat-map/package.json b/node_modules/concat-map/package.json new file mode 100644 index 0000000..84be795 --- /dev/null +++ b/node_modules/concat-map/package.json @@ -0,0 +1,88 @@ +{ + "_from": "concat-map@0.0.1", + "_id": "concat-map@0.0.1", + "_inBundle": false, + "_integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "_location": "/concat-map", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "concat-map@0.0.1", + "name": "concat-map", + "escapedName": "concat-map", + "rawSpec": "0.0.1", + "saveSpec": null, + "fetchSpec": "0.0.1" + }, + "_requiredBy": [ + "/brace-expansion" + ], + "_resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "_shasum": "d8a96bd77fd68df7793a73036a3ba0d5405d477b", + "_spec": "concat-map@0.0.1", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/brace-expansion", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bugs": { + "url": "https://github.com/substack/node-concat-map/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "concatenative mapdashery", + "devDependencies": { + "tape": "~2.4.0" + }, + "directories": { + "example": "example", + "test": "test" + }, + "homepage": "https://github.com/substack/node-concat-map#readme", + "keywords": [ + "concat", + "concatMap", + "map", + "functional", + "higher-order" + ], + "license": "MIT", + "main": "index.js", + "name": "concat-map", + "repository": { + "type": "git", + "url": "git://github.com/substack/node-concat-map.git" + }, + "scripts": { + "test": "tape test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": { + "ie": [ + 6, + 7, + 8, + 9 + ], + "ff": [ + 3.5, + 10, + 15 + ], + "chrome": [ + 10, + 22 + ], + "safari": [ + 5.1 + ], + "opera": [ + 12 + ] + } + }, + "version": "0.0.1" +} diff --git a/node_modules/concat-map/test/map.js b/node_modules/concat-map/test/map.js new file mode 100644 index 0000000..fdbd702 --- /dev/null +++ b/node_modules/concat-map/test/map.js @@ -0,0 +1,39 @@ +var concatMap = require('../'); +var test = require('tape'); + +test('empty or not', function (t) { + var xs = [ 1, 2, 3, 4, 5, 6 ]; + var ixes = []; + var ys = concatMap(xs, function (x, ix) { + ixes.push(ix); + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; + }); + t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]); + t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]); + t.end(); +}); + +test('always something', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ]; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('scalars', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : x; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('undefs', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function () {}); + t.same(ys, [ undefined, undefined, undefined, undefined ]); + t.end(); +}); diff --git a/node_modules/cycle/README.md b/node_modules/cycle/README.md new file mode 100644 index 0000000..de9a06d --- /dev/null +++ b/node_modules/cycle/README.md @@ -0,0 +1,49 @@ +Fork of https://github.com/douglascrockford/JSON-js, maintained in npm as `cycle`. + +# Contributors + +* Douglas Crockford +* Nuno Job +* Justin Warkentin + +# JSON in JavaScript + +Douglas Crockford +douglas@crockford.com + +2010-11-18 + + +JSON is a light-weight, language independent, data interchange format. +See http://www.JSON.org/ + +The files in this collection implement JSON encoders/decoders in JavaScript. + +JSON became a built-in feature of JavaScript when the ECMAScript Programming +Language Standard - Fifth Edition was adopted by the ECMA General Assembly +in December 2009. Most of the files in this collection are for applications +that are expected to run in obsolete web browsers. For most purposes, json2.js +is the best choice. + + +json2.js: This file creates a JSON property in the global object, if there +isn't already one, setting its value to an object containing a stringify +method and a parse method. The parse method uses the eval method to do the +parsing, guarding it with several regular expressions to defend against +accidental code execution hazards. On current browsers, this file does nothing, +prefering the built-in JSON object. + +json.js: This file does everything that json2.js does. It also adds a +toJSONString method and a parseJSON method to Object.prototype. Use of this +file is not recommended. + +json_parse.js: This file contains an alternative JSON parse function that +uses recursive descent instead of eval. + +json_parse_state.js: This files contains an alternative JSON parse function that +uses a state machine instead of eval. + +cycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle, +which make it possible to encode cyclical structures and dags in JSON, and to +then recover them. JSONPath is used to represent the links. +http://GOESSNER.net/articles/JsonPath/ diff --git a/node_modules/cycle/cycle.js b/node_modules/cycle/cycle.js new file mode 100644 index 0000000..2e776ad --- /dev/null +++ b/node_modules/cycle/cycle.js @@ -0,0 +1,170 @@ +/* + cycle.js + 2013-02-19 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. +*/ + +/*jslint evil: true, regexp: true */ + +/*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push, + retrocycle, stringify, test, toString +*/ + +var cycle = exports; + +cycle.decycle = function decycle(object) { + 'use strict'; + +// Make a deep copy of an object or array, assuring that there is at most +// one instance of each object or array in the resulting structure. The +// duplicate references (which might be forming cycles) are replaced with +// an object of the form +// {$ref: PATH} +// where the PATH is a JSONPath string that locates the first occurance. +// So, +// var a = []; +// a[0] = a; +// return JSON.stringify(JSON.decycle(a)); +// produces the string '[{"$ref":"$"}]'. + +// JSONPath is used to locate the unique object. $ indicates the top level of +// the object or array. [NUMBER] or [STRING] indicates a child member or +// property. + + var objects = [], // Keep a reference to each unique object or array + paths = []; // Keep the path to each unique object or array + + return (function derez(value, path) { + +// The derez recurses through the object, producing the deep copy. + + var i, // The loop counter + name, // Property name + nu; // The new object or array + +// typeof null === 'object', so go on if this value is really an object but not +// one of the weird builtin objects. + + if (typeof value === 'object' && value !== null && + !(value instanceof Boolean) && + !(value instanceof Date) && + !(value instanceof Number) && + !(value instanceof RegExp) && + !(value instanceof String)) { + +// If the value is an object or array, look to see if we have already +// encountered it. If so, return a $ref/path object. This is a hard way, +// linear search that will get slower as the number of unique objects grows. + + for (i = 0; i < objects.length; i += 1) { + if (objects[i] === value) { + return {$ref: paths[i]}; + } + } + +// Otherwise, accumulate the unique value and its path. + + objects.push(value); + paths.push(path); + +// If it is an array, replicate the array. + + if (Object.prototype.toString.apply(value) === '[object Array]') { + nu = []; + for (i = 0; i < value.length; i += 1) { + nu[i] = derez(value[i], path + '[' + i + ']'); + } + } else { + +// If it is an object, replicate the object. + + nu = {}; + for (name in value) { + if (Object.prototype.hasOwnProperty.call(value, name)) { + nu[name] = derez(value[name], + path + '[' + JSON.stringify(name) + ']'); + } + } + } + return nu; + } + return value; + }(object, '$')); +}; + + +cycle.retrocycle = function retrocycle($) { + 'use strict'; + +// Restore an object that was reduced by decycle. Members whose values are +// objects of the form +// {$ref: PATH} +// are replaced with references to the value found by the PATH. This will +// restore cycles. The object will be mutated. + +// The eval function is used to locate the values described by a PATH. The +// root object is kept in a $ variable. A regular expression is used to +// assure that the PATH is extremely well formed. The regexp contains nested +// * quantifiers. That has been known to have extremely bad performance +// problems on some browsers for very long strings. A PATH is expected to be +// reasonably short. A PATH is allowed to belong to a very restricted subset of +// Goessner's JSONPath. + +// So, +// var s = '[{"$ref":"$"}]'; +// return JSON.retrocycle(JSON.parse(s)); +// produces an array containing a single element which is the array itself. + + var px = + /^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/; + + (function rez(value) { + +// The rez function walks recursively through the object looking for $ref +// properties. When it finds one that has a value that is a path, then it +// replaces the $ref object with a reference to the value that is found by +// the path. + + var i, item, name, path; + + if (value && typeof value === 'object') { + if (Object.prototype.toString.apply(value) === '[object Array]') { + for (i = 0; i < value.length; i += 1) { + item = value[i]; + if (item && typeof item === 'object') { + path = item.$ref; + if (typeof path === 'string' && px.test(path)) { + value[i] = eval(path); + } else { + rez(item); + } + } + } + } else { + for (name in value) { + if (typeof value[name] === 'object') { + item = value[name]; + if (item) { + path = item.$ref; + if (typeof path === 'string' && px.test(path)) { + value[name] = eval(path); + } else { + rez(item); + } + } + } + } + } + } + }($)); + return $; +}; diff --git a/node_modules/cycle/package.json b/node_modules/cycle/package.json new file mode 100644 index 0000000..764d9a7 --- /dev/null +++ b/node_modules/cycle/package.json @@ -0,0 +1,49 @@ +{ + "_from": "cycle@1.0.x", + "_id": "cycle@1.0.3", + "_inBundle": false, + "_integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=", + "_location": "/cycle", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "cycle@1.0.x", + "name": "cycle", + "escapedName": "cycle", + "rawSpec": "1.0.x", + "saveSpec": null, + "fetchSpec": "1.0.x" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "_shasum": "21e80b2be8580f98b468f379430662b046c34ad2", + "_spec": "cycle@1.0.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/winston", + "author": "", + "bugs": { + "url": "http://github.com/douglascrockford/JSON-js/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "decycle your json", + "engines": { + "node": ">=0.4.0" + }, + "homepage": "https://github.com/douglascrockford/JSON-js", + "keywords": [ + "json", + "cycle", + "stringify", + "parse" + ], + "main": "./cycle.js", + "name": "cycle", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/dscape/cycle.git" + }, + "version": "1.0.3" +} diff --git a/node_modules/deep-equal/.travis.yml b/node_modules/deep-equal/.travis.yml new file mode 100644 index 0000000..f1d0f13 --- /dev/null +++ b/node_modules/deep-equal/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/node_modules/deep-equal/LICENSE b/node_modules/deep-equal/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/deep-equal/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +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/deep-equal/example/cmp.js b/node_modules/deep-equal/example/cmp.js new file mode 100644 index 0000000..67014b8 --- /dev/null +++ b/node_modules/deep-equal/example/cmp.js @@ -0,0 +1,11 @@ +var equal = require('../'); +console.dir([ + equal( + { a : [ 2, 3 ], b : [ 4 ] }, + { a : [ 2, 3 ], b : [ 4 ] } + ), + equal( + { x : 5, y : [6] }, + { x : 5, y : 6 } + ) +]); diff --git a/node_modules/deep-equal/index.js b/node_modules/deep-equal/index.js new file mode 100644 index 0000000..dbc11f2 --- /dev/null +++ b/node_modules/deep-equal/index.js @@ -0,0 +1,94 @@ +var pSlice = Array.prototype.slice; +var objectKeys = require('./lib/keys.js'); +var isArguments = require('./lib/is_arguments.js'); + +var deepEqual = module.exports = function (actual, expected, opts) { + if (!opts) opts = {}; + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + + } else if (actual instanceof Date && expected instanceof Date) { + return actual.getTime() === expected.getTime(); + + // 7.3. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (typeof actual != 'object' && typeof expected != 'object') { + return opts.strict ? actual === expected : actual == expected; + + // 7.4. For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else { + return objEquiv(actual, expected, opts); + } +} + +function isUndefinedOrNull(value) { + return value === null || value === undefined; +} + +function isBuffer (x) { + if (!x || typeof x !== 'object' || typeof x.length !== 'number') return false; + if (typeof x.copy !== 'function' || typeof x.slice !== 'function') { + return false; + } + if (x.length > 0 && typeof x[0] !== 'number') return false; + return true; +} + +function objEquiv(a, b, opts) { + var i, key; + if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) + return false; + // an identical 'prototype' property. + if (a.prototype !== b.prototype) return false; + //~~~I've managed to break Object.keys through screwy arguments passing. + // Converting to array solves the problem. + if (isArguments(a)) { + if (!isArguments(b)) { + return false; + } + a = pSlice.call(a); + b = pSlice.call(b); + return deepEqual(a, b, opts); + } + if (isBuffer(a)) { + if (!isBuffer(b)) { + return false; + } + if (a.length !== b.length) return false; + for (i = 0; i < a.length; i++) { + if (a[i] !== b[i]) return false; + } + return true; + } + try { + var ka = objectKeys(a), + kb = objectKeys(b); + } catch (e) {//happens when one is a string literal and the other isn't + return false; + } + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length != kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] != kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!deepEqual(a[key], b[key], opts)) return false; + } + return typeof a === typeof b; +} diff --git a/node_modules/deep-equal/lib/is_arguments.js b/node_modules/deep-equal/lib/is_arguments.js new file mode 100644 index 0000000..1ff150f --- /dev/null +++ b/node_modules/deep-equal/lib/is_arguments.js @@ -0,0 +1,20 @@ +var supportsArgumentsClass = (function(){ + return Object.prototype.toString.call(arguments) +})() == '[object Arguments]'; + +exports = module.exports = supportsArgumentsClass ? supported : unsupported; + +exports.supported = supported; +function supported(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +}; + +exports.unsupported = unsupported; +function unsupported(object){ + return object && + typeof object == 'object' && + typeof object.length == 'number' && + Object.prototype.hasOwnProperty.call(object, 'callee') && + !Object.prototype.propertyIsEnumerable.call(object, 'callee') || + false; +}; diff --git a/node_modules/deep-equal/lib/keys.js b/node_modules/deep-equal/lib/keys.js new file mode 100644 index 0000000..13af263 --- /dev/null +++ b/node_modules/deep-equal/lib/keys.js @@ -0,0 +1,9 @@ +exports = module.exports = typeof Object.keys === 'function' + ? Object.keys : shim; + +exports.shim = shim; +function shim (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} diff --git a/node_modules/deep-equal/package.json b/node_modules/deep-equal/package.json new file mode 100644 index 0000000..a2f4946 --- /dev/null +++ b/node_modules/deep-equal/package.json @@ -0,0 +1,87 @@ +{ + "_from": "deep-equal@~0.2.1", + "_id": "deep-equal@0.2.2", + "_inBundle": false, + "_integrity": "sha1-hLdFiW80xoTpjyzg5Cq69Du6AX0=", + "_location": "/deep-equal", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "deep-equal@~0.2.1", + "name": "deep-equal", + "escapedName": "deep-equal", + "rawSpec": "~0.2.1", + "saveSpec": null, + "fetchSpec": "~0.2.1" + }, + "_requiredBy": [ + "/utile" + ], + "_resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-0.2.2.tgz", + "_shasum": "84b745896f34c684e98f2ce0e42abaf43bba017d", + "_spec": "deep-equal@~0.2.1", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/utile", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bugs": { + "url": "https://github.com/substack/node-deep-equal/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "node's assert.deepEqual algorithm", + "devDependencies": { + "tape": "^3.5.0" + }, + "directories": { + "lib": ".", + "example": "example", + "test": "test" + }, + "homepage": "https://github.com/substack/node-deep-equal#readme", + "keywords": [ + "equality", + "equal", + "compare" + ], + "license": "MIT", + "main": "index.js", + "name": "deep-equal", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/substack/node-deep-equal.git" + }, + "scripts": { + "test": "tape test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": { + "ie": [ + 6, + 7, + 8, + 9 + ], + "ff": [ + 3.5, + 10, + 15 + ], + "chrome": [ + 10, + 22 + ], + "safari": [ + 5.1 + ], + "opera": [ + 12 + ] + } + }, + "version": "0.2.2" +} diff --git a/node_modules/deep-equal/readme.markdown b/node_modules/deep-equal/readme.markdown new file mode 100644 index 0000000..f489c2a --- /dev/null +++ b/node_modules/deep-equal/readme.markdown @@ -0,0 +1,61 @@ +# deep-equal + +Node's `assert.deepEqual() algorithm` as a standalone module. + +This module is around [5 times faster](https://gist.github.com/2790507) +than wrapping `assert.deepEqual()` in a `try/catch`. + +[![browser support](https://ci.testling.com/substack/node-deep-equal.png)](https://ci.testling.com/substack/node-deep-equal) + +[![build status](https://secure.travis-ci.org/substack/node-deep-equal.png)](https://travis-ci.org/substack/node-deep-equal) + +# example + +``` js +var equal = require('deep-equal'); +console.dir([ + equal( + { a : [ 2, 3 ], b : [ 4 ] }, + { a : [ 2, 3 ], b : [ 4 ] } + ), + equal( + { x : 5, y : [6] }, + { x : 5, y : 6 } + ) +]); +``` + +# methods + +``` js +var deepEqual = require('deep-equal') +``` + +## deepEqual(a, b, opts) + +Compare objects `a` and `b`, returning whether they are equal according to a +recursive equality algorithm. + +If `opts.strict` is `true`, use strict equality (`===`) to compare leaf nodes. +The default is to use coercive equality (`==`) because that's how +`assert.deepEqual()` works by default. + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install deep-equal +``` + +# test + +With [npm](http://npmjs.org) do: + +``` +npm test +``` + +# license + +MIT. Derived largely from node's assert module. diff --git a/node_modules/deep-equal/test/cmp.js b/node_modules/deep-equal/test/cmp.js new file mode 100644 index 0000000..d141256 --- /dev/null +++ b/node_modules/deep-equal/test/cmp.js @@ -0,0 +1,89 @@ +var test = require('tape'); +var equal = require('../'); +var isArguments = require('../lib/is_arguments.js'); +var objectKeys = require('../lib/keys.js'); + +test('equal', function (t) { + t.ok(equal( + { a : [ 2, 3 ], b : [ 4 ] }, + { a : [ 2, 3 ], b : [ 4 ] } + )); + t.end(); +}); + +test('not equal', function (t) { + t.notOk(equal( + { x : 5, y : [6] }, + { x : 5, y : 6 } + )); + t.end(); +}); + +test('nested nulls', function (t) { + t.ok(equal([ null, null, null ], [ null, null, null ])); + t.end(); +}); + +test('strict equal', function (t) { + t.notOk(equal( + [ { a: 3 }, { b: 4 } ], + [ { a: '3' }, { b: '4' } ], + { strict: true } + )); + t.end(); +}); + +test('non-objects', function (t) { + t.ok(equal(3, 3)); + t.ok(equal('beep', 'beep')); + t.ok(equal('3', 3)); + t.notOk(equal('3', 3, { strict: true })); + t.notOk(equal('3', [3])); + t.end(); +}); + +test('arguments class', function (t) { + t.ok(equal( + (function(){return arguments})(1,2,3), + (function(){return arguments})(1,2,3), + "compares arguments" + )); + t.notOk(equal( + (function(){return arguments})(1,2,3), + [1,2,3], + "differenciates array and arguments" + )); + t.end(); +}); + +test('test the arguments shim', function (t) { + t.ok(isArguments.supported((function(){return arguments})())); + t.notOk(isArguments.supported([1,2,3])); + + t.ok(isArguments.unsupported((function(){return arguments})())); + t.notOk(isArguments.unsupported([1,2,3])); + + t.end(); +}); + +test('test the keys shim', function (t) { + t.deepEqual(objectKeys.shim({ a: 1, b : 2 }), [ 'a', 'b' ]); + t.end(); +}); + +test('dates', function (t) { + var d0 = new Date(1387585278000); + var d1 = new Date('Fri Dec 20 2013 16:21:18 GMT-0800 (PST)'); + t.ok(equal(d0, d1)); + t.end(); +}); + +test('buffers', function (t) { + t.ok(equal(Buffer('xyz'), Buffer('xyz'))); + t.end(); +}); + +test('booleans and arrays', function (t) { + t.notOk(equal(true, [])); + t.end(); +}) diff --git a/node_modules/defaults/.npmignore b/node_modules/defaults/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/defaults/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/defaults/LICENSE b/node_modules/defaults/LICENSE new file mode 100644 index 0000000..d88b072 --- /dev/null +++ b/node_modules/defaults/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Elijah Insua + +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/defaults/README.md b/node_modules/defaults/README.md new file mode 100644 index 0000000..1a4a2ea --- /dev/null +++ b/node_modules/defaults/README.md @@ -0,0 +1,43 @@ +# defaults + +A simple one level options merge utility + +## install + +`npm install defaults` + +## use + +```javascript + +var defaults = require('defaults'); + +var handle = function(options, fn) { + options = defaults(options, { + timeout: 100 + }); + + setTimeout(function() { + fn(options); + }, options.timeout); +} + +handle({ timeout: 1000 }, function() { + // we're here 1000 ms later +}); + +handle({ timeout: 10000 }, function() { + // we're here 10s later +}); + +``` + +## summary + +this module exports a function that takes 2 arguments: `options` and `defaults`. When called, it overrides all of `undefined` properties in `options` with the clones of properties defined in `defaults` + +Sidecases: if called with a falsy `options` value, options will be initialized to a new object before being merged onto. + +## license + +[MIT](LICENSE) diff --git a/node_modules/defaults/index.js b/node_modules/defaults/index.js new file mode 100644 index 0000000..cb7d75c --- /dev/null +++ b/node_modules/defaults/index.js @@ -0,0 +1,13 @@ +var clone = require('clone'); + +module.exports = function(options, defaults) { + options = options || {}; + + Object.keys(defaults).forEach(function(key) { + if (typeof options[key] === 'undefined') { + options[key] = clone(defaults[key]); + } + }); + + return options; +};
\ No newline at end of file diff --git a/node_modules/defaults/package.json b/node_modules/defaults/package.json new file mode 100644 index 0000000..350abbc --- /dev/null +++ b/node_modules/defaults/package.json @@ -0,0 +1,57 @@ +{ + "_from": "defaults@^1.0.3", + "_id": "defaults@1.0.3", + "_inBundle": false, + "_integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", + "_location": "/defaults", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "defaults@^1.0.3", + "name": "defaults", + "escapedName": "defaults", + "rawSpec": "^1.0.3", + "saveSpec": null, + "fetchSpec": "^1.0.3" + }, + "_requiredBy": [ + "/wcwidth" + ], + "_resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", + "_shasum": "c656051e9817d9ff08ed881477f3fe4019f3ef7d", + "_spec": "defaults@^1.0.3", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/wcwidth", + "author": { + "name": "Elijah Insua", + "email": "tmpvar@gmail.com" + }, + "bugs": { + "url": "https://github.com/tmpvar/defaults/issues" + }, + "bundleDependencies": false, + "dependencies": { + "clone": "^1.0.2" + }, + "deprecated": false, + "description": "merge single level defaults over a config object", + "devDependencies": { + "tap": "^2.0.0" + }, + "homepage": "https://github.com/tmpvar/defaults#readme", + "keywords": [ + "config", + "defaults" + ], + "license": "MIT", + "main": "index.js", + "name": "defaults", + "repository": { + "type": "git", + "url": "git://github.com/tmpvar/defaults.git" + }, + "scripts": { + "test": "node test.js" + }, + "version": "1.0.3" +} diff --git a/node_modules/defaults/test.js b/node_modules/defaults/test.js new file mode 100644 index 0000000..60e0ffb --- /dev/null +++ b/node_modules/defaults/test.js @@ -0,0 +1,34 @@ +var defaults = require('./'), + test = require('tap').test; + +test("ensure options is an object", function(t) { + var options = defaults(false, { a : true }); + t.ok(options.a); + t.end() +}); + +test("ensure defaults override keys", function(t) { + var result = defaults({}, { a: false, b: true }); + t.ok(result.b, 'b merges over undefined'); + t.equal(result.a, false, 'a merges over undefined'); + t.end(); +}); + +test("ensure defined keys are not overwritten", function(t) { + var result = defaults({ b: false }, { a: false, b: true }); + t.equal(result.b, false, 'b not merged'); + t.equal(result.a, false, 'a merges over undefined'); + t.end(); +}); + +test("ensure defaults clone nested objects", function(t) { + var d = { a: [1,2,3], b: { hello : 'world' } }; + var result = defaults({}, d); + t.equal(result.a.length, 3, 'objects should be clones'); + t.ok(result.a !== d.a, 'objects should be clones'); + + t.equal(Object.keys(result.b).length, 1, 'objects should be clones'); + t.ok(result.b !== d.b, 'objects should be clones'); + t.end(); +}); + diff --git a/node_modules/eyes/LICENSE b/node_modules/eyes/LICENSE new file mode 100644 index 0000000..a1edd93 --- /dev/null +++ b/node_modules/eyes/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009 cloudhead + +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/eyes/Makefile b/node_modules/eyes/Makefile new file mode 100644 index 0000000..a121dea --- /dev/null +++ b/node_modules/eyes/Makefile @@ -0,0 +1,4 @@ +test: + @@node test/eyes-test.js + +.PHONY: test diff --git a/node_modules/eyes/README.md b/node_modules/eyes/README.md new file mode 100644 index 0000000..c4f6f76 --- /dev/null +++ b/node_modules/eyes/README.md @@ -0,0 +1,73 @@ +eyes +==== + +a customizable value inspector for Node.js + +synopsis +-------- + +I was tired of looking at cluttered output in the console -- something needed to be done, +`sys.inspect()` didn't display regexps correctly, and was too verbose, and I had an hour or two to spare. +So I decided to have some fun. _eyes_ were born. + +![eyes-ss](http://dl.dropbox.com/u/251849/eyes-js-ss.gif) + +_example of the output of a user-customized eyes.js inspector_ + +*eyes* also deals with circular objects in an intelligent way, and can pretty-print object literals. + +usage +----- + + var inspect = require('eyes').inspector({styles: {all: 'magenta'}}); + + inspect(something); // inspect with the settings passed to `inspector` + +or + + var eyes = require('eyes'); + + eyes.inspect(something); // inspect with the default settings + +you can pass a _label_ to `inspect()`, to keep track of your inspections: + + eyes.inspect(something, "a random value"); + +If you want to return the output of eyes without printing it, you can set it up this way: + + var inspect = require('eyes').inspector({ stream: null }); + + sys.puts(inspect({ something: 42 })); + +customization +------------- + +These are the default styles and settings used by _eyes_. + + styles: { // Styles applied to stdout + all: 'cyan', // Overall style applied to everything + label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` + other: 'inverted', // Objects which don't have a literal representation, such as functions + key: 'bold', // The keys in object literals, like 'a' in `{a: 1}` + special: 'grey', // null, undefined... + string: 'green', + number: 'magenta', + bool: 'blue', // true false + regexp: 'green', // /\d+/ + }, + + pretty: true, // Indent object literals + hideFunctions: false, // Don't output functions at all + stream: process.stdout, // Stream to write to, or null + maxLength: 2048 // Truncate output if longer + +You can overwrite them with your own, by passing a similar object to `inspector()` or `inspect()`. + + var inspect = require('eyes').inspector({ + styles: { + all: 'magenta', + special: 'bold' + }, + maxLength: 512 + }); + diff --git a/node_modules/eyes/lib/eyes.js b/node_modules/eyes/lib/eyes.js new file mode 100644 index 0000000..10d964b --- /dev/null +++ b/node_modules/eyes/lib/eyes.js @@ -0,0 +1,236 @@ +// +// Eyes.js - a customizable value inspector for Node.js +// +// usage: +// +// var inspect = require('eyes').inspector({styles: {all: 'magenta'}}); +// inspect(something); // inspect with the settings passed to `inspector` +// +// or +// +// var eyes = require('eyes'); +// eyes.inspect(something); // inspect with the default settings +// +var eyes = exports, + stack = []; + +eyes.defaults = { + styles: { // Styles applied to stdout + all: 'cyan', // Overall style applied to everything + label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` + other: 'inverted', // Objects which don't have a literal representation, such as functions + key: 'bold', // The keys in object literals, like 'a' in `{a: 1}` + special: 'grey', // null, undefined... + string: 'green', + number: 'magenta', + bool: 'blue', // true false + regexp: 'green', // /\d+/ + }, + pretty: true, // Indent object literals + hideFunctions: false, + showHidden: false, + stream: process.stdout, + maxLength: 2048 // Truncate output if longer +}; + +// Return a curried inspect() function, with the `options` argument filled in. +eyes.inspector = function (options) { + var that = this; + return function (obj, label, opts) { + return that.inspect.call(that, obj, label, + merge(options || {}, opts || {})); + }; +}; + +// If we have a `stream` defined, use it to print a styled string, +// if not, we just return the stringified object. +eyes.inspect = function (obj, label, options) { + options = merge(this.defaults, options || {}); + + if (options.stream) { + return this.print(stringify(obj, options), label, options); + } else { + return stringify(obj, options) + (options.styles ? '\033[39m' : ''); + } +}; + +// Output using the 'stream', and an optional label +// Loop through `str`, and truncate it after `options.maxLength` has been reached. +// Because escape sequences are, at this point embeded within +// the output string, we can't measure the length of the string +// in a useful way, without separating what is an escape sequence, +// versus a printable character (`c`). So we resort to counting the +// length manually. +eyes.print = function (str, label, options) { + for (var c = 0, i = 0; i < str.length; i++) { + if (str.charAt(i) === '\033') { i += 4 } // `4` because '\033[25m'.length + 1 == 5 + else if (c === options.maxLength) { + str = str.slice(0, i - 1) + '…'; + break; + } else { c++ } + } + return options.stream.write.call(options.stream, (label ? + this.stylize(label, options.styles.label, options.styles) + ': ' : '') + + this.stylize(str, options.styles.all, options.styles) + '\033[0m' + "\n"); +}; + +// Apply a style to a string, eventually, +// I'd like this to support passing multiple +// styles. +eyes.stylize = function (str, style, styles) { + var codes = { + 'bold' : [1, 22], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'cyan' : [36, 39], + 'magenta' : [35, 39], + 'blue' : [34, 39], + 'yellow' : [33, 39], + 'green' : [32, 39], + 'red' : [31, 39], + 'grey' : [90, 39] + }, endCode; + + if (style && codes[style]) { + endCode = (codes[style][1] === 39 && styles.all) ? codes[styles.all][0] + : codes[style][1]; + return '\033[' + codes[style][0] + 'm' + str + + '\033[' + endCode + 'm'; + } else { return str } +}; + +// Convert any object to a string, ready for output. +// When an 'array' or an 'object' are encountered, they are +// passed to specialized functions, which can then recursively call +// stringify(). +function stringify(obj, options) { + var that = this, stylize = function (str, style) { + return eyes.stylize(str, options.styles[style], options.styles) + }, index, result; + + if ((index = stack.indexOf(obj)) !== -1) { + return stylize(new(Array)(stack.length - index + 1).join('.'), 'special'); + } + stack.push(obj); + + result = (function (obj) { + switch (typeOf(obj)) { + case "string" : obj = stringifyString(obj.indexOf("'") === -1 ? "'" + obj + "'" + : '"' + obj + '"'); + return stylize(obj, 'string'); + case "regexp" : return stylize('/' + obj.source + '/', 'regexp'); + case "number" : return stylize(obj + '', 'number'); + case "function" : return options.stream ? stylize("Function", 'other') : '[Function]'; + case "null" : return stylize("null", 'special'); + case "undefined": return stylize("undefined", 'special'); + case "boolean" : return stylize(obj + '', 'bool'); + case "date" : return stylize(obj.toUTCString()); + case "array" : return stringifyArray(obj, options, stack.length); + case "object" : return stringifyObject(obj, options, stack.length); + } + })(obj); + + stack.pop(); + return result; +}; + +// Escape invisible characters in a string +function stringifyString (str, options) { + return str.replace(/\\/g, '\\\\') + .replace(/\n/g, '\\n') + .replace(/[\u0001-\u001F]/g, function (match) { + return '\\0' + match[0].charCodeAt(0).toString(8); + }); +} + +// Convert an array to a string, such as [1, 2, 3]. +// This function calls stringify() for each of the elements +// in the array. +function stringifyArray(ary, options, level) { + var out = []; + var pretty = options.pretty && (ary.length > 4 || ary.some(function (o) { + return (o !== null && typeof(o) === 'object' && Object.keys(o).length > 0) || + (Array.isArray(o) && o.length > 0); + })); + var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' '; + + for (var i = 0; i < ary.length; i++) { + out.push(stringify(ary[i], options)); + } + + if (out.length === 0) { + return '[]'; + } else { + return '[' + ws + + out.join(',' + (pretty ? ws : ' ')) + + (pretty ? ws.slice(0, -4) : ws) + + ']'; + } +}; + +// Convert an object to a string, such as {a: 1}. +// This function calls stringify() for each of its values, +// and does not output functions or prototype values. +function stringifyObject(obj, options, level) { + var out = []; + var pretty = options.pretty && (Object.keys(obj).length > 2 || + Object.keys(obj).some(function (k) { return typeof(obj[k]) === 'object' })); + var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' '; + + var keys = options.showHidden ? Object.keys(obj) : Object.getOwnPropertyNames(obj); + keys.forEach(function (k) { + if (Object.prototype.hasOwnProperty.call(obj, k) + && !(obj[k] instanceof Function && options.hideFunctions)) { + out.push(eyes.stylize(k, options.styles.key, options.styles) + ': ' + + stringify(obj[k], options)); + } + }); + + if (out.length === 0) { + return '{}'; + } else { + return "{" + ws + + out.join(',' + (pretty ? ws : ' ')) + + (pretty ? ws.slice(0, -4) : ws) + + "}"; + } +}; + +// A better `typeof` +function typeOf(value) { + var s = typeof(value), + types = [Object, Array, String, RegExp, Number, Function, Boolean, Date]; + + if (s === 'object' || s === 'function') { + if (value) { + types.forEach(function (t) { + if (value instanceof t) { s = t.name.toLowerCase() } + }); + } else { s = 'null' } + } + return s; +} + +function merge(/* variable args */) { + var objs = Array.prototype.slice.call(arguments); + var target = {}; + + objs.forEach(function (o) { + Object.keys(o).forEach(function (k) { + if (k === 'styles') { + if (! o.styles) { + target.styles = false; + } else { + target.styles = {} + for (var s in o.styles) { + target.styles[s] = o.styles[s]; + } + } + } else { + target[k] = o[k]; + } + }); + }); + return target; +} + diff --git a/node_modules/eyes/package.json b/node_modules/eyes/package.json new file mode 100644 index 0000000..3fcf7e5 --- /dev/null +++ b/node_modules/eyes/package.json @@ -0,0 +1,61 @@ +{ + "_from": "eyes@0.1.x", + "_id": "eyes@0.1.8", + "_inBundle": false, + "_integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=", + "_location": "/eyes", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "eyes@0.1.x", + "name": "eyes", + "escapedName": "eyes", + "rawSpec": "0.1.x", + "saveSpec": null, + "fetchSpec": "0.1.x" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "_shasum": "62cf120234c683785d902348a800ef3e0cc20bc0", + "_spec": "eyes@0.1.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/winston", + "author": { + "name": "Alexis Sellier", + "email": "self@cloudhead.net" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Charlie Robbins", + "email": "charlie@nodejitsu.com" + } + ], + "deprecated": false, + "description": "a customizable value inspector", + "directories": { + "lib": "./lib", + "test": "./test" + }, + "engines": { + "node": "> 0.1.90" + }, + "keywords": [ + "inspector", + "debug", + "inspect", + "print" + ], + "licenses": [ + "MIT" + ], + "main": "./lib/eyes", + "name": "eyes", + "scripts": { + "test": "node test/*-test.js" + }, + "url": "http://github.com/cloudhead/eyes.js", + "version": "0.1.8" +} diff --git a/node_modules/eyes/test/eyes-test.js b/node_modules/eyes/test/eyes-test.js new file mode 100644 index 0000000..1f9606a --- /dev/null +++ b/node_modules/eyes/test/eyes-test.js @@ -0,0 +1,56 @@ +var util = require('util'); +var eyes = require('../lib/eyes'); + +eyes.inspect({ + number: 42, + string: "John Galt", + regexp: /[a-z]+/, + array: [99, 168, 'x', {}], + func: function () {}, + bool: false, + nil: null, + undef: undefined, + object: {attr: []} +}, "native types"); + +eyes.inspect({ + number: new(Number)(42), + string: new(String)("John Galt"), + regexp: new(RegExp)(/[a-z]+/), + array: new(Array)(99, 168, 'x', {}), + bool: new(Boolean)(false), + object: new(Object)({attr: []}), + date: new(Date) +}, "wrapped types"); + +var obj = {}; +obj.that = { self: obj }; +obj.self = obj; + +eyes.inspect(obj, "circular object"); +eyes.inspect({hello: 'moto'}, "small object"); +eyes.inspect({hello: new(Array)(6) }, "big object"); +eyes.inspect(["hello 'world'", 'hello "world"'], "quotes"); +eyes.inspect({ + recommendations: [{ + id: 'a7a6576c2c822c8e2bd81a27e41437d8', + key: [ 'spree', 3.764316258020699 ], + value: { + _id: 'a7a6576c2c822c8e2bd81a27e41437d8', + _rev: '1-2e2d2f7fd858c4a5984bcf809d22ed98', + type: 'domain', + domain: 'spree', + weight: 3.764316258020699, + product_id: 30 + } + }] +}, 'complex'); + +eyes.inspect([null], "null in array"); + +var inspect = eyes.inspector({ stream: null }); + +util.puts(inspect('something', "something")); +util.puts(inspect("something else")); + +util.puts(inspect(["no color"], null, { styles: false })); diff --git a/node_modules/fs.realpath/LICENSE b/node_modules/fs.realpath/LICENSE new file mode 100644 index 0000000..5bd884c --- /dev/null +++ b/node_modules/fs.realpath/LICENSE @@ -0,0 +1,43 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +---- + +This library bundles a version of the `fs.realpath` and `fs.realpathSync` +methods from Node.js v0.10 under the terms of the Node.js MIT license. + +Node's license follows, also included at the header of `old.js` which contains +the licensed code: + + Copyright Joyent, Inc. and other Node contributors. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. diff --git a/node_modules/fs.realpath/README.md b/node_modules/fs.realpath/README.md new file mode 100644 index 0000000..a42ceac --- /dev/null +++ b/node_modules/fs.realpath/README.md @@ -0,0 +1,33 @@ +# fs.realpath + +A backwards-compatible fs.realpath for Node v6 and above + +In Node v6, the JavaScript implementation of fs.realpath was replaced +with a faster (but less resilient) native implementation. That raises +new and platform-specific errors and cannot handle long or excessively +symlink-looping paths. + +This module handles those cases by detecting the new errors and +falling back to the JavaScript implementation. On versions of Node +prior to v6, it has no effect. + +## USAGE + +```js +var rp = require('fs.realpath') + +// async version +rp.realpath(someLongAndLoopingPath, function (er, real) { + // the ELOOP was handled, but it was a bit slower +}) + +// sync version +var real = rp.realpathSync(someLongAndLoopingPath) + +// monkeypatch at your own risk! +// This replaces the fs.realpath/fs.realpathSync builtins +rp.monkeypatch() + +// un-do the monkeypatching +rp.unmonkeypatch() +``` diff --git a/node_modules/fs.realpath/index.js b/node_modules/fs.realpath/index.js new file mode 100644 index 0000000..b09c7c7 --- /dev/null +++ b/node_modules/fs.realpath/index.js @@ -0,0 +1,66 @@ +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch + +var fs = require('fs') +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync + +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = require('./old.js') + +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} + +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } + + if (typeof cache === 'function') { + cb = cache + cache = null + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) + } else { + cb(er, result) + } + }) +} + +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } + + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } + } +} + +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync +} + +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync +} diff --git a/node_modules/fs.realpath/old.js b/node_modules/fs.realpath/old.js new file mode 100644 index 0000000..b40305e --- /dev/null +++ b/node_modules/fs.realpath/old.js @@ -0,0 +1,303 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var pathModule = require('path'); +var isWindows = process.platform === 'win32'; +var fs = require('fs'); + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } + + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } +} + +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} + +var normalize = pathModule.normalize; + +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} + +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} + +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } + + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } + + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } + + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } + + if (cache) cache[original] = p; + + return p; +}; + + +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } + + return fs.lstat(base, gotStat); + } + + function gotStat(err, stat) { + if (err) return cb(err); + + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); + + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + + function gotTarget(err, target, base) { + if (err) return cb(err); + + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; diff --git a/node_modules/fs.realpath/package.json b/node_modules/fs.realpath/package.json new file mode 100644 index 0000000..fbb73d8 --- /dev/null +++ b/node_modules/fs.realpath/package.json @@ -0,0 +1,59 @@ +{ + "_from": "fs.realpath@^1.0.0", + "_id": "fs.realpath@1.0.0", + "_inBundle": false, + "_integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "_location": "/fs.realpath", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "fs.realpath@^1.0.0", + "name": "fs.realpath", + "escapedName": "fs.realpath", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "_shasum": "1504ad2523158caa40db4a2787cb01411994ea4f", + "_spec": "fs.realpath@^1.0.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/glob", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/fs.realpath/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Use node's fs.realpath, but fall back to the JS implementation if the native one fails", + "devDependencies": {}, + "files": [ + "old.js", + "index.js" + ], + "homepage": "https://github.com/isaacs/fs.realpath#readme", + "keywords": [ + "realpath", + "fs", + "polyfill" + ], + "license": "ISC", + "main": "index.js", + "name": "fs.realpath", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/fs.realpath.git" + }, + "scripts": { + "test": "tap test/*.js --cov" + }, + "version": "1.0.0" +} diff --git a/node_modules/glob/LICENSE b/node_modules/glob/LICENSE new file mode 100644 index 0000000..42ca266 --- /dev/null +++ b/node_modules/glob/LICENSE @@ -0,0 +1,21 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +## Glob Logo + +Glob's logo created by Tanya Brassie <http://tanyabrassie.com/>, licensed +under a Creative Commons Attribution-ShareAlike 4.0 International License +https://creativecommons.org/licenses/by-sa/4.0/ diff --git a/node_modules/glob/README.md b/node_modules/glob/README.md new file mode 100644 index 0000000..0916a48 --- /dev/null +++ b/node_modules/glob/README.md @@ -0,0 +1,375 @@ +# Glob + +Match files using the patterns the shell uses, like stars and stuff. + +[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) + +This is a glob implementation in JavaScript. It uses the `minimatch` +library to do its matching. + +![](logo/glob.png) + +## Usage + +Install with npm + +``` +npm i glob +``` + +```javascript +var glob = require("glob") + +// options is optional +glob("**/*.js", options, function (er, files) { + // files is an array of filenames. + // If the `nonull` option is set, and nothing + // was found, then files is ["**/*.js"] + // er is an error object or null. +}) +``` + +## Glob Primer + +"Globs" are the patterns you type when you do stuff like `ls *.js` on +the command line, or put `build/*` in a `.gitignore` file. + +Before parsing the path part patterns, braced sections are expanded +into a set. Braced sections start with `{` and end with `}`, with any +number of comma-delimited sections within. Braced sections may contain +slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. + +The following characters have special magic meaning when used in a +path portion: + +* `*` Matches 0 or more characters in a single path portion +* `?` Matches 1 character +* `[...]` Matches a range of characters, similar to a RegExp range. + If the first character of the range is `!` or `^` then it matches + any character not in the range. +* `!(pattern|pattern|pattern)` Matches anything that does not match + any of the patterns provided. +* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the + patterns provided. +* `+(pattern|pattern|pattern)` Matches one or more occurrences of the + patterns provided. +* `*(a|b|c)` Matches zero or more occurrences of the patterns provided +* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns + provided +* `**` If a "globstar" is alone in a path portion, then it matches + zero or more directories and subdirectories searching for matches. + It does not crawl symlinked directories. + +### Dots + +If a file or directory path portion has a `.` as the first character, +then it will not match any glob pattern unless that pattern's +corresponding path part also has a `.` as its first character. + +For example, the pattern `a/.*/c` would match the file at `a/.b/c`. +However the pattern `a/*/c` would not, because `*` does not start with +a dot character. + +You can make glob treat dots as normal characters by setting +`dot:true` in the options. + +### Basename Matching + +If you set `matchBase:true` in the options, and the pattern has no +slashes in it, then it will seek for any file anywhere in the tree +with a matching basename. For example, `*.js` would match +`test/simple/basic.js`. + +### Empty Sets + +If no matching files are found, then an empty array is returned. This +differs from the shell, where the pattern itself is returned. For +example: + + $ echo a*s*d*f + a*s*d*f + +To get the bash-style behavior, set the `nonull:true` in the options. + +### See Also: + +* `man sh` +* `man bash` (Search for "Pattern Matching") +* `man 3 fnmatch` +* `man 5 gitignore` +* [minimatch documentation](https://github.com/isaacs/minimatch) + +## glob.hasMagic(pattern, [options]) + +Returns `true` if there are any special characters in the pattern, and +`false` otherwise. + +Note that the options affect the results. If `noext:true` is set in +the options object, then `+(a|b)` will not be considered a magic +pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` +then that is considered magical, unless `nobrace:true` is set in the +options. + +## glob(pattern, [options], cb) + +* `pattern` `{String}` Pattern to be matched +* `options` `{Object}` +* `cb` `{Function}` + * `err` `{Error | null}` + * `matches` `{Array<String>}` filenames found matching the pattern + +Perform an asynchronous glob search. + +## glob.sync(pattern, [options]) + +* `pattern` `{String}` Pattern to be matched +* `options` `{Object}` +* return: `{Array<String>}` filenames found matching the pattern + +Perform a synchronous glob search. + +## Class: glob.Glob + +Create a Glob object by instantiating the `glob.Glob` class. + +```javascript +var Glob = require("glob").Glob +var mg = new Glob(pattern, options, cb) +``` + +It's an EventEmitter, and starts walking the filesystem to find matches +immediately. + +### new glob.Glob(pattern, [options], [cb]) + +* `pattern` `{String}` pattern to search for +* `options` `{Object}` +* `cb` `{Function}` Called when an error occurs, or matches are found + * `err` `{Error | null}` + * `matches` `{Array<String>}` filenames found matching the pattern + +Note that if the `sync` flag is set in the options, then matches will +be immediately available on the `g.found` member. + +### Properties + +* `minimatch` The minimatch object that the glob uses. +* `options` The options object passed in. +* `aborted` Boolean which is set to true when calling `abort()`. There + is no way at this time to continue a glob search after aborting, but + you can re-use the statCache to avoid having to duplicate syscalls. +* `cache` Convenience object. Each field has the following possible + values: + * `false` - Path does not exist + * `true` - Path exists + * `'FILE'` - Path exists, and is not a directory + * `'DIR'` - Path exists, and is a directory + * `[file, entries, ...]` - Path exists, is a directory, and the + array value is the results of `fs.readdir` +* `statCache` Cache of `fs.stat` results, to prevent statting the same + path multiple times. +* `symlinks` A record of which paths are symbolic links, which is + relevant in resolving `**` patterns. +* `realpathCache` An optional object which is passed to `fs.realpath` + to minimize unnecessary syscalls. It is stored on the instantiated + Glob object, and may be re-used. + +### Events + +* `end` When the matching is finished, this is emitted with all the + matches found. If the `nonull` option is set, and no match was found, + then the `matches` list contains the original pattern. The matches + are sorted, unless the `nosort` flag is set. +* `match` Every time a match is found, this is emitted with the specific + thing that matched. It is not deduplicated or resolved to a realpath. +* `error` Emitted when an unexpected error is encountered, or whenever + any fs error occurs if `options.strict` is set. +* `abort` When `abort()` is called, this event is raised. + +### Methods + +* `pause` Temporarily stop the search +* `resume` Resume the search +* `abort` Stop the search forever + +### Options + +All the options that can be passed to Minimatch can also be passed to +Glob to change pattern matching behavior. Also, some have been added, +or have glob-specific ramifications. + +All options are false by default, unless otherwise noted. + +All options are added to the Glob object, as well. + +If you are running many `glob` operations, you can pass a Glob object +as the `options` argument to a subsequent operation to shortcut some +`stat` and `readdir` calls. At the very least, you may pass in shared +`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that +parallel glob operations will be sped up by sharing information about +the filesystem. + +* `cwd` The current working directory in which to search. Defaults + to `process.cwd()`. +* `root` The place where patterns starting with `/` will be mounted + onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix + systems, and `C:\` or some such on Windows.) +* `dot` Include `.dot` files in normal matches and `globstar` matches. + Note that an explicit dot in a portion of the pattern will always + match dot files. +* `nomount` By default, a pattern starting with a forward-slash will be + "mounted" onto the root setting, so that a valid filesystem path is + returned. Set this flag to disable that behavior. +* `mark` Add a `/` character to directory matches. Note that this + requires additional stat calls. +* `nosort` Don't sort the results. +* `stat` Set to true to stat *all* results. This reduces performance + somewhat, and is completely unnecessary, unless `readdir` is presumed + to be an untrustworthy indicator of file existence. +* `silent` When an unusual error is encountered when attempting to + read a directory, a warning will be printed to stderr. Set the + `silent` option to true to suppress these warnings. +* `strict` When an unusual error is encountered when attempting to + read a directory, the process will just continue on in search of + other matches. Set the `strict` option to raise an error in these + cases. +* `cache` See `cache` property above. Pass in a previously generated + cache object to save some fs calls. +* `statCache` A cache of results of filesystem information, to prevent + unnecessary stat calls. While it should not normally be necessary + to set this, you may pass the statCache from one glob() call to the + options object of another, if you know that the filesystem will not + change between calls. (See "Race Conditions" below.) +* `symlinks` A cache of known symbolic links. You may pass in a + previously generated `symlinks` object to save `lstat` calls when + resolving `**` matches. +* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. +* `nounique` In some cases, brace-expanded patterns can result in the + same file showing up multiple times in the result set. By default, + this implementation prevents duplicates in the result set. Set this + flag to disable that behavior. +* `nonull` Set to never return an empty set, instead returning a set + containing the pattern itself. This is the default in glob(3). +* `debug` Set to enable debug logging in minimatch and glob. +* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. +* `noglobstar` Do not match `**` against multiple filenames. (Ie, + treat it as a normal `*` instead.) +* `noext` Do not match `+(a|b)` "extglob" patterns. +* `nocase` Perform a case-insensitive match. Note: on + case-insensitive filesystems, non-magic patterns will match by + default, since `stat` and `readdir` will not raise errors. +* `matchBase` Perform a basename-only match if the pattern does not + contain any slash characters. That is, `*.js` would be treated as + equivalent to `**/*.js`, matching all js files in all directories. +* `nodir` Do not match directories, only files. (Note: to match + *only* directories, simply put a `/` at the end of the pattern.) +* `ignore` Add a pattern or an array of glob patterns to exclude matches. + Note: `ignore` patterns are *always* in `dot:true` mode, regardless + of any other settings. +* `follow` Follow symlinked directories when expanding `**` patterns. + Note that this can result in a lot of duplicate references in the + presence of cyclic links. +* `realpath` Set to true to call `fs.realpath` on all of the results. + In the case of a symlink that cannot be resolved, the full absolute + path to the matched entry is returned (though it will usually be a + broken symlink) +* `absolute` Set to true to always receive absolute paths for matched + files. Unlike `realpath`, this also affects the values returned in + the `match` event. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between node-glob and other +implementations, and are intentional. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.3, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +Note that symlinked directories are not crawled as part of a `**`, +though their contents may match against subsequent portions of the +pattern. This prevents infinite loops and duplicates and the like. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then glob returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +### Comments and Negation + +Previously, this module let you mark a pattern as a "comment" if it +started with a `#` character, or a "negated" pattern if it started +with a `!` character. + +These options were deprecated in version 5, and removed in version 6. + +To specify things that should not match, use the `ignore` option. + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes will always +be interpreted as escape characters, not path separators. + +Results from absolute patterns such as `/foo/*` are mounted onto the +root setting using `path.join`. On windows, this will by default result +in `/foo/*` matching `C:\foo\bar.txt`. + +## Race Conditions + +Glob searching, by its very nature, is susceptible to race conditions, +since it relies on directory walking and such. + +As a result, it is possible that a file that exists when glob looks for +it may have been deleted or modified by the time it returns the result. + +As part of its internal implementation, this program caches all stat +and readdir calls that it makes, in order to cut down on system +overhead. However, this also makes it even more susceptible to races, +especially if the cache or statCache objects are reused between glob +calls. + +Users are thus advised not to use a glob result as a guarantee of +filesystem state in the face of rapid changes. For the vast majority +of operations, this is never a problem. + +## Glob Logo +Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). + +The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). + +## Contributing + +Any change to behavior (including bugfixes) must come with a test. + +Patches that fail tests or reduce performance will be rejected. + +``` +# to run tests +npm test + +# to re-generate test fixtures +npm run test-regen + +# to benchmark against bash/zsh +npm run bench + +# to profile javascript +npm run prof +``` + +![](oh-my-glob.gif) diff --git a/node_modules/glob/changelog.md b/node_modules/glob/changelog.md new file mode 100644 index 0000000..4163677 --- /dev/null +++ b/node_modules/glob/changelog.md @@ -0,0 +1,67 @@ +## 7.0 + +- Raise error if `options.cwd` is specified, and not a directory + +## 6.0 + +- Remove comment and negation pattern support +- Ignore patterns are always in `dot:true` mode + +## 5.0 + +- Deprecate comment and negation patterns +- Fix regression in `mark` and `nodir` options from making all cache + keys absolute path. +- Abort if `fs.readdir` returns an error that's unexpected +- Don't emit `match` events for ignored items +- Treat ENOTSUP like ENOTDIR in readdir + +## 4.5 + +- Add `options.follow` to always follow directory symlinks in globstar +- Add `options.realpath` to call `fs.realpath` on all results +- Always cache based on absolute path + +## 4.4 + +- Add `options.ignore` +- Fix handling of broken symlinks + +## 4.3 + +- Bump minimatch to 2.x +- Pass all tests on Windows + +## 4.2 + +- Add `glob.hasMagic` function +- Add `options.nodir` flag + +## 4.1 + +- Refactor sync and async implementations for performance +- Throw if callback provided to sync glob function +- Treat symbolic links in globstar results the same as Bash 4.3 + +## 4.0 + +- Use `^` for dependency versions (bumped major because this breaks + older npm versions) +- Ensure callbacks are only ever called once +- switch to ISC license + +## 3.x + +- Rewrite in JavaScript +- Add support for setting root, cwd, and windows support +- Cache many fs calls +- Add globstar support +- emit match events + +## 2.x + +- Use `glob.h` and `fnmatch.h` from NetBSD + +## 1.x + +- `glob.h` static binding. diff --git a/node_modules/glob/common.js b/node_modules/glob/common.js new file mode 100644 index 0000000..66651bb --- /dev/null +++ b/node_modules/glob/common.js @@ -0,0 +1,240 @@ +exports.alphasort = alphasort +exports.alphasorti = alphasorti +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var path = require("path") +var minimatch = require("minimatch") +var isAbsolute = require("path-is-absolute") +var Minimatch = minimatch.Minimatch + +function alphasorti (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()) +} + +function alphasort (a, b) { + return a.localeCompare(b) +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || [] + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) + } + + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {} + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } + + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute + + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) + + setupIgnores(self, options) + + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd + } + + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + self.nomount = !!options.nomount + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true + + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} + +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } + + if (!nou) + all = Object.keys(all) + + if (!self.nosort) + all = all.sort(self.nocase ? alphasorti : alphasort) + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) + + self.found = all +} + +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' + + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) + + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} diff --git a/node_modules/glob/glob.js b/node_modules/glob/glob.js new file mode 100644 index 0000000..58dec0f --- /dev/null +++ b/node_modules/glob/glob.js @@ -0,0 +1,790 @@ +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +module.exports = glob + +var fs = require('fs') +var rp = require('fs.realpath') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var inherits = require('inherits') +var EE = require('events').EventEmitter +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path-is-absolute') +var globSync = require('./sync.js') +var common = require('./common.js') +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = require('inflight') +var util = require('util') +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +var once = require('once') + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync + +// old api surface +glob.glob = glob + +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] + } + return origin +} + +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true + + var g = new Glob(pattern, options) + var set = g.minimatch.set + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +} + +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options) + this._didRealPath = false + + // process each pattern in the minimatch set + var n = this.minimatch.set.length + + // The matches are stored as {<filename>: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) + + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } + + var self = this + this._processing = 0 + + this._emitQueue = [] + this._processQueue = [] + this.paused = false + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + sync = false + + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } + } + } +} + +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common.finish(this) + this.emit('end', this.found) +} + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true + + var n = this.matches.length + if (n === 0) + return this._finish() + + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) + + function next () { + if (--n === 0) + self._finish() + } +} + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() + + var found = Object.keys(matchset) + var self = this + var n = found.length + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} + +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} + +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } + } + } +} + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return + + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) + } + cb() +} + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]) + return + } + + var abs = isAbsolute(e) ? e : this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) + e = abs + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) + + this.emit('match', e) +} + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) + + if (lstatcb) + fs.lstat(abs, lstatcb) + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } +} + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + + var self = this + fs.readdir(abs, readdirCb(this, abs, cb)) +} + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + return cb(null, entries) +} + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break + } + + return cb() +} + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) + + var isSym = this.symlinks[abs] + var len = entries.length + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } + + cb() +} + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + fs.lstat(abs, statcb) + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } +} + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() + } + + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) +} diff --git a/node_modules/glob/package.json b/node_modules/glob/package.json new file mode 100644 index 0000000..358e8ed --- /dev/null +++ b/node_modules/glob/package.json @@ -0,0 +1,79 @@ +{ + "_from": "glob@^7.1.3", + "_id": "glob@7.1.6", + "_inBundle": false, + "_integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "_location": "/glob", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "glob@^7.1.3", + "name": "glob", + "escapedName": "glob", + "rawSpec": "^7.1.3", + "saveSpec": null, + "fetchSpec": "^7.1.3" + }, + "_requiredBy": [ + "/rimraf" + ], + "_resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "_shasum": "141f33b81a7c2492e125594307480c46679278a6", + "_spec": "glob@^7.1.3", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/rimraf", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/node-glob/issues" + }, + "bundleDependencies": false, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "deprecated": false, + "description": "a little globber", + "devDependencies": { + "mkdirp": "0", + "rimraf": "^2.2.8", + "tap": "^12.0.1", + "tick": "0.0.6" + }, + "engines": { + "node": "*" + }, + "files": [ + "glob.js", + "sync.js", + "common.js" + ], + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "homepage": "https://github.com/isaacs/node-glob#readme", + "license": "ISC", + "main": "glob.js", + "name": "glob", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-glob.git" + }, + "scripts": { + "bench": "bash benchmark.sh", + "benchclean": "node benchclean.js", + "prepublish": "npm run benchclean", + "prof": "bash prof.sh && cat profile.txt", + "profclean": "rm -f v8.log profile.txt", + "test": "tap test/*.js --cov", + "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js" + }, + "version": "7.1.6" +} diff --git a/node_modules/glob/sync.js b/node_modules/glob/sync.js new file mode 100644 index 0000000..c952134 --- /dev/null +++ b/node_modules/glob/sync.js @@ -0,0 +1,486 @@ +module.exports = globSync +globSync.GlobSync = GlobSync + +var fs = require('fs') +var rp = require('fs.realpath') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var Glob = require('./glob.js').Glob +var util = require('util') +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path-is-absolute') +var common = require('./common.js') +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options) + + if (this.noprocess) + return this + + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} + +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) + } + common.finish(this) +} + + +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} + + +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return + + var abs = this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) { + e = abs + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) + + return entries +} + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) + + var len = entries.length + var isSym = this.symlinks[abs] + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) +} + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } + + this.statCache[abs] = stat + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return false + + return c +} + +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} diff --git a/node_modules/has-flag/index.d.ts b/node_modules/has-flag/index.d.ts new file mode 100644 index 0000000..a0a48c8 --- /dev/null +++ b/node_modules/has-flag/index.d.ts @@ -0,0 +1,39 @@ +/** +Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag. + +@param flag - CLI flag to look for. The `--` prefix is optional. +@param argv - CLI arguments. Default: `process.argv`. +@returns Whether the flag exists. + +@example +``` +// $ ts-node foo.ts -f --unicorn --foo=bar -- --rainbow + +// foo.ts +import hasFlag = require('has-flag'); + +hasFlag('unicorn'); +//=> true + +hasFlag('--unicorn'); +//=> true + +hasFlag('f'); +//=> true + +hasFlag('-f'); +//=> true + +hasFlag('foo=bar'); +//=> true + +hasFlag('foo'); +//=> false + +hasFlag('rainbow'); +//=> false +``` +*/ +declare function hasFlag(flag: string, argv?: string[]): boolean; + +export = hasFlag; diff --git a/node_modules/has-flag/index.js b/node_modules/has-flag/index.js new file mode 100644 index 0000000..b6f80b1 --- /dev/null +++ b/node_modules/has-flag/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; diff --git a/node_modules/has-flag/license b/node_modules/has-flag/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/has-flag/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/has-flag/package.json b/node_modules/has-flag/package.json new file mode 100644 index 0000000..383def3 --- /dev/null +++ b/node_modules/has-flag/package.json @@ -0,0 +1,78 @@ +{ + "_from": "has-flag@^4.0.0", + "_id": "has-flag@4.0.0", + "_inBundle": false, + "_integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "_location": "/has-flag", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "has-flag@^4.0.0", + "name": "has-flag", + "escapedName": "has-flag", + "rawSpec": "^4.0.0", + "saveSpec": null, + "fetchSpec": "^4.0.0" + }, + "_requiredBy": [ + "/supports-color" + ], + "_resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "_shasum": "944771fd9c81c81265c4d6941860da06bb59479b", + "_spec": "has-flag@^4.0.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/supports-color", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/has-flag/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Check if argv has a specific flag", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/has-flag#readme", + "keywords": [ + "has", + "check", + "detect", + "contains", + "find", + "flag", + "cli", + "command-line", + "argv", + "process", + "arg", + "args", + "argument", + "arguments", + "getopt", + "minimist", + "optimist" + ], + "license": "MIT", + "name": "has-flag", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/has-flag.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "4.0.0" +} diff --git a/node_modules/has-flag/readme.md b/node_modules/has-flag/readme.md new file mode 100644 index 0000000..3f72dff --- /dev/null +++ b/node_modules/has-flag/readme.md @@ -0,0 +1,89 @@ +# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag) + +> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag + +Correctly stops looking after an `--` argument terminator. + +--- + +<div align="center"> + <b> + <a href="https://tidelift.com/subscription/pkg/npm-has-flag?utm_source=npm-has-flag&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> + </b> + <br> + <sub> + Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. + </sub> +</div> + +--- + + +## Install + +``` +$ npm install has-flag +``` + + +## Usage + +```js +// foo.js +const hasFlag = require('has-flag'); + +hasFlag('unicorn'); +//=> true + +hasFlag('--unicorn'); +//=> true + +hasFlag('f'); +//=> true + +hasFlag('-f'); +//=> true + +hasFlag('foo=bar'); +//=> true + +hasFlag('foo'); +//=> false + +hasFlag('rainbow'); +//=> false +``` + +``` +$ node foo.js -f --unicorn --foo=bar -- --rainbow +``` + + +## API + +### hasFlag(flag, [argv]) + +Returns a boolean for whether the flag exists. + +#### flag + +Type: `string` + +CLI flag to look for. The `--` prefix is optional. + +#### argv + +Type: `string[]`<br> +Default: `process.argv` + +CLI arguments. + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/i/.npmignore b/node_modules/i/.npmignore new file mode 100644 index 0000000..435e4bb --- /dev/null +++ b/node_modules/i/.npmignore @@ -0,0 +1,3 @@ +node_modules +npm-debug.log +*.swp diff --git a/node_modules/i/.travis.yml b/node_modules/i/.travis.yml new file mode 100644 index 0000000..2f1969e --- /dev/null +++ b/node_modules/i/.travis.yml @@ -0,0 +1,14 @@ +sudo: false +language: node_js +node_js: + - '5' + - '4' + - '3' + - '2' + - '1' + - '0.12' + - '0.10' + - '0.8' +notifications: + email: + on_success: never diff --git a/node_modules/i/LICENSE b/node_modules/i/LICENSE new file mode 100644 index 0000000..c9b44cb --- /dev/null +++ b/node_modules/i/LICENSE @@ -0,0 +1,18 @@ +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/i/README.md b/node_modules/i/README.md new file mode 100644 index 0000000..37ca209 --- /dev/null +++ b/node_modules/i/README.md @@ -0,0 +1,176 @@ +# inflect + +customizable inflections for nodejs + +**NOTE: 0.3.2 was accidentally unpublished from the server and npm doesn't allow me to publish it back. Please upgrade to 0.3.3** + +## Installation + +```bash +npm install i +``` + +## Usage + +Require the module before using + +```js +var inflect = require('i')(); +``` + +All the below api functions can be called directly on a string + +```js +inflect.titleize('messages to store') // === 'Messages To Store' +'messages to store'.titleize // === 'Messages To Store' +``` + +only if `true` is passed while initiating + +```js +var inflect = require('i')(true); +``` + +### Pluralize + +```js +inflect.pluralize('person'); // === 'people' +inflect.pluralize('octopus'); // === 'octopi' +inflect.pluralize('Hat'); // === 'Hats' +``` + +### Singularize + +```js +inflect.singularize('people'); // === 'person' +inflect.singularize('octopi'); // === 'octopus' +inflect.singularize('Hats'); // === 'Hat' +``` + +### Camelize + +```js +inflect.camelize('message_properties'); // === 'MessageProperties' +inflect.camelize('message_properties', false); // === 'messageProperties' +``` + +### Underscore + +```js +inflect.underscore('MessageProperties'); // === 'message_properties' +inflect.underscore('messageProperties'); // === 'message_properties' +``` + +### Humanize + +```js +inflect.humanize('message_id'); // === 'Message' +``` + +### Dasherize + +```js +inflect.dasherize('message_properties'); // === 'message-properties' +inflect.dasherize('Message Properties'); // === 'Message Properties' +``` + +### Titleize + +```js +inflect.titleize('message_properties'); // === 'Message Properties' +inflect.titleize('message properties to keep'); // === 'Message Properties to Keep' +``` + +### Demodulize + +```js +inflect.demodulize('Message.Bus.Properties'); // === 'Properties' +``` + +### Tableize + +```js +inflect.tableize('MessageBusProperty'); // === 'message_bus_properties' +``` + +### Classify + +```js +inflect.classify('message_bus_properties'); // === 'MessageBusProperty' +``` + +### Foreign key + +```js +inflect.foreign_key('MessageBusProperty'); // === 'message_bus_property_id' +inflect.foreign_key('MessageBusProperty', false); // === 'message_bus_propertyid' +``` + +### Ordinalize + +```js +inflect.ordinalize( '1' ); // === '1st' +``` + +## Custom rules for inflection + +### Custom plural + +We can use regexp in any of these custom rules + +```js +inflect.inflections.plural('person', 'guys'); +inflect.pluralize('person'); // === 'guys' +inflect.singularize('guys'); // === 'guy' +``` + +### Custom singular + +```js +inflect.inflections.singular('guys', 'person') +inflect.singularize('guys'); // === 'person' +inflect.pluralize('person'); // === 'people' +``` + +### Custom irregular + +```js +inflect.inflections.irregular('person', 'guys') +inflect.pluralize('person'); // === 'guys' +inflect.singularize('guys'); // === 'person' +``` + +### Custom human + +```js +inflect.inflections.human(/^(.*)_cnt$/i, '$1_count'); +inflect.inflections.humanize('jargon_cnt'); // === 'Jargon count' +``` + +### Custom uncountable + +```js +inflect.inflections.uncountable('oil') +inflect.pluralize('oil'); // === 'oil' +inflect.singularize('oil'); // === 'oil' +``` + +## Contributors +Here is a list of [Contributors](http://github.com/pksunkara/inflect/contributors) + +### TODO + +- More obscure test cases + +__I accept pull requests and guarantee a reply back within a day__ + +## License +MIT/X11 + +## Bug Reports +Report [here](http://github.com/pksunkara/inflect/issues). __Guaranteed reply within a day__. + +## Contact +Pavan Kumar Sunkara (pavan.sss1991@gmail.com) + +Follow me on [github](https://github.com/users/follow?target=pksunkara), [twitter](http://twitter.com/pksunkara) diff --git a/node_modules/i/lib/defaults.js b/node_modules/i/lib/defaults.js new file mode 100644 index 0000000..05bdaf2 --- /dev/null +++ b/node_modules/i/lib/defaults.js @@ -0,0 +1,68 @@ +// Default inflections +module.exports = function (inflect) { + + inflect.plural(/$/, 's'); + inflect.plural(/s$/i, 's'); + inflect.plural(/(ax|test)is$/i, '$1es'); + inflect.plural(/(octop|vir)us$/i, '$1i'); + inflect.plural(/(octop|vir)i$/i, '$1i'); + inflect.plural(/(alias|status)$/i, '$1es'); + inflect.plural(/(bu)s$/i, '$1ses'); + inflect.plural(/(buffal|tomat)o$/i, '$1oes'); + inflect.plural(/([ti])um$/i, '$1a'); + inflect.plural(/([ti])a$/i, '$1a'); + inflect.plural(/sis$/i, 'ses'); + inflect.plural(/(?:([^fa])fe|(?:(oa)f)|([lr])f)$/i, '$1ves'); + inflect.plural(/(hive)$/i, '$1s'); + inflect.plural(/([^aeiouy]|qu)y$/i, '$1ies'); + inflect.plural(/(x|ch|ss|sh)$/i, '$1es'); + inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'); + inflect.plural(/([m|l])ouse$/i, '$1ice'); + inflect.plural(/([m|l])ice$/i, '$1ice'); + inflect.plural(/^(ox)$/i, '$1en'); + inflect.plural(/^(oxen)$/i, '$1'); + inflect.plural(/(quiz)$/i, '$1zes'); + + inflect.singular(/s$/i, ''); + inflect.singular(/(n)ews$/i, '$1ews'); + inflect.singular(/([ti])a$/i, '$1um'); + inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '$1sis'); + inflect.singular(/(^analy)ses$/i, '$1sis'); + inflect.singular(/([^f])ves$/i, '$1fe'); + inflect.singular(/(hive)s$/i, '$1'); + inflect.singular(/(tive)s$/i, '$1'); + inflect.singular(/(oave)s$/i, 'oaf'); + inflect.singular(/([lr])ves$/i, '$1f'); + inflect.singular(/([^aeiouy]|qu)ies$/i, '$1y'); + inflect.singular(/(s)eries$/i, '$1eries'); + inflect.singular(/(m)ovies$/i, '$1ovie'); + inflect.singular(/(x|ch|ss|sh)es$/i, '$1'); + inflect.singular(/([m|l])ice$/i, '$1ouse'); + inflect.singular(/(bus)es$/i, '$1'); + inflect.singular(/(o)es$/i, '$1'); + inflect.singular(/(shoe)s$/i, '$1'); + inflect.singular(/(cris|ax|test)es$/i, '$1is'); + inflect.singular(/(octop|vir)i$/i, '$1us'); + inflect.singular(/(alias|status)es$/i, '$1'); + inflect.singular(/^(ox)en/i, '$1'); + inflect.singular(/(vert|ind)ices$/i, '$1ex'); + inflect.singular(/(matr)ices$/i, '$1ix'); + inflect.singular(/(quiz)zes$/i, '$1'); + inflect.singular(/(database)s$/i, '$1'); + + inflect.irregular('child', 'children'); + inflect.irregular('person', 'people'); + inflect.irregular('man', 'men'); + inflect.irregular('child', 'children'); + inflect.irregular('sex', 'sexes'); + inflect.irregular('move', 'moves'); + inflect.irregular('cow', 'kine'); + inflect.irregular('zombie', 'zombies'); + inflect.irregular('oaf', 'oafs', true); + inflect.irregular('jefe', 'jefes'); + inflect.irregular('save', 'saves'); + inflect.irregular('safe', 'safes'); + inflect.irregular('fife', 'fifes'); + + inflect.uncountable(['equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'sushi']); +} diff --git a/node_modules/i/lib/inflect.js b/node_modules/i/lib/inflect.js new file mode 100644 index 0000000..5e0cc70 --- /dev/null +++ b/node_modules/i/lib/inflect.js @@ -0,0 +1,11 @@ +// Requiring modules + +module.exports = function (attach) { + var methods = require('./methods'); + + if (attach) { + require('./native')(methods); + } + + return methods +}; diff --git a/node_modules/i/lib/inflections.js b/node_modules/i/lib/inflections.js new file mode 100644 index 0000000..1972551 --- /dev/null +++ b/node_modules/i/lib/inflections.js @@ -0,0 +1,120 @@ +// A singleton instance of this class is yielded by Inflector.inflections, which can then be used to specify additional +// inflection rules. Examples: +// +// BulletSupport.Inflector.inflect ($) -> +// $.plural /^(ox)$/i, '$1en' +// $.singular /^(ox)en/i, '$1' +// +// $.irregular 'octopus', 'octopi' +// +// $.uncountable "equipment" +// +// New rules are added at the top. So in the example above, the irregular rule for octopus will now be the first of the +// pluralization and singularization rules that is runs. This guarantees that your rules run before any of the rules that may +// already have been loaded. + +var util = require('./util'); + +var Inflections = function () { + this.plurals = []; + this.singulars = []; + this.uncountables = []; + this.humans = []; + require('./defaults')(this); + return this; +}; + +// Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression. +// The replacement should always be a string that may include references to the matched data from the rule. +Inflections.prototype.plural = function (rule, replacement) { + if (typeof rule == 'string') { + this.uncountables = util.array.del(this.uncountables, rule); + } + this.uncountables = util.array.del(this.uncountables, replacement); + this.plurals.unshift([rule, replacement]); +}; + +// Specifies a new singularization rule and its replacement. The rule can either be a string or a regular expression. +// The replacement should always be a string that may include references to the matched data from the rule. +Inflections.prototype.singular = function (rule, replacement) { + if (typeof rule == 'string') { + this.uncountables = util.array.del(this.uncountables, rule); + } + this.uncountables = util.array.del(this.uncountables, replacement); + this.singulars.unshift([rule, replacement]); +}; + +// Specifies a new irregular that applies to both pluralization and singularization at the same time. This can only be used +// for strings, not regular expressions. You simply pass the irregular in singular and plural form. +// +// irregular 'octopus', 'octopi' +// irregular 'person', 'people' +Inflections.prototype.irregular = function (singular, plural, fullMatchRequired) { + this.uncountables = util.array.del(this.uncountables, singular); + this.uncountables = util.array.del(this.uncountables, plural); + var prefix = ""; + if (fullMatchRequired) { + prefix = "^"; + } + if (singular[0].toUpperCase() == plural[0].toUpperCase()) { + this.plural(new RegExp("(" + prefix + singular[0] + ")" + singular.slice(1) + "$", "i"), '$1' + plural.slice(1)); + this.plural(new RegExp("(" + prefix + plural[0] + ")" + plural.slice(1) + "$", "i"), '$1' + plural.slice(1)); + this.singular(new RegExp("(" + prefix + plural[0] + ")" + plural.slice(1) + "$", "i"), '$1' + singular.slice(1)); + } else { + this.plural(new RegExp(prefix + (singular[0].toUpperCase()) + singular.slice(1) + "$"), plural[0].toUpperCase() + plural.slice(1)); + this.plural(new RegExp(prefix + (singular[0].toLowerCase()) + singular.slice(1) + "$"), plural[0].toLowerCase() + plural.slice(1)); + this.plural(new RegExp(prefix + (plural[0].toUpperCase()) + plural.slice(1) + "$"), plural[0].toUpperCase() + plural.slice(1)); + this.plural(new RegExp(prefix + (plural[0].toLowerCase()) + plural.slice(1) + "$"), plural[0].toLowerCase() + plural.slice(1)); + this.singular(new RegExp(prefix + (plural[0].toUpperCase()) + plural.slice(1) + "$"), singular[0].toUpperCase() + singular.slice(1)); + this.singular(new RegExp(prefix + (plural[0].toLowerCase()) + plural.slice(1) + "$"), singular[0].toLowerCase() + singular.slice(1)); + } +}; + +// Specifies a humanized form of a string by a regular expression rule or by a string mapping. +// When using a regular expression based replacement, the normal humanize formatting is called after the replacement. +// When a string is used, the human form should be specified as desired (example: 'The name', not 'the_name') +// +// human /(.*)_cnt$/i, '$1_count' +// human "legacy_col_person_name", "Name" +Inflections.prototype.human = function (rule, replacement) { + this.humans.unshift([rule, replacement]); +} + +// Add uncountable words that shouldn't be attempted inflected. +// +// uncountable "money" +// uncountable ["money", "information"] +Inflections.prototype.uncountable = function (words) { + this.uncountables = this.uncountables.concat(words); +} + +// Clears the loaded inflections within a given scope (default is _'all'_). +// Give the scope as a symbol of the inflection type, the options are: _'plurals'_, +// _'singulars'_, _'uncountables'_, _'humans'_. +// +// clear 'all' +// clear 'plurals' +Inflections.prototype.clear = function (scope) { + if (scope == null) scope = 'all'; + switch (scope) { + case 'all': + this.plurals = []; + this.singulars = []; + this.uncountables = []; + this.humans = []; + default: + this[scope] = []; + } +} + +// Clears the loaded inflections and initializes them to [default](../inflections.html) +Inflections.prototype.default = function () { + this.plurals = []; + this.singulars = []; + this.uncountables = []; + this.humans = []; + require('./defaults')(this); + return this; +}; + +module.exports = new Inflections(); diff --git a/node_modules/i/lib/methods.js b/node_modules/i/lib/methods.js new file mode 100644 index 0000000..8bbc9be --- /dev/null +++ b/node_modules/i/lib/methods.js @@ -0,0 +1,232 @@ +// The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without, +// and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept +// in inflections.coffee +// +// If you discover an incorrect inflection and require it for your application, you'll need +// to correct it yourself (explained below). + +var util = require('./util'); + +var inflect = module.exports; + +// Import [inflections](inflections.html) instance +inflect.inflections = require('./inflections') + +// Gives easy access to add inflections to this class +inflect.inflect = function (fn) { + fn(inflect.inflections); +}; + +// By default, _camelize_ converts strings to UpperCamelCase. If the argument to _camelize_ +// is set to _false_ then _camelize_ produces lowerCamelCase. +// +// _camelize_ will also convert '/' to '.' which is useful for converting paths to namespaces. +// +// "bullet_record".camelize() // => "BulletRecord" +// "bullet_record".camelize(false) // => "bulletRecord" +// "bullet_record/errors".camelize() // => "BulletRecord.Errors" +// "bullet_record/errors".camelize(false) // => "bulletRecord.Errors" +// +// As a rule of thumb you can think of _camelize_ as the inverse of _underscore_, +// though there are cases where that does not hold: +// +// "SSLError".underscore.camelize // => "SslError" +inflect.camelize = function(lower_case_and_underscored_word, first_letter_in_uppercase) { + var result; + if (first_letter_in_uppercase == null) first_letter_in_uppercase = true; + result = util.string.gsub(lower_case_and_underscored_word, /\/(.?)/, function($) { + return "." + (util.string.upcase($[1])); + }); + result = util.string.gsub(result, /(?:_)(.)/, function($) { + return util.string.upcase($[1]); + }); + if (first_letter_in_uppercase) { + return util.string.upcase(result); + } else { + return util.string.downcase(result); + } +}; + +// Makes an underscored, lowercase form from the expression in the string. +// +// Changes '.' to '/' to convert namespaces to paths. +// +// "BulletRecord".underscore() // => "bullet_record" +// "BulletRecord.Errors".underscore() // => "bullet_record/errors" +// +// As a rule of thumb you can think of +underscore+ as the inverse of +camelize+, +// though there are cases where that does not hold: +// +// "SSLError".underscore().camelize() // => "SslError" +inflect.underscore = function (camel_cased_word) { + var self; + self = util.string.gsub(camel_cased_word, /\./, '/'); + self = util.string.gsub(self, /([A-Z]+)([A-Z][a-z])/, "$1_$2"); + self = util.string.gsub(self, /([a-z\d])([A-Z])/, "$1_$2"); + self = util.string.gsub(self, /-/, '_'); + return self.toLowerCase(); +}; + +// Replaces underscores with dashes in the string. +// +// "puni_puni".dasherize() // => "puni-puni" +inflect.dasherize = function (underscored_word) { + return util.string.gsub(underscored_word, /_/, '-'); +}; + +// Removes the module part from the expression in the string. +// +// "BulletRecord.String.Inflections".demodulize() // => "Inflections" +// "Inflections".demodulize() // => "Inflections" +inflect.demodulize = function (class_name_in_module) { + return util.string.gsub(class_name_in_module, /^.*\./, ''); +}; + +// Creates a foreign key name from a class name. +// _separate_class_name_and_id_with_underscore_ sets whether +// the method should put '_' between the name and 'id'. +// +// "Message".foreign_key() // => "message_id" +// "Message".foreign_key(false) // => "messageid" +// "Admin::Post".foreign_key() // => "post_id" +inflect.foreign_key = function (class_name, separate_class_name_and_id_with_underscore) { + if (separate_class_name_and_id_with_underscore == null) { + separate_class_name_and_id_with_underscore = true; + } + return inflect.underscore(inflect.demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id"); +}; + +// Turns a number into an ordinal string used to denote the position in an +// ordered sequence such as 1st, 2nd, 3rd, 4th. +// +// ordinalize(1) // => "1st" +// ordinalize(2) // => "2nd" +// ordinalize(1002) // => "1002nd" +// ordinalize(1003) // => "1003rd" +// ordinalize(-11) // => "-11th" +// ordinalize(-1021) // => "-1021st" +inflect.ordinalize = function (number) { + var _ref; + number = parseInt(number); + if ((_ref = Math.abs(number) % 100) === 11 || _ref === 12 || _ref === 13) { + return "" + number + "th"; + } else { + switch (Math.abs(number) % 10) { + case 1: + return "" + number + "st"; + case 2: + return "" + number + "nd"; + case 3: + return "" + number + "rd"; + default: + return "" + number + "th"; + } + } +}; + +// Checks a given word for uncountability +// +// "money".uncountability() // => true +// "my money".uncountability() // => true +inflect.uncountability = function (word) { + return inflect.inflections.uncountables.some(function(ele, ind, arr) { + return word.match(new RegExp("(\\b|_)" + ele + "$", 'i')) != null; + }); +}; + +// Returns the plural form of the word in the string. +// +// "post".pluralize() // => "posts" +// "octopus".pluralize() // => "octopi" +// "sheep".pluralize() // => "sheep" +// "words".pluralize() // => "words" +// "CamelOctopus".pluralize() // => "CamelOctopi" +inflect.pluralize = function (word) { + var plural, result; + result = word; + if (word === '' || inflect.uncountability(word)) { + return result; + } else { + for (var i = 0; i < inflect.inflections.plurals.length; i++) { + plural = inflect.inflections.plurals[i]; + result = util.string.gsub(result, plural[0], plural[1]); + if (word.match(plural[0]) != null) break; + } + return result; + } +}; + +// The reverse of _pluralize_, returns the singular form of a word in a string. +// +// "posts".singularize() // => "post" +// "octopi".singularize() // => "octopus" +// "sheep".singularize() // => "sheep" +// "word".singularize() // => "word" +// "CamelOctopi".singularize() // => "CamelOctopus" +inflect.singularize = function (word) { + var result, singular; + result = word; + if (word === '' || inflect.uncountability(word)) { + return result; + } else { + for (var i = 0; i < inflect.inflections.singulars.length; i++) { + singular = inflect.inflections.singulars[i]; + result = util.string.gsub(result, singular[0], singular[1]); + if (word.match(singular[0])) break; + } + return result; + } +}; + +// Capitalizes the first word and turns underscores into spaces and strips a +// trailing "_id", if any. Like _titleize_, this is meant for creating pretty output. +// +// "employee_salary".humanize() // => "Employee salary" +// "author_id".humanize() // => "Author" +inflect.humanize = function (lower_case_and_underscored_word) { + var human, result; + result = lower_case_and_underscored_word; + for (var i = 0; i < inflect.inflections.humans.length; i++) { + human = inflect.inflections.humans[i]; + result = util.string.gsub(result, human[0], human[1]); + } + result = util.string.gsub(result, /_id$/, ""); + result = util.string.gsub(result, /_/, " "); + return util.string.capitalize(result, true); +}; + +// Capitalizes all the words and replaces some characters in the string to create +// a nicer looking title. _titleize_ is meant for creating pretty output. It is not +// used in the Bullet internals. +// +// +// "man from the boondocks".titleize() // => "Man From The Boondocks" +// "x-men: the last stand".titleize() // => "X Men: The Last Stand" +inflect.titleize = function (word) { + var self; + self = inflect.humanize(inflect.underscore(word)); + return util.string.capitalize(self); +}; + +// Create the name of a table like Bullet does for models to table names. This method +// uses the _pluralize_ method on the last word in the string. +// +// "RawScaledScorer".tableize() // => "raw_scaled_scorers" +// "egg_and_ham".tableize() // => "egg_and_hams" +// "fancyCategory".tableize() // => "fancy_categories" +inflect.tableize = function (class_name) { + return inflect.pluralize(inflect.underscore(class_name)); +}; + +// Create a class name from a plural table name like Bullet does for table names to models. +// Note that this returns a string and not a Class. +// +// "egg_and_hams".classify() // => "EggAndHam" +// "posts".classify() // => "Post" +// +// Singular names are not handled correctly: +// +// "business".classify() // => "Busines" +inflect.classify = function (table_name) { + return inflect.camelize(inflect.singularize(util.string.gsub(table_name, /.*\./, ''))); +} diff --git a/node_modules/i/lib/native.js b/node_modules/i/lib/native.js new file mode 100644 index 0000000..d2c8de1 --- /dev/null +++ b/node_modules/i/lib/native.js @@ -0,0 +1,26 @@ +module.exports = function (obj) { + + var addProperty = function (method, func) { + String.prototype.__defineGetter__(method, func); + } + + 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', 'gsub' + ]; + + Object.keys(obj).forEach(function (key) { + if (key != 'inflect' && key != 'inflections') { + if (stringPrototypeBlacklist.indexOf(key) !== -1) { + console.log('warn: You should not override String.prototype.' + key); + } else { + addProperty(key, function () { + return obj[key](this); + }); + } + } + }); + +} diff --git a/node_modules/i/lib/util.js b/node_modules/i/lib/util.js new file mode 100644 index 0000000..7af707d --- /dev/null +++ b/node_modules/i/lib/util.js @@ -0,0 +1,147 @@ +// Some utility functions in js + +var u = module.exports = { + array: { + // Returns a copy of the array with the value removed once + // + // [1, 2, 3, 1].del 1 #=> [2, 3, 1] + // [1, 2, 3].del 4 #=> [1, 2, 3] + del: function (arr, val) { + var index = arr.indexOf(val); + + if (index != -1) { + if (index == 0) { + return arr.slice(1) + } else { + return arr.slice(0, index).concat(arr.slice(index+1)); + } + } else { + return arr; + } + }, + + // Returns the first element of the array + // + // [1, 2, 3].first() #=> 1 + first: function(arr) { + return arr[0]; + }, + + // Returns the last element of the array + // + // [1, 2, 3].last() #=> 3 + last: function(arr) { + return arr[arr.length-1]; + } + }, + string: { + // Returns a copy of str with all occurrences of pattern replaced with either replacement or the return value of a function. + // The pattern will typically be a Regexp; if it is a String then no regular expression metacharacters will be interpreted + // (that is /\d/ will match a digit, but ‘\d’ will match a backslash followed by a ‘d’). + // + // In the function form, the current match object is passed in as a parameter to the function, and variables such as + // $[1], $[2], $[3] (where $ is the match object) will be set appropriately. The value returned by the function will be + // substituted for the match on each call. + // + // The result inherits any tainting in the original string or any supplied replacement string. + // + // "hello".gsub /[aeiou]/, '*' #=> "h*ll*" + // "hello".gsub /[aeiou]/, '<$1>' #=> "h<e>ll<o>" + // "hello".gsub /[aeiou]/, ($) { + // "<#{$[1]}>" #=> "h<e>ll<o>" + // + gsub: function (str, pattern, replacement) { + var i, match, matchCmpr, matchCmprPrev, replacementStr, result, self; + if (!((pattern != null) && (replacement != null))) return u.string.value(str); + result = ''; + self = str; + while (self.length > 0) { + if ((match = self.match(pattern))) { + result += self.slice(0, match.index); + if (typeof replacement === 'function') { + match[1] = match[1] || match[0]; + result += replacement(match); + } else if (replacement.match(/\$[1-9]/)) { + matchCmprPrev = match; + matchCmpr = u.array.del(match, void 0); + while (matchCmpr !== matchCmprPrev) { + matchCmprPrev = matchCmpr; + matchCmpr = u.array.del(matchCmpr, void 0); + } + match[1] = match[1] || match[0]; + replacementStr = replacement; + for (i = 1; i <= 9; i++) { + if (matchCmpr[i]) { + replacementStr = u.string.gsub(replacementStr, new RegExp("\\\$" + i), matchCmpr[i]); + } + } + result += replacementStr; + } else { + result += replacement; + } + self = self.slice(match.index + match[0].length); + } else { + result += self; + self = ''; + } + } + return result; + }, + + // Returns a copy of the String with the first letter being upper case + // + // "hello".upcase #=> "Hello" + upcase: function(str) { + var self = u.string.gsub(str, /_([a-z])/, function ($) { + return "_" + $[1].toUpperCase(); + }); + + self = u.string.gsub(self, /\/([a-z])/, function ($) { + return "/" + $[1].toUpperCase(); + }); + + return self[0].toUpperCase() + self.substr(1); + }, + + // Returns a copy of capitalized string + // + // "employee salary" #=> "Employee Salary" + capitalize: function (str, spaces) { + if (!str.length) { + return str; + } + + var self = str.toLowerCase(); + + if (!spaces) { + self = u.string.gsub(self, /\s([a-z])/, function ($) { + return " " + $[1].toUpperCase(); + }); + } + + return self[0].toUpperCase() + self.substr(1); + }, + + // Returns a copy of the String with the first letter being lower case + // + // "HELLO".downcase #=> "hELLO" + downcase: function(str) { + var self = u.string.gsub(str, /_([A-Z])/, function ($) { + return "_" + $[1].toLowerCase(); + }); + + self = u.string.gsub(self, /\/([A-Z])/, function ($) { + return "/" + $[1].toLowerCase(); + }); + + return self[0].toLowerCase() + self.substr(1); + }, + + // Returns a string value for the String object + // + // "hello".value() #=> "hello" + value: function (str) { + return str.substr(0); + } + } +} diff --git a/node_modules/i/package.json b/node_modules/i/package.json new file mode 100644 index 0000000..156ba2a --- /dev/null +++ b/node_modules/i/package.json @@ -0,0 +1,82 @@ +{ + "_from": "i@0.3.x", + "_id": "i@0.3.6", + "_inBundle": false, + "_integrity": "sha1-2WyScyB28HJxG2sQ/X1PZa2O4j0=", + "_location": "/i", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "i@0.3.x", + "name": "i", + "escapedName": "i", + "rawSpec": "0.3.x", + "saveSpec": null, + "fetchSpec": "0.3.x" + }, + "_requiredBy": [ + "/utile" + ], + "_resolved": "https://registry.npmjs.org/i/-/i-0.3.6.tgz", + "_shasum": "d96c92732076f072711b6b10fd7d4f65ad8ee23d", + "_spec": "i@0.3.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/utile", + "author": { + "name": "Pavan Kumar Sunkara", + "email": "pavan.sss1991@gmail.com", + "url": "pksunkara.github.com" + }, + "bugs": { + "url": "https://github.com/pksunkara/inflect/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Pavan Kumar Sunkara", + "email": "pavan.sss1991@gmail.com" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "custom inflections for nodejs", + "devDependencies": { + "vows": "0.7.0" + }, + "engines": { + "node": ">=0.4" + }, + "homepage": "http://pksunkara.github.com/inflect", + "keywords": [ + "singular", + "plural", + "camelize", + "underscore", + "dasherize", + "demodulize", + "ordinalize", + "uncountable", + "pluralize", + "singularize", + "titleize", + "tableize", + "classify", + "foreign_key" + ], + "licenses": [ + { + "type": "MIT", + "url": "https://github.com/pksunkara/inflect/raw/master/LICENSE" + } + ], + "main": "./lib/inflect", + "name": "i", + "repository": { + "type": "git", + "url": "git://github.com/pksunkara/inflect.git" + }, + "scripts": { + "test": "vows --spec $(find test -name '*-test.js')" + }, + "version": "0.3.6" +} diff --git a/node_modules/i/test/inflector/cases.js b/node_modules/i/test/inflector/cases.js new file mode 100644 index 0000000..a818f9a --- /dev/null +++ b/node_modules/i/test/inflector/cases.js @@ -0,0 +1,230 @@ +(function() { + + module.exports = { + SingularToPlural: { + "search": "searches", + "switch": "switches", + "fix": "fixes", + "box": "boxes", + "process": "processes", + "address": "addresses", + "case": "cases", + "stack": "stacks", + "wish": "wishes", + "fish": "fish", + "jeans": "jeans", + "funky jeans": "funky jeans", + "my money": "my money", + "category": "categories", + "query": "queries", + "ability": "abilities", + "agency": "agencies", + "movie": "movies", + "archive": "archives", + "index": "indices", + "wife": "wives", + "safe": "saves", + "half": "halves", + "move": "moves", + "salesperson": "salespeople", + "person": "people", + "spokesman": "spokesmen", + "man": "men", + "woman": "women", + "basis": "bases", + "diagnosis": "diagnoses", + "diagnosis_a": "diagnosis_as", + "datum": "data", + "medium": "media", + "stadium": "stadia", + "analysis": "analyses", + "node_child": "node_children", + "child": "children", + "experience": "experiences", + "day": "days", + "comment": "comments", + "foobar": "foobars", + "newsletter": "newsletters", + "old_news": "old_news", + "news": "news", + "series": "series", + "species": "species", + "quiz": "quizzes", + "perspective": "perspectives", + "ox": "oxen", + "photo": "photos", + "buffalo": "buffaloes", + "tomato": "tomatoes", + "dwarf": "dwarves", + "elf": "elves", + "information": "information", + "equipment": "equipment", + "bus": "buses", + "status": "statuses", + "status_code": "status_codes", + "mouse": "mice", + "louse": "lice", + "house": "houses", + "octopus": "octopi", + "virus": "viri", + "alias": "aliases", + "portfolio": "portfolios", + "vertex": "vertices", + "matrix": "matrices", + "matrix_fu": "matrix_fus", + "axis": "axes", + "testis": "testes", + "crisis": "crises", + "rice": "rice", + "shoe": "shoes", + "horse": "horses", + "prize": "prizes", + "edge": "edges", + "cow": "kine", + "database": "databases", + "safe": "safes", + "belief": "beliefs", + "gaffe": "gaffes", + "cafe": "cafes", + "caffe": "caffes", + "life": "lives", + "wife": "wives", + "save": "saves", + "fife": "fifes", + "carafe": "carafes", + "giraffe": "giraffes", + "elf": "elves", + "calf": "calves", + "bookshelf": "bookshelves", + "wolf": "wolves", + "half": "halves", + "meatloaf": "meatloaves", + "loaf": "loaves", + "oaf": "oafs", + "jefe": "jefes", + "afterlife": "afterlives", + }, + CamelToUnderscore: { + "Product": "product", + "SpecialGuest": "special_guest", + "ApplicationController": "application_controller", + "Area51Controller": "area51_controller" + }, + UnderscoreToLowerCamel: { + "product": "product", + "Widget": "widget", + "special_guest": "specialGuest", + "application_controller": "applicationController", + "area51_controller": "area51Controller" + }, + CamelToUnderscoreWithoutReverse: { + "HTMLTidy": "html_tidy", + "HTMLTidyGenerator": "html_tidy_generator", + "FreeBSD": "free_bsd", + "HTML": "html" + }, + CamelWithModuleToUnderscoreWithSlash: { + "Admin.Product": "admin/product", + "Users.Commission.Department": "users/commission/department", + "UsersSection.CommissionDepartment": "users_section/commission_department" + }, + ClassNameToForeignKeyWithUnderscore: { + "Person": "person_id", + "MyApplication.Billing.Account": "account_id" + }, + ClassNameToForeignKeyWithoutUnderscore: { + "Person": "personid", + "MyApplication.Billing.Account": "accountid" + }, + ClassNameToTableName: { + "PrimarySpokesman": "primary_spokesmen", + "NodeChild": "node_children" + }, + UnderscoreToHuman: { + "employee_salary": "Employee salary", + "employee_id": "Employee", + "underground": "Underground" + }, + MixtureToTitleCase: { + 'bullet_record': 'Bullet Record', + 'BulletRecord': 'Bullet Record', + 'bullet web service': 'Bullet Web Service', + 'Bullet Web Service': 'Bullet Web Service', + 'Bullet web service': 'Bullet Web Service', + 'bulletwebservice': 'Bulletwebservice', + 'Bulletwebservice': 'Bulletwebservice', + "pavan's code": "Pavan's Code", + "Pavan's code": "Pavan's Code", + "pavan's Code": "Pavan's Code" + }, + OrdinalNumbers: { + "-1": "-1st", + "-2": "-2nd", + "-3": "-3rd", + "-4": "-4th", + "-5": "-5th", + "-6": "-6th", + "-7": "-7th", + "-8": "-8th", + "-9": "-9th", + "-10": "-10th", + "-11": "-11th", + "-12": "-12th", + "-13": "-13th", + "-14": "-14th", + "-20": "-20th", + "-21": "-21st", + "-22": "-22nd", + "-23": "-23rd", + "-24": "-24th", + "-100": "-100th", + "-101": "-101st", + "-102": "-102nd", + "-103": "-103rd", + "-104": "-104th", + "-110": "-110th", + "-111": "-111th", + "-112": "-112th", + "-113": "-113th", + "-1000": "-1000th", + "-1001": "-1001st", + "0": "0th", + "1": "1st", + "2": "2nd", + "3": "3rd", + "4": "4th", + "5": "5th", + "6": "6th", + "7": "7th", + "8": "8th", + "9": "9th", + "10": "10th", + "11": "11th", + "12": "12th", + "13": "13th", + "14": "14th", + "20": "20th", + "21": "21st", + "22": "22nd", + "23": "23rd", + "24": "24th", + "100": "100th", + "101": "101st", + "102": "102nd", + "103": "103rd", + "104": "104th", + "110": "110th", + "111": "111th", + "112": "112th", + "113": "113th", + "1000": "1000th", + "1001": "1001st" + }, + UnderscoresToDashes: { + "street": "street", + "street_address": "street-address", + "person_street_address": "person-street-address" + } + }; + +}).call(this); diff --git a/node_modules/i/test/inflector/inflections-test.js b/node_modules/i/test/inflector/inflections-test.js new file mode 100644 index 0000000..be8d960 --- /dev/null +++ b/node_modules/i/test/inflector/inflections-test.js @@ -0,0 +1,87 @@ +(function() { + var assert, vows; + + vows = require('vows'); + + assert = require('assert'); + + vows.describe('Module Inflector inflections').addBatch({ + 'Test inflector inflections': { + topic: require('../../lib/inflections'), + 'clear': { + 'single': function(topic) { + topic.uncountables = [1, 2, 3]; + topic.humans = [1, 2, 3]; + topic.clear('uncountables'); + assert.isEmpty(topic.uncountables); + return assert.deepEqual(topic.humans, [1, 2, 3]); + }, + 'all': function(topic) { + assert.deepEqual(topic.humans, [1, 2, 3]); + topic.uncountables = [1, 2, 3]; + topic.clear(); + assert.isEmpty(topic.uncountables); + return assert.isEmpty(topic.humans); + } + }, + 'uncountable': { + 'one item': function(topic) { + topic.clear(); + assert.isEmpty(topic.uncountables); + topic.uncountable('money'); + return assert.deepEqual(topic.uncountables, ['money']); + }, + 'many items': function(topic) { + topic.clear(); + assert.isEmpty(topic.uncountables); + topic.uncountable(['money', 'rice']); + return assert.deepEqual(topic.uncountables, ['money', 'rice']); + } + }, + 'human': function(topic) { + topic.clear(); + assert.isEmpty(topic.humans); + topic.human("legacy_col_person_name", "Name"); + return assert.deepEqual(topic.humans, [["legacy_col_person_name", "Name"]]); + }, + 'plural': function(topic) { + topic.clear(); + assert.isEmpty(topic.plurals); + topic.plural('ox', 'oxen'); + assert.deepEqual(topic.plurals, [['ox', 'oxen']]); + topic.uncountable('money'); + assert.deepEqual(topic.uncountables, ['money']); + topic.uncountable('monies'); + topic.plural('money', 'monies'); + assert.deepEqual(topic.plurals, [['money', 'monies'], ['ox', 'oxen']]); + return assert.isEmpty(topic.uncountables); + }, + 'singular': function(topic) { + topic.clear(); + assert.isEmpty(topic.singulars); + topic.singular('ox', 'oxen'); + assert.deepEqual(topic.singulars, [['ox', 'oxen']]); + topic.uncountable('money'); + assert.deepEqual(topic.uncountables, ['money']); + topic.uncountable('monies'); + topic.singular('money', 'monies'); + assert.deepEqual(topic.singulars, [['money', 'monies'], ['ox', 'oxen']]); + return assert.isEmpty(topic.uncountables); + }, + 'irregular': function(topic) { + topic.clear(); + topic.uncountable(['octopi', 'octopus']); + assert.deepEqual(topic.uncountables, ['octopi', 'octopus']); + topic.irregular('octopus', 'octopi'); + assert.isEmpty(topic.uncountables); + assert.equal(topic.singulars[0][0].toString(), /(o)ctopi$/i.toString()); + assert.equal(topic.singulars[0][1], '$1ctopus'); + assert.equal(topic.plurals[0][0].toString(), /(o)ctopi$/i.toString()); + assert.equal(topic.plurals[0][1], '$1ctopi'); + assert.equal(topic.plurals[1][0].toString(), /(o)ctopus$/i.toString()); + return assert.equal(topic.plurals[1][1].toString(), '$1ctopi'); + } + } + })["export"](module); + +}).call(this); diff --git a/node_modules/i/test/inflector/methods-test.js b/node_modules/i/test/inflector/methods-test.js new file mode 100644 index 0000000..1cd419b --- /dev/null +++ b/node_modules/i/test/inflector/methods-test.js @@ -0,0 +1,348 @@ +(function() { + var assert, cases, vows, util; + + vows = require('vows'); + + assert = require('assert'); + + util = require('../../lib/util'); + + cases = require('./cases'); + + vows.describe('Module Inflector methods').addBatch({ + 'Test inflector method': { + topic: require('../../lib/methods'), + 'camelize': { + 'word': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.CamelToUnderscore; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.camelize(words[i]), i)); + } + return _results; + }, + 'word with first letter lower': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.UnderscoreToLowerCamel; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.camelize(i, false), words[i])); + } + return _results; + }, + 'path': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.CamelWithModuleToUnderscoreWithSlash; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.camelize(words[i]), i)); + } + return _results; + }, + 'path with first letter lower': function(topic) { + return assert.equal(topic.camelize('bullet_record/errors', false), 'bulletRecord.Errors'); + } + }, + 'underscore': { + 'word': function(topic) { + var i, words, _i, _j, _len, _len2, _ref, _ref2, _results; + words = cases.CamelToUnderscore; + _ref = Object.keys(words); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + assert.equal(topic.underscore(i), words[i]); + } + words = cases.CamelToUnderscoreWithoutReverse; + _ref2 = Object.keys(words); + _results = []; + for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) { + i = _ref2[_j]; + _results.push(assert.equal(topic.underscore(i), words[i])); + } + return _results; + }, + 'path': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.CamelWithModuleToUnderscoreWithSlash; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.underscore(i), words[i])); + } + return _results; + }, + 'from dasherize': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.UnderscoresToDashes; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.underscore(topic.dasherize(i)), i)); + } + return _results; + } + }, + 'dasherize': { + 'underscored_word': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.UnderscoresToDashes; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.dasherize(i), words[i])); + } + return _results; + } + }, + 'demodulize': { + 'module name': function(topic) { + return assert.equal(topic.demodulize('BulletRecord.CoreExtensions.Inflections'), 'Inflections'); + }, + 'isolated module name': function(topic) { + return assert.equal(topic.demodulize('Inflections'), 'Inflections'); + } + }, + 'foreign_key': { + 'normal': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.ClassNameToForeignKeyWithoutUnderscore; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.foreign_key(i, false), words[i])); + } + return _results; + }, + 'with_underscore': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.ClassNameToForeignKeyWithUnderscore; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.foreign_key(i), words[i])); + } + return _results; + } + }, + 'ordinalize': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.OrdinalNumbers; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.ordinalize(i), words[i])); + } + return _results; + } + } + }).addBatch({ + 'Test inflector inflection methods': { + topic: function() { + var Inflector; + Inflector = require('../../lib/methods'); + Inflector.inflections["default"](); + return Inflector; + }, + 'pluralize': { + 'empty': function(topic) { + return assert.equal(topic.pluralize(''), ''); + }, + 'uncountable': function(topic) { + return assert.equal(topic.pluralize('money'), 'money'); + }, + 'normal': function(topic) { + topic.inflections.irregular('octopus', 'octopi'); + return assert.equal(topic.pluralize('octopus'), 'octopi'); + }, + 'cases': function(topic) { + var i, words, _i, _j, _len, _len2, _ref, _ref2, _results; + words = cases.SingularToPlural; + _ref = Object.keys(words); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + assert.equal(topic.pluralize(i), words[i]); + } + _ref2 = Object.keys(words); + _results = []; + for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) { + i = _ref2[_j]; + _results.push(assert.equal(topic.pluralize(util.string.capitalize(i)), util.string.capitalize(words[i]))); + } + return _results; + }, + 'cases plural': function(topic) { + var i, words, _i, _j, _len, _len2, _ref, _ref2, _results; + words = cases.SingularToPlural; + _ref = Object.keys(words); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + assert.equal(topic.pluralize(words[i]), words[i]); + } + _ref2 = Object.keys(words); + _results = []; + for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) { + i = _ref2[_j]; + _results.push(assert.equal(topic.pluralize(util.string.capitalize(words[i])), util.string.capitalize(words[i]))); + } + return _results; + } + }, + 'singuralize': { + 'empty': function(topic) { + return assert.equal(topic.singularize(''), ''); + }, + 'uncountable': function(topic) { + return assert.equal(topic.singularize('money'), 'money'); + }, + 'normal': function(topic) { + topic.inflections.irregular('octopus', 'octopi'); + return assert.equal(topic.singularize('octopi'), 'octopus'); + }, + 'cases': function(topic) { + var i, words, _i, _j, _len, _len2, _ref, _ref2, _results; + words = cases.SingularToPlural; + _ref = Object.keys(words); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + assert.equal(topic.singularize(words[i]), i); + } + _ref2 = Object.keys(words); + _results = []; + for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) { + i = _ref2[_j]; + _results.push(assert.equal(topic.singularize(util.string.capitalize(words[i])), util.string.capitalize(i))); + } + return _results; + } + }, + 'uncountablility': { + 'normal': function(topic) { + var i, words, _i, _j, _k, _len, _len2, _len3, _results; + words = topic.inflections.uncountables; + for (_i = 0, _len = words.length; _i < _len; _i++) { + i = words[_i]; + assert.equal(topic.singularize(i), i); + } + for (_j = 0, _len2 = words.length; _j < _len2; _j++) { + i = words[_j]; + assert.equal(topic.pluralize(i), i); + } + _results = []; + for (_k = 0, _len3 = words.length; _k < _len3; _k++) { + i = words[_k]; + _results.push(assert.equal(topic.singularize(i), topic.pluralize(i))); + } + return _results; + }, + 'greedy': function(topic) { + var countable_word, uncountable_word; + uncountable_word = "ors"; + countable_word = "sponsor"; + topic.inflections.uncountable(uncountable_word); + assert.equal(topic.singularize(uncountable_word), uncountable_word); + assert.equal(topic.pluralize(uncountable_word), uncountable_word); + assert.equal(topic.pluralize(uncountable_word), topic.singularize(uncountable_word)); + assert.equal(topic.singularize(countable_word), 'sponsor'); + assert.equal(topic.pluralize(countable_word), 'sponsors'); + return assert.equal(topic.singularize(topic.pluralize(countable_word)), 'sponsor'); + } + }, + 'humanize': { + 'normal': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.UnderscoreToHuman; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.humanize(i), words[i])); + } + return _results; + }, + 'with rule': function(topic) { + topic.inflections.human(/^(.*)_cnt$/i, '$1_count'); + topic.inflections.human(/^prefix_(.*)$/i, '$1'); + assert.equal(topic.humanize('jargon_cnt'), 'Jargon count'); + return assert.equal(topic.humanize('prefix_request'), 'Request'); + }, + 'with string': function(topic) { + topic.inflections.human('col_rpted_bugs', 'Reported bugs'); + assert.equal(topic.humanize('col_rpted_bugs'), 'Reported bugs'); + return assert.equal(topic.humanize('COL_rpted_bugs'), 'Col rpted bugs'); + }, + 'with _id': function(topic) { + return assert.equal(topic.humanize('author_id'), 'Author'); + }, + 'with just _id': function(topic) { + return assert.equal(topic.humanize('_id'), ''); + } + }, + 'titleize': { + 'normal': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.MixtureToTitleCase; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.titleize(i), words[i])); + } + return _results; + }, + 'with hyphens': function(topic) { + return assert.equal(topic.titleize('x-men: the last stand'), 'X Men: The Last Stand'); + }, + 'with ampersands': function(topic) { + return assert.equal(topic.titleize('garfunkel & oates'), 'Garfunkel & Oates'); + } + }, + 'tableize': function(topic) { + var i, words, _i, _len, _ref, _results; + words = cases.ClassNameToTableName; + _ref = Object.keys(words); + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + _results.push(assert.equal(topic.tableize(i), words[i])); + } + return _results; + }, + 'classify': { + 'underscore': function(topic) { + var i, words, _i, _j, _len, _len2, _ref, _ref2, _results; + words = cases.ClassNameToTableName; + _ref = Object.keys(words); + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + i = _ref[_i]; + assert.equal(topic.classify(words[i]), i); + } + _ref2 = Object.keys(words); + _results = []; + for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) { + i = _ref2[_j]; + _results.push(assert.equal(topic.classify('table_prefix.' + words[i]), i)); + } + return _results; + }, + 'normal': function(topic) { + topic.inflections.irregular('octopus', 'octopi'); + return assert.equal(topic.classify('octopi'), 'Octopus'); + } + } + } + })["export"](module); + +}).call(this); diff --git a/node_modules/i/test/utils/array-test.js b/node_modules/i/test/utils/array-test.js new file mode 100644 index 0000000..95ba2bc --- /dev/null +++ b/node_modules/i/test/utils/array-test.js @@ -0,0 +1,39 @@ +(function() { + var assert, vows, util; + + vows = require('vows'); + + assert = require('assert'); + + util = require('../../lib/util'); + + vows.describe('Module core extension Array').addBatch({ + 'Testing del': { + topic: ['a', 'b', 'c'], + 'element exists': { + 'first element': function(topic) { + return assert.deepEqual(util.array.del(topic, 'a'), ['b', 'c']); + }, + 'middle element': function(topic) { + return assert.deepEqual(util.array.del(topic, 'b'), ['a', 'c']); + }, + 'last element': function(topic) { + return assert.deepEqual(util.array.del(topic, 'c'), ['a', 'b']); + } + }, + 'element does not exist': function(topic) { + return assert.deepEqual(util.array.del(topic, 'd'), ['a', 'b', 'c']); + } + }, + 'Testing utils': { + topic: ['a', 'b', 'c'], + 'first': function(topic) { + return assert.equal(util.array.first(topic), 'a'); + }, + 'last': function(topic) { + return assert.equal(util.array.last(topic), 'c'); + } + } + })["export"](module); + +}).call(this); diff --git a/node_modules/i/test/utils/string-test.js b/node_modules/i/test/utils/string-test.js new file mode 100644 index 0000000..e932233 --- /dev/null +++ b/node_modules/i/test/utils/string-test.js @@ -0,0 +1,88 @@ +(function() { + var assert, vows, util; + + vows = require('vows'); + + assert = require('assert'); + + util = require('../../lib/util'); + + vows.describe('Module core extension String').addBatch({ + 'Testing value': { + topic: 'bullet', + 'join the keys': function(topic) { + return assert.equal(util.string.value(topic), 'bullet'); + } + }, + 'Testing gsub': { + topic: 'bullet', + 'when no args': function(topic) { + return assert.equal(util.string.gsub(topic), 'bullet'); + }, + 'when only 1 arg': function(topic) { + return assert.equal(util.string.gsub(topic, /./), 'bullet'); + }, + 'when given proper args': function(topic) { + return assert.equal(util.string.gsub(topic, /[aeiou]/, '*'), 'b*ll*t'); + }, + 'when replacement is a function': { + 'with many groups': function(topic) { + var str; + str = util.string.gsub(topic, /([aeiou])(.)/, function($) { + return "<" + $[1] + ">" + $[2]; + }); + return assert.equal(str, 'b<u>ll<e>t'); + }, + 'with no groups': function(topic) { + var str; + str = util.string.gsub(topic, /[aeiou]/, function($) { + return "<" + $[1] + ">"; + }); + return assert.equal(str, 'b<u>ll<e>t'); + } + }, + 'when replacement is special': { + 'with many groups': function(topic) { + return assert.equal(util.string.gsub(topic, /([aeiou])(.)/, '<$1>$2'), 'b<u>ll<e>t'); + }, + 'with no groups': function(topic) { + return assert.equal(util.string.gsub(topic, /[aeiou]/, '<$1>'), 'b<u>ll<e>t'); + } + } + }, + 'Testing capitalize': { + topic: 'employee salary', + 'normal': function(topic) { + return assert.equal(util.string.capitalize(topic), 'Employee Salary'); + } + }, + 'Testing upcase': { + topic: 'bullet', + 'only first letter should be upcase': function(topic) { + return assert.equal(util.string.upcase(topic), 'Bullet'); + }, + 'letter after underscore': function(topic) { + return assert.equal(util.string.upcase('bullet_record'), 'Bullet_Record'); + }, + 'letter after slash': function(topic) { + return assert.equal(util.string.upcase('bullet_record/errors'), 'Bullet_Record/Errors'); + }, + 'no letter after space': function(topic) { + return assert.equal(util.string.upcase('employee salary'), 'Employee salary'); + } + }, + 'Testing downcase': { + topic: 'BULLET', + 'only first letter should be downcase': function(topic) { + return assert.equal(util.string.downcase(topic), 'bULLET'); + }, + 'letter after underscore': function(topic) { + return assert.equal(util.string.downcase('BULLET_RECORD'), 'bULLET_rECORD'); + }, + 'letter after slash': function(topic) { + return assert.equal(util.string.downcase('BULLET_RECORD/ERRORS'), 'bULLET_rECORD/eRRORS'); + } + } + })["export"](module); + +}).call(this); diff --git a/node_modules/inflight/LICENSE b/node_modules/inflight/LICENSE new file mode 100644 index 0000000..05eeeb8 --- /dev/null +++ b/node_modules/inflight/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/inflight/README.md b/node_modules/inflight/README.md new file mode 100644 index 0000000..6dc8929 --- /dev/null +++ b/node_modules/inflight/README.md @@ -0,0 +1,37 @@ +# inflight + +Add callbacks to requests in flight to avoid async duplication + +## USAGE + +```javascript +var inflight = require('inflight') + +// some request that does some stuff +function req(key, callback) { + // key is any random string. like a url or filename or whatever. + // + // will return either a falsey value, indicating that the + // request for this key is already in flight, or a new callback + // which when called will call all callbacks passed to inflightk + // with the same key + callback = inflight(key, callback) + + // If we got a falsey value back, then there's already a req going + if (!callback) return + + // this is where you'd fetch the url or whatever + // callback is also once()-ified, so it can safely be assigned + // to multiple events etc. First call wins. + setTimeout(function() { + callback(null, key) + }, 100) +} + +// only assigns a single setTimeout +// when it dings, all cbs get called +req('foo', cb1) +req('foo', cb2) +req('foo', cb3) +req('foo', cb4) +``` diff --git a/node_modules/inflight/inflight.js b/node_modules/inflight/inflight.js new file mode 100644 index 0000000..48202b3 --- /dev/null +++ b/node_modules/inflight/inflight.js @@ -0,0 +1,54 @@ +var wrappy = require('wrappy') +var reqs = Object.create(null) +var once = require('once') + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + } + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} diff --git a/node_modules/inflight/package.json b/node_modules/inflight/package.json new file mode 100644 index 0000000..9dc456f --- /dev/null +++ b/node_modules/inflight/package.json @@ -0,0 +1,58 @@ +{ + "_from": "inflight@^1.0.4", + "_id": "inflight@1.0.6", + "_inBundle": false, + "_integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "_location": "/inflight", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "inflight@^1.0.4", + "name": "inflight", + "escapedName": "inflight", + "rawSpec": "^1.0.4", + "saveSpec": null, + "fetchSpec": "^1.0.4" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "_shasum": "49bd6331d7d02d0c09bc910a1075ba8165b56df9", + "_spec": "inflight@^1.0.4", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/glob", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/inflight/issues" + }, + "bundleDependencies": false, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + }, + "deprecated": false, + "description": "Add callbacks to requests in flight to avoid async duplication", + "devDependencies": { + "tap": "^7.1.2" + }, + "files": [ + "inflight.js" + ], + "homepage": "https://github.com/isaacs/inflight", + "license": "ISC", + "main": "inflight.js", + "name": "inflight", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/inflight.git" + }, + "scripts": { + "test": "tap test.js --100" + }, + "version": "1.0.6" +} diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/node_modules/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..f71f2d9 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..86bbb3d --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..b7fab74 --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,61 @@ +{ + "_from": "inherits@2", + "_id": "inherits@2.0.4", + "_inBundle": false, + "_integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "_location": "/inherits", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "inherits@2", + "name": "inherits", + "escapedName": "inherits", + "rawSpec": "2", + "saveSpec": null, + "fetchSpec": "2" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "_shasum": "0fa2c64f932917c3433a0ded55363aae37416b7c", + "_spec": "inherits@2", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/glob", + "browser": "./inherits_browser.js", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ], + "homepage": "https://github.com/isaacs/inherits#readme", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "license": "ISC", + "main": "./inherits.js", + "name": "inherits", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "scripts": { + "test": "tap" + }, + "version": "2.0.4" +} diff --git a/node_modules/is-interactive/index.d.ts b/node_modules/is-interactive/index.d.ts new file mode 100644 index 0000000..5984dc6 --- /dev/null +++ b/node_modules/is-interactive/index.d.ts @@ -0,0 +1,31 @@ +/// <reference types="node"/> + +declare namespace isInteractive { + interface Options { + /** + The stream to check. + + @default process.stdout + */ + readonly stream?: NodeJS.WritableStream; + } +} + +/** +Check if stdout or stderr is [interactive](https://unix.stackexchange.com/a/43389/7678). + +It checks that the stream is [TTY](https://jameshfisher.com/2017/12/09/what-is-a-tty/), not a dumb terminal, and not running in a CI. + +This can be useful to decide whether to present interactive UI or animations in the terminal. + +@example +``` +import isInteractive = require('is-interactive'); + +isInteractive(); +//=> true +``` +*/ +declare function isInteractive(options?: isInteractive.Options): boolean; + +export = isInteractive; diff --git a/node_modules/is-interactive/index.js b/node_modules/is-interactive/index.js new file mode 100644 index 0000000..99ff823 --- /dev/null +++ b/node_modules/is-interactive/index.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = ({stream = process.stdout} = {}) => { + return Boolean( + stream && stream.isTTY && + process.env.TERM !== 'dumb' && + !('CI' in process.env) + ); +}; diff --git a/node_modules/is-interactive/license b/node_modules/is-interactive/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/is-interactive/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/is-interactive/package.json b/node_modules/is-interactive/package.json new file mode 100644 index 0000000..fa9bbbb --- /dev/null +++ b/node_modules/is-interactive/package.json @@ -0,0 +1,70 @@ +{ + "_from": "is-interactive@^1.0.0", + "_id": "is-interactive@1.0.0", + "_inBundle": false, + "_integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", + "_location": "/is-interactive", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-interactive@^1.0.0", + "name": "is-interactive", + "escapedName": "is-interactive", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/ora" + ], + "_resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "_shasum": "cea6e6ae5c870a7b0a0004070b7b587e0252912e", + "_spec": "is-interactive@^1.0.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/ora", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/is-interactive/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Check if stdout or stderr is interactive", + "devDependencies": { + "@types/node": "^12.0.12", + "ava": "^2.1.0", + "tsd": "^0.7.3", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/is-interactive#readme", + "keywords": [ + "interactive", + "stdout", + "stderr", + "detect", + "is", + "terminal", + "shell", + "tty" + ], + "license": "MIT", + "name": "is-interactive", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/is-interactive.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "1.0.0" +} diff --git a/node_modules/is-interactive/readme.md b/node_modules/is-interactive/readme.md new file mode 100644 index 0000000..49a8598 --- /dev/null +++ b/node_modules/is-interactive/readme.md @@ -0,0 +1,51 @@ +# is-interactive [![Build Status](https://travis-ci.com/sindresorhus/is-interactive.svg?branch=master)](https://travis-ci.com/sindresorhus/is-interactive) + +> Check if stdout or stderr is [interactive](https://unix.stackexchange.com/a/43389/7678) + +It checks that the stream is [TTY](https://jameshfisher.com/2017/12/09/what-is-a-tty/), not a dumb terminal, and not running in a CI. + +This can be useful to decide whether to present interactive UI or animations in the terminal. + + +## Install + +``` +$ npm install is-interactive +``` + + +## Usage + +```js +const isInteractive = require('is-interactive'); + +isInteractive(); +//=> true +``` + + +## API + +### isInteractive(options?) + +#### options + +Type: `object` + +##### stream + +Type: [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable)<br> +Default: [`process.stdout`](https://nodejs.org/api/process.html#process_process_stdout) + +The stream to check. + + +## FAQ + +#### Why are you not using [`ci-info`](https://github.com/watson/ci-info) for the CI check? + +It's silly to have to detect individual CIs. They should identify themselves with the `CI` environment variable, and most do just that. A manually maintained list of detections will easily get out of date. And if a package using `ci-info` doesn't update to the latest version all the time, they will not support certain CIs. It also creates unpredictability as you might assume a CI is not supported and then suddenly it gets supported and you didn't account for that. In addition, some of the manual detections are loose and might cause false-positives which could create hard-to-debug bugs. + +#### Why does this even exist? It's just a few lines. + +It's not about the number of lines, but rather discoverability and documentation. A lot of people wouldn't even know they need this. Feel free to copy-paste the code if you don't want the dependency. You might also want to read [this blog post](https://blog.sindresorhus.com/small-focused-modules-9238d977a92a). diff --git a/node_modules/isstream/.jshintrc b/node_modules/isstream/.jshintrc new file mode 100644 index 0000000..c8ef3ca --- /dev/null +++ b/node_modules/isstream/.jshintrc @@ -0,0 +1,59 @@ +{ + "predef": [ ] + , "bitwise": false + , "camelcase": false + , "curly": false + , "eqeqeq": false + , "forin": false + , "immed": false + , "latedef": false + , "noarg": true + , "noempty": true + , "nonew": true + , "plusplus": false + , "quotmark": true + , "regexp": false + , "undef": true + , "unused": true + , "strict": false + , "trailing": true + , "maxlen": 120 + , "asi": true + , "boss": true + , "debug": true + , "eqnull": true + , "esnext": true + , "evil": true + , "expr": true + , "funcscope": false + , "globalstrict": false + , "iterator": false + , "lastsemic": true + , "laxbreak": true + , "laxcomma": true + , "loopfunc": true + , "multistr": false + , "onecase": false + , "proto": false + , "regexdash": false + , "scripturl": true + , "smarttabs": false + , "shadow": false + , "sub": true + , "supernew": false + , "validthis": true + , "browser": true + , "couch": false + , "devel": false + , "dojo": false + , "mootools": false + , "node": true + , "nonstandard": true + , "prototypejs": false + , "rhino": false + , "worker": true + , "wsh": false + , "nomen": false + , "onevar": false + , "passfail": false +}
\ No newline at end of file diff --git a/node_modules/isstream/.npmignore b/node_modules/isstream/.npmignore new file mode 100644 index 0000000..aa1ec1e --- /dev/null +++ b/node_modules/isstream/.npmignore @@ -0,0 +1 @@ +*.tgz diff --git a/node_modules/isstream/.travis.yml b/node_modules/isstream/.travis.yml new file mode 100644 index 0000000..1fec2ab --- /dev/null +++ b/node_modules/isstream/.travis.yml @@ -0,0 +1,12 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" +branches: + only: + - master +notifications: + email: + - rod@vagg.org +script: npm test diff --git a/node_modules/isstream/LICENSE.md b/node_modules/isstream/LICENSE.md new file mode 100644 index 0000000..43f7153 --- /dev/null +++ b/node_modules/isstream/LICENSE.md @@ -0,0 +1,11 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2015 Rod Vagg +--------------------------- + +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/isstream/README.md b/node_modules/isstream/README.md new file mode 100644 index 0000000..06770e8 --- /dev/null +++ b/node_modules/isstream/README.md @@ -0,0 +1,66 @@ +# isStream + +[![Build Status](https://secure.travis-ci.org/rvagg/isstream.png)](http://travis-ci.org/rvagg/isstream) + +**Test if an object is a `Stream`** + +[![NPM](https://nodei.co/npm/isstream.svg)](https://nodei.co/npm/isstream/) + +The missing `Stream.isStream(obj)`: determine if an object is standard Node.js `Stream`. Works for Node-core `Stream` objects (for 0.8, 0.10, 0.11, and in theory, older and newer versions) and all versions of **[readable-stream](https://github.com/isaacs/readable-stream)**. + +## Usage: + +```js +var isStream = require('isstream') +var Stream = require('stream') + +isStream(new Stream()) // true + +isStream({}) // false + +isStream(new Stream.Readable()) // true +isStream(new Stream.Writable()) // true +isStream(new Stream.Duplex()) // true +isStream(new Stream.Transform()) // true +isStream(new Stream.PassThrough()) // true +``` + +## But wait! There's more! + +You can also test for `isReadable(obj)`, `isWritable(obj)` and `isDuplex(obj)` to test for implementations of Streams2 (and Streams3) base classes. + +```js +var isReadable = require('isstream').isReadable +var isWritable = require('isstream').isWritable +var isDuplex = require('isstream').isDuplex +var Stream = require('stream') + +isReadable(new Stream()) // false +isWritable(new Stream()) // false +isDuplex(new Stream()) // false + +isReadable(new Stream.Readable()) // true +isReadable(new Stream.Writable()) // false +isReadable(new Stream.Duplex()) // true +isReadable(new Stream.Transform()) // true +isReadable(new Stream.PassThrough()) // true + +isWritable(new Stream.Readable()) // false +isWritable(new Stream.Writable()) // true +isWritable(new Stream.Duplex()) // true +isWritable(new Stream.Transform()) // true +isWritable(new Stream.PassThrough()) // true + +isDuplex(new Stream.Readable()) // false +isDuplex(new Stream.Writable()) // false +isDuplex(new Stream.Duplex()) // true +isDuplex(new Stream.Transform()) // true +isDuplex(new Stream.PassThrough()) // true +``` + +*Reminder: when implementing your own streams, please [use **readable-stream** rather than core streams](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).* + + +## License + +**isStream** is Copyright (c) 2015 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. diff --git a/node_modules/isstream/isstream.js b/node_modules/isstream/isstream.js new file mode 100644 index 0000000..a1d104a --- /dev/null +++ b/node_modules/isstream/isstream.js @@ -0,0 +1,27 @@ +var stream = require('stream') + + +function isStream (obj) { + return obj instanceof stream.Stream +} + + +function isReadable (obj) { + return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' +} + + +function isWritable (obj) { + return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' +} + + +function isDuplex (obj) { + return isReadable(obj) && isWritable(obj) +} + + +module.exports = isStream +module.exports.isReadable = isReadable +module.exports.isWritable = isWritable +module.exports.isDuplex = isDuplex diff --git a/node_modules/isstream/package.json b/node_modules/isstream/package.json new file mode 100644 index 0000000..415a023 --- /dev/null +++ b/node_modules/isstream/package.json @@ -0,0 +1,61 @@ +{ + "_from": "isstream@0.1.x", + "_id": "isstream@0.1.2", + "_inBundle": false, + "_integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "_location": "/isstream", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "isstream@0.1.x", + "name": "isstream", + "escapedName": "isstream", + "rawSpec": "0.1.x", + "saveSpec": null, + "fetchSpec": "0.1.x" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "_shasum": "47e63f7af55afa6f92e1500e690eb8b8529c099a", + "_spec": "isstream@0.1.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/winston", + "author": { + "name": "Rod Vagg", + "email": "rod@vagg.org" + }, + "bugs": { + "url": "https://github.com/rvagg/isstream/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Determine if an object is a Stream", + "devDependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x", + "tape": "~2.12.3" + }, + "homepage": "https://github.com/rvagg/isstream", + "keywords": [ + "stream", + "type", + "streams", + "readable-stream", + "hippo" + ], + "license": "MIT", + "main": "isstream.js", + "name": "isstream", + "repository": { + "type": "git", + "url": "git+https://github.com/rvagg/isstream.git" + }, + "scripts": { + "test": "tar --xform 's/^package/readable-stream-1.0/' -zxf readable-stream-1.0.*.tgz && tar --xform 's/^package/readable-stream-1.1/' -zxf readable-stream-1.1.*.tgz && node test.js; rm -rf readable-stream-1.?/" + }, + "version": "0.1.2" +} diff --git a/node_modules/isstream/test.js b/node_modules/isstream/test.js new file mode 100644 index 0000000..8c950c5 --- /dev/null +++ b/node_modules/isstream/test.js @@ -0,0 +1,168 @@ +var tape = require('tape') + , EE = require('events').EventEmitter + , util = require('util') + + + , isStream = require('./') + , isReadable = require('./').isReadable + , isWritable = require('./').isWritable + , isDuplex = require('./').isDuplex + + , CoreStreams = require('stream') + , ReadableStream10 = require('./readable-stream-1.0/') + , ReadableStream11 = require('./readable-stream-1.1/') + + +function test (pass, type, stream) { + tape('isStream(' + type + ')', function (t) { + t.plan(1) + t.ok(pass === isStream(stream), type) + }) +} + + +function testReadable (pass, type, stream) { + tape('isReadable(' + type + ')', function (t) { + t.plan(1) + t.ok(pass === isReadable(stream), type) + }) +} + + +function testWritable (pass, type, stream) { + tape('isWritable(' + type + ')', function (t) { + t.plan(1) + t.ok(pass === isWritable(stream), type) + }) +} + + +function testDuplex (pass, type, stream) { + tape('isDuplex(' + type + ')', function (t) { + t.plan(1) + t.ok(pass === isDuplex(stream), type) + }) +} + + +[ undefined, null, '', true, false, 0, 1, 1.0, 'string', {}, function foo () {} ].forEach(function (o) { + test(false, 'non-stream / primitive: ' + (JSON.stringify(o) || (o && o.toString()) || o), o) +}) + + +test(false, 'fake stream obj', { pipe: function () {} }) + + +;(function () { + + // looks like a stream! + + function Stream () { + EE.call(this) + } + util.inherits(Stream, EE) + Stream.prototype.pipe = function () {} + Stream.Stream = Stream + + test(false, 'fake stream "new Stream()"', new Stream()) + +}()) + + +test(true, 'CoreStreams.Stream', new (CoreStreams.Stream)()) +test(true, 'CoreStreams.Readable', new (CoreStreams.Readable)()) +test(true, 'CoreStreams.Writable', new (CoreStreams.Writable)()) +test(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)()) +test(true, 'CoreStreams.Transform', new (CoreStreams.Transform)()) +test(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)()) + +test(true, 'ReadableStream10.Readable', new (ReadableStream10.Readable)()) +test(true, 'ReadableStream10.Writable', new (ReadableStream10.Writable)()) +test(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)()) +test(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)()) +test(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)()) + +test(true, 'ReadableStream11.Readable', new (ReadableStream11.Readable)()) +test(true, 'ReadableStream11.Writable', new (ReadableStream11.Writable)()) +test(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)()) +test(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)()) +test(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)()) + + +testReadable(false, 'CoreStreams.Stream', new (CoreStreams.Stream)()) +testReadable(true, 'CoreStreams.Readable', new (CoreStreams.Readable)()) +testReadable(false, 'CoreStreams.Writable', new (CoreStreams.Writable)()) +testReadable(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)()) +testReadable(true, 'CoreStreams.Transform', new (CoreStreams.Transform)()) +testReadable(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)()) + +testReadable(true, 'ReadableStream10.Readable', new (ReadableStream10.Readable)()) +testReadable(false, 'ReadableStream10.Writable', new (ReadableStream10.Writable)()) +testReadable(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)()) +testReadable(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)()) +testReadable(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)()) + +testReadable(true, 'ReadableStream11.Readable', new (ReadableStream11.Readable)()) +testReadable(false, 'ReadableStream11.Writable', new (ReadableStream11.Writable)()) +testReadable(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)()) +testReadable(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)()) +testReadable(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)()) + + +testWritable(false, 'CoreStreams.Stream', new (CoreStreams.Stream)()) +testWritable(false, 'CoreStreams.Readable', new (CoreStreams.Readable)()) +testWritable(true, 'CoreStreams.Writable', new (CoreStreams.Writable)()) +testWritable(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)()) +testWritable(true, 'CoreStreams.Transform', new (CoreStreams.Transform)()) +testWritable(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)()) + +testWritable(false, 'ReadableStream10.Readable', new (ReadableStream10.Readable)()) +testWritable(true, 'ReadableStream10.Writable', new (ReadableStream10.Writable)()) +testWritable(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)()) +testWritable(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)()) +testWritable(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)()) + +testWritable(false, 'ReadableStream11.Readable', new (ReadableStream11.Readable)()) +testWritable(true, 'ReadableStream11.Writable', new (ReadableStream11.Writable)()) +testWritable(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)()) +testWritable(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)()) +testWritable(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)()) + + +testDuplex(false, 'CoreStreams.Stream', new (CoreStreams.Stream)()) +testDuplex(false, 'CoreStreams.Readable', new (CoreStreams.Readable)()) +testDuplex(false, 'CoreStreams.Writable', new (CoreStreams.Writable)()) +testDuplex(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)()) +testDuplex(true, 'CoreStreams.Transform', new (CoreStreams.Transform)()) +testDuplex(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)()) + +testDuplex(false, 'ReadableStream10.Readable', new (ReadableStream10.Readable)()) +testDuplex(false, 'ReadableStream10.Writable', new (ReadableStream10.Writable)()) +testDuplex(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)()) +testDuplex(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)()) +testDuplex(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)()) + +testDuplex(false, 'ReadableStream11.Readable', new (ReadableStream11.Readable)()) +testDuplex(false, 'ReadableStream11.Writable', new (ReadableStream11.Writable)()) +testDuplex(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)()) +testDuplex(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)()) +testDuplex(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)()) + + +;[ CoreStreams, ReadableStream10, ReadableStream11 ].forEach(function (p) { + [ 'Stream', 'Readable', 'Writable', 'Duplex', 'Transform', 'PassThrough' ].forEach(function (k) { + if (!p[k]) + return + + function SubStream () { + p[k].call(this) + } + util.inherits(SubStream, p[k]) + + test(true, 'Stream subclass: ' + p.name + '.' + k, new SubStream()) + + }) +}) + + + diff --git a/node_modules/log-symbols/browser.js b/node_modules/log-symbols/browser.js new file mode 100644 index 0000000..a66f8ec --- /dev/null +++ b/node_modules/log-symbols/browser.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = { + info: 'ℹ️', + success: '✅', + warning: '⚠️', + error: '❌️' +}; diff --git a/node_modules/log-symbols/index.d.ts b/node_modules/log-symbols/index.d.ts new file mode 100644 index 0000000..4d3b7d1 --- /dev/null +++ b/node_modules/log-symbols/index.d.ts @@ -0,0 +1,25 @@ +/** +Colored symbols for various log levels. + +Includes fallbacks for Windows CMD which only supports a [limited character set](https://en.wikipedia.org/wiki/Code_page_437). + +@example +``` +import logSymbols = require('log-symbols'); + +console.log(logSymbols.success, 'Finished successfully!'); +// On good OSes: ✔ Finished successfully! +// On Windows: √ Finished successfully! +``` +*/ +declare const logSymbols: { + readonly info: string; + + readonly success: string; + + readonly warning: string; + + readonly error: string; +}; + +export = logSymbols; diff --git a/node_modules/log-symbols/index.js b/node_modules/log-symbols/index.js new file mode 100644 index 0000000..247bb59 --- /dev/null +++ b/node_modules/log-symbols/index.js @@ -0,0 +1,20 @@ +'use strict'; +const chalk = require('chalk'); + +const isSupported = process.platform !== 'win32' || process.env.CI || process.env.TERM === 'xterm-256color'; + +const main = { + info: chalk.blue('ℹ'), + success: chalk.green('✔'), + warning: chalk.yellow('⚠'), + error: chalk.red('✖') +}; + +const fallbacks = { + info: chalk.blue('i'), + success: chalk.green('√'), + warning: chalk.yellow('‼'), + error: chalk.red('×') +}; + +module.exports = isSupported ? main : fallbacks; diff --git a/node_modules/log-symbols/license b/node_modules/log-symbols/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/log-symbols/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://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. diff --git a/node_modules/log-symbols/package.json b/node_modules/log-symbols/package.json new file mode 100644 index 0000000..c5fd74b --- /dev/null +++ b/node_modules/log-symbols/package.json @@ -0,0 +1,82 @@ +{ + "_from": "log-symbols@^4.0.0", + "_id": "log-symbols@4.0.0", + "_inBundle": false, + "_integrity": "sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA==", + "_location": "/log-symbols", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "log-symbols@^4.0.0", + "name": "log-symbols", + "escapedName": "log-symbols", + "rawSpec": "^4.0.0", + "saveSpec": null, + "fetchSpec": "^4.0.0" + }, + "_requiredBy": [ + "/ora" + ], + "_resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.0.0.tgz", + "_shasum": "69b3cc46d20f448eccdb75ea1fa733d9e821c920", + "_spec": "log-symbols@^4.0.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/ora", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "browser": "browser.js", + "bugs": { + "url": "https://github.com/sindresorhus/log-symbols/issues" + }, + "bundleDependencies": false, + "dependencies": { + "chalk": "^4.0.0" + }, + "deprecated": false, + "description": "Colored symbols for various log levels. Example: `✔︎ Success`", + "devDependencies": { + "ava": "^3.7.1", + "strip-ansi": "^6.0.0", + "tsd": "^0.11.0", + "xo": "^0.30.0" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.js", + "index.d.ts", + "browser.js" + ], + "homepage": "https://github.com/sindresorhus/log-symbols#readme", + "keywords": [ + "unicode", + "cli", + "cmd", + "command-line", + "characters", + "symbol", + "symbols", + "figure", + "figures", + "fallback", + "windows", + "log", + "logging", + "terminal", + "stdout" + ], + "license": "MIT", + "name": "log-symbols", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/log-symbols.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "4.0.0" +} diff --git a/node_modules/log-symbols/readme.md b/node_modules/log-symbols/readme.md new file mode 100644 index 0000000..9c34cc8 --- /dev/null +++ b/node_modules/log-symbols/readme.md @@ -0,0 +1,51 @@ +# log-symbols [![Build Status](https://travis-ci.com/sindresorhus/log-symbols.svg?branch=master)](https://travis-ci.com/sindresorhus/log-symbols) + +<img src="screenshot.png" width="226" height="192" align="right"> + +> Colored symbols for various log levels + +Includes fallbacks for Windows CMD which only supports a [limited character set](https://en.wikipedia.org/wiki/Code_page_437). + +## Install + +``` +$ npm install log-symbols +``` + +## Usage + +```js +const logSymbols = require('log-symbols'); + +console.log(logSymbols.success, 'Finished successfully!'); +// On good OSes: ✔ Finished successfully! +// On Windows: √ Finished successfully! +``` + +## API + +### logSymbols + +#### info +#### success +#### warning +#### error + +## Related + +- [figures](https://github.com/sindresorhus/figures) - Unicode symbols with Windows CMD fallbacks +- [py-log-symbols](https://github.com/ManrajGrover/py-log-symbols) - Python port +- [log-symbols](https://github.com/palash25/log-symbols) - Ruby port +- [guumaster/logsymbols](https://github.com/guumaster/logsymbols) - Golang port + +--- + +<div align="center"> + <b> + <a href="https://tidelift.com/subscription/pkg/npm-log-symbols?utm_source=npm-log-symbols&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> + </b> + <br> + <sub> + Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. + </sub> +</div> diff --git a/node_modules/mimic-fn/index.d.ts b/node_modules/mimic-fn/index.d.ts new file mode 100644 index 0000000..b4047d5 --- /dev/null +++ b/node_modules/mimic-fn/index.d.ts @@ -0,0 +1,54 @@ +declare const mimicFn: { + /** + Make a function mimic another one. It will copy over the properties `name`, `length`, `displayName`, and any custom properties you may have set. + + @param to - Mimicking function. + @param from - Function to mimic. + @returns The modified `to` function. + + @example + ``` + import mimicFn = require('mimic-fn'); + + function foo() {} + foo.unicorn = '🦄'; + + function wrapper() { + return foo(); + } + + console.log(wrapper.name); + //=> 'wrapper' + + mimicFn(wrapper, foo); + + console.log(wrapper.name); + //=> 'foo' + + console.log(wrapper.unicorn); + //=> '🦄' + ``` + */ + < + ArgumentsType extends unknown[], + ReturnType, + FunctionType extends (...arguments: ArgumentsType) => ReturnType + >( + to: (...arguments: ArgumentsType) => ReturnType, + from: FunctionType + ): FunctionType; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function mimicFn< + // ArgumentsType extends unknown[], + // ReturnType, + // FunctionType extends (...arguments: ArgumentsType) => ReturnType + // >( + // to: (...arguments: ArgumentsType) => ReturnType, + // from: FunctionType + // ): FunctionType; + // export = mimicFn; + default: typeof mimicFn; +}; + +export = mimicFn; diff --git a/node_modules/mimic-fn/index.js b/node_modules/mimic-fn/index.js new file mode 100644 index 0000000..1a59705 --- /dev/null +++ b/node_modules/mimic-fn/index.js @@ -0,0 +1,13 @@ +'use strict'; + +const mimicFn = (to, from) => { + for (const prop of Reflect.ownKeys(from)) { + Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop)); + } + + return to; +}; + +module.exports = mimicFn; +// TODO: Remove this for the next major release +module.exports.default = mimicFn; diff --git a/node_modules/mimic-fn/license b/node_modules/mimic-fn/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/mimic-fn/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mimic-fn/package.json b/node_modules/mimic-fn/package.json new file mode 100644 index 0000000..eca5fba --- /dev/null +++ b/node_modules/mimic-fn/package.json @@ -0,0 +1,74 @@ +{ + "_from": "mimic-fn@^2.1.0", + "_id": "mimic-fn@2.1.0", + "_inBundle": false, + "_integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "_location": "/mimic-fn", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "mimic-fn@^2.1.0", + "name": "mimic-fn", + "escapedName": "mimic-fn", + "rawSpec": "^2.1.0", + "saveSpec": null, + "fetchSpec": "^2.1.0" + }, + "_requiredBy": [ + "/onetime" + ], + "_resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "_shasum": "7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b", + "_spec": "mimic-fn@^2.1.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/onetime", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/mimic-fn/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Make a function mimic another one", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/mimic-fn#readme", + "keywords": [ + "function", + "mimic", + "imitate", + "rename", + "copy", + "inherit", + "properties", + "name", + "func", + "fn", + "set", + "infer", + "change" + ], + "license": "MIT", + "name": "mimic-fn", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/mimic-fn.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.1.0" +} diff --git a/node_modules/mimic-fn/readme.md b/node_modules/mimic-fn/readme.md new file mode 100644 index 0000000..0ef8a13 --- /dev/null +++ b/node_modules/mimic-fn/readme.md @@ -0,0 +1,69 @@ +# mimic-fn [![Build Status](https://travis-ci.org/sindresorhus/mimic-fn.svg?branch=master)](https://travis-ci.org/sindresorhus/mimic-fn) + +> Make a function mimic another one + +Useful when you wrap a function in another function and like to preserve the original name and other properties. + + +## Install + +``` +$ npm install mimic-fn +``` + + +## Usage + +```js +const mimicFn = require('mimic-fn'); + +function foo() {} +foo.unicorn = '🦄'; + +function wrapper() { + return foo(); +} + +console.log(wrapper.name); +//=> 'wrapper' + +mimicFn(wrapper, foo); + +console.log(wrapper.name); +//=> 'foo' + +console.log(wrapper.unicorn); +//=> '🦄' +``` + + +## API + +It will copy over the properties `name`, `length`, `displayName`, and any custom properties you may have set. + +### mimicFn(to, from) + +Modifies the `to` function and returns it. + +#### to + +Type: `Function` + +Mimicking function. + +#### from + +Type: `Function` + +Function to mimic. + + +## Related + +- [rename-fn](https://github.com/sindresorhus/rename-fn) - Rename a function +- [keep-func-props](https://github.com/ehmicky/keep-func-props) - Wrap a function without changing its name, length and other properties + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/minimatch/LICENSE b/node_modules/minimatch/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/minimatch/README.md b/node_modules/minimatch/README.md new file mode 100644 index 0000000..ad72b81 --- /dev/null +++ b/node_modules/minimatch/README.md @@ -0,0 +1,209 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/minimatch/minimatch.js b/node_modules/minimatch/minimatch.js new file mode 100644 index 0000000..5b5f8cf --- /dev/null +++ b/node_modules/minimatch/minimatch.js @@ -0,0 +1,923 @@ +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = { sep: '/' } +try { + path = require('path') +} catch (er) {} + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } + + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:<pattern>)<type> + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] + + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) + + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} diff --git a/node_modules/minimatch/package.json b/node_modules/minimatch/package.json new file mode 100644 index 0000000..cac8ad8 --- /dev/null +++ b/node_modules/minimatch/package.json @@ -0,0 +1,63 @@ +{ + "_from": "minimatch@^3.0.4", + "_id": "minimatch@3.0.4", + "_inBundle": false, + "_integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "_location": "/minimatch", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "minimatch@^3.0.4", + "name": "minimatch", + "escapedName": "minimatch", + "rawSpec": "^3.0.4", + "saveSpec": null, + "fetchSpec": "^3.0.4" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "_shasum": "5166e286457f03306064be5497e8dbb0c3d32083", + "_spec": "minimatch@^3.0.4", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/glob", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "bugs": { + "url": "https://github.com/isaacs/minimatch/issues" + }, + "bundleDependencies": false, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "deprecated": false, + "description": "a glob matcher in javascript", + "devDependencies": { + "tap": "^10.3.2" + }, + "engines": { + "node": "*" + }, + "files": [ + "minimatch.js" + ], + "homepage": "https://github.com/isaacs/minimatch#readme", + "license": "ISC", + "main": "minimatch.js", + "name": "minimatch", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "scripts": { + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap test/*.js --cov" + }, + "version": "3.0.4" +} diff --git a/node_modules/minimist/.travis.yml b/node_modules/minimist/.travis.yml new file mode 100644 index 0000000..74c57bf --- /dev/null +++ b/node_modules/minimist/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.12" + - "iojs" +before_install: + - npm install -g npm@~1.4.6 diff --git a/node_modules/minimist/LICENSE b/node_modules/minimist/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/minimist/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +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/minimist/example/parse.js b/node_modules/minimist/example/parse.js new file mode 100644 index 0000000..f7c8d49 --- /dev/null +++ b/node_modules/minimist/example/parse.js @@ -0,0 +1,2 @@ +var argv = require('../')(process.argv.slice(2)); +console.log(argv); diff --git a/node_modules/minimist/index.js b/node_modules/minimist/index.js new file mode 100644 index 0000000..d2afe5e --- /dev/null +++ b/node_modules/minimist/index.js @@ -0,0 +1,245 @@ +module.exports = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {}, unknownFn: null }; + + if (typeof opts['unknown'] === 'function') { + flags.unknownFn = opts['unknown']; + } + + if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { + flags.allBools = true; + } else { + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function argDefined(key, arg) { + return (flags.allBools && /^--[^=]+$/.test(arg)) || + flags.strings[key] || flags.bools[key] || aliases[key]; + } + + function setArg (key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + function setKey (obj, keys, value) { + var o = obj; + for (var i = 0; i < keys.length-1; i++) { + var key = keys[i]; + if (key === '__proto__') return; + if (o[key] === undefined) o[key] = {}; + if (o[key] === Object.prototype || o[key] === Number.prototype + || o[key] === String.prototype) o[key] = {}; + if (o[key] === Array.prototype) o[key] = []; + o = o[key]; + } + + var key = keys[keys.length - 1]; + if (key === '__proto__') return; + if (o === Object.prototype || o === Number.prototype + || o === String.prototype) o = {}; + if (o === Array.prototype) o = []; + if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } + } + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + var key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, next, arg); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next, arg) + continue; + } + + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split('=')[1], arg); + broken = true; + break; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2), arg); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, args[i+1], arg); + i++; + } + else if (args[i+1] && /^(true|false)$/.test(args[i+1])) { + setArg(key, args[i+1] === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } + else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + if (opts['--']) { + argv['--'] = new Array(); + notFlags.forEach(function(key) { + argv['--'].push(key); + }); + } + else { + notFlags.forEach(function(key) { + argv._.push(key); + }); + } + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + diff --git a/node_modules/minimist/package.json b/node_modules/minimist/package.json new file mode 100644 index 0000000..60a557e --- /dev/null +++ b/node_modules/minimist/package.json @@ -0,0 +1,73 @@ +{ + "_from": "minimist@^1.2.5", + "_id": "minimist@1.2.5", + "_inBundle": false, + "_integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "_location": "/minimist", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "minimist@^1.2.5", + "name": "minimist", + "escapedName": "minimist", + "rawSpec": "^1.2.5", + "saveSpec": null, + "fetchSpec": "^1.2.5" + }, + "_requiredBy": [ + "/mkdirp" + ], + "_resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "_shasum": "67d66014b66a6a8aaa0c083c5fd58df4e4e97602", + "_spec": "minimist@^1.2.5", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/mkdirp", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bugs": { + "url": "https://github.com/substack/minimist/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "parse argument options", + "devDependencies": { + "covert": "^1.0.0", + "tap": "~0.4.0", + "tape": "^3.5.0" + }, + "homepage": "https://github.com/substack/minimist", + "keywords": [ + "argv", + "getopt", + "parser", + "optimist" + ], + "license": "MIT", + "main": "index.js", + "name": "minimist", + "repository": { + "type": "git", + "url": "git://github.com/substack/minimist.git" + }, + "scripts": { + "coverage": "covert test/*.js", + "test": "tap test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/6..latest", + "ff/5", + "firefox/latest", + "chrome/10", + "chrome/latest", + "safari/5.1", + "safari/latest", + "opera/12" + ] + }, + "version": "1.2.5" +} diff --git a/node_modules/minimist/readme.markdown b/node_modules/minimist/readme.markdown new file mode 100644 index 0000000..5fd97ab --- /dev/null +++ b/node_modules/minimist/readme.markdown @@ -0,0 +1,95 @@ +# minimist + +parse argument options + +This module is the guts of optimist's argument parser without all the +fanciful decoration. + +# example + +``` js +var argv = require('minimist')(process.argv.slice(2)); +console.log(argv); +``` + +``` +$ node example/parse.js -a beep -b boop +{ _: [], a: 'beep', b: 'boop' } +``` + +``` +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz +{ _: [ 'foo', 'bar', 'baz' ], + x: 3, + y: 4, + n: 5, + a: true, + b: true, + c: true, + beep: 'boop' } +``` + +# security + +Previous versions had a prototype pollution bug that could cause privilege +escalation in some circumstances when handling untrusted user input. + +Please use version 1.2.3 or later: https://snyk.io/vuln/SNYK-JS-MINIMIST-559764 + +# methods + +``` js +var parseArgs = require('minimist') +``` + +## var argv = parseArgs(args, opts={}) + +Return an argument object `argv` populated with the array arguments from `args`. + +`argv._` contains all the arguments that didn't have an option associated with +them. + +Numeric-looking arguments will be returned as numbers unless `opts.string` or +`opts.boolean` is set for that argument name. + +Any arguments after `'--'` will not be parsed and will end up in `argv._`. + +options can be: + +* `opts.string` - a string or array of strings argument names to always treat as +strings +* `opts.boolean` - a boolean, string or array of strings to always treat as +booleans. if `true` will treat all double hyphenated arguments without equal signs +as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) +* `opts.alias` - an object mapping string names to strings or arrays of string +argument names to use as aliases +* `opts.default` - an object mapping string argument names to default values +* `opts.stopEarly` - when true, populate `argv._` with everything after the +first non-option +* `opts['--']` - when true, populate `argv._` with everything before the `--` +and `argv['--']` with everything after the `--`. Here's an example: + + ``` + > require('./')('one two three -- four five --six'.split(' '), { '--': true }) + { _: [ 'one', 'two', 'three' ], + '--': [ 'four', 'five', '--six' ] } + ``` + + Note that with `opts['--']` set, parsing for arguments still stops after the + `--`. + +* `opts.unknown` - a function which is invoked with a command line parameter not +defined in the `opts` configuration object. If the function returns `false`, the +unknown option is not added to `argv`. + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install minimist +``` + +# license + +MIT diff --git a/node_modules/minimist/test/all_bool.js b/node_modules/minimist/test/all_bool.js new file mode 100644 index 0000000..ac83548 --- /dev/null +++ b/node_modules/minimist/test/all_bool.js @@ -0,0 +1,32 @@ +var parse = require('../'); +var test = require('tape'); + +test('flag boolean true (default all --args to boolean)', function (t) { + var argv = parse(['moo', '--honk', 'cow'], { + boolean: true + }); + + t.deepEqual(argv, { + honk: true, + _: ['moo', 'cow'] + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); + +test('flag boolean true only affects double hyphen arguments without equals signs', function (t) { + var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], { + boolean: true + }); + + t.deepEqual(argv, { + honk: true, + tacos: 'good', + p: 55, + _: ['moo', 'cow'] + }); + + t.deepEqual(typeof argv.honk, 'boolean'); + t.end(); +}); diff --git a/node_modules/minimist/test/bool.js b/node_modules/minimist/test/bool.js new file mode 100644 index 0000000..5f7dbde --- /dev/null +++ b/node_modules/minimist/test/bool.js @@ -0,0 +1,178 @@ +var parse = require('../'); +var test = require('tape'); + +test('flag boolean default false', function (t) { + var argv = parse(['moo'], { + boolean: ['t', 'verbose'], + default: { verbose: false, t: false } + }); + + t.deepEqual(argv, { + verbose: false, + t: false, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); + +}); + +test('boolean groups', function (t) { + var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { + boolean: ['x','y','z'] + }); + + t.deepEqual(argv, { + x : true, + y : false, + z : true, + _ : [ 'one', 'two', 'three' ] + }); + + t.deepEqual(typeof argv.x, 'boolean'); + t.deepEqual(typeof argv.y, 'boolean'); + t.deepEqual(typeof argv.z, 'boolean'); + t.end(); +}); +test('boolean and alias with chainable api', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + herp: { alias: 'h', boolean: true } + }; + var aliasedArgv = parse(aliased, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var propertyArgv = parse(regular, { + boolean: 'herp', + alias: { h: 'herp' } + }); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var opts = { + alias: { 'h': 'herp' }, + boolean: 'herp' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +test('boolean and alias array with options hash', function (t) { + var aliased = [ '-h', 'derp' ]; + var regular = [ '--herp', 'derp' ]; + var alt = [ '--harp', 'derp' ]; + var opts = { + alias: { 'h': ['herp', 'harp'] }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var altPropertyArgv = parse(alt, opts); + var expected = { + harp: true, + herp: true, + h: true, + '_': [ 'derp' ] + }; + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.same(altPropertyArgv, expected); + t.end(); +}); + +test('boolean and alias using explicit true', function (t) { + var aliased = [ '-h', 'true' ]; + var regular = [ '--herp', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h' + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + var expected = { + herp: true, + h: true, + '_': [ ] + }; + + t.same(aliasedArgv, expected); + t.same(propertyArgv, expected); + t.end(); +}); + +// regression, see https://github.com/substack/node-optimist/issues/71 +test('boolean and --x=true', function(t) { + var parsed = parse(['--boool', '--other=true'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'true'); + + parsed = parse(['--boool', '--other=false'], { + boolean: 'boool' + }); + + t.same(parsed.boool, true); + t.same(parsed.other, 'false'); + t.end(); +}); + +test('boolean --boool=true', function (t) { + var parsed = parse(['--boool=true'], { + default: { + boool: false + }, + boolean: ['boool'] + }); + + t.same(parsed.boool, true); + t.end(); +}); + +test('boolean --boool=false', function (t) { + var parsed = parse(['--boool=false'], { + default: { + boool: true + }, + boolean: ['boool'] + }); + + t.same(parsed.boool, false); + t.end(); +}); + +test('boolean using something similar to true', function (t) { + var opts = { boolean: 'h' }; + var result = parse(['-h', 'true.txt'], opts); + var expected = { + h: true, + '_': ['true.txt'] + }; + + t.same(result, expected); + t.end(); +});
\ No newline at end of file diff --git a/node_modules/minimist/test/dash.js b/node_modules/minimist/test/dash.js new file mode 100644 index 0000000..5a4fa5b --- /dev/null +++ b/node_modules/minimist/test/dash.js @@ -0,0 +1,31 @@ +var parse = require('../'); +var test = require('tape'); + +test('-', function (t) { + t.plan(5); + t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); + t.deepEqual(parse([ '-' ]), { _: [ '-' ] }); + t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] }); + t.deepEqual( + parse([ '-b', '-' ], { boolean: 'b' }), + { b: true, _: [ '-' ] } + ); + t.deepEqual( + parse([ '-s', '-' ], { string: 's' }), + { s: '-', _: [] } + ); +}); + +test('-a -- b', function (t) { + t.plan(3); + t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); +}); + +test('move arguments after the -- into their own `--` array', function(t) { + t.plan(1); + t.deepEqual( + parse([ '--name', 'John', 'before', '--', 'after' ], { '--': true }), + { name: 'John', _: [ 'before' ], '--': [ 'after' ] }); +}); diff --git a/node_modules/minimist/test/default_bool.js b/node_modules/minimist/test/default_bool.js new file mode 100644 index 0000000..780a311 --- /dev/null +++ b/node_modules/minimist/test/default_bool.js @@ -0,0 +1,35 @@ +var test = require('tape'); +var parse = require('../'); + +test('boolean default true', function (t) { + var argv = parse([], { + boolean: 'sometrue', + default: { sometrue: true } + }); + t.equal(argv.sometrue, true); + t.end(); +}); + +test('boolean default false', function (t) { + var argv = parse([], { + boolean: 'somefalse', + default: { somefalse: false } + }); + t.equal(argv.somefalse, false); + t.end(); +}); + +test('boolean default to null', function (t) { + var argv = parse([], { + boolean: 'maybe', + default: { maybe: null } + }); + t.equal(argv.maybe, null); + var argv = parse(['--maybe'], { + boolean: 'maybe', + default: { maybe: null } + }); + t.equal(argv.maybe, true); + t.end(); + +}) diff --git a/node_modules/minimist/test/dotted.js b/node_modules/minimist/test/dotted.js new file mode 100644 index 0000000..d8b3e85 --- /dev/null +++ b/node_modules/minimist/test/dotted.js @@ -0,0 +1,22 @@ +var parse = require('../'); +var test = require('tape'); + +test('dotted alias', function (t) { + var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 22); + t.equal(argv.aa.bb, 22); + t.end(); +}); + +test('dotted default', function (t) { + var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); + t.equal(argv.a.b, 11); + t.equal(argv.aa.bb, 11); + t.end(); +}); + +test('dotted default with no alias', function (t) { + var argv = parse('', {default: {'a.b': 11}}); + t.equal(argv.a.b, 11); + t.end(); +}); diff --git a/node_modules/minimist/test/kv_short.js b/node_modules/minimist/test/kv_short.js new file mode 100644 index 0000000..f813b30 --- /dev/null +++ b/node_modules/minimist/test/kv_short.js @@ -0,0 +1,16 @@ +var parse = require('../'); +var test = require('tape'); + +test('short -k=v' , function (t) { + t.plan(1); + + var argv = parse([ '-b=123' ]); + t.deepEqual(argv, { b: 123, _: [] }); +}); + +test('multi short -k=v' , function (t) { + t.plan(1); + + var argv = parse([ '-a=whatever', '-b=robots' ]); + t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] }); +}); diff --git a/node_modules/minimist/test/long.js b/node_modules/minimist/test/long.js new file mode 100644 index 0000000..5d3a1e0 --- /dev/null +++ b/node_modules/minimist/test/long.js @@ -0,0 +1,31 @@ +var test = require('tape'); +var parse = require('../'); + +test('long opts', function (t) { + t.deepEqual( + parse([ '--bool' ]), + { bool : true, _ : [] }, + 'long boolean' + ); + t.deepEqual( + parse([ '--pow', 'xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture sp' + ); + t.deepEqual( + parse([ '--pow=xixxle' ]), + { pow : 'xixxle', _ : [] }, + 'long capture eq' + ); + t.deepEqual( + parse([ '--host', 'localhost', '--port', '555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures sp' + ); + t.deepEqual( + parse([ '--host=localhost', '--port=555' ]), + { host : 'localhost', port : 555, _ : [] }, + 'long captures eq' + ); + t.end(); +}); diff --git a/node_modules/minimist/test/num.js b/node_modules/minimist/test/num.js new file mode 100644 index 0000000..2cc77f4 --- /dev/null +++ b/node_modules/minimist/test/num.js @@ -0,0 +1,36 @@ +var parse = require('../'); +var test = require('tape'); + +test('nums', function (t) { + var argv = parse([ + '-x', '1234', + '-y', '5.67', + '-z', '1e7', + '-w', '10f', + '--hex', '0xdeadbeef', + '789' + ]); + t.deepEqual(argv, { + x : 1234, + y : 5.67, + z : 1e7, + w : '10f', + hex : 0xdeadbeef, + _ : [ 789 ] + }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv.y, 'number'); + t.deepEqual(typeof argv.z, 'number'); + t.deepEqual(typeof argv.w, 'string'); + t.deepEqual(typeof argv.hex, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); + +test('already a number', function (t) { + var argv = parse([ '-x', 1234, 789 ]); + t.deepEqual(argv, { x : 1234, _ : [ 789 ] }); + t.deepEqual(typeof argv.x, 'number'); + t.deepEqual(typeof argv._[0], 'number'); + t.end(); +}); diff --git a/node_modules/minimist/test/parse.js b/node_modules/minimist/test/parse.js new file mode 100644 index 0000000..7b4a2a1 --- /dev/null +++ b/node_modules/minimist/test/parse.js @@ -0,0 +1,197 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse args', function (t) { + t.deepEqual( + parse([ '--no-moo' ]), + { moo : false, _ : [] }, + 'no' + ); + t.deepEqual( + parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), + { v : ['a','b','c'], _ : [] }, + 'multi' + ); + t.end(); +}); + +test('comprehensive', function (t) { + t.deepEqual( + parse([ + '--name=meowmers', 'bare', '-cats', 'woo', + '-h', 'awesome', '--multi=quux', + '--key', 'value', + '-b', '--bool', '--no-meep', '--multi=baz', + '--', '--not-a-flag', 'eek' + ]), + { + c : true, + a : true, + t : true, + s : 'woo', + h : 'awesome', + b : true, + bool : true, + key : 'value', + multi : [ 'quux', 'baz' ], + meep : false, + name : 'meowmers', + _ : [ 'bare', '--not-a-flag', 'eek' ] + } + ); + t.end(); +}); + +test('flag boolean', function (t) { + var argv = parse([ '-t', 'moo' ], { boolean: 't' }); + t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('flag boolean value', function (t) { + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { + boolean: [ 't', 'verbose' ], + default: { verbose: true } + }); + + t.deepEqual(argv, { + verbose: false, + t: true, + _: ['moo'] + }); + + t.deepEqual(typeof argv.verbose, 'boolean'); + t.deepEqual(typeof argv.t, 'boolean'); + t.end(); +}); + +test('newlines in params' , function (t) { + var args = parse([ '-s', "X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + + // reproduce in bash: + // VALUE="new + // line" + // node program.js --s="$VALUE" + args = parse([ "--s=X\nX" ]) + t.deepEqual(args, { _ : [], s : "X\nX" }); + t.end(); +}); + +test('strings' , function (t) { + var s = parse([ '-s', '0001234' ], { string: 's' }).s; + t.equal(s, '0001234'); + t.equal(typeof s, 'string'); + + var x = parse([ '-x', '56' ], { string: 'x' }).x; + t.equal(x, '56'); + t.equal(typeof x, 'string'); + t.end(); +}); + +test('stringArgs', function (t) { + var s = parse([ ' ', ' ' ], { string: '_' })._; + t.same(s.length, 2); + t.same(typeof s[0], 'string'); + t.same(s[0], ' '); + t.same(typeof s[1], 'string'); + t.same(s[1], ' '); + t.end(); +}); + +test('empty strings', function(t) { + var s = parse([ '-s' ], { string: 's' }).s; + t.equal(s, ''); + t.equal(typeof s, 'string'); + + var str = parse([ '--str' ], { string: 'str' }).str; + t.equal(str, ''); + t.equal(typeof str, 'string'); + + var letters = parse([ '-art' ], { + string: [ 'a', 't' ] + }); + + t.equal(letters.a, ''); + t.equal(letters.r, true); + t.equal(letters.t, ''); + + t.end(); +}); + + +test('string and alias', function(t) { + var x = parse([ '--str', '000123' ], { + string: 's', + alias: { s: 'str' } + }); + + t.equal(x.str, '000123'); + t.equal(typeof x.str, 'string'); + t.equal(x.s, '000123'); + t.equal(typeof x.s, 'string'); + + var y = parse([ '-s', '000123' ], { + string: 'str', + alias: { str: 's' } + }); + + t.equal(y.str, '000123'); + t.equal(typeof y.str, 'string'); + t.equal(y.s, '000123'); + t.equal(typeof y.s, 'string'); + t.end(); +}); + +test('slashBreak', function (t) { + t.same( + parse([ '-I/foo/bar/baz' ]), + { I : '/foo/bar/baz', _ : [] } + ); + t.same( + parse([ '-xyz/foo/bar/baz' ]), + { x : true, y : true, z : '/foo/bar/baz', _ : [] } + ); + t.end(); +}); + +test('alias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: 'zoom' } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.f, 11); + t.end(); +}); + +test('multiAlias', function (t) { + var argv = parse([ '-f', '11', '--zoom', '55' ], { + alias: { z: [ 'zm', 'zoom' ] } + }); + t.equal(argv.zoom, 55); + t.equal(argv.z, argv.zoom); + t.equal(argv.z, argv.zm); + t.equal(argv.f, 11); + t.end(); +}); + +test('nested dotted objects', function (t) { + var argv = parse([ + '--foo.bar', '3', '--foo.baz', '4', + '--foo.quux.quibble', '5', '--foo.quux.o_O', + '--beep.boop' + ]); + + t.same(argv.foo, { + bar : 3, + baz : 4, + quux : { + quibble : 5, + o_O : true + } + }); + t.same(argv.beep, { boop : true }); + t.end(); +}); diff --git a/node_modules/minimist/test/parse_modified.js b/node_modules/minimist/test/parse_modified.js new file mode 100644 index 0000000..ab620dc --- /dev/null +++ b/node_modules/minimist/test/parse_modified.js @@ -0,0 +1,9 @@ +var parse = require('../'); +var test = require('tape'); + +test('parse with modifier functions' , function (t) { + t.plan(1); + + var argv = parse([ '-b', '123' ], { boolean: 'b' }); + t.deepEqual(argv, { b: true, _: [123] }); +}); diff --git a/node_modules/minimist/test/proto.js b/node_modules/minimist/test/proto.js new file mode 100644 index 0000000..8649107 --- /dev/null +++ b/node_modules/minimist/test/proto.js @@ -0,0 +1,44 @@ +var parse = require('../'); +var test = require('tape'); + +test('proto pollution', function (t) { + var argv = parse(['--__proto__.x','123']); + t.equal({}.x, undefined); + t.equal(argv.__proto__.x, undefined); + t.equal(argv.x, undefined); + t.end(); +}); + +test('proto pollution (array)', function (t) { + var argv = parse(['--x','4','--x','5','--x.__proto__.z','789']); + t.equal({}.z, undefined); + t.deepEqual(argv.x, [4,5]); + t.equal(argv.x.z, undefined); + t.equal(argv.x.__proto__.z, undefined); + t.end(); +}); + +test('proto pollution (number)', function (t) { + var argv = parse(['--x','5','--x.__proto__.z','100']); + t.equal({}.z, undefined); + t.equal((4).z, undefined); + t.equal(argv.x, 5); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (string)', function (t) { + var argv = parse(['--x','abc','--x.__proto__.z','def']); + t.equal({}.z, undefined); + t.equal('...'.z, undefined); + t.equal(argv.x, 'abc'); + t.equal(argv.x.z, undefined); + t.end(); +}); + +test('proto pollution (constructor)', function (t) { + var argv = parse(['--constructor.prototype.y','123']); + t.equal({}.y, undefined); + t.equal(argv.y, undefined); + t.end(); +}); diff --git a/node_modules/minimist/test/short.js b/node_modules/minimist/test/short.js new file mode 100644 index 0000000..d513a1c --- /dev/null +++ b/node_modules/minimist/test/short.js @@ -0,0 +1,67 @@ +var parse = require('../'); +var test = require('tape'); + +test('numeric short args', function (t) { + t.plan(2); + t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] }); + t.deepEqual( + parse([ '-123', '456' ]), + { 1: true, 2: true, 3: 456, _: [] } + ); +}); + +test('short', function (t) { + t.deepEqual( + parse([ '-b' ]), + { b : true, _ : [] }, + 'short boolean' + ); + t.deepEqual( + parse([ 'foo', 'bar', 'baz' ]), + { _ : [ 'foo', 'bar', 'baz' ] }, + 'bare' + ); + t.deepEqual( + parse([ '-cats' ]), + { c : true, a : true, t : true, s : true, _ : [] }, + 'group' + ); + t.deepEqual( + parse([ '-cats', 'meow' ]), + { c : true, a : true, t : true, s : 'meow', _ : [] }, + 'short group next' + ); + t.deepEqual( + parse([ '-h', 'localhost' ]), + { h : 'localhost', _ : [] }, + 'short capture' + ); + t.deepEqual( + parse([ '-h', 'localhost', '-p', '555' ]), + { h : 'localhost', p : 555, _ : [] }, + 'short captures' + ); + t.end(); +}); + +test('mixed short bool and capture', function (t) { + t.same( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); + +test('short and long', function (t) { + t.deepEqual( + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), + { + f : true, p : 555, h : 'localhost', + _ : [ 'script.js' ] + } + ); + t.end(); +}); diff --git a/node_modules/minimist/test/stop_early.js b/node_modules/minimist/test/stop_early.js new file mode 100644 index 0000000..bdf9fbc --- /dev/null +++ b/node_modules/minimist/test/stop_early.js @@ -0,0 +1,15 @@ +var parse = require('../'); +var test = require('tape'); + +test('stops parsing on the first non-option when stopEarly is set', function (t) { + var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], { + stopEarly: true + }); + + t.deepEqual(argv, { + aaa: 'bbb', + _: ['ccc', '--ddd'] + }); + + t.end(); +}); diff --git a/node_modules/minimist/test/unknown.js b/node_modules/minimist/test/unknown.js new file mode 100644 index 0000000..462a36b --- /dev/null +++ b/node_modules/minimist/test/unknown.js @@ -0,0 +1,102 @@ +var parse = require('../'); +var test = require('tape'); + +test('boolean and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'true', '--derp', 'true' ]; + var regular = [ '--herp', 'true', '-d', 'true' ]; + var opts = { + alias: { h: 'herp' }, + boolean: 'h', + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('flag boolean true any double hyphen argument is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], { + boolean: true, + unknown: unknownFn + }); + t.same(unknown, ['--tacos=good', 'cow', '-p']); + t.same(argv, { + honk: true, + _: [] + }); + t.end(); +}); + +test('string and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'hello', '--derp', 'goodbye' ]; + var regular = [ '--herp', 'hello', '-d', 'moon' ]; + var opts = { + alias: { h: 'herp' }, + string: 'h', + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, ['--derp', '-d']); + t.end(); +}); + +test('default and alias is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '-h', 'hello' ]; + var regular = [ '--herp', 'hello' ]; + var opts = { + default: { 'h': 'bar' }, + alias: { 'h': 'herp' }, + unknown: unknownFn + }; + var aliasedArgv = parse(aliased, opts); + var propertyArgv = parse(regular, opts); + + t.same(unknown, []); + t.end(); + unknownFn(); // exercise fn for 100% coverage +}); + +test('value following -- is not unknown', function (t) { + var unknown = []; + function unknownFn(arg) { + unknown.push(arg); + return false; + } + var aliased = [ '--bad', '--', 'good', 'arg' ]; + var opts = { + '--': true, + unknown: unknownFn + }; + var argv = parse(aliased, opts); + + t.same(unknown, ['--bad']); + t.same(argv, { + '--': ['good', 'arg'], + '_': [] + }) + t.end(); +}); diff --git a/node_modules/minimist/test/whitespace.js b/node_modules/minimist/test/whitespace.js new file mode 100644 index 0000000..8a52a58 --- /dev/null +++ b/node_modules/minimist/test/whitespace.js @@ -0,0 +1,8 @@ +var parse = require('../'); +var test = require('tape'); + +test('whitespace should be whitespace' , function (t) { + t.plan(1); + var x = parse([ '-x', '\t' ]).x; + t.equal(x, '\t'); +}); diff --git a/node_modules/mkdirp/LICENSE b/node_modules/mkdirp/LICENSE new file mode 100644 index 0000000..432d1ae --- /dev/null +++ b/node_modules/mkdirp/LICENSE @@ -0,0 +1,21 @@ +Copyright 2010 James Halliday (mail@substack.net) + +This project is free software released under the MIT/X11 license: + +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/mkdirp/bin/cmd.js b/node_modules/mkdirp/bin/cmd.js new file mode 100644 index 0000000..d95de15 --- /dev/null +++ b/node_modules/mkdirp/bin/cmd.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +var mkdirp = require('../'); +var minimist = require('minimist'); +var fs = require('fs'); + +var argv = minimist(process.argv.slice(2), { + alias: { m: 'mode', h: 'help' }, + string: [ 'mode' ] +}); +if (argv.help) { + fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout); + return; +} + +var paths = argv._.slice(); +var mode = argv.mode ? parseInt(argv.mode, 8) : undefined; + +(function next () { + if (paths.length === 0) return; + var p = paths.shift(); + + if (mode === undefined) mkdirp(p, cb) + else mkdirp(p, mode, cb) + + function cb (err) { + if (err) { + console.error(err.message); + process.exit(1); + } + else next(); + } +})(); diff --git a/node_modules/mkdirp/bin/usage.txt b/node_modules/mkdirp/bin/usage.txt new file mode 100644 index 0000000..f952aa2 --- /dev/null +++ b/node_modules/mkdirp/bin/usage.txt @@ -0,0 +1,12 @@ +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + diff --git a/node_modules/mkdirp/index.js b/node_modules/mkdirp/index.js new file mode 100644 index 0000000..468d7cd --- /dev/null +++ b/node_modules/mkdirp/index.js @@ -0,0 +1,99 @@ +var path = require('path'); +var fs = require('fs'); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + if (path.dirname(p) === p) return cb(er); + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/node_modules/mkdirp/package.json b/node_modules/mkdirp/package.json new file mode 100644 index 0000000..d4908d2 --- /dev/null +++ b/node_modules/mkdirp/package.json @@ -0,0 +1,69 @@ +{ + "_from": "mkdirp@0.x.x", + "_id": "mkdirp@0.5.5", + "_inBundle": false, + "_integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "_location": "/mkdirp", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "mkdirp@0.x.x", + "name": "mkdirp", + "escapedName": "mkdirp", + "rawSpec": "0.x.x", + "saveSpec": null, + "fetchSpec": "0.x.x" + }, + "_requiredBy": [ + "/utile" + ], + "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "_shasum": "d91cefd62d1436ca0f41620e251288d420099def", + "_spec": "mkdirp@0.x.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/utile", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bin": { + "mkdirp": "bin/cmd.js" + }, + "bugs": { + "url": "https://github.com/substack/node-mkdirp/issues" + }, + "bundleDependencies": false, + "dependencies": { + "minimist": "^1.2.5" + }, + "deprecated": false, + "description": "Recursively mkdir, like `mkdir -p`", + "devDependencies": { + "mock-fs": "^3.7.0", + "tap": "^5.4.2" + }, + "files": [ + "bin", + "index.js" + ], + "homepage": "https://github.com/substack/node-mkdirp#readme", + "keywords": [ + "mkdir", + "directory" + ], + "license": "MIT", + "main": "index.js", + "name": "mkdirp", + "publishConfig": { + "tag": "legacy" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/substack/node-mkdirp.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "version": "0.5.5" +} diff --git a/node_modules/mkdirp/readme.markdown b/node_modules/mkdirp/readme.markdown new file mode 100644 index 0000000..fc314bf --- /dev/null +++ b/node_modules/mkdirp/readme.markdown @@ -0,0 +1,100 @@ +# mkdirp + +Like `mkdir -p`, but in node.js! + +[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) + +# example + +## pow.js + +```js +var mkdirp = require('mkdirp'); + +mkdirp('/tmp/foo/bar/baz', function (err) { + if (err) console.error(err) + else console.log('pow!') +}); +``` + +Output + +``` +pow! +``` + +And now /tmp/foo/bar/baz exists, huzzah! + +# methods + +```js +var mkdirp = require('mkdirp'); +``` + +## mkdirp(dir, opts, cb) + +Create a new directory and any necessary subdirectories at `dir` with octal +permission string `opts.mode`. If `opts` is a non-object, it will be treated as +the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777`. + +`cb(err, made)` fires with the error or the first directory `made` +that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and +`opts.fs.stat(path, cb)`. + +## mkdirp.sync(dir, opts) + +Synchronously create a new directory and any necessary subdirectories at `dir` +with octal permission string `opts.mode`. If `opts` is a non-object, it will be +treated as the `opts.mode`. + +If `opts.mode` isn't specified, it defaults to `0777`. + +Returns the first directory that had to be created, if any. + +You can optionally pass in an alternate `fs` implementation by passing in +`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and +`opts.fs.statSync(path)`. + +# usage + +This package also ships with a `mkdirp` command. + +``` +usage: mkdirp [DIR1,DIR2..] {OPTIONS} + + Create each supplied directory including any necessary parent directories that + don't yet exist. + + If the directory already exists, do nothing. + +OPTIONS are: + + -m, --mode If a directory needs to be created, set the mode as an octal + permission string. + +``` + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +to get the library, or + +``` +npm install -g mkdirp +``` + +to get the command. + +# license + +MIT diff --git a/node_modules/mute-stream/LICENSE b/node_modules/mute-stream/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/mute-stream/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/mute-stream/README.md b/node_modules/mute-stream/README.md new file mode 100644 index 0000000..8ab1238 --- /dev/null +++ b/node_modules/mute-stream/README.md @@ -0,0 +1,68 @@ +# mute-stream + +Bytes go in, but they don't come out (when muted). + +This is a basic pass-through stream, but when muted, the bytes are +silently dropped, rather than being passed through. + +## Usage + +```javascript +var MuteStream = require('mute-stream') + +var ms = new MuteStream(options) + +ms.pipe(process.stdout) +ms.write('foo') // writes 'foo' to stdout +ms.mute() +ms.write('bar') // does not write 'bar' +ms.unmute() +ms.write('baz') // writes 'baz' to stdout + +// can also be used to mute incoming data +var ms = new MuteStream +input.pipe(ms) + +ms.on('data', function (c) { + console.log('data: ' + c) +}) + +input.emit('data', 'foo') // logs 'foo' +ms.mute() +input.emit('data', 'bar') // does not log 'bar' +ms.unmute() +input.emit('data', 'baz') // logs 'baz' +``` + +## Options + +All options are optional. + +* `replace` Set to a string to replace each character with the + specified string when muted. (So you can show `****` instead of the + password, for example.) + +* `prompt` If you are using a replacement char, and also using a + prompt with a readline stream (as for a `Password: *****` input), + then specify what the prompt is so that backspace will work + properly. Otherwise, pressing backspace will overwrite the prompt + with the replacement character, which is weird. + +## ms.mute() + +Set `muted` to `true`. Turns `.write()` into a no-op. + +## ms.unmute() + +Set `muted` to `false` + +## ms.isTTY + +True if the pipe destination is a TTY, or if the incoming pipe source is +a TTY. + +## Other stream methods... + +The other standard readable and writable stream methods are all +available. The MuteStream object acts as a facade to its pipe source +and destination. diff --git a/node_modules/mute-stream/mute.js b/node_modules/mute-stream/mute.js new file mode 100644 index 0000000..a24fc09 --- /dev/null +++ b/node_modules/mute-stream/mute.js @@ -0,0 +1,145 @@ +var Stream = require('stream') + +module.exports = MuteStream + +// var out = new MuteStream(process.stdout) +// argument auto-pipes +function MuteStream (opts) { + Stream.apply(this) + opts = opts || {} + this.writable = this.readable = true + this.muted = false + this.on('pipe', this._onpipe) + this.replace = opts.replace + + // For readline-type situations + // This much at the start of a line being redrawn after a ctrl char + // is seen (such as backspace) won't be redrawn as the replacement + this._prompt = opts.prompt || null + this._hadControl = false +} + +MuteStream.prototype = Object.create(Stream.prototype) + +Object.defineProperty(MuteStream.prototype, 'constructor', { + value: MuteStream, + enumerable: false +}) + +MuteStream.prototype.mute = function () { + this.muted = true +} + +MuteStream.prototype.unmute = function () { + this.muted = false +} + +Object.defineProperty(MuteStream.prototype, '_onpipe', { + value: onPipe, + enumerable: false, + writable: true, + configurable: true +}) + +function onPipe (src) { + this._src = src +} + +Object.defineProperty(MuteStream.prototype, 'isTTY', { + get: getIsTTY, + set: setIsTTY, + enumerable: true, + configurable: true +}) + +function getIsTTY () { + return( (this._dest) ? this._dest.isTTY + : (this._src) ? this._src.isTTY + : false + ) +} + +// basically just get replace the getter/setter with a regular value +function setIsTTY (isTTY) { + Object.defineProperty(this, 'isTTY', { + value: isTTY, + enumerable: true, + writable: true, + configurable: true + }) +} + +Object.defineProperty(MuteStream.prototype, 'rows', { + get: function () { + return( this._dest ? this._dest.rows + : this._src ? this._src.rows + : undefined ) + }, enumerable: true, configurable: true }) + +Object.defineProperty(MuteStream.prototype, 'columns', { + get: function () { + return( this._dest ? this._dest.columns + : this._src ? this._src.columns + : undefined ) + }, enumerable: true, configurable: true }) + + +MuteStream.prototype.pipe = function (dest, options) { + this._dest = dest + return Stream.prototype.pipe.call(this, dest, options) +} + +MuteStream.prototype.pause = function () { + if (this._src) return this._src.pause() +} + +MuteStream.prototype.resume = function () { + if (this._src) return this._src.resume() +} + +MuteStream.prototype.write = function (c) { + if (this.muted) { + if (!this.replace) return true + if (c.match(/^\u001b/)) { + if(c.indexOf(this._prompt) === 0) { + c = c.substr(this._prompt.length); + c = c.replace(/./g, this.replace); + c = this._prompt + c; + } + this._hadControl = true + return this.emit('data', c) + } else { + if (this._prompt && this._hadControl && + c.indexOf(this._prompt) === 0) { + this._hadControl = false + this.emit('data', this._prompt) + c = c.substr(this._prompt.length) + } + c = c.toString().replace(/./g, this.replace) + } + } + this.emit('data', c) +} + +MuteStream.prototype.end = function (c) { + if (this.muted) { + if (c && this.replace) { + c = c.toString().replace(/./g, this.replace) + } else { + c = null + } + } + if (c) this.emit('data', c) + this.emit('end') +} + +function proxy (fn) { return function () { + var d = this._dest + var s = this._src + if (d && d[fn]) d[fn].apply(d, arguments) + if (s && s[fn]) s[fn].apply(s, arguments) +}} + +MuteStream.prototype.destroy = proxy('destroy') +MuteStream.prototype.destroySoon = proxy('destroySoon') +MuteStream.prototype.close = proxy('close') diff --git a/node_modules/mute-stream/package.json b/node_modules/mute-stream/package.json new file mode 100644 index 0000000..c9dcf49 --- /dev/null +++ b/node_modules/mute-stream/package.json @@ -0,0 +1,62 @@ +{ + "_from": "mute-stream@0.0.8", + "_id": "mute-stream@0.0.8", + "_inBundle": false, + "_integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", + "_location": "/mute-stream", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mute-stream@0.0.8", + "name": "mute-stream", + "escapedName": "mute-stream", + "rawSpec": "0.0.8", + "saveSpec": null, + "fetchSpec": "0.0.8" + }, + "_requiredBy": [ + "/ora" + ], + "_resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "_shasum": "1630c42b2251ff81e2a283de96a5497ea92e5e0d", + "_spec": "mute-stream@0.0.8", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/ora", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/mute-stream/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Bytes go in, but they don't come out (when muted).", + "devDependencies": { + "tap": "^12.1.1" + }, + "directories": { + "test": "test" + }, + "files": [ + "mute.js" + ], + "homepage": "https://github.com/isaacs/mute-stream#readme", + "keywords": [ + "mute", + "stream", + "pipe" + ], + "license": "ISC", + "main": "mute.js", + "name": "mute-stream", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/mute-stream.git" + }, + "scripts": { + "test": "tap test/*.js --cov" + }, + "version": "0.0.8" +} diff --git a/node_modules/ncp/.npmignore b/node_modules/ncp/.npmignore new file mode 100644 index 0000000..3e6a4d7 --- /dev/null +++ b/node_modules/ncp/.npmignore @@ -0,0 +1,4 @@ +node_modules +.*.sw[op] +.DS_Store +test/*fixtures/out diff --git a/node_modules/ncp/.travis.yml b/node_modules/ncp/.travis.yml new file mode 100644 index 0000000..a6e2198 --- /dev/null +++ b/node_modules/ncp/.travis.yml @@ -0,0 +1,6 @@ +language: node_js + +node_js: + - 0.8 + - "0.10" + - "0.11" diff --git a/node_modules/ncp/LICENSE.md b/node_modules/ncp/LICENSE.md new file mode 100644 index 0000000..e2b9b41 --- /dev/null +++ b/node_modules/ncp/LICENSE.md @@ -0,0 +1,21 @@ +# MIT License + +###Copyright (C) 2011 by Charlie McConnell + +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/ncp/README.md b/node_modules/ncp/README.md new file mode 100644 index 0000000..9480032 --- /dev/null +++ b/node_modules/ncp/README.md @@ -0,0 +1,63 @@ +# ncp - Asynchronous recursive file & directory copying + +[![Build Status](https://secure.travis-ci.org/AvianFlu/ncp.png)](http://travis-ci.org/AvianFlu/ncp) + +Think `cp -r`, but pure node, and asynchronous. `ncp` can be used both as a CLI tool and programmatically. + +## Command Line usage + +Usage is simple: `ncp [source] [dest] [--limit=concurrency limit] +[--filter=filter] --stopOnErr` + +The 'filter' is a Regular Expression - matched files will be copied. + +The 'concurrency limit' is an integer that represents how many pending file system requests `ncp` has at a time. + +'stoponerr' is a boolean flag that will tell `ncp` to stop immediately if any +errors arise, rather than attempting to continue while logging errors. The default behavior is to complete as many copies as possible, logging errors along the way. + +If there are no errors, `ncp` will output `done.` when complete. If there are errors, the error messages will be logged to `stdout` and to `./ncp-debug.log`, and the copy operation will attempt to continue. + +## Programmatic usage + +Programmatic usage of `ncp` is just as simple. The only argument to the completion callback is a possible error. + +```javascript +var ncp = require('ncp').ncp; + +ncp.limit = 16; + +ncp(source, destination, function (err) { + if (err) { + return console.error(err); + } + console.log('done!'); +}); +``` + +You can also call ncp like `ncp(source, destination, options, callback)`. +`options` should be a dictionary. Currently, such options are available: + + * `options.filter` - a `RegExp` instance, against which each file name is + tested to determine whether to copy it or not, or a function taking single + parameter: copied file name, returning `true` or `false`, determining + whether to copy file or not. + + * `options.transform` - a function: `function (read, write) { read.pipe(write) }` + used to apply streaming transforms while copying. + + * `options.clobber` - boolean=true. if set to false, `ncp` will not overwrite + destination files that already exist. + + * `options.dereference` - boolean=false. If set to true, `ncp` will follow symbolic + links. For example, a symlink in the source tree pointing to a regular file + will become a regular file in the destination tree. Broken symlinks will result in + errors. + + * `options.stopOnErr` - boolean=false. If set to true, `ncp` will behave like `cp -r`, + and stop on the first error it encounters. By default, `ncp` continues copying, logging all + errors and returning an array. + + * `options.errs` - stream. If `options.stopOnErr` is `false`, a stream can be provided, and errors will be written to this stream. + +Please open an issue if any bugs arise. As always, I accept (working) pull requests, and refunds are available at `/dev/null`. diff --git a/node_modules/ncp/bin/ncp b/node_modules/ncp/bin/ncp new file mode 100644 index 0000000..388eaba --- /dev/null +++ b/node_modules/ncp/bin/ncp @@ -0,0 +1,48 @@ +#!/usr/bin/env node + + + + +var ncp = require('../lib/ncp'), + args = process.argv.slice(2), + source, dest; + +if (args.length < 2) { + console.error('Usage: ncp [source] [destination] [--filter=filter] [--limit=concurrency limit]'); + process.exit(1); +} + +// parse arguments the hard way +function startsWith(str, prefix) { + return str.substr(0, prefix.length) == prefix; +} + +var options = {}; +args.forEach(function (arg) { + if (startsWith(arg, "--limit=")) { + options.limit = parseInt(arg.split('=', 2)[1], 10); + } + if (startsWith(arg, "--filter=")) { + options.filter = new RegExp(arg.split('=', 2)[1]); + } + if (startsWith(arg, "--stoponerr")) { + options.stopOnErr = true; + } +}); + +ncp.ncp(args[0], args[1], options, function (err) { + if (Array.isArray(err)) { + console.error('There were errors during the copy.'); + err.forEach(function (err) { + console.error(err.stack || err.message); + }); + process.exit(1); + } + else if (err) { + console.error('An error has occurred.'); + console.error(err.stack || err.message); + process.exit(1); + } +}); + + diff --git a/node_modules/ncp/lib/ncp.js b/node_modules/ncp/lib/ncp.js new file mode 100644 index 0000000..bc25a05 --- /dev/null +++ b/node_modules/ncp/lib/ncp.js @@ -0,0 +1,266 @@ +var fs = require('fs'), + path = require('path'), + util = require('util'); + +const modern = /^v0\.1\d\.\d+/.test(process.version); + +module.exports = ncp; +ncp.ncp = ncp; + +function ncp (source, dest, options, callback) { + var cback = callback; + + if (!callback) { + cback = options; + options = {}; + } + + var basePath = process.cwd(), + currentPath = path.resolve(basePath, source), + targetPath = path.resolve(basePath, dest), + filter = options.filter, + rename = options.rename, + transform = options.transform, + clobber = options.clobber !== false, + modified = options.modified, + dereference = options.dereference, + errs = null, + eventName = modern ? 'finish' : 'close', + defer = modern ? setImmediate : process.nextTick, + started = 0, + finished = 0, + running = 0, + limit = options.limit || ncp.limit || 16; + + limit = (limit < 1) ? 1 : (limit > 512) ? 512 : limit; + + startCopy(currentPath); + + function startCopy(source) { + started++; + if (filter) { + if (filter instanceof RegExp) { + if (!filter.test(source)) { + return cb(true); + } + } + else if (typeof filter === 'function') { + if (!filter(source)) { + return cb(true); + } + } + } + return getStats(source); + } + + function getStats(source) { + var stat = dereference ? fs.stat : fs.lstat; + if (running >= limit) { + return defer(function () { + getStats(source); + }); + } + running++; + stat(source, function (err, stats) { + var item = {}; + if (err) { + return onError(err); + } + + // We need to get the mode from the stats object and preserve it. + item.name = source; + item.mode = stats.mode; + item.mtime = stats.mtime; //modified time + item.atime = stats.atime; //access time + + if (stats.isDirectory()) { + return onDir(item); + } + else if (stats.isFile()) { + return onFile(item); + } + else if (stats.isSymbolicLink()) { + // Symlinks don't really need to know about the mode. + return onLink(source); + } + }); + } + + function onFile(file) { + var target = file.name.replace(currentPath, targetPath); + if(rename) { + target = rename(target); + } + isWritable(target, function (writable) { + if (writable) { + return copyFile(file, target); + } + if(clobber) { + rmFile(target, function () { + copyFile(file, target); + }); + } + if (modified) { + var stat = dereference ? fs.stat : fs.lstat; + stat(target, function(err, stats) { + //if souce modified time greater to target modified time copy file + if (file.mtime.getTime()>stats.mtime.getTime()) + copyFile(file, target); + else return cb(); + }); + } + else { + return cb(); + } + }); + } + + function copyFile(file, target) { + var readStream = fs.createReadStream(file.name), + writeStream = fs.createWriteStream(target, { mode: file.mode }); + + readStream.on('error', onError); + writeStream.on('error', onError); + + if(transform) { + transform(readStream, writeStream, file); + } else { + writeStream.on('open', function() { + readStream.pipe(writeStream); + }); + } + writeStream.once(eventName, function() { + if (modified) { + //target file modified date sync. + fs.utimesSync(target, file.atime, file.mtime); + cb(); + } + else cb(); + }); + } + + function rmFile(file, done) { + fs.unlink(file, function (err) { + if (err) { + return onError(err); + } + return done(); + }); + } + + function onDir(dir) { + var target = dir.name.replace(currentPath, targetPath); + isWritable(target, function (writable) { + if (writable) { + return mkDir(dir, target); + } + copyDir(dir.name); + }); + } + + function mkDir(dir, target) { + fs.mkdir(target, dir.mode, function (err) { + if (err) { + return onError(err); + } + copyDir(dir.name); + }); + } + + function copyDir(dir) { + fs.readdir(dir, function (err, items) { + if (err) { + return onError(err); + } + items.forEach(function (item) { + startCopy(dir + '/' + item); + }); + return cb(); + }); + } + + function onLink(link) { + var target = link.replace(currentPath, targetPath); + fs.readlink(link, function (err, resolvedPath) { + if (err) { + return onError(err); + } + checkLink(resolvedPath, target); + }); + } + + function checkLink(resolvedPath, target) { + if (dereference) { + resolvedPath = path.resolve(basePath, resolvedPath); + } + isWritable(target, function (writable) { + if (writable) { + return makeLink(resolvedPath, target); + } + fs.readlink(target, function (err, targetDest) { + if (err) { + return onError(err); + } + if (dereference) { + targetDest = path.resolve(basePath, targetDest); + } + if (targetDest === resolvedPath) { + return cb(); + } + return rmFile(target, function () { + makeLink(resolvedPath, target); + }); + }); + }); + } + + function makeLink(linkPath, target) { + fs.symlink(linkPath, target, function (err) { + if (err) { + return onError(err); + } + return cb(); + }); + } + + function isWritable(path, done) { + fs.lstat(path, function (err) { + if (err) { + if (err.code === 'ENOENT') return done(true); + return done(false); + } + return done(false); + }); + } + + function onError(err) { + if (options.stopOnError) { + return cback(err); + } + else if (!errs && options.errs) { + errs = fs.createWriteStream(options.errs); + } + else if (!errs) { + errs = []; + } + if (typeof errs.write === 'undefined') { + errs.push(err); + } + else { + errs.write(err.stack + '\n\n'); + } + return cb(); + } + + function cb(skipped) { + if (!skipped) running--; + finished++; + if ((started === finished) && (running === 0)) { + if (cback !== undefined ) { + return errs ? cback(errs) : cback(null); + } + } + } +} + + diff --git a/node_modules/ncp/package.json b/node_modules/ncp/package.json new file mode 100644 index 0000000..af48e69 --- /dev/null +++ b/node_modules/ncp/package.json @@ -0,0 +1,62 @@ +{ + "_from": "ncp@1.0.x", + "_id": "ncp@1.0.1", + "_inBundle": false, + "_integrity": "sha1-0VNn5cuHQyuhF9K/gP30Wuz7QkY=", + "_location": "/ncp", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "ncp@1.0.x", + "name": "ncp", + "escapedName": "ncp", + "rawSpec": "1.0.x", + "saveSpec": null, + "fetchSpec": "1.0.x" + }, + "_requiredBy": [ + "/utile" + ], + "_resolved": "https://registry.npmjs.org/ncp/-/ncp-1.0.1.tgz", + "_shasum": "d15367e5cb87432ba117d2bf80fdf45aecfb4246", + "_spec": "ncp@1.0.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/utile", + "author": { + "name": "AvianFlu", + "email": "charlie@charlieistheman.com" + }, + "bin": { + "ncp": "bin/ncp" + }, + "bugs": { + "url": "https://github.com/AvianFlu/ncp/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Asynchronous recursive file copy utility.", + "devDependencies": { + "mocha": "1.15.x", + "read-dir-files": "0.0.x", + "rimraf": "1.0.x" + }, + "engine": { + "node": ">=0.8" + }, + "homepage": "https://github.com/AvianFlu/ncp#readme", + "keywords": [ + "cli", + "copy" + ], + "license": "MIT", + "main": "./lib/ncp.js", + "name": "ncp", + "repository": { + "type": "git", + "url": "git+https://github.com/AvianFlu/ncp.git" + }, + "scripts": { + "test": "mocha -R spec" + }, + "version": "1.0.1" +} diff --git a/node_modules/ncp/test/modified-files/out/a b/node_modules/ncp/test/modified-files/out/a new file mode 100644 index 0000000..29f446a --- /dev/null +++ b/node_modules/ncp/test/modified-files/out/a @@ -0,0 +1 @@ +test3
\ No newline at end of file diff --git a/node_modules/ncp/test/modified-files/src/a b/node_modules/ncp/test/modified-files/src/a new file mode 100644 index 0000000..29f446a --- /dev/null +++ b/node_modules/ncp/test/modified-files/src/a @@ -0,0 +1 @@ +test3
\ No newline at end of file diff --git a/node_modules/ncp/test/ncp.js b/node_modules/ncp/test/ncp.js new file mode 100644 index 0000000..bc6df22 --- /dev/null +++ b/node_modules/ncp/test/ncp.js @@ -0,0 +1,197 @@ + + +var assert = require('assert'), + fs = require('fs'), + path = require('path'), + rimraf = require('rimraf'), + readDirFiles = require('read-dir-files'), + util = require('util'), + ncp = require('../').ncp; + + + +describe('ncp', function () { + describe('regular files and directories', function () { + var fixtures = path.join(__dirname, 'regular-fixtures'), + src = path.join(fixtures, 'src'), + out = path.join(fixtures, 'out'); + + before(function (cb) { + rimraf(out, function() { + ncp(src, out, cb); + }); + }); + + describe('when copying a directory of files', function () { + it('files are copied correctly', function (cb) { + readDirFiles(src, 'utf8', function (srcErr, srcFiles) { + readDirFiles(out, 'utf8', function (outErr, outFiles) { + assert.ifError(srcErr); + assert.deepEqual(srcFiles, outFiles); + cb(); + }); + }); + }); + }); + + describe('when copying files using filter', function () { + before(function (cb) { + var filter = function(name) { + return name.substr(name.length - 1) != 'a'; + }; + rimraf(out, function () { + ncp(src, out, {filter: filter}, cb); + }); + }); + + it('files are copied correctly', function (cb) { + readDirFiles(src, 'utf8', function (srcErr, srcFiles) { + function filter(files) { + for (var fileName in files) { + var curFile = files[fileName]; + if (curFile instanceof Object) + return filter(curFile); + if (fileName.substr(fileName.length - 1) == 'a') + delete files[fileName]; + } + } + filter(srcFiles); + readDirFiles(out, 'utf8', function (outErr, outFiles) { + assert.ifError(outErr); + assert.deepEqual(srcFiles, outFiles); + cb(); + }); + }); + }); + }); + + describe('when using clobber=false', function () { + it('the copy is completed successfully', function (cb) { + ncp(src, out, function() { + ncp(src, out, {clobber: false}, function(err) { + assert.ifError(err); + cb(); + }); + }); + }); + }); + + describe('when using transform', function () { + it('file descriptors are passed correctly', function (cb) { + ncp(src, out, { + transform: function(read,write,file) { + assert.notEqual(file.name, undefined); + assert.strictEqual(typeof file.mode,'number'); + read.pipe(write); + } + }, cb); + }); + }); + + describe('when using rename', function() { + it('output files are correctly redirected', function(cb) { + ncp(src, out, { + rename: function(target) { + if(path.basename(target) == 'a') return path.resolve(path.dirname(target), 'z'); + return target; + } + }, function(err) { + if(err) return cb(err); + + readDirFiles(src, 'utf8', function (srcErr, srcFiles) { + readDirFiles(out, 'utf8', function (outErr, outFiles) { + assert.ifError(srcErr); + assert.deepEqual(srcFiles.a, outFiles.z); + cb(); + }); + }); + }); + }); + }); + }); + + describe('symlink handling', function () { + var fixtures = path.join(__dirname, 'symlink-fixtures'), + src = path.join(fixtures, 'src'), + out = path.join(fixtures, 'out'); + + beforeEach(function (cb) { + rimraf(out, cb); + }); + + it('copies symlinks by default', function (cb) { + ncp(src, out, function (err) { + if (err) return cb(err); + assert.equal(fs.readlinkSync(path.join(out, 'file-symlink')), 'foo'); + assert.equal(fs.readlinkSync(path.join(out, 'dir-symlink')), 'dir'); + cb(); + }) + }); + + it('copies file contents when dereference=true', function (cb) { + ncp(src, out, { dereference: true }, function (err) { + var fileSymlinkPath = path.join(out, 'file-symlink'); + assert.ok(fs.lstatSync(fileSymlinkPath).isFile()); + assert.equal(fs.readFileSync(fileSymlinkPath), 'foo contents'); + + var dirSymlinkPath = path.join(out, 'dir-symlink'); + assert.ok(fs.lstatSync(dirSymlinkPath).isDirectory()); + assert.deepEqual(fs.readdirSync(dirSymlinkPath), ['bar']); + + cb(); + }); + }); + }); + + describe('broken symlink handling', function () { + var fixtures = path.join(__dirname, 'broken-symlink-fixtures'), + src = path.join(fixtures, 'src'), + out = path.join(fixtures, 'out'); + + beforeEach(function (cb) { + rimraf(out, cb); + }); + + it('copies broken symlinks by default', function (cb) { + ncp(src, out, function (err) { + if (err) return cb(err); + assert.equal(fs.readlinkSync(path.join(out, 'broken-symlink')), 'does-not-exist'); + cb(); + }) + }); + + it('returns an error when dereference=true', function (cb) { + ncp(src, out, {dereference: true}, function (err) { + assert.equal(err.length, 1); + assert.equal(err[0].code, 'ENOENT'); + cb(); + }); + }); + }); + + describe('modified files copies', function () { + var fixtures = path.join(__dirname, 'modified-files'), + src = path.join(fixtures, 'src'), + out = path.join(fixtures, 'out'); + + it('if file not exists copy file to target', function(cb) { + rimraf(out, function() { + ncp(src, out, {modified: true, clobber: false}, function (err) { + assert.equal(fs.existsSync(out), true); + cb(); + }); + }); + }); + + it('change source file mtime and copy', function(cb) { + fs.utimesSync(src+"/a", new Date().getTime()/1000, new Date('2015-01-01 00:00:00').getTime()/1000); + ncp(src, out, {modified: true, clobber: false}, function (err) { + fs.stat(out+"/a", function(err, stats) { + assert.equal(stats.mtime.getTime(), new Date('2015-01-01 00:00:00').getTime()); + cb(); + }); + }); + }); + + }); +});
\ No newline at end of file diff --git a/node_modules/ncp/test/regular-fixtures/src/a b/node_modules/ncp/test/regular-fixtures/src/a new file mode 100644 index 0000000..802992c --- /dev/null +++ b/node_modules/ncp/test/regular-fixtures/src/a @@ -0,0 +1 @@ +Hello world diff --git a/node_modules/ncp/test/regular-fixtures/src/b b/node_modules/ncp/test/regular-fixtures/src/b new file mode 100644 index 0000000..9f6bb18 --- /dev/null +++ b/node_modules/ncp/test/regular-fixtures/src/b @@ -0,0 +1 @@ +Hello ncp diff --git a/node_modules/ncp/test/regular-fixtures/src/c b/node_modules/ncp/test/regular-fixtures/src/c new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/node_modules/ncp/test/regular-fixtures/src/c diff --git a/node_modules/ncp/test/regular-fixtures/src/d b/node_modules/ncp/test/regular-fixtures/src/d new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/node_modules/ncp/test/regular-fixtures/src/d diff --git a/node_modules/ncp/test/regular-fixtures/src/e b/node_modules/ncp/test/regular-fixtures/src/e new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/node_modules/ncp/test/regular-fixtures/src/e diff --git a/node_modules/ncp/test/regular-fixtures/src/f b/node_modules/ncp/test/regular-fixtures/src/f new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/node_modules/ncp/test/regular-fixtures/src/f diff --git a/node_modules/ncp/test/regular-fixtures/src/sub/a b/node_modules/ncp/test/regular-fixtures/src/sub/a new file mode 100644 index 0000000..cf291b5 --- /dev/null +++ b/node_modules/ncp/test/regular-fixtures/src/sub/a @@ -0,0 +1 @@ +Hello nodejitsu diff --git a/node_modules/ncp/test/regular-fixtures/src/sub/b b/node_modules/ncp/test/regular-fixtures/src/sub/b new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/node_modules/ncp/test/regular-fixtures/src/sub/b diff --git a/node_modules/ncp/test/symlink-fixtures/src/dir/bar b/node_modules/ncp/test/symlink-fixtures/src/dir/bar new file mode 100644 index 0000000..fd06f5f --- /dev/null +++ b/node_modules/ncp/test/symlink-fixtures/src/dir/bar @@ -0,0 +1 @@ +bar contents
\ No newline at end of file diff --git a/node_modules/ncp/test/symlink-fixtures/src/foo b/node_modules/ncp/test/symlink-fixtures/src/foo new file mode 100644 index 0000000..35fc060 --- /dev/null +++ b/node_modules/ncp/test/symlink-fixtures/src/foo @@ -0,0 +1 @@ +foo contents
\ No newline at end of file diff --git a/node_modules/once/LICENSE b/node_modules/once/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/once/README.md b/node_modules/once/README.md new file mode 100644 index 0000000..1f1ffca --- /dev/null +++ b/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/node_modules/once/once.js b/node_modules/once/once.js new file mode 100644 index 0000000..2354067 --- /dev/null +++ b/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/node_modules/once/package.json b/node_modules/once/package.json new file mode 100644 index 0000000..ea788d6 --- /dev/null +++ b/node_modules/once/package.json @@ -0,0 +1,67 @@ +{ + "_from": "once@^1.3.0", + "_id": "once@1.4.0", + "_inBundle": false, + "_integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "_location": "/once", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "once@^1.3.0", + "name": "once", + "escapedName": "once", + "rawSpec": "^1.3.0", + "saveSpec": null, + "fetchSpec": "^1.3.0" + }, + "_requiredBy": [ + "/glob", + "/inflight" + ], + "_resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "_shasum": "583b1aa775961d4b113ac17d9c50baef9dd76bd1", + "_spec": "once@^1.3.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/glob", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/once/issues" + }, + "bundleDependencies": false, + "dependencies": { + "wrappy": "1" + }, + "deprecated": false, + "description": "Run a function exactly one time", + "devDependencies": { + "tap": "^7.0.1" + }, + "directories": { + "test": "test" + }, + "files": [ + "once.js" + ], + "homepage": "https://github.com/isaacs/once#readme", + "keywords": [ + "once", + "function", + "one", + "single" + ], + "license": "ISC", + "main": "once.js", + "name": "once", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "version": "1.4.0" +} diff --git a/node_modules/onetime/index.d.ts b/node_modules/onetime/index.d.ts new file mode 100644 index 0000000..ea84cab --- /dev/null +++ b/node_modules/onetime/index.d.ts @@ -0,0 +1,64 @@ +declare namespace onetime { + interface Options { + /** + Throw an error when called more than once. + + @default false + */ + throw?: boolean; + } +} + +declare const onetime: { + /** + Ensure a function is only called once. When called multiple times it will return the return value from the first call. + + @param fn - Function that should only be called once. + @returns A function that only calls `fn` once. + + @example + ``` + import onetime = require('onetime'); + + let i = 0; + + const foo = onetime(() => ++i); + + foo(); //=> 1 + foo(); //=> 1 + foo(); //=> 1 + + onetime.callCount(foo); //=> 3 + ``` + */ + <ArgumentsType extends unknown[], ReturnType>( + fn: (...arguments: ArgumentsType) => ReturnType, + options?: onetime.Options + ): (...arguments: ArgumentsType) => ReturnType; + + /** + Get the number of times `fn` has been called. + + @param fn - Function to get call count from. + @returns A number representing how many times `fn` has been called. + + @example + ``` + import onetime = require('onetime'); + + const foo = onetime(() => {}); + foo(); + foo(); + foo(); + + console.log(onetime.callCount(foo)); + //=> 3 + ``` + */ + callCount(fn: (...arguments: any[]) => unknown): number; + + // TODO: Remove this for the next major release + default: typeof onetime; +}; + +export = onetime; diff --git a/node_modules/onetime/index.js b/node_modules/onetime/index.js new file mode 100644 index 0000000..99c5fc1 --- /dev/null +++ b/node_modules/onetime/index.js @@ -0,0 +1,44 @@ +'use strict'; +const mimicFn = require('mimic-fn'); + +const calledFunctions = new WeakMap(); + +const onetime = (function_, options = {}) => { + if (typeof function_ !== 'function') { + throw new TypeError('Expected a function'); + } + + let returnValue; + let callCount = 0; + const functionName = function_.displayName || function_.name || '<anonymous>'; + + const onetime = function (...arguments_) { + calledFunctions.set(onetime, ++callCount); + + if (callCount === 1) { + returnValue = function_.apply(this, arguments_); + function_ = null; + } else if (options.throw === true) { + throw new Error(`Function \`${functionName}\` can only be called once`); + } + + return returnValue; + }; + + mimicFn(onetime, function_); + calledFunctions.set(onetime, callCount); + + return onetime; +}; + +module.exports = onetime; +// TODO: Remove this for the next major release +module.exports.default = onetime; + +module.exports.callCount = function_ => { + if (!calledFunctions.has(function_)) { + throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`); + } + + return calledFunctions.get(function_); +}; diff --git a/node_modules/onetime/license b/node_modules/onetime/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/onetime/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://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. diff --git a/node_modules/onetime/package.json b/node_modules/onetime/package.json new file mode 100644 index 0000000..794f6d9 --- /dev/null +++ b/node_modules/onetime/package.json @@ -0,0 +1,75 @@ +{ + "_from": "onetime@^5.1.0", + "_id": "onetime@5.1.2", + "_inBundle": false, + "_integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "_location": "/onetime", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "onetime@^5.1.0", + "name": "onetime", + "escapedName": "onetime", + "rawSpec": "^5.1.0", + "saveSpec": null, + "fetchSpec": "^5.1.0" + }, + "_requiredBy": [ + "/restore-cursor" + ], + "_resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "_shasum": "d0e96ebb56b07476df1dd9c4806e5237985ca45e", + "_spec": "onetime@^5.1.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/restore-cursor", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/onetime/issues" + }, + "bundleDependencies": false, + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "deprecated": false, + "description": "Ensure a function is only called once", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/onetime#readme", + "keywords": [ + "once", + "function", + "one", + "onetime", + "func", + "fn", + "single", + "call", + "called", + "prevent" + ], + "license": "MIT", + "name": "onetime", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/onetime.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "5.1.2" +} diff --git a/node_modules/onetime/readme.md b/node_modules/onetime/readme.md new file mode 100644 index 0000000..2d133d3 --- /dev/null +++ b/node_modules/onetime/readme.md @@ -0,0 +1,94 @@ +# onetime [![Build Status](https://travis-ci.com/sindresorhus/onetime.svg?branch=master)](https://travis-ci.com/github/sindresorhus/onetime) + +> Ensure a function is only called once + +When called multiple times it will return the return value from the first call. + +*Unlike the module [once](https://github.com/isaacs/once), this one isn't naughty and extending `Function.prototype`.* + +## Install + +``` +$ npm install onetime +``` + +## Usage + +```js +const onetime = require('onetime'); + +let i = 0; + +const foo = onetime(() => ++i); + +foo(); //=> 1 +foo(); //=> 1 +foo(); //=> 1 + +onetime.callCount(foo); //=> 3 +``` + +```js +const onetime = require('onetime'); + +const foo = onetime(() => {}, {throw: true}); + +foo(); + +foo(); +//=> Error: Function `foo` can only be called once +``` + +## API + +### onetime(fn, options?) + +Returns a function that only calls `fn` once. + +#### fn + +Type: `Function` + +Function that should only be called once. + +#### options + +Type: `object` + +##### throw + +Type: `boolean`\ +Default: `false` + +Throw an error when called more than once. + +### onetime.callCount(fn) + +Returns a number representing how many times `fn` has been called. + +Note: It throws an error if you pass in a function that is not wrapped by `onetime`. + +```js +const onetime = require('onetime'); + +const foo = onetime(() => {}); + +foo(); +foo(); +foo(); + +console.log(onetime.callCount(foo)); +//=> 3 +``` + +#### fn + +Type: `Function` + +Function to get call count from. + +## onetime for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of onetime 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-onetime?utm_source=npm-onetime&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/ora/index.d.ts b/node_modules/ora/index.d.ts new file mode 100644 index 0000000..392deb2 --- /dev/null +++ b/node_modules/ora/index.d.ts @@ -0,0 +1,269 @@ +/// <reference types="node"/> +import {SpinnerName} from 'cli-spinners'; + +declare namespace ora { + interface Spinner { + readonly interval?: number; + readonly frames: string[]; + } + + type Color = + | 'black' + | 'red' + | 'green' + | 'yellow' + | 'blue' + | 'magenta' + | 'cyan' + | 'white' + | 'gray'; + + interface Options { + /** + Text to display after the spinner. + */ + readonly text?: string; + + /** + Text to display before the spinner. No prefix text will be displayed if set to an empty string. + */ + readonly prefixText?: string; + + /** + Name of one of the provided spinners. See [`example.js`](https://github.com/BendingBender/ora/blob/master/example.js) in this repo if you want to test out different spinners. On Windows, it will always use the line spinner as the Windows command-line doesn't have proper Unicode support. + + @default 'dots' + + Or an object like: + + @example + ``` + { + interval: 80, // Optional + frames: ['-', '+', '-'] + } + ``` + */ + readonly spinner?: SpinnerName | Spinner; + + /** + Color of the spinner. + + @default 'cyan' + */ + readonly color?: Color; + + /** + Set to `false` to stop Ora from hiding the cursor. + + @default true + */ + readonly hideCursor?: boolean; + + /** + Indent the spinner with the given number of spaces. + + @default 0 + */ + readonly indent?: number; + + /** + Interval between each frame. + + Spinners provide their own recommended interval, so you don't really need to specify this. + + Default: Provided by the spinner or `100`. + */ + readonly interval?: number; + + /** + Stream to write the output. + + You could for example set this to `process.stdout` instead. + + @default process.stderr + */ + readonly stream?: NodeJS.WritableStream; + + /** + Force enable/disable the spinner. If not specified, the spinner will be enabled if the `stream` is being run inside a TTY context (not spawned or piped) and/or not in a CI environment. + + Note that `{isEnabled: false}` doesn't mean it won't output anything. It just means it won't output the spinner, colors, and other ansi escape codes. It will still log text. + */ + readonly isEnabled?: boolean; + + /** + Discard stdin input (except Ctrl+C) while running if it's TTY. This prevents the spinner from twitching on input, outputting broken lines on `Enter` key presses, and prevents buffering of input while the spinner is running. + + This has no effect on Windows as there's no good way to implement discarding stdin properly there. + + @default true + */ + readonly discardStdin?: boolean; + } + + interface PersistOptions { + /** + Symbol to replace the spinner with. + + @default ' ' + */ + readonly symbol?: string; + + /** + Text to be persisted after the symbol. + + Default: Current `text`. + */ + readonly text?: string; + + /** + Text to be persisted before the symbol. No prefix text will be displayed if set to an empty string. + + Default: Current `prefixText`. + */ + readonly prefixText?: string; + } + + interface Ora { + /** + A boolean of whether the instance is currently spinning. + */ + readonly isSpinning: boolean; + + /** + Change the text after the spinner. + */ + text: string; + + /** + Change the text before the spinner. No prefix text will be displayed if set to an empty string. + */ + prefixText: string; + + /** + Change the spinner color. + */ + color: Color; + + /** + Change the spinner. + */ + spinner: SpinnerName | Spinner; + + /** + Change the spinner indent. + */ + indent: number; + + /** + Start the spinner. + + @param text - Set the current text. + @returns The spinner instance. + */ + start(text?: string): Ora; + + /** + Stop and clear the spinner. + + @returns The spinner instance. + */ + stop(): Ora; + + /** + Stop the spinner, change it to a green `✔` and persist the current text, or `text` if provided. + + @param text - Will persist text if provided. + @returns The spinner instance. + */ + succeed(text?: string): Ora; + + /** + Stop the spinner, change it to a red `✖` and persist the current text, or `text` if provided. + + @param text - Will persist text if provided. + @returns The spinner instance. + */ + fail(text?: string): Ora; + + /** + Stop the spinner, change it to a yellow `⚠` and persist the current text, or `text` if provided. + + @param text - Will persist text if provided. + @returns The spinner instance. + */ + warn(text?: string): Ora; + + /** + Stop the spinner, change it to a blue `ℹ` and persist the current text, or `text` if provided. + + @param text - Will persist text if provided. + @returns The spinner instance. + */ + info(text?: string): Ora; + + /** + Stop the spinner and change the symbol or text. + + @returns The spinner instance. + */ + stopAndPersist(options?: PersistOptions): Ora; + + /** + Clear the spinner. + + @returns The spinner instance. + */ + clear(): Ora; + + /** + Manually render a new frame. + + @returns The spinner instance. + */ + render(): Ora; + + /** + Get a new frame. + + @returns The spinner instance text. + */ + frame(): string; + } +} + +declare const ora: { + /** + Elegant terminal spinner. + + @param options - If a string is provided, it is treated as a shortcut for `options.text`. + + @example + ``` + import ora = require('ora'); + + const spinner = ora('Loading unicorns').start(); + + setTimeout(() => { + spinner.color = 'yellow'; + spinner.text = 'Loading rainbows'; + }, 1000); + ``` + */ + (options?: ora.Options | string): ora.Ora; + + /** + Starts a spinner for a promise. The spinner is stopped with `.succeed()` if the promise fulfills or with `.fail()` if it rejects. + + @param action - The promise to start the spinner for. + @param options - If a string is provided, it is treated as a shortcut for `options.text`. + @returns The spinner instance. + */ + promise( + action: PromiseLike<unknown>, + options?: ora.Options | string + ): ora.Ora; +}; + +export = ora; diff --git a/node_modules/ora/index.js b/node_modules/ora/index.js new file mode 100644 index 0000000..c18218a --- /dev/null +++ b/node_modules/ora/index.js @@ -0,0 +1,359 @@ +'use strict'; +const readline = require('readline'); +const chalk = require('chalk'); +const cliCursor = require('cli-cursor'); +const cliSpinners = require('cli-spinners'); +const logSymbols = require('log-symbols'); +const stripAnsi = require('strip-ansi'); +const wcwidth = require('wcwidth'); +const isInteractive = require('is-interactive'); +const MuteStream = require('mute-stream'); + +const TEXT = Symbol('text'); +const PREFIX_TEXT = Symbol('prefixText'); + +const ASCII_ETX_CODE = 0x03; // Ctrl+C emits this code + +class StdinDiscarder { + constructor() { + this.requests = 0; + + this.mutedStream = new MuteStream(); + this.mutedStream.pipe(process.stdout); + this.mutedStream.mute(); + + const self = this; + this.ourEmit = function (event, data, ...args) { + const {stdin} = process; + if (self.requests > 0 || stdin.emit === self.ourEmit) { + if (event === 'keypress') { // Fixes readline behavior + return; + } + + if (event === 'data' && data.includes(ASCII_ETX_CODE)) { + process.emit('SIGINT'); + } + + Reflect.apply(self.oldEmit, this, [event, data, ...args]); + } else { + Reflect.apply(process.stdin.emit, this, [event, data, ...args]); + } + }; + } + + start() { + this.requests++; + + if (this.requests === 1) { + this.realStart(); + } + } + + stop() { + if (this.requests <= 0) { + throw new Error('`stop` called more times than `start`'); + } + + this.requests--; + + if (this.requests === 0) { + this.realStop(); + } + } + + realStart() { + // No known way to make it work reliably on Windows + if (process.platform === 'win32') { + return; + } + + this.rl = readline.createInterface({ + input: process.stdin, + output: this.mutedStream + }); + + this.rl.on('SIGINT', () => { + if (process.listenerCount('SIGINT') === 0) { + process.emit('SIGINT'); + } else { + this.rl.close(); + process.kill(process.pid, 'SIGINT'); + } + }); + } + + realStop() { + if (process.platform === 'win32') { + return; + } + + this.rl.close(); + this.rl = undefined; + } +} + +let stdinDiscarder; + +class Ora { + constructor(options) { + if (!stdinDiscarder) { + stdinDiscarder = new StdinDiscarder(); + } + + if (typeof options === 'string') { + options = { + text: options + }; + } + + this.options = { + text: '', + color: 'cyan', + stream: process.stderr, + discardStdin: true, + ...options + }; + + this.spinner = this.options.spinner; + + this.color = this.options.color; + this.hideCursor = this.options.hideCursor !== false; + this.interval = this.options.interval || this.spinner.interval || 100; + this.stream = this.options.stream; + this.id = undefined; + this.isEnabled = typeof this.options.isEnabled === 'boolean' ? this.options.isEnabled : isInteractive({stream: this.stream}); + + // Set *after* `this.stream` + this.text = this.options.text; + this.prefixText = this.options.prefixText; + this.linesToClear = 0; + this.indent = this.options.indent; + this.discardStdin = this.options.discardStdin; + this.isDiscardingStdin = false; + } + + get indent() { + return this._indent; + } + + set indent(indent = 0) { + if (!(indent >= 0 && Number.isInteger(indent))) { + throw new Error('The `indent` option must be an integer from 0 and up'); + } + + this._indent = indent; + } + + _updateInterval(interval) { + if (interval !== undefined) { + this.interval = interval; + } + } + + get spinner() { + return this._spinner; + } + + set spinner(spinner) { + this.frameIndex = 0; + + if (typeof spinner === 'object') { + if (spinner.frames === undefined) { + throw new Error('The given spinner must have a `frames` property'); + } + + this._spinner = spinner; + } else if (process.platform === 'win32') { + this._spinner = cliSpinners.line; + } else if (spinner === undefined) { + // Set default spinner + this._spinner = cliSpinners.dots; + } else if (cliSpinners[spinner]) { + this._spinner = cliSpinners[spinner]; + } else { + throw new Error(`There is no built-in spinner named '${spinner}'. See https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json for a full list.`); + } + + this._updateInterval(this._spinner.interval); + } + + get text() { + return this[TEXT]; + } + + get prefixText() { + return this[PREFIX_TEXT]; + } + + get isSpinning() { + return this.id !== undefined; + } + + updateLineCount() { + const columns = this.stream.columns || 80; + const fullPrefixText = (typeof this[PREFIX_TEXT] === 'string') ? this[PREFIX_TEXT] + '-' : ''; + this.lineCount = stripAnsi(fullPrefixText + '--' + this[TEXT]).split('\n').reduce((count, line) => { + return count + Math.max(1, Math.ceil(wcwidth(line) / columns)); + }, 0); + } + + set text(value) { + this[TEXT] = value; + this.updateLineCount(); + } + + set prefixText(value) { + this[PREFIX_TEXT] = value; + this.updateLineCount(); + } + + frame() { + const {frames} = this.spinner; + let frame = frames[this.frameIndex]; + + if (this.color) { + frame = chalk[this.color](frame); + } + + this.frameIndex = ++this.frameIndex % frames.length; + const fullPrefixText = (typeof this.prefixText === 'string' && this.prefixText !== '') ? this.prefixText + ' ' : ''; + const fullText = typeof this.text === 'string' ? ' ' + this.text : ''; + + return fullPrefixText + frame + fullText; + } + + clear() { + if (!this.isEnabled || !this.stream.isTTY) { + return this; + } + + for (let i = 0; i < this.linesToClear; i++) { + if (i > 0) { + this.stream.moveCursor(0, -1); + } + + this.stream.clearLine(); + this.stream.cursorTo(this.indent); + } + + this.linesToClear = 0; + + return this; + } + + render() { + this.clear(); + this.stream.write(this.frame()); + this.linesToClear = this.lineCount; + + return this; + } + + start(text) { + if (text) { + this.text = text; + } + + if (!this.isEnabled) { + if (this.text) { + this.stream.write(`- ${this.text}\n`); + } + + return this; + } + + if (this.isSpinning) { + return this; + } + + if (this.hideCursor) { + cliCursor.hide(this.stream); + } + + if (this.discardStdin && process.stdin.isTTY) { + this.isDiscardingStdin = true; + stdinDiscarder.start(); + } + + this.render(); + this.id = setInterval(this.render.bind(this), this.interval); + + return this; + } + + stop() { + if (!this.isEnabled) { + return this; + } + + clearInterval(this.id); + this.id = undefined; + this.frameIndex = 0; + this.clear(); + if (this.hideCursor) { + cliCursor.show(this.stream); + } + + if (this.discardStdin && process.stdin.isTTY && this.isDiscardingStdin) { + stdinDiscarder.stop(); + this.isDiscardingStdin = false; + } + + return this; + } + + succeed(text) { + return this.stopAndPersist({symbol: logSymbols.success, text}); + } + + fail(text) { + return this.stopAndPersist({symbol: logSymbols.error, text}); + } + + warn(text) { + return this.stopAndPersist({symbol: logSymbols.warning, text}); + } + + info(text) { + return this.stopAndPersist({symbol: logSymbols.info, text}); + } + + stopAndPersist(options = {}) { + const prefixText = options.prefixText || this.prefixText; + const fullPrefixText = (typeof prefixText === 'string' && prefixText !== '') ? prefixText + ' ' : ''; + const text = options.text || this.text; + const fullText = (typeof text === 'string') ? ' ' + text : ''; + + this.stop(); + this.stream.write(`${fullPrefixText}${options.symbol || ' '}${fullText}\n`); + + return this; + } +} + +const oraFactory = function (options) { + return new Ora(options); +}; + +module.exports = oraFactory; + +module.exports.promise = (action, options) => { + // eslint-disable-next-line promise/prefer-await-to-then + if (typeof action.then !== 'function') { + throw new TypeError('Parameter `action` must be a Promise'); + } + + const spinner = new Ora(options); + spinner.start(); + + (async () => { + try { + await action; + spinner.succeed(); + } catch (_) { + spinner.fail(); + } + })(); + + return spinner; +}; diff --git a/node_modules/ora/license b/node_modules/ora/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/ora/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://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. diff --git a/node_modules/ora/package.json b/node_modules/ora/package.json new file mode 100644 index 0000000..9c9c82c --- /dev/null +++ b/node_modules/ora/package.json @@ -0,0 +1,89 @@ +{ + "_from": "ora", + "_id": "ora@5.0.0", + "_inBundle": false, + "_integrity": "sha512-s26qdWqke2kjN/wC4dy+IQPBIMWBJlSU/0JZhk30ZDBLelW25rv66yutUWARMigpGPzcXHb+Nac5pNhN/WsARw==", + "_location": "/ora", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "ora", + "name": "ora", + "escapedName": "ora", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/ora/-/ora-5.0.0.tgz", + "_shasum": "4f0b34f2994877b49b452a707245ab1e9f6afccb", + "_spec": "ora", + "_where": "/data/dev/Projets/Bingoloto Remote", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/ora/issues" + }, + "bundleDependencies": false, + "dependencies": { + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.4.0", + "is-interactive": "^1.0.0", + "log-symbols": "^4.0.0", + "mute-stream": "0.0.8", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + }, + "deprecated": false, + "description": "Elegant terminal spinner", + "devDependencies": { + "@types/node": "^14.0.27", + "ava": "^2.4.0", + "get-stream": "^5.1.0", + "tsd": "^0.13.1", + "xo": "^0.25.0" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "funding": "https://github.com/sponsors/sindresorhus", + "homepage": "https://github.com/sindresorhus/ora#readme", + "keywords": [ + "cli", + "spinner", + "spinners", + "terminal", + "term", + "console", + "ascii", + "unicode", + "loading", + "indicator", + "progress", + "busy", + "wait", + "idle" + ], + "license": "MIT", + "name": "ora", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/ora.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "5.0.0" +} diff --git a/node_modules/ora/readme.md b/node_modules/ora/readme.md new file mode 100644 index 0000000..d2f0447 --- /dev/null +++ b/node_modules/ora/readme.md @@ -0,0 +1,256 @@ +# ora [![Build Status](https://travis-ci.com/sindresorhus/ora.svg?branch=master)](https://travis-ci.com/github/sindresorhus/ora) + +> Elegant terminal spinner + +<p align="center"> + <br> + <img src="screenshot.svg" width="500"> + <br> +</p> + +## Install + +``` +$ npm install ora +``` + +## Usage + +```js +const ora = require('ora'); + +const spinner = ora('Loading unicorns').start(); + +setTimeout(() => { + spinner.color = 'yellow'; + spinner.text = 'Loading rainbows'; +}, 1000); +``` + +## API + +### ora(text) +### ora(options) + +If a string is provided, it is treated as a shortcut for [`options.text`](#text). + +#### options + +Type: `object` + +##### text + +Type: `string` + +Text to display after the spinner. + +##### prefixText + +Type: `string` + +Text to display before the spinner. No prefix text will be displayed if set to an empty string. + +##### spinner + +Type: `string | object`\ +Default: `'dots'` <img src="screenshot-spinner.gif" width="14"> + +Name of one of the [provided spinners](https://github.com/sindresorhus/cli-spinners/blob/master/spinners.json). See `example.js` in this repo if you want to test out different spinners. On Windows, it will always use the `line` spinner as the Windows command-line doesn't have proper Unicode support. + +Or an object like: + +```js +{ + interval: 80, // Optional + frames: ['-', '+', '-'] +} +``` + +##### color + +Type: `string`\ +Default: `'cyan'`\ +Values: `'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray'` + +Color of the spinner. + +##### hideCursor + +Type: `boolean`\ +Default: `true` + +Set to `false` to stop Ora from hiding the cursor. + +##### indent + +Type: `number`\ +Default: `0` + +Indent the spinner with the given number of spaces. + +##### interval + +Type: `number`\ +Default: Provided by the spinner or `100` + +Interval between each frame. + +Spinners provide their own recommended interval, so you don't really need to specify this. + +##### stream + +Type: `stream.Writable`\ +Default: `process.stderr` + +Stream to write the output. + +You could for example set this to `process.stdout` instead. + +##### isEnabled + +Type: `boolean` + +Force enable/disable the spinner. If not specified, the spinner will be enabled if the `stream` is being run inside a TTY context (not spawned or piped) and/or not in a CI environment. + +Note that `{isEnabled: false}` doesn't mean it won't output anything. It just means it won't output the spinner, colors, and other ansi escape codes. It will still log text. + +##### discardStdin + +Type: `boolean`\ +Default: `true` + +Discard stdin input (except Ctrl+C) while running if it's TTY. This prevents the spinner from twitching on input, outputting broken lines on <kbd>Enter</kbd> key presses, and prevents buffering of input while the spinner is running. + +This has no effect on Windows as there's no good way to implement discarding stdin properly there. + +### Instance + +#### .start(text?) + +Start the spinner. Returns the instance. Set the current text if `text` is provided. + +#### .stop() + +Stop and clear the spinner. Returns the instance. + +#### .succeed(text?) + +Stop the spinner, change it to a green `✔` and persist the current text, or `text` if provided. Returns the instance. See the GIF below. + +#### .fail(text?) + +Stop the spinner, change it to a red `✖` and persist the current text, or `text` if provided. Returns the instance. See the GIF below. + +#### .warn(text?) + +Stop the spinner, change it to a yellow `⚠` and persist the current text, or `text` if provided. Returns the instance. + +#### .info(text?) + +Stop the spinner, change it to a blue `ℹ` and persist the current text, or `text` if provided. Returns the instance. + +#### .isSpinning + +A boolean of whether the instance is currently spinning. + +#### .stopAndPersist(options?) + +Stop the spinner and change the symbol or text. Returns the instance. See the GIF below. + +##### options + +Type: `object` + +###### symbol + +Type: `string`\ +Default: `' '` + +Symbol to replace the spinner with. + +###### text + +Type: `string`\ +Default: Current `'text'` + +Text to be persisted after the symbol + +###### prefixText + +Type: `string`\ +Default: Current `prefixText` + +Text to be persisted before the symbol. No prefix text will be displayed if set to an empty string. + +<img src="screenshot-2.gif" width="480"> + +#### .clear() + +Clear the spinner. Returns the instance. + +#### .render() + +Manually render a new frame. Returns the instance. + +#### .frame() + +Get a new frame. + +#### .text + +Change the text after the spinner. + +#### .prefixText + +Change the text before the spinner. No prefix text will be displayed if set to an empty string. + +#### .color + +Change the spinner color. + +#### .spinner + +Change the spinner. + +#### .indent + +Change the spinner indent. + +### ora.promise(action, text) +### ora.promise(action, options) + +Starts a spinner for a promise. The spinner is stopped with `.succeed()` if the promise fulfills or with `.fail()` if it rejects. Returns the spinner instance. + +#### action + +Type: `Promise` + +## FAQ + +### How do I change the color of the text? + +Use [Chalk](https://github.com/chalk/chalk): + +```js +const ora = require('ora'); +const chalk = require('chalk'); + +const spinner = ora(`Loading ${chalk.red('unicorns')}`).start(); +``` + +### Why does the spinner freeze? + +JavaScript is single-threaded, so synchronous operations blocks the thread, including the spinner animation. Prefer asynchronous operations whenever possible. + +## Related + +- [cli-spinners](https://github.com/sindresorhus/cli-spinners) - Spinners for use in the terminal +- [listr](https://github.com/SamVerschueren/listr) - Terminal task list +- [CLISpinner](https://github.com/kiliankoe/CLISpinner) - Terminal spinner library for Swift +- [halo](https://github.com/ManrajGrover/halo) - Python port +- [spinners](https://github.com/FGRibreau/spinners) - Terminal spinners for Rust +- [marquee-ora](https://github.com/joeycozza/marquee-ora) - Scrolling marquee spinner for Ora +- [briandowns/spinner](https://github.com/briandowns/spinner) - Terminal spinner/progress indicator for Go +- [tj/go-spin](https://github.com/tj/go-spin) - Terminal spinner package for Go +- [observablehq.com/@victordidenko/ora](https://observablehq.com/@victordidenko/ora) - Ora port to Observable notebooks +- [spinnies](https://github.com/jcarpanelli/spinnies) - Terminal multi-spinner library for Node.js diff --git a/node_modules/path-is-absolute/index.js b/node_modules/path-is-absolute/index.js new file mode 100644 index 0000000..22aa6c3 --- /dev/null +++ b/node_modules/path-is-absolute/index.js @@ -0,0 +1,20 @@ +'use strict'; + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; diff --git a/node_modules/path-is-absolute/license b/node_modules/path-is-absolute/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/path-is-absolute/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/path-is-absolute/package.json b/node_modules/path-is-absolute/package.json new file mode 100644 index 0000000..c2611f7 --- /dev/null +++ b/node_modules/path-is-absolute/package.json @@ -0,0 +1,75 @@ +{ + "_from": "path-is-absolute@^1.0.0", + "_id": "path-is-absolute@1.0.1", + "_inBundle": false, + "_integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "_location": "/path-is-absolute", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "path-is-absolute@^1.0.0", + "name": "path-is-absolute", + "escapedName": "path-is-absolute", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "_shasum": "174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f", + "_spec": "path-is-absolute@^1.0.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/glob", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/path-is-absolute/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Node.js 0.12 path.isAbsolute() ponyfill", + "devDependencies": { + "xo": "^0.16.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/path-is-absolute#readme", + "keywords": [ + "path", + "paths", + "file", + "dir", + "absolute", + "isabsolute", + "is-absolute", + "built-in", + "util", + "utils", + "core", + "ponyfill", + "polyfill", + "shim", + "is", + "detect", + "check" + ], + "license": "MIT", + "name": "path-is-absolute", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/path-is-absolute.git" + }, + "scripts": { + "test": "xo && node test.js" + }, + "version": "1.0.1" +} diff --git a/node_modules/path-is-absolute/readme.md b/node_modules/path-is-absolute/readme.md new file mode 100644 index 0000000..8dbdf5f --- /dev/null +++ b/node_modules/path-is-absolute/readme.md @@ -0,0 +1,59 @@ +# path-is-absolute [![Build Status](https://travis-ci.org/sindresorhus/path-is-absolute.svg?branch=master)](https://travis-ci.org/sindresorhus/path-is-absolute) + +> Node.js 0.12 [`path.isAbsolute()`](http://nodejs.org/api/path.html#path_path_isabsolute_path) [ponyfill](https://ponyfill.com) + + +## Install + +``` +$ npm install --save path-is-absolute +``` + + +## Usage + +```js +const pathIsAbsolute = require('path-is-absolute'); + +// Running on Linux +pathIsAbsolute('/home/foo'); +//=> true +pathIsAbsolute('C:/Users/foo'); +//=> false + +// Running on Windows +pathIsAbsolute('C:/Users/foo'); +//=> true +pathIsAbsolute('/home/foo'); +//=> false + +// Running on any OS +pathIsAbsolute.posix('/home/foo'); +//=> true +pathIsAbsolute.posix('C:/Users/foo'); +//=> false +pathIsAbsolute.win32('C:/Users/foo'); +//=> true +pathIsAbsolute.win32('/home/foo'); +//=> false +``` + + +## API + +See the [`path.isAbsolute()` docs](http://nodejs.org/api/path.html#path_path_isabsolute_path). + +### pathIsAbsolute(path) + +### pathIsAbsolute.posix(path) + +POSIX specific version. + +### pathIsAbsolute.win32(path) + +Windows specific version. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/pkginfo/.npmignore b/node_modules/pkginfo/.npmignore new file mode 100644 index 0000000..9303c34 --- /dev/null +++ b/node_modules/pkginfo/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log
\ No newline at end of file diff --git a/node_modules/pkginfo/LICENSE b/node_modules/pkginfo/LICENSE new file mode 100644 index 0000000..ed4a4e7 --- /dev/null +++ b/node_modules/pkginfo/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Charlie Robbins. + +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/pkginfo/README.md b/node_modules/pkginfo/README.md new file mode 100644 index 0000000..97d7a7f --- /dev/null +++ b/node_modules/pkginfo/README.md @@ -0,0 +1,80 @@ +# node-pkginfo + +An easy way to expose properties on a module from a package.json + +### Installing pkginfo +``` + npm install pkginfo +``` + +## Motivation +How often when writing node.js modules have you written the following line(s) of code? + +* Hard code your version string into your code + +``` js + exports.version = '0.1.0'; +``` + +* Programmatically expose the version from the package.json + +``` js + exports.version = require('/path/to/package.json').version; +``` + +In other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!** + +## Usage + +Using `pkginfo` is idiot-proof, just require and invoke it. + +``` js + var pkginfo = require('pkginfo')(module); + + console.dir(module.exports); +``` + +By invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). + +Here's a sample of the output: + +``` + { name: 'simple-app', + description: 'A test fixture for pkginfo', + version: '0.1.0', + author: 'Charlie Robbins <charlie.robbins@gmail.com>', + keywords: [ 'test', 'fixture' ], + main: './index.js', + scripts: { test: 'vows test/*-test.js --spec' }, + engines: { node: '>= 0.4.0' } } +``` + +### Expose specific properties +If you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function: + +``` js + var pkginfo = require('pkginfo')(module, 'version', 'author'); + + console.dir(module.exports); +``` + +``` + { version: '0.1.0', + author: 'Charlie Robbins <charlie.robbins@gmail.com>' } +``` + +If you're looking for further usage see the [examples][0] included in this repository. + +## Run Tests +Tests are written in [vows][1] and give complete coverage of all APIs. + +``` + npm install + npm test +``` + +[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples +[1]: http://vowsjs.org + +#### Author: [Charlie Robbins](http://github.com/indexzero) +#### License: MIT diff --git a/node_modules/pkginfo/examples/all-properties.js b/node_modules/pkginfo/examples/all-properties.js new file mode 100644 index 0000000..fd1d831 --- /dev/null +++ b/node_modules/pkginfo/examples/all-properties.js @@ -0,0 +1,19 @@ +/* + * all-properties.js: Sample of including all properties from a package.json file + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + pkginfo = require('../lib/pkginfo')(module); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/pkginfo/examples/array-argument.js b/node_modules/pkginfo/examples/array-argument.js new file mode 100644 index 0000000..b1b6848 --- /dev/null +++ b/node_modules/pkginfo/examples/array-argument.js @@ -0,0 +1,20 @@ +/* + * array-argument.js: Sample of including specific properties from a package.json file + * using Array argument syntax. + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + pkginfo = require('../lib/pkginfo')(module, ['version', 'author']); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/pkginfo/examples/multiple-properties.js b/node_modules/pkginfo/examples/multiple-properties.js new file mode 100644 index 0000000..b4b5fd6 --- /dev/null +++ b/node_modules/pkginfo/examples/multiple-properties.js @@ -0,0 +1,19 @@ +/* + * multiple-properties.js: Sample of including multiple properties from a package.json file + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + pkginfo = require('../lib/pkginfo')(module, 'version', 'author'); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/pkginfo/examples/object-argument.js b/node_modules/pkginfo/examples/object-argument.js new file mode 100644 index 0000000..28420c8 --- /dev/null +++ b/node_modules/pkginfo/examples/object-argument.js @@ -0,0 +1,22 @@ +/* + * object-argument.js: Sample of including specific properties from a package.json file + * using Object argument syntax. + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + pkginfo = require('../lib/pkginfo')(module, { + include: ['version', 'author'] + }); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/pkginfo/examples/package.json b/node_modules/pkginfo/examples/package.json new file mode 100644 index 0000000..1f2f01c --- /dev/null +++ b/node_modules/pkginfo/examples/package.json @@ -0,0 +1,10 @@ +{ + "name": "simple-app", + "description": "A test fixture for pkginfo", + "version": "0.1.0", + "author": "Charlie Robbins <charlie.robbins@gmail.com>", + "keywords": ["test", "fixture"], + "main": "./index.js", + "scripts": { "test": "vows test/*-test.js --spec" }, + "engines": { "node": ">= 0.4.0" } +} diff --git a/node_modules/pkginfo/examples/single-property.js b/node_modules/pkginfo/examples/single-property.js new file mode 100644 index 0000000..4f44561 --- /dev/null +++ b/node_modules/pkginfo/examples/single-property.js @@ -0,0 +1,19 @@ +/* + * single-property.js: Sample of including a single specific properties from a package.json file + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + pkginfo = require('../lib/pkginfo')(module, 'version'); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/pkginfo/examples/subdir/package.json b/node_modules/pkginfo/examples/subdir/package.json new file mode 100644 index 0000000..aa85410 --- /dev/null +++ b/node_modules/pkginfo/examples/subdir/package.json @@ -0,0 +1,11 @@ +{ + "name": "simple-app-subdir", + "description": "A test fixture for pkginfo", + "version": "0.1.0", + "author": "Charlie Robbins <charlie.robbins@gmail.com>", + "keywords": ["test", "fixture"], + "main": "./index.js", + "scripts": { "test": "vows test/*-test.js --spec" }, + "engines": { "node": ">= 0.4.0" }, + "subdironly": "true" +} diff --git a/node_modules/pkginfo/examples/target-dir.js b/node_modules/pkginfo/examples/target-dir.js new file mode 100644 index 0000000..88770e6 --- /dev/null +++ b/node_modules/pkginfo/examples/target-dir.js @@ -0,0 +1,20 @@ +/* + * multiple-properties.js: Sample of including multiple properties from a package.json file + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + path = require('path'), + pkginfo = require('../lib/pkginfo')(module, { dir: path.resolve(__dirname, 'subdir' )}); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/pkginfo/lib/pkginfo.js b/node_modules/pkginfo/lib/pkginfo.js new file mode 100644 index 0000000..47ab248 --- /dev/null +++ b/node_modules/pkginfo/lib/pkginfo.js @@ -0,0 +1,133 @@ +/* + * pkginfo.js: Top-level include for the pkginfo module + * + * (C) 2011, Charlie Robbins + * + */ + +var path = require('path'); + +// +// ### function pkginfo ([options, 'property', 'property' ..]) +// #### @pmodule {Module} Parent module to read from. +// #### @options {Object|Array|string} **Optional** Options used when exposing properties. +// #### @arguments {string...} **Optional** Specified properties to expose. +// Exposes properties from the package.json file for the parent module on +// it's exports. Valid usage: +// +// `require('pkginfo')()` +// +// `require('pkginfo')('version', 'author');` +// +// `require('pkginfo')(['version', 'author']);` +// +// `require('pkginfo')({ include: ['version', 'author'] });` +// +var pkginfo = module.exports = function (pmodule, options) { + var args = [].slice.call(arguments, 2).filter(function (arg) { + return typeof arg === 'string'; + }); + + // + // **Parse variable arguments** + // + if (Array.isArray(options)) { + // + // If the options passed in is an Array assume that + // it is the Array of properties to expose from the + // on the package.json file on the parent module. + // + options = { include: options }; + } + else if (typeof options === 'string') { + // + // Otherwise if the first argument is a string, then + // assume that it is the first property to expose from + // the package.json file on the parent module. + // + options = { include: [options] }; + } + + // + // **Setup default options** + // + options = options || {}; + + // ensure that includes have been defined + options.include = options.include || []; + + if (args.length > 0) { + // + // If additional string arguments have been passed in + // then add them to the properties to expose on the + // parent module. + // + options.include = options.include.concat(args); + } + + var pkg = pkginfo.read(pmodule, options.dir).package; + Object.keys(pkg).forEach(function (key) { + if (options.include.length > 0 && !~options.include.indexOf(key)) { + return; + } + + if (!pmodule.exports[key]) { + pmodule.exports[key] = pkg[key]; + } + }); + + return pkginfo; +}; + +// +// ### function find (dir) +// #### @pmodule {Module} Parent module to read from. +// #### @dir {string} **Optional** Directory to start search from. +// Searches up the directory tree from `dir` until it finds a directory +// which contains a `package.json` file. +// +pkginfo.find = function (pmodule, dir) { + if (! dir) { + dir = path.dirname(pmodule.filename || pmodule.id); + } + + if (dir === path.dirname(dir)) { + throw new Error('Could not find package.json up from ' + + (pmodule.filename || pmodule.id)); + } + else if (!dir || dir === '.') { + throw new Error('Cannot find package.json from unspecified directory'); + } + + var contents; + try { + contents = require(dir + '/package.json'); + } catch (error) {} + + if (contents) return contents; + + return pkginfo.find(pmodule, path.dirname(dir)); +}; + +// +// ### function read (pmodule, dir) +// #### @pmodule {Module} Parent module to read from. +// #### @dir {string} **Optional** Directory to start search from. +// Searches up the directory tree from `dir` until it finds a directory +// which contains a `package.json` file and returns the package information. +// +pkginfo.read = function (pmodule, dir) { + return { + dir: dir, + package: pkginfo.find(pmodule, dir), + }; +}; + +// +// Call `pkginfo` on this module and expose version. +// +pkginfo(module, { + dir: __dirname, + include: ['version'], + target: pkginfo +}); diff --git a/node_modules/pkginfo/package.json b/node_modules/pkginfo/package.json new file mode 100644 index 0000000..acb13c4 --- /dev/null +++ b/node_modules/pkginfo/package.json @@ -0,0 +1,58 @@ +{ + "_from": "pkginfo@0.x.x", + "_id": "pkginfo@0.4.1", + "_inBundle": false, + "_integrity": "sha1-tUGO8EOd5UJfxJlQQtztFPsqhP8=", + "_location": "/pkginfo", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "pkginfo@0.x.x", + "name": "pkginfo", + "escapedName": "pkginfo", + "rawSpec": "0.x.x", + "saveSpec": null, + "fetchSpec": "0.x.x" + }, + "_requiredBy": [ + "/prompt" + ], + "_resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.4.1.tgz", + "_shasum": "b5418ef0439de5425fc4995042dced14fb2a84ff", + "_spec": "pkginfo@0.x.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/prompt", + "author": { + "name": "Charlie Robbins", + "email": "charlie.robbins@gmail.com" + }, + "bugs": { + "url": "https://github.com/indexzero/node-pkginfo/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "An easy way to expose properties on a module from a package.json", + "devDependencies": { + "vows": "0.8.0" + }, + "engines": { + "node": ">= 0.4.0" + }, + "homepage": "https://github.com/indexzero/node-pkginfo#readme", + "keywords": [ + "info", + "tools", + "package.json" + ], + "license": "MIT", + "main": "./lib/pkginfo.js", + "name": "pkginfo", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indexzero/node-pkginfo.git" + }, + "scripts": { + "test": "vows test/*-test.js --spec" + }, + "version": "0.4.1" +} diff --git a/node_modules/pkginfo/test/pkginfo-test.js b/node_modules/pkginfo/test/pkginfo-test.js new file mode 100644 index 0000000..a59f077 --- /dev/null +++ b/node_modules/pkginfo/test/pkginfo-test.js @@ -0,0 +1,83 @@ +/* + * pkginfo-test.js: Tests for the pkginfo module. + * + * (C) 2011, Charlie Robbins + * + */ + +var assert = require('assert'), + exec = require('child_process').exec, + fs = require('fs'), + path = require('path'), + vows = require('vows'), + pkginfo = require('../lib/pkginfo'); + +function assertProperties (source, target) { + assert.lengthOf(source, target.length + 1); + target.forEach(function (prop) { + assert.isTrue(!!~source.indexOf(prop)); + }); +} + +function compareWithExample(targetPath) { + var examplePaths = ['package.json']; + + if (targetPath) { + examplePaths.unshift(targetPath); + } + + return function(exposed) { + var pkg = fs.readFileSync(path.join.apply(null, [__dirname, '..', 'examples'].concat(examplePaths))).toString(), + keys = Object.keys(JSON.parse(pkg)); + + assertProperties(exposed, keys); + }; +} + +function testExposes (options) { + return { + topic: function () { + exec('node ' + path.join(__dirname, '..', 'examples', options.script), this.callback); + }, + "should expose that property correctly": function (err, stdout, stderr) { + assert.isNull(err); + + var exposed = stderr.match(/'(\w+)'/ig).map(function (p) { + return p.substring(1, p.length - 1); + }); + + return !options.assert + ? assertProperties(exposed, options.properties) + : options.assert(exposed); + } + } +} + +vows.describe('pkginfo').addBatch({ + "When using the pkginfo module": { + "and passed a single `string` argument": testExposes({ + script: 'single-property.js', + properties: ['version'] + }), + "and passed multiple `string` arguments": testExposes({ + script: 'multiple-properties.js', + properties: ['version', 'author'] + }), + "and passed an `object` argument": testExposes({ + script: 'object-argument.js', + properties: ['version', 'author'] + }), + "and passed an `array` argument": testExposes({ + script: 'array-argument.js', + properties: ['version', 'author'] + }), + "and read from a specified directory": testExposes({ + script: 'target-dir.js', + assert: compareWithExample('subdir') + }), + "and passed no arguments": testExposes({ + script: 'all-properties.js', + assert: compareWithExample() + }) + } +}).export(module); diff --git a/node_modules/prompt/.jshintrc b/node_modules/prompt/.jshintrc new file mode 100644 index 0000000..0d97986 --- /dev/null +++ b/node_modules/prompt/.jshintrc @@ -0,0 +1,54 @@ +{ + "passfail": false, + "maxerr": 100, + + "browser": false, + "node": true, + "rhino": false, + "couch": true, + "wsh": true, + "jquery": true, + "prototypejs": false, + "mootools": false, + "dojo": false, + + "devel": false, + + "es5": true, + "strict": false, + "globalstrict": false, + + "asi": false, + "lastsemic": true, + "laxbreak": true, + "laxcomma": false, + "bitwise": false, + "boss": false, + "curly": true, + "eqeqeq": true, + "eqnull": false, + "evil": false, + "expr": false, + "forin": false, + "immed": false, + "latedef": false, + "loopfunc": true, + "noarg": true, + "regexp": true, + "regexdash": false, + "scripturl": true, + "shadow": true, + "supernew": true, + "undef": true, + + "newcap": true, + "noempty": true, + "nonew": true, + "nomen": false, + "onevar": true, + "plusplus": false, + "sub": true, + "trailing": true, + "white": false, + "indent": 2 +}
\ No newline at end of file diff --git a/node_modules/prompt/.npmignore b/node_modules/prompt/.npmignore new file mode 100644 index 0000000..e3bc275 --- /dev/null +++ b/node_modules/prompt/.npmignore @@ -0,0 +1,3 @@ +node_modules/ +node_modules/* +npm-debug.log
\ No newline at end of file diff --git a/node_modules/prompt/.travis.yml b/node_modules/prompt/.travis.yml new file mode 100644 index 0000000..9473f32 --- /dev/null +++ b/node_modules/prompt/.travis.yml @@ -0,0 +1,8 @@ +language: node_js +node_js: + - "node" + - "0.12" + - "4" + - "5" + +sudo: false diff --git a/node_modules/prompt/CHANGELOG.md b/node_modules/prompt/CHANGELOG.md new file mode 100644 index 0000000..b094c48 --- /dev/null +++ b/node_modules/prompt/CHANGELOG.md @@ -0,0 +1,13 @@ + +0.2.7 / 2012-08-30 +================== + + * Fixed handling of numeric inputs with parseFloat + * Fixed overwriting of non-string inputs + * Added support for boolean types + +0.2.6 / 2012-08-12 +================== + + * Added allowance of empty default values + diff --git a/node_modules/prompt/LICENSE b/node_modules/prompt/LICENSE new file mode 100644 index 0000000..56217ca --- /dev/null +++ b/node_modules/prompt/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Nodejitsu Inc. + +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/prompt/README.md b/node_modules/prompt/README.md new file mode 100644 index 0000000..2fb9ffb --- /dev/null +++ b/node_modules/prompt/README.md @@ -0,0 +1,444 @@ +# prompt [![Build Status](https://secure.travis-ci.org/flatiron/prompt.svg)](http://travis-ci.org/flatiron/prompt) + +A beautiful command-line prompt for node.js + +## Features + +* prompts the user for input +* supports validation and defaults +* hides passwords + +## Usage +Using prompt is relatively straight forward. There are two core methods you should be aware of: `prompt.get()` and `prompt.addProperties()`. Their methods take strings representing property names in addition to objects for complex property validation (and more). There are a number of [examples][0] that you should examine for detailed usage. + +### Getting Basic Prompt Information +Getting started with `prompt` is easy. Lets take a look at `examples/simple-prompt.js`: + +``` js + var prompt = require('prompt'); + + // + // Start the prompt + // + prompt.start(); + + // + // Get two properties from the user: username and email + // + prompt.get(['username', 'email'], function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' username: ' + result.username); + console.log(' email: ' + result.email); + }); +``` + +This will result in the following command-line output: + +``` + $ node examples/simple-prompt.js + prompt: username: some-user + prompt: email: some-user@some-place.org + Command-line input received: + username: some-user + email: some-user@some-place.org +``` + +### Prompting with Validation, Default Values, and More (Complex Properties) +In addition to prompting the user with simple string prompts, there is a robust API for getting and validating complex information from a command-line prompt. Here's a quick sample: + +``` js + var schema = { + properties: { + name: { + pattern: /^[a-zA-Z\s\-]+$/, + message: 'Name must be only letters, spaces, or dashes', + required: true + }, + password: { + hidden: true + } + } + }; + + // + // Start the prompt + // + prompt.start(); + + // + // Get two properties from the user: email, password + // + prompt.get(schema, function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' name: ' + result.name); + console.log(' password: ' + result.password); + }); +``` + +Pretty easy right? The output from the above script is: + +``` + $ node examples/property-prompt.js + prompt: name: nodejitsu000 + error: Invalid input for name + error: Name must be only letters, spaces, or dashes + prompt: name: Nodejitsu Inc + prompt: password: + Command-line input received: + name: Nodejitsu Inc + password: some-password +``` + +## Valid Property Settings +`prompt` understands JSON-schema with a few extra parameters and uses [revalidator](https://github.com/flatiron/revalidator) for validation. + +Here's an overview of the properties that may be used for validation and prompting controls: + +``` js + { + description: 'Enter your password', // Prompt displayed to the user. If not supplied name will be used. + type: 'string', // Specify the type of input to expect. + pattern: /^\w+$/, // Regular expression that input must be valid against. + message: 'Password must be letters', // Warning message to display if validation fails. + hidden: true, // If true, characters entered will either not be output to console or will be outputed using the `replace` string. + replace: '*', // If `hidden` is set it will replace each hidden character with the specified string. + default: 'lamepassword', // Default value to use if no value is entered. + required: true // If true, value entered must be non-empty. + before: function(value) { return 'v' + value; } // Runs before node-prompt callbacks. It modifies user's input + } +``` + +Alternatives to `pattern` include `format` and `conform`, as documented in [revalidator](https://github.com/flatiron/revalidator). + +Supported types are `string`, `boolean`, `number`, `integer`, `array` + +Using `type: 'boolean'` accepts case insensitive values 'true', 't', 'false', 'f' + +Using `type: 'array'` has some special cases. + +- `description` will not work in the schema if `type: 'array'` is defined. +- `maxItems` takes precedence over `minItems`. +- Arrays that do not have `maxItems` defined will require users to `SIGINT` (`^C`) before the array is ended. +- If `SIGINT` (`^C`) is triggered before `minItems` is met, a validation error will appear. This will require users to `SIGEOF` (`^D`) to end the input. + +For more information on things such as `maxItems` and `minItems`, refer to the [revalidator](https://github.com/flatiron/revalidator) repository. + +### Alternate Validation API: + +Prompt, in addition to iterating over JSON-Schema properties, will also happily iterate over an array of validation objects given an extra 'name' property: + +```js + var prompt = require('../lib/prompt'); + + // + // Start the prompt + // + prompt.start(); + + // + // Get two properties from the user: username and password + // + prompt.get([{ + name: 'username', + required: true + }, { + name: 'password', + hidden: true, + conform: function (value) { + return true; + } + }], function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' username: ' + result.username); + console.log(' password: ' + result.password); + }); +``` + +### Backward Compatibility + +Note that, while this structure is similar to that used by prompt 0.1.x, that the object properties use the same names as in JSON-Schema. prompt 0.2.x is backward compatible with prompt 0.1.x except for asynchronous validation. + +### Skipping Prompts + +Sometimes power users may wish to skip prompts and specify all data as command line options. +if a value is set as a property of `prompt.override` prompt will use that instead of +prompting the user. + +``` js + //prompt-override.js + + var prompt = require('prompt'), + optimist = require('optimist') + + // + // set the overrides + // + prompt.override = optimist.argv + + // + // Start the prompt + // + prompt.start(); + + // + // Get two properties from the user: username and email + // + prompt.get(['username', 'email'], function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' username: ' + result.username); + console.log(' email: ' + result.email); + }) + + //: node prompt-override.js --username USER --email EMAIL +``` + +It is also possible to skip prompts dynamically based on previous prompts. +If an `ask` method is added, prompt will use it to determine if the prompt should be displayed. +If `ask` returns true the prompt is displayed. otherwise, the default value or empty string are used. + +``` js + var schema = { + properties: { + proxy: { + description: 'Proxy url', + }, + proxyCredentials: { + description: 'Proxy credentials', + ask: function() { + // only ask for proxy credentials if a proxy was set + return prompt.history('proxy').value > 0; + } + } + } + }; + + // + // Start the prompt + // + prompt.start(); + + // + // Get one or two properties from the user, depending on + // what the user answered for proxy + // + prompt.get(schema, function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' proxy: ' + result.proxy); + console.log(' credentials: ' + result.proxyCredentials); + }); +``` + + +### Adding Properties to an Object +A common use-case for prompting users for data from the command-line is to extend or create a configuration object that is passed onto the entry-point method for your CLI tool. `prompt` exposes a convenience method for doing just this: + +``` js + var obj = { + password: 'lamepassword', + mindset: 'NY' + } + + // + // Log the initial object. + // + console.log('Initial object to be extended:'); + console.dir(obj); + + // + // Add two properties to the empty object: username and email + // + prompt.addProperties(obj, ['username', 'email'], function (err) { + // + // Log the results. + // + console.log('Updated object received:'); + console.dir(obj); + }); +``` + +### Prompt history +You can use the `prompt.history()` method to get access to previous prompt input. + +``` js + prompt.get([{ + name: 'name', + description: 'Your name', + type: 'string', + required: true + }, { + name: 'surname', + description: 'Your surname', + type: 'string', + required: true, + message: 'Please dont use the demo credentials', + conform: function(surname) { + var name = prompt.history('name').value; + return (name !== 'John' || surname !== 'Smith'); + } + }], function(err, results) { + console.log(results); + }); +``` + +## Customizing your prompt +Aside from changing `property.message`, you can also change `prompt.message` +and `prompt.delimiter` to change the appearance of your prompt. + +The basic structure of a prompt is this: + +``` js +prompt.message + prompt.delimiter + property.message + prompt.delimiter; +``` + +The default `prompt.message` is "prompt," the default `prompt.delimiter` is +": ", and the default `property.message` is `property.name`. +Changing these allows you to customize the appearance of your prompts! In +addition, prompt supports ANSI color codes via the +[colors module](https://github.com/Marak/colors.js) for custom colors. For a +very colorful example: + +``` js + var prompt = require("prompt"); + var colors = require("colors/safe"); + // + // Setting these properties customizes the prompt. + // + prompt.message = colors.rainbow("Question!"); + prompt.delimiter = colors.green("><"); + + prompt.start(); + + prompt.get({ + properties: { + name: { + description: colors.magenta("What is your name?") + } + } + }, function (err, result) { + console.log(colors.cyan("You said your name is: " + result.name)); + }); +``` + +If you don't want colors, you can set + +```js +var prompt = require('prompt'); + +prompt.colors = false; +``` + +## Integration with streamlinejs + +When integrating prompt with projects using streamlinejs such as the following + +``` +prompt.start(); +function test_prompt(_){ + console.log(prompt.get(loadDataValues(), _).output); +} +test_prompt(_); +``` + +This will work, however the process is then stuck with a stdin stream still open. If you setup the traditional way (with callback) such as this + + ``` +prompt.start(); +function test_prompt(){ + prompt.get(loadDataValues(), function(err, data){ + console.log(data.output); + }); +} +test_prompt(); +``` +This works and ends correctly. + +To resolve this we have added a new method to prompt, which will stop the stdin stream + +``` +// +// ### function stop () +// Stops input coming in from stdin +// +prompt.stop = function () { + if (prompt.stopped || !prompt.started) { + return; + } + + stdin.destroy(); + prompt.emit('stop'); + prompt.stopped = true; + prompt.started = false; + prompt.paused = false; + return prompt; +} +``` + +And you can find an example in the example folder `examples/prompt-streamline.js` + +``` +/* + * prompt-streamline._js: Example of how to use prompt with streamlinejs. + * + * calling syntax: _node prompt-streamline._js + * + */ +var prompt = require('../lib/prompt'); + +function getSampleData(){ + return [ + { + name: 'username', + message: 'Enter a username' + } + ]; +}; + +// +// Start the prompt +// +prompt.start(); + +function get_username_prompt(_){ + console.log(prompt.get(getSampleData(), _).username); +} + +get_username_prompt(_); + +// +// Clean the prompt +// +prompt.stop(); +``` + +## Installation + +``` bash + $ [sudo] npm install prompt +``` + +## Running tests + +``` bash + $ npm test +``` + +#### License: MIT +#### Author: [Charlie Robbins](http://github.com/indexzero) +#### Contributors: [Josh Holbrook](http://github.com/jesusabdullah), [Pavan Kumar Sunkara](http://github.com/pksunkara) + +[0]: https://github.com/flatiron/prompt/tree/master/examples diff --git a/node_modules/prompt/docs/docco.css b/node_modules/prompt/docs/docco.css new file mode 100644 index 0000000..bd54134 --- /dev/null +++ b/node_modules/prompt/docs/docco.css @@ -0,0 +1,194 @@ +/*--------------------- Layout and Typography ----------------------------*/ +body { + font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; + font-size: 15px; + line-height: 22px; + color: #252519; + margin: 0; padding: 0; +} +a { + color: #261a3b; +} + a:visited { + color: #261a3b; + } +p { + margin: 0 0 15px 0; +} +h4, h5, h6 { + color: #333; + margin: 6px 0 6px 0; + font-size: 13px; +} + h2, h3 { + margin-bottom: 0; + color: #000; + } + h1 { + margin-top: 40px; + margin-bottom: 15px; + color: #000; + } +#container { + position: relative; +} +#background { + position: fixed; + top: 0; left: 525px; right: 0; bottom: 0; + background: #f5f5ff; + border-left: 1px solid #e5e5ee; + z-index: -1; +} +#jump_to, #jump_page { + background: white; + -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; + -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; + font: 10px Arial; + text-transform: uppercase; + cursor: pointer; + text-align: right; +} +#jump_to, #jump_wrapper { + position: fixed; + right: 0; top: 0; + padding: 5px 10px; +} + #jump_wrapper { + padding: 0; + display: none; + } + #jump_to:hover #jump_wrapper { + display: block; + } + #jump_page { + padding: 5px 0 3px; + margin: 0 0 25px 25px; + } + #jump_page .source { + display: block; + padding: 5px 10px; + text-decoration: none; + border-top: 1px solid #eee; + } + #jump_page .source:hover { + background: #f5f5ff; + } + #jump_page .source:first-child { + } +table td { + border: 0; + outline: 0; +} + td.docs, th.docs { + max-width: 450px; + min-width: 450px; + min-height: 5px; + padding: 10px 25px 1px 50px; + overflow-x: hidden; + vertical-align: top; + text-align: left; + } + .docs pre { + margin: 15px 0 15px; + padding-left: 15px; + } + .docs p tt, .docs p code { + background: #f8f8ff; + border: 1px solid #dedede; + font-size: 12px; + padding: 0 0.2em; + } + .pilwrap { + position: relative; + } + .pilcrow { + font: 12px Arial; + text-decoration: none; + color: #454545; + position: absolute; + top: 3px; left: -20px; + padding: 1px 2px; + opacity: 0; + -webkit-transition: opacity 0.2s linear; + } + td.docs:hover .pilcrow { + opacity: 1; + } + td.code, th.code { + padding: 14px 15px 16px 25px; + width: 100%; + vertical-align: top; + background: #f5f5ff; + border-left: 1px solid #e5e5ee; + } + pre, tt, code { + font-size: 12px; line-height: 18px; + font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; + margin: 0; padding: 0; + } + + +/*---------------------- Syntax Highlighting -----------------------------*/ +td.linenos { background-color: #f0f0f0; padding-right: 10px; } +span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } +body .hll { background-color: #ffffcc } +body .c { color: #408080; font-style: italic } /* Comment */ +body .err { border: 1px solid #FF0000 } /* Error */ +body .k { color: #954121 } /* Keyword */ +body .o { color: #666666 } /* Operator */ +body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ +body .cp { color: #BC7A00 } /* Comment.Preproc */ +body .c1 { color: #408080; font-style: italic } /* Comment.Single */ +body .cs { color: #408080; font-style: italic } /* Comment.Special */ +body .gd { color: #A00000 } /* Generic.Deleted */ +body .ge { font-style: italic } /* Generic.Emph */ +body .gr { color: #FF0000 } /* Generic.Error */ +body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ +body .gi { color: #00A000 } /* Generic.Inserted */ +body .go { color: #808080 } /* Generic.Output */ +body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ +body .gs { font-weight: bold } /* Generic.Strong */ +body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ +body .gt { color: #0040D0 } /* Generic.Traceback */ +body .kc { color: #954121 } /* Keyword.Constant */ +body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ +body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ +body .kp { color: #954121 } /* Keyword.Pseudo */ +body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ +body .kt { color: #B00040 } /* Keyword.Type */ +body .m { color: #666666 } /* Literal.Number */ +body .s { color: #219161 } /* Literal.String */ +body .na { color: #7D9029 } /* Name.Attribute */ +body .nb { color: #954121 } /* Name.Builtin */ +body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ +body .no { color: #880000 } /* Name.Constant */ +body .nd { color: #AA22FF } /* Name.Decorator */ +body .ni { color: #999999; font-weight: bold } /* Name.Entity */ +body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ +body .nf { color: #0000FF } /* Name.Function */ +body .nl { color: #A0A000 } /* Name.Label */ +body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ +body .nt { color: #954121; font-weight: bold } /* Name.Tag */ +body .nv { color: #19469D } /* Name.Variable */ +body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ +body .w { color: #bbbbbb } /* Text.Whitespace */ +body .mf { color: #666666 } /* Literal.Number.Float */ +body .mh { color: #666666 } /* Literal.Number.Hex */ +body .mi { color: #666666 } /* Literal.Number.Integer */ +body .mo { color: #666666 } /* Literal.Number.Oct */ +body .sb { color: #219161 } /* Literal.String.Backtick */ +body .sc { color: #219161 } /* Literal.String.Char */ +body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ +body .s2 { color: #219161 } /* Literal.String.Double */ +body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ +body .sh { color: #219161 } /* Literal.String.Heredoc */ +body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ +body .sx { color: #954121 } /* Literal.String.Other */ +body .sr { color: #BB6688 } /* Literal.String.Regex */ +body .s1 { color: #219161 } /* Literal.String.Single */ +body .ss { color: #19469D } /* Literal.String.Symbol */ +body .bp { color: #954121 } /* Name.Builtin.Pseudo */ +body .vc { color: #19469D } /* Name.Variable.Class */ +body .vg { color: #19469D } /* Name.Variable.Global */ +body .vi { color: #19469D } /* Name.Variable.Instance */ +body .il { color: #666666 } /* Literal.Number.Integer.Long */
\ No newline at end of file diff --git a/node_modules/prompt/docs/prompt.html b/node_modules/prompt/docs/prompt.html new file mode 100644 index 0000000..7776f5b --- /dev/null +++ b/node_modules/prompt/docs/prompt.html @@ -0,0 +1,296 @@ +<!DOCTYPE html> <html> <head> <title>prompt.js</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" media="all" href="docco.css" /> </head> <body> <div id="container"> <div id="background"></div> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th class="docs"> <h1> prompt.js </h1> </th> <th class="code"> </th> </tr> </thead> <tbody> <tr id="section-1"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-1">¶</a> </div> </td> <td class="code"> <div class="highlight"><pre><span class="cm">/*</span> +<span class="cm"> * prompt.js: Simple prompt for prompting information from the command line </span> +<span class="cm"> *</span> +<span class="cm"> * (C) 2010, Nodejitsu Inc.</span> +<span class="cm"> *</span> +<span class="cm"> */</span> + +<span class="kd">var</span> <span class="nx">events</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'events'</span><span class="p">),</span> + <span class="nx">async</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'async'</span><span class="p">),</span> + <span class="nx">colors</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'colors'</span><span class="p">),</span> + <span class="nx">winston</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'winston'</span><span class="p">),</span> + <span class="nx">stdio</span> <span class="o">=</span> <span class="nx">process</span><span class="p">.</span><span class="nx">binding</span><span class="p">(</span><span class="s1">'stdio'</span><span class="p">);</span></pre></div> </td> </tr> <tr id="section-2"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-2">¶</a> </div> <h3>@private function capitalize (str)</h3> + +<h4>str {string} String to capitalize</h4> + +<p>Capitalizes the string supplied.</p> </td> <td class="code"> <div class="highlight"><pre><span class="kd">function</span> <span class="nx">capitalize</span><span class="p">(</span><span class="nx">str</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span> <span class="nx">str</span><span class="p">.</span><span class="nx">charAt</span><span class="p">(</span><span class="mi">0</span><span class="p">).</span><span class="nx">toUpperCase</span><span class="p">()</span> <span class="o">+</span> <span class="nx">str</span><span class="p">.</span><span class="nx">slice</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> +<span class="p">}</span> + +<span class="kd">var</span> <span class="nx">prompt</span> <span class="o">=</span> <span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="nb">Object</span><span class="p">.</span><span class="nx">create</span><span class="p">(</span><span class="nx">events</span><span class="p">.</span><span class="nx">EventEmitter</span><span class="p">.</span><span class="nx">prototype</span><span class="p">);</span> + +<span class="kd">var</span> <span class="nx">logger</span> <span class="o">=</span> <span class="nx">prompt</span><span class="p">.</span><span class="nx">logger</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">winston</span><span class="p">.</span><span class="nx">Logger</span><span class="p">({</span> + <span class="nx">transports</span><span class="o">:</span> <span class="p">[</span> + <span class="k">new</span> <span class="p">(</span><span class="nx">winston</span><span class="p">.</span><span class="nx">transports</span><span class="p">.</span><span class="nx">Console</span><span class="p">)()</span> + <span class="p">]</span> +<span class="p">});</span> + +<span class="nx">prompt</span><span class="p">.</span><span class="nx">started</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span> +<span class="nx">prompt</span><span class="p">.</span><span class="nx">paused</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span> +<span class="nx">prompt</span><span class="p">.</span><span class="nx">allowEmpty</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span> + +<span class="kd">var</span> <span class="nx">stdin</span><span class="p">,</span> <span class="nx">stdout</span><span class="p">;</span></pre></div> </td> </tr> <tr id="section-3"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-3">¶</a> </div> <p>Create an empty object for the properties +known to <code>prompt</code></p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">prompt</span><span class="p">.</span><span class="nx">properties</span> <span class="o">=</span> <span class="p">{};</span></pre></div> </td> </tr> <tr id="section-4"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-4">¶</a> </div> <p>Setup the default winston logger to use +the <code>cli</code> levels and colors.</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">logger</span><span class="p">.</span><span class="nx">cli</span><span class="p">();</span></pre></div> </td> </tr> <tr id="section-5"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-5">¶</a> </div> <h3>function start (options)</h3> + +<h4>@options {Object} <strong>Optional</strong> Options to consume by prompt</h4> + +<p>Starts the prompt by listening to the appropriate events on <code>options.stdin</code> +and <code>options.stdout</code>. If no streams are supplied, then <code>process.stdin</code> +and <code>process.stdout</code> are used, respectively.</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">prompt</span><span class="p">.</span><span class="nx">start</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">options</span><span class="p">)</span> <span class="p">{</span> + <span class="k">if</span> <span class="p">(</span><span class="nx">prompt</span><span class="p">.</span><span class="nx">started</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span><span class="p">;</span> + <span class="p">}</span> + + <span class="nx">options</span> <span class="o">=</span> <span class="nx">options</span> <span class="o">||</span> <span class="p">{};</span> + <span class="nx">stdin</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">stdin</span> <span class="o">||</span> <span class="nx">process</span><span class="p">.</span><span class="nx">openStdin</span><span class="p">();</span> + <span class="nx">stdout</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">stdout</span> <span class="o">||</span> <span class="nx">process</span><span class="p">.</span><span class="nx">stdout</span><span class="p">;</span> + + <span class="nx">prompt</span><span class="p">.</span><span class="nx">allowEmpty</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">allowEmpty</span> <span class="o">||</span> <span class="kc">false</span><span class="p">;</span> + + <span class="nx">process</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'SIGINT'</span><span class="p">,</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span> + <span class="nx">stdout</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="s1">'\n'</span><span class="p">);</span> + <span class="nx">process</span><span class="p">.</span><span class="nx">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> + <span class="p">})</span> + + <span class="nx">prompt</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'start'</span><span class="p">);</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">started</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span> + <span class="k">return</span> <span class="nx">prompt</span><span class="p">;</span> +<span class="p">};</span></pre></div> </td> </tr> <tr id="section-6"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-6">¶</a> </div> <h3>function pause ()</h3> + +<p>Pauses input coming in from stdin</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">prompt</span><span class="p">.</span><span class="nx">pause</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span> + <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">prompt</span><span class="p">.</span><span class="nx">started</span> <span class="o">||</span> <span class="nx">prompt</span><span class="p">.</span><span class="nx">paused</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span><span class="p">;</span> + <span class="p">}</span> + + <span class="nx">stdin</span><span class="p">.</span><span class="nx">pause</span><span class="p">();</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'pause'</span><span class="p">);</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">paused</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span> + <span class="k">return</span> <span class="nx">prompt</span><span class="p">;</span> +<span class="p">};</span></pre></div> </td> </tr> <tr id="section-7"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-7">¶</a> </div> <h3>function resume ()</h3> + +<p>Resumes input coming in from stdin </p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">prompt</span><span class="p">.</span><span class="nx">resume</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span> + <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">prompt</span><span class="p">.</span><span class="nx">started</span> <span class="o">||</span> <span class="o">!</span><span class="nx">prompt</span><span class="p">.</span><span class="nx">paused</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span><span class="p">;</span> + <span class="p">}</span> + + <span class="nx">stdin</span><span class="p">.</span><span class="nx">resume</span><span class="p">();</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'resume'</span><span class="p">);</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">paused</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span> + <span class="k">return</span> <span class="nx">prompt</span><span class="p">;</span> +<span class="p">};</span></pre></div> </td> </tr> <tr id="section-8"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-8">¶</a> </div> <h3>function get (msg, [validator,] callback)</h3> + +<h4>@msg {Array|Object|string} Set of variables to get input for.</h4> + +<h4>@callback {function} Continuation to pass control to when complete.</h4> + +<p>Gets input from the user via stdin for the specified message(s) <code>msg</code>.</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">prompt</span><span class="p">.</span><span class="nx">get</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">msg</span><span class="p">,</span> <span class="nx">callback</span><span class="p">)</span> <span class="p">{</span> + <span class="kd">var</span> <span class="nx">vars</span> <span class="o">=</span> <span class="o">!</span><span class="nb">Array</span><span class="p">.</span><span class="nx">isArray</span><span class="p">(</span><span class="nx">msg</span><span class="p">)</span> <span class="o">?</span> <span class="p">[</span><span class="nx">msg</span><span class="p">]</span> <span class="o">:</span> <span class="nx">msg</span><span class="p">,</span> + <span class="nx">result</span> <span class="o">=</span> <span class="p">{};</span> + + <span class="nx">vars</span> <span class="o">=</span> <span class="nx">vars</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">v</span><span class="p">)</span> <span class="p">{</span> + <span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nx">v</span> <span class="o">===</span> <span class="s1">'string'</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">v</span> <span class="o">=</span> <span class="nx">v</span><span class="p">.</span><span class="nx">toLowerCase</span><span class="p">();</span> + <span class="p">}</span> + + <span class="k">return</span> <span class="nx">prompt</span><span class="p">.</span><span class="nx">properties</span><span class="p">[</span><span class="nx">v</span><span class="p">]</span> <span class="o">||</span> <span class="nx">v</span><span class="p">;</span> + <span class="p">});</span> + + <span class="kd">function</span> <span class="nx">get</span><span class="p">(</span><span class="nx">target</span><span class="p">,</span> <span class="nx">next</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">getInput</span><span class="p">(</span><span class="nx">target</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">line</span><span class="p">)</span> <span class="p">{</span> + <span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span> <span class="nx">next</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span> + <span class="p">}</span> + + <span class="kd">var</span> <span class="nx">name</span> <span class="o">=</span> <span class="nx">target</span><span class="p">.</span><span class="nx">name</span> <span class="o">||</span> <span class="nx">target</span><span class="p">;</span> + <span class="nx">result</span><span class="p">[</span><span class="nx">name</span><span class="p">]</span> <span class="o">=</span> <span class="nx">line</span><span class="p">;</span> + <span class="nx">next</span><span class="p">();</span> + <span class="p">});</span> + <span class="p">}</span> + + <span class="nx">async</span><span class="p">.</span><span class="nx">forEachSeries</span><span class="p">(</span><span class="nx">vars</span><span class="p">,</span> <span class="nx">get</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span> <span class="nx">err</span> <span class="o">?</span> <span class="nx">callback</span><span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="o">:</span> <span class="nx">callback</span><span class="p">(</span><span class="kc">null</span><span class="p">,</span> <span class="nx">result</span><span class="p">);</span> + <span class="p">});</span> + + <span class="k">return</span> <span class="nx">prompt</span><span class="p">;</span> +<span class="p">};</span></pre></div> </td> </tr> <tr id="section-9"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-9">¶</a> </div> <h3>function getInput (msg, validator, callback)</h3> + +<h4>@msg {Object|string} Variable to get input for.</h4> + +<h4>@callback {function} Continuation to pass control to when complete.</h4> + +<p>Gets input from the user via stdin for the specified message <code>msg</code>.</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">prompt</span><span class="p">.</span><span class="nx">getInput</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">prop</span><span class="p">,</span> <span class="nx">callback</span><span class="p">)</span> <span class="p">{</span> + <span class="kd">var</span> <span class="nx">name</span> <span class="o">=</span> <span class="nx">prop</span><span class="p">.</span><span class="nx">message</span> <span class="o">||</span> <span class="nx">prop</span><span class="p">.</span><span class="nx">name</span> <span class="o">||</span> <span class="nx">prop</span><span class="p">,</span> + <span class="nx">raw</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'prompt'</span><span class="p">,</span> <span class="s1">': '</span> <span class="o">+</span> <span class="nx">name</span><span class="p">.</span><span class="nx">grey</span><span class="p">,</span> <span class="s1">': '</span><span class="p">.</span><span class="nx">grey</span><span class="p">],</span> + <span class="nx">read</span> <span class="o">=</span> <span class="nx">prop</span><span class="p">.</span><span class="nx">hidden</span> <span class="o">?</span> <span class="nx">prompt</span><span class="p">.</span><span class="nx">readLineHidden</span> <span class="o">:</span> <span class="nx">prompt</span><span class="p">.</span><span class="nx">readLine</span><span class="p">,</span> + <span class="nx">length</span><span class="p">,</span> <span class="nx">msg</span><span class="p">;</span> + + <span class="k">if</span> <span class="p">(</span><span class="nx">prop</span><span class="p">.</span><span class="k">default</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">raw</span><span class="p">.</span><span class="nx">splice</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="s1">' ('</span> <span class="o">+</span> <span class="nx">prop</span><span class="p">.</span><span class="k">default</span> <span class="o">+</span> <span class="s1">')'</span><span class="p">);</span> + <span class="p">}</span> + </pre></div> </td> </tr> <tr id="section-10"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-10">¶</a> </div> <p>Calculate the raw length and colorize the prompt</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">length</span> <span class="o">=</span> <span class="nx">raw</span><span class="p">.</span><span class="nx">join</span><span class="p">(</span><span class="s1">''</span><span class="p">).</span><span class="nx">length</span><span class="p">;</span> + <span class="nx">raw</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="nx">raw</span><span class="p">[</span><span class="mi">0</span><span class="p">];</span> + <span class="nx">msg</span> <span class="o">=</span> <span class="nx">raw</span><span class="p">.</span><span class="nx">join</span><span class="p">(</span><span class="s1">''</span><span class="p">);</span> + + <span class="k">if</span> <span class="p">(</span><span class="nx">prop</span><span class="p">.</span><span class="nx">help</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">prop</span><span class="p">.</span><span class="nx">help</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">line</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">logger</span><span class="p">.</span><span class="nx">help</span><span class="p">(</span><span class="nx">line</span><span class="p">);</span> + <span class="p">});</span> + <span class="p">}</span> + + <span class="nx">stdout</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">msg</span><span class="p">);</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'prompt'</span><span class="p">,</span> <span class="nx">prop</span><span class="p">);</span> + + <span class="nx">read</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="kc">null</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">line</span><span class="p">)</span> <span class="p">{</span> + <span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span> <span class="nx">callback</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span> + <span class="p">}</span> + + <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">line</span> <span class="o">||</span> <span class="nx">line</span> <span class="o">===</span> <span class="s1">''</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">line</span> <span class="o">=</span> <span class="nx">prop</span><span class="p">.</span><span class="k">default</span> <span class="o">||</span> <span class="nx">line</span><span class="p">;</span> + <span class="p">}</span> + + <span class="k">if</span> <span class="p">(</span><span class="nx">prop</span><span class="p">.</span><span class="nx">validator</span> <span class="o">||</span> <span class="nx">prop</span><span class="p">.</span><span class="nx">empty</span> <span class="o">===</span> <span class="kc">false</span><span class="p">)</span> <span class="p">{</span> + <span class="kd">var</span> <span class="nx">valid</span><span class="p">;</span> + + <span class="k">if</span> <span class="p">(</span><span class="nx">prop</span><span class="p">.</span><span class="nx">validator</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">valid</span> <span class="o">=</span> <span class="nx">prop</span><span class="p">.</span><span class="nx">validator</span><span class="p">.</span><span class="nx">test</span> + <span class="o">?</span> <span class="nx">prop</span><span class="p">.</span><span class="nx">validator</span><span class="p">.</span><span class="nx">test</span><span class="p">(</span><span class="nx">line</span><span class="p">)</span> + <span class="o">:</span> <span class="nx">prop</span><span class="p">.</span><span class="nx">validator</span><span class="p">(</span><span class="nx">line</span><span class="p">);</span> + <span class="p">}</span> + + <span class="k">if</span> <span class="p">(</span><span class="nx">prop</span><span class="p">.</span><span class="nx">empty</span> <span class="o">===</span> <span class="kc">false</span> <span class="o">&&</span> <span class="nx">valid</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">valid</span> <span class="o">=</span> <span class="nx">line</span><span class="p">.</span><span class="nx">length</span> <span class="o">></span> <span class="mi">0</span><span class="p">;</span> + <span class="nx">prop</span><span class="p">.</span><span class="nx">warning</span> <span class="o">=</span> <span class="nx">prop</span><span class="p">.</span><span class="nx">warning</span> <span class="o">||</span> <span class="s1">'You must supply a value.'</span><span class="p">;</span> + <span class="p">}</span> + + <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">valid</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">logger</span><span class="p">.</span><span class="nx">error</span><span class="p">(</span><span class="s1">'Invalid input for '</span> <span class="o">+</span> <span class="nx">name</span><span class="p">.</span><span class="nx">grey</span><span class="p">);</span> + <span class="k">if</span> <span class="p">(</span><span class="nx">prop</span><span class="p">.</span><span class="nx">warning</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">logger</span><span class="p">.</span><span class="nx">error</span><span class="p">(</span><span class="nx">prop</span><span class="p">.</span><span class="nx">warning</span><span class="p">);</span> + <span class="p">}</span> + + <span class="nx">prompt</span><span class="p">.</span><span class="nx">emit</span><span class="p">(</span><span class="s1">'invalid'</span><span class="p">,</span> <span class="nx">prop</span><span class="p">,</span> <span class="nx">line</span><span class="p">);</span> + <span class="k">return</span> <span class="nx">prompt</span><span class="p">.</span><span class="nx">getInput</span><span class="p">(</span><span class="nx">prop</span><span class="p">,</span> <span class="nx">callback</span><span class="p">);</span> + <span class="p">}</span> + <span class="p">}</span> + + <span class="nx">logger</span><span class="p">.</span><span class="nx">input</span><span class="p">(</span><span class="nx">line</span><span class="p">.</span><span class="nx">yellow</span><span class="p">);</span> + <span class="nx">callback</span><span class="p">(</span><span class="kc">null</span><span class="p">,</span> <span class="nx">line</span><span class="p">);</span> + <span class="p">});</span> + + <span class="k">return</span> <span class="nx">prompt</span><span class="p">;</span> +<span class="p">};</span></pre></div> </td> </tr> <tr id="section-11"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-11">¶</a> </div> <h3>function addProperties (obj, properties, callback)</h3> + +<h4>@obj {Object} Object to add properties to</h4> + +<h4>@properties {Array} List of properties to get values for</h4> + +<h4>@callback {function} Continuation to pass control to when complete.</h4> + +<p>Prompts the user for values each of the <code>properties</code> if <code>obj</code> does not already +have a value for the property. Responds with the modified object. </p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">prompt</span><span class="p">.</span><span class="nx">addProperties</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">obj</span><span class="p">,</span> <span class="nx">properties</span><span class="p">,</span> <span class="nx">callback</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">properties</span> <span class="o">=</span> <span class="nx">properties</span><span class="p">.</span><span class="nx">filter</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">prop</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span> <span class="k">typeof</span> <span class="nx">obj</span><span class="p">[</span><span class="nx">prop</span><span class="p">]</span> <span class="o">===</span> <span class="s1">'undefined'</span><span class="p">;</span> + <span class="p">});</span> + + <span class="k">if</span> <span class="p">(</span><span class="nx">properties</span><span class="p">.</span><span class="nx">length</span> <span class="o">===</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span> <span class="nx">callback</span><span class="p">(</span><span class="nx">obj</span><span class="p">);</span> + <span class="p">}</span> + + <span class="nx">prompt</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">properties</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">results</span><span class="p">)</span> <span class="p">{</span> + <span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span> <span class="nx">callback</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span> + <span class="p">}</span> + <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">results</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span> <span class="nx">callback</span><span class="p">(</span><span class="kc">null</span><span class="p">,</span> <span class="nx">obj</span><span class="p">);</span> + <span class="p">}</span> + + <span class="kd">function</span> <span class="nx">putNested</span> <span class="p">(</span><span class="nx">obj</span><span class="p">,</span> <span class="nx">path</span><span class="p">,</span> <span class="nx">value</span><span class="p">)</span> <span class="p">{</span> + <span class="kd">var</span> <span class="nx">last</span> <span class="o">=</span> <span class="nx">obj</span><span class="p">,</span> <span class="nx">key</span><span class="p">;</span> + + <span class="k">while</span> <span class="p">(</span><span class="nx">path</span><span class="p">.</span><span class="nx">length</span> <span class="o">></span> <span class="mi">1</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">key</span> <span class="o">=</span> <span class="nx">path</span><span class="p">.</span><span class="nx">shift</span><span class="p">();</span> + <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">last</span><span class="p">[</span><span class="nx">key</span><span class="p">])</span> <span class="p">{</span> + <span class="nx">last</span><span class="p">[</span><span class="nx">key</span><span class="p">]</span> <span class="o">=</span> <span class="p">{};</span> + <span class="p">}</span> + + <span class="nx">last</span> <span class="o">=</span> <span class="nx">last</span><span class="p">[</span><span class="nx">key</span><span class="p">];</span> + <span class="p">}</span> + + <span class="nx">last</span><span class="p">[</span><span class="nx">path</span><span class="p">.</span><span class="nx">shift</span><span class="p">()]</span> <span class="o">=</span> <span class="nx">value</span><span class="p">;</span> + <span class="p">}</span> + + <span class="nb">Object</span><span class="p">.</span><span class="nx">keys</span><span class="p">(</span><span class="nx">results</span><span class="p">).</span><span class="nx">forEach</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">key</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">putNested</span><span class="p">(</span><span class="nx">obj</span><span class="p">,</span> <span class="nx">key</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="s1">'.'</span><span class="p">),</span> <span class="nx">results</span><span class="p">[</span><span class="nx">key</span><span class="p">]);</span> + <span class="p">});</span> + + <span class="nx">callback</span><span class="p">(</span><span class="kc">null</span><span class="p">,</span> <span class="nx">obj</span><span class="p">);</span> + <span class="p">});</span> + + <span class="k">return</span> <span class="nx">prompt</span><span class="p">;</span> +<span class="p">};</span></pre></div> </td> </tr> <tr id="section-12"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-12">¶</a> </div> <h3>function readLine (callback)</h3> + +<h4>@callback {function} Continuation to respond to when complete</h4> + +<p>Gets a single line of input from the user. </p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">prompt</span><span class="p">.</span><span class="nx">readLine</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">callback</span><span class="p">)</span> <span class="p">{</span> + <span class="kd">var</span> <span class="nx">value</span> <span class="o">=</span> <span class="s1">''</span><span class="p">,</span> <span class="nx">buffer</span> <span class="o">=</span> <span class="s1">''</span><span class="p">;</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">resume</span><span class="p">();</span> + <span class="nx">stdin</span><span class="p">.</span><span class="nx">setEncoding</span><span class="p">(</span><span class="s1">'utf8'</span><span class="p">);</span> + <span class="nx">stdin</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="nx">callback</span><span class="p">);</span> + <span class="nx">stdin</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="kd">function</span> <span class="nx">data</span> <span class="p">(</span><span class="nx">chunk</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">value</span> <span class="o">+=</span> <span class="nx">buffer</span> <span class="o">+</span> <span class="nx">chunk</span><span class="p">;</span> + <span class="nx">buffer</span> <span class="o">=</span> <span class="s1">''</span><span class="p">;</span> + <span class="nx">value</span> <span class="o">=</span> <span class="nx">value</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="sr">/\r/g</span><span class="p">,</span> <span class="s1">''</span><span class="p">);</span> + <span class="k">if</span> <span class="p">(</span><span class="nx">value</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s1">'\n'</span><span class="p">)</span> <span class="o">!==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span> + <span class="k">if</span> <span class="p">(</span><span class="nx">value</span> <span class="o">!==</span> <span class="s1">'\n'</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">value</span> <span class="o">=</span> <span class="nx">value</span><span class="p">.</span><span class="nx">replace</span><span class="p">(</span><span class="sr">/^\n+/</span><span class="p">,</span> <span class="s1">''</span><span class="p">);</span> + <span class="p">}</span> + + <span class="nx">buffer</span> <span class="o">=</span> <span class="nx">value</span><span class="p">.</span><span class="nx">substr</span><span class="p">(</span><span class="nx">value</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s1">'\n'</span><span class="p">));</span> + <span class="nx">val</span> <span class="o">=</span> <span class="nx">value</span><span class="p">.</span><span class="nx">substr</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nx">value</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s1">'\n'</span><span class="p">));</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">pause</span><span class="p">();</span> + <span class="nx">stdin</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="nx">data</span><span class="p">);</span> + <span class="nx">stdin</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="nx">callback</span><span class="p">);</span> + <span class="nx">value</span> <span class="o">=</span> <span class="nx">value</span><span class="p">.</span><span class="nx">trim</span><span class="p">();</span> + <span class="nx">callback</span><span class="p">(</span><span class="kc">null</span><span class="p">,</span> <span class="nx">value</span><span class="p">);</span> + <span class="p">}</span> + <span class="p">});</span> + + <span class="k">return</span> <span class="nx">prompt</span><span class="p">;</span> +<span class="p">};</span></pre></div> </td> </tr> <tr id="section-13"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-13">¶</a> </div> <h3>function readLineHidden (callback)</h3> + +<h4>@callback {function} Continuation to respond to when complete</h4> + +<p>Gets a single line of hidden input (i.e. <code>rawMode = true</code>) from the user. </p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">prompt</span><span class="p">.</span><span class="nx">readLineHidden</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">callback</span><span class="p">)</span> <span class="p">{</span> + <span class="kd">var</span> <span class="nx">value</span> <span class="o">=</span> <span class="s1">''</span><span class="p">,</span> <span class="nx">buffer</span> <span class="o">=</span> <span class="s1">''</span><span class="p">;</span> + <span class="nx">stdio</span><span class="p">.</span><span class="nx">setRawMode</span><span class="p">(</span><span class="kc">true</span><span class="p">);</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">resume</span><span class="p">();</span> + <span class="nx">stdin</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="nx">callback</span><span class="p">);</span> + <span class="nx">stdin</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="kd">function</span> <span class="nx">data</span> <span class="p">(</span><span class="nx">c</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">c</span> <span class="o">=</span> <span class="s1">''</span> <span class="o">+</span> <span class="nx">c</span><span class="p">;</span> + <span class="k">switch</span> <span class="p">(</span><span class="nx">c</span><span class="p">)</span> <span class="p">{</span> + <span class="k">case</span> <span class="s1">'\n'</span><span class="o">:</span> <span class="k">case</span> <span class="s1">'\r'</span><span class="o">:</span> <span class="k">case</span> <span class="s1">'\r\n'</span><span class="o">:</span> <span class="k">case</span> <span class="s1">'\u0004'</span><span class="o">:</span> + <span class="nx">stdio</span><span class="p">.</span><span class="nx">setRawMode</span><span class="p">(</span><span class="kc">false</span><span class="p">);</span> + <span class="nx">stdin</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'data'</span><span class="p">,</span> <span class="nx">data</span><span class="p">);</span> + <span class="nx">stdin</span><span class="p">.</span><span class="nx">removeListener</span><span class="p">(</span><span class="s1">'error'</span><span class="p">,</span> <span class="nx">callback</span><span class="p">);</span> + <span class="nx">value</span> <span class="o">=</span> <span class="nx">value</span><span class="p">.</span><span class="nx">trim</span><span class="p">();</span> + <span class="nx">stdout</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="s1">'\n'</span><span class="p">);</span> + <span class="nx">stdout</span><span class="p">.</span><span class="nx">flush</span><span class="p">();</span> + <span class="nx">prompt</span><span class="p">.</span><span class="nx">pause</span><span class="p">();</span> + <span class="k">return</span> <span class="nx">callback</span><span class="p">(</span><span class="kc">null</span><span class="p">,</span> <span class="nx">value</span><span class="p">)</span> + <span class="k">case</span> <span class="s1">'\u0003'</span><span class="o">:</span> <span class="k">case</span> <span class="s1">'\0'</span><span class="o">:</span> + <span class="nx">stdout</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="s1">'\n'</span><span class="p">);</span> + <span class="nx">process</span><span class="p">.</span><span class="nx">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> + <span class="k">break</span><span class="p">;</span> + <span class="k">default</span><span class="o">:</span> + <span class="nx">value</span> <span class="o">+=</span> <span class="nx">buffer</span> <span class="o">+</span> <span class="nx">c</span> + <span class="nx">buffer</span> <span class="o">=</span> <span class="s1">''</span><span class="p">;</span> + <span class="k">break</span><span class="p">;</span> + <span class="p">}</span> + <span class="p">});</span> + + <span class="k">return</span> <span class="nx">prompt</span><span class="p">;</span> +<span class="p">};</span> + +</pre></div> </td> </tr> </tbody> </table> </div> </body> </html> diff --git a/node_modules/prompt/examples/add-properties.js b/node_modules/prompt/examples/add-properties.js new file mode 100644 index 0000000..1a56176 --- /dev/null +++ b/node_modules/prompt/examples/add-properties.js @@ -0,0 +1,35 @@ +/* + * add-properties.js: Example of how to add properties to an object using prompt. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var prompt = require('../lib/prompt'); + +// +// Start the prompt +// +prompt.start(); + +var obj = { + password: 'lamepassword', + mindset: 'NY' +} + +// +// Log the initial object. +// +console.log('Initial object to be extended:'); +console.dir(obj); + +// +// Add two properties to the empty object: username and email +// +prompt.addProperties(obj, ['username', 'email'], function (err) { + // + // Log the results. + // + console.log('Updated object received:'); + console.dir(obj); +});
\ No newline at end of file diff --git a/node_modules/prompt/examples/color.js b/node_modules/prompt/examples/color.js new file mode 100644 index 0000000..7c63112 --- /dev/null +++ b/node_modules/prompt/examples/color.js @@ -0,0 +1,19 @@ +var prompt = require("../lib/prompt"); +var colors = require("colors/safe"); +// +// Setting these properties customizes the prompt. +// +prompt.message = colors.rainbow("Question!"); +prompt.delimiter = colors.green("><"); + +prompt.start(); + +prompt.get({ + properties: { + name: { + description: colors.magenta("What is your name?") + } + } +}, function (err, result) { + console.log(colors.cyan("You said your name is: " + result.name)); +}); diff --git a/node_modules/prompt/examples/dynamic-ask-prompt.js b/node_modules/prompt/examples/dynamic-ask-prompt.js new file mode 100644 index 0000000..194e1ef --- /dev/null +++ b/node_modules/prompt/examples/dynamic-ask-prompt.js @@ -0,0 +1,38 @@ +/* + * dynamic-ask-prompt.js: Dynamically decide whether to display prompt. + */ + +var prompt = require('../lib/prompt'); + +var schema = { + properties: { + proxy: { + description: 'Proxy url' + }, + proxyCredentials: { + description: 'Proxy credentials', + ask: function() { + // only ask for proxy credentials if a proxy was set + return prompt.history('proxy').value > 0; + } + } + } +}; + +// +// Start the prompt +// +prompt.start(); + +// +// Get one or two properties from the user, depending on +// what the user answered for proxy +// +prompt.get(schema, function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' proxy: ' + result.proxy); + console.log(' credentials: ' + result.proxyCredentials); +}); diff --git a/node_modules/prompt/examples/existing-properties.js b/node_modules/prompt/examples/existing-properties.js new file mode 100644 index 0000000..d87503b --- /dev/null +++ b/node_modules/prompt/examples/existing-properties.js @@ -0,0 +1,35 @@ +/* + * existing-properties.js: Example of using prompt with predefined properties. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var prompt = require('../lib/prompt'); + +prompt.properties = { + email: { + format: 'email', + message: 'Must be a valid email address' + }, + password: { + hidden: true + } +}; + +// +// Start the prompt +// +prompt.start(); + +// +// Get two properties from the user: email, password +// +prompt.get(['email', 'password'], function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' email: ' + result.email); + console.log(' password: ' + result.password); +}); diff --git a/node_modules/prompt/examples/history.js b/node_modules/prompt/examples/history.js new file mode 100644 index 0000000..fd4369d --- /dev/null +++ b/node_modules/prompt/examples/history.js @@ -0,0 +1,44 @@ +/* + * history.js: Example of using the prompt history capabilities. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var prompt = require('../lib/prompt'); + +// +// Start the prompt +// +prompt.start(); + +var properties = { + properties: { + animal: { + description: 'Enter an animal', + default: 'dog', + pattern: /dog|cat/ + }, + sound: { + description: 'What sound does this animal make?', + conform: function (value) { + var animal = prompt.history(0).value; + + return animal === 'dog' && value === 'woof' + || animal === 'cat' && value === 'meow'; + } + } + } +} + +// +// Get two properties from the user +// +prompt.get(properties, function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' animal: ' + result.animal); + console.log(' sound: ' + result.sound); +}); diff --git a/node_modules/prompt/examples/nested-properties-prompt.js b/node_modules/prompt/examples/nested-properties-prompt.js new file mode 100644 index 0000000..25106a2 --- /dev/null +++ b/node_modules/prompt/examples/nested-properties-prompt.js @@ -0,0 +1,37 @@ +/* + * property-prompt.js: Example of using prompt with complex properties. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var prompt = require('../lib/prompt'); + +var schema = { + properties: { + url: { + required: true, + format: 'url' + }, + auth: { + properties: { + username: { + required: true + }, + password: { + required: true, + hidden: true + } + } + } + } +}; + +prompt.start(); + +prompt.get(schema, function (err, result) { + console.log('Command-line input received:'); + console.log(' url: ' + result.url); + console.log(' auth:username: ' + result.auth.username); + console.log(' auth:password: ' + result.auth.password); +}); diff --git a/node_modules/prompt/examples/old-schema.js b/node_modules/prompt/examples/old-schema.js new file mode 100644 index 0000000..631b7b5 --- /dev/null +++ b/node_modules/prompt/examples/old-schema.js @@ -0,0 +1,36 @@ +/* + * simple-prompt.js: Simple example of using prompt. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var prompt = require('../lib/prompt'); + +// +// Start the prompt +// +prompt.start(); + +// +// Get two properties from the user: username and email +// +prompt.get([ + { + name: 'username', + validator: /^[a-z]+$/, + warning: 'Username should consist only lowercase alphabets', + empty: false + }, + { + name: 'email', + message: 'Email Address' + } +], function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' username: ' + result.username); + console.log(' email: ' + result.email); +}); diff --git a/node_modules/prompt/examples/override-validation.js b/node_modules/prompt/examples/override-validation.js new file mode 100644 index 0000000..0ca9ddd --- /dev/null +++ b/node_modules/prompt/examples/override-validation.js @@ -0,0 +1,52 @@ +/* + * override-validation.js: Example of using prompt with complex properties and command-line input. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var prompt = require('../lib/prompt'), + optimist = require('optimist'); + +var schema = { + properties: { + name: { + pattern: /^[a-zA-Z\s-]+$/, + message: 'Name must be only letters, spaces, or dashes', + required: true + }, + email: { + name: 'email', + format: 'email', + message: 'Must be a valid email address' + } + } +}; + +// +// Set the overrides +// +prompt.override = optimist.argv + +// +// Start the prompt +// +prompt.start(); + +// +// Get two properties from the user: email, password +// +prompt.get(schema, function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' name: ' + result.name); + console.log(' email: ' + result.email); +}); + +// try running +// $ node ./override-validation.js --name USER --email EMAIL +// You will only be asked for email because it's invalid +// $ node ./override-validation.js --name h$acker --email me@example.com +// You will only be asked for name becasue it's invalid diff --git a/node_modules/prompt/examples/password.js b/node_modules/prompt/examples/password.js new file mode 100644 index 0000000..e8015e6 --- /dev/null +++ b/node_modules/prompt/examples/password.js @@ -0,0 +1,42 @@ +/* + * password.js: Simple example of using prompt. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var prompt = require('../lib/prompt'); + +// +// Start the prompt +// +prompt.start(); + +// +// Get two properties from the user: username and password and password masked +// +prompt.get([{ + name: 'username', + required: true + }, { + name: 'password', + hidden: true, + conform: function (value) { + return true; + } + }, { + name: 'passwordMasked', + hidden: true, + replace: '*', + conform: function (value) { + return true; + } + }], function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' username: ' + result.username); + console.log(' password: ' + result.password); + console.log(' passwordMasked: ' + result.passwordMasked); +}); diff --git a/node_modules/prompt/examples/prompt-override.js b/node_modules/prompt/examples/prompt-override.js new file mode 100644 index 0000000..7f2848b --- /dev/null +++ b/node_modules/prompt/examples/prompt-override.js @@ -0,0 +1,36 @@ +var prompt = require('../lib/prompt'), + optimist; + +try { + optimist = require('optimist'); +} catch (err) { + throw new Error([ + 'You need to install optimist before this example will work!', + 'Try: `npm install optimist`.' + ].join('\n')); +} + +// +// Set the overrides +// +prompt.override = optimist.argv + +// +// Start the prompt +// +prompt.start(); + +// +// Get two properties from the user: username and email +// +prompt.get(['username', 'email'], function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' username: ' + result.username); + console.log(' email: ' + result.email); + prompt.pause(); +}) + +// $ node ./prompt-override.js --username USER --email EMAIL diff --git a/node_modules/prompt/examples/prompt-streamline._js b/node_modules/prompt/examples/prompt-streamline._js new file mode 100644 index 0000000..e7fef42 --- /dev/null +++ b/node_modules/prompt/examples/prompt-streamline._js @@ -0,0 +1,32 @@ +/* + * prompt-streamline._js: Example of how to use prompt with streamlinejs. + * + * calling syntax: _node prompt-streamline._js + * + */ +var prompt = require('../lib/prompt'); + +function getSampleData(){ + return [ + { + name: 'username', + message: 'Enter a username' + } + ]; +}; + +// +// Start the prompt +// +prompt.start(); + +function get_username_prompt(_){ + console.log(prompt.get(getSampleData(), _).username); +} + +get_username_prompt(_); + +// +// Clean the prompt +// +prompt.stop();
\ No newline at end of file diff --git a/node_modules/prompt/examples/property-prompt.js b/node_modules/prompt/examples/property-prompt.js new file mode 100644 index 0000000..c8b343b --- /dev/null +++ b/node_modules/prompt/examples/property-prompt.js @@ -0,0 +1,45 @@ +/* + * property-prompt.js: Example of using prompt with complex properties. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var prompt = require('../lib/prompt'); + +var schema = { + properties: { + name: { + pattern: /^[a-zA-Z\s-]+$/, + message: 'Name must be only letters, spaces, or dashes', + required: true + }, + email: { + name: 'email', + format: 'email', + message: 'Must be a valid email address' + }, + password: { + required: true, + hidden: true + } + } +}; + +// +// Start the prompt +// +prompt.start(); + +// +// Get two properties from the user: email, password +// +prompt.get(schema, function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' name: ' + result.name); + console.log(' email: ' + result.email); + console.log(' password: ' + result.password); +}); diff --git a/node_modules/prompt/examples/simple-prompt.js b/node_modules/prompt/examples/simple-prompt.js new file mode 100644 index 0000000..062e529 --- /dev/null +++ b/node_modules/prompt/examples/simple-prompt.js @@ -0,0 +1,25 @@ +/* + * simple-prompt.js: Simple example of using prompt. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var prompt = require('../lib/prompt'); + +// +// Start the prompt +// +prompt.start(); + +// +// Get two properties from the user: username and email +// +prompt.get(['username', 'email'], function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' username: ' + result.username); + console.log(' email: ' + result.email); +});
\ No newline at end of file diff --git a/node_modules/prompt/examples/types.js b/node_modules/prompt/examples/types.js new file mode 100644 index 0000000..83f45a6 --- /dev/null +++ b/node_modules/prompt/examples/types.js @@ -0,0 +1,20 @@ +var prompt = require('../lib/prompt'); + +prompt.start(); + +prompt.get([{ + name: 'integer', + type: 'integer', + required: true + }, { + name: 'number', + type: 'number', + required: true + }, { + name: 'boolean', + type: 'boolean', + required: true + }], function (err, result) { + console.log('Input received:'); + console.log(JSON.stringify(result, null, 2)); +}); diff --git a/node_modules/prompt/examples/yes-or-no-prompt.js b/node_modules/prompt/examples/yes-or-no-prompt.js new file mode 100644 index 0000000..512b556 --- /dev/null +++ b/node_modules/prompt/examples/yes-or-no-prompt.js @@ -0,0 +1,32 @@ +/* + * yes-or-no-prompt.js: Simple example of using prompt. + * + * (C) 2012, Nodejitsu Inc. + * + */ + +var prompt = require('../lib/prompt'); + +// +// Start the prompt +// +prompt.start(); + +var property = { + name: 'yesno', + message: 'are you sure?', + validator: /y[es]*|n[o]?/, + warning: 'Must respond yes or no', + default: 'no' +}; + +// +// Get the simple yes or no property +// +prompt.get(property, function (err, result) { + // + // Log the results. + // + console.log('Command-line input received:'); + console.log(' result: ' + result.yesno); +});
\ No newline at end of file diff --git a/node_modules/prompt/lib/prompt.js b/node_modules/prompt/lib/prompt.js new file mode 100644 index 0000000..78aeda2 --- /dev/null +++ b/node_modules/prompt/lib/prompt.js @@ -0,0 +1,783 @@ +/* + * prompt.js: Simple prompt for prompting information from the command line + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var events = require('events'), + readline = require('readline'), + utile = require('utile'), + async = utile.async, + read = require('read'), + validate = require('revalidator').validate, + winston = require('winston'), + colors = require('colors/safe'); + +// +// Monkey-punch readline.Interface to work-around +// https://github.com/joyent/node/issues/3860 +// +readline.Interface.prototype.setPrompt = function(prompt, length) { + this._prompt = prompt; + if (length) { + this._promptLength = length; + } else { + var lines = prompt.split(/[\r\n]/); + var lastLine = lines[lines.length - 1]; + this._promptLength = lastLine.replace(/\u001b\[(\d+(;\d+)*)?m/g, '').length; + } +}; + +// +// Expose version using `pkginfo` +// +require('pkginfo')(module, 'version'); + +var stdin, stdout, history = []; +var prompt = module.exports = Object.create(events.EventEmitter.prototype); +var logger = prompt.logger = new winston.Logger({ + transports: [new (winston.transports.Console)()] +}); + +prompt.started = false; +prompt.paused = false; +prompt.stopped = true; +prompt.allowEmpty = false; +prompt.message = 'prompt'; +prompt.delimiter = ': '; +prompt.colors = true; + +// +// Create an empty object for the properties +// known to `prompt` +// +prompt.properties = {}; + +// +// Setup the default winston logger to use +// the `cli` levels and colors. +// +logger.cli(); + +// +// ### function start (options) +// #### @options {Object} **Optional** Options to consume by prompt +// Starts the prompt by listening to the appropriate events on `options.stdin` +// and `options.stdout`. If no streams are supplied, then `process.stdin` +// and `process.stdout` are used, respectively. +// +prompt.start = function (options) { + if (prompt.started) { + return; + } + + options = options || {}; + stdin = options.stdin || process.stdin; + stdout = options.stdout || process.stdout; + + // + // By default: Remember the last `10` prompt property / + // answer pairs and don't allow empty responses globally. + // + prompt.memory = options.memory || 10; + prompt.allowEmpty = options.allowEmpty || false; + prompt.message = options.message || prompt.message; + prompt.delimiter = options.delimiter || prompt.delimiter; + prompt.colors = options.colors || prompt.colors; + + if (process.platform !== 'win32') { + // windows falls apart trying to deal with SIGINT + process.on('SIGINT', function () { + stdout.write('\n'); + process.exit(1); + }); + } + + prompt.emit('start'); + prompt.started = true; + prompt.stopped = false; + return prompt; +}; + +// +// ### function pause () +// Pauses input coming in from stdin +// +prompt.pause = function () { + if (!prompt.started || prompt.stopped || prompt.paused) { + return; + } + + stdin.pause(); + prompt.emit('pause'); + prompt.paused = true; + return prompt; +}; + +// +// ### function stop () +// Stops input coming in from stdin +// +prompt.stop = function () { + if (prompt.stopped || !prompt.started) { + return; + } + + stdin.destroy(); + prompt.emit('stop'); + prompt.stopped = true; + prompt.started = false; + prompt.paused = false; + return prompt; +} + +// +// ### function resume () +// Resumes input coming in from stdin +// +prompt.resume = function () { + if (!prompt.started || !prompt.paused) { + return; + } + + stdin.resume(); + prompt.emit('resume'); + prompt.paused = false; + return prompt; +}; + +// +// ### function history (search) +// #### @search {Number|string} Index or property name to find. +// Returns the `property:value` pair from within the prompts +// `history` array. +// +prompt.history = function (search) { + if (typeof search === 'number') { + return history[search] || {}; + } + + var names = history.map(function (pair) { + return typeof pair.property === 'string' + ? pair.property + : pair.property.name; + }); + + if (!~names.indexOf(search)) { + return null; + } + + return history.filter(function (pair) { + return typeof pair.property === 'string' + ? pair.property === search + : pair.property.name === search; + })[0]; +}; + +// +// ### function get (schema, callback) +// #### @schema {Array|Object|string} Set of variables to get input for. +// #### @callback {function} Continuation to pass control to when complete. +// Gets input from the user via stdin for the specified message(s) `msg`. +// +prompt.get = function (schema, callback) { + // + // Transforms a full JSON-schema into an array describing path and sub-schemas. + // Used for iteration purposes. + // + function untangle(schema, path) { + var results = []; + path = path || []; + + if (schema.properties) { + // + // Iterate over the properties in the schema and use recursion + // to process sub-properties. + // + Object.keys(schema.properties).forEach(function (key) { + var obj = {}; + obj[key] = schema.properties[key]; + + // + // Concat a sub-untangling to the results. + // + results = results.concat(untangle(obj[key], path.concat(key))); + }); + + // Return the results. + return results; + } + + // + // This is a schema "leaf". + // + return { + path: path, + schema: schema + }; + } + + // + // Iterate over the values in the schema, represented as + // a legit single-property object subschemas. Accepts `schema` + // of the forms: + // + // 'prop-name' + // + // ['string-name', { path: ['or-well-formed-subschema'], properties: ... }] + // + // { path: ['or-well-formed-subschema'], properties: ... ] } + // + // { properties: { 'schema-with-no-path' } } + // + // And transforms them all into + // + // { path: ['path', 'to', 'property'], properties: { path: { to: ...} } } + // + function iterate(schema, get, done) { + var iterator = [], + result = {}; + + if (typeof schema === 'string') { + // + // We can iterate over a single string. + // + iterator.push({ + path: [schema], + schema: prompt.properties[schema.toLowerCase()] || {} + }); + } + else if (Array.isArray(schema)) { + // + // An array of strings and/or single-prop schema and/or no-prop schema. + // + iterator = schema.map(function (element) { + if (typeof element === 'string') { + return { + path: [element], + schema: prompt.properties[element.toLowerCase()] || {} + }; + } + else if (element.properties) { + return { + path: [Object.keys(element.properties)[0]], + schema: element.properties[Object.keys(element.properties)[0]] + }; + } + else if (element.path && element.schema) { + return element; + } + else { + return { + path: [element.name || 'question'], + schema: element + }; + } + }); + } + else if (schema.properties) { + // + // Or a complete schema `untangle` it for use. + // + iterator = untangle(schema); + } + else { + // + // Or a partial schema and path. + // TODO: Evaluate need for this option. + // + iterator = [{ + schema: schema.schema ? schema.schema : schema, + path: schema.path || [schema.name || 'question'] + }]; + } + + // + // Now, iterate and assemble the result. + // + async.forEachSeries(iterator, function (branch, next) { + get(branch, function assembler(err, line) { + if (err) { + return next(err); + } + + function build(path, line) { + var obj = {}; + if (path.length) { + obj[path[0]] = build(path.slice(1), line); + return obj; + } + + return line; + } + + function attach(obj, attr) { + var keys; + if (typeof attr !== 'object' || attr instanceof Array) { + return attr; + } + + keys = Object.keys(attr); + if (keys.length) { + if (!obj[keys[0]]) { + obj[keys[0]] = {}; + } + obj[keys[0]] = attach(obj[keys[0]], attr[keys[0]]); + } + + return obj; + } + + result = attach(result, build(branch.path, line)); + next(); + }); + }, function (err) { + return err ? done(err) : done(null, result); + }); + } + + iterate(schema, function get(target, next) { + prompt.getInput(target, function (err, line) { + return err ? next(err) : next(null, line); + }); + }, callback); + + return prompt; +}; + +// +// ### function confirm (msg, callback) +// #### @msg {Array|Object|string} set of message to confirm +// #### @callback {function} Continuation to pass control to when complete. +// Confirms a single or series of messages by prompting the user for a Y/N response. +// Returns `true` if ALL messages are answered in the affirmative, otherwise `false` +// +// `msg` can be a string, or object (or array of strings/objects). +// An object may have the following properties: +// +// { +// description: 'yes/no' // message to prompt user +// pattern: /^[yntf]{1}/i // optional - regex defining acceptable responses +// yes: /^[yt]{1}/i // optional - regex defining `affirmative` responses +// message: 'yes/no' // optional - message to display for invalid responses +// } +// +prompt.confirm = function (/* msg, options, callback */) { + var args = Array.prototype.slice.call(arguments), + msg = args.shift(), + callback = args.pop(), + opts = args.shift(), + vars = !Array.isArray(msg) ? [msg] : msg, + RX_Y = /^[yt]{1}/i, + RX_YN = /^[yntf]{1}/i; + + function confirm(target, next) { + var yes = target.yes || RX_Y, + options = utile.mixin({ + description: typeof target === 'string' ? target : target.description||'yes/no', + pattern: target.pattern || RX_YN, + name: 'confirm', + message: target.message || 'yes/no' + }, opts || {}); + + + prompt.get([options], function (err, result) { + next(err ? false : yes.test(result[options.name])); + }); + } + + async.rejectSeries(vars, confirm, function(result) { + callback(null, result.length===0); + }); +}; + + +// Variables needed outside of getInput for multiline arrays. +var tmp = []; + + +// ### function getInput (prop, callback) +// #### @prop {Object|string} Variable to get input for. +// #### @callback {function} Continuation to pass control to when complete. +// Gets input from the user via stdin for the specified message `msg`. +// +prompt.getInput = function (prop, callback) { + var schema = prop.schema || prop, + propName = prop.path && prop.path.join(':') || prop, + storedSchema = prompt.properties[propName.toLowerCase()], + delim = prompt.delimiter, + defaultLine, + against, + hidden, + length, + valid, + name, + raw, + msg; + + // + // If there is a stored schema for `propName` in `propmpt.properties` + // then use it. + // + if (schema instanceof Object && !Object.keys(schema).length && + typeof storedSchema !== 'undefined') { + schema = storedSchema; + } + + // + // Build a proper validation schema if we just have a string + // and no `storedSchema`. + // + if (typeof prop === 'string' && !storedSchema) { + schema = {}; + } + + schema = convert(schema); + defaultLine = schema.default; + name = prop.description || schema.description || propName; + raw = prompt.colors + ? [colors.grey(name), colors.grey(delim)] + : [name, delim]; + + if (prompt.message) + raw.unshift(prompt.message, delim); + + prop = { + schema: schema, + path: propName.split(':') + }; + + // + // If the schema has no `properties` value then set + // it to an object containing the current schema + // for `propName`. + // + if (!schema.properties) { + schema = (function () { + var obj = { properties: {} }; + obj.properties[propName] = schema; + return obj; + })(); + } + + // + // Handle overrides here. + // TODO: Make overrides nestable + // + if (prompt.override && prompt.override[propName]) { + if (prompt._performValidation(name, prop, prompt.override, schema, -1, callback)) { + return callback(null, prompt.override[propName]); + } + + delete prompt.override[propName]; + } + + // + // Check if we should skip this prompt + // + if (typeof prop.schema.ask === 'function' && + !prop.schema.ask()) { + return callback(null, prop.schema.default || ''); + } + + var type = (schema.properties && schema.properties[propName] && + schema.properties[propName].type || '').toLowerCase().trim(), + wait = type === 'array'; + + if (type === 'array') { + length = prop.schema.maxItems; + if (length) { + msg = (tmp.length + 1).toString() + '/' + length.toString(); + } + else { + msg = (tmp.length + 1).toString(); + } + msg += delim; + raw.push(prompt.colors ? msg.grey : msg); + } + + // + // Calculate the raw length and colorize the prompt + // + length = raw.join('').length; + raw[0] = raw[0]; + msg = raw.join(''); + + if (schema.help) { + schema.help.forEach(function (line) { + logger.help(line); + }); + } + + // + // Emit a "prompting" event + // + prompt.emit('prompt', prop); + + // + // If there is no default line, set it to an empty string + // + if(typeof defaultLine === 'undefined') { + defaultLine = ''; + } + + // + // set to string for readline ( will not accept Numbers ) + // + defaultLine = defaultLine.toString(); + + // + // Make the actual read + // + read({ + prompt: msg, + silent: prop.schema && prop.schema.hidden, + replace: prop.schema && prop.schema.replace, + default: defaultLine, + input: stdin, + output: stdout + }, function (err, line) { + if (err && wait === false) { + return callback(err); + } + + var against = {}, + numericInput, + isValid; + + if (line !== '') { + + if (schema.properties[propName]) { + var type = (schema.properties[propName].type || '').toLowerCase().trim() || undefined; + + // + // If type is some sort of numeric create a Number object to pass to revalidator + // + if (type === 'number' || type === 'integer') { + line = Number(line); + } + + // + // Attempt to parse input as a boolean if the schema expects a boolean + // + if (type == 'boolean') { + if(line.toLowerCase() === "true" || line.toLowerCase() === 't') { + line = true; + } else if(line.toLowerCase() === "false" || line.toLowerCase() === 'f') { + line = false; + } + } + + // + // If the type is an array, wait for the end. Fixes #54 + // + if (type == 'array') { + var length = prop.schema.maxItems; + if (err) { + if (err.message == 'canceled') { + wait = false; + stdout.write('\n'); + } + } + else { + if (length) { + if (tmp.length + 1 < length) { + isValid = false; + wait = true; + } + else { + isValid = true; + wait = false; + } + } + else { + isValid = false; + wait = true; + } + tmp.push(line); + } + line = tmp; + } + } + + against[propName] = line; + } + + if (prop && prop.schema.before) { + line = prop.schema.before(line); + } + + // Validate + if (isValid === undefined) isValid = prompt._performValidation(name, prop, against, schema, line, callback); + + if (!isValid) { + return prompt.getInput(prop, callback); + } + + // + // Log the resulting line, append this `property:value` + // pair to the history for `prompt` and respond to + // the callback. + // + logger.input(line.yellow); + prompt._remember(propName, line); + callback(null, line); + + // Make sure `tmp` is emptied + tmp = []; + }); +}; + +// +// ### function performValidation (name, prop, against, schema, line, callback) +// #### @name {Object} Variable name +// #### @prop {Object|string} Variable to get input for. +// #### @against {Object} Input +// #### @schema {Object} Validation schema +// #### @line {String|Boolean} Input line +// #### @callback {function} Continuation to pass control to when complete. +// Perfoms user input validation, print errors if needed and returns value according to validation +// +prompt._performValidation = function (name, prop, against, schema, line, callback) { + var numericInput, valid, msg; + try { + valid = validate(against, schema); + } + catch (err) { + return (line !== -1) ? callback(err) : false; + } + + if (!valid.valid) { + if (prop.schema.message) { + logger.error(prop.schema.message); + } else { + msg = line !== -1 ? 'Invalid input for ' : 'Invalid command-line input for '; + + if (prompt.colors) { + logger.error(msg + name.grey); + } + else { + logger.error(msg + name); + } + } + + prompt.emit('invalid', prop, line); + } + + return valid.valid; +}; + +// +// ### function addProperties (obj, properties, callback) +// #### @obj {Object} Object to add properties to +// #### @properties {Array} List of properties to get values for +// #### @callback {function} Continuation to pass control to when complete. +// Prompts the user for values each of the `properties` if `obj` does not already +// have a value for the property. Responds with the modified object. +// +prompt.addProperties = function (obj, properties, callback) { + properties = properties.filter(function (prop) { + return typeof obj[prop] === 'undefined'; + }); + + if (properties.length === 0) { + return callback(obj); + } + + prompt.get(properties, function (err, results) { + if (err) { + return callback(err); + } + else if (!results) { + return callback(null, obj); + } + + function putNested (obj, path, value) { + var last = obj, key; + + while (path.length > 1) { + key = path.shift(); + if (!last[key]) { + last[key] = {}; + } + + last = last[key]; + } + + last[path.shift()] = value; + } + + Object.keys(results).forEach(function (key) { + putNested(obj, key.split('.'), results[key]); + }); + + callback(null, obj); + }); + + return prompt; +}; + +// +// ### @private function _remember (property, value) +// #### @property {Object|string} Property that the value is in response to. +// #### @value {string} User input captured by `prompt`. +// Prepends the `property:value` pair into the private `history` Array +// for `prompt` so that it can be accessed later. +// +prompt._remember = function (property, value) { + history.unshift({ + property: property, + value: value + }); + + // + // If the length of the `history` Array + // has exceeded the specified length to remember, + // `prompt.memory`, truncate it. + // + if (history.length > prompt.memory) { + history.splice(prompt.memory, history.length - prompt.memory); + } +}; + +// +// ### @private function convert (schema) +// #### @schema {Object} Schema for a property +// Converts the schema into new format if it is in old format +// +function convert(schema) { + var newProps = Object.keys(validate.messages), + newSchema = false, + key; + + newProps = newProps.concat(['description', 'dependencies']); + + for (key in schema) { + if (newProps.indexOf(key) > 0) { + newSchema = true; + break; + } + } + + if (!newSchema || schema.validator || schema.warning || typeof schema.empty !== 'undefined') { + schema.description = schema.message; + schema.message = schema.warning; + + if (typeof schema.validator === 'function') { + schema.conform = schema.validator; + } else { + schema.pattern = schema.validator; + } + + if (typeof schema.empty !== 'undefined') { + schema.required = !(schema.empty); + } + + delete schema.warning; + delete schema.validator; + delete schema.empty; + } + + return schema; +} diff --git a/node_modules/prompt/package.json b/node_modules/prompt/package.json new file mode 100644 index 0000000..ce79183 --- /dev/null +++ b/node_modules/prompt/package.json @@ -0,0 +1,73 @@ +{ + "_from": "prompt", + "_id": "prompt@1.0.0", + "_inBundle": false, + "_integrity": "sha1-jlcSPDlquYiJf7Mn/Trtw+c15P4=", + "_location": "/prompt", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "prompt", + "name": "prompt", + "escapedName": "prompt", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/prompt/-/prompt-1.0.0.tgz", + "_shasum": "8e57123c396ab988897fb327fd3aedc3e735e4fe", + "_spec": "prompt", + "_where": "/data/dev/Projets/Bingoloto Remote", + "author": { + "name": "Nodejitsu Inc.", + "email": "info@nodejitsu.com" + }, + "bugs": { + "url": "https://github.com/flatiron/prompt/issues" + }, + "bundleDependencies": false, + "dependencies": { + "colors": "^1.1.2", + "pkginfo": "0.x.x", + "read": "1.0.x", + "revalidator": "0.1.x", + "utile": "0.3.x", + "winston": "2.1.x" + }, + "deprecated": false, + "description": "A beautiful command-line prompt for node.js", + "devDependencies": { + "vows": "0.7.0" + }, + "engines": { + "node": ">= 0.6.6" + }, + "homepage": "https://github.com/flatiron/prompt#readme", + "license": "MIT", + "main": "./lib/prompt", + "maintainers": [ + { + "name": "indexzero", + "email": "charlie@nodejitsu.com" + }, + { + "name": "jesusabdullah", + "email": "josh@nodejitsu.com" + } + ], + "name": "prompt", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/flatiron/prompt.git" + }, + "scripts": { + "test": "vows test/prompt-test.js --spec", + "test-all": "vows --spec" + }, + "version": "1.0.0" +} diff --git a/node_modules/prompt/test/helpers.js b/node_modules/prompt/test/helpers.js new file mode 100644 index 0000000..b21021f --- /dev/null +++ b/node_modules/prompt/test/helpers.js @@ -0,0 +1,161 @@ +/* + * helpers.js: test helpers for the prompt tests. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var stream = require('stream'), + util = require('util'), + prompt = require('../lib/prompt'); + +var helpers = exports; + +var MockReadWriteStream = helpers.MockReadWriteStream = function () { + // + // No need to do anything here, it's just a mock. + // + var self = this; + this.on('pipe', function (src) { + var _emit = src.emit; + src.emit = function () { + //console.dir(arguments); + _emit.apply(src, arguments); + }; + + src.on('data', function (d) { + self.emit('data', d + ''); + }) + }) +}; + +util.inherits(MockReadWriteStream, stream.Stream); + +['resume', 'pause', 'setEncoding', 'flush', 'end'].forEach(function (method) { + MockReadWriteStream.prototype[method] = function () { /* Mock */ }; +}); + +MockReadWriteStream.prototype.write = function (msg) { + this.emit('data', msg); + return true; +}; + +MockReadWriteStream.prototype.writeNextTick = function (msg) { + var self = this + process.nextTick(function () { + self.write(msg); + }); +}; + +// +// Create some mock streams for asserting against +// in our prompt teSts. +// +helpers.stdin = new MockReadWriteStream(); +helpers.stdout = new MockReadWriteStream(); +helpers.stderr = new MockReadWriteStream(); + +// +// Because `read` uses a `process.nextTick` for reading from +// stdin, it is necessary to write sequences of input with extra +// `process.nextTick` calls +// +helpers.stdin.writeSequence = function (lines) { + if (!lines || !lines.length) { + return; + } + + helpers.stdin.writeNextTick(lines.shift()); + prompt.once('prompt', function () { + process.nextTick(function () { + helpers.stdin.writeSequence(lines); + }); + }); +} + +// +// Monkey punch `util.error` to silence console output +// and redirect to helpers.stderr for testing. +// +process.stderr.write = function () { + helpers.stderr.write.apply(helpers.stderr, arguments); +} + +// 1) .properties +// 2) warning --> message +// 3) Name --> description || key +// 4) validator --> conform (fxns), pattern (regexp), format (built-in) +// 5) empty --> required +helpers.schema = { + properties: { + oldschema: { + message: 'Enter your username', + validator: /^[\w|\-]+$/, + warning: 'username can only be letters, numbers, and dashes', + empty: false + }, + riffwabbles: { + pattern: /^[\w|\-]+$/, + message: 'riffwabbles can only be letters, numbers, and dashes', + default: 'foobizzles' + }, + number: { + type: 'number', + message: 'pick a number, any number', + default: 10 + }, + integer: { + type: 'integer' + }, + boolean: { + type: 'boolean' + }, + username: { + pattern: /^[\w|\-]+$/, + message: 'Username can only be letters, numbers, and dashes' + }, + notblank: { + required: true + }, + password: { + hidden: true, + required: true + }, + badValidator: { + pattern: ['cant', 'use', 'array'] + }, + animal: { + description: 'Enter an animal', + default: 'dog', + pattern: /dog|cat/ + }, + sound: { + description: 'What sound does this animal make?', + conform: function (value) { + var animal = prompt.history(0).value; + + return animal === 'dog' && value === 'woof' + || animal === 'cat' && value === 'meow'; + } + }, + fnvalidator: { + name: 'fnvalidator', + validator: function (line) { + return line.slice(0,2) == 'fn'; + }, + message: 'fnvalidator must start with "fn"' + }, + fnconform: { + conform: function (line) { + return line.slice(0,2) == 'fn'; + }, + message: 'fnconform must start with "fn"' + }/*, + cbvalidator: { + conform: function (line, next) { + next(line.slice(0,2) == 'cb'); + }, + message: 'cbvalidator must start with "cb"' + }*/ + } +}; diff --git a/node_modules/prompt/test/interactive-prompt-test.js b/node_modules/prompt/test/interactive-prompt-test.js new file mode 100644 index 0000000..a3032e3 --- /dev/null +++ b/node_modules/prompt/test/interactive-prompt-test.js @@ -0,0 +1,49 @@ +/* + * prompt-test.js: Tests for prompt. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var assert = require('assert'), + vows = require('vows'), + prompt = require('../lib/prompt'), + winston = require('winston').cli(), + helpers = require('./helpers'); + +vows.describe('prompt/interactive').addBatch({ + "When using prompt": { + topic: function () { + // + // Reset the prompt for interactive testing + // + prompt.started = false; + prompt.start(); + winston.info('These prompt tests are interactive'); + winston.info('Not following instructions will result in test failure'); + return null; + }, + "the getInput() method": { + "when passed a complex property with `hidden: true`": { + topic: function () { + winston.info('When prompted, enter: 12345 [backspace] [backspace] [enter]'); + prompt.getInput({ path: ['password'], schema: helpers.schema.properties.password }, this.callback); + }, + "should respond with `123`": function (err, result) { + assert.isNull(err); + assert.equal(result, '123'); + }, + "and then when passed a complex property expecting a number": { + topic: function () { + winston.info('When prompted, enter: 123 [enter]'); + prompt.getInput({ path: ['number'], schema: helpers.schema.properties.number }, this.callback); + }, + "should respond with `123` (as a number)": function (err, result) { + assert.isNull(err); + assert.equal(result, 123); + } + } + } + } + } +}).export(module); diff --git a/node_modules/prompt/test/macros.js b/node_modules/prompt/test/macros.js new file mode 100644 index 0000000..9f58f08 --- /dev/null +++ b/node_modules/prompt/test/macros.js @@ -0,0 +1,82 @@ +/* + * macros.js: Test macros for prompt. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var assert = require('assert'), + helpers = require('./helpers'), + prompt = require('../lib/prompt'); + +exports.shouldConfirm = function (options, mixin) { + var message = options.response.toString().replace(/\n/g, ''), + messages = ["When using prompt", "the confirm() method"], + context = {}, + last = context; + + messages = messages.concat(options.messages || []); + + while (messages.length) { + var text = messages.shift(); + last[text] = {}; + last = last[text]; + } + + last['responding with ' + message] = { + topic: function () { + if(!mixin) + prompt.confirm(options.prop, this.callback); + else + prompt.confirm(options.prop, mixin, this.callback); + + if (!Array.isArray(options.response)) { + helpers.stdin.writeNextTick(options.response + '\n'); + } + else { + helpers.stdin.writeSequence(options.response); + } + }, + "should respond with true" : function(err, result) { + assert.isNull(err); + assert.isTrue(result); + } + } + + return context; +}; + +exports.shouldNotConfirm = function (options) { + var message = options.response.toString().replace(/\n/g, ''), + messages = ["When using prompt", "the confirm() method"], + context = {}, + last = context; + + messages = messages.concat(options.messages || []); + + while (messages.length) { + var text = messages.shift(); + last[text] = {}; + last = last[text]; + } + + last['responding with ' + message] = { + topic: function () { + prompt.confirm(options.prop, this.callback); + + if (!Array.isArray(options.response)) { + helpers.stdin.writeNextTick(options.response + '\n'); + } + else { + helpers.stdin.writeSequence(options.response); + } + }, + "should respond with false" : function(err, result) { + assert.isNull(err); + assert.isFalse(result); + } + }; + + return context; +}; + diff --git a/node_modules/prompt/test/prompt-test.js b/node_modules/prompt/test/prompt-test.js new file mode 100644 index 0000000..2be73bc --- /dev/null +++ b/node_modules/prompt/test/prompt-test.js @@ -0,0 +1,817 @@ +/* + * prompt-test.js: Tests for prompt. + * + * (C) 2010, Nodejitsu Inc. + * + */ + +var assert = require('assert'), + vows = require('vows'), + prompt = require('../lib/prompt'), + helpers = require('./helpers'), + macros = require('./macros'), + schema = helpers.schema; + +// A helper to pass fragments of our schema into prompt as full schemas. +function grab () { + var names = [].slice.call(arguments), + complete = { schema: {} }; + + names.forEach(function (name) { + complete.path = [name], + complete.schema = schema.properties[name]; + }); + return complete; +}; + +// +// Reset the prompt for mock testing +// +prompt.started = false; +prompt.start({ + stdin: helpers.stdin, + stdout: helpers.stdout +}); + +vows.describe('prompt').addBatch({ + "When using prompt": { + "the getInput() method": { + "with a simple string prompt": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }) + + prompt.getInput('test input', this.callback); + helpers.stdin.writeNextTick('test value\n'); + }, + "should prompt to stdout and respond with data": function (err, input) { + assert.isNull(err); + assert.equal(input, 'test value'); + assert.isTrue(this.msg.indexOf('test input') !== -1); + } + }, + } + } +}).addBatch({ + "When using prompt": { + "the getInput() method": { + "with any field that is not supposed to be empty": { + "and we don't provide any input": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + helpers.stderr.once('data', function (msg) { + that.errmsg = msg; + }); + + prompt.getInput(grab('notblank'), function () {}); + prompt.once('invalid', this.callback.bind(null, null)) + helpers.stdin.writeNextTick('\n'); + }, + "should prompt with an error": function (_, prop, input) { + assert.isObject(prop); + assert.equal(input, ''); + assert.isTrue(this.errmsg.indexOf('Invalid input') !== -1); + assert.isTrue(this.msg.indexOf('notblank') !== -1); + } + } + } + } + } +}).addBatch({ + "When using prompt": { + "the getInput() method": { + "with a hidden field that is not supposed to be empty": { + "and we provide valid input": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + prompt.getInput('password', this.callback); + helpers.stdin.writeNextTick('trustno1\n'); + }, + + "should prompt to stdout and respond with data": function (err, input) { + assert.isNull(err); + assert.equal(input, 'trustno1'); + assert.isTrue(this.msg.indexOf('password') !== -1); + } + }, + } + } + } +}).addBatch({ + "When using prompt": { + "the getInput() method": { + "with a hidden field that is not supposed to be empty": { + "and we don't provide an input": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + helpers.stderr.once('data', function (msg) { + that.errmsg = msg; + }); + + prompt.getInput(grab('password'), function () {} ); + prompt.once('invalid', this.callback.bind(null, null)) + helpers.stdin.writeNextTick('\n'); + }, + "should prompt with an error": function (ign, prop, input) { + assert.isObject(prop); + assert.equal(input, ''); + assert.isTrue(this.errmsg.indexOf('Invalid input') !== -1); + assert.isTrue(this.msg.indexOf('password') !== -1); + } + } + } + } + } +}).addBatch({ + "When using prompt": { + "the getInput() method": { + "with an integer field": { + "and we provide valid input": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + prompt.getInput(grab('integer'), this.callback); + helpers.stdin.writeNextTick('42\n'); + }, + "should prompt to stdout and respond with data": function (err, input) { + assert.isNull(err); + assert.equal(input, '42'); + assert.isTrue(this.msg.indexOf('integer') !== -1); + } + }, + } + } + } +}).addBatch({ + "When using prompt": { + "the getInput() method": { + "with an integer field": { + "and we don't provide an integer": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + helpers.stderr.once('data', function (msg) { + that.errmsg = msg; + }) + + prompt.getInput(grab('integer'), this.callback); + + prompt.once('invalid', function () { + prompt.once('prompt', function () { + process.nextTick(function () { + helpers.stdin.writeNextTick('42\n'); + }) + }) + }); + + helpers.stdin.writeNextTick('4.2\n'); + }, + "should prompt with an error before completing the operation": function (err, input) { + assert.isNull(err); + assert.equal(input, '42'); + assert.isTrue(this.errmsg.indexOf('Invalid input') !== -1); + assert.isTrue(this.msg.indexOf('integer') !== -1); + } + } + } + } + } +}).addBatch({ + "When using prompt": { + "the getInput() method": { + "with a boolean field": { + "and we provide valid input": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + prompt.getInput(grab('boolean'), this.callback); + helpers.stdin.writeNextTick('true\n'); + }, + "should prompt to stdout and respond with data": function (err, input) { + assert.isNull(err); + assert.equal(input, true); + assert.isTrue(this.msg.indexOf('boolean') !== -1); + } + }, + } + } + } +}).addBatch({ + "When using prompt": { + "the getInput() method": { + "with a boolean field": { + "and we don't provide an bool": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + helpers.stderr.once('data', function (msg) { + that.errmsg = msg; + }) + + prompt.getInput(grab('boolean'), this.callback); + + prompt.once('invalid', function () { + prompt.once('prompt', function () { + process.nextTick(function () { + helpers.stdin.writeNextTick('F\n'); + }) + }) + }); + + helpers.stdin.writeNextTick('4.2\n'); + }, + "should prompt with an error before completing the operation": function (err, input) { + assert.isNull(err); + assert.equal(input, false); + assert.isTrue(this.errmsg.indexOf('Invalid input') !== -1); + assert.isTrue(this.msg.indexOf('boolean') !== -1); + } + } + } + } + } +}).addBatch({ + "When using prompt": { + "the getInput() method": { + "with a complex property prompt": { + "and a valid input": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + prompt.getInput(grab('username'), this.callback); + helpers.stdin.writeNextTick('some-user\n'); + }, + "should prompt to stdout and respond with data": function (err, input) { + assert.isNull(err); + assert.equal(input, 'some-user'); + assert.isTrue(this.msg.indexOf('username') !== -1); + } + } + } + } + } +}).addBatch({ + "When using prompt": { + "the getInput() method": { + "with a complex property prompt": { + "and an invalid input": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + helpers.stderr.once('data', function (msg) { + that.errmsg = msg; + }) + + prompt.getInput(grab('username'), this.callback); + + prompt.once('invalid', function () { + prompt.once('prompt', function () { + process.nextTick(function () { + helpers.stdin.writeNextTick('some-user\n'); + }) + }) + }); + + helpers.stdin.writeNextTick('some -user\n'); + }, + "should prompt with an error before completing the operation": function (err, input) { + assert.isNull(err); + assert.equal(input, 'some-user'); + assert.isTrue(this.errmsg.indexOf('Username can only be letters, numbers, and dashes') !== -1); + assert.isTrue(this.msg.indexOf('username') !== -1); + } + } + } + } + } +}).addBatch({ + "When using prompt": { + "the getInput() method": { + "with a complex property prompt": { + "with an invalid validator (array)": { + topic: function () { + var that = this, + called; + + prompt.getInput(grab('badValidator'), function (err) { + if (!called) { + called = true; + that.callback(err); + } + }); + helpers.stdin.writeNextTick('some-user\n'); + }, + "should respond with an error": function (err, ign) { + assert.isTrue(!!err); + } + } + } + } + } +}).addBatch({ + "When using prompt": { + "the get() method": { + "with a simple string prompt": { + "that is not a property in prompt.properties": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }) + + prompt.get('test input', this.callback); + helpers.stdin.writeNextTick('test value\n'); + }, + "should prompt to stdout and respond with the value": function (err, result) { + assert.isNull(err); + assert.include(result, 'test input'); + assert.equal(result['test input'], 'test value'); + assert.isTrue(this.msg.indexOf('test input') !== -1); + } + }, + } + } + } +}).addBatch({ + "When using prompt": { + "the get() method": { + "with a simple string prompt": { + "that is a property name in prompt.properties": { + "with a default value": { + topic: function () { + var that = this; + + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + prompt.properties.riffwabbles = schema.properties.riffwabbles; + prompt.get('riffwabbles', this.callback); + helpers.stdin.writeNextTick('\n'); + }, + "should prompt to stdout and respond with the default value": function (err, result) { + assert.isNull(err); + assert.isTrue(this.msg.indexOf('riffwabbles') !== -1); + assert.isTrue(this.msg.indexOf('(foobizzles)') !== -1); + assert.include(result, 'riffwabbles'); + assert.equal(result['riffwabbles'], schema.properties['riffwabbles'].default); + } + }, + } + } + } + } +}).addBatch({ + "When using prompt": { + "the get() method": { + "with a simple string prompt": { + "that is a property name in prompt.properties": { + "that expects a numeric value": { + "and gets valid input": { + topic: function () { + var that = this; + + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + prompt.properties.number = schema.properties.number; + prompt.get('number', this.callback); + helpers.stdin.writeNextTick('15\n'); + }, + "should prompt to stdout and respond with a numeric value": function (err, result) { + assert.isNull(err); + assert.include(result, 'number'); + assert.equal(result['number'], 15); + } + } + } + } + } + } + } +}).addBatch({ + "When using prompt": { + "the get() method": { + "with a simple string prompt": { + "that is a property name in prompt.properties": { + "with a sync function validator (.validator)": { + topic: function () { + var that = this; + + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + prompt.get(helpers.schema.properties.fnvalidator, this.callback); + helpers.stdin.writeNextTick('fn123\n'); + }, + "should accept a value that is checked": function (err, result) { + assert.isNull(err); + assert.equal(result['fnvalidator'],'fn123'); + } + } + } + } + } + } +}).addBatch({ + "When using prompt": { + "the get() method": { + "with a simple string prompt": { + "that is a property name in prompt.properties": { + "with a sync function validator (.conform)": { + topic: function () { + var that = this; + + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + prompt.get(grab('fnconform'), this.callback); + helpers.stdin.writeNextTick('fn123\n'); + }, + "should accept a value that is checked": function (err, result) { + assert.isNull(err); + assert.equal(result['fnconform'],'fn123'); + } + } + // + // Remark Does not work with revalidator + // + // "with a callback validator": { + // topic: function () { + // var that = this; + // + // helpers.stdout.once('data', function (msg) { + // that.msg = msg; + // }); + // + // prompt.get(grab('cbvalidator'), this.callback); + // helpers.stdin.writeNextTick('cb123\n'); + // }, + // "should not accept a value that is correct": function (err, result) { + // assert.isNull(err); + // assert.equal(result['cbvalidator'],'cb123'); + // } + // } + } + }, + } + } +}).addBatch({ + "When using prompt": { + "the get() method": { + "with a simple string prompt": { + "that is a property name in prompt.properties": { + "with a sync function before (.before)": { + topic: function() { + var that = this; + + helpers.stdout.once('data', function(msg) { + that.msg = msg; + }); + + prompt.get({ + properties: { + fnbefore: { + before: function(v) { + return 'v' + v; + } + } + } + }, this.callback); + helpers.stdin.writeNextTick('fn456\n'); + }, + "should modify user's input": function(e, result) { + assert.equal(result.fnbefore, 'vfn456'); + } + } + } + } + } + } +}).addBatch({ + "When using prompt": { + "the get() method": { + "skip prompt with prompt.overide": { + topic: function () { + prompt.override = { coconihet: 'whatever' } + prompt.get('coconihet', this.callback); + }, + "skips prompt and uses overide": function (err, results) { + assert.equal(results.coconihet, 'whatever') + } + } + } + } +}).addBatch({ + "When using prompt": { + "the addProperties() method": { + topic: function () { + prompt.addProperties({}, ['foo', 'bar'], this.callback); + helpers.stdin.writeSequence(['foo\n', 'bar\n']); + }, + "should add the properties to the object": function (err, obj) { + assert.isNull(err); + assert.isObject(obj); + assert.equal(obj.foo, 'foo'); + assert.equal(obj.bar, 'bar'); + } + } + } +}).addBatch({ + "When using prompt": { + "the get() method": { + "with old schema": { + topic: function () { + var that = this; + + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + prompt.properties.username = schema.properties.oldschema; + prompt.get('username', this.callback); + + helpers.stdin.writeSequence(['\n', 'hell$\n', 'hello\n']); + }, + "should prompt to stdout and respond with the default value": function (err, result) { + assert.isNull(err); + assert.isTrue(this.msg.indexOf('username') !== -1); + assert.include(result, 'username'); + assert.equal(result.username, 'hello'); + } + } + } + } +}).addBatch({ + "When using prompt": { + "the history() method": { + "when used inside of a complex property": { + "with correct value(s)": { + topic: function () { + prompt.get([grab('animal'), grab('sound')], this.callback); + helpers.stdin.writeSequence(['dog\n', 'woof\n']); + }, + "should respond with the values entered": function (err, result) { + assert.isTrue(!err); + assert.equal(result.animal, 'dog'); + assert.equal(result.sound, 'woof'); + assert.equal(prompt.history('nothing'), null); + assert.deepEqual(prompt.history('animal'), { property: 'animal', value: 'dog' }); + } + }, + } + } + } +}).addBatch({ + "When using prompt": { + "the history() method": { + "when used inside of a complex property": { + "with an incorrect value": { + topic: function () { + prompt.get([grab('animal'), grab('sound')], function () {}); + prompt.once('invalid', this.callback.bind(null, null)); + helpers.stdin.writeSequence(['dog\n', 'meow\n']); + }, + "should prompt for the error": function (ign, property, line) { + assert.equal(property.path.join(''), 'sound'); + assert.equal(line, 'meow'); + } + } + } + } + } +}).addBatch({ + "when using prompt": { + "the get() method": { + topic: function () { + prompt.override = { xyz: 468, abc: 123 } + prompt.get(['xyz', 'abc'], this.callback); + }, + "should respond with overrides": function (err, results) { + assert.isNull(err); + assert.deepEqual(results, { xyz: 468, abc: 123 }); + } + } + } +}).addBatch({ + "When using prompt": { + "with fancy properties": { + "the get() method": { + topic: function () { + prompt.override = { UVW: 5423, DEF: 64235 } + prompt.get({ + properties: { + 'UVW': { + description: 'a custom message', + default: 6 + }, + 'DEF': { + description: 'a custom message', + default: 6 + } + } + }, this.callback); + }, + "should respond with overrides": function (err, results) { + assert.isNull(err); + assert.deepEqual(results, { UVW: 5423, DEF: 64235 }); + } + } + } + } +}).addBatch({ + "When using prompt": { + "with a type and a description property": { + "the get() method": { + topic: function () { + var that = this; + helpers.stdout.once('data', function (msg) { + that.msg = msg; + }); + + prompt.get({ + name: 'test', + type: 'number', + description: 'Please input a number' + }, this.callback); + helpers.stdin.writeNextTick('42\n'); + }, + "should prompt to stdout and respond with the value": function (err, result) { + assert.isNull(err); + assert.include(result, 'test'); + assert.equal(result['test'], '42'); + assert.isTrue(this.msg.indexOf('Please input a number') !== -1); + } + }, + } + } + }) +.addBatch( + macros.shouldConfirm({ + messages: ['with a string message'], + prop: 'test', + response: 'Y' + }) +).addBatch( + macros.shouldConfirm({ + messages: ['with an empty string and default yes'], + prop: 'test', + response: '' + }, { + default: 'yes' + }) +).addBatch( + macros.shouldNotConfirm({ + messages: ['with a string message'], + prop: 'test', + response: 'N' + }) +).addBatch( + macros.shouldConfirm({ + messages: ['with a string message'], + prop: 'test', + response: 'YES' + }) +).addBatch( + macros.shouldNotConfirm({ + messages: ['with a string message'], + prop: 'test', + response: 'NO' + }) +).addBatch( + macros.shouldConfirm({ + messages: ['with a string message'], + prop: 'test', + response: 'T' + }) +).addBatch( + macros.shouldNotConfirm({ + messages: ['with a string message'], + prop: 'test', + response: 'F' + }) +).addBatch( + macros.shouldConfirm({ + messages: ['with a string message'], + prop: 'test', + response: 'TRUE' + }) +).addBatch( + macros.shouldNotConfirm({ + messages: ['with a string message'], + prop: 'test', + response: 'FALSE' + }) +).addBatch( + macros.shouldConfirm({ + messages: ['with an object', 'and description set'], + prop: { description: 'a custom message' }, + response: 'Y' + }) +).addBatch( + macros.shouldConfirm({ + messages: ['with an object', 'and they forgot the description'], + prop: { description: 'a custom message' }, + response: 'Y' + }) +).addBatch( + macros.shouldConfirm({ + messages: ['with an object', 'and custom validators'], + prop: { + description: 'node or jitsu?', + pattern: /^(node|jitsu)/i, + yes: /^node/i + }, + response: 'node' + }) +).addBatch( + macros.shouldNotConfirm({ + messages: ['with an object', 'and custom validators'], + prop: { + description: 'node or jitsu?', + pattern: /^(node|jitsu)/i, + yes: /^node/i + }, + response: 'jitsu' + }) +).addBatch( + macros.shouldConfirm({ + messages: ['with multiple strings'], + prop: ["test", "test2", "test3"], + response: ['Y\n', 'y\n', 'YES\n'] + }) +).addBatch( + macros.shouldNotConfirm({ + messages: ['with multiple strings'], + prop: ["test", "test2", "test3"], + response: ['Y\n', 'N\n', 'YES\n'] + }) +).addBatch( + macros.shouldNotConfirm({ + messages: ['with multiple strings'], + prop: ["test", "test2", "test3"], + response: ['n\n', 'NO\n', 'N\n'] + }) +).addBatch( + macros.shouldConfirm({ + messages: ['with multiple objects'], + prop: [ + { message: "test" }, + { message: "test2" } + ], + response: ['y\n', 'y\n'] + }) +).addBatch( + macros.shouldNotConfirm({ + messages: ['with multiple objects'], + prop: [ + { message: "test" }, + { message: "test2" } + ], + response: ['n\n', 'n\n'] + }) +).addBatch( + macros.shouldNotConfirm({ + messages: ['with multiple objects'], + prop: [ + { message: "test" }, + { message: "test2" } + ], + response: ['n\n', 'y\n'] + }) +).export(module); diff --git a/node_modules/read/LICENSE b/node_modules/read/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/read/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/read/README.md b/node_modules/read/README.md new file mode 100644 index 0000000..5967fad --- /dev/null +++ b/node_modules/read/README.md @@ -0,0 +1,53 @@ +## read + +For reading user input from stdin. + +Similar to the `readline` builtin's `question()` method, but with a +few more features. + +## USAGE + +```javascript +var read = require("read") +read(options, callback) +``` + +The callback gets called with either the user input, or the default +specified, or an error, as `callback(error, result, isDefault)` +node style. + +## OPTIONS + +Every option is optional. + +* `prompt` What to write to stdout before reading input. +* `silent` Don't echo the output as the user types it. +* `replace` Replace silenced characters with the supplied character value. +* `timeout` Number of ms to wait for user input before giving up. +* `default` The default value if the user enters nothing. +* `edit` Allow the user to edit the default value. +* `terminal` Treat the output as a TTY, whether it is or not. +* `input` Readable stream to get input data from. (default `process.stdin`) +* `output` Writeable stream to write prompts to. (default: `process.stdout`) + +If silent is true, and the input is a TTY, then read will set raw +mode, and read character by character. + +## COMPATIBILITY + +This module works sort of with node 0.6. It does not work with node +versions less than 0.6. It is best on node 0.8. + +On node version 0.6, it will remove all listeners on the input +stream's `data` and `keypress` events, because the readline module did +not fully clean up after itself in that version of node, and did not +make it possible to clean up after it in a way that has no potential +for side effects. + +Additionally, some of the readline options (like `terminal`) will not +function in versions of node before 0.8, because they were not +implemented in the builtin readline module. + +## CONTRIBUTING + +Patches welcome. diff --git a/node_modules/read/lib/read.js b/node_modules/read/lib/read.js new file mode 100644 index 0000000..a93d1b3 --- /dev/null +++ b/node_modules/read/lib/read.js @@ -0,0 +1,113 @@ + +module.exports = read + +var readline = require('readline') +var Mute = require('mute-stream') + +function read (opts, cb) { + if (opts.num) { + throw new Error('read() no longer accepts a char number limit') + } + + if (typeof opts.default !== 'undefined' && + typeof opts.default !== 'string' && + typeof opts.default !== 'number') { + throw new Error('default value must be string or number') + } + + var input = opts.input || process.stdin + var output = opts.output || process.stdout + var prompt = (opts.prompt || '').trim() + ' ' + var silent = opts.silent + var editDef = false + var timeout = opts.timeout + + var def = opts.default || '' + if (def) { + if (silent) { + prompt += '(<default hidden>) ' + } else if (opts.edit) { + editDef = true + } else { + prompt += '(' + def + ') ' + } + } + var terminal = !!(opts.terminal || output.isTTY) + + var m = new Mute({ replace: opts.replace, prompt: prompt }) + m.pipe(output, {end: false}) + output = m + var rlOpts = { input: input, output: output, terminal: terminal } + + if (process.version.match(/^v0\.6/)) { + var rl = readline.createInterface(rlOpts.input, rlOpts.output) + } else { + var rl = readline.createInterface(rlOpts) + } + + + output.unmute() + rl.setPrompt(prompt) + rl.prompt() + if (silent) { + output.mute() + } else if (editDef) { + rl.line = def + rl.cursor = def.length + rl._refreshLine() + } + + var called = false + rl.on('line', onLine) + rl.on('error', onError) + + rl.on('SIGINT', function () { + rl.close() + onError(new Error('canceled')) + }) + + var timer + if (timeout) { + timer = setTimeout(function () { + onError(new Error('timed out')) + }, timeout) + } + + function done () { + called = true + rl.close() + + if (process.version.match(/^v0\.6/)) { + rl.input.removeAllListeners('data') + rl.input.removeAllListeners('keypress') + rl.input.pause() + } + + clearTimeout(timer) + output.mute() + output.end() + } + + function onError (er) { + if (called) return + done() + return cb(er) + } + + function onLine (line) { + if (called) return + if (silent && terminal) { + output.unmute() + output.write('\r\n') + } + done() + // truncate the \n at the end. + line = line.replace(/\r?\n$/, '') + var isDefault = !!(editDef && line === def) + if (def && !line) { + isDefault = true + line = def + } + cb(null, line, isDefault) + } +} diff --git a/node_modules/read/package.json b/node_modules/read/package.json new file mode 100644 index 0000000..d409938 --- /dev/null +++ b/node_modules/read/package.json @@ -0,0 +1,60 @@ +{ + "_from": "read@1.0.x", + "_id": "read@1.0.7", + "_inBundle": false, + "_integrity": "sha1-s9oZvQUkMal2cdRKQmNK33ELQMQ=", + "_location": "/read", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "read@1.0.x", + "name": "read", + "escapedName": "read", + "rawSpec": "1.0.x", + "saveSpec": null, + "fetchSpec": "1.0.x" + }, + "_requiredBy": [ + "/prompt" + ], + "_resolved": "https://registry.npmjs.org/read/-/read-1.0.7.tgz", + "_shasum": "b3da19bd052431a97671d44a42634adf710b40c4", + "_spec": "read@1.0.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/prompt", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/read/issues" + }, + "bundleDependencies": false, + "dependencies": { + "mute-stream": "~0.0.4" + }, + "deprecated": false, + "description": "read(1) for node programs", + "devDependencies": { + "tap": "^1.2.0" + }, + "engines": { + "node": ">=0.8" + }, + "files": [ + "lib/read.js" + ], + "homepage": "https://github.com/isaacs/read#readme", + "license": "ISC", + "main": "lib/read.js", + "name": "read", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/read.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "version": "1.0.7" +} diff --git a/node_modules/restore-cursor/index.d.ts b/node_modules/restore-cursor/index.d.ts new file mode 100644 index 0000000..83ff2f4 --- /dev/null +++ b/node_modules/restore-cursor/index.d.ts @@ -0,0 +1,13 @@ +/** +Gracefully restore the CLI cursor on exit. + +@example +``` +import restoreCursor = require('restore-cursor'); + +restoreCursor(); +``` +*/ +declare function restoreCursor(): void; + +export = restoreCursor; diff --git a/node_modules/restore-cursor/index.js b/node_modules/restore-cursor/index.js new file mode 100644 index 0000000..3e8dd07 --- /dev/null +++ b/node_modules/restore-cursor/index.js @@ -0,0 +1,9 @@ +'use strict'; +const onetime = require('onetime'); +const signalExit = require('signal-exit'); + +module.exports = onetime(() => { + signalExit(() => { + process.stderr.write('\u001B[?25h'); + }, {alwaysLast: true}); +}); diff --git a/node_modules/restore-cursor/license b/node_modules/restore-cursor/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/restore-cursor/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/restore-cursor/package.json b/node_modules/restore-cursor/package.json new file mode 100644 index 0000000..91f5fc7 --- /dev/null +++ b/node_modules/restore-cursor/package.json @@ -0,0 +1,84 @@ +{ + "_from": "restore-cursor@^3.1.0", + "_id": "restore-cursor@3.1.0", + "_inBundle": false, + "_integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "_location": "/restore-cursor", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "restore-cursor@^3.1.0", + "name": "restore-cursor", + "escapedName": "restore-cursor", + "rawSpec": "^3.1.0", + "saveSpec": null, + "fetchSpec": "^3.1.0" + }, + "_requiredBy": [ + "/cli-cursor" + ], + "_resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "_shasum": "39f67c54b3a7a58cea5236d95cf0034239631f7e", + "_spec": "restore-cursor@^3.1.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/cli-cursor", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/restore-cursor/issues" + }, + "bundleDependencies": false, + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "deprecated": false, + "description": "Gracefully restore the CLI cursor on exit", + "devDependencies": { + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/restore-cursor#readme", + "keywords": [ + "exit", + "quit", + "process", + "graceful", + "shutdown", + "sigterm", + "sigint", + "terminate", + "kill", + "stop", + "cli", + "cursor", + "ansi", + "show", + "term", + "terminal", + "console", + "tty", + "shell", + "command-line" + ], + "license": "MIT", + "name": "restore-cursor", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/restore-cursor.git" + }, + "scripts": { + "test": "xo && tsd" + }, + "version": "3.1.0" +} diff --git a/node_modules/restore-cursor/readme.md b/node_modules/restore-cursor/readme.md new file mode 100644 index 0000000..c224a29 --- /dev/null +++ b/node_modules/restore-cursor/readme.md @@ -0,0 +1,26 @@ +# restore-cursor [![Build Status](https://travis-ci.org/sindresorhus/restore-cursor.svg?branch=master)](https://travis-ci.org/sindresorhus/restore-cursor) + +> Gracefully restore the CLI cursor on exit + +Prevent the cursor you've hidden interactively from remaining hidden if the process crashes. + + +## Install + +``` +$ npm install restore-cursor +``` + + +## Usage + +```js +const restoreCursor = require('restore-cursor'); + +restoreCursor(); +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/revalidator/.npmignore b/node_modules/revalidator/.npmignore new file mode 100644 index 0000000..5171c54 --- /dev/null +++ b/node_modules/revalidator/.npmignore @@ -0,0 +1,2 @@ +node_modules +npm-debug.log
\ No newline at end of file diff --git a/node_modules/revalidator/.travis.yml b/node_modules/revalidator/.travis.yml new file mode 100644 index 0000000..04d6dd9 --- /dev/null +++ b/node_modules/revalidator/.travis.yml @@ -0,0 +1,11 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" + +notifications: + email: + - travis@nodejitsu.com + irc: "irc.freenode.org#nodejitsu" + diff --git a/node_modules/revalidator/CHANGELOG.md b/node_modules/revalidator/CHANGELOG.md new file mode 100644 index 0000000..8befb22 --- /dev/null +++ b/node_modules/revalidator/CHANGELOG.md @@ -0,0 +1,25 @@ + +0.1.3 / 2012-10-17 +================== + + * Fixed case problem with types + +0.1.2 / 2012-06-27 +================== + + * Added host-name String format + * Added support for additionalProperties + * Added few default validation messages for formats + +0.1.1 / 2012-04-16 +================== + + * Added default and custom error message support + * Added suport for conform function + * Updated date-time format + +0.1.0 / 2011-11-09 +================= + + * Initial release + diff --git a/node_modules/revalidator/LICENSE b/node_modules/revalidator/LICENSE new file mode 100644 index 0000000..a83d179 --- /dev/null +++ b/node_modules/revalidator/LICENSE @@ -0,0 +1,179 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright (c) 2009-2010 Alexis Sellier, Charlie Robbins, Nodejitsu Inc. diff --git a/node_modules/revalidator/README.md b/node_modules/revalidator/README.md new file mode 100644 index 0000000..be6601b --- /dev/null +++ b/node_modules/revalidator/README.md @@ -0,0 +1,301 @@ +# revalidator [![Build Status](https://secure.travis-ci.org/flatiron/revalidator.png)](http://travis-ci.org/flatiron/revalidator) + +A cross-browser / node.js validator used by resourceful and flatiron. Revalidator has [JSONSchema](http://tools.ietf.org/html/draft-zyp-json-schema-04) compatibility as primary goal. + +## Example +The core of `revalidator` is simple and succinct: `revalidator.validate(obj, schema)`: + +``` js + var revalidator = require('revalidator'); + + console.dir(revalidator.validate(someObject, { + properties: { + url: { + description: 'the url the object should be stored at', + type: 'string', + pattern: '^/[^#%&*{}\\:<>?\/+]+$', + required: true + }, + challenge: { + description: 'a means of protecting data (insufficient for production, used as example)', + type: 'string', + minLength: 5 + }, + body: { + description: 'what to store at the url', + type: 'any', + default: null + } + } + })); +``` + +This will return with a value indicating if the `obj` conforms to the `schema`. If it does not, a descriptive object will be returned containing the errors encountered with validation. + +``` js + { + valid: true // or false + errors: [/* Array of errors if valid is false */] + } +``` + +In the browser, the validation function is exposed on `window.validate` by simply including `revalidator.js`. + +## Installation + +### Installing npm (node package manager) +``` bash + $ curl http://npmjs.org/install.sh | sh +``` + +### Installing revalidator +``` bash + $ [sudo] npm install revalidator +``` + +## Usage + +`revalidator` takes json-schema as input to validate objects. + +### revalidator.validate (obj, schema, options) + +This will return with a value indicating if the `obj` conforms to the `schema`. If it does not, a descriptive object will be returned containing the errors encountered with validation. + +``` js +{ + valid: true // or false + errors: [/* Array of errors if valid is false */] +} +``` + +#### Available Options + +* __validateFormats__: Enforce format constraints (_default true_) +* __validateFormatsStrict__: When `validateFormats` is _true_ treat unrecognized formats as validation errors (_default false_) +* __validateFormatExtensions__: When `validateFormats` is _true_ also validate formats defined in `validate.formatExtensions` (_default true_) +* __cast__: Enforce casting of some types (for integers/numbers are only supported) when it's possible, e.g. `"42" => 42`, but `"forty2" => "forty2"` for the `integer` type. + +### Schema +For a property an `value` is that which is given as input for validation where as an `expected value` is the value of the below fields + +#### required +If true, the value should not be undefined + +```js +{ required: true } +``` + +#### allowEmpty +If false, the value must not be an empty string + +```js +{ allowEmpty: false } +``` + +#### type +The `type of value` should be equal to the expected value + +```js +{ type: 'string' } +{ type: 'number' } +{ type: 'integer' } +{ type: 'array' } +{ type: 'boolean' } +{ type: 'object' } +{ type: 'null' } +{ type: 'any' } +{ type: ['boolean', 'string'] } +``` + +#### pattern +The expected value regex needs to be satisfied by the value + +```js +{ pattern: /^[a-z]+$/ } +``` + +#### maxLength +The length of value must be greater than or equal to expected value + +```js +{ maxLength: 8 } +``` + +#### minLength +The length of value must be lesser than or equal to expected value + +```js +{ minLength: 8 } +``` + +#### minimum +Value must be greater than or equal to the expected value + +```js +{ minimum: 10 } +``` + +#### maximum +Value must be lesser than or equal to the expected value + +```js +{ maximum: 10 } +``` + +#### allowEmpty +Value may not be empty + +```js +{ allowEmpty: false } +``` + +#### exclusiveMinimum +Value must be greater than expected value + +```js +{ exclusiveMinimum: 9 } +``` + +### exclusiveMaximum +Value must be lesser than expected value + +```js +{ exclusiveMaximum: 11 } +``` + +#### divisibleBy +Value must be divisible by expected value + +```js +{ divisibleBy: 5 } +{ divisibleBy: 0.5 } +``` + +#### minItems +Value must contain more then expected value number of items + +```js +{ minItems: 2 } +``` + +#### maxItems +Value must contains less then expected value number of items + +```js +{ maxItems: 5 } +``` + +#### uniqueItems +Value must hold a unique set of values + +```js +{ uniqueItems: true } +``` + +#### enum +Value must be present in the array of expected value + +```js +{ enum: ['month', 'year'] } +``` + +#### format +Value must be a valid format + +```js +{ format: 'url' } +{ format: 'email' } +{ format: 'ip-address' } +{ format: 'ipv6' } +{ format: 'date-time' } +{ format: 'date' } +{ format: 'time' } +{ format: 'color' } +{ format: 'host-name' } +{ format: 'utc-millisec' } +{ format: 'regex' } +``` + +#### conform +Value must conform to constraint denoted by expected value + +```js +{ conform: function (v) { + if (v%3==1) return true; + return false; + } +} +``` + +#### dependencies +Value is valid only if the dependent value is valid + +```js +{ + town: { required: true, dependencies: 'country' }, + country: { maxLength: 3, required: true } +} +``` + +### Nested Schema +We also allow nested schema + +```js +{ + properties: { + title: { + type: 'string', + maxLength: 140, + required: true + }, + author: { + type: 'object', + required: true, + properties: { + name: { + type: 'string', + required: true + }, + email: { + type: 'string', + format: 'email' + } + } + } + } +} +``` + +### Custom Messages +We also allow custom message for different constraints + +```js +{ + type: 'string', + format: 'url' + messages: { + type: 'Not a string type', + format: 'Expected format is a url' + } +``` + +```js +{ + conform: function () { ... }, + message: 'This can be used as a global message' +} +``` + +## Tests +All tests are written with [vows][0] and should be run with [npm][1]: + +``` bash + $ npm test +``` + +#### Author: [Charlie Robbins](http://nodejitsu.com), [Alexis Sellier](http://cloudhead.io) +#### Contributors: [Fedor Indutny](http://github.com/indutny), [Bradley Meck](http://github.com/bmeck), [Laurie Harper](http://laurie.holoweb.net/) +#### License: Apache 2.0 + +[0]: http://vowsjs.org +[1]: http://npmjs.org diff --git a/node_modules/revalidator/example/webservice.js b/node_modules/revalidator/example/webservice.js new file mode 100644 index 0000000..33d5f0e --- /dev/null +++ b/node_modules/revalidator/example/webservice.js @@ -0,0 +1,204 @@ +// +// (C) 2011, Nodejitsu Inc. +// MIT License +// +// A simple web service for storing JSON data via REST +// +// GET - View Object +// POST - Create Object +// PUT - Update Object +// DELETE - Delete Object +// + +var revalidator = require('../'), + http = require('http'), +// +// Keep our objects in a simple memory store +// + memoryStore = {}, +// +// Set up our request schema +// + schema = { + properties: { + url: { + description: 'the url the object should be stored at', + type: 'string', + pattern: '^/[^#%&*{}\\:<>?\/+]+$', + required: true + }, + challenge: { + description: 'a means of protecting data (insufficient for production, used as example)', + type: 'string', + minLength: 5 + }, + body: { + description: 'what to store at the url', + type: 'any', + default: null + } + } + } + +var server = http.createServer(function validateRestRequest (req, res) { + req.method = req.method.toUpperCase(); + + // + // Log the requests + // + console.log(req.method, req.url); + + // + // Buffer the request so it can be parsed as JSON + // + var requestBody = []; + req.on('data', function addDataToBody (data) { + requestBody.push(data); + }); + + // + // Once the request has ended work with the body + // + req.on('end', function dealWithRest () { + + // + // Parse the JSON + // + requestBody = requestBody.join(''); + if ({POST: 1, PUT: 1}[req.method]) { + try { + requestBody = JSON.parse(requestBody); + } + catch (e) { + res.writeHead(400); + res.end(e); + return; + } + } + else { + requestBody = {}; + } + + // + // If this was sent to a url but the body url was not declared + // Make sure the body get the requested url so that our schema + // validates before we work on it + // + if (!requestBody.url) { + requestBody.url = req.url; + } + + // + // Don't let users override the main API endpoint + // + if (requestBody.url === '/') { + res.writeHead(400); + res.end('Cannot override the API endpoint "/"'); + return; + } + + // + // See if our request and target are out of sync + // This lets us double check the url we are about to take up + // if we choose to send the request to the url directly + // + if (req.url !== '/' && requestBody.url !== req.url) { + res.writeHead(400); + res.end('Requested url and actual url do not match'); + return; + } + + // + // Validate the schema + // + var validation = revalidator.validate(requestBody, schema); + if (!validation.valid) { + res.writeHead(400); + res.end(validation.errors.join('\n')); + return; + } + + // + // Grab the current value from storage and + // check if it is a valid state for REST + // + var storedValue = memoryStore[requestBody.url]; + if (req.method === 'POST') { + if (storedValue) { + res.writeHead(400); + res.end('ALREADY EXISTS'); + return; + } + } + else if (!storedValue) { + res.writeHead(404); + res.end('DOES NOT EXIST'); + return; + } + + // + // Check our challenge + // + if (storedValue && requestBody.challenge != storedValue.challenge) { + res.writeHead(403); + res.end('NOT AUTHORIZED'); + return; + } + + // + // Since revalidator only checks and does not manipulate + // our object we need to set up the defaults our selves + // For an easier solution to this please look at Flatiron's + // `Resourceful` project + // + if (requestBody.body === undefined) { + requestBody.body = schema.properties.body.default; + } + + // + // Use REST to determine how to manipulate the stored + // values + // + switch (req.method) { + + case "GET": + res.writeHead(200); + var result = storedValue.body; + res.end(JSON.stringify(result)); + return; + + case "POST": + res.writeHead(201); + res.end(); + memoryStore[requestBody.url] = requestBody; + return; + + case "DELETE": + delete memoryStore[requestBody.url]; + res.writeHead(200); + res.end(); + return; + + case "PUT": + memoryStore[requestBody.url] = requestBody; + res.writeHead(200); + res.end(); + return; + + default: + res.writeHead(400); + res.end('Invalid Http Verb'); + return; + } + }); +}) +// +// Listen to various ports depending on environment we are being run on +// +server.listen(process.env.PORT || process.env.C9_PORT || 1337, function reportListening () { + + console.log('JSON REST Service listening on port', this.address().port); + console.log('Requests can be sent via REST to "/" if they conform to the following schema:'); + console.log(JSON.stringify(schema, null, ' ')); + +});
\ No newline at end of file diff --git a/node_modules/revalidator/lib/revalidator.js b/node_modules/revalidator/lib/revalidator.js new file mode 100644 index 0000000..ad65814 --- /dev/null +++ b/node_modules/revalidator/lib/revalidator.js @@ -0,0 +1,427 @@ +(function (exports) { + exports.validate = validate; + exports.mixin = mixin; + + // + // ### function validate (object, schema, options) + // #### {Object} object the object to validate. + // #### {Object} schema (optional) the JSON Schema to validate against. + // #### {Object} options (optional) options controlling the validation + // process. See {@link #validate.defaults) for details. + // Validate <code>object</code> against a JSON Schema. + // If <code>object</code> is self-describing (i.e. has a + // <code>$schema</code> property), it will also be validated + // against the referenced schema. [TODO]: This behaviour bay be + // suppressed by setting the {@link #validate.options.???} + // option to <code>???</code>.[/TODO] + // + // If <code>schema</code> is not specified, and <code>object</code> + // is not self-describing, validation always passes. + // + // <strong>Note:</strong> in order to pass options but no schema, + // <code>schema</code> <em>must</em> be specified in the call to + // <code>validate()</code>; otherwise, <code>options</code> will + // be interpreted as the schema. <code>schema</code> may be passed + // as <code>null</code>, <code>undefinded</code>, or the empty object + // (<code>{}</code>) in this case. + // + function validate(object, schema, options) { + options = mixin({}, options, validate.defaults); + var errors = []; + + validateObject(object, schema, options, errors); + + // + // TODO: self-described validation + // if (! options.selfDescribing) { ... } + // + + return { + valid: !(errors.length), + errors: errors + }; + }; + + /** + * Default validation options. Defaults can be overridden by + * passing an 'options' hash to {@link #validate}. They can + * also be set globally be changing the values in + * <code>validate.defaults</code> directly. + */ + validate.defaults = { + /** + * <p> + * Enforce 'format' constraints. + * </p><p> + * <em>Default: <code>true</code></em> + * </p> + */ + validateFormats: true, + /** + * <p> + * When {@link #validateFormats} is <code>true</code>, + * treat unrecognized formats as validation errors. + * </p><p> + * <em>Default: <code>false</code></em> + * </p> + * + * @see validation.formats for default supported formats. + */ + validateFormatsStrict: false, + /** + * <p> + * When {@link #validateFormats} is <code>true</code>, + * also validate formats defined in {@link #validate.formatExtensions}. + * </p><p> + * <em>Default: <code>true</code></em> + * </p> + */ + validateFormatExtensions: true + }; + + /** + * Default messages to include with validation errors. + */ + validate.messages = { + required: "is required", + allowEmpty: "must not be empty", + minLength: "is too short (minimum is %{expected} characters)", + maxLength: "is too long (maximum is %{expected} characters)", + pattern: "invalid input", + minimum: "must be greater than or equal to %{expected}", + maximum: "must be less than or equal to %{expected}", + exclusiveMinimum: "must be greater than %{expected}", + exclusiveMaximum: "must be less than %{expected}", + divisibleBy: "must be divisible by %{expected}", + minItems: "must contain more than %{expected} items", + maxItems: "must contain less than %{expected} items", + uniqueItems: "must hold a unique set of values", + format: "is not a valid %{expected}", + conform: "must conform to given constraint", + type: "must be of %{expected} type" + }; + validate.messages['enum'] = "must be present in given enumerator"; + + /** + * + */ + validate.formats = { + 'email': /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, + 'ip-address': /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i, + 'ipv6': /^([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}$/, + 'date-time': /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:.\d{1,3})?Z$/, + 'date': /^\d{4}-\d{2}-\d{2}$/, + 'time': /^\d{2}:\d{2}:\d{2}$/, + 'color': /^#[a-z0-9]{6}|#[a-z0-9]{3}|(?:rgb\(\s*(?:[+-]?\d+%?)\s*,\s*(?:[+-]?\d+%?)\s*,\s*(?:[+-]?\d+%?)\s*\))aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow$/i, + //'style': (not supported) + //'phone': (not supported) + //'uri': (not supported) + 'host-name': /^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])/, + 'utc-millisec': { + test: function (value) { + return typeof(value) === 'number' && value >= 0; + } + }, + 'regex': { + test: function (value) { + try { new RegExp(value) } + catch (e) { return false } + + return true; + } + } + }; + + /** + * + */ + validate.formatExtensions = { + 'url': /^(https?|ftp|git):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i + }; + + function mixin(obj) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue } + + if (typeof(source) !== 'object') { + throw new TypeError('mixin non-object'); + } + + for (var p in source) { + if (source.hasOwnProperty(p)) { + obj[p] = source[p]; + } + } + } + + return obj; + }; + + function validateObject(object, schema, options, errors) { + var props, allProps = Object.keys(object), + visitedProps = []; + + // see 5.2 + if (schema.properties) { + props = schema.properties; + for (var p in props) { + if (props.hasOwnProperty(p)) { + visitedProps.push(p); + validateProperty(object, object[p], p, props[p], options, errors); + } + } + } + + // see 5.3 + if (schema.patternProperties) { + props = schema.patternProperties; + for (var p in props) { + if (props.hasOwnProperty(p)) { + var re = new RegExp(p); + + // Find all object properties that are matching `re` + for (var k in object) { + if (object.hasOwnProperty(k)) { + visitedProps.push(k); + if (re.exec(k) !== null) { + validateProperty(object, object[k], p, props[p], options, errors); + } + } + } + } + } + } + + // see 5.4 + if (undefined !== schema.additionalProperties) { + var i, l; + + var unvisitedProps = allProps.filter(function(k){ + return -1 === visitedProps.indexOf(k); + }); + + // Prevent additional properties; each unvisited property is therefore an error + if (schema.additionalProperties === false && unvisitedProps.length > 0) { + for (i = 0, l = unvisitedProps.length; i < l; i++) { + error("additionalProperties", unvisitedProps[i], object[unvisitedProps[i]], false, errors); + } + } + // additionalProperties is a schema and validate unvisited properties against that schema + else if (typeof schema.additionalProperties == "object" && unvisitedProps.length > 0) { + for (i = 0, l = unvisitedProps.length; i < l; i++) { + validateProperty(object, object[unvisitedProps[i]], unvisitedProps[i], schema.unvisitedProperties, options, errors); + } + } + } + + }; + + function validateProperty(object, value, property, schema, options, errors) { + var format, + valid, + spec, + type; + + function constrain(name, value, assert) { + if (schema[name] !== undefined && !assert(value, schema[name])) { + error(name, property, value, schema, errors); + } + } + + if (value === undefined) { + if (schema.required && schema.type !== 'any') { + return error('required', property, undefined, schema, errors); + } else { + return; + } + } + + if (options.cast) { + if (('integer' === schema.type || 'number' === schema.type) && value == +value) { + value = +value; + object[property] = value; + } + + if ('boolean' === schema.type) { + if ('true' === value || '1' === value || 1 === value) { + value = true; + object[property] = value; + } + + if ('false' === value || '0' === value || 0 === value) { + value = false; + object[property] = value; + } + } + } + + if (schema.format && options.validateFormats) { + format = schema.format; + + if (options.validateFormatExtensions) { spec = validate.formatExtensions[format] } + if (!spec) { spec = validate.formats[format] } + if (!spec) { + if (options.validateFormatsStrict) { + return error('format', property, value, schema, errors); + } + } + else { + if (!spec.test(value)) { + return error('format', property, value, schema, errors); + } + } + } + + if (schema['enum'] && schema['enum'].indexOf(value) === -1) { + error('enum', property, value, schema, errors); + } + + // Dependencies (see 5.8) + if (typeof schema.dependencies === 'string' && + object[schema.dependencies] === undefined) { + error('dependencies', property, null, schema, errors); + } + + if (isArray(schema.dependencies)) { + for (var i = 0, l = schema.dependencies.length; i < l; i++) { + if (object[schema.dependencies[i]] === undefined) { + error('dependencies', property, null, schema, errors); + } + } + } + + if (typeof schema.dependencies === 'object') { + validateObject(object, schema.dependencies, options, errors); + } + + checkType(value, schema.type, function(err, type) { + if (err) return error('type', property, typeof value, schema, errors); + + constrain('conform', value, function (a, e) { return e(a, object) }); + + switch (type || (isArray(value) ? 'array' : typeof value)) { + case 'string': + constrain('allowEmpty', value, function (a, e) { return e ? e : a !== '' }); + constrain('minLength', value.length, function (a, e) { return a >= e }); + constrain('maxLength', value.length, function (a, e) { return a <= e }); + constrain('pattern', value, function (a, e) { + e = typeof e === 'string' + ? e = new RegExp(e) + : e; + return e.test(a) + }); + break; + case 'integer': + case 'number': + constrain('minimum', value, function (a, e) { return a >= e }); + constrain('maximum', value, function (a, e) { return a <= e }); + constrain('exclusiveMinimum', value, function (a, e) { return a > e }); + constrain('exclusiveMaximum', value, function (a, e) { return a < e }); + constrain('divisibleBy', value, function (a, e) { + var multiplier = Math.max((a - Math.floor(a)).toString().length - 2, (e - Math.floor(e)).toString().length - 2); + multiplier = multiplier > 0 ? Math.pow(10, multiplier) : 1; + return (a * multiplier) % (e * multiplier) === 0 + }); + break; + case 'array': + constrain('items', value, function (a, e) { + for (var i = 0, l = a.length; i < l; i++) { + validateProperty(object, a[i], property, e, options, errors); + } + return true; + }); + constrain('minItems', value, function (a, e) { return a.length >= e }); + constrain('maxItems', value, function (a, e) { return a.length <= e }); + constrain('uniqueItems', value, function (a) { + var h = {}; + + for (var i = 0, l = a.length; i < l; i++) { + var key = JSON.stringify(a[i]); + if (h[key]) return false; + h[key] = true; + } + + return true; + }); + break; + case 'object': + // Recursive validation + if (schema.properties || schema.patternProperties || schema.additionalProperties) { + validateObject(value, schema, options, errors); + } + break; + } + }); + }; + + function checkType(val, type, callback) { + var result = false, + types = isArray(type) ? type : [type]; + + // No type - no check + if (type === undefined) return callback(null, type); + + // Go through available types + // And fine first matching + for (var i = 0, l = types.length; i < l; i++) { + type = types[i].toLowerCase().trim(); + if (type === 'string' ? typeof val === 'string' : + type === 'array' ? isArray(val) : + type === 'object' ? val && typeof val === 'object' && + !isArray(val) : + type === 'number' ? typeof val === 'number' : + type === 'integer' ? typeof val === 'number' && ~~val === val : + type === 'null' ? val === null : + type === 'boolean'? typeof val === 'boolean' : + type === 'date' ? isDate(val) : + type === 'any' ? typeof val !== 'undefined' : false) { + return callback(null, type); + } + }; + + callback(true); + }; + + function error(attribute, property, actual, schema, errors) { + var lookup = { expected: schema[attribute], actual: actual, attribute: attribute, property: property }; + var message = schema.messages && schema.messages[attribute] || schema.message || validate.messages[attribute] || "no default message"; + message = message.replace(/%\{([a-z]+)\}/ig, function (_, match) { return lookup[match.toLowerCase()] || ''; }); + errors.push({ + attribute: attribute, + property: property, + expected: schema[attribute], + actual: actual, + message: message + }); + }; + + function isArray(value) { + var s = typeof value; + if (s === 'object') { + if (value) { + if (typeof value.length === 'number' && + !(value.propertyIsEnumerable('length')) && + typeof value.splice === 'function') { + return true; + } + } + } + return false; + } + + function isDate(value) { + var s = typeof value; + if (s === 'object') { + if (value) { + if (typeof value.getTime === 'function') { + return true; + } + } + } + + return false; + } + +})(typeof module === 'object' && module && module.exports ? module.exports : window); diff --git a/node_modules/revalidator/package.json b/node_modules/revalidator/package.json new file mode 100644 index 0000000..ee318b9 --- /dev/null +++ b/node_modules/revalidator/package.json @@ -0,0 +1,63 @@ +{ + "_from": "revalidator@0.1.x", + "_id": "revalidator@0.1.8", + "_inBundle": false, + "_integrity": "sha1-/s5hv6DBtSoga9axgZgYS91SOjs=", + "_location": "/revalidator", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "revalidator@0.1.x", + "name": "revalidator", + "escapedName": "revalidator", + "rawSpec": "0.1.x", + "saveSpec": null, + "fetchSpec": "0.1.x" + }, + "_requiredBy": [ + "/prompt" + ], + "_resolved": "https://registry.npmjs.org/revalidator/-/revalidator-0.1.8.tgz", + "_shasum": "fece61bfa0c1b52a206bd6b18198184bdd523a3b", + "_spec": "revalidator@0.1.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/prompt", + "author": { + "name": "Nodejitsu Inc.", + "email": "info@nodejitsu.com" + }, + "bugs": { + "url": "https://github.com/flatiron/revalidator/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A cross-browser / node.js validator used by resourceful", + "devDependencies": { + "vows": "0.7.0" + }, + "engines": { + "node": ">= 0.4.0" + }, + "homepage": "https://github.com/flatiron/revalidator#readme", + "license": "Apache 2.0", + "main": "./lib/revalidator", + "maintainers": [ + { + "name": "indexzero", + "email": "charlie@nodejitsu.com" + }, + { + "name": "indutny", + "email": "fedor.indutny@gmail.com" + } + ], + "name": "revalidator", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/flatiron/revalidator.git" + }, + "scripts": { + "test": "vows test/*-test.js --spec" + }, + "version": "0.1.8" +} diff --git a/node_modules/revalidator/test/validator-test.js b/node_modules/revalidator/test/validator-test.js new file mode 100644 index 0000000..6d962c2 --- /dev/null +++ b/node_modules/revalidator/test/validator-test.js @@ -0,0 +1,421 @@ +var assert = require('assert'), + vows = require('vows'), + revalidator = require('../lib/revalidator'); + +function clone(object) { + return Object.keys(object).reduce(function (obj, k) { + obj[k] = object[k]; + return obj; + }, {}); +}; + + +function assertInvalid(res) { + assert.isObject(res); + assert.strictEqual(res.valid, false); +} + +function assertValid(res) { + assert.isObject(res); + assert.strictEqual(res.valid, true); +} + +function assertHasError(attr, field) { + return function (res) { + assert.notEqual(res.errors.length, 0); + assert.ok(res.errors.some(function (e) { + return e.attribute === attr && (field ? e.property === field : true); + })); + }; +} + +function assertHasErrorMsg(attr, msg) { + return function (res) { + assert.notEqual(res.errors.length, 0); + assert.ok(res.errors.some(function (e) { + return e.attribute === attr && e.message === msg; + })); + }; +} + +function assertValidates(passingValue, failingValue, attributes) { + var schema = { + name: 'Resource', + properties: { field: {} } + }; + + var failing; + + if (!attributes) { + attributes = failingValue; + failing = false; + } else { + failing = true; + } + + var attr = Object.keys(attributes)[0]; + revalidator.mixin(schema.properties.field, attributes); + + var result = { + "when the object conforms": { + topic: function () { + return revalidator.validate({ field: passingValue }, schema); + }, + "return an object with `valid` set to true": assertValid + } + }; + + if (failing) { + result["when the object does not conform"] ={ + topic: function () { + return revalidator.validate({ field: failingValue }, schema); + }, + "return an object with `valid` set to false": assertInvalid, + "and an error concerning the attribute": assertHasError(Object.keys(attributes)[0], 'field') + }; + }; + + return result; +} + +vows.describe('revalidator', { + "Validating": { + "with <type>:'string'": assertValidates ('hello', 42, { type: "string" }), + "with <type>:'number'": assertValidates (42, 'hello', { type: "number" }), + "with <type>:'integer'": assertValidates (42, 42.5, { type: "integer" }), + "with <type>:'array'": assertValidates ([4, 2], 'hi', { type: "array" }), + "with <type>:'object'": assertValidates ({}, [], { type: "object" }), + "with <type>:'boolean'": assertValidates (false, 42, { type: "boolean" }), + "with <types>:bool,num": assertValidates (false, 'hello', { type: ["boolean", "number"] }), + "with <types>:bool,num": assertValidates (544, null, { type: ["boolean", "number"] }), + "with <type>:'null'": assertValidates (null, false, { type: "null" }), + "with <type>:'any'": assertValidates (9, { type: "any" }), + "with <type>:'date'": assertValidates (new Date(), 'hello', { type: "date" }), + "with <pattern>": assertValidates ("kaboom", "42", { pattern: /^[a-z]+$/ }), + "with <maxLength>": assertValidates ("boom", "kaboom", { maxLength: 4 }), + "with <minLength>": assertValidates ("kaboom", "boom", { minLength: 6 }), + "with <allowEmpty>": assertValidates ("hello", "", { allowEmpty: false }), + "with <minimum>": assertValidates ( 512, 43, { minimum: 473 }), + "with <maximum>": assertValidates ( 512, 1949, { maximum: 678 }), + "with <divisibleBy>": assertValidates ( 10, 9, { divisibleBy: 5 }), + "with <divisibleBy> decimal": assertValidates ( 0.2, 0.009, { divisibleBy: 0.01 }), + "with <enum>": assertValidates ("orange", "cigar", { enum: ["orange", "apple", "pear"] }), + "with <format>:'url'": assertValidates ('http://test.com/', 'hello', { format: 'url' }), + "with <dependencies>": { + topic: { + properties: { + town: { dependencies: "country" }, + country: { } + } + }, + "when the object conforms": { + topic: function (schema) { + return revalidator.validate({ town: "luna", country: "moon" }, schema); + }, + "return an object with `valid` set to true": assertValid + }, + "when the object does not conform": { + topic: function (schema) { + return revalidator.validate({ town: "luna" }, schema); + }, + "return an object with `valid` set to false": assertInvalid, + "and an error concerning the attribute": assertHasError('dependencies') + } + }, + "with <dependencies> as array": { + topic: { + properties: { + town: { dependencies: ["country", "planet"] }, + country: { }, + planet: { } + } + }, + "when the object conforms": { + topic: function (schema) { + return revalidator.validate({ town: "luna", country: "moon", planet: "mars" }, schema); + }, + "return an object with `valid` set to true": assertValid + }, + "when the object does not conform": { + topic: function (schema) { + return revalidator.validate({ town: "luna", planet: "mars" }, schema); + }, + "return an object with `valid` set to false": assertInvalid, + "and an error concerning the attribute": assertHasError('dependencies') + } + }, + "with <dependencies> as schema": { + topic: { + properties: { + town: { + type: 'string', + dependencies: { + properties: { x: { type: "number" } } + } + }, + country: { } + } + }, + "when the object conforms": { + topic: function (schema) { + return revalidator.validate({ town: "luna", x: 1 }, schema); + }, + "return an object with `valid` set to true": assertValid, + }, + "when the object does not conform": { + topic: function (schema) { + return revalidator.validate({ town: "luna", x: 'no' }, schema); + }, + "return an object with `valid` set to false": assertInvalid + } + }, + "with <type>:'integer' and": { + "<minimum> constraints": assertValidates ( 512, 43, { minimum: 473, type: 'integer' }), + "<maximum> constraints": assertValidates ( 512, 1949, { maximum: 678, type: 'integer' }), + "<divisibleBy> constraints": assertValidates ( 10, 9, { divisibleBy: 5, type: 'integer' }) + }, + "with <additionalProperties>:false": { + topic: { + properties: { + town: { type: 'string' } + }, + additionalProperties: false + }, + "when the object conforms": { + topic: function (schema) { + return revalidator.validate({ town: "luna" }, schema); + }, + "return an object with `valid` set to true": assertValid + }, + "when the object does not conform": { + topic: function (schema) { + return revalidator.validate({ town: "luna", area: 'park' }, schema); + }, + "return an object with `valid` set to false": assertInvalid + } + } + } +}).addBatch({ + "A schema": { + topic: { + name: 'Article', + properties: { + title: { + type: 'string', + maxLength: 140, + conditions: { + optional: function () { + return !this.published; + } + } + }, + date: { type: 'string', format: 'date', messages: { format: "must be a valid %{expected} and nothing else" } }, + body: { type: 'string' }, + tags: { + type: 'array', + uniqueItems: true, + minItems: 2, + items: { + type: 'string', + pattern: /[a-z ]+/ + } + }, + tuple: { + type: 'array', + minItems: 2, + maxItems: 2, + items: { + type: ['string', 'number'] + } + }, + author: { type: 'string', pattern: /^[\w ]+$/i, required: true, messages: { required: "is essential for survival" } }, + published: { type: 'boolean', 'default': false }, + category: { type: 'string' }, + palindrome: {type: 'string', conform: function(val) { + return val == val.split("").reverse().join(""); } + }, + name: { type: 'string', default: '', conform: function(val, data) { + return (val === data.author); } + } + }, + patternProperties: { + '^_': { + type: 'boolean', default: false + } + } + }, + "and an object": { + topic: { + title: 'Gimme some Gurus', + date: '2012-02-04', + body: "And I will pwn your codex.", + tags: ['energy drinks', 'code'], + tuple: ['string0', 103], + author: 'cloudhead', + published: true, + category: 'misc', + palindrome: 'dennis sinned', + name: 'cloudhead', + _flag: true + }, + "can be validated with `revalidator.validate`": { + "and if it conforms": { + topic: function (object, schema) { + return revalidator.validate(object, schema); + }, + "return an object with the `valid` property set to true": assertValid, + "return an object with the `errors` property as an empty array": function (res) { + assert.isArray(res.errors); + assert.isEmpty(res.errors); + } + }, + "and if it has a missing required property": { + topic: function (object, schema) { + object = clone(object); + delete object.author; + return revalidator.validate(object, schema); + }, + "return an object with `valid` set to false": assertInvalid, + "and an error concerning the 'required' attribute": assertHasError('required'), + "and the error message defined": assertHasErrorMsg('required', "is essential for survival") + }, + "and if it has a missing non-required property": { + topic: function (object, schema) { + object = clone(object); + delete object.category; + return revalidator.validate(object, schema); + }, + "return an object with `valid` set to false": assertValid + }, + "and if it has a incorrect pattern property": { + topic: function (object, schema) { + object = clone(object); + object._additionalFlag = 'text'; + return revalidator.validate(object, schema); + }, + "return an object with `valid` set to false": assertInvalid + }, + "and if it has a incorrect unique array property": { + topic: function (object, schema) { + object = clone(object); + object.tags = ['a', 'a']; + return revalidator.validate(object, schema); + }, + "return an object with `valid` set to false": assertInvalid + }, + "and if it has a incorrect array property (wrong values)": { + topic: function (object, schema) { + object = clone(object); + object.tags = ['a', '____']; + return revalidator.validate(object, schema); + }, + "return an object with `valid` set to false": assertInvalid + }, + "and if it has a incorrect array property (< minItems)": { + topic: function (object, schema) { + object = clone(object); + object.tags = ['x']; + return revalidator.validate(object, schema); + }, + "return an object with `valid` set to false": assertInvalid + }, + "and if it has a incorrect format (date)": { + topic: function (object, schema) { + object = clone(object); + object.date = 'bad date'; + return revalidator.validate(object, schema); + }, + "return an object with `valid` set to false": assertInvalid, + "and the error message defined": assertHasErrorMsg('format', "must be a valid date and nothing else") + }, + "and if it is not a palindrome (conform function)": { + topic: function (object, schema) { + object = clone(object); + object.palindrome = 'bad palindrome'; + return revalidator.validate(object, schema); + }, + "return an object with `valid` set to false": assertInvalid + }, + "and if it didn't validate a pattern": { + topic: function (object, schema) { + object = clone(object); + object.author = 'email@address.com'; + return revalidator.validate(object, schema); + }, + "return an object with `valid` set to false": assertInvalid, + "and an error concerning the 'pattern' attribute": assertHasError('pattern') + }, + } + }, + "with <cast> option": { + topic: { + properties: { + answer: { type: "integer" }, + is_ready: { type: "boolean" } + } + }, + "and <integer> property": { + "is castable string": { + topic: function (schema) { + return revalidator.validate({ answer: "42" }, schema, { cast: true }); + }, + "return an object with `valid` set to true": assertValid + }, + "is uncastable string": { + topic: function (schema) { + return revalidator.validate({ answer: "forty2" }, schema, { cast: true }); + }, + "return an object with `valid` set to false": assertInvalid + }, + "is casted to integer": { + topic: function (schema) { + var object = { answer: "42" }; + revalidator.validate(object, schema, { cast: true }); + return object; + }, + "return an object with `answer` set to 42": function(res) { assert.strictEqual(res.answer, 42) } + } + }, + "and <boolean> property": { + "is castable 'true/false' string": { + topic: function (schema) { + return revalidator.validate({ is_ready: "true" }, schema, { cast: true }); + }, + "return an object with `valid` set to true": assertValid + }, + "is castable '1/0' string": { + topic: function (schema) { + return revalidator.validate({ is_ready: "1" }, schema, { cast: true }); + }, + "return an object with `valid` set to true": assertValid + }, + "is castable `1/0` integer": { + topic: function (schema) { + return revalidator.validate({ is_ready: 1 }, schema, { cast: true }); + }, + "return an object with `valid` set to true": assertValid + }, + "is uncastable string": { + topic: function (schema) { + return revalidator.validate({ is_ready: "not yet" }, schema, { cast: true }); + }, + "return an object with `valid` set to false": assertInvalid + }, + "is uncastable number": { + topic: function (schema) { + return revalidator.validate({ is_ready: 42 }, schema, { cast: true }); + }, + "return an object with `valid` set to false": assertInvalid + }, + "is casted to boolean": { + topic: function (schema) { + var object = { is_ready: "true" }; + revalidator.validate(object, schema, { cast: true }); + return object; + }, + "return an object with `is_ready` set to true": function(res) { assert.strictEqual(res.is_ready, true) } + } + } + } + } +}).export(module); diff --git a/node_modules/rimraf/LICENSE b/node_modules/rimraf/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/rimraf/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/rimraf/README.md b/node_modules/rimraf/README.md new file mode 100644 index 0000000..423b8cf --- /dev/null +++ b/node_modules/rimraf/README.md @@ -0,0 +1,101 @@ +[![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) + +The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. + +Install with `npm install rimraf`, or just drop rimraf.js somewhere. + +## API + +`rimraf(f, [opts], callback)` + +The first parameter will be interpreted as a globbing pattern for files. If you +want to disable globbing you can do so with `opts.disableGlob` (defaults to +`false`). This might be handy, for instance, if you have filenames that contain +globbing wildcard characters. + +The callback will be called with an error if there is one. Certain +errors are handled for you: + +* Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of + `opts.maxBusyTries` times before giving up, adding 100ms of wait + between each attempt. The default `maxBusyTries` is 3. +* `ENOENT` - If the file doesn't exist, rimraf will return + successfully, since your desired outcome is already the case. +* `EMFILE` - Since `readdir` requires opening a file descriptor, it's + possible to hit `EMFILE` if too many file descriptors are in use. + In the sync case, there's nothing to be done for this. But in the + async case, rimraf will gradually back off with timeouts up to + `opts.emfileWait` ms, which defaults to 1000. + +## options + +* unlink, chmod, stat, lstat, rmdir, readdir, + unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync + + In order to use a custom file system library, you can override + specific fs functions on the options object. + + If any of these functions are present on the options object, then + the supplied function will be used instead of the default fs + method. + + Sync methods are only relevant for `rimraf.sync()`, of course. + + For example: + + ```javascript + var myCustomFS = require('some-custom-fs') + + rimraf('some-thing', myCustomFS, callback) + ``` + +* maxBusyTries + + If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered + on Windows systems, then rimraf will retry with a linear backoff + wait of 100ms longer on each try. The default maxBusyTries is 3. + + Only relevant for async usage. + +* emfileWait + + If an `EMFILE` error is encountered, then rimraf will retry + repeatedly with a linear backoff of 1ms longer on each try, until + the timeout counter hits this max. The default limit is 1000. + + If you repeatedly encounter `EMFILE` errors, then consider using + [graceful-fs](http://npm.im/graceful-fs) in your program. + + Only relevant for async usage. + +* glob + + Set to `false` to disable [glob](http://npm.im/glob) pattern + matching. + + Set to an object to pass options to the glob module. The default + glob options are `{ nosort: true, silent: true }`. + + Glob version 6 is used in this module. + + Relevant for both sync and async usage. + +* disableGlob + + Set to any non-falsey value to disable globbing entirely. + (Equivalent to setting `glob: false`.) + +## rimraf.sync + +It can remove stuff synchronously, too. But that's not so good. Use +the async API. It's better. + +## CLI + +If installed with `npm install rimraf -g` it can be used as a global +command `rimraf <path> [<path> ...]` which is useful for cross platform support. + +## mkdirp + +If you need to create a directory recursively, check out +[mkdirp](https://github.com/substack/node-mkdirp). diff --git a/node_modules/rimraf/bin.js b/node_modules/rimraf/bin.js new file mode 100644 index 0000000..0d1e17b --- /dev/null +++ b/node_modules/rimraf/bin.js @@ -0,0 +1,50 @@ +#!/usr/bin/env node + +var rimraf = require('./') + +var help = false +var dashdash = false +var noglob = false +var args = process.argv.slice(2).filter(function(arg) { + if (dashdash) + return !!arg + else if (arg === '--') + dashdash = true + else if (arg === '--no-glob' || arg === '-G') + noglob = true + else if (arg === '--glob' || arg === '-g') + noglob = false + else if (arg.match(/^(-+|\/)(h(elp)?|\?)$/)) + help = true + else + return !!arg +}) + +if (help || args.length === 0) { + // If they didn't ask for help, then this is not a "success" + var log = help ? console.log : console.error + log('Usage: rimraf <path> [<path> ...]') + log('') + log(' Deletes all files and folders at "path" recursively.') + log('') + log('Options:') + log('') + log(' -h, --help Display this usage info') + log(' -G, --no-glob Do not expand glob patterns in arguments') + log(' -g, --glob Expand glob patterns in arguments (default)') + process.exit(help ? 0 : 1) +} else + go(0) + +function go (n) { + if (n >= args.length) + return + var options = {} + if (noglob) + options = { glob: false } + rimraf(args[n], options, function (er) { + if (er) + throw er + go(n+1) + }) +} diff --git a/node_modules/rimraf/package.json b/node_modules/rimraf/package.json new file mode 100644 index 0000000..871c823 --- /dev/null +++ b/node_modules/rimraf/package.json @@ -0,0 +1,67 @@ +{ + "_from": "rimraf@2.x.x", + "_id": "rimraf@2.7.1", + "_inBundle": false, + "_integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "_location": "/rimraf", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "rimraf@2.x.x", + "name": "rimraf", + "escapedName": "rimraf", + "rawSpec": "2.x.x", + "saveSpec": null, + "fetchSpec": "2.x.x" + }, + "_requiredBy": [ + "/utile" + ], + "_resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "_shasum": "35797f13a7fdadc566142c29d4f07ccad483e3ec", + "_spec": "rimraf@2.x.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/utile", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bin": { + "rimraf": "bin.js" + }, + "bugs": { + "url": "https://github.com/isaacs/rimraf/issues" + }, + "bundleDependencies": false, + "dependencies": { + "glob": "^7.1.3" + }, + "deprecated": false, + "description": "A deep deletion module for node (like `rm -rf`)", + "devDependencies": { + "mkdirp": "^0.5.1", + "tap": "^12.1.1" + }, + "files": [ + "LICENSE", + "README.md", + "bin.js", + "rimraf.js" + ], + "homepage": "https://github.com/isaacs/rimraf#readme", + "license": "ISC", + "main": "rimraf.js", + "name": "rimraf", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/rimraf.git" + }, + "scripts": { + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap test/*.js" + }, + "version": "2.7.1" +} diff --git a/node_modules/rimraf/rimraf.js b/node_modules/rimraf/rimraf.js new file mode 100644 index 0000000..a90ad02 --- /dev/null +++ b/node_modules/rimraf/rimraf.js @@ -0,0 +1,372 @@ +module.exports = rimraf +rimraf.sync = rimrafSync + +var assert = require("assert") +var path = require("path") +var fs = require("fs") +var glob = undefined +try { + glob = require("glob") +} catch (_err) { + // treat glob as optional. +} +var _0666 = parseInt('666', 8) + +var defaultGlobOpts = { + nosort: true, + silent: true +} + +// for EMFILE handling +var timeout = 0 + +var isWindows = (process.platform === "win32") + +function defaults (options) { + var methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(function(m) { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) + + options.maxBusyTries = options.maxBusyTries || 3 + options.emfileWait = options.emfileWait || 1000 + if (options.glob === false) { + options.disableGlob = true + } + if (options.disableGlob !== true && glob === undefined) { + throw Error('glob dependency not found, set `options.disableGlob = true` if intentional') + } + options.disableGlob = options.disableGlob || false + options.glob = options.glob || defaultGlobOpts +} + +function rimraf (p, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert.equal(typeof cb, 'function', 'rimraf: callback function required') + assert(options, 'rimraf: invalid options argument provided') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + + defaults(options) + + var busyTries = 0 + var errState = null + var n = 0 + + if (options.disableGlob || !glob.hasMagic(p)) + return afterGlob(null, [p]) + + options.lstat(p, function (er, stat) { + if (!er) + return afterGlob(null, [p]) + + glob(p, options.glob, afterGlob) + }) + + function next (er) { + errState = errState || er + if (--n === 0) + cb(errState) + } + + function afterGlob (er, results) { + if (er) + return cb(er) + + n = results.length + if (n === 0) + return cb() + + results.forEach(function (p) { + rimraf_(p, options, function CB (er) { + if (er) { + if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && + busyTries < options.maxBusyTries) { + busyTries ++ + var time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(function () { + rimraf_(p, options, CB) + }, time) + } + + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < options.emfileWait) { + return setTimeout(function () { + rimraf_(p, options, CB) + }, timeout ++) + } + + // already gone + if (er.code === "ENOENT") er = null + } + + timeout = 0 + next(er) + }) + }) + } +} + +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, function (er, st) { + if (er && er.code === "ENOENT") + return cb(null) + + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === "EPERM" && isWindows) + fixWinEPERM(p, options, er, cb) + + if (st && st.isDirectory()) + return rmdir(p, options, er, cb) + + options.unlink(p, function (er) { + if (er) { + if (er.code === "ENOENT") + return cb(null) + if (er.code === "EPERM") + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + if (er.code === "EISDIR") + return rmdir(p, options, er, cb) + } + return cb(er) + }) + }) +} + +function fixWinEPERM (p, options, er, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + if (er) + assert(er instanceof Error) + + options.chmod(p, _0666, function (er2) { + if (er2) + cb(er2.code === "ENOENT" ? null : er) + else + options.stat(p, function(er3, stats) { + if (er3) + cb(er3.code === "ENOENT" ? null : er) + else if (stats.isDirectory()) + rmdir(p, options, er, cb) + else + options.unlink(p, cb) + }) + }) +} + +function fixWinEPERMSync (p, options, er) { + assert(p) + assert(options) + if (er) + assert(er instanceof Error) + + try { + options.chmodSync(p, _0666) + } catch (er2) { + if (er2.code === "ENOENT") + return + else + throw er + } + + try { + var stats = options.statSync(p) + } catch (er3) { + if (er3.code === "ENOENT") + return + else + throw er + } + + if (stats.isDirectory()) + rmdirSync(p, options, er) + else + options.unlinkSync(p) +} + +function rmdir (p, options, originalEr, cb) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + assert(typeof cb === 'function') + + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, function (er) { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) + rmkids(p, options, cb) + else if (er && er.code === "ENOTDIR") + cb(originalEr) + else + cb(er) + }) +} + +function rmkids(p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.readdir(p, function (er, files) { + if (er) + return cb(er) + var n = files.length + if (n === 0) + return options.rmdir(p, cb) + var errState + files.forEach(function (f) { + rimraf(path.join(p, f), options, function (er) { + if (errState) + return + if (er) + return cb(errState = er) + if (--n === 0) + options.rmdir(p, cb) + }) + }) + }) +} + +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p, options) { + options = options || {} + defaults(options) + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + + var results + + if (options.disableGlob || !glob.hasMagic(p)) { + results = [p] + } else { + try { + options.lstatSync(p) + results = [p] + } catch (er) { + results = glob.sync(p, options.glob) + } + } + + if (!results.length) + return + + for (var i = 0; i < results.length; i++) { + var p = results[i] + + try { + var st = options.lstatSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + + // Windows can EPERM on stat. Life is suffering. + if (er.code === "EPERM" && isWindows) + fixWinEPERMSync(p, options, er) + } + + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) + rmdirSync(p, options, null) + else + options.unlinkSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "EPERM") + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + if (er.code !== "EISDIR") + throw er + + rmdirSync(p, options, er) + } + } +} + +function rmdirSync (p, options, originalEr) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "ENOTDIR") + throw originalEr + if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") + rmkidsSync(p, options) + } +} + +function rmkidsSync (p, options) { + assert(p) + assert(options) + options.readdirSync(p).forEach(function (f) { + rimrafSync(path.join(p, f), options) + }) + + // We only end up here once we got ENOTEMPTY at least once, and + // at this point, we are guaranteed to have removed all the kids. + // So, we know that it won't be ENOENT or ENOTDIR or anything else. + // try really hard to delete stuff on windows, because it has a + // PROFOUNDLY annoying habit of not closing handles promptly when + // files are deleted, resulting in spurious ENOTEMPTY errors. + var retries = isWindows ? 100 : 1 + var i = 0 + do { + var threw = true + try { + var ret = options.rmdirSync(p, options) + threw = false + return ret + } finally { + if (++i < retries && threw) + continue + } + } while (true) +} diff --git a/node_modules/signal-exit/CHANGELOG.md b/node_modules/signal-exit/CHANGELOG.md new file mode 100644 index 0000000..ed104f4 --- /dev/null +++ b/node_modules/signal-exit/CHANGELOG.md @@ -0,0 +1,35 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [3.0.3](https://github.com/tapjs/signal-exit/compare/v3.0.2...v3.0.3) (2020-03-26) + + +### Bug Fixes + +* patch `SIGHUP` to `SIGINT` when on Windows ([cfd1046](https://github.com/tapjs/signal-exit/commit/cfd1046079af4f0e44f93c69c237a09de8c23ef2)) +* **ci:** use Travis for Windows builds ([007add7](https://github.com/tapjs/signal-exit/commit/007add793d2b5ae3c382512103adbf321768a0b8)) + +<a name="3.0.1"></a> +## [3.0.1](https://github.com/tapjs/signal-exit/compare/v3.0.0...v3.0.1) (2016-09-08) + + +### Bug Fixes + +* do not listen on SIGBUS, SIGFPE, SIGSEGV and SIGILL ([#40](https://github.com/tapjs/signal-exit/issues/40)) ([5b105fb](https://github.com/tapjs/signal-exit/commit/5b105fb)) + + + +<a name="3.0.0"></a> +# [3.0.0](https://github.com/tapjs/signal-exit/compare/v2.1.2...v3.0.0) (2016-06-13) + + +### Bug Fixes + +* get our test suite running on Windows ([#23](https://github.com/tapjs/signal-exit/issues/23)) ([6f3eda8](https://github.com/tapjs/signal-exit/commit/6f3eda8)) +* hooking SIGPROF was interfering with profilers see [#21](https://github.com/tapjs/signal-exit/issues/21) ([#24](https://github.com/tapjs/signal-exit/issues/24)) ([1248a4c](https://github.com/tapjs/signal-exit/commit/1248a4c)) + + +### BREAKING CHANGES + +* signal-exit no longer wires into SIGPROF diff --git a/node_modules/signal-exit/LICENSE.txt b/node_modules/signal-exit/LICENSE.txt new file mode 100644 index 0000000..eead04a --- /dev/null +++ b/node_modules/signal-exit/LICENSE.txt @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/signal-exit/README.md b/node_modules/signal-exit/README.md new file mode 100644 index 0000000..9f8eb59 --- /dev/null +++ b/node_modules/signal-exit/README.md @@ -0,0 +1,39 @@ +# signal-exit + +[![Build Status](https://travis-ci.org/tapjs/signal-exit.png)](https://travis-ci.org/tapjs/signal-exit) +[![Coverage](https://coveralls.io/repos/tapjs/signal-exit/badge.svg?branch=master)](https://coveralls.io/r/tapjs/signal-exit?branch=master) +[![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) + +When you want to fire an event no matter how a process exits: + +* reaching the end of execution. +* explicitly having `process.exit(code)` called. +* having `process.kill(pid, sig)` called. +* receiving a fatal signal from outside the process + +Use `signal-exit`. + +```js +var onExit = require('signal-exit') + +onExit(function (code, signal) { + console.log('process exited!') +}) +``` + +## API + +`var remove = onExit(function (code, signal) {}, options)` + +The return value of the function is a function that will remove the +handler. + +Note that the function *only* fires for signals if the signal would +cause the proces to exit. That is, there are no other listeners, and +it is a fatal signal. + +## Options + +* `alwaysLast`: Run this handler after any other signal or exit + handlers. This causes `process.emit` to be monkeypatched. diff --git a/node_modules/signal-exit/index.js b/node_modules/signal-exit/index.js new file mode 100644 index 0000000..6b6c43a --- /dev/null +++ b/node_modules/signal-exit/index.js @@ -0,0 +1,163 @@ +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +var assert = require('assert') +var signals = require('./signals.js') +var isWin = /^win/i.test(process.platform) + +var EE = require('events') +/* istanbul ignore if */ +if (typeof EE !== 'function') { + EE = EE.EventEmitter +} + +var emitter +if (process.__signal_exit_emitter__) { + emitter = process.__signal_exit_emitter__ +} else { + emitter = process.__signal_exit_emitter__ = new EE() + emitter.count = 0 + emitter.emitted = {} +} + +// Because this emitter is a global, we have to check to see if a +// previous version of this library failed to enable infinite listeners. +// I know what you're about to say. But literally everything about +// signal-exit is a compromise with evil. Get used to it. +if (!emitter.infinite) { + emitter.setMaxListeners(Infinity) + emitter.infinite = true +} + +module.exports = function (cb, opts) { + assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') + + if (loaded === false) { + load() + } + + var ev = 'exit' + if (opts && opts.alwaysLast) { + ev = 'afterexit' + } + + var remove = function () { + emitter.removeListener(ev, cb) + if (emitter.listeners('exit').length === 0 && + emitter.listeners('afterexit').length === 0) { + unload() + } + } + emitter.on(ev, cb) + + return remove +} + +module.exports.unload = unload +function unload () { + if (!loaded) { + return + } + loaded = false + + signals.forEach(function (sig) { + try { + process.removeListener(sig, sigListeners[sig]) + } catch (er) {} + }) + process.emit = originalProcessEmit + process.reallyExit = originalProcessReallyExit + emitter.count -= 1 +} + +function emit (event, code, signal) { + if (emitter.emitted[event]) { + return + } + emitter.emitted[event] = true + emitter.emit(event, code, signal) +} + +// { <signal>: <listener fn>, ... } +var sigListeners = {} +signals.forEach(function (sig) { + sigListeners[sig] = function listener () { + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + var listeners = process.listeners(sig) + if (listeners.length === emitter.count) { + unload() + emit('exit', null, sig) + /* istanbul ignore next */ + emit('afterexit', null, sig) + /* istanbul ignore next */ + if (isWin && sig === 'SIGHUP') { + // "SIGHUP" throws an `ENOSYS` error on Windows, + // so use a supported signal instead + sig = 'SIGINT' + } + process.kill(process.pid, sig) + } + } +}) + +module.exports.signals = function () { + return signals +} + +module.exports.load = load + +var loaded = false + +function load () { + if (loaded) { + return + } + loaded = true + + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + emitter.count += 1 + + signals = signals.filter(function (sig) { + try { + process.on(sig, sigListeners[sig]) + return true + } catch (er) { + return false + } + }) + + process.emit = processEmit + process.reallyExit = processReallyExit +} + +var originalProcessReallyExit = process.reallyExit +function processReallyExit (code) { + process.exitCode = code || 0 + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + /* istanbul ignore next */ + originalProcessReallyExit.call(process, process.exitCode) +} + +var originalProcessEmit = process.emit +function processEmit (ev, arg) { + if (ev === 'exit') { + if (arg !== undefined) { + process.exitCode = arg + } + var ret = originalProcessEmit.apply(this, arguments) + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + return ret + } else { + return originalProcessEmit.apply(this, arguments) + } +} diff --git a/node_modules/signal-exit/package.json b/node_modules/signal-exit/package.json new file mode 100644 index 0000000..7f79a0f --- /dev/null +++ b/node_modules/signal-exit/package.json @@ -0,0 +1,66 @@ +{ + "_from": "signal-exit@^3.0.2", + "_id": "signal-exit@3.0.3", + "_inBundle": false, + "_integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==", + "_location": "/signal-exit", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "signal-exit@^3.0.2", + "name": "signal-exit", + "escapedName": "signal-exit", + "rawSpec": "^3.0.2", + "saveSpec": null, + "fetchSpec": "^3.0.2" + }, + "_requiredBy": [ + "/restore-cursor" + ], + "_resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", + "_shasum": "a1410c2edd8f077b08b4e253c8eacfcaf057461c", + "_spec": "signal-exit@^3.0.2", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/restore-cursor", + "author": { + "name": "Ben Coe", + "email": "ben@npmjs.com" + }, + "bugs": { + "url": "https://github.com/tapjs/signal-exit/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "when you want to fire an event no matter how a process exits.", + "devDependencies": { + "chai": "^3.5.0", + "coveralls": "^2.11.10", + "nyc": "^8.1.0", + "standard": "^8.1.0", + "standard-version": "^2.3.0", + "tap": "^8.0.1" + }, + "files": [ + "index.js", + "signals.js" + ], + "homepage": "https://github.com/tapjs/signal-exit", + "keywords": [ + "signal", + "exit" + ], + "license": "ISC", + "main": "index.js", + "name": "signal-exit", + "repository": { + "type": "git", + "url": "git+https://github.com/tapjs/signal-exit.git" + }, + "scripts": { + "coverage": "nyc report --reporter=text-lcov | coveralls", + "pretest": "standard", + "release": "standard-version", + "test": "tap --timeout=240 ./test/*.js --cov" + }, + "version": "3.0.3" +} diff --git a/node_modules/signal-exit/signals.js b/node_modules/signal-exit/signals.js new file mode 100644 index 0000000..3bd67a8 --- /dev/null +++ b/node_modules/signal-exit/signals.js @@ -0,0 +1,53 @@ +// This is not the set of all possible signals. +// +// It IS, however, the set of all signals that trigger +// an exit on either Linux or BSD systems. Linux is a +// superset of the signal names supported on BSD, and +// the unknown signals just fail to register, so we can +// catch that easily enough. +// +// Don't bother with SIGKILL. It's uncatchable, which +// means that we can't fire any callbacks anyway. +// +// If a user does happen to register a handler on a non- +// fatal signal like SIGWINCH or something, and then +// exit, it'll end up firing `process.emit('exit')`, so +// the handler will be fired anyway. +// +// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised +// artificially, inherently leave the process in a +// state from which it is not safe to try and enter JS +// listeners. +module.exports = [ + 'SIGABRT', + 'SIGALRM', + 'SIGHUP', + 'SIGINT', + 'SIGTERM' +] + +if (process.platform !== 'win32') { + module.exports.push( + 'SIGVTALRM', + 'SIGXCPU', + 'SIGXFSZ', + 'SIGUSR2', + 'SIGTRAP', + 'SIGSYS', + 'SIGQUIT', + 'SIGIOT' + // should detect profiler and enable/disable accordingly. + // see #21 + // 'SIGPROF' + ) +} + +if (process.platform === 'linux') { + module.exports.push( + 'SIGIO', + 'SIGPOLL', + 'SIGPWR', + 'SIGSTKFLT', + 'SIGUNUSED' + ) +} diff --git a/node_modules/stack-trace/.npmignore b/node_modules/stack-trace/.npmignore new file mode 100644 index 0000000..b59f7e3 --- /dev/null +++ b/node_modules/stack-trace/.npmignore @@ -0,0 +1 @@ +test/
\ No newline at end of file diff --git a/node_modules/stack-trace/License b/node_modules/stack-trace/License new file mode 100644 index 0000000..11ec094 --- /dev/null +++ b/node_modules/stack-trace/License @@ -0,0 +1,19 @@ +Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.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. diff --git a/node_modules/stack-trace/Makefile b/node_modules/stack-trace/Makefile new file mode 100644 index 0000000..a7ce31d --- /dev/null +++ b/node_modules/stack-trace/Makefile @@ -0,0 +1,11 @@ +SHELL := /bin/bash + +test: + @./test/run.js + +release: + git push + git push --tags + npm publish . + +.PHONY: test diff --git a/node_modules/stack-trace/Readme.md b/node_modules/stack-trace/Readme.md new file mode 100644 index 0000000..fcd1b97 --- /dev/null +++ b/node_modules/stack-trace/Readme.md @@ -0,0 +1,98 @@ +# stack-trace + +Get v8 stack traces as an array of CallSite objects. + +## Install + +``` bash +npm install stack-trace +``` + +## Usage + +The stack-trace module makes it easy for you to capture the current stack: + +``` javascript +var stackTrace = require('stack-trace'); +var trace = stackTrace.get(); + +require('assert').strictEqual(trace[0].getFileName(), __filename); +``` + +However, sometimes you have already popped the stack you are interested in, +and all you have left is an `Error` object. This module can help: + +``` javascript +var stackTrace = require('stack-trace'); +var err = new Error('something went wrong'); +var trace = stackTrace.parse(err); + +require('assert').strictEqual(trace[0].getFileName(), __filename); +``` + +Please note that parsing the `Error#stack` property is not perfect, only +certain properties can be retrieved with it as noted in the API docs below. + +## Long stack traces + +stack-trace works great with [long-stack-traces][], when parsing an `err.stack` +that has crossed the event loop boundary, a `CallSite` object returning +`'----------------------------------------'` for `getFileName()` is created. +All other methods of the event loop boundary call site return `null`. + +[long-stack-traces]: https://github.com/tlrobinson/long-stack-traces + +## API + +### stackTrace.get([belowFn]) + +Returns an array of `CallSite` objects, where element `0` is the current call +site. + +When passing a function on the current stack as the `belowFn` parameter, the +returned array will only include `CallSite` objects below this function. + +### stackTrace.parse(err) + +Parses the `err.stack` property of an `Error` object into an array compatible +with those returned by `stackTrace.get()`. However, only the following methods +are implemented on the returned `CallSite` objects. + +* getTypeName +* getFunctionName +* getMethodName +* getFileName +* getLineNumber +* getColumnNumber +* isNative + +Note: Except `getFunctionName()`, all of the above methods return exactly the +same values as you would get from `stackTrace.get()`. `getFunctionName()` +is sometimes a little different, but still useful. + +### CallSite + +The official v8 CallSite object API can be found [here][v8stackapi]. A quick +excerpt: + +> A CallSite object defines the following methods: +> +> * **getThis**: returns the value of this +> * **getTypeName**: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object's [[Class]] internal property. +> * **getFunction**: returns the current function +> * **getFunctionName**: returns the name of the current function, typically its name property. If a name property is not available an attempt will be made to try to infer a name from the function's context. +> * **getMethodName**: returns the name of the property of this or one of its prototypes that holds the current function +> * **getFileName**: if this function was defined in a script returns the name of the script +> * **getLineNumber**: if this function was defined in a script returns the current line number +> * **getColumnNumber**: if this function was defined in a script returns the current column number +> * **getEvalOrigin**: if this function was created using a call to eval returns a CallSite object representing the location where eval was called +> * **isToplevel**: is this a toplevel invocation, that is, is this the global object? +> * **isEval**: does this call take place in code defined by a call to eval? +> * **isNative**: is this call in native V8 code? +> * **isConstructor**: is this a constructor call? + +[v8stackapi]: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + +## License + +stack-trace is licensed under the MIT license. diff --git a/node_modules/stack-trace/lib/stack-trace.js b/node_modules/stack-trace/lib/stack-trace.js new file mode 100644 index 0000000..cbadd58 --- /dev/null +++ b/node_modules/stack-trace/lib/stack-trace.js @@ -0,0 +1,136 @@ +exports.get = function(belowFn) { + var oldLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Infinity; + + var dummyObject = {}; + + var v8Handler = Error.prepareStackTrace; + Error.prepareStackTrace = function(dummyObject, v8StackTrace) { + return v8StackTrace; + }; + Error.captureStackTrace(dummyObject, belowFn || exports.get); + + var v8StackTrace = dummyObject.stack; + Error.prepareStackTrace = v8Handler; + Error.stackTraceLimit = oldLimit; + + return v8StackTrace; +}; + +exports.parse = function(err) { + if (!err.stack) { + return []; + } + + var self = this; + var lines = err.stack.split('\n').slice(1); + + return lines + .map(function(line) { + if (line.match(/^\s*[-]{4,}$/)) { + return self._createParsedCallSite({ + fileName: line, + lineNumber: null, + functionName: null, + typeName: null, + methodName: null, + columnNumber: null, + 'native': null, + }); + } + + var lineMatch = line.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/); + if (!lineMatch) { + return; + } + + var object = null; + var method = null; + var functionName = null; + var typeName = null; + var methodName = null; + var isNative = (lineMatch[5] === 'native'); + + if (lineMatch[1]) { + functionName = lineMatch[1]; + var methodStart = functionName.lastIndexOf('.'); + if (functionName[methodStart-1] == '.') + methodStart--; + if (methodStart > 0) { + object = functionName.substr(0, methodStart); + method = functionName.substr(methodStart + 1); + var objectEnd = object.indexOf('.Module'); + if (objectEnd > 0) { + functionName = functionName.substr(objectEnd + 1); + object = object.substr(0, objectEnd); + } + } + typeName = null; + } + + if (method) { + typeName = object; + methodName = method; + } + + if (method === '<anonymous>') { + methodName = null; + functionName = null; + } + + var properties = { + fileName: lineMatch[2] || null, + lineNumber: parseInt(lineMatch[3], 10) || null, + functionName: functionName, + typeName: typeName, + methodName: methodName, + columnNumber: parseInt(lineMatch[4], 10) || null, + 'native': isNative, + }; + + return self._createParsedCallSite(properties); + }) + .filter(function(callSite) { + return !!callSite; + }); +}; + +function CallSite(properties) { + for (var property in properties) { + this[property] = properties[property]; + } +} + +var strProperties = [ + 'this', + 'typeName', + 'functionName', + 'methodName', + 'fileName', + 'lineNumber', + 'columnNumber', + 'function', + 'evalOrigin' +]; +var boolProperties = [ + 'topLevel', + 'eval', + 'native', + 'constructor' +]; +strProperties.forEach(function (property) { + CallSite.prototype[property] = null; + CallSite.prototype['get' + property[0].toUpperCase() + property.substr(1)] = function () { + return this[property]; + } +}); +boolProperties.forEach(function (property) { + CallSite.prototype[property] = false; + CallSite.prototype['is' + property[0].toUpperCase() + property.substr(1)] = function () { + return this[property]; + } +}); + +exports._createParsedCallSite = function(properties) { + return new CallSite(properties); +}; diff --git a/node_modules/stack-trace/package.json b/node_modules/stack-trace/package.json new file mode 100644 index 0000000..edd3073 --- /dev/null +++ b/node_modules/stack-trace/package.json @@ -0,0 +1,53 @@ +{ + "_from": "stack-trace@0.0.x", + "_id": "stack-trace@0.0.10", + "_inBundle": false, + "_integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=", + "_location": "/stack-trace", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "stack-trace@0.0.x", + "name": "stack-trace", + "escapedName": "stack-trace", + "rawSpec": "0.0.x", + "saveSpec": null, + "fetchSpec": "0.0.x" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "_shasum": "547c70b347e8d32b4e108ea1a2a159e5fdde19c0", + "_spec": "stack-trace@0.0.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/winston", + "author": { + "name": "Felix Geisendörfer", + "email": "felix@debuggable.com", + "url": "http://debuggable.com/" + }, + "bugs": { + "url": "https://github.com/felixge/node-stack-trace/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Get v8 stack traces as an array of CallSite objects.", + "devDependencies": { + "far": "0.0.3", + "long-stack-traces": "0.1.2" + }, + "engines": { + "node": "*" + }, + "homepage": "https://github.com/felixge/node-stack-trace", + "license": "MIT", + "main": "./lib/stack-trace", + "name": "stack-trace", + "repository": { + "type": "git", + "url": "git://github.com/felixge/node-stack-trace.git" + }, + "version": "0.0.10" +} diff --git a/node_modules/strip-ansi/index.d.ts b/node_modules/strip-ansi/index.d.ts new file mode 100644 index 0000000..907fccc --- /dev/null +++ b/node_modules/strip-ansi/index.d.ts @@ -0,0 +1,17 @@ +/** +Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. + +@example +``` +import stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` +*/ +declare function stripAnsi(string: string): string; + +export = stripAnsi; diff --git a/node_modules/strip-ansi/index.js b/node_modules/strip-ansi/index.js new file mode 100644 index 0000000..9a593df --- /dev/null +++ b/node_modules/strip-ansi/index.js @@ -0,0 +1,4 @@ +'use strict'; +const ansiRegex = require('ansi-regex'); + +module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/node_modules/strip-ansi/license b/node_modules/strip-ansi/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/strip-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/strip-ansi/package.json b/node_modules/strip-ansi/package.json new file mode 100644 index 0000000..095c11c --- /dev/null +++ b/node_modules/strip-ansi/package.json @@ -0,0 +1,86 @@ +{ + "_from": "strip-ansi@^6.0.0", + "_id": "strip-ansi@6.0.0", + "_inBundle": false, + "_integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "_location": "/strip-ansi", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "strip-ansi@^6.0.0", + "name": "strip-ansi", + "escapedName": "strip-ansi", + "rawSpec": "^6.0.0", + "saveSpec": null, + "fetchSpec": "^6.0.0" + }, + "_requiredBy": [ + "/ora" + ], + "_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "_shasum": "0b1571dd7669ccd4f3e06e14ef1eed26225ae532", + "_spec": "strip-ansi@^6.0.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/ora", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/chalk/strip-ansi/issues" + }, + "bundleDependencies": false, + "dependencies": { + "ansi-regex": "^5.0.0" + }, + "deprecated": false, + "description": "Strip ANSI escape codes from a string", + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.10.0", + "xo": "^0.25.3" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/chalk/strip-ansi#readme", + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "license": "MIT", + "name": "strip-ansi", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/strip-ansi.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "6.0.0" +} diff --git a/node_modules/strip-ansi/readme.md b/node_modules/strip-ansi/readme.md new file mode 100644 index 0000000..7c4b56d --- /dev/null +++ b/node_modules/strip-ansi/readme.md @@ -0,0 +1,46 @@ +# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) + +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string + + +## Install + +``` +$ npm install strip-ansi +``` + + +## Usage + +```js +const stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` + + +## strip-ansi for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of strip-ansi 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-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + + +## Related + +- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + diff --git a/node_modules/supports-color/browser.js b/node_modules/supports-color/browser.js new file mode 100644 index 0000000..62afa3a --- /dev/null +++ b/node_modules/supports-color/browser.js @@ -0,0 +1,5 @@ +'use strict'; +module.exports = { + stdout: false, + stderr: false +}; diff --git a/node_modules/supports-color/index.js b/node_modules/supports-color/index.js new file mode 100644 index 0000000..dcaa454 --- /dev/null +++ b/node_modules/supports-color/index.js @@ -0,0 +1,139 @@ +'use strict'; +const os = require('os'); +const tty = require('tty'); +const hasFlag = require('has-flag'); + +const {env} = process; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; +} + +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if ('GITHUB_ACTIONS' in env) { + return 1; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; diff --git a/node_modules/supports-color/license b/node_modules/supports-color/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/supports-color/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/supports-color/package.json b/node_modules/supports-color/package.json new file mode 100644 index 0000000..8eefbba --- /dev/null +++ b/node_modules/supports-color/package.json @@ -0,0 +1,85 @@ +{ + "_from": "supports-color@^7.1.0", + "_id": "supports-color@7.1.0", + "_inBundle": false, + "_integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "_location": "/supports-color", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "supports-color@^7.1.0", + "name": "supports-color", + "escapedName": "supports-color", + "rawSpec": "^7.1.0", + "saveSpec": null, + "fetchSpec": "^7.1.0" + }, + "_requiredBy": [ + "/chalk" + ], + "_resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", + "_shasum": "68e32591df73e25ad1c4b49108a2ec507962bfd1", + "_spec": "supports-color@^7.1.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/chalk", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "browser": "browser.js", + "bugs": { + "url": "https://github.com/chalk/supports-color/issues" + }, + "bundleDependencies": false, + "dependencies": { + "has-flag": "^4.0.0" + }, + "deprecated": false, + "description": "Detect whether a terminal supports color", + "devDependencies": { + "ava": "^1.4.1", + "import-fresh": "^3.0.0", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "browser.js" + ], + "homepage": "https://github.com/chalk/supports-color#readme", + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "license": "MIT", + "name": "supports-color", + "repository": { + "type": "git", + "url": "git+https://github.com/chalk/supports-color.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "7.1.0" +} diff --git a/node_modules/supports-color/readme.md b/node_modules/supports-color/readme.md new file mode 100644 index 0000000..3654228 --- /dev/null +++ b/node_modules/supports-color/readme.md @@ -0,0 +1,76 @@ +# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color) + +> Detect whether a terminal supports color + + +## Install + +``` +$ npm install supports-color +``` + + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +--- + +<div align="center"> + <b> + <a href="https://tidelift.com/subscription/pkg/npm-supports-color?utm_source=npm-supports-color&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a> + </b> + <br> + <sub> + Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies. + </sub> +</div> + +--- diff --git a/node_modules/utile/.npmignore b/node_modules/utile/.npmignore new file mode 100644 index 0000000..8d8bfd5 --- /dev/null +++ b/node_modules/utile/.npmignore @@ -0,0 +1,4 @@ +node_modules +npm-debug.log +*.swp +*.swo diff --git a/node_modules/utile/.travis.yml b/node_modules/utile/.travis.yml new file mode 100644 index 0000000..b6a50e4 --- /dev/null +++ b/node_modules/utile/.travis.yml @@ -0,0 +1,10 @@ +language: node_js +node_js: + - 0.8 + - 0.10 + +notifications: + email: + - travis@nodejitsu.com + irc: "irc.freenode.org#nodejitsu" + diff --git a/node_modules/utile/CHANGELOG.md b/node_modules/utile/CHANGELOG.md new file mode 100644 index 0000000..b4e427a --- /dev/null +++ b/node_modules/utile/CHANGELOG.md @@ -0,0 +1,16 @@ + +0.1.5 / 2012-09-18 +================== + + * Fixed problem with underscore values in camelToUnderscore + +0.1.4 / 2012-07-26 +================== + + * Made use of inflect for camel to underscore conversion + +0.1.3 / 2012-07-25 +================== + + * Added camel to underscore conversion and vice-versa + diff --git a/node_modules/utile/LICENSE b/node_modules/utile/LICENSE new file mode 100644 index 0000000..58974d8 --- /dev/null +++ b/node_modules/utile/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011, Charlie Robbins & the Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/utile/README.md b/node_modules/utile/README.md new file mode 100644 index 0000000..58dfde4 --- /dev/null +++ b/node_modules/utile/README.md @@ -0,0 +1,87 @@ +# utile [![Build Status](https://secure.travis-ci.org/flatiron/utile.png)](http://travis-ci.org/flatiron/utile) + +A drop-in replacement for `util` with some additional advantageous functions + +## Motivation +Javascript is definitely a "batteries not included language" when compared to languages like Ruby or Python. Node.js has a simple utility library which exposes some basic (but important) functionality: + +``` +$ node +> var util = require('util'); +> util. +(...) + +util.debug util.error util.exec util.inherits util.inspect +util.log util.p util.print util.pump util.puts +``` + +When one considers their own utility library, why ever bother requiring `util` again? That is the approach taken by this module. To compare: + +``` +$ node +> var utile = require('./lib') +> utile. +(...) + +utile.async utile.capitalize utile.clone utile.cpr utile.createPath utile.debug +utile.each utile.error utile.exec utile.file utile.filter utile.find +utile.inherits utile.log utile.mixin utile.mkdirp utile.p utile.path +utile.print utile.pump utile.puts utile.randomString utile.requireDir uile.requireDirLazy +utile.rimraf +``` + +As you can see all of the original methods from `util` are there, but there are several new methods specific to `utile`. A note about implementation: _no node.js native modules are modified by utile, it simply copies those methods._ + +## Methods +The `utile` modules exposes some simple utility methods: + +* `.each(obj, iterator)`: Iterate over the keys of an object. +* `.mixin(target [source0, source1, ...])`: Copies enumerable properties from `source0 ... sourceN` onto `target` and returns the resulting object. +* `.clone(obj)`: Shallow clones the specified object. +* `.capitalize(str)`: Capitalizes the specified `str`. +* `.randomString(length)`: randomString returns a pseudo-random ASCII string (subset) the return value is a string of length ⌈bits/6⌉ of characters from the base64 alphabet. +* `.filter(obj, test)`: return an object with the properties that `test` returns true on. +* `.args(arguments)`: Converts function arguments into actual array with special `callback`, `cb`, `array`, and `last` properties. Also supports *optional* argument contracts. See [the example](https://github.com/flatiron/utile/blob/master/examples/utile-args.js) for more details. +* `.requireDir(directory)`: Requires all files and directories from `directory`, returning an object with keys being filenames (without trailing `.js`) and respective values being return values of `require(filename)`. +* `.requireDirLazy(directory)`: Lazily requires all files and directories from `directory`, returning an object with keys being filenames (without trailing `.js`) and respective values (getters) being return values of `require(filename)`. +* `.format([string] text, [array] formats, [array] replacements)`: Replace `formats` in `text` with `replacements`. This will fall back to the original `util.format` command if it is called improperly. + +## Packaged Dependencies +In addition to the methods that are built-in, utile includes a number of commonly used dependencies to reduce the number of includes in your package.json. These modules _are not eagerly loaded to be respectful of startup time,_ but instead are lazy-loaded getters on the `utile` object + +* `.async`: [Async utilities for node and the browser][0] +* `.inflect`: [Customizable inflections for node.js][6] +* `.mkdirp`: [Recursively mkdir, like mkdir -p, but in node.js][1] +* `.rimraf`: [A rm -rf util for nodejs][2] +* `.cpr`: [Asynchronous recursive file copying with Node.js][3] + +## Installation + +### Installing npm (node package manager) +``` + curl http://npmjs.org/install.sh | sh +``` + +### Installing utile +``` + [sudo] npm install utile +``` + +## Tests +All tests are written with [vows][4] and should be run with [npm][5]: + +``` bash + $ npm test +``` + +#### Author: [Charlie Robbins](http://github.com/indexzero) +#### Contributors: [Dominic Tarr](http://github.com/dominictarr), [Marak Squires](https://github.com/marak) +#### License: MIT + +[0]: https://github.com/caolan/async +[1]: https://github.com/substack/node-mkdirp +[2]: https://github.com/isaacs/rimraf +[3]: https://github.com/avianflu/ncp +[4]: https://vowsjs.org +[5]: https://npmjs.org +[6]: https://github.com/pksunkara/inflect diff --git a/node_modules/utile/lib/args.js b/node_modules/utile/lib/args.js new file mode 100644 index 0000000..b4b92b8 --- /dev/null +++ b/node_modules/utile/lib/args.js @@ -0,0 +1,46 @@ +/* + * args.js: function argument parsing helper utility + * + * (C) 2011, Charlie Robbins & the Contributors + * MIT LICENSE + * + */ + +var utile = require('./index'); + +// +// ### function args(_args) +// #### _args {Arguments} Original function arguments +// +// Top-level method will accept a javascript "arguments" object (the actual keyword +// "arguments" inside any scope), and attempt to return back an intelligent object +// representing the functions arguments +// +module.exports = function (_args) { + var args = utile.rargs(_args), + _cb; + + // + // Find and define the first argument + // + Object.defineProperty(args, 'first', { value: args[0] }); + + // + // Find and define any callback + // + _cb = args[args.length - 1] || args[args.length]; + if (typeof _cb === "function") { + Object.defineProperty(args, 'callback', { value: _cb }); + Object.defineProperty(args, 'cb', { value: _cb }); + args.pop(); + } + + // + // Find and define the last argument + // + if (args.length) { + Object.defineProperty(args, 'last', { value: args[args.length - 1] }); + } + + return args; +}; diff --git a/node_modules/utile/lib/base64.js b/node_modules/utile/lib/base64.js new file mode 100644 index 0000000..c52e356 --- /dev/null +++ b/node_modules/utile/lib/base64.js @@ -0,0 +1,44 @@ +/* + * base64.js: An extremely simple implementation of base64 encoding / decoding using node.js Buffers + * + * (C) 2010, Charlie Robbins & the Contributors. + * + */ + +var base64 = exports; + +// +// ### function encode (unencoded) +// #### @unencoded {string} The string to base64 encode +// Encodes the specified string to base64 using node.js Buffers. +// +base64.encode = function (unencoded) { + var encoded; + + try { + encoded = new Buffer(unencoded || '').toString('base64'); + } + catch (ex) { + return null; + } + + return encoded; +}; + +// +// ### function decode (encoded) +// #### @encoded {string} The string to base64 decode +// Decodes the specified string from base64 using node.js Buffers. +// +base64.decode = function (encoded) { + var decoded; + + try { + decoded = new Buffer(encoded || '', 'base64').toString('utf8'); + } + catch (ex) { + return null; + } + + return decoded; +}; diff --git a/node_modules/utile/lib/file.js b/node_modules/utile/lib/file.js new file mode 100644 index 0000000..ee98758 --- /dev/null +++ b/node_modules/utile/lib/file.js @@ -0,0 +1,33 @@ +/* + * file.js: Simple utilities for working with the file system. + * + * (C) 2011, Charlie Robbins & the Contributors + * MIT LICENSE + * + */ + +var fs = require('fs'); + +exports.readJson = exports.readJSON = function (file, callback) { + if (typeof callback !== 'function') { + throw new Error('utile.file.readJson needs a callback'); + } + + fs.readFile(file, 'utf-8', function (err, data) { + if (err) { + return callback(err); + } + + try { + var json = JSON.parse(data); + callback(null, json); + } + catch (err) { + return callback(err); + } + }); +}; + +exports.readJsonSync = exports.readJSONSync = function (file) { + return JSON.parse(fs.readFileSync(file, 'utf-8')); +}; diff --git a/node_modules/utile/lib/format.js b/node_modules/utile/lib/format.js new file mode 100644 index 0000000..dfa25e8 --- /dev/null +++ b/node_modules/utile/lib/format.js @@ -0,0 +1,25 @@ +/* + * format.js: `util.format` enhancement to allow custom formatting parameters. + * + * (C) 2011, Charlie Robbins & the Contributors + * MIT LICENSE + * + */ + +var util = require('util'); + +exports = module.exports = function(str) { + var formats = [].slice.call(arguments, 1, 3); + + if (!(formats[0] instanceof Array && formats[1] instanceof Array) || arguments.length > 3) + return util.format.apply(null, arguments); + + var replacements = formats.pop(), + formats = formats.shift(); + + formats.forEach(function(format, id) { + str = str.replace(new RegExp(format), replacements[id]); + }); + + return str; +}; diff --git a/node_modules/utile/lib/index.js b/node_modules/utile/lib/index.js new file mode 100644 index 0000000..b4b7d87 --- /dev/null +++ b/node_modules/utile/lib/index.js @@ -0,0 +1,467 @@ +/* + * index.js: Top-level include for the `utile` module. + * + * (C) 2011, Charlie Robbins & the Contributors + * MIT LICENSE + * + */ + +var fs = require('fs'), + path = require('path'), + util = require('util'); + +var utile = module.exports; + +// +// Extend the `utile` object with all methods from the +// core node `util` methods. +// +Object.keys(util).forEach(function (key) { + utile[key] = util[key]; +}); + +Object.defineProperties(utile, { + + // + // ### function async + // Simple wrapper to `require('async')`. + // + 'async': { + get: function() { + return utile.async = require('async'); + } + }, + + // + // ### function inflect + // Simple wrapper to `require('i')`. + // + 'inflect': { + get: function() { + return utile.inflect = require('i')(); + } + }, + + // + // ### function mkdirp + // Simple wrapper to `require('mkdirp')` + // + 'mkdirp': { + get: function() { + return utile.mkdirp = require('mkdirp'); + } + }, + + // + // ### function deepEqual + // Simple wrapper to `require('deep-equal')` + // Remark: deepEqual is 4x faster then using assert.deepEqual + // see: https://gist.github.com/2790507 + // + 'deepEqual': { + get: function() { + return utile.deepEqual = require('deep-equal'); + } + }, + + // + // ### function rimraf + // Simple wrapper to `require('rimraf')` + // + 'rimraf': { + get: function() { + return utile.rimraf = require('rimraf'); + } + }, + + // + // ### function cpr + // Simple wrapper to `require('ncp').ncp` + // + 'cpr': { + get: function() { + return utile.cpr = require('ncp').ncp; + } + }, + + // + // ### @file {Object} + // Lazy-loaded `file` module + // + 'file': { + get: function() { + return utile.file = require('./file'); + } + }, + + // + // ### @args {Object} + // Lazy-loaded `args` module + // + 'args': { + get: function() { + return utile.args = require('./args'); + } + }, + + // + // ### @base64 {Object} + // Lazy-loaded `base64` object + // + 'base64': { + get: function() { + return utile.base64 = require('./base64'); + } + }, + + // + // ### @format {Object} + // Lazy-loaded `format` object + // + 'format': { + get: function() { + return utile.format = require('./format'); + } + } + +}); + + +// +// ### function rargs(_args) +// #### _args {Arguments} Original function arguments +// +// Top-level method will accept a javascript "arguments" object +// (the actual keyword "arguments" inside any scope) and return +// back an Array. +// +utile.rargs = function (_args, slice) { + if (!slice) { + slice = 0; + } + + var len = (_args || []).length, + args = new Array(len - slice), + i; + + // + // Convert the raw `_args` to a proper Array. + // + for (i = slice; i < len; i++) { + args[i - slice] = _args[i]; + } + + return args; +}; + +// +// ### function each (obj, iterator) +// #### @obj {Object} Object to iterate over +// #### @iterator {function} Continuation to use on each key. `function (value, key, object)` +// Iterate over the keys of an object. +// +utile.each = function (obj, iterator) { + Object.keys(obj).forEach(function (key) { + iterator(obj[key], key, obj); + }); +}; + +// +// ### function find (o) +// +// +utile.find = function (obj, pred) { + var value, key; + + for (key in obj) { + value = obj[key]; + if (pred(value, key)) { + return value; + } + } +}; + +// +// ### function pad (str, len, chr) +// ### @str {String} String to pad +// ### @len {Number} Number of chars to pad str with +// ### @chr {String} Optional replacement character, defaults to empty space +// Appends chr to str until it reaches a length of len +// +utile.pad = function pad(str, len, chr) { + var s; + if (!chr) { + chr = ' '; + } + str = str || ''; + s = str; + if (str.length < len) { + for (var i = 0; i < (len - str.length); i++) { + s += chr; + } + } + return s; +} + +// +// ### function path (obj, path, value) +// ### @obj {Object} Object to insert value into +// ### @path {Array} List of nested keys to insert value at +// Retreives a value from given Object, `obj`, located at the +// nested keys, `path`. +// +utile.path = function (obj, path) { + var key, i; + + for (i in path) { + if (typeof obj === 'undefined') { + return undefined; + } + + key = path[i]; + obj = obj[key]; + } + + return obj; +}; + +// +// ### function createPath (obj, path, value) +// ### @obj {Object} Object to insert value into +// ### @path {Array} List of nested keys to insert value at +// ### @value {*} Value to insert into the object. +// Inserts the `value` into the given Object, `obj`, creating +// any keys in `path` along the way if necessary. +// +utile.createPath = function (obj, path, value) { + var key, i; + + for (i in path) { + key = path[i]; + if (!obj[key]) { + obj[key] = ((+i + 1 === path.length) ? value : {}); + } + + obj = obj[key]; + } +}; + +// +// ### function mixin (target [source0, source1, ...]) +// Copies enumerable properties from `source0 ... sourceN` +// onto `target` and returns the resulting object. +// +utile.mixin = function (target) { + utile.rargs(arguments, 1).forEach(function (o) { + Object.getOwnPropertyNames(o).forEach(function(attr) { + var getter = Object.getOwnPropertyDescriptor(o, attr).get, + setter = Object.getOwnPropertyDescriptor(o, attr).set; + + if (!getter && !setter) { + target[attr] = o[attr]; + } + else { + Object.defineProperty(target, attr, { + get: getter, + set: setter + }); + } + }); + }); + + return target; +}; + + +// +// ### function capitalize (str) +// #### @str {string} String to capitalize +// Capitalizes the specified `str`. +// +utile.capitalize = utile.inflect.camelize; + +// +// ### function escapeRegExp (str) +// #### @str {string} String to be escaped +// Escape string for use in Javascript regex +// +utile.escapeRegExp = function (str) { + return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); +}; + +// +// ### function randomString (length) +// #### @length {integer} The number of bits for the random base64 string returned to contain +// randomString returns a pseude-random ASCII string (subset) +// the return value is a string of length ⌈bits/6⌉ of characters +// from the base64 alphabet. +// +utile.randomString = function (length) { + var chars, rand, i, ret, mod, bits; + + chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'; + ret = ''; + // standard 4 + mod = 4; + // default is 16 + bits = length * mod || 64; + + // in v8, Math.random() yields 32 pseudo-random bits (in spidermonkey it gives 53) + while (bits > 0) { + // 32-bit integer + rand = Math.floor(Math.random() * 0x100000000); + //we use the top bits + for (i = 26; i > 0 && bits > 0; i -= mod, bits -= mod) { + ret += chars[0x3F & rand >>> i]; + } + } + + return ret; +}; + +// +// ### function filter (object, test) +// #### @obj {Object} Object to iterate over +// #### @pred {function} Predicate applied to each property. `function (value, key, object)` +// Returns an object with properties from `obj` which satisfy +// the predicate `pred` +// +utile.filter = function (obj, pred) { + var copy; + if (Array.isArray(obj)) { + copy = []; + utile.each(obj, function (val, key) { + if (pred(val, key, obj)) { + copy.push(val); + } + }); + } + else { + copy = {}; + utile.each(obj, function (val, key) { + if (pred(val, key, obj)) { + copy[key] = val; + } + }); + } + return copy; +}; + +// +// ### function requireDir (directory) +// #### @directory {string} Directory to require +// Requires all files and directories from `directory`, returning an object +// with keys being filenames (without trailing `.js`) and respective values +// being return values of `require(filename)`. +// +utile.requireDir = function (directory) { + var result = {}, + files = fs.readdirSync(directory); + + files.forEach(function (file) { + if (file.substr(-3) === '.js') { + file = file.substr(0, file.length - 3); + } + result[file] = require(path.resolve(directory, file)); + }); + return result; +}; + +// +// ### function requireDirLazy (directory) +// #### @directory {string} Directory to require +// Lazily requires all files and directories from `directory`, returning an +// object with keys being filenames (without trailing `.js`) and respective +// values (getters) being return values of `require(filename)`. +// +utile.requireDirLazy = function (directory) { + var result = {}, + files = fs.readdirSync(directory); + + files.forEach(function (file) { + if (file.substr(-3) === '.js') { + file = file.substr(0, file.length - 3); + } + Object.defineProperty(result, file, { + get: function() { + return result[file] = require(path.resolve(directory, file)); + } + }); + }); + + return result; +}; + +// +// ### function clone (object, filter) +// #### @object {Object} Object to clone +// #### @filter {Function} Filter to be used +// Shallow clones the specified object. +// +utile.clone = function (object, filter) { + return Object.keys(object).reduce(filter ? function (obj, k) { + if (filter(k)) obj[k] = object[k]; + return obj; + } : function (obj, k) { + obj[k] = object[k]; + return obj; + }, {}); +}; + +// +// ### function camelToUnderscore (obj) +// #### @obj {Object} Object to convert keys on. +// Converts all keys of the type `keyName` to `key_name` on the +// specified `obj`. +// +utile.camelToUnderscore = function (obj) { + if (typeof obj !== 'object' || obj === null) { + return obj; + } + + if (Array.isArray(obj)) { + obj.forEach(utile.camelToUnderscore); + return obj; + } + + Object.keys(obj).forEach(function (key) { + var k = utile.inflect.underscore(key); + if (k !== key) { + obj[k] = obj[key]; + delete obj[key]; + key = k; + } + utile.camelToUnderscore(obj[key]); + }); + + return obj; +}; + +// +// ### function underscoreToCamel (obj) +// #### @obj {Object} Object to convert keys on. +// Converts all keys of the type `key_name` to `keyName` on the +// specified `obj`. +// +utile.underscoreToCamel = function (obj) { + if (typeof obj !== 'object' || obj === null) { + return obj; + } + + if (Array.isArray(obj)) { + obj.forEach(utile.underscoreToCamel); + return obj; + } + + Object.keys(obj).forEach(function (key) { + var k = utile.inflect.camelize(key, false); + if (k !== key) { + obj[k] = obj[key]; + delete obj[key]; + key = k; + } + utile.underscoreToCamel(obj[key]); + }); + + return obj; +}; diff --git a/node_modules/utile/package.json b/node_modules/utile/package.json new file mode 100644 index 0000000..ba6b15d --- /dev/null +++ b/node_modules/utile/package.json @@ -0,0 +1,66 @@ +{ + "_from": "utile@0.3.x", + "_id": "utile@0.3.0", + "_inBundle": false, + "_integrity": "sha1-E1LDQOuCDk2N26A5pPv6oy7U7zo=", + "_location": "/utile", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "utile@0.3.x", + "name": "utile", + "escapedName": "utile", + "rawSpec": "0.3.x", + "saveSpec": null, + "fetchSpec": "0.3.x" + }, + "_requiredBy": [ + "/prompt" + ], + "_resolved": "https://registry.npmjs.org/utile/-/utile-0.3.0.tgz", + "_shasum": "1352c340eb820e4d8ddba039a4fbfaa32ed4ef3a", + "_spec": "utile@0.3.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/prompt", + "author": { + "name": "Nodejitsu Inc.", + "email": "info@nodejitsu.com" + }, + "bugs": { + "url": "https://github.com/flatiron/utile/issues" + }, + "bundleDependencies": false, + "dependencies": { + "async": "~0.9.0", + "deep-equal": "~0.2.1", + "i": "0.3.x", + "mkdirp": "0.x.x", + "ncp": "1.0.x", + "rimraf": "2.x.x" + }, + "deprecated": false, + "description": "A drop-in replacement for `util` with some additional advantageous functions", + "devDependencies": { + "vows": "0.8.x" + }, + "engines": { + "node": ">= 0.8.0" + }, + "homepage": "https://github.com/flatiron/utile#readme", + "main": "./lib/index", + "maintainers": [ + { + "name": "indexzero", + "email": "charlie@nodejitsu.com" + } + ], + "name": "utile", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/flatiron/utile.git" + }, + "scripts": { + "test": "vows --spec" + }, + "version": "0.3.0" +} diff --git a/node_modules/utile/test/file-test.js b/node_modules/utile/test/file-test.js new file mode 100644 index 0000000..99b2217 --- /dev/null +++ b/node_modules/utile/test/file-test.js @@ -0,0 +1,31 @@ +/* + * file-test.js: Tests for `utile.file` module. + * + * (C) 2011, Charlie Robbins & the Contributors + * MIT LICENSE + * + */ + +var assert = require('assert'), + path = require('path'), + vows = require('vows'), + macros = require('./helpers/macros'), + utile = require('../'); + +var fixture = path.join(__dirname, 'fixtures', 'read-json-file', 'config.json'); + +vows.describe('utile/file').addBatch({ + 'When using utile': { + 'the `.file.readJson()` function': { + topic: function () { + utile.file.readJson(fixture, this.callback); + }, + 'should return correct JSON structure': macros.assertReadCorrectJson + }, + 'the `.file.readJsonSync()` function': { + topic: utile.file.readJsonSync(fixture), + 'should return correct JSON structure': macros.assertReadCorrectJson + } + } +}).export(module); + diff --git a/node_modules/utile/test/fixtures/read-json-file/config.json b/node_modules/utile/test/fixtures/read-json-file/config.json new file mode 100644 index 0000000..e12a106 --- /dev/null +++ b/node_modules/utile/test/fixtures/read-json-file/config.json @@ -0,0 +1,9 @@ +{ + "hello": "World", + "I am": ["the utile module"], + "thisMakesMe": { + "really": 1337, + "right?": true + } +} + diff --git a/node_modules/utile/test/fixtures/require-directory/directory/index.js b/node_modules/utile/test/fixtures/require-directory/directory/index.js new file mode 100644 index 0000000..1afb489 --- /dev/null +++ b/node_modules/utile/test/fixtures/require-directory/directory/index.js @@ -0,0 +1,2 @@ +exports.me = 'directory/index.js'; + diff --git a/node_modules/utile/test/fixtures/require-directory/helloWorld.js b/node_modules/utile/test/fixtures/require-directory/helloWorld.js new file mode 100644 index 0000000..1c842ec --- /dev/null +++ b/node_modules/utile/test/fixtures/require-directory/helloWorld.js @@ -0,0 +1,2 @@ +exports.me = 'helloWorld.js'; + diff --git a/node_modules/utile/test/format-test.js b/node_modules/utile/test/format-test.js new file mode 100644 index 0000000..0648f5a --- /dev/null +++ b/node_modules/utile/test/format-test.js @@ -0,0 +1,31 @@ +/* + * format-test.js: Tests for `utile.format` module. + * + * (C) 2011, Charlie Robbins & the Contributors + * MIT LICENSE + * + */ + +var vows = require('vows'), + assert = require('assert'), + utile = require('../lib'); + +vows.describe('utile/format').addBatch({ + + 'Should use the original `util.format` if there are no custom parameters to replace.': function() { + assert.equal(utile.format('%s %s %s', 'test', 'test2', 'test3'), 'test test2 test3'); + }, + + 'Should use `utile.format` if custom parameters are provided.': function() { + assert.equal(utile.format('%a %b %c', [ + '%a', + '%b', + '%c' + ], [ + 'test', + 'test2', + 'test3' + ]), 'test test2 test3'); + } + +}).export(module); diff --git a/node_modules/utile/test/function-args-test.js b/node_modules/utile/test/function-args-test.js new file mode 100644 index 0000000..e78c4b2 --- /dev/null +++ b/node_modules/utile/test/function-args-test.js @@ -0,0 +1,104 @@ +/* + * function-args-test.js: Tests for `args` method + * + * (C) 2011, Charlie Robbins & the Contributors + * MIT LICENSE + * + */ + +var assert = require('assert'), + path = require('path'), + vows = require('vows'), + macros = require('./helpers/macros'), + utile = require('../'); + +vows.describe('utile/args').addBatch({ + 'When using utile': { + 'the `args` function': { + topic: utile, + 'should be a function': function (_utile) { + assert.isFunction(_utile.args); + }, + } + }, + 'utile.rargs()': { + 'with no arguments': { + topic: utile.rargs(), + 'should return an empty object': function (result) { + assert.isArray(result); + assert.lengthOf(result, 0); + } + }, + 'with simple arguments': { + topic: function () { + return (function () { + return utile.rargs(arguments); + })('a', 'b', 'c'); + }, + 'should return an array with three items': function (result) { + assert.isArray(result); + assert.equal(3, result.length); + assert.equal(result[0], 'a'); + assert.equal(result[1], 'b'); + assert.equal(result[2], 'c'); + } + }, + 'with a simple slice': { + topic: function () { + return (function () { + return utile.rargs(arguments, 1); + })('a', 'b', 'c'); + }, + 'should return an array with three items': function (result) { + assert.isArray(result); + assert.equal(2, result.length); + assert.equal(result[0], 'b'); + assert.equal(result[1], 'c'); + } + } + }, + 'utile.args()': { + 'with no arguments': { + topic: utile.args(), + 'should return an empty Array': function (result) { + assert.isUndefined(result.callback); + assert.isArray(result); + assert.lengthOf(result, 0); + } + }, + 'with simple arguments': { + topic: function () { + return (function () { + return utile.args(arguments); + })('a', 'b', 'c', function () { + return 'ok'; + }); + }, + 'should return an array with three items': function (result) { + assert.isArray(result); + assert.equal(3, result.length); + assert.equal(result[0], 'a'); + assert.equal(result[1], 'b'); + assert.equal(result[2], 'c'); + + // + // Ensure that the Array returned + // by `utile.args()` enumerates correctly + // + var length = 0; + result.forEach(function (item) { + length++; + }); + + assert.equal(length, 3); + }, + 'should return lookup helpers': function (result) { + assert.isArray(result); + assert.equal(result.first, 'a'); + assert.equal(result.last, 'c'); + assert.isFunction(result.callback); + assert.isFunction(result.cb); + } + } + } +}).export(module); diff --git a/node_modules/utile/test/helpers/macros.js b/node_modules/utile/test/helpers/macros.js new file mode 100644 index 0000000..f86fcc6 --- /dev/null +++ b/node_modules/utile/test/helpers/macros.js @@ -0,0 +1,37 @@ +/* + * macros.js: Test macros for `utile` module. + * + * (C) 2011, Charlie Robbins & the Contributors + * MIT LICENSE + * + */ + +var assert = require('assert'), + utile = require('../../lib'); + +var macros = exports; + +macros.assertReadCorrectJson = function (obj) { + assert.isObject(obj); + utile.deepEqual(obj, { + hello: 'World', + 'I am': ['the utile module'], + thisMakesMe: { + really: 1337, + 'right?': true + } + }); +}; + +macros.assertDirectoryRequired = function (obj) { + assert.isObject(obj); + utile.deepEqual(obj, { + directory: { + me: 'directory/index.js' + }, + helloWorld: { + me: 'helloWorld.js' + } + }); +}; + diff --git a/node_modules/utile/test/random-string-test.js b/node_modules/utile/test/random-string-test.js new file mode 100644 index 0000000..84e9c8b --- /dev/null +++ b/node_modules/utile/test/random-string-test.js @@ -0,0 +1,39 @@ +/* + * common-test.js : testing common.js for expected functionality + * + * (C) 2011, Charlie Robbins & the Contributors + * + */ + +var assert = require('assert'), + vows = require('vows'), + utile = require('../lib'); + +vows.describe('utile/randomString').addBatch({ + "When using utile": { + "the randomString() function": { + topic: function () { + return utile.randomString(); + }, + "should return 16 characters that are actually random by default": function (random) { + assert.isString(random); + assert.lengthOf(random, 16); + assert.notEqual(random, utile.randomString()); + }, + "when you can asked for different length strings": { + topic: function () { + return [utile.randomString(4), utile.randomString(128)]; + }, + "where they actually are of length 4, 128": function (strings) { + assert.isArray(strings); + assert.lengthOf(strings,2); + assert.isString(strings[0]); + assert.isString(strings[1]); + assert.lengthOf(strings[0], 4); + assert.lengthOf(strings[1], 128); + assert.notEqual(strings[0], strings[1].substr(0,4)); + } + } + } + } +}).export(module); diff --git a/node_modules/utile/test/require-directory-test.js b/node_modules/utile/test/require-directory-test.js new file mode 100644 index 0000000..4664db8 --- /dev/null +++ b/node_modules/utile/test/require-directory-test.js @@ -0,0 +1,35 @@ +/* + * require-directory-test.js: Tests for `requireDir` and `requireDirLazy` + * methods. + * + * (C) 2011, Charlie Robbins & the Contributors + * MIT LICENSE + * + */ + +var assert = require('assert'), + path = require('path'), + vows = require('vows'), + macros = require('./helpers/macros'), + utile = require('../'); + +var requireFixtures = path.join(__dirname, 'fixtures', 'require-directory'); + +vows.describe('utile/require-directory').addBatch({ + 'When using utile': { + 'the `requireDir()` function': { + topic: utile.requireDir(requireFixtures), + 'should contain all wanted modules': macros.assertDirectoryRequired + }, + 'the `requireDirLazy()` function': { + topic: utile.requireDirLazy(requireFixtures), + 'all properties should be getters': function (obj) { + assert.isObject(obj); + assert.isTrue(!!Object.getOwnPropertyDescriptor(obj, 'directory').get); + assert.isTrue(!!Object.getOwnPropertyDescriptor(obj, 'helloWorld').get); + }, + 'should contain all wanted modules': macros.assertDirectoryRequired + } + } +}).export(module); + diff --git a/node_modules/utile/test/utile-test.js b/node_modules/utile/test/utile-test.js new file mode 100644 index 0000000..0cecc34 --- /dev/null +++ b/node_modules/utile/test/utile-test.js @@ -0,0 +1,126 @@ +/* + * utile-test.js: Tests for `utile` module. + * + * (C) 2011, Charlie Robbins & the Contributors + * MIT LICENSE + * + */ + +var assert = require('assert'), + vows = require('vows'), + utile = require('../lib'); + +var obj1, obj2; + +obj1 = { + foo: true, + bar: { + bar1: true, + bar2: 'bar2' + } +}; + +obj2 = { + baz: true, + buzz: 'buzz' +}; + +Object.defineProperties(obj2, { + + 'bazz': { + get: function() { + return 'bazz'; + }, + + set: function() { + return 'bazz'; + } + }, + + 'wat': { + set: function() { + return 'wat'; + } + } + +}); + +vows.describe('utile').addBatch({ + "When using utile": { + "it should have the same methods as the `util` module": function () { + Object.keys(require('util')).forEach(function (fn) { + assert.isFunction(utile[fn]); + }); + }, + "it should have the correct methods defined": function () { + assert.isFunction(utile.mixin); + assert.isFunction(utile.clone); + assert.isFunction(utile.rimraf); + assert.isFunction(utile.mkdirp); + assert.isFunction(utile.cpr); + }, + "the mixin() method": function () { + var mixed = utile.mixin({}, obj1, obj2); + assert.isTrue(mixed.foo); + assert.isObject(mixed.bar); + assert.isTrue(mixed.baz); + assert.isString(mixed.buzz); + assert.isTrue(!!Object.getOwnPropertyDescriptor(mixed, 'bazz').get); + assert.isTrue(!!Object.getOwnPropertyDescriptor(mixed, 'bazz').set); + assert.isTrue(!!Object.getOwnPropertyDescriptor(mixed, 'wat').set); + assert.isString(mixed.bazz); + }, + "the clone() method": function () { + var clone = utile.clone(obj1); + assert.isTrue(clone.foo); + assert.isObject(clone.bar); + assert.notStrictEqual(obj1, clone); + }, + "the createPath() method": function () { + var x = {}, + r = Math.random(); + + utile.createPath(x, ['a','b','c'], r) + assert.equal(x.a.b.c, r) + }, + "the capitalize() method": function () { + assert.isFunction(utile.capitalize); + assert.equal(utile.capitalize('bullet'), 'Bullet'); + assert.equal(utile.capitalize('bullet_train'), 'BulletTrain'); + }, + "the escapeRegExp() method": function () { + var ans = "\\/path\\/to\\/resource\\.html\\?search=query"; + assert.isFunction(utile.escapeRegExp); + assert.equal(utile.escapeRegExp('/path/to/resource.html?search=query'), ans); + }, + "the underscoreToCamel() method": function () { + var obj = utile.underscoreToCamel({ + key_with_underscore: { + andNested: 'values', + several: [1, 2, 3], + nested_underscores: true + }, + just_one: 'underscore' + }); + + assert.isObject(obj.keyWithUnderscore); + assert.isString(obj.justOne); + assert.isTrue(obj.keyWithUnderscore.nestedUnderscores); + }, + "the camelToUnderscore() method": function () { + var obj = utile.camelToUnderscore({ + keyWithCamel: { + andNested: 'values', + several: [1, 2, 3], + nestedCamel: true + }, + justOne: 'camel' + }); + + assert.isObject(obj.key_with_camel); + assert.isString(obj.just_one); + assert.isTrue(obj.key_with_camel.nested_camel); + } + } +}).export(module); + diff --git a/node_modules/wcwidth/.npmignore b/node_modules/wcwidth/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/wcwidth/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/wcwidth/LICENSE b/node_modules/wcwidth/LICENSE new file mode 100644 index 0000000..313ef1e --- /dev/null +++ b/node_modules/wcwidth/LICENSE @@ -0,0 +1,30 @@ +wcwidth.js: JavaScript Portng of Markus Kuhn's wcwidth() Implementation +======================================================================= + +Copyright (C) 2012 by Jun Woong. + +This package is a JavaScript porting of `wcwidth()` implementation +[by Markus Kuhn](http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c). + +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. + + +THIS SOFTWARE IS PROVIDED ``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 AUTHOR +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 SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + diff --git a/node_modules/wcwidth/Readme.md b/node_modules/wcwidth/Readme.md new file mode 100644 index 0000000..0649a31 --- /dev/null +++ b/node_modules/wcwidth/Readme.md @@ -0,0 +1,33 @@ +# wcwidth + +Determine columns needed for a fixed-size wide-character string + +---- + +wcwidth is a simple JavaScript port of [wcwidth](http://man7.org/linux/man-pages/man3/wcswidth.3.html) implemented in C by Markus Kuhn. + +JavaScript port [originally](https://github.com/mycoboco/wcwidth.js) written by Woong Jun <woong.jun@gmail.com> (http://code.woong.org/) + +## Example + +```js +'한'.length // => 1 +wcwidth('한'); // => 2 + +'한글'.length // => 2 +wcwidth('한글'); // => 4 +``` + +`wcwidth()` and its string version, `wcswidth()` are defined by IEEE Std +1002.1-2001, a.k.a. POSIX.1-2001, and return the number of columns used +to represent the given wide character and string. + +Markus's implementation assumes the wide character given to those +functions to be encoded in ISO 10646, which is almost true for +JavaScript's characters. + +[Further explaination here](docs) + +## License + +MIT diff --git a/node_modules/wcwidth/combining.js b/node_modules/wcwidth/combining.js new file mode 100644 index 0000000..dac9789 --- /dev/null +++ b/node_modules/wcwidth/combining.js @@ -0,0 +1,50 @@ +module.exports = [ + [ 0x0300, 0x036F ], [ 0x0483, 0x0486 ], [ 0x0488, 0x0489 ], + [ 0x0591, 0x05BD ], [ 0x05BF, 0x05BF ], [ 0x05C1, 0x05C2 ], + [ 0x05C4, 0x05C5 ], [ 0x05C7, 0x05C7 ], [ 0x0600, 0x0603 ], + [ 0x0610, 0x0615 ], [ 0x064B, 0x065E ], [ 0x0670, 0x0670 ], + [ 0x06D6, 0x06E4 ], [ 0x06E7, 0x06E8 ], [ 0x06EA, 0x06ED ], + [ 0x070F, 0x070F ], [ 0x0711, 0x0711 ], [ 0x0730, 0x074A ], + [ 0x07A6, 0x07B0 ], [ 0x07EB, 0x07F3 ], [ 0x0901, 0x0902 ], + [ 0x093C, 0x093C ], [ 0x0941, 0x0948 ], [ 0x094D, 0x094D ], + [ 0x0951, 0x0954 ], [ 0x0962, 0x0963 ], [ 0x0981, 0x0981 ], + [ 0x09BC, 0x09BC ], [ 0x09C1, 0x09C4 ], [ 0x09CD, 0x09CD ], + [ 0x09E2, 0x09E3 ], [ 0x0A01, 0x0A02 ], [ 0x0A3C, 0x0A3C ], + [ 0x0A41, 0x0A42 ], [ 0x0A47, 0x0A48 ], [ 0x0A4B, 0x0A4D ], + [ 0x0A70, 0x0A71 ], [ 0x0A81, 0x0A82 ], [ 0x0ABC, 0x0ABC ], + [ 0x0AC1, 0x0AC5 ], [ 0x0AC7, 0x0AC8 ], [ 0x0ACD, 0x0ACD ], + [ 0x0AE2, 0x0AE3 ], [ 0x0B01, 0x0B01 ], [ 0x0B3C, 0x0B3C ], + [ 0x0B3F, 0x0B3F ], [ 0x0B41, 0x0B43 ], [ 0x0B4D, 0x0B4D ], + [ 0x0B56, 0x0B56 ], [ 0x0B82, 0x0B82 ], [ 0x0BC0, 0x0BC0 ], + [ 0x0BCD, 0x0BCD ], [ 0x0C3E, 0x0C40 ], [ 0x0C46, 0x0C48 ], + [ 0x0C4A, 0x0C4D ], [ 0x0C55, 0x0C56 ], [ 0x0CBC, 0x0CBC ], + [ 0x0CBF, 0x0CBF ], [ 0x0CC6, 0x0CC6 ], [ 0x0CCC, 0x0CCD ], + [ 0x0CE2, 0x0CE3 ], [ 0x0D41, 0x0D43 ], [ 0x0D4D, 0x0D4D ], + [ 0x0DCA, 0x0DCA ], [ 0x0DD2, 0x0DD4 ], [ 0x0DD6, 0x0DD6 ], + [ 0x0E31, 0x0E31 ], [ 0x0E34, 0x0E3A ], [ 0x0E47, 0x0E4E ], + [ 0x0EB1, 0x0EB1 ], [ 0x0EB4, 0x0EB9 ], [ 0x0EBB, 0x0EBC ], + [ 0x0EC8, 0x0ECD ], [ 0x0F18, 0x0F19 ], [ 0x0F35, 0x0F35 ], + [ 0x0F37, 0x0F37 ], [ 0x0F39, 0x0F39 ], [ 0x0F71, 0x0F7E ], + [ 0x0F80, 0x0F84 ], [ 0x0F86, 0x0F87 ], [ 0x0F90, 0x0F97 ], + [ 0x0F99, 0x0FBC ], [ 0x0FC6, 0x0FC6 ], [ 0x102D, 0x1030 ], + [ 0x1032, 0x1032 ], [ 0x1036, 0x1037 ], [ 0x1039, 0x1039 ], + [ 0x1058, 0x1059 ], [ 0x1160, 0x11FF ], [ 0x135F, 0x135F ], + [ 0x1712, 0x1714 ], [ 0x1732, 0x1734 ], [ 0x1752, 0x1753 ], + [ 0x1772, 0x1773 ], [ 0x17B4, 0x17B5 ], [ 0x17B7, 0x17BD ], + [ 0x17C6, 0x17C6 ], [ 0x17C9, 0x17D3 ], [ 0x17DD, 0x17DD ], + [ 0x180B, 0x180D ], [ 0x18A9, 0x18A9 ], [ 0x1920, 0x1922 ], + [ 0x1927, 0x1928 ], [ 0x1932, 0x1932 ], [ 0x1939, 0x193B ], + [ 0x1A17, 0x1A18 ], [ 0x1B00, 0x1B03 ], [ 0x1B34, 0x1B34 ], + [ 0x1B36, 0x1B3A ], [ 0x1B3C, 0x1B3C ], [ 0x1B42, 0x1B42 ], + [ 0x1B6B, 0x1B73 ], [ 0x1DC0, 0x1DCA ], [ 0x1DFE, 0x1DFF ], + [ 0x200B, 0x200F ], [ 0x202A, 0x202E ], [ 0x2060, 0x2063 ], + [ 0x206A, 0x206F ], [ 0x20D0, 0x20EF ], [ 0x302A, 0x302F ], + [ 0x3099, 0x309A ], [ 0xA806, 0xA806 ], [ 0xA80B, 0xA80B ], + [ 0xA825, 0xA826 ], [ 0xFB1E, 0xFB1E ], [ 0xFE00, 0xFE0F ], + [ 0xFE20, 0xFE23 ], [ 0xFEFF, 0xFEFF ], [ 0xFFF9, 0xFFFB ], + [ 0x10A01, 0x10A03 ], [ 0x10A05, 0x10A06 ], [ 0x10A0C, 0x10A0F ], + [ 0x10A38, 0x10A3A ], [ 0x10A3F, 0x10A3F ], [ 0x1D167, 0x1D169 ], + [ 0x1D173, 0x1D182 ], [ 0x1D185, 0x1D18B ], [ 0x1D1AA, 0x1D1AD ], + [ 0x1D242, 0x1D244 ], [ 0xE0001, 0xE0001 ], [ 0xE0020, 0xE007F ], + [ 0xE0100, 0xE01EF ] +] diff --git a/node_modules/wcwidth/docs/index.md b/node_modules/wcwidth/docs/index.md new file mode 100644 index 0000000..5c5126d --- /dev/null +++ b/node_modules/wcwidth/docs/index.md @@ -0,0 +1,65 @@ +### Javascript porting of Markus Kuhn's wcwidth() implementation + +The following explanation comes from the original C implementation: + +This is an implementation of wcwidth() and wcswidth() (defined in +IEEE Std 1002.1-2001) for Unicode. + +http://www.opengroup.org/onlinepubs/007904975/functions/wcwidth.html +http://www.opengroup.org/onlinepubs/007904975/functions/wcswidth.html + +In fixed-width output devices, Latin characters all occupy a single +"cell" position of equal width, whereas ideographic CJK characters +occupy two such cells. Interoperability between terminal-line +applications and (teletype-style) character terminals using the +UTF-8 encoding requires agreement on which character should advance +the cursor by how many cell positions. No established formal +standards exist at present on which Unicode character shall occupy +how many cell positions on character terminals. These routines are +a first attempt of defining such behavior based on simple rules +applied to data provided by the Unicode Consortium. + +For some graphical characters, the Unicode standard explicitly +defines a character-cell width via the definition of the East Asian +FullWidth (F), Wide (W), Half-width (H), and Narrow (Na) classes. +In all these cases, there is no ambiguity about which width a +terminal shall use. For characters in the East Asian Ambiguous (A) +class, the width choice depends purely on a preference of backward +compatibility with either historic CJK or Western practice. +Choosing single-width for these characters is easy to justify as +the appropriate long-term solution, as the CJK practice of +displaying these characters as double-width comes from historic +implementation simplicity (8-bit encoded characters were displayed +single-width and 16-bit ones double-width, even for Greek, +Cyrillic, etc.) and not any typographic considerations. + +Much less clear is the choice of width for the Not East Asian +(Neutral) class. Existing practice does not dictate a width for any +of these characters. It would nevertheless make sense +typographically to allocate two character cells to characters such +as for instance EM SPACE or VOLUME INTEGRAL, which cannot be +represented adequately with a single-width glyph. The following +routines at present merely assign a single-cell width to all +neutral characters, in the interest of simplicity. This is not +entirely satisfactory and should be reconsidered before +establishing a formal standard in this area. At the moment, the +decision which Not East Asian (Neutral) characters should be +represented by double-width glyphs cannot yet be answered by +applying a simple rule from the Unicode database content. Setting +up a proper standard for the behavior of UTF-8 character terminals +will require a careful analysis not only of each Unicode character, +but also of each presentation form, something the author of these +routines has avoided to do so far. + +http://www.unicode.org/unicode/reports/tr11/ + +Markus Kuhn -- 2007-05-26 (Unicode 5.0) + +Permission to use, copy, modify, and distribute this software +for any purpose and without fee is hereby granted. The author +disclaims all warranties with regard to this software. + +Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c + + + diff --git a/node_modules/wcwidth/index.js b/node_modules/wcwidth/index.js new file mode 100644 index 0000000..48cbb60 --- /dev/null +++ b/node_modules/wcwidth/index.js @@ -0,0 +1,99 @@ +"use strict" + +var defaults = require('defaults') +var combining = require('./combining') + +var DEFAULTS = { + nul: 0, + control: 0 +} + +module.exports = function wcwidth(str) { + return wcswidth(str, DEFAULTS) +} + +module.exports.config = function(opts) { + opts = defaults(opts || {}, DEFAULTS) + return function wcwidth(str) { + return wcswidth(str, opts) + } +} + +/* + * The following functions define the column width of an ISO 10646 + * character as follows: + * - The null character (U+0000) has a column width of 0. + * - Other C0/C1 control characters and DEL will lead to a return value + * of -1. + * - Non-spacing and enclosing combining characters (general category + * code Mn or Me in the + * Unicode database) have a column width of 0. + * - SOFT HYPHEN (U+00AD) has a column width of 1. + * - Other format characters (general category code Cf in the Unicode + * database) and ZERO WIDTH + * SPACE (U+200B) have a column width of 0. + * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF) + * have a column width of 0. + * - Spacing characters in the East Asian Wide (W) or East Asian + * Full-width (F) category as + * defined in Unicode Technical Report #11 have a column width of 2. + * - All remaining characters (including all printable ISO 8859-1 and + * WGL4 characters, Unicode control characters, etc.) have a column + * width of 1. + * This implementation assumes that characters are encoded in ISO 10646. +*/ + +function wcswidth(str, opts) { + if (typeof str !== 'string') return wcwidth(str, opts) + + var s = 0 + for (var i = 0; i < str.length; i++) { + var n = wcwidth(str.charCodeAt(i), opts) + if (n < 0) return -1 + s += n + } + + return s +} + +function wcwidth(ucs, opts) { + // test for 8-bit control characters + if (ucs === 0) return opts.nul + if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) return opts.control + + // binary search in table of non-spacing characters + if (bisearch(ucs)) return 0 + + // if we arrive here, ucs is not a combining or C0/C1 control character + return 1 + + (ucs >= 0x1100 && + (ucs <= 0x115f || // Hangul Jamo init. consonants + ucs == 0x2329 || ucs == 0x232a || + (ucs >= 0x2e80 && ucs <= 0xa4cf && + ucs != 0x303f) || // CJK ... Yi + (ucs >= 0xac00 && ucs <= 0xd7a3) || // Hangul Syllables + (ucs >= 0xf900 && ucs <= 0xfaff) || // CJK Compatibility Ideographs + (ucs >= 0xfe10 && ucs <= 0xfe19) || // Vertical forms + (ucs >= 0xfe30 && ucs <= 0xfe6f) || // CJK Compatibility Forms + (ucs >= 0xff00 && ucs <= 0xff60) || // Fullwidth Forms + (ucs >= 0xffe0 && ucs <= 0xffe6) || + (ucs >= 0x20000 && ucs <= 0x2fffd) || + (ucs >= 0x30000 && ucs <= 0x3fffd))); +} + +function bisearch(ucs) { + var min = 0 + var max = combining.length - 1 + var mid + + if (ucs < combining[0][0] || ucs > combining[max][1]) return false + + while (max >= min) { + mid = Math.floor((min + max) / 2) + if (ucs > combining[mid][1]) min = mid + 1 + else if (ucs < combining[mid][0]) max = mid - 1 + else return true + } + + return false +} diff --git a/node_modules/wcwidth/package.json b/node_modules/wcwidth/package.json new file mode 100644 index 0000000..63323d1 --- /dev/null +++ b/node_modules/wcwidth/package.json @@ -0,0 +1,73 @@ +{ + "_from": "wcwidth@^1.0.1", + "_id": "wcwidth@1.0.1", + "_inBundle": false, + "_integrity": "sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g=", + "_location": "/wcwidth", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "wcwidth@^1.0.1", + "name": "wcwidth", + "escapedName": "wcwidth", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/ora" + ], + "_resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "_shasum": "f0b0dcf915bc5ff1528afadb2c0e17b532da2fe8", + "_spec": "wcwidth@^1.0.1", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/ora", + "author": { + "name": "Tim Oxley" + }, + "bugs": { + "url": "https://github.com/timoxley/wcwidth/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Woong Jun", + "email": "woong.jun@gmail.com", + "url": "http://code.woong.org/" + } + ], + "dependencies": { + "defaults": "^1.0.3" + }, + "deprecated": false, + "description": "Port of C's wcwidth() and wcswidth()", + "devDependencies": { + "tape": "^4.5.1" + }, + "directories": { + "doc": "docs", + "test": "test" + }, + "homepage": "https://github.com/timoxley/wcwidth#readme", + "keywords": [ + "wide character", + "wc", + "wide character string", + "wcs", + "terminal", + "width", + "wcwidth", + "wcswidth" + ], + "license": "MIT", + "main": "index.js", + "name": "wcwidth", + "repository": { + "type": "git", + "url": "git+https://github.com/timoxley/wcwidth.git" + }, + "scripts": { + "test": "tape test/*.js" + }, + "version": "1.0.1" +} diff --git a/node_modules/wcwidth/test/index.js b/node_modules/wcwidth/test/index.js new file mode 100644 index 0000000..5180599 --- /dev/null +++ b/node_modules/wcwidth/test/index.js @@ -0,0 +1,64 @@ +"use strict" + +var wcwidth = require('../') +var test = require('tape') + +test('handles regular strings', function(t) { + t.strictEqual(wcwidth('abc'), 3) + t.end() +}) + +test('handles multibyte strings', function(t) { + t.strictEqual(wcwidth('字的模块'), 8) + t.end() +}) + +test('handles multibyte characters mixed with regular characters', function(t) { + t.strictEqual(wcwidth('abc 字的模块'), 12) + t.end() +}) + +test('ignores control characters e.g. \\n', function(t) { + t.strictEqual(wcwidth('abc\n字的模块\ndef'), 14) + t.end() +}) + +test('ignores bad input', function(t) { + t.strictEqual(wcwidth(''), 0) + t.strictEqual(wcwidth(3), 0) + t.strictEqual(wcwidth({}), 0) + t.strictEqual(wcwidth([]), 0) + t.strictEqual(wcwidth(), 0) + t.end() +}) + +test('ignores nul (charcode 0)', function(t) { + t.strictEqual(wcwidth(String.fromCharCode(0)), 0) + t.end() +}) + +test('ignores nul mixed with chars', function(t) { + t.strictEqual(wcwidth('a' + String.fromCharCode(0) + '\n字的'), 5) + t.end() +}) + +test('can have custom value for nul', function(t) { + t.strictEqual(wcwidth.config({ + nul: 10 + })(String.fromCharCode(0) + 'a字的'), 15) + t.end() +}) + +test('can have custom control char value', function(t) { + t.strictEqual(wcwidth.config({ + control: 1 + })('abc\n字的模块\ndef'), 16) + t.end() +}) + +test('negative custom control chars == -1', function(t) { + t.strictEqual(wcwidth.config({ + control: -1 + })('abc\n字的模块\ndef'), -1) + t.end() +}) diff --git a/node_modules/winston/CHANGELOG.md b/node_modules/winston/CHANGELOG.md new file mode 100644 index 0000000..2aac1a1 --- /dev/null +++ b/node_modules/winston/CHANGELOG.md @@ -0,0 +1,188 @@ +## v2.1.1 / 2015-11-18 +### COLOR ME IMPRESSED EDITION + +- [#751](https://github.com/winstonjs/winston/pull/751), Fix colors not appearing in non-tty environments. Fixes [#609](https://github.com/winstonjs/winston/issues/609), [#616](https://github.com/winstonjs/winston/issues/616), [#669](https://github.com/winstonjs/winston/issues/669), [#648](https://github.com/winstonjs/winston/issues/648) (`fiznool`). +- [#752](https://github.com/winstonjs/winston/pull/752) Correct syslog RFC number. 5424 instead of 524. (`jbenoit2011`) + +## v2.1.0 / 2015-11-03 +### TEST ALL THE ECOSYSTEM EDITION + +- [#742](https://github.com/winstonjs/winston/pull/742), [32d52b7](https://github.com/winstonjs/winston/commit/32d52b7) Distribute common test files used by transports in the `winston` ecosystem. + +## v2.0.1 / 2015-11-02 +### BUGS ALWAYS HAPPEN OK EDITION + +- [#739](https://github.com/winstonjs/winston/issues/739), [1f16861](https://github.com/winstonjs/winston/commit/1f16861) Ensure that `logger.log("info", undefined)` does not throw. + +## v2.0.0 / 2015-10-29 +### OMG IT'S MY SISTER'S BIRTHDAY EDITION + +#### Breaking changes + +**Most important** +- **[0f82204](https://github.com/winstonjs/winston/commit/0f82204) Move `winston.transports.DailyRotateFile` [into a separate module](https://github.com/winstonjs/winston-daily-rotate-file)**: `require('winston-daily-rotate-file');` +- **[fb9eec0](https://github.com/winstonjs/winston/commit/fb9eec0) Reverse log levels in `npm` and `cli` configs to conform to [RFC524](https://tools.ietf.org/html/rfc5424). Fixes [#424](https://github.com/winstonjs/winston/pull/424) [#406](https://github.com/winstonjs/winston/pull/406) [#290](https://github.com/winstonjs/winston/pull/290)** +- **[8cd8368](https://github.com/winstonjs/winston/commit/8cd8368) Change the method signature to a `filter` function to be consistent with `rewriter` and log functions:** +``` js +function filter (level, msg, meta, inst) { + // Filter logic goes here... +} +``` + +**Other breaking changes** +- [e0c9dde](https://github.com/winstonjs/winston/commit/e0c9dde) Remove `winston.transports.Webhook`. Use `winston.transports.Http` instead. +- [f71e638](https://github.com/winstonjs/winston/commit/f71e638) Remove `Logger.prototype.addRewriter` and `Logger.prototype.addFilter` since they just push to an Array of functions. Use `logger.filters.push` or `logger.rewriters.push` explicitly instead. +- [a470ab5](https://github.com/winstonjs/winston/commit/a470ab5) No longer respect the `handleExceptions` option to `new winston.Logger`. Instead just pass in the `exceptionHandlers` option itself. +- [8cb7048](https://github.com/winstonjs/winston/commit/8cb7048) Removed `Logger.prototype.extend` functionality + +#### New features +- [3aa990c](https://github.com/winstonjs/winston/commit/3aa990c) Added `Logger.prototype.configure` which now contains all logic previously in the `winston.Logger` constructor function. (`indexzero`) +- [#726](https://github.com/winstonjs/winston/pull/726) Update .npmignore (`coreybutler`) +- [#700](https://github.com/winstonjs/winston/pull/700) Add an `eol` option to the `Console` transport. (`aquavitae`) +- [#731](https://github.com/winstonjs/winston/pull/731) Update `lib/transports.js` for better static analysis. (`indexzero`) + +#### Fixes, refactoring, and optimizations. OH MY! +- [#632](https://github.com/winstonjs/winston/pull/632) Allow `File` transport to be an `objectMode` writable stream. (`stambata`) +- [#527](https://github.com/winstonjs/winston/issues/527), [163f4f9](https://github.com/winstonjs/winston/commit/163f4f9), [3747ccf](https://github.com/winstonjs/winston/commit/3747ccf) Performance optimizations and string interpolation edge cases (`indexzero`) +- [f0edafd](https://github.com/winstonjs/winston/commit/f0edafd) Code cleanup for reability, ad-hoc styleguide enforcement (`indexzero`) + +## v1.1.1 - v1.1.2 / 2015-10 +### MINOR FIXES EDITION + +#### Notable changes + * [727](https://github.com/winstonjs/winston/pull/727) Fix "raw" mode (`jcrugzz`) + * [703](https://github.com/winstonjs/winston/pull/703) Do not modify Error or Date objects when logging. Fixes #610 (`harriha`). + +## v1.1.0 / 2015-10-09 +### GREETINGS FROM CARTAGENA EDITION + +#### Notable Changes + * [#721](https://github.com/winstonjs/winston/pull/721) Fixed octal literal to work with node 4 strict mode (`wesleyeff`) + * [#630](https://github.com/winstonjs/winston/pull/630) Add stderrLevels option to Console Transport and update docs (`paulhroth`) + * [#626](https://github.com/winstonjs/winston/pull/626) Add the logger (this) in the fourth argument in the rewriters and filters functions (`christophehurpeau `) + * [#623](https://github.com/winstonjs/winston/pull/623) Fix Console Transport's align option tests (`paulhroth`, `kikobeats`) + * [#692](https://github.com/winstonjs/winston/pull/692) Adding winston-aws-cloudwatch to transport docs (`timdp`) + +## v1.0.2 2015-09-25 +### LET'S TALK ON GITTER EDITION + +#### Notable Changes + * [de80160](https://github.com/winstonjs/winston/commit/de80160) Add Gitter badge (`The Gitter Badger`) + * [44564de](https://github.com/winstonjs/winston/commit/44564de) [fix] Correct listeners in `logException`. Fixes [#218](https://github.com/winstonjs/winston/issues/218) [#213](https://github.com/winstonjs/winston/issues/213) [#327](https://github.com/winstonjs/winston/issues/327). (`indexzero`) + * [45b1eeb](https://github.com/winstonjs/winston/commit/45b1eeb) [fix] Get `tailFile` function working on latest/all node versions (`Christopher Jeffrey`) + * [c6d45f9](https://github.com/winstonjs/winston/commit/c6d45f9) Fixed event subscription on close (`Roman Stetsyshin`) + +#### Other changes + * TravisCI updates & best practices [87b97cc](https://github.com/winstonjs/winston/commit/87b97cc) [91a5bc4](https://github.com/winstonjs/winston/commit/91a5bc4), [cf24e6a](https://github.com/winstonjs/winston/commit/cf24e6a) (`indexzero`) + * [d5397e7](https://github.com/winstonjs/winston/commit/d5397e7) Bump async version (`Roderick Hsiao`) + * Documentation updates & fixes [86d7527](https://github.com/winstonjs/winston/commit/86d7527), [38254c1](https://github.com/winstonjs/winston/commit/38254c1), [04e2928](https://github.com/winstonjs/winston/commit/04e2928), [61c8a89](https://github.com/winstonjs/winston/commit/61c8a89), [c42a783](https://github.com/winstonjs/winston/commit/c42a783), [0688a22](https://github.com/winstonjs/winston/commit/0688a22), [eabc113](https://github.com/winstonjs/winston/commit/eabc113) [c9506b7](https://github.com/winstonjs/winston/commit/c9506b7), [17534d2](https://github.com/winstonjs/winston/commit/17534d2), [b575e7b](https://github.com/winstonjs/winston/commit/b575e7b) (`Stefan Thies`, `charukiewicz`, `unLucio`, `Adam Cohen`, `Denis Gorbachev`, `Frederik Ring`, `Luigi Pinca`, `jeffreypriebe`) + * Documentation refactor & cleanup [a19607e](https://github.com/winstonjs/winston/commit/a19607e), [d1932b4](https://github.com/winstonjs/winston/commit/d1932b4), [7a13132](https://github.com/winstonjs/winston/commit/7a13132) (`indexzero`) + + +## v1.0.1 / 2015-06-26 +### YAY DOCS EDITION + + * [#639](https://github.com/winstonjs/winston/pull/639) Fix for [#213](https://github.com/winstonjs/winston/issues/213): More than 10 containers triggers EventEmitter memory leak warning (`marcus`) + * Documentation and `package.json` updates [cec892c](https://github.com/winstonjs/winston/commit/cec892c), [2f13b4f](https://github.com/winstonjs/winston/commit/2f13b4f), [b246efd](https://github.com/winstonjs/winston/commit/b246efd), [22a5f5a](https://github.com/winstonjs/winston/commit/22a5f5a), [5868b78](https://github.com/winstonjs/winston/commit/5868b78), [99b6b44](https://github.com/winstonjs/winston/commit/99b6b44), [447a813](https://github.com/winstonjs/winston/commit/447a813), [7f75b48](https://github.com/winstonjs/winston/commit/7f75b48) (`peteward44`, `Gilad Peleg`, `Anton Ian Sipos`, `nimrod-becker`, `LarsTi`, `indexzero`) + +## v1.0.0 / 2015-04-07 +### OMG 1.0.0 FINALLY EDITION + +#### Breaking Changes + * [#587](https://github.com/winstonjs/winston/pull/587) Do not extend `String` prototypes as a side effect of using `colors`. (`kenperkins`) + * [#581](https://github.com/winstonjs/winston/pull/581) File transports now emit `error` on error of the underlying streams after `maxRetries` attempts. (`ambbell`). + * [#583](https://github.com/winstonjs/winston/pull/583), [92729a](https://github.com/winstonjs/winston/commit/92729a68d71d07715501c35d94d2ac06ac03ca08) Use `os.EOL` for all file writing by default. (`Mik13`, `indexzero`) + * [#532](https://github.com/winstonjs/winston/pull/532) Delete logger instance from `Container` when `close` event is emitted. (`snater`) + * [#380](https://github.com/winstonjs/winston/pull/380) Rename `duration` to `durationMs`, which is now a number a not a string ending in `ms`. (`neoziro`) + * [#253](https://github.com/winstonjs/winston/pull/253) Do not set a default level. When `level` is falsey on any `Transport` instance, any `Logger` instance uses the configured level (instead of the Transport level) (`jstamerj`). + +#### Other changes + + * [b83de62](https://github.com/winstonjs/winston/commit/b83de62) Fix rendering of stack traces. + * [c899cc](https://github.com/winstonjs/winston/commit/c899cc1f0719e49b26ec933e0fa263578168ea3b) Update documentation (Fixes [#549](https://github.com/winstonjs/winston/issues/549)) + * [#551](https://github.com/winstonjs/winston/pull/551) Filter metadata along with messages + * [#578](https://github.com/winstonjs/winston/pull/578) Fixes minor issue with `maxFiles` in `File` transport (Fixes [#556](https://github.com/winstonjs/winston/issues/556)). + * [#560](https://github.com/winstonjs/winston/pull/560) Added `showLevel` support to `File` transport. + * [#558](https://github.com/winstonjs/winston/pull/558) Added `showLevel` support to `Console` transport. + +## v0.9.0 / 2015-02-03 + + * [#496](https://github.com/flatiron/winston/pull/496) Updated default option handling for CLI (`oojacoboo`). + * [f37634b](https://github.com/flatiron/winston/commit/f37634b) [dist] Only support `node >= 0.8.0`. (`indexzero`) + * [91a1e90](https://github.com/flatiron/winston/commit/91a1e90), [50163a0](https://github.com/flatiron/winston/commit/50163a0) Fix #84 [Enable a better unhandled exception experience](https://github.com/flatiron/winston/issues/84) (`samz`) + * [8b5fbcd](https://github.com/flatiron/winston/commit/8b5fbcd) #448 Added tailable option to file transport which rolls files backwards instead of creating incrementing appends. Implements #268 (`neouser99`) + * [a34f7d2](https://github.com/flatiron/winston/commit/a34f7d2) Custom log formatter functionality were added. (`Melnyk Andii`) + * [4c08191](https://github.com/flatiron/winston/commit/4c08191) Added showLevel flag to common.js, file*, memory and console transports. (`Tony Germaneri`) + * [64ed8e0](https://github.com/flatiron/winston/commit/64ed8e0) Adding custom pretty print function test. (`Alberto Pose`) + * [3872dfb](https://github.com/flatiron/winston/commit/3872dfb) Adding prettyPrint parameter as function example. (`Alberto Pose`) + * [2b96eee](https://github.com/flatiron/winston/commit/2b96eee) implemented filters #526 (`Chris Oloff`) + * [72273b1](https://github.com/flatiron/winston/commit/72273b1) Added the options to colorize only the level, only the message or all. Default behavior is kept. Using true will only colorize the level and false will not colorize anything. (`Michiel De Mey`) + * [178e8a6](https://github.com/flatiron/winston/commit/178e8a6) Prevent message from meta input being overwritten (`Leonard Martin`) + * [270be86](https://github.com/flatiron/winston/commit/270be86) [api] Allow for transports to be removed by their string name [test fix] Add test coverage for multiple transports of the same type added in #187. [doc] Document using multiple transports of the same type (`indexzero`) + * [0a848fa](https://github.com/flatiron/winston/commit/0a848fa) Add depth options for meta pretty print (`Loïc Mahieu`) + * [106b670](https://github.com/flatiron/winston/commit/106b670) Allow debug messages to be sent to stdout (`John Frizelle`) + * [ad2d5e1](https://github.com/flatiron/winston/commit/ad2d5e1) [fix] Handle Error instances in a sane way since their properties are non-enumerable __by default.__ Fixes #280. (`indexzero`) + * [5109dd0](https://github.com/flatiron/winston/commit/5109dd0) [fix] Have a default `until` before a default `from`. Fixes #478. (`indexzero`) + * [d761960](https://github.com/flatiron/winston/commit/d761960) Fix logging regular expression objects (`Chasen Le Hara`) + * [2632eb8](https://github.com/flatiron/winston/commit/2632eb8) Add option for EOL chars on FileTransport (`José F. Romaniello`) + * [bdecce7](https://github.com/flatiron/winston/commit/bdecce7) Remove duplicate logstash option (`José F. Romaniello`) + * [7a01f9a](https://github.com/flatiron/winston/commit/7a01f9a) Update declaration block according to project's style guide (`Ricardo Torres`) + * [ae27a19](https://github.com/flatiron/winston/commit/ae27a19) Fixes #306: Can't set customlevels to my loggers (RangeError: Maximum call stack size exceeded) (`Alberto Pose`) + * [1ba4f51](https://github.com/flatiron/winston/commit/1ba4f51) [fix] Call `res.resume()` in HttpTransport to get around known issues in streams2. (`indexzero`) + * [39e0258](https://github.com/flatiron/winston/commit/39e0258) Updated default option handling for CLI (`Jacob Thomason`) + * [8252801](https://github.com/flatiron/winston/commit/8252801) Added logstash support to console transport (`Ramon Snir`) + * [18aa301](https://github.com/flatiron/winston/commit/18aa301) Module isStream should be isstream (`Michael Neil`) + * [2f5f296](https://github.com/flatiron/winston/commit/2f5f296) options.prettyPrint can now be a function (`Matt Zukowski`) + * [a87a876](https://github.com/flatiron/winston/commit/a87a876) Adding rotationFormat prop to file.js (`orcaman`) + * [ff187f4](https://github.com/flatiron/winston/commit/ff187f4) Allow custom exception level (`jupiter`) + +## 0.8.3 / 2014-11-04 + +* [fix lowercase issue (`jcrugzz`)](https://github.com/flatiron/winston/commit/b3ffaa10b5fe9d2a510af5348cf4fb3870534123) + +## 0.8.2 / 2014-11-04 + +* [Full fix for #296 with proper streams2 detection with `isstream` for file transport (`jcrugzz`)](https://github.com/flatiron/winston/commit/5c4bd4191468570e46805ed399cad63cfb1856cc) +* [Add isstream module (`jcrugzz`)](https://github.com/flatiron/winston/commit/498b216d0199aebaef72ee4d8659a00fb737b9ae) +* [Partially fix #296 with streams2 detection for file transport (`indexzero`)](https://github.com/flatiron/winston/commit/b0227b6c27cf651ffa8b8192ef79ab24296362e3) +* [add stress test for issue #288 (`indexzero`)](https://github.com/flatiron/winston/commit/e08e504b5b3a00f0acaade75c5ba69e6439c84a6) +* [lessen timeouts to check test sanity (`indexzero`)](https://github.com/flatiron/winston/commit/e925f5bc398a88464f3e796545ff88912aff7568) +* [update winston-graylog2 documentation (`unlucio`)](https://github.com/flatiron/winston/commit/49fa86c31baf12c8ac3adced3bdba6deeea2e363) +* [fix test formatting (`indexzero`)](https://github.com/flatiron/winston/commit/8e2225799520a4598044cdf93006d216812a27f9) +* [fix so options are not redefined (`indexzero`)](https://github.com/flatiron/winston/commit/d1d146e8a5bb73dcb01579ad433f6d4f70b668ea) +* [fix self/this issue that broke `http` transport (`indexzero`)](https://github.com/flatiron/winston/commit/d10cbc07755c853b60729ab0cd14aa665da2a63b) + + +## 0.8.1 / 2014-10-06 + +* [Add label option for DailyRotateFile transport (`francoisTemasys`)](https://github.com/flatiron/winston/pull/459) +* [fix Logger#transports length check upon Logger#log (`adriano-di-giovanni`, `indexzero`)](https://github.com/flatiron/winston/pull/404) +* [err can be a string. (`gdw2`, `indexzero`)](https://github.com/flatiron/winston/pull/396) +* [Added color for pre-defined cli set. (`danilo1105`, `indexzero`)](https://github.com/flatiron/winston/pull/365) +* [Fix dates on transport test (`revington`)](https://github.com/flatiron/winston/pull/346) +* [Included the label from options to the output in JSON mode. (`arxony`)](https://github.com/flatiron/winston/pull/326) +* [Allow using logstash option with the File transport (`gmajoulet`)](https://github.com/flatiron/winston/pull/299) +* [Be more defensive when working with `query` methods from Transports. Fixes #356. (indexzero)](https://github.com/flatiron/winston/commit/b80638974057f74b521dbe6f43fef2105110afa2) +* [Catch exceptions for file transport unlinkSync (`calvinfo`)](https://github.com/flatiron/winston/pull/266) +* [Adding the 'addRewriter' to winston (`machadogj`)](https://github.com/flatiron/winston/pull/258) +* [Updates to transport documentation (`pose`)](https://github.com/flatiron/winston/pull/262) +* [fix typo in "Extending another object with Logging" section.](https://github.com/flatiron/winston/pull/281) +* [Updated README.md - Replaced properties with those listed in winston-mongodb module](https://github.com/flatiron/winston/pull/264) + +## 0.8.0 / 2014-09-15 + * [Fixes for HTTP Transport](https://github.com/flatiron/winston/commit/a876a012641f8eba1a976eada15b6687d4a03f82) + * Removing [jsonquest](https://github.com/flatiron/winston/commit/4f088382aeda28012b7a0498829ceb243ed74ac1) and [request](https://github.com/flatiron/winston/commit/a5676313b4e9744802cc3b8e1468e4af48830876) dependencies. + * Configuration is now [shalow cloned](https://github.com/flatiron/winston/commit/08fccc81d18536d33050496102d98bde648853f2). + * [Added logstash support](https://github.com/flatiron/winston/pull/445/files) + * Fix for ["flush" event should always fire after "flush" call bug](https://github.com/flatiron/winston/pull/446/files) + * Added tests for file: [open and stress](https://github.com/flatiron/winston/commit/47d885797a2dd0d3cd879305ca813a0bd951c378). + * [Test fixes](https://github.com/flatiron/winston/commit/9e39150e0018f43d198ca4c160acef2af9860bf4) + * [Fix ")" on string interpolation](https://github.com/flatiron/winston/pull/394/files) + +## 0.6.2 / 2012-07-08 + + * Added prettyPrint option for console logging + * Multi-line values for conditional returns are not allowed + * Added acceptance of `stringify` option + * Fixed padding for log levels + diff --git a/node_modules/winston/LICENSE b/node_modules/winston/LICENSE new file mode 100644 index 0000000..948d80d --- /dev/null +++ b/node_modules/winston/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Charlie Robbins + +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/winston/README.md b/node_modules/winston/README.md new file mode 100644 index 0000000..7f4497d --- /dev/null +++ b/node_modules/winston/README.md @@ -0,0 +1,833 @@ +# winston + +[![Join the chat at https://gitter.im/winstonjs/winston](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/winstonjs/winston?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +[![Version npm](https://img.shields.io/npm/v/winston.svg?style=flat-square)](https://www.npmjs.com/package/winston)[![npm Downloads](https://img.shields.io/npm/dm/winston.svg?style=flat-square)](https://www.npmjs.com/package/winston)[![Build Status](https://img.shields.io/travis/winstonjs/winston/master.svg?style=flat-square)](https://travis-ci.org/winstonjs/winston)[![Dependencies](https://img.shields.io/david/winstonjs/winston.svg?style=flat-square)](https://david-dm.org/winstonjs/winston) + +[![NPM](https://nodei.co/npm/winston.png?downloads=true&downloadRank=true)](https://nodei.co/npm/winston/) + +A multi-transport async logging library for node.js. <span style="font-size:28px; font-weight:bold;">"CHILL WINSTON! ... I put it in the logs."</span> + +## Motivation +Winston is designed to be a simple and universal logging library with support for multiple transports. A transport is essentially a storage device for your logs. Each instance of a winston logger can have multiple transports configured at different levels. For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file. + +There also seemed to be a lot of logging libraries out there that coupled their implementation of logging (i.e. how the logs are stored / indexed) to the API that they exposed to the programmer. This library aims to decouple those parts of the process to make it more flexible and extensible. + +## Installation + +```bashp +npm install winston +``` + +## Usage +There are two different ways to use winston: directly via the default logger, or by instantiating your own Logger. The former is merely intended to be a convenient shared logger to use throughout your application if you so choose. + +* [Logging](#logging) + * [Using the Default Logger](#using-the-default-logger) + * [Instantiating your own Logger](#instantiating-your-own-logger) + * [Logging with Metadata](#logging-with-metadata) + * [String interpolation](#string-interpolation) +* [Transports](https://github.com/winstonjs/winston/blob/master/docs/transports.md) + * [Multiple transports of the same type](#multiple-transports-of-the-same-type) +* [Profiling](#profiling) +* [Streaming Logs](#streaming-logs) +* [Querying Logs](#querying-logs) +* [Exceptions](#exceptions) + * [Handling Uncaught Exceptions with winston](#handling-uncaught-exceptions-with-winston) + * [To Exit or Not to Exit](#to-exit-or-not-to-exit) +* [Logging Levels](#logging-levels) + * [Using Logging Levels](#using-logging-levels) + * [Using Custom Logging Levels](#using-custom-logging-levels) +* [Further Reading](#further-reading) + * [Events and Callbacks in Winston](#events-and-callbacks-in-winston) + * [Working with multiple Loggers in winston](#working-with-multiple-loggers-in-winston) + * [Using winston in a CLI tool](#using-winston-in-a-cli-tool) + * [Filters and Rewriters](#filters-and-rewriters) + * [Adding Custom Transports](#adding-custom-transports) +* [Installation](#installation) +* [Run Tests](#run-tests) + + +## Logging + +Logging levels in `winston` conform to the severity ordering specified by [RFC5424](https://tools.ietf.org/html/rfc5424): _severity of all levels is assumed to be numerically **ascending** from most important to least important._ + +### Using the Default Logger +The default logger is accessible through the winston module directly. Any method that you could call on an instance of a logger is available on the default logger: + +``` js + var winston = require('winston'); + + winston.log('info', 'Hello distributed log files!'); + winston.info('Hello again distributed logs'); + + winston.level = 'debug'; + winston.log('debug', 'Now my debug messages are written to console!'); +``` + +By default, only the Console transport is set on the default logger. You can add or remove transports via the add() and remove() methods: + +``` js + winston.add(winston.transports.File, { filename: 'somefile.log' }); + winston.remove(winston.transports.Console); +``` + +For more documentation about working with each individual transport supported by Winston see the [Winston Transports](docs/transports.md) document. + +### Instantiating your own Logger +If you would prefer to manage the object lifetime of loggers you are free to instantiate them yourself: + +``` js + var logger = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)(), + new (winston.transports.File)({ filename: 'somefile.log' }) + ] + }); +``` + +You can work with this logger in the same way that you work with the default logger: + +``` js + // + // Logging + // + logger.log('info', 'Hello distributed log files!'); + logger.info('Hello again distributed logs'); + + // + // Adding / Removing Transports + // (Yes It's chainable) + // + logger + .add(winston.transports.File) + .remove(winston.transports.Console); +``` + +You can also wholesale reconfigure a `winston.Logger` instance using the `configure` method: + +``` js + var logger = new winston.Logger({ + level: 'info', + transports: [ + new (winston.transports.Console)(), + new (winston.transports.File)({ filename: 'somefile.log' }) + ] + }); + + // + // Replaces the previous transports with those in the + // new configuration wholesale. + // + logger.configure({ + level: 'verbose', + transports: [ + new require('winston-daily-rotate-file')(opts) + ] + }); +``` + + +### Logging with Metadata +In addition to logging string messages, winston will also optionally log additional JSON metadata objects. Adding metadata is simple: + +``` js + winston.log('info', 'Test Log Message', { anything: 'This is metadata' }); +``` + +The way these objects are stored varies from transport to transport (to best support the storage mechanisms offered). Here's a quick summary of how each transports handles metadata: + +1. __Console:__ Logged via util.inspect(meta) +2. __File:__ Logged via util.inspect(meta) + +## Multiple transports of the same type + +It is possible to use multiple transports of the same type e.g. `winston.transports.File` by passing in a custom `name` when you construct the transport. + +``` js +var logger = new (winston.Logger)({ + transports: [ + new (winston.transports.File)({ + name: 'info-file', + filename: 'filelog-info.log', + level: 'info' + }), + new (winston.transports.File)({ + name: 'error-file', + filename: 'filelog-error.log', + level: 'error' + }) + ] +}); +``` + +If you later want to remove one of these transports you can do so by using the string name. e.g.: + +``` js +logger.remove('info-file'); +``` + +In this example one could also remove by passing in the instance of the Transport itself. e.g. this is equivalent to the string example above; + +``` js +// Notice it was first in the Array above +var infoFile = logger.transports[0]; +logger.remove(infoFile); +``` + +## Profiling +In addition to logging messages and metadata, winston also has a simple profiling mechanism implemented for any logger: + +``` js + // + // Start profile of 'test' + // Remark: Consider using Date.now() with async operations + // + winston.profile('test'); + + setTimeout(function () { + // + // Stop profile of 'test'. Logging will now take place: + // "17 Jan 21:00:00 - info: test duration=1000ms" + // + winston.profile('test'); + }, 1000); +``` + +All profile messages are set to the 'info' by default and both message and metadata are optional There are no plans in the Roadmap to make this configurable, but I'm open to suggestions / issues. + +### String interpolation +The `log` method provides the same string interpolation methods like [`util.format`][10]. + +This allows for the following log messages. +``` js +logger.log('info', 'test message %s', 'my string'); +// info: test message my string + +logger.log('info', 'test message %d', 123); +// info: test message 123 + +logger.log('info', 'test message %j', {number: 123}, {}); +// info: test message {"number":123} +// meta = {} + +logger.log('info', 'test message %s, %s', 'first', 'second', {number: 123}); +// info: test message first, second +// meta = {number: 123} + +logger.log('info', 'test message', 'first', 'second', {number: 123}); +// info: test message first second +// meta = {number: 123} + +logger.log('info', 'test message %s, %s', 'first', 'second', {number: 123}, function(){}); +// info: test message first, second +// meta = {number: 123} +// callback = function(){} + +logger.log('info', 'test message', 'first', 'second', {number: 123}, function(){}); +// info: test message first second +// meta = {number: 123} +// callback = function(){} +``` + + + + + +## Querying Logs +Winston supports querying of logs with Loggly-like options. [See Loggly Search API](http://wiki.loggly.com/retrieve_events#optional). +Specifically: `File`, `Couchdb`, `Redis`, `Loggly`, `Nssocket`, and `Http`. + +``` js + var options = { + from: new Date - 24 * 60 * 60 * 1000, + until: new Date, + limit: 10, + start: 0, + order: 'desc', + fields: ['message'] + }; + + // + // Find items logged between today and yesterday. + // + winston.query(options, function (err, results) { + if (err) { + throw err; + } + + console.log(results); + }); +``` + +## Streaming Logs +Streaming allows you to stream your logs back from your chosen transport. + +``` js + // + // Start at the end. + // + winston.stream({ start: -1 }).on('log', function(log) { + console.log(log); + }); +``` + +## Exceptions + +### Handling Uncaught Exceptions with winston + +With `winston`, it is possible to catch and log `uncaughtException` events from your process. There are two distinct ways of enabling this functionality either through the default winston logger or your own logger instance. + +If you want to use this feature with the default logger simply call `.handleExceptions()` with a transport instance. + +``` js + // + // You can add a separate exception logger by passing it to `.handleExceptions` + // + winston.handleExceptions(new winston.transports.File({ filename: 'path/to/exceptions.log' })) + + // + // Alternatively you can set `.handleExceptions` to true when adding transports to winston. + // You can use the `.humanReadableUnhandledException` option to get more readable exceptions. + // + winston.add(winston.transports.File, { + filename: 'path/to/all-logs.log', + handleExceptions: true, + humanReadableUnhandledException: true + }); +``` + +### To Exit or Not to Exit + +By default, winston will exit after logging an uncaughtException. if this is not the behavior you want, +set `exitOnError = false` + +``` js + var logger = new (winston.Logger)({ exitOnError: false }); + + // + // or, like this: + // + logger.exitOnError = false; +``` + +When working with custom logger instances, you can pass in separate transports to the `exceptionHandlers` property or set `.handleExceptions` on any transport. + +Example 1 + +``` js + var logger = new (winston.Logger)({ + transports: [ + new winston.transports.File({ filename: 'path/to/all-logs.log' }) + ], + exceptionHandlers: [ + new winston.transports.File({ filename: 'path/to/exceptions.log' }) + ] + }); +``` + +Example 2 + +``` js +var logger = new winston.Logger({ + transports: [ + new winston.transports.Console({ + handleExceptions: true, + json: true + }) + ], + exitOnError: false +}); +``` + +The `exitOnError` option can also be a function to prevent exit on only certain types of errors: + +``` js + function ignoreEpipe(err) { + return err.code !== 'EPIPE'; + } + + var logger = new (winston.Logger)({ exitOnError: ignoreEpipe }); + + // + // or, like this: + // + logger.exitOnError = ignoreEpipe; +``` + +## Logging Levels + +Each `level` is given a specific integer priority. The higher the priority the more important the message is considered to be, and the lower the corresponding integer priority. For example, `npm` logging levels are prioritized from 0 to 5 (highest to lowest): + +``` js +{ error: 0, warn: 1, info: 2, verbose: 3, debug: 4, silly: 5 } +``` + +Similarly, as specified exactly in RFC5424 the `syslog` levels are prioritized from 0 to 7 (highest to lowest). + +```js +{ emerg: 0, alert: 1, crit: 2, error: 3, warning: 4, notice: 5, info: 6, debug: 7 } +``` + +If you do not explicitly define the levels that `winston` should use the `npm` levels above will be used. + +### Using Logging Levels +Setting the level for your logging message can be accomplished in one of two ways. You can pass a string representing the logging level to the log() method or use the level specified methods defined on every winston Logger. + +``` js + // + // Any logger instance + // + logger.log('silly', "127.0.0.1 - there's no place like home"); + logger.log('debug', "127.0.0.1 - there's no place like home"); + logger.log('verbose', "127.0.0.1 - there's no place like home"); + logger.log('info', "127.0.0.1 - there's no place like home"); + logger.log('warn', "127.0.0.1 - there's no place like home"); + logger.log('error', "127.0.0.1 - there's no place like home"); + logger.info("127.0.0.1 - there's no place like home"); + logger.warn("127.0.0.1 - there's no place like home"); + logger.error("127.0.0.1 - there's no place like home"); + + // + // Default logger + // + winston.log('info', "127.0.0.1 - there's no place like home"); + winston.info("127.0.0.1 - there's no place like home"); +``` + +`winston` allows you to define a `level` property on each transport which specifies the **maximum** level of messages that a transport should log. For example, using the `npm` levels you could log only `error` messages to the console and everything `info` and below to a file (which includes `error` messages): + +``` js + var logger = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)({ level: 'error' }), + new (winston.transports.File)({ + filename: 'somefile.log', + level: 'info' + }) + ] + }); +``` + +You may also dynamically change the log level of a transport: + +``` js + var logger = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)({ level: 'warn' }), + new (winston.transports.File)({ filename: 'somefile.log', level: 'error' }) + ] + }); + logger.debug("Will not be logged in either transport!"); + logger.transports.console.level = 'debug'; + logger.transports.file.level = 'verbose'; + logger.verbose("Will be logged in both transports!"); +``` + +As of 0.2.0, winston supports customizable logging levels, defaulting to [npm][0] style logging levels. Changing logging levels is easy: + +``` js + // + // Change levels on the default winston logger + // + winston.setLevels(winston.config.syslog.levels); + + // + // Change levels on an instance of a logger + // + logger.setLevels(winston.config.syslog.levels); +``` + +Calling `.setLevels` on a logger will remove all of the previous helper methods for the old levels and define helper methods for the new levels. Thus, you should be careful about the logging statements you use when changing levels. For example, if you ran this code after changing to the syslog levels: + +``` js + // + // Logger does not have 'silly' defined since that level is not in the syslog levels + // + logger.silly('some silly message'); +``` + +### Using Custom Logging Levels +In addition to the predefined `npm` and `syslog` levels available in Winston, you can also choose to define your own: + +``` js + var myCustomLevels = { + levels: { + foo: 0, + bar: 1, + baz: 2, + foobar: 3 + }, + colors: { + foo: 'blue', + bar: 'green', + baz: 'yellow', + foobar: 'red' + } + }; + + var customLevelLogger = new (winston.Logger)({ levels: myCustomLevels.levels }); + customLevelLogger.foobar('some foobar level-ed message'); +``` + +Although there is slight repetition in this data structure, it enables simple encapsulation if you do not want to have colors. If you do wish to have colors, in addition to passing the levels to the Logger itself, you must make winston aware of them: + +``` js + // + // Make winston aware of these colors + // + winston.addColors(myCustomLevels.colors); +``` + +This enables transports with the 'colorize' option set to appropriately color the output of custom levels. + +## Further Reading + +### Events and Callbacks in Winston +Each instance of winston.Logger is also an instance of an [EventEmitter][1]. A log event will be raised each time a transport successfully logs a message: + +``` js + logger.on('logging', function (transport, level, msg, meta) { + // [msg] and [meta] have now been logged at [level] to [transport] + }); + + logger.info('CHILL WINSTON!', { seriously: true }); +``` + +It is also worth mentioning that the logger also emits an 'error' event which you should handle or suppress if you don't want unhandled exceptions: + +``` js + // + // Handle errors + // + logger.on('error', function (err) { /* Do Something */ }); + + // + // Or just suppress them. + // + logger.emitErrs = false; +``` + +Every logging method described in the previous section also takes an optional callback which will be called only when all of the transports have logged the specified message. + +``` js + logger.info('CHILL WINSTON!', { seriously: true }, function (err, level, msg, meta) { + // [msg] and [meta] have now been logged at [level] to **every** transport. + }); +``` + +### Working with multiple Loggers in winston + +Often in larger, more complex applications it is necessary to have multiple logger instances with different settings. Each logger is responsible for a different feature area (or category). This is exposed in `winston` in two ways: through `winston.loggers` and instances of `winston.Container`. In fact, `winston.loggers` is just a predefined instance of `winston.Container`: + +``` js + var winston = require('winston'); + + // + // Configure the logger for `category1` + // + winston.loggers.add('category1', { + console: { + level: 'silly', + colorize: true, + label: 'category one' + }, + file: { + filename: '/path/to/some/file' + } + }); + + // + // Configure the logger for `category2` + // + winston.loggers.add('category2', { + couchdb: { + host: '127.0.0.1', + port: 5984 + } + }); +``` + +Now that your loggers are setup you can require winston _in any file in your application_ and access these pre-configured loggers: + +``` js + var winston = require('winston'); + + // + // Grab your preconfigured logger + // + var category1 = winston.loggers.get('category1'); + + category1.info('logging from your IoC container-based logger'); +``` + +If you prefer to manage the `Container` yourself you can simply instantiate one: + +``` js + var winston = require('winston'), + container = new winston.Container(); + + container.add('category1', { + console: { + level: 'silly', + colorize: true + }, + file: { + filename: '/path/to/some/file' + } + }); +``` + +### Sharing transports between Loggers in winston + +``` js + var winston = require('winston'); + + // + // Setup transports to be shared across all loggers + // in three ways: + // + // 1. By setting it on the default Container + // 2. By passing `transports` into the constructor function of winston.Container + // 3. By passing `transports` into the `.get()` or `.add()` methods + // + + // + // 1. By setting it on the default Container + // + winston.loggers.options.transports = [ + // Setup your shared transports here + ]; + + // + // 2. By passing `transports` into the constructor function of winston.Container + // + var container = new winston.Container({ + transports: [ + // Setup your shared transports here + ] + }); + + // + // 3. By passing `transports` into the `.get()` or `.add()` methods + // + winston.loggers.add('some-category', { + transports: [ + // Setup your shared transports here + ] + }); + + container.add('some-category', { + transports: [ + // Setup your shared transports here + ] + }); +``` + +### Using winston in a CLI tool +A common use-case for logging is output to a CLI tool. Winston has a special helper method which will pretty print output from your CLI tool. Here's an example from the [require-analyzer][2] written by [Nodejitsu][3]: + +``` + info: require-analyzer starting in /Users/Charlie/Nodejitsu/require-analyzer + info: Found existing dependencies + data: { + data: colors: '0.x.x', + data: eyes: '0.1.x', + data: findit: '0.0.x', + data: npm: '1.0.x', + data: optimist: '0.2.x', + data: semver: '1.0.x', + data: winston: '0.2.x' + data: } + info: Analyzing dependencies... + info: Done analyzing raw dependencies + info: Retrieved packages from npm + warn: No additional dependencies found +``` + +Configuring output for this style is easy, just use the `.cli()` method on `winston` or an instance of `winston.Logger`: + +``` js + var winston = require('winston'); + + // + // Configure CLI output on the default logger + // + winston.cli(); + + // + // Configure CLI on an instance of winston.Logger + // + var logger = new winston.Logger({ + transports: [ + new (winston.transports.Console)() + ] + }); + + logger.cli(); +``` + +### Filters and Rewriters +Filters allow modifying the contents of **log messages**, and Rewriters allow modifying the contents of **log meta** e.g. to mask data that should not appear in logs. + +Both filters and rewriters are simple Arrays of functions which can be provided when creating a `new winston.Logger(options)`. e.g.: + +``` js +var logger = new winston.Logger({ + rewriters: [function (level, msg, meta) { /* etc etc */ }] + filters: [function (level, msg, meta) { /* etc etc */ }] +}) +``` + +Like any Array they can also be modified at runtime with no adverse side-effects to the `winston` internals. + +``` js +logger.filters.push(function(level, msg, meta) { + return meta.production + ? maskCardNumbers(msg) + : msg; +}); + +logger.info('transaction with card number 123456789012345 successful.'); +``` + +This may result in this output: + +``` +info: transaction with card number 123456****2345 successful. +``` + +Where as for rewriters, if you wanted to sanitize the `creditCard` field of your `meta` you could: + +``` js +logger.rewriters.push(function(level, msg, meta) { + if (meta.creditCard) { + meta.creditCard = maskCardNumbers(meta.creditCard) + } + + return meta; +}); + +logger.info('transaction ok', { creditCard: 123456789012345 }); +``` + +which may result in this output: + +``` +info: transaction ok creditCard=123456****2345 +``` + +See [log-filter-test.js](./test/log-filter-test.js), where card number masking is implemented as an example along with [log-rewriter-test.js](./test/log-rewriter-test.js) + +## Adding Custom Transports +Adding a custom transport is actually pretty easy. All you need to do is accept a couple of options, set a name, implement a log() method, and add it to the set of transports exposed by winston. + +``` js + var util = require('util'), + winston = require('winston'); + + var CustomLogger = winston.transports.CustomLogger = function (options) { + // + // Name this logger + // + this.name = 'customLogger'; + + // + // Set the level from your options + // + this.level = options.level || 'info'; + + // + // Configure your storage backing as you see fit + // + }; + + // + // Inherit from `winston.Transport` so you can take advantage + // of the base functionality and `.handleExceptions()`. + // + util.inherits(CustomLogger, winston.Transport); + + CustomLogger.prototype.log = function (level, msg, meta, callback) { + // + // Store this message and metadata, maybe use some custom logic + // then callback indicating success. + // + callback(null, true); + }; +``` + +### Custom Log Format +To specify custom log format you should set formatter function for transport. Currently supported transports are: Console, File, Memory. +Options object will be passed to the format function. It's general properties are: timestamp, level, message, meta. Depending on the transport type may be additional properties. + +``` js +var logger = new (winston.Logger)({ + transports: [ + new (winston.transports.Console)({ + timestamp: function() { + return Date.now(); + }, + formatter: function(options) { + // Return string will be passed to logger. + return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') + + (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' ); + } + }) + ] +}); +logger.info('Data to log.'); +``` + +### Inspirations +1. [npm][0] +2. [log.js][4] +3. [socket.io][5] +4. [node-rlog][6] +5. [BigBrother][7] +6. [Loggly][8] + +## Installation + +### Installing npm (node package manager) +``` + curl http://npmjs.org/install.sh | sh +``` + +### Installing winston +``` + [sudo] npm install winston +``` + +## Run Tests +All of the winston tests are written in [vows][9], and designed to be run with npm. + +``` bash + $ npm test +``` + +#### Author: [Charlie Robbins](http://twitter.com/indexzero) +#### Contributors: [Matthew Bergman](http://github.com/fotoverite), [Marak Squires](http://github.com/marak) + +[0]: https://github.com/npm/npmlog/blob/master/log.js +[1]: http://nodejs.org/docs/v0.3.5/api/events.html#events.EventEmitter +[2]: http://github.com/nodejitsu/require-analyzer +[3]: http://nodejitsu.com +[4]: https://github.com/visionmedia/log.js +[5]: http://socket.io +[6]: https://github.com/jbrisbin/node-rlog +[7]: https://github.com/feisty/BigBrother +[8]: http://loggly.com +[9]: http://vowsjs.org +[10]: http://nodejs.org/api/util.html#util_util_format_format +[14]: http://nodejs.org/api/stream.html#stream_class_stream_writable +[16]: https://github.com/indexzero/winston-mongodb +[17]: https://github.com/indexzero/winston-riak +[18]: https://github.com/appsattic/winston-simpledb +[19]: https://github.com/wavded/winston-mail +[21]: https://github.com/jesseditson/winston-sns +[22]: https://github.com/flite/winston-graylog2 +[23]: https://github.com/kenperkins/winston-papertrail +[24]: https://github.com/jorgebay/winston-cassandra +[25]: https://github.com/jesseditson/winston-sns +[26]: https://github.com/inspiredjw/winston-dynamodb/ diff --git a/node_modules/winston/lib/winston.js b/node_modules/winston/lib/winston.js new file mode 100644 index 0000000..43aa6d1 --- /dev/null +++ b/node_modules/winston/lib/winston.js @@ -0,0 +1,165 @@ +/* + * winston.js: Top-level include defining Winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var winston = exports; + +// +// Expose version using `pkginfo` +// +require('pkginfo')(module, 'version'); + +// +// Include transports defined by default by winston +// +winston.transports = require('./winston/transports'); + +// +// Expose utility methods +// +var common = require('./winston/common'); +winston.hash = common.hash; +winston.clone = common.clone; +winston.longestElement = common.longestElement; +winston.exception = require('./winston/exception'); +winston.config = require('./winston/config'); +winston.addColors = winston.config.addColors; + +// +// Expose core Logging-related prototypes. +// +winston.Container = require('./winston/container').Container; +winston.Logger = require('./winston/logger').Logger; +winston.Transport = require('./winston/transports/transport').Transport; + +// +// We create and expose a default `Container` to `winston.loggers` so that the +// programmer may manage multiple `winston.Logger` instances without any additional overhead. +// +// ### some-file1.js +// +// var logger = require('winston').loggers.get('something'); +// +// ### some-file2.js +// +// var logger = require('winston').loggers.get('something'); +// +winston.loggers = new winston.Container(); + +// +// We create and expose a 'defaultLogger' so that the programmer may do the +// following without the need to create an instance of winston.Logger directly: +// +// var winston = require('winston'); +// winston.log('info', 'some message'); +// winston.error('some error'); +// +var defaultLogger = new winston.Logger({ + transports: [new winston.transports.Console()] +}); + +// +// Pass through the target methods onto `winston. +// +var methods = [ + 'log', + 'query', + 'stream', + 'add', + 'remove', + 'clear', + 'profile', + 'startTimer', + 'extend', + 'cli', + 'handleExceptions', + 'unhandleExceptions', + 'addRewriter', + 'addFilter' +]; +common.setLevels(winston, null, defaultLogger.levels); +methods.forEach(function (method) { + winston[method] = function () { + return defaultLogger[method].apply(defaultLogger, arguments); + }; +}); + +// +// ### function cli () +// Configures the default winston logger to have the +// settings for command-line interfaces: no timestamp, +// colors enabled, padded output, and additional levels. +// +winston.cli = function () { + winston.padLevels = true; + common.setLevels(winston, defaultLogger.levels, winston.config.cli.levels); + defaultLogger.setLevels(winston.config.cli.levels); + winston.config.addColors(winston.config.cli.colors); + + if (defaultLogger.transports.console) { + defaultLogger.transports.console.colorize = true; + defaultLogger.transports.console.timestamp = false; + } + + return winston; +}; + +// +// ### function setLevels (target) +// #### @target {Object} Target levels to use +// Sets the `target` levels specified on the default winston logger. +// +winston.setLevels = function (target) { + common.setLevels(winston, defaultLogger.levels, target); + defaultLogger.setLevels(target); +}; + +// +// Define getter / setter for the default logger level +// which need to be exposed by winston. +// +Object.defineProperty(winston, 'level', { + get: function () { + return defaultLogger.level; + }, + set: function (val) { + defaultLogger.level = val; + + Object.keys(defaultLogger.transports).forEach(function(key) { + defaultLogger.transports[key].level = val; + }); + } +}); + +// +// Define getters / setters for appropriate properties of the +// default logger which need to be exposed by winston. +// +['emitErrs', 'exitOnError', 'padLevels', 'levelLength', 'stripColors'].forEach(function (prop) { + Object.defineProperty(winston, prop, { + get: function () { + return defaultLogger[prop]; + }, + set: function (val) { + defaultLogger[prop] = val; + } + }); +}); + +// +// @default {Object} +// The default transports and exceptionHandlers for +// the default winston logger. +// +Object.defineProperty(winston, 'default', { + get: function () { + return { + transports: defaultLogger.transports, + exceptionHandlers: defaultLogger.exceptionHandlers + }; + } +}); diff --git a/node_modules/winston/lib/winston/common.js b/node_modules/winston/lib/winston/common.js new file mode 100644 index 0000000..29dfec0 --- /dev/null +++ b/node_modules/winston/lib/winston/common.js @@ -0,0 +1,483 @@ +/* + * common.js: Internal helper and utility functions for winston + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var util = require('util'), + crypto = require('crypto'), + cycle = require('cycle'), + fs = require('fs'), + StringDecoder = require('string_decoder').StringDecoder, + Stream = require('stream').Stream, + config = require('./config'); + +// +// ### function setLevels (target, past, current) +// #### @target {Object} Object on which to set levels. +// #### @past {Object} Previous levels set on target. +// #### @current {Object} Current levels to set on target. +// Create functions on the target objects for each level +// in current.levels. If past is defined, remove functions +// for each of those levels. +// +exports.setLevels = function (target, past, current, isDefault) { + var self = this; + if (past) { + Object.keys(past).forEach(function (level) { + delete target[level]; + }); + } + + target.levels = current || config.npm.levels; + if (target.padLevels) { + target.levelLength = exports.longestElement(Object.keys(target.levels)); + } + + // + // Define prototype methods for each log level + // e.g. target.log('info', msg) <=> target.info(msg) + // + Object.keys(target.levels).forEach(function (level) { + + // TODO Refactor logging methods into a different object to avoid name clashes + if (level === 'log') { + console.warn('Log level named "log" will clash with the method "log". Consider using a different name.'); + return; + } + + target[level] = function (msg) { + // build argument list (level, msg, ... [string interpolate], [{metadata}], [callback]) + var args = [level].concat(Array.prototype.slice.call(arguments)); + target.log.apply(target, args); + }; + }); + + return target; +}; + +// +// ### function longestElement +// #### @xs {Array} Array to calculate against +// Returns the longest element in the `xs` array. +// +exports.longestElement = function (xs) { + return Math.max.apply( + null, + xs.map(function (x) { return x.length; }) + ); +}; + +// +// ### function clone (obj) +// #### @obj {Object} Object to clone. +// Helper method for deep cloning pure JSON objects +// i.e. JSON objects that are either literals or objects (no Arrays, etc) +// +exports.clone = function (obj) { + // + // We only need to clone reference types (Object) + // + var copy = {}; + + if (obj instanceof Error) { + // With potential custom Error objects, this might not be exactly correct, + // but probably close-enough for purposes of this lib. + copy = new Error(obj.message); + Object.getOwnPropertyNames(obj).forEach(function (key) { + copy[key] = obj[key]; + }); + + return copy; + } + else if (!(obj instanceof Object)) { + return obj; + } + else if (obj instanceof Date) { + return new Date(obj.getTime()); + } + + for (var i in obj) { + if (Array.isArray(obj[i])) { + copy[i] = obj[i].slice(0); + } + else if (obj[i] instanceof Buffer) { + copy[i] = obj[i].slice(0); + } + else if (typeof obj[i] != 'function') { + copy[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i]; + } + else if (typeof obj[i] === 'function') { + copy[i] = obj[i]; + } + } + + return copy; +}; + +// +// ### function log (options) +// #### @options {Object} All information about the log serialization. +// Generic logging function for returning timestamped strings +// with the following options: +// +// { +// level: 'level to add to serialized message', +// message: 'message to serialize', +// meta: 'additional logging metadata to serialize', +// colorize: false, // Colorizes output (only if `.json` is false) +// align: false // Align message level. +// timestamp: true // Adds a timestamp to the serialized message +// label: 'label to prepend the message' +// } +// +exports.log = function (options) { + var timestampFn = typeof options.timestamp === 'function' + ? options.timestamp + : exports.timestamp, + timestamp = options.timestamp ? timestampFn() : null, + showLevel = options.showLevel === undefined ? true : options.showLevel, + meta = options.meta !== null && options.meta !== undefined && !(options.meta instanceof Error) + ? exports.clone(cycle.decycle(options.meta)) + : options.meta || null, + output; + + // + // raw mode is intended for outputing winston as streaming JSON to STDOUT + // + if (options.raw) { + if (typeof meta !== 'object' && meta != null) { + meta = { meta: meta }; + } + output = exports.clone(meta) || {}; + output.level = options.level; + // + // Remark (jcrugzz): This used to be output.message = options.message.stripColors. + // I do not know why this is, it does not make sense but im handling that + // case here as well as handling the case that does make sense which is to + // make the `output.message = options.message` + // + output.message = options.message.stripColors + ? options.message.stripColors + : options.message; + + return JSON.stringify(output); + } + + // + // json mode is intended for pretty printing multi-line json to the terminal + // + if (options.json || true === options.logstash) { + if (typeof meta !== 'object' && meta != null) { + meta = { meta: meta }; + } + + output = exports.clone(meta) || {}; + output.level = options.level; + output.message = output.message || ''; + + if (options.label) { output.label = options.label; } + if (options.message) { output.message = options.message; } + if (timestamp) { output.timestamp = timestamp; } + + if (options.logstash === true) { + // use logstash format + var logstashOutput = {}; + if (output.message !== undefined) { + logstashOutput['@message'] = output.message; + delete output.message; + } + + if (output.timestamp !== undefined) { + logstashOutput['@timestamp'] = output.timestamp; + delete output.timestamp; + } + + logstashOutput['@fields'] = exports.clone(output); + output = logstashOutput; + } + + if (typeof options.stringify === 'function') { + return options.stringify(output); + } + + return JSON.stringify(output, function (key, value) { + return value instanceof Buffer + ? value.toString('base64') + : value; + }); + } + + // + // Remark: this should really be a call to `util.format`. + // + if (typeof options.formatter == 'function') { + return String(options.formatter(exports.clone(options))); + } + + output = timestamp ? timestamp + ' - ' : ''; + if (showLevel) { + output += options.colorize === 'all' || options.colorize === 'level' || options.colorize === true + ? config.colorize(options.level) + : options.level; + } + + output += (options.align) ? '\t' : ''; + output += (timestamp || showLevel) ? ': ' : ''; + output += options.label ? ('[' + options.label + '] ') : ''; + output += options.colorize === 'all' || options.colorize === 'message' + ? config.colorize(options.level, options.message) + : options.message; + + if (meta !== null && meta !== undefined) { + if (meta && meta instanceof Error && meta.stack) { + meta = meta.stack; + } + + if (typeof meta !== 'object') { + output += ' ' + meta; + } + else if (Object.keys(meta).length > 0) { + if (typeof options.prettyPrint === 'function') { + output += ' ' + options.prettyPrint(meta); + } else if (options.prettyPrint) { + output += ' ' + '\n' + util.inspect(meta, false, options.depth || null, options.colorize); + } else if ( + options.humanReadableUnhandledException + && Object.keys(meta).length === 5 + && meta.hasOwnProperty('date') + && meta.hasOwnProperty('process') + && meta.hasOwnProperty('os') + && meta.hasOwnProperty('trace') + && meta.hasOwnProperty('stack')) { + + // + // If meta carries unhandled exception data serialize the stack nicely + // + var stack = meta.stack; + delete meta.stack; + delete meta.trace; + output += ' ' + exports.serialize(meta); + output += '\n' + stack.join('\n'); + } else { + output += ' ' + exports.serialize(meta); + } + } + } + + return output; +}; + +exports.capitalize = function (str) { + return str && str[0].toUpperCase() + str.slice(1); +}; + +// +// ### function hash (str) +// #### @str {string} String to hash. +// Utility function for creating unique ids +// e.g. Profiling incoming HTTP requests on the same tick +// +exports.hash = function (str) { + return crypto.createHash('sha1').update(str).digest('hex'); +}; + +// +// ### function pad (n) +// Returns a padded string if `n < 10`. +// +exports.pad = function (n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +}; + +// +// ### function timestamp () +// Returns a timestamp string for the current time. +// +exports.timestamp = function () { + return new Date().toISOString(); +}; + +// +// ### function serialize (obj, key) +// #### @obj {Object|literal} Object to serialize +// #### @key {string} **Optional** Optional key represented by obj in a larger object +// Performs simple comma-separated, `key=value` serialization for Loggly when +// logging to non-JSON inputs. +// +exports.serialize = function (obj, key) { + if (obj === null) { + obj = 'null'; + } + else if (obj === undefined) { + obj = 'undefined'; + } + else if (obj === false) { + obj = 'false'; + } + + if (typeof obj !== 'object') { + return key ? key + '=' + obj : obj; + } + + if (obj instanceof Buffer) { + return key ? key + '=' + obj.toString('base64') : obj.toString('base64'); + } + + var msg = '', + keys = Object.keys(obj), + length = keys.length; + + for (var i = 0; i < length; i++) { + if (Array.isArray(obj[keys[i]])) { + msg += keys[i] + '=['; + + for (var j = 0, l = obj[keys[i]].length; j < l; j++) { + msg += exports.serialize(obj[keys[i]][j]); + if (j < l - 1) { + msg += ', '; + } + } + + msg += ']'; + } + else if (obj[keys[i]] instanceof Date) { + msg += keys[i] + '=' + obj[keys[i]]; + } + else { + msg += exports.serialize(obj[keys[i]], keys[i]); + } + + if (i < length - 1) { + msg += ', '; + } + } + + return msg; +}; + +// +// ### function tailFile (options, callback) +// #### @options {Object} Options for tail. +// #### @callback {function} Callback to execute on every line. +// `tail -f` a file. Options must include file. +// +exports.tailFile = function(options, callback) { + var buffer = new Buffer(64 * 1024) + , decode = new StringDecoder('utf8') + , stream = new Stream + , buff = '' + , pos = 0 + , row = 0; + + if (options.start === -1) { + delete options.start; + } + + stream.readable = true; + stream.destroy = function() { + stream.destroyed = true; + stream.emit('end'); + stream.emit('close'); + }; + + fs.open(options.file, 'a+', '0644', function(err, fd) { + if (err) { + if (!callback) { + stream.emit('error', err); + } else { + callback(err); + } + stream.destroy(); + return; + } + + (function read() { + if (stream.destroyed) { + fs.close(fd); + return; + } + + return fs.read(fd, buffer, 0, buffer.length, pos, function(err, bytes) { + if (err) { + if (!callback) { + stream.emit('error', err); + } else { + callback(err); + } + stream.destroy(); + return; + } + + if (!bytes) { + if (buff) { + if (options.start == null || row > options.start) { + if (!callback) { + stream.emit('line', buff); + } else { + callback(null, buff); + } + } + row++; + buff = ''; + } + return setTimeout(read, 1000); + } + + var data = decode.write(buffer.slice(0, bytes)); + + if (!callback) { + stream.emit('data', data); + } + + var data = (buff + data).split(/\n+/) + , l = data.length - 1 + , i = 0; + + for (; i < l; i++) { + if (options.start == null || row > options.start) { + if (!callback) { + stream.emit('line', data[i]); + } else { + callback(null, data[i]); + } + } + row++; + } + + buff = data[l]; + + pos += bytes; + + return read(); + }); + })(); + }); + + if (!callback) { + return stream; + } + + return stream.destroy; +}; + +// +// ### function stringArrayToSet (array) +// #### @strArray {Array} Array of Set-elements as strings. +// #### @errMsg {string} **Optional** Custom error message thrown on invalid input. +// Returns a Set-like object with strArray's elements as keys (each with the value true). +// +exports.stringArrayToSet = function (strArray, errMsg) { + if (typeof errMsg === 'undefined') { + errMsg = 'Cannot make set from Array with non-string elements'; + } + return strArray.reduce(function (set, el) { + if (!(typeof el === 'string' || el instanceof String)) { + throw new Error(errMsg); + } + set[el] = true; + return set; + }, Object.create(null)); +}; diff --git a/node_modules/winston/lib/winston/config.js b/node_modules/winston/lib/winston/config.js new file mode 100644 index 0000000..1bb52fd --- /dev/null +++ b/node_modules/winston/lib/winston/config.js @@ -0,0 +1,68 @@ +/* + * config.js: Default settings for all levels that winston knows about + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var colors = require('colors/safe'); + +// Fix colors not appearing in non-tty environments +colors.enabled = true; + +var config = exports, + allColors = exports.allColors = {}; + +config.addColors = function (colors) { + mixin(allColors, colors); +}; + +config.colorize = function (level, message) { + if (typeof message === 'undefined') message = level; + + var colorized = message; + if (allColors[level] instanceof Array) { + for (var i = 0, l = allColors[level].length; i < l; ++i) { + colorized = colors[allColors[level][i]](colorized); + } + } + else if (allColors[level].match(/\s/)) { + var colorArr = allColors[level].split(/\s+/); + for (var i = 0; i < colorArr.length; ++i) { + colorized = colors[colorArr[i]](colorized); + } + allColors[level] = colorArr; + } + else { + colorized = colors[allColors[level]](colorized); + } + + return colorized; +}; + +// +// Export config sets +// +config.cli = require('./config/cli-config'); +config.npm = require('./config/npm-config'); +config.syslog = require('./config/syslog-config'); + +// +// Add colors for pre-defined config sets +// +config.addColors(config.cli.colors); +config.addColors(config.npm.colors); +config.addColors(config.syslog.colors); + +function mixin (target) { + var args = Array.prototype.slice.call(arguments, 1); + + args.forEach(function (a) { + var keys = Object.keys(a); + for (var i = 0; i < keys.length; i++) { + target[keys[i]] = a[keys[i]]; + } + }); + return target; +}; diff --git a/node_modules/winston/lib/winston/config/cli-config.js b/node_modules/winston/lib/winston/config/cli-config.js new file mode 100644 index 0000000..764d2a8 --- /dev/null +++ b/node_modules/winston/lib/winston/config/cli-config.js @@ -0,0 +1,35 @@ +/* + * cli-config.js: Config that conform to commonly used CLI logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var cliConfig = exports; + +cliConfig.levels = { + error: 0, + warn: 1, + help: 2, + data: 3, + info: 4, + debug: 5, + prompt: 6, + verbose: 7, + input: 8, + silly: 9, +}; + +cliConfig.colors = { + error: 'red', + warn: 'yellow', + help: 'cyan', + data: 'grey', + info: 'green', + debug: 'blue', + prompt: 'grey', + verbose: 'cyan', + input: 'grey', + silly: 'magenta' +}; diff --git a/node_modules/winston/lib/winston/config/npm-config.js b/node_modules/winston/lib/winston/config/npm-config.js new file mode 100644 index 0000000..6402ab3 --- /dev/null +++ b/node_modules/winston/lib/winston/config/npm-config.js @@ -0,0 +1,27 @@ +/* + * npm-config.js: Config that conform to npm logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var npmConfig = exports; + +npmConfig.levels = { + error: 0, + warn: 1, + info: 2, + verbose: 3, + debug: 4, + silly: 5 +}; + +npmConfig.colors = { + error: 'red', + warn: 'yellow', + info: 'green', + verbose: 'cyan', + debug: 'blue', + silly: 'magenta' +}; diff --git a/node_modules/winston/lib/winston/config/syslog-config.js b/node_modules/winston/lib/winston/config/syslog-config.js new file mode 100644 index 0000000..67c6a09 --- /dev/null +++ b/node_modules/winston/lib/winston/config/syslog-config.js @@ -0,0 +1,31 @@ +/* + * syslog-config.js: Config that conform to syslog logging levels. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var syslogConfig = exports; + +syslogConfig.levels = { + emerg: 0, + alert: 1, + crit: 2, + error: 3, + warning: 4, + notice: 5, + info: 6, + debug: 7 +}; + +syslogConfig.colors = { + emerg: 'red', + alert: 'yellow', + crit: 'red', + error: 'red', + warning: 'red', + notice: 'yellow', + info: 'green', + debug: 'blue' +}; diff --git a/node_modules/winston/lib/winston/container.js b/node_modules/winston/lib/winston/container.js new file mode 100644 index 0000000..f5faaa7 --- /dev/null +++ b/node_modules/winston/lib/winston/container.js @@ -0,0 +1,127 @@ +/* + * container.js: Inversion of control container for winston logger instances + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var common = require('./common'), + winston = require('../winston'), + extend = require('util')._extend; + +// +// ### function Container (options) +// #### @options {Object} Default pass-thru options for Loggers +// Constructor function for the Container object responsible for managing +// a set of `winston.Logger` instances based on string ids. +// +var Container = exports.Container = function (options) { + this.loggers = {}; + this.options = options || {}; + this.default = { + transports: [ + new winston.transports.Console({ + level: 'silly', + colorize: false + }) + ] + } +}; + +// +// ### function get / add (id, options) +// #### @id {string} Id of the Logger to get +// #### @options {Object} **Optional** Options for the Logger instance +// Retreives a `winston.Logger` instance for the specified `id`. If +// an instance does not exist, one is created. +// +Container.prototype.get = Container.prototype.add = function (id, options) { + var self = this, + existing; + + if (!this.loggers[id]) { + // + // Remark: Simple shallow clone for configuration options in case we pass in + // instantiated protoypal objects + // + options = extend({}, options || this.options || this.default); + existing = options.transports || this.options.transports; + // + // Remark: Make sure if we have an array of transports we slice it to make copies + // of those references. + // + options.transports = existing ? existing.slice() : []; + + if (options.transports.length === 0 && (!options || !options['console'])) { + options.transports.push(this.default.transports[0]); + } + + Object.keys(options).forEach(function (key) { + if (key === 'transports') { + return; + } + + var name = common.capitalize(key); + + if (!winston.transports[name]) { + throw new Error('Cannot add unknown transport: ' + name); + } + + var namedOptions = options[key]; + namedOptions.id = id; + options.transports.push(new (winston.transports[name])(namedOptions)); + }); + + this.loggers[id] = new winston.Logger(options); + + this.loggers[id].on('close', function () { + self._delete(id); + }); + } + + return this.loggers[id]; +}; + +// +// ### function close (id) +// #### @id {string} **Optional** Id of the Logger instance to find +// Returns a boolean value indicating if this instance +// has a logger with the specified `id`. +// +Container.prototype.has = function (id) { + return !!this.loggers[id]; +}; + +// +// ### function close (id) +// #### @id {string} **Optional** Id of the Logger instance to close +// Closes a `Logger` instance with the specified `id` if it exists. +// If no `id` is supplied then all Loggers are closed. +// +Container.prototype.close = function (id) { + var self = this; + + function _close (id) { + if (!self.loggers[id]) { + return; + } + + self.loggers[id].close(); + self._delete(id); + } + + return id ? _close(id) : Object.keys(this.loggers).forEach(function (id) { + _close(id); + }); +}; + +// +// ### @private function _delete (id) +// #### @id {string} Id of the Logger instance to delete from container +// Deletes a `Logger` instance with the specified `id`. +// +Container.prototype._delete = function (id) { + delete this.loggers[id]; +} + diff --git a/node_modules/winston/lib/winston/exception.js b/node_modules/winston/lib/winston/exception.js new file mode 100644 index 0000000..22717dd --- /dev/null +++ b/node_modules/winston/lib/winston/exception.js @@ -0,0 +1,56 @@ +/* + * exception.js: Utility methods for gathing information about uncaughtExceptions. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var os = require('os'), + stackTrace = require('stack-trace'); + +var exception = exports; + +exception.getAllInfo = function (err) { + return { + date: new Date().toString(), + process: exception.getProcessInfo(), + os: exception.getOsInfo(), + trace: exception.getTrace(err), + stack: err.stack && err.stack.split('\n') + }; +}; + +exception.getProcessInfo = function () { + return { + pid: process.pid, + uid: process.getuid ? process.getuid() : null, + gid: process.getgid ? process.getgid() : null, + cwd: process.cwd(), + execPath: process.execPath, + version: process.version, + argv: process.argv, + memoryUsage: process.memoryUsage() + }; +}; + +exception.getOsInfo = function () { + return { + loadavg: os.loadavg(), + uptime: os.uptime() + }; +}; + +exception.getTrace = function (err) { + var trace = err ? stackTrace.parse(err) : stackTrace.get(); + return trace.map(function (site) { + return { + column: site.getColumnNumber(), + file: site.getFileName(), + function: site.getFunctionName(), + line: site.getLineNumber(), + method: site.getMethodName(), + native: site.isNative(), + } + }); +}; diff --git a/node_modules/winston/lib/winston/logger.js b/node_modules/winston/lib/winston/logger.js new file mode 100644 index 0000000..97fba64 --- /dev/null +++ b/node_modules/winston/lib/winston/logger.js @@ -0,0 +1,723 @@ +/* + * logger.js: Core logger object used by winston. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var events = require('events'), + util = require('util'), + async = require('async'), + config = require('./config'), + common = require('./common'), + exception = require('./exception'), + Stream = require('stream').Stream; + +const formatRegExp = /%[sdj%]/g; + +// +// ### function Logger (options) +// #### @options {Object} Options for this instance. +// Constructor function for the Logger object responsible +// for persisting log messages and metadata to one or more transports. +// +var Logger = exports.Logger = function (options) { + events.EventEmitter.call(this); + this.configure(options); +}; + +// +// Inherit from `events.EventEmitter`. +// +util.inherits(Logger, events.EventEmitter); + +// +// ### function configure (options) +// This will wholesale reconfigure this instance by: +// 1. Resetting all transports. Older transports will be removed implicitly. +// 2. Set all other options including levels, colors, rewriters, filters, +// exceptionHandlers, etc. +// +Logger.prototype.configure = function (options) { + var self = this; + + // + // If we have already been setup with transports + // then remove them before proceeding. + // + if (Array.isArray(this._names) && this._names.length) { + this.clear(); + } + + options = options || {}; + this.transports = {}; + this._names = []; + + if (options.transports) { + options.transports.forEach(function (transport) { + self.add(transport, null, true); + }); + } + + // + // Set Levels and default logging level + // + this.padLevels = options.padLevels || false; + this.setLevels(options.levels); + if (options.colors) { + config.addColors(options.colors); + } + + // + // Hoist other options onto this instance. + // + this.level = options.level || 'info'; + this.emitErrs = options.emitErrs || false; + this.stripColors = options.stripColors || false; + this.exitOnError = typeof options.exitOnError !== 'undefined' + ? options.exitOnError + : true; + + // + // Setup internal state as empty Objects even though it is + // defined lazily later to ensure a strong existential API contract. + // + this.exceptionHandlers = {}; + this.profilers = {}; + + ['rewriters', 'filters'].forEach(function (kind) { + self[kind] = Array.isArray(options[kind]) + ? options[kind] + : []; + }); + + if (options.exceptionHandlers) { + this.handleExceptions(options.exceptionHandlers); + } +}; + +// +// ### function log (level, msg, [meta], callback) +// #### @level {string} Level at which to log the message. +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Core logging method exposed to Winston. Metadata is optional. +// +Logger.prototype.log = function (level) { + var args = Array.prototype.slice.call(arguments, 1), + self = this, + transports; + + while (args[args.length - 1] === null) { + args.pop(); + } + + // + // Determining what is `meta` and what are arguments for string interpolation + // turns out to be VERY tricky. e.g. in the cases like this: + // + // logger.info('No interpolation symbols', 'ok', 'why', { meta: 'is-this' }); + // + var callback = typeof args[args.length - 1] === 'function' + ? args.pop() + : null; + + // + // Handle errors appropriately. + // + function onError(err) { + if (callback) { + callback(err); + } + else if (self.emitErrs) { + self.emit('error', err); + } + } + + if (this._names.length === 0) { + return onError(new Error('Cannot log with no transports.')); + } + else if (typeof self.levels[level] === 'undefined') { + return onError(new Error('Unknown log level: ' + level)); + } + + // + // If there are no transports that match the level + // then be eager and return. This could potentially be calculated + // during `setLevels` for more performance gains. + // + var targets = this._names.filter(function (name) { + var transport = self.transports[name]; + return (transport.level && self.levels[transport.level] >= self.levels[level]) + || (!transport.level && self.levels[self.level] >= self.levels[level]); + }); + + if (!targets.length) { + if (callback) { callback(); } + return; + } + + // + // Determining what is `meta` and what are arguments for string interpolation + // turns out to be VERY tricky. e.g. in the cases like this: + // + // logger.info('No interpolation symbols', 'ok', 'why', { meta: 'is-this' }); + // + var metaType = Object.prototype.toString.call(args[args.length - 1]), + fmtMatch = args[0] && args[0].match && args[0].match(formatRegExp), + isFormat = fmtMatch && fmtMatch.length, + validMeta = !isFormat + ? metaType === '[object Object]' || metaType === '[object Error]' || metaType === '[object Array]' + : metaType === '[object Object]', + meta = validMeta ? args.pop() : {}, + msg = util.format.apply(null, args); + + // + // Respond to the callback. + // + function finish(err) { + if (callback) { + if (err) return callback(err); + callback(null, level, msg, meta); + } + + callback = null; + if (!err) { + self.emit('logged', level, msg, meta); + } + } + + // If we should pad for levels, do so + if (this.padLevels) { + msg = new Array(this.levelLength - level.length + 1).join(' ') + msg; + } + + this.rewriters.forEach(function (rewriter) { + meta = rewriter(level, msg, meta, self); + }); + + this.filters.forEach(function(filter) { + var filtered = filter(level, msg, meta, self); + if (typeof filtered === 'string') + msg = filtered; + else { + msg = filtered.msg; + meta = filtered.meta; + } + }); + + // + // For consideration of terminal 'color" programs like colors.js, + // which can add ANSI escape color codes to strings, we destyle the + // ANSI color escape codes when `this.stripColors` is set. + // + // see: http://en.wikipedia.org/wiki/ANSI_escape_code + // + if (this.stripColors) { + var code = /\u001b\[(\d+(;\d+)*)?m/g; + msg = ('' + msg).replace(code, ''); + } + + // + // Log for each transport and emit 'logging' event + // + function transportLog(name, next) { + var transport = self.transports[name]; + transport.log(level, msg, meta, function (err) { + if (err) { + err.transport = transport; + finish(err); + return next(); + } + + self.emit('logging', transport, level, msg, meta); + next(); + }); + } + + async.forEach(targets, transportLog, finish); + return this; +}; + +// +// ### function query (options, callback) +// #### @options {Object} Query options for this instance. +// #### @callback {function} Continuation to respond to when complete. +// Queries the all transports for this instance with the specified `options`. +// This will aggregate each transport's results into one object containing +// a property per transport. +// +Logger.prototype.query = function (options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var self = this, + options = options || {}, + results = {}, + query = common.clone(options.query) || {}, + transports; + + // + // Helper function to query a single transport + // + function queryTransport(transport, next) { + if (options.query) { + options.query = transport.formatQuery(query); + } + + transport.query(options, function (err, results) { + if (err) { + return next(err); + } + + next(null, transport.formatResults(results, options.format)); + }); + } + + // + // Helper function to accumulate the results from + // `queryTransport` into the `results`. + // + function addResults(transport, next) { + queryTransport(transport, function (err, result) { + // + // queryTransport could potentially invoke the callback + // multiple times since Transport code can be unpredictable. + // + if (next) { + result = err || result; + if (result) { + results[transport.name] = result; + } + + next(); + } + + next = null; + }); + } + + // + // If an explicit transport is being queried then + // respond with the results from only that transport + // + if (options.transport) { + options.transport = options.transport.toLowerCase(); + return queryTransport(this.transports[options.transport], callback); + } + + // + // Create a list of all transports for this instance. + // + transports = this._names.map(function (name) { + return self.transports[name]; + }).filter(function (transport) { + return !!transport.query; + }); + + // + // Iterate over the transports in parallel setting the + // appropriate key in the `results` + // + async.forEach(transports, addResults, function () { + callback(null, results); + }); +}; + +// +// ### function stream (options) +// #### @options {Object} Stream options for this instance. +// Returns a log stream for all transports. Options object is optional. +// +Logger.prototype.stream = function (options) { + var self = this, + options = options || {}, + out = new Stream, + streams = [], + transports; + + if (options.transport) { + var transport = this.transports[options.transport]; + delete options.transport; + if (transport && transport.stream) { + return transport.stream(options); + } + } + + out._streams = streams; + out.destroy = function () { + var i = streams.length; + while (i--) streams[i].destroy(); + }; + + // + // Create a list of all transports for this instance. + // + transports = this._names.map(function (name) { + return self.transports[name]; + }).filter(function (transport) { + return !!transport.stream; + }); + + transports.forEach(function (transport) { + var stream = transport.stream(options); + if (!stream) return; + + streams.push(stream); + + stream.on('log', function (log) { + log.transport = log.transport || []; + log.transport.push(transport.name); + out.emit('log', log); + }); + + stream.on('error', function (err) { + err.transport = err.transport || []; + err.transport.push(transport.name); + out.emit('error', err); + }); + }); + + return out; +}; + +// +// ### function close () +// Cleans up resources (streams, event listeners) for all +// transports associated with this instance (if necessary). +// +Logger.prototype.close = function () { + var self = this; + + this._names.forEach(function (name) { + var transport = self.transports[name]; + if (transport && transport.close) { + transport.close(); + } + }); + + this.emit('close'); +}; + +// +// ### function handleExceptions ([tr0, tr1...] || tr0, tr1, ...) +// Handles `uncaughtException` events for the current process by +// ADDING any handlers passed in. +// +Logger.prototype.handleExceptions = function () { + var args = Array.prototype.slice.call(arguments), + handlers = [], + self = this; + + args.forEach(function (a) { + if (Array.isArray(a)) { + handlers = handlers.concat(a); + } + else { + handlers.push(a); + } + }); + + this.exceptionHandlers = this.exceptionHandlers || {}; + handlers.forEach(function (handler) { + self.exceptionHandlers[handler.name] = handler; + }); + + this._hnames = Object.keys(self.exceptionHandlers); + + if (!this.catchExceptions) { + this.catchExceptions = this._uncaughtException.bind(this); + process.on('uncaughtException', this.catchExceptions); + } +}; + +// +// ### function unhandleExceptions () +// Removes any handlers to `uncaughtException` events +// for the current process +// +Logger.prototype.unhandleExceptions = function () { + var self = this; + + if (this.catchExceptions) { + Object.keys(this.exceptionHandlers).forEach(function (name) { + var handler = self.exceptionHandlers[name]; + if (handler.close) { + handler.close(); + } + }); + + this.exceptionHandlers = {}; + Object.keys(this.transports).forEach(function (name) { + var transport = self.transports[name]; + if (transport.handleExceptions) { + transport.handleExceptions = false; + } + }) + + process.removeListener('uncaughtException', this.catchExceptions); + this.catchExceptions = false; + } +}; + +// +// ### function add (transport, [options]) +// #### @transport {Transport} Prototype of the Transport object to add. +// #### @options {Object} **Optional** Options for the Transport to add. +// #### @instance {Boolean} **Optional** Value indicating if `transport` is already instantiated. +// Adds a transport of the specified type to this instance. +// +Logger.prototype.add = function (transport, options, created) { + var instance = created ? transport : (new (transport)(options)); + + if (!instance.name && !instance.log) { + throw new Error('Unknown transport with no log() method'); + } + else if (this.transports[instance.name]) { + throw new Error('Transport already attached: ' + instance.name); + } + + this.transports[instance.name] = instance; + this._names = Object.keys(this.transports); + + // + // Listen for the `error` event on the new Transport + // + instance._onError = this._onError.bind(this, instance) + if (!created) { + instance.on('error', instance._onError); + } + + // + // If this transport has `handleExceptions` set to `true` + // and we are not already handling exceptions, do so. + // + if (instance.handleExceptions && !this.catchExceptions) { + this.handleExceptions(); + } + + return this; +}; + +// +// ### function clear () +// Remove all transports from this instance +// +Logger.prototype.clear = function () { + Object.keys(this.transports).forEach(function (name) { + this.remove({ name: name }); + }, this); +}; + +// +// ### function remove (transport) +// #### @transport {Transport|String} Transport or Name to remove. +// Removes a transport of the specified type from this instance. +// +Logger.prototype.remove = function (transport) { + var name = typeof transport !== 'string' + ? transport.name || transport.prototype.name + : transport; + + if (!this.transports[name]) { + throw new Error('Transport ' + name + ' not attached to this instance'); + } + + var instance = this.transports[name]; + delete this.transports[name]; + this._names = Object.keys(this.transports); + + if (instance.close) { + instance.close(); + } + + if (instance._onError) { + instance.removeListener('error', instance._onError); + } + return this; +}; + +// +// ### function startTimer () +// Returns an object corresponding to a specific timing. When done +// is called the timer will finish and log the duration. e.g.: +// +// timer = winston.startTimer() +// setTimeout(function(){ +// timer.done("Logging message"); +// }, 1000); +// +Logger.prototype.startTimer = function () { + return new ProfileHandler(this); +}; + +// +// ### function profile (id, [msg, meta, callback]) +// #### @id {string} Unique id of the profiler +// #### @msg {string} **Optional** Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} **Optional** Continuation to respond to when complete. +// Tracks the time inbetween subsequent calls to this method +// with the same `id` parameter. The second call to this method +// will log the difference in milliseconds along with the message. +// +Logger.prototype.profile = function (id) { + var now = Date.now(), then, args, + msg, meta, callback; + + if (this.profilers[id]) { + then = this.profilers[id]; + delete this.profilers[id]; + + // Support variable arguments: msg, meta, callback + args = Array.prototype.slice.call(arguments); + callback = typeof args[args.length - 1] === 'function' ? args.pop() : null; + meta = typeof args[args.length - 1] === 'object' ? args.pop() : {}; + msg = args.length === 2 ? args[1] : id; + + // Set the duration property of the metadata + meta.durationMs = now - then; + return this.info(msg, meta, callback); + } + else { + this.profilers[id] = now; + } + + return this; +}; + +// +// ### function setLevels (target) +// #### @target {Object} Target levels to use on this instance +// Sets the `target` levels specified on this instance. +// +Logger.prototype.setLevels = function (target) { + return common.setLevels(this, this.levels, target); +}; + +// +// ### function cli () +// Configures this instance to have the default +// settings for command-line interfaces: no timestamp, +// colors enabled, padded output, and additional levels. +// +Logger.prototype.cli = function () { + this.padLevels = true; + this.setLevels(config.cli.levels); + config.addColors(config.cli.colors); + + if (this.transports.console) { + this.transports.console.colorize = this.transports.console.colorize || true; + this.transports.console.timestamp = this.transports.console.timestamp || false; + } + + return this; +}; + +// +// ### @private function _uncaughtException (err) +// #### @err {Error} Error to handle +// Logs all relevant information around the `err` and +// exits the current process. +// +Logger.prototype._uncaughtException = function (err) { + var self = this, + responded = false, + info = exception.getAllInfo(err), + handlers = this._getExceptionHandlers(), + timeout, + doExit; + + // + // Calculate if we should exit on this error + // + doExit = typeof this.exitOnError === 'function' + ? this.exitOnError(err) + : this.exitOnError; + + function logAndWait(transport, next) { + transport.logException('uncaughtException: ' + (err.message || err), info, next, err); + } + + function gracefulExit() { + if (doExit && !responded) { + // + // Remark: Currently ignoring any exceptions from transports + // when catching uncaught exceptions. + // + clearTimeout(timeout); + responded = true; + process.exit(1); + } + } + + if (!handlers || handlers.length === 0) { + return gracefulExit(); + } + + // + // Log to all transports and allow the operation to take + // only up to `3000ms`. + // + async.forEach(handlers, logAndWait, gracefulExit); + if (doExit) { + timeout = setTimeout(gracefulExit, 3000); + } +}; + +// +// ### @private function _getExceptionHandlers () +// Returns the list of transports and exceptionHandlers +// for this instance. +// +Logger.prototype._getExceptionHandlers = function () { + var self = this; + + return this._hnames.map(function (name) { + return self.exceptionHandlers[name]; + }).concat(this._names.map(function (name) { + return self.transports[name].handleExceptions && self.transports[name]; + })).filter(Boolean); +}; + +// +// ### @private function _onError (transport, err) +// #### @transport {Object} Transport on which the error occured +// #### @err {Error} Error that occurred on the transport +// Bubbles the error, `err`, that occured on the specified `transport` +// up from this instance if `emitErrs` has been set. +// +Logger.prototype._onError = function (transport, err) { + if (this.emitErrs) { + this.emit('error', err, transport); + } +}; + +// +// ### @private ProfileHandler +// Constructor function for the ProfileHandler instance used by +// `Logger.prototype.startTimer`. When done is called the timer +// will finish and log the duration. +// +function ProfileHandler(logger) { + this.logger = logger; + this.start = Date.now(); +} + +// +// ### function done (msg) +// Ends the current timer (i.e. ProfileHandler) instance and +// logs the `msg` along with the duration since creation. +// +ProfileHandler.prototype.done = function (msg) { + var args = Array.prototype.slice.call(arguments), + callback = typeof args[args.length - 1] === 'function' ? args.pop() : null, + meta = typeof args[args.length - 1] === 'object' ? args.pop() : {}; + + meta.duration = (Date.now()) - this.start + 'ms'; + return this.logger.info(msg, meta, callback); +}; diff --git a/node_modules/winston/lib/winston/transports.js b/node_modules/winston/lib/winston/transports.js new file mode 100644 index 0000000..34f800e --- /dev/null +++ b/node_modules/winston/lib/winston/transports.js @@ -0,0 +1,29 @@ +/* + * transports.js: Set of all transports Winston knows about + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var path = require('path'); + +// +// Setup all transports as lazy-loaded getters. +// +Object.defineProperties( + exports, + ['Console', 'File', 'Http', 'Memory'] + .reduce(function (acc, name) { + acc[name] = { + configurable: true, + enumerable: true, + get: function () { + var fullpath = path.join(__dirname, 'transports', name.toLowerCase()); + return exports[name] = require(fullpath)[name]; + } + }; + + return acc; + }, {}) +); diff --git a/node_modules/winston/lib/winston/transports/console.js b/node_modules/winston/lib/winston/transports/console.js new file mode 100644 index 0000000..f573e17 --- /dev/null +++ b/node_modules/winston/lib/winston/transports/console.js @@ -0,0 +1,130 @@ +/* + * console.js: Transport for outputting to the console + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var events = require('events'), + os = require('os'), + util = require('util'), + common = require('../common'), + Transport = require('./transport').Transport; + +// +// ### function Console (options) +// #### @options {Object} Options for this instance. +// Constructor function for the Console transport object responsible +// for persisting log messages and metadata to a terminal or TTY. +// +var Console = exports.Console = function (options) { + Transport.call(this, options); + options = options || {}; + + this.json = options.json || false; + this.colorize = options.colorize || false; + this.prettyPrint = options.prettyPrint || false; + this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false; + this.showLevel = options.showLevel === undefined ? true : options.showLevel; + this.label = options.label || null; + this.logstash = options.logstash || false; + this.depth = options.depth || null; + this.align = options.align || false; + this.stderrLevels = setStderrLevels(options.stderrLevels, options.debugStdout); + this.eol = options.eol || os.EOL; + + if (this.json) { + this.stringify = options.stringify || function (obj) { + return JSON.stringify(obj, null, 2); + }; + } + + // + // Convert stderrLevels into an Object for faster key-lookup times than an Array. + // + // For backwards compatibility, stderrLevels defaults to ['error', 'debug'] + // or ['error'] depending on whether options.debugStdout is true. + // + function setStderrLevels (levels, debugStdout) { + var defaultMsg = 'Cannot have non-string elements in stderrLevels Array'; + if (debugStdout) { + if (levels) { + // + // Don't allow setting both debugStdout and stderrLevels together, + // since this could cause behaviour a programmer might not expect. + // + throw new Error('Cannot set debugStdout and stderrLevels together'); + } + + return common.stringArrayToSet(['error'], defaultMsg); + } + + if (!levels) { + return common.stringArrayToSet(['error', 'debug'], defaultMsg); + } else if (!(Array.isArray(levels))) { + throw new Error('Cannot set stderrLevels to type other than Array'); + } + + return common.stringArrayToSet(levels, defaultMsg); + }; +}; + +// +// Inherit from `winston.Transport`. +// +util.inherits(Console, Transport); + +// +// Expose the name of this Transport on the prototype +// +Console.prototype.name = 'console'; + +// +// ### function log (level, msg, [meta], callback) +// #### @level {string} Level at which to log the message. +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Core logging method exposed to Winston. Metadata is optional. +// +Console.prototype.log = function (level, msg, meta, callback) { + if (this.silent) { + return callback(null, true); + } + + var self = this, + output; + + output = common.log({ + colorize: this.colorize, + json: this.json, + level: level, + message: msg, + meta: meta, + stringify: this.stringify, + timestamp: this.timestamp, + showLevel: this.showLevel, + prettyPrint: this.prettyPrint, + raw: this.raw, + label: this.label, + logstash: this.logstash, + depth: this.depth, + formatter: this.formatter, + align: this.align, + humanReadableUnhandledException: this.humanReadableUnhandledException + }); + + if (this.stderrLevels[level]) { + process.stderr.write(output + '\n'); + } else { + process.stdout.write(output + this.eol); + } + + // + // Emit the `logged` event immediately because the event loop + // will not exit until `process.stdout` has drained anyway. + // + self.emit('logged'); + callback(null, true); +}; diff --git a/node_modules/winston/lib/winston/transports/file.js b/node_modules/winston/lib/winston/transports/file.js new file mode 100644 index 0000000..b3df4b5 --- /dev/null +++ b/node_modules/winston/lib/winston/transports/file.js @@ -0,0 +1,678 @@ +/* + * file.js: Transport for outputting to a local log file + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var events = require('events'), + fs = require('fs'), + path = require('path'), + util = require('util'), + async = require('async'), + zlib = require('zlib'), + common = require('../common'), + Transport = require('./transport').Transport, + isWritable = require('isstream').isWritable, + Stream = require('stream').Stream, + os = require('os'); + +// +// ### function File (options) +// #### @options {Object} Options for this instance. +// Constructor function for the File transport object responsible +// for persisting log messages and metadata to one or more files. +// +var File = exports.File = function (options) { + var self = this; + Transport.call(this, options); + + // + // Helper function which throws an `Error` in the event + // that any of the rest of the arguments is present in `options`. + // + function throwIf (target /*, illegal... */) { + Array.prototype.slice.call(arguments, 1).forEach(function (name) { + if (options[name]) { + throw new Error('Cannot set ' + name + ' and ' + target + 'together'); + } + }); + } + + if (options.filename || options.dirname) { + throwIf('filename or dirname', 'stream'); + this._basename = this.filename = options.filename + ? path.basename(options.filename) + : 'winston.log'; + + this.dirname = options.dirname || path.dirname(options.filename); + this.options = options.options || { flags: 'a' }; + + // + // "24 bytes" is maybe a good value for logging lines. + // + this.options.highWaterMark = this.options.highWaterMark || 24; + } + else if (options.stream) { + throwIf('stream', 'filename', 'maxsize'); + this._stream = options.stream; + this._isStreams2 = isWritable(this._stream); + this._stream.on('error', function(error){ + self.emit('error', error); + }); + // + // We need to listen for drain events when + // write() returns false. This can make node + // mad at times. + // + this._stream.setMaxListeners(Infinity); + } + else { + throw new Error('Cannot log to file without filename or stream.'); + } + + this.json = options.json !== false; + this.logstash = options.logstash || false; + this.colorize = options.colorize || false; + this.maxsize = options.maxsize || null; + this.rotationFormat = options.rotationFormat || false; + this.zippedArchive = options.zippedArchive || false; + this.maxFiles = options.maxFiles || null; + this.prettyPrint = options.prettyPrint || false; + this.label = options.label || null; + this.timestamp = options.timestamp != null ? options.timestamp : true; + this.eol = options.eol || os.EOL; + this.tailable = options.tailable || false; + this.depth = options.depth || null; + this.showLevel = options.showLevel === undefined ? true : options.showLevel; + this.maxRetries = options.maxRetries || 2; + + if (this.json) { + this.stringify = options.stringify; + } + + // + // Internal state variables representing the number + // of files this instance has created and the current + // size (in bytes) of the current logfile. + // + this._size = 0; + this._created = 0; + this._buffer = []; + this._draining = false; + this._opening = false; + this._failures = 0; + this._archive = null; +}; + +// +// Inherit from `winston.Transport`. +// +util.inherits(File, Transport); + +// +// Expose the name of this Transport on the prototype +// +File.prototype.name = 'file'; + +// +// ### function log (level, msg, [meta], callback) +// #### @level {string} Level at which to log the message. +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Core logging method exposed to Winston. Metadata is optional. +// +File.prototype.log = function (level, msg, meta, callback) { + if (this.silent) { + return callback(null, true); + } + + // + // If failures exceeds maxRetries then we can't access the + // stream. In this case we need to perform a noop and return + // an error. + // + if (this._failures >= this.maxRetries) { + return callback(new Error('Transport is in a failed state.')); + } + + var self = this; + + if (typeof msg !== 'string') { + msg = '' + msg; + } + + var output = common.log({ + level: level, + message: msg, + meta: meta, + json: this.json, + logstash: this.logstash, + colorize: this.colorize, + prettyPrint: this.prettyPrint, + timestamp: this.timestamp, + showLevel: this.showLevel, + stringify: this.stringify, + label: this.label, + depth: this.depth, + formatter: this.formatter, + humanReadableUnhandledException: this.humanReadableUnhandledException + }); + + if (typeof output === 'string') { + output += this.eol; + } + + if (!this.filename) { + // + // If there is no `filename` on this instance then it was configured + // with a raw `WriteableStream` instance and we should not perform any + // size restrictions. + // + this._write(output, callback); + this._size += output.length; + this._lazyDrain(); + } + else { + this.open(function (err) { + if (err) { + // + // If there was an error enqueue the message + // + return self._buffer.push([output, callback]); + } + + self._write(output, callback); + self._size += output.length; + self._lazyDrain(); + }); + } +}; + +// +// ### function _write (data, cb) +// #### @data {String|Buffer} Data to write to the instance's stream. +// #### @cb {function} Continuation to respond to when complete. +// Write to the stream, ensure execution of a callback on completion. +// +File.prototype._write = function(data, callback) { + if (this._isStreams2) { + this._stream.write(data); + return callback && process.nextTick(function () { + callback(null, true); + }); + } + + // If this is a file write stream, we could use the builtin + // callback functionality, however, the stream is not guaranteed + // to be an fs.WriteStream. + var ret = this._stream.write(data); + if (!callback) return; + if (ret === false) { + return this._stream.once('drain', function() { + callback(null, true); + }); + } + process.nextTick(function () { + callback(null, true); + }); +}; + +// +// ### function query (options, callback) +// #### @options {Object} Loggly-like query options for this instance. +// #### @callback {function} Continuation to respond to when complete. +// Query the transport. Options object is optional. +// +File.prototype.query = function (options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var file = path.join(this.dirname, this.filename), + options = this.normalizeQuery(options), + buff = '', + results = [], + row = 0; + + var stream = fs.createReadStream(file, { + encoding: 'utf8' + }); + + stream.on('error', function (err) { + if (stream.readable) { + stream.destroy(); + } + if (!callback) return; + return err.code !== 'ENOENT' + ? callback(err) + : callback(null, results); + }); + + stream.on('data', function (data) { + var data = (buff + data).split(/\n+/), + l = data.length - 1, + i = 0; + + for (; i < l; i++) { + if (!options.start || row >= options.start) { + add(data[i]); + } + row++; + } + + buff = data[l]; + }); + + stream.on('close', function () { + if (buff) add(buff, true); + if (options.order === 'desc') { + results = results.reverse(); + } + if (callback) callback(null, results); + }); + + function add(buff, attempt) { + try { + var log = JSON.parse(buff); + if (check(log)) push(log); + } catch (e) { + if (!attempt) { + stream.emit('error', e); + } + } + } + + function push(log) { + if (options.rows && results.length >= options.rows) { + if (stream.readable) { + stream.destroy(); + } + return; + } + + if (options.fields) { + var obj = {}; + options.fields.forEach(function (key) { + obj[key] = log[key]; + }); + log = obj; + } + + results.push(log); + } + + function check(log) { + if (!log) return; + + if (typeof log !== 'object') return; + + var time = new Date(log.timestamp); + if ((options.from && time < options.from) + || (options.until && time > options.until)) { + return; + } + + return true; + } +}; + +// +// ### function stream (options) +// #### @options {Object} Stream options for this instance. +// Returns a log stream for this transport. Options object is optional. +// +File.prototype.stream = function (options) { + var file = path.join(this.dirname, this.filename), + options = options || {}, + stream = new Stream; + + var tail = { + file: file, + start: options.start + }; + + stream.destroy = common.tailFile(tail, function (err, line) { + + if(err){ + return stream.emit('error',err); + } + + try { + stream.emit('data', line); + line = JSON.parse(line); + stream.emit('log', line); + } catch (e) { + stream.emit('error', e); + } + }); + + return stream; +}; + +// +// ### function open (callback) +// #### @callback {function} Continuation to respond to when complete +// Checks to see if a new file needs to be created based on the `maxsize` +// (if any) and the current size of the file used. +// +File.prototype.open = function (callback) { + if (this.opening) { + // + // If we are already attempting to open the next + // available file then respond with a value indicating + // that the message should be buffered. + // + return callback(true); + } + else if (!this._stream || (this.maxsize && this._size >= this.maxsize)) { + // + // If we dont have a stream or have exceeded our size, then create + // the next stream and respond with a value indicating that + // the message should be buffered. + // + callback(true); + return this._createStream(); + } + + this._archive = this.zippedArchive ? this._stream.path : null; + + // + // Otherwise we have a valid (and ready) stream. + // + callback(); +}; + +// +// ### function close () +// Closes the stream associated with this instance. +// +File.prototype.close = function () { + var self = this; + + if (this._stream) { + this._stream.end(); + this._stream.destroySoon(); + + this._stream.once('finish', function () { + self.emit('flush'); + self.emit('closed'); + }); + } +}; + +// +// ### function flush () +// Flushes any buffered messages to the current `stream` +// used by this instance. +// +File.prototype.flush = function () { + var self = this; + + // If nothing to flush, there will be no "flush" event from native stream + // Thus, the "open" event will never be fired (see _createStream.createAndFlush function) + // That means, self.opening will never set to false and no logs will be written to disk + if (!this._buffer.length) { + return self.emit('flush'); + } + + // + // Iterate over the `_buffer` of enqueued messaged + // and then write them to the newly created stream. + // + this._buffer.forEach(function (item) { + var str = item[0], + callback = item[1]; + + process.nextTick(function () { + self._write(str, callback); + self._size += str.length; + }); + }); + + // + // Quickly truncate the `_buffer` once the write operations + // have been started + // + self._buffer.length = 0; + + // + // When the stream has drained we have flushed + // our buffer. + // + self._stream.once('drain', function () { + self.emit('flush'); + self.emit('logged'); + }); +}; + +// +// ### @private function _createStream () +// Attempts to open the next appropriate file for this instance +// based on the common state (such as `maxsize` and `_basename`). +// +File.prototype._createStream = function () { + var self = this; + this.opening = true; + + (function checkFile (target) { + var fullname = path.join(self.dirname, target); + + // + // Creates the `WriteStream` and then flushes any + // buffered messages. + // + function createAndFlush (size) { + if (self._stream) { + self._stream.end(); + self._stream.destroySoon(); + } + + self._size = size; + self.filename = target; + self._stream = fs.createWriteStream(fullname, self.options); + self._isStreams2 = isWritable(self._stream); + self._stream.on('error', function(error){ + if (self._failures < self.maxRetries) { + self._createStream(); + self._failures++; + } + else { + self.emit('error', error); + } + }); + // + // We need to listen for drain events when + // write() returns false. This can make node + // mad at times. + // + self._stream.setMaxListeners(Infinity); + + // + // When the current stream has finished flushing + // then we can be sure we have finished opening + // and thus can emit the `open` event. + // + self.once('flush', function () { + // Because "flush" event is based on native stream "drain" event, + // logs could be written inbetween "self.flush()" and here + // Therefore, we need to flush again to make sure everything is flushed + self.flush(); + + self.opening = false; + self.emit('open', fullname); + }); + // + // Remark: It is possible that in the time it has taken to find the + // next logfile to be written more data than `maxsize` has been buffered, + // but for sensible limits (10s - 100s of MB) this seems unlikely in less + // than one second. + // + self.flush(); + compressFile(); + } + + function compressFile() { + if (self._archive) { + var gzip = zlib.createGzip(); + + var inp = fs.createReadStream(String(self._archive)); + var out = fs.createWriteStream(self._archive + '.gz'); + + inp.pipe(gzip).pipe(out); + + fs.unlink(String(self._archive)); + self._archive = ''; + } + } + + fs.stat(fullname, function (err, stats) { + if (err) { + if (err.code !== 'ENOENT') { + return self.emit('error', err); + } + return createAndFlush(0); + } + + if (!stats || (self.maxsize && stats.size >= self.maxsize)) { + // + // If `stats.size` is greater than the `maxsize` for + // this instance then try again + // + return self._incFile(function() { + checkFile(self._getFile()); + }); + } + + createAndFlush(stats.size); + }); + })(this._getFile()); +}; + + +File.prototype._incFile = function (callback) { + var ext = path.extname(this._basename), + basename = path.basename(this._basename, ext), + oldest, + target; + + if (!this.tailable) { + this._created += 1; + this._checkMaxFilesIncrementing(ext, basename, callback); + } + else { + this._checkMaxFilesTailable(ext, basename, callback); + } +}; + +// +// ### @private function _getFile () +// Gets the next filename to use for this instance +// in the case that log filesizes are being capped. +// +File.prototype._getFile = function () { + var ext = path.extname(this._basename), + basename = path.basename(this._basename, ext); + + // + // Caveat emptor (indexzero): rotationFormat() was broken by design + // when combined with max files because the set of files to unlink + // is never stored. + // + return !this.tailable && this._created + ? basename + (this.rotationFormat ? this.rotationFormat() : this._created) + ext + : basename + ext; +}; + +// +// ### @private function _checkMaxFilesIncrementing () +// Increment the number of files created or +// checked by this instance. +// +File.prototype._checkMaxFilesIncrementing = function (ext, basename, callback) { + var oldest, target, + self = this; + + if (self.zippedArchive) { + self._archive = path.join(self.dirname, basename + + ((self._created === 1) ? '' : self._created-1) + + ext); + } + + + // Check for maxFiles option and delete file + if (!self.maxFiles || self._created < self.maxFiles) { + return callback(); + } + + oldest = self._created - self.maxFiles; + target = path.join(self.dirname, basename + (oldest !== 0 ? oldest : '') + ext + + (self.zippedArchive ? '.gz' : '')); + fs.unlink(target, callback); +}; + +// +// ### @private function _checkMaxFilesTailable () +// +// Roll files forward based on integer, up to maxFiles. +// e.g. if base if file.log and it becomes oversized, roll +// to file1.log, and allow file.log to be re-used. If +// file is oversized again, roll file1.log to file2.log, +// roll file.log to file1.log, and so on. +File.prototype._checkMaxFilesTailable = function (ext, basename, callback) { + var tasks = [], + self = this; + + if (!this.maxFiles) + return; + + for (var x = this.maxFiles - 1; x > 0; x--) { + tasks.push(function (i) { + return function (cb) { + var tmppath = path.join(self.dirname, basename + (i - 1) + ext + + (self.zippedArchive ? '.gz' : '')); + fs.exists(tmppath, function (exists) { + if (!exists) { + return cb(null); + } + + fs.rename(tmppath, path.join(self.dirname, basename + i + ext + + (self.zippedArchive ? '.gz' : '')), cb); + }); + }; + }(x)); + } + + if (self.zippedArchive) { + self._archive = path.join(self.dirname, basename + 1 + ext); + } + async.series(tasks, function (err) { + fs.rename( + path.join(self.dirname, basename + ext), + path.join(self.dirname, basename + 1 + ext), + callback + ); + }); +}; + +// +// ### @private function _lazyDrain () +// Lazily attempts to emit the `logged` event when `this.stream` has +// drained. This is really just a simple mutex that only works because +// Node.js is single-threaded. +// +File.prototype._lazyDrain = function () { + var self = this; + + if (!this._draining && this._stream) { + this._draining = true; + + this._stream.once('drain', function () { + this._draining = false; + self.emit('logged'); + }); + } +}; diff --git a/node_modules/winston/lib/winston/transports/http.js b/node_modules/winston/lib/winston/transports/http.js new file mode 100644 index 0000000..f7e1af6 --- /dev/null +++ b/node_modules/winston/lib/winston/transports/http.js @@ -0,0 +1,232 @@ +var util = require('util'), + winston = require('../../winston'), + http = require('http'), + https = require('https'), + Stream = require('stream').Stream, + Transport = require('./transport').Transport; + +// +// ### function Http (options) +// #### @options {Object} Options for this instance. +// Constructor function for the Http transport object responsible +// for persisting log messages and metadata to a terminal or TTY. +// +var Http = exports.Http = function (options) { + Transport.call(this, options); + options = options || {}; + + this.name = 'http'; + this.ssl = !!options.ssl; + this.host = options.host || 'localhost'; + this.port = options.port; + this.auth = options.auth; + this.path = options.path || ''; + + if (!this.port) { + this.port = this.ssl ? 443 : 80; + } +}; + +util.inherits(Http, winston.Transport); + +// +// Expose the name of this Transport on the prototype +// +Http.prototype.name = 'http'; + +// +// ### function _request (options, callback) +// #### @callback {function} Continuation to respond to when complete. +// Make a request to a winstond server or any http server which can +// handle json-rpc. +// +Http.prototype._request = function (options, callback) { + options = options || {}; + + var auth = options.auth || this.auth, + path = options.path || this.path || '', + req; + + delete options.auth; + delete options.path; + + // Prepare options for outgoing HTTP request + req = (this.ssl ? https : http).request({ + host: this.host, + port: this.port, + path: '/' + path.replace(/^\//, ''), + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + auth: (auth) ? auth.username + ':' + auth.password : '' + }); + + req.on('error', callback); + req.on('response', function (res) { + res.on('end', function () { + callback(null, res); + }); + + res.resume(); + }); + + req.end(new Buffer(JSON.stringify(options), 'utf8')); +}; + +// +// ### function log (level, msg, [meta], callback) +// #### @level {string} Level at which to log the message. +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Core logging method exposed to Winston. Metadata is optional. +// +Http.prototype.log = function (level, msg, meta, callback) { + var self = this; + + if (typeof meta === 'function') { + callback = meta; + meta = {}; + } + + var options = { + method: 'collect', + params: { + level: level, + message: msg, + meta: meta + } + }; + + if (meta) { + if (meta.path) { + options.path = meta.path; + delete meta.path; + } + + if (meta.auth) { + options.auth = meta.auth; + delete meta.auth; + } + } + + this._request(options, function (err, res) { + if (res && res.statusCode !== 200) { + err = new Error('HTTP Status Code: ' + res.statusCode); + } + + if (err) return callback(err); + + // TODO: emit 'logged' correctly, + // keep track of pending logs. + self.emit('logged'); + + if (callback) callback(null, true); + }); +}; + +// +// ### function query (options, callback) +// #### @options {Object} Loggly-like query options for this instance. +// #### @callback {function} Continuation to respond to when complete. +// Query the transport. Options object is optional. +// +Http.prototype.query = function (options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + + var self = this, + options = this.normalizeQuery(options); + + options = { + method: 'query', + params: options + }; + + if (options.params.path) { + options.path = options.params.path; + delete options.params.path; + } + + if (options.params.auth) { + options.auth = options.params.auth; + delete options.params.auth; + } + + this._request(options, function (err, res, body) { + if (res && res.statusCode !== 200) { + err = new Error('HTTP Status Code: ' + res.statusCode); + } + + if (err) return callback(err); + + if (typeof body === 'string') { + try { + body = JSON.parse(body); + } catch (e) { + return callback(e); + } + } + + callback(null, body); + }); +}; + +// +// ### function stream (options) +// #### @options {Object} Stream options for this instance. +// Returns a log stream for this transport. Options object is optional. +// +Http.prototype.stream = function (options) { + options = options || {}; + + var self = this, + stream = new Stream, + req, + buff; + + stream.destroy = function () { + req.destroy(); + }; + + options = { + method: 'stream', + params: options + }; + + if (options.params.path) { + options.path = options.params.path; + delete options.params.path; + } + + if (options.params.auth) { + options.auth = options.params.auth; + delete options.params.auth; + } + + req = this._request(options); + buff = ''; + + req.on('data', function (data) { + var data = (buff + data).split(/\n+/), + l = data.length - 1, + i = 0; + + for (; i < l; i++) { + try { + stream.emit('log', JSON.parse(data[i])); + } catch (e) { + stream.emit('error', e); + } + } + + buff = data[l]; + }); + + req.on('error', function (err) { + stream.emit('error', err); + }); + + return stream; +}; diff --git a/node_modules/winston/lib/winston/transports/memory.js b/node_modules/winston/lib/winston/transports/memory.js new file mode 100644 index 0000000..e4f562e --- /dev/null +++ b/node_modules/winston/lib/winston/transports/memory.js @@ -0,0 +1,89 @@ +var events = require('events'), + util = require('util'), + common = require('../common'), + Transport = require('./transport').Transport; + +// +// ### function Memory (options) +// #### @options {Object} Options for this instance. +// Constructor function for the Memory transport object responsible +// for persisting log messages and metadata to a memory array of messages. +// +var Memory = exports.Memory = function (options) { + Transport.call(this, options); + options = options || {}; + + this.errorOutput = []; + this.writeOutput = []; + + this.json = options.json || false; + this.colorize = options.colorize || false; + this.prettyPrint = options.prettyPrint || false; + this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false; + this.showLevel = options.showLevel === undefined ? true : options.showLevel; + this.label = options.label || null; + this.depth = options.depth || null; + + if (this.json) { + this.stringify = options.stringify || function (obj) { + return JSON.stringify(obj, null, 2); + }; + } +}; + +// +// Inherit from `winston.Transport`. +// +util.inherits(Memory, Transport); + +// +// Expose the name of this Transport on the prototype +// +Memory.prototype.name = 'memory'; + +// +// ### function log (level, msg, [meta], callback) +// #### @level {string} Level at which to log the message. +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Core logging method exposed to Winston. Metadata is optional. +// +Memory.prototype.log = function (level, msg, meta, callback) { + if (this.silent) { + return callback(null, true); + } + + var self = this, + output; + + output = common.log({ + colorize: this.colorize, + json: this.json, + level: level, + message: msg, + meta: meta, + stringify: this.stringify, + timestamp: this.timestamp, + prettyPrint: this.prettyPrint, + raw: this.raw, + label: this.label, + depth: this.depth, + formatter: this.formatter, + humanReadableUnhandledException: this.humanReadableUnhandledException + }); + + if (level === 'error' || level === 'debug') { + this.errorOutput.push(output); + } else { + this.writeOutput.push(output); + } + + self.emit('logged'); + callback(null, true); +}; + +Memory.prototype.clearLogs = function () { + this.errorOutput = []; + this.writeOutput = []; +}; diff --git a/node_modules/winston/lib/winston/transports/transport.js b/node_modules/winston/lib/winston/transports/transport.js new file mode 100644 index 0000000..d279d00 --- /dev/null +++ b/node_modules/winston/lib/winston/transports/transport.js @@ -0,0 +1,135 @@ +/* + * transport.js: Base Transport object for all Winston transports. + * + * (C) 2010 Charlie Robbins + * MIT LICENCE + * + */ + +var events = require('events'), + util = require('util'); + +// +// ### function Transport (options) +// #### @options {Object} Options for this instance. +// Constructor function for the Tranport object responsible +// base functionality for all winston transports. +// +var Transport = exports.Transport = function (options) { + events.EventEmitter.call(this); + + options = options || {}; + this.silent = options.silent || false; + this.raw = options.raw || false; + this.name = options.name || this.name; + this.formatter = options.formatter; + + // + // Do not set a default level. When `level` is falsey on any + // `Transport` instance, any `Logger` instance uses the + // configured level (instead of the Transport level) + // + this.level = options.level; + + this.handleExceptions = options.handleExceptions || false; + this.exceptionsLevel = options.exceptionsLevel || 'error'; + this.humanReadableUnhandledException = options.humanReadableUnhandledException || false; +}; + +// +// Inherit from `events.EventEmitter`. +// +util.inherits(Transport, events.EventEmitter); + +// +// ### function formatQuery (query) +// #### @query {string|Object} Query to format +// Formats the specified `query` Object (or string) to conform +// with the underlying implementation of this transport. +// +Transport.prototype.formatQuery = function (query) { + return query; +}; + +// +// ### function normalizeQuery (query) +// #### @options {string|Object} Query to normalize +// Normalize options for query +// +Transport.prototype.normalizeQuery = function (options) { + // + // Use options similar to loggly. + // [See Loggly Search API](http://wiki.loggly.com/retrieve_events#optional) + // + + options = options || {}; + + // limit + options.rows = options.rows || options.limit || 10; + + // starting row offset + options.start = options.start || 0; + + // now + options.until = options.until || new Date; + if (typeof options.until !== 'object') { + options.until = new Date(options.until); + } + + // now - 24 + options.from = options.from || (options.until - (24 * 60 * 60 * 1000)); + if (typeof options.from !== 'object') { + options.from = new Date(options.from); + } + + + // 'asc' or 'desc' + options.order = options.order || 'desc'; + + // which fields to select + options.fields = options.fields; + + return options; +}; + +// +// ### function formatResults (results, options) +// #### @results {Object|Array} Results returned from `.query`. +// #### @options {Object} **Optional** Formatting options +// Formats the specified `results` with the given `options` accordinging +// to the implementation of this transport. +// +Transport.prototype.formatResults = function (results, options) { + return results; +}; + +// +// ### function logException (msg, meta, callback) +// #### @msg {string} Message to log +// #### @meta {Object} **Optional** Additional metadata to attach +// #### @callback {function} Continuation to respond to when complete. +// Logs the specified `msg`, `meta` and responds to the callback once the log +// operation is complete to ensure that the event loop will not exit before +// all logging has completed. +// +Transport.prototype.logException = function (msg, meta, callback) { + var self = this, + called; + + if (this.silent) { + return callback(); + } + + function onComplete () { + if (!called) { + called = true; + self.removeListener('logged', onComplete); + self.removeListener('error', onComplete); + callback(); + } + } + + this.once('logged', onComplete); + this.once('error', onComplete); + this.log(self.exceptionsLevel, msg, meta, function () { }); +}; diff --git a/node_modules/winston/node_modules/async/.jshintrc b/node_modules/winston/node_modules/async/.jshintrc new file mode 100644 index 0000000..172f491 --- /dev/null +++ b/node_modules/winston/node_modules/async/.jshintrc @@ -0,0 +1,24 @@ +{ + // Enforcing options + "eqeqeq": false, + "forin": true, + "indent": 4, + "noarg": true, + "undef": true, + "trailing": true, + "evil": true, + "laxcomma": true, + + // Relaxing options + "onevar": false, + "asi": false, + "eqnull": true, + "expr": false, + "loopfunc": true, + "sub": true, + "browser": true, + "node": true, + "globals": { + "define": true + } +} diff --git a/node_modules/winston/node_modules/async/.travis.yml b/node_modules/winston/node_modules/async/.travis.yml new file mode 100644 index 0000000..6064ca0 --- /dev/null +++ b/node_modules/winston/node_modules/async/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.10" + - "0.12" + - "iojs" diff --git a/node_modules/winston/node_modules/async/CHANGELOG.md b/node_modules/winston/node_modules/async/CHANGELOG.md new file mode 100644 index 0000000..7d39c37 --- /dev/null +++ b/node_modules/winston/node_modules/async/CHANGELOG.md @@ -0,0 +1,16 @@ +# v1.0.0 + +No known breaking changes, we are simply complying with semver from here on out. + +Changes: + +- Start using a changelog! +- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) (#168 #704 #321) +- Detect deadlocks in `auto` (#663) +- Better support for require.js (#527) +- Throw if queue created with concurrency `0` (#714) +- Fix unneeded iteration in `queue.resume()` (#758) +- Guard against timer mocking overriding `setImmediate` (#609 #611) +- Miscellaneous doc fixes (#542 #596 #615 #628 #631 #690 #729) +- Use single noop function internally (#546) +- Optimize internal `_each`, `_map` and `_keys` functions. diff --git a/node_modules/winston/node_modules/async/LICENSE b/node_modules/winston/node_modules/async/LICENSE new file mode 100644 index 0000000..8f29698 --- /dev/null +++ b/node_modules/winston/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010-2014 Caolan McMahon + +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/winston/node_modules/async/README.md b/node_modules/winston/node_modules/async/README.md new file mode 100644 index 0000000..7e5e15f --- /dev/null +++ b/node_modules/winston/node_modules/async/README.md @@ -0,0 +1,1720 @@ +# Async.js + +[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async) +[![NPM version](http://img.shields.io/npm/v/async.svg)](https://www.npmjs.org/package/async) + + +Async is a utility module which provides straight-forward, powerful functions +for working with asynchronous JavaScript. Although originally designed for +use with [Node.js](http://nodejs.org) and installable via `npm install async`, +it can also be used directly in the browser. + +Async is also installable via: + +- [bower](http://bower.io/): `bower install async` +- [component](https://github.com/component/component): `component install + caolan/async` +- [jam](http://jamjs.org/): `jam install async` +- [spm](http://spmjs.io/): `spm install async` + +Async provides around 20 functions that include the usual 'functional' +suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns +for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these +functions assume you follow the Node.js convention of providing a single +callback as the last argument of your `async` function. + + +## Quick Examples + +```javascript +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); + +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); + +async.parallel([ + function(){ ... }, + function(){ ... } +], callback); + +async.series([ + function(){ ... }, + function(){ ... } +]); +``` + +There are many more functions available so take a look at the docs below for a +full list. This module aims to be comprehensive, so if you feel anything is +missing please create a GitHub issue for it. + +## Common Pitfalls + +### Binding a context to an iterator + +This section is really about `bind`, not about `async`. If you are wondering how to +make `async` execute your iterators in a given context, or are confused as to why +a method of another library isn't working as an iterator, study this example: + +```js +// Here is a simple object with an (unnecessarily roundabout) squaring method +var AsyncSquaringLibrary = { + squareExponent: 2, + square: function(number, callback){ + var result = Math.pow(number, this.squareExponent); + setTimeout(function(){ + callback(null, result); + }, 200); + } +}; + +async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){ + // result is [NaN, NaN, NaN] + // This fails because the `this.squareExponent` expression in the square + // function is not evaluated in the context of AsyncSquaringLibrary, and is + // therefore undefined. +}); + +async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){ + // result is [1, 4, 9] + // With the help of bind we can attach a context to the iterator before + // passing it to async. Now the square function will be executed in its + // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent` + // will be as expected. +}); +``` + +## Download + +The source is available for download from +[GitHub](https://github.com/caolan/async/blob/master/lib/async.js). +Alternatively, you can install using Node Package Manager (`npm`): + + npm install async + +As well as using Bower: + + bower install async + +__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed + +## In the Browser + +So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. + +Usage: + +```html +<script type="text/javascript" src="async.js"></script> +<script type="text/javascript"> + + async.map(data, asyncProcess, function(err, results){ + alert(results); + }); + +</script> +``` + +## Documentation + +### Collections + +* [`each`](#each) +* [`eachSeries`](#eachSeries) +* [`eachLimit`](#eachLimit) +* [`forEachOf`](#forEachOf) +* [`forEachOfSeries`](#forEachOfSeries) +* [`forEachOfLimit`](#forEachOfLimit) +* [`map`](#map) +* [`mapSeries`](#mapSeries) +* [`mapLimit`](#mapLimit) +* [`filter`](#filter) +* [`filterSeries`](#filterSeries) +* [`reject`](#reject) +* [`rejectSeries`](#rejectSeries) +* [`reduce`](#reduce) +* [`reduceRight`](#reduceRight) +* [`detect`](#detect) +* [`detectSeries`](#detectSeries) +* [`sortBy`](#sortBy) +* [`some`](#some) +* [`every`](#every) +* [`concat`](#concat) +* [`concatSeries`](#concatSeries) + +### Control Flow + +* [`series`](#seriestasks-callback) +* [`parallel`](#parallel) +* [`parallelLimit`](#parallellimittasks-limit-callback) +* [`whilst`](#whilst) +* [`doWhilst`](#doWhilst) +* [`until`](#until) +* [`doUntil`](#doUntil) +* [`forever`](#forever) +* [`waterfall`](#waterfall) +* [`compose`](#compose) +* [`seq`](#seq) +* [`applyEach`](#applyEach) +* [`applyEachSeries`](#applyEachSeries) +* [`queue`](#queue) +* [`priorityQueue`](#priorityQueue) +* [`cargo`](#cargo) +* [`auto`](#auto) +* [`retry`](#retry) +* [`iterator`](#iterator) +* [`apply`](#apply) +* [`nextTick`](#nextTick) +* [`times`](#times) +* [`timesSeries`](#timesSeries) + +### Utils + +* [`memoize`](#memoize) +* [`unmemoize`](#unmemoize) +* [`log`](#log) +* [`dir`](#dir) +* [`noConflict`](#noConflict) + + +## Collections + +<a name="forEach" /> +<a name="each" /> +### each(arr, iterator, callback) + +Applies the function `iterator` to each item in `arr`, in parallel. +The `iterator` is called with an item from the list, and a callback for when it +has finished. If the `iterator` passes an error to its `callback`, the main +`callback` (for the `each` function) is immediately called with the error. + +Note, that since this function applies `iterator` to each item in parallel, +there is no guarantee that the iterator functions will complete in order. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the `callback` should be run without + arguments or with an explicit `null` argument. The array index is not passed + to the iterator. If you need the index, use [`forEachOf`](#forEachOf). +* `callback(err)` - A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Examples__ + + +```js +// assuming openFiles is an array of file names and saveFile is a function +// to save the modified contents of that file: + +async.each(openFiles, saveFile, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +```js +// assuming openFiles is an array of file names + +async.each(openFiles, function(file, callback) { + + // Perform operation on file here. + console.log('Processing file ' + file); + + if( file.length > 32 ) { + console.log('This file name is too long'); + callback('File name too long'); + } else { + // Do work to process file here + console.log('File processed'); + callback(); + } +}, function(err){ + // if any of the file processing produced an error, err would equal that error + if( err ) { + // One of the iterations produced an error. + // All processing will now stop. + console.log('A file failed to process'); + } else { + console.log('All files have been processed successfully'); + } +}); +``` + +--------------------------------------- + +<a name="forEachSeries" /> +<a name="eachSeries" /> +### eachSeries(arr, iterator, callback) + +The same as [`each`](#each), only `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +This means the `iterator` functions will complete in order. + + +--------------------------------------- + +<a name="forEachLimit" /> +<a name="eachLimit" /> +### eachLimit(arr, limit, iterator, callback) + +The same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously +running at any time. + +Note that the items in `arr` are not processed in batches, so there is no guarantee that +the first `limit` `iterator` functions will complete before any others are started. + +__Arguments__ + +* `arr` - An array to iterate over. +* `limit` - The maximum number of `iterator`s to run at any time. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err)` which must be called once it has + completed. If no error has occurred, the callback should be run without + arguments or with an explicit `null` argument. +* `callback(err)` - A callback which is called when all `iterator` functions + have finished, or an error occurs. + +__Example__ + +```js +// Assume documents is an array of JSON objects and requestApi is a +// function that interacts with a rate-limited REST api. + +async.eachLimit(documents, 20, requestApi, function(err){ + // if any of the saves produced an error, err would equal that error +}); +``` + +--------------------------------------- + +<a name="forEachOf" /> +<a name="eachOf" /> + +### forEachOf(obj, iterator, callback) + +Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator. + +__Arguments__ + +* `obj` - An object or array to iterate over. +* `iterator(item, key, callback)` - A function to apply to each item in `obj`. +The `key` is the item's key, or index in the case of an array. The iterator is +passed a `callback(err)` which must be called once it has completed. If no +error has occurred, the callback should be run without arguments or with an +explicit `null` argument. +* `callback(err)` - A callback which is called when all `iterator` functions have finished, or an error occurs. + +__Example__ + +```js +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; +var configs = {}; + +async.forEachOf(obj, function (value, key, callback) { + fs.readFile(__dirname + value, "utf8", function (err, data) { + if (err) return callback(err); + try { + configs[key] = JSON.parse(data); + } catch (e) { + return callback(e); + } + callback(); + }) +}, function (err) { + if (err) console.error(err.message); + // configs is now a map of JSON data + doSomethingWith(configs); +}) +``` + +--------------------------------------- + +<a name="forEachOfSeries" /> +<a name="eachOfSeries" /> + +### forEachOfSeries(obj, iterator, callback) + +Like [`forEachOf`](#forEachOf), except only one `iterator` is run at a time. The order of execution is not guaranteed for objects, but it will be guaranteed for arrays. + +--------------------------------------- + +<a name="forEachOfLimit" /> +<a name="eachOfLimit" /> + +### forEachOfLimit(obj, limit, iterator, callback) + +Like [`forEachOf`](#forEachOf), except the number of `iterator`s running at a given time is controlled by `limit`. + + +--------------------------------------- + +<a name="map" /> +### map(arr, iterator, callback) + +Produces a new array of values by mapping each value in `arr` through +the `iterator` function. The `iterator` is called with an item from `arr` and a +callback for when it has finished processing. Each of these callback takes 2 arguments: +an `error`, and the transformed item from `arr`. If `iterator` passes an error to its +callback, the main `callback` (for the `map` function) is immediately called with the error. + +Note, that since this function applies the `iterator` to each item in parallel, +there is no guarantee that the `iterator` functions will complete in order. +However, the results array will be in the same order as the original `arr`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - A callback which is called when all `iterator` + functions have finished, or an error occurs. Results is an array of the + transformed items from the `arr`. + +__Example__ + +```js +async.map(['file1','file2','file3'], fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +--------------------------------------- + +<a name="mapSeries" /> +### mapSeries(arr, iterator, callback) + +The same as [`map`](#map), only the `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + + +--------------------------------------- + +<a name="mapLimit" /> +### mapLimit(arr, limit, iterator, callback) + +The same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously +running at any time. + +Note that the items are not processed in batches, so there is no guarantee that +the first `limit` `iterator` functions will complete before any others are started. + +__Arguments__ + +* `arr` - An array to iterate over. +* `limit` - The maximum number of `iterator`s to run at any time. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, transformed)` which must be called once + it has completed with an error (which can be `null`) and a transformed item. +* `callback(err, results)` - A callback which is called when all `iterator` + calls have finished, or an error occurs. The result is an array of the + transformed items from the original `arr`. + +__Example__ + +```js +async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){ + // results is now an array of stats for each file +}); +``` + +--------------------------------------- + +<a name="select" /> +<a name="filter" /> +### filter(arr, iterator, callback) + +__Alias:__ `select` + +Returns a new array of all the values in `arr` which pass an async truth test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. This operation is +performed in parallel, but the results array will be in the same order as the +original. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The `iterator` is passed a `callback(truthValue)`, which must be called with a + boolean argument once it has completed. +* `callback(results)` - A callback which is called after all the `iterator` + functions have finished. + +__Example__ + +```js +async.filter(['file1','file2','file3'], fs.exists, function(results){ + // results now equals an array of the existing files +}); +``` + +--------------------------------------- + +<a name="selectSeries" /> +<a name="filterSeries" /> +### filterSeries(arr, iterator, callback) + +__Alias:__ `selectSeries` + +The same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + +--------------------------------------- + +<a name="reject" /> +### reject(arr, iterator, callback) + +The opposite of [`filter`](#filter). Removes values that pass an `async` truth test. + +--------------------------------------- + +<a name="rejectSeries" /> +### rejectSeries(arr, iterator, callback) + +The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr` +in series. + + +--------------------------------------- + +<a name="reduce" /> +### reduce(arr, memo, iterator, callback) + +__Aliases:__ `inject`, `foldl` + +Reduces `arr` into a single value using an async `iterator` to return +each successive step. `memo` is the initial state of the reduction. +This function only operates in series. + +For performance reasons, it may make sense to split a call to this function into +a parallel map, and then use the normal `Array.prototype.reduce` on the results. +This function is for situations where each step in the reduction needs to be async; +if you can get the data before reducing it, then it's probably a good idea to do so. + +__Arguments__ + +* `arr` - An array to iterate over. +* `memo` - The initial state of the reduction. +* `iterator(memo, item, callback)` - A function applied to each item in the + array to produce the next step in the reduction. The `iterator` is passed a + `callback(err, reduction)` which accepts an optional error as its first + argument, and the state of the reduction as the second. If an error is + passed to the callback, the reduction is stopped and the main `callback` is + immediately called with the error. +* `callback(err, result)` - A callback which is called after all the `iterator` + functions have finished. Result is the reduced value. + +__Example__ + +```js +async.reduce([1,2,3], 0, function(memo, item, callback){ + // pointless async: + process.nextTick(function(){ + callback(null, memo + item) + }); +}, function(err, result){ + // result is now equal to the last value of memo, which is 6 +}); +``` + +--------------------------------------- + +<a name="reduceRight" /> +### reduceRight(arr, memo, iterator, callback) + +__Alias:__ `foldr` + +Same as [`reduce`](#reduce), only operates on `arr` in reverse order. + + +--------------------------------------- + +<a name="detect" /> +### detect(arr, iterator, callback) + +Returns the first value in `arr` that passes an async truth test. The +`iterator` is applied in parallel, meaning the first iterator to return `true` will +fire the detect `callback` with that result. That means the result might not be +the first item in the original `arr` (in terms of order) that passes the test. + +If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries). + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in `arr`. + The iterator is passed a `callback(truthValue)` which must be called with a + boolean argument once it has completed. +* `callback(result)` - A callback which is called as soon as any iterator returns + `true`, or after all the `iterator` functions have finished. Result will be + the first item in the array that passes the truth test (iterator) or the + value `undefined` if none passed. + +__Example__ + +```js +async.detect(['file1','file2','file3'], fs.exists, function(result){ + // result now equals the first file in the list that exists +}); +``` + +--------------------------------------- + +<a name="detectSeries" /> +### detectSeries(arr, iterator, callback) + +The same as [`detect`](#detect), only the `iterator` is applied to each item in `arr` +in series. This means the result is always the first in the original `arr` (in +terms of array order) that passes the truth test. + + +--------------------------------------- + +<a name="sortBy" /> +### sortBy(arr, iterator, callback) + +Sorts a list by the results of running each `arr` value through an async `iterator`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, sortValue)` which must be called once it + has completed with an error (which can be `null`) and a value to use as the sort + criteria. +* `callback(err, results)` - A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is the items from + the original `arr` sorted by the values returned by the `iterator` calls. + +__Example__ + +```js +async.sortBy(['file1','file2','file3'], function(file, callback){ + fs.stat(file, function(err, stats){ + callback(err, stats.mtime); + }); +}, function(err, results){ + // results is now the original array of files sorted by + // modified date +}); +``` + +__Sort Order__ + +By modifying the callback parameter the sorting order can be influenced: + +```js +//ascending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x); +}, function(err,result){ + //result callback +} ); + +//descending order +async.sortBy([1,9,3,5], function(x, callback){ + callback(null, x*-1); //<- x*-1 instead of x, turns the order around +}, function(err,result){ + //result callback +} ); +``` + +--------------------------------------- + +<a name="some" /> +### some(arr, iterator, callback) + +__Alias:__ `any` + +Returns `true` if at least one element in the `arr` satisfies an async test. +_The callback for each iterator call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. Once any iterator +call returns `true`, the main `callback` is immediately called. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a callback(truthValue) which must be + called with a boolean argument once it has completed. +* `callback(result)` - A callback which is called as soon as any iterator returns + `true`, or after all the iterator functions have finished. Result will be + either `true` or `false` depending on the values of the async tests. + +__Example__ + +```js +async.some(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then at least one of the files exists +}); +``` + +--------------------------------------- + +<a name="every" /> +### every(arr, iterator, callback) + +__Alias:__ `all` + +Returns `true` if every element in `arr` satisfies an async test. +_The callback for each `iterator` call only accepts a single argument of `true` or +`false`; it does not accept an error argument first!_ This is in-line with the +way node libraries work with truth tests like `fs.exists`. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A truth test to apply to each item in the array + in parallel. The iterator is passed a callback(truthValue) which must be + called with a boolean argument once it has completed. +* `callback(result)` - A callback which is called after all the `iterator` + functions have finished. Result will be either `true` or `false` depending on + the values of the async tests. + +__Example__ + +```js +async.every(['file1','file2','file3'], fs.exists, function(result){ + // if result is true then every file exists +}); +``` + +--------------------------------------- + +<a name="concat" /> +### concat(arr, iterator, callback) + +Applies `iterator` to each item in `arr`, concatenating the results. Returns the +concatenated list. The `iterator`s are called in parallel, and the results are +concatenated as they return. There is no guarantee that the results array will +be returned in the original order of `arr` passed to the `iterator` function. + +__Arguments__ + +* `arr` - An array to iterate over. +* `iterator(item, callback)` - A function to apply to each item in `arr`. + The iterator is passed a `callback(err, results)` which must be called once it + has completed with an error (which can be `null`) and an array of results. +* `callback(err, results)` - A callback which is called after all the `iterator` + functions have finished, or an error occurs. Results is an array containing + the concatenated results of the `iterator` function. + +__Example__ + +```js +async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ + // files is now a list of filenames that exist in the 3 directories +}); +``` + +--------------------------------------- + +<a name="concatSeries" /> +### concatSeries(arr, iterator, callback) + +Same as [`concat`](#concat), but executes in series instead of parallel. + + +## Control Flow + +<a name="series" /> +### series(tasks, [callback]) + +Run the functions in the `tasks` array in series, each one running once the previous +function has completed. If any functions in the series pass an error to its +callback, no more functions are run, and `callback` is immediately called with the value of the error. +Otherwise, `callback` receives an array of results when `tasks` have completed. + +It is also possible to use an object instead of an array. Each property will be +run as a function, and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`series`](#series). + +**Note** that while many implementations preserve the order of object properties, the +[ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) +explicitly states that + +> The mechanics and order of enumerating the properties is not specified. + +So if you rely on the order in which your series of functions are executed, and want +this to work on all platforms, consider using an array. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +__Example__ + +```js +async.series([ + function(callback){ + // do some stuff ... + callback(null, 'one'); + }, + function(callback){ + // do some more stuff ... + callback(null, 'two'); + } +], +// optional callback +function(err, results){ + // results is now equal to ['one', 'two'] +}); + + +// an example using an object instead of an array +async.series({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equal to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + +<a name="parallel" /> +### parallel(tasks, [callback]) + +Run the `tasks` array of functions in parallel, without waiting until the previous +function has completed. If any of the functions pass an error to its +callback, the main `callback` is immediately called with the value of the error. +Once the `tasks` have completed, the results are passed to the final `callback` as an +array. + +It is also possible to use an object instead of an array. Each property will be +run as a function and the results will be passed to the final `callback` as an object +instead of an array. This can be a more readable way of handling results from +[`parallel`](#parallel). + + +__Arguments__ + +* `tasks` - An array or object containing functions to run. Each function is passed + a `callback(err, result)` which it must call on completion with an error `err` + (which can be `null`) and an optional `result` value. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the task callbacks. + +__Example__ + +```js +async.parallel([ + function(callback){ + setTimeout(function(){ + callback(null, 'one'); + }, 200); + }, + function(callback){ + setTimeout(function(){ + callback(null, 'two'); + }, 100); + } +], +// optional callback +function(err, results){ + // the results array will equal ['one','two'] even though + // the second function had a shorter timeout. +}); + + +// an example using an object instead of an array +async.parallel({ + one: function(callback){ + setTimeout(function(){ + callback(null, 1); + }, 200); + }, + two: function(callback){ + setTimeout(function(){ + callback(null, 2); + }, 100); + } +}, +function(err, results) { + // results is now equals to: {one: 1, two: 2} +}); +``` + +--------------------------------------- + +<a name="parallelLimit" /> +### parallelLimit(tasks, limit, [callback]) + +The same as [`parallel`](#parallel), only `tasks` are executed in parallel +with a maximum of `limit` tasks executing at any time. + +Note that the `tasks` are not executed in batches, so there is no guarantee that +the first `limit` tasks will complete before any others are started. + +__Arguments__ + +* `tasks` - An array or object containing functions to run, each function is passed + a `callback(err, result)` it must call on completion with an error `err` (which can + be `null`) and an optional `result` value. +* `limit` - The maximum number of `tasks` to run at any time. +* `callback(err, results)` - An optional callback to run once all the functions + have completed. This function gets a results array (or object) containing all + the result arguments passed to the `task` callbacks. + +--------------------------------------- + +<a name="whilst" /> +### whilst(test, fn, callback) + +Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +__Arguments__ + +* `test()` - synchronous truth test to perform before each execution of `fn`. +* `fn(callback)` - A function which is called each time `test` passes. The function is + passed a `callback(err)`, which must be called once it has completed with an + optional `err` argument. +* `callback(err)` - A callback which is called after the test fails and repeated + execution of `fn` has stopped. + +__Example__ + +```js +var count = 0; + +async.whilst( + function () { return count < 5; }, + function (callback) { + count++; + setTimeout(callback, 1000); + }, + function (err) { + // 5 seconds have passed + } +); +``` + +--------------------------------------- + +<a name="doWhilst" /> +### doWhilst(fn, test, callback) + +The post-check version of [`whilst`](#whilst). To reflect the difference in +the order of operations, the arguments `test` and `fn` are switched. + +`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + +--------------------------------------- + +<a name="until" /> +### until(test, fn, callback) + +Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +The inverse of [`whilst`](#whilst). + +--------------------------------------- + +<a name="doUntil" /> +### doUntil(fn, test, callback) + +Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`. + +--------------------------------------- + +<a name="forever" /> +### forever(fn, errback) + +Calls the asynchronous function `fn` with a callback parameter that allows it to +call itself again, in series, indefinitely. + +If an error is passed to the callback then `errback` is called with the +error, and execution stops, otherwise it will never be called. + +```js +async.forever( + function(next) { + // next is suitable for passing to things that need a callback(err [, whatever]); + // it will result in this function being called again. + }, + function(err) { + // if next is called with a value in its first parameter, it will appear + // in here as 'err', and execution will stop. + } +); +``` + +--------------------------------------- + +<a name="waterfall" /> +### waterfall(tasks, [callback]) + +Runs the `tasks` array of functions in series, each passing their results to the next in +the array. However, if any of the `tasks` pass an error to their own callback, the +next function is not executed, and the main `callback` is immediately called with +the error. + +__Arguments__ + +* `tasks` - An array of functions to run, each function is passed a + `callback(err, result1, result2, ...)` it must call on completion. The first + argument is an error (which can be `null`) and any further arguments will be + passed as arguments in order to the next task. +* `callback(err, [results])` - An optional callback to run once all the functions + have completed. This will be passed the results of the last task's callback. + + + +__Example__ + +```js +async.waterfall([ + function(callback) { + callback(null, 'one', 'two'); + }, + function(arg1, arg2, callback) { + // arg1 now equals 'one' and arg2 now equals 'two' + callback(null, 'three'); + }, + function(arg1, callback) { + // arg1 now equals 'three' + callback(null, 'done'); + } +], function (err, result) { + // result now equals 'done' +}); +``` + +--------------------------------------- +<a name="compose" /> +### compose(fn1, fn2...) + +Creates a function which is a composition of the passed asynchronous +functions. Each function consumes the return value of the function that +follows. Composing functions `f()`, `g()`, and `h()` would produce the result of +`f(g(h()))`, only this version uses callbacks to obtain the return values. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* `functions...` - the asynchronous functions to compose + + +__Example__ + +```js +function add1(n, callback) { + setTimeout(function () { + callback(null, n + 1); + }, 10); +} + +function mul3(n, callback) { + setTimeout(function () { + callback(null, n * 3); + }, 10); +} + +var add1mul3 = async.compose(mul3, add1); + +add1mul3(4, function (err, result) { + // result now equals 15 +}); +``` + +--------------------------------------- +<a name="seq" /> +### seq(fn1, fn2...) + +Version of the compose function that is more natural to read. +Each function consumes the return value of the previous function. +It is the equivalent of [`compose`](#compose) with the arguments reversed. + +Each function is executed with the `this` binding of the composed function. + +__Arguments__ + +* functions... - the asynchronous functions to compose + + +__Example__ + +```js +// Requires lodash (or underscore), express3 and dresende's orm2. +// Part of an app, that fetches cats of the logged user. +// This example uses `seq` function to avoid overnesting and error +// handling clutter. +app.get('/cats', function(request, response) { + var User = request.models.User; + async.seq( + _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) + function(user, fn) { + user.getCats(fn); // 'getCats' has signature (callback(err, data)) + } + )(req.session.user_id, function (err, cats) { + if (err) { + console.error(err); + response.json({ status: 'error', message: err.message }); + } else { + response.json({ status: 'ok', message: 'Cats found', data: cats }); + } + }); +}); +``` + +--------------------------------------- +<a name="applyEach" /> +### applyEach(fns, args..., callback) + +Applies the provided arguments to each function in the array, calling +`callback` after all functions have completed. If you only provide the first +argument, then it will return a function which lets you pass in the +arguments as if it were a single function call. + +__Arguments__ + +* `fns` - the asynchronous functions to all call with the same arguments +* `args...` - any number of separate arguments to pass to the function +* `callback` - the final argument should be the callback, called when all + functions have completed processing + + +__Example__ + +```js +async.applyEach([enableSearch, updateSchema], 'bucket', callback); + +// partial application example: +async.each( + buckets, + async.applyEach([enableSearch, updateSchema]), + callback +); +``` + +--------------------------------------- + +<a name="applyEachSeries" /> +### applyEachSeries(arr, args..., callback) + +The same as [`applyEach`](#applyEach) only the functions are applied in series. + +--------------------------------------- + +<a name="queue" /> +### queue(worker, concurrency) + +Creates a `queue` object with the specified `concurrency`. Tasks added to the +`queue` are processed in parallel (up to the `concurrency` limit). If all +`worker`s are in progress, the task is queued until one becomes available. +Once a `worker` completes a `task`, that `task`'s callback is called. + +__Arguments__ + +* `worker(task, callback)` - An asynchronous function for processing a queued + task, which must call its `callback(err)` argument when finished, with an + optional `error` as an argument. +* `concurrency` - An `integer` for determining how many `worker` functions should be + run in parallel. + +__Queue objects__ + +The `queue` object returned by this function has the following properties and +methods: + +* `length()` - a function returning the number of items waiting to be processed. +* `started` - a function returning whether or not any items have been pushed and processed by the queue +* `running()` - a function returning the number of items currently being processed. +* `idle()` - a function returning false if there are items waiting or being processed, or true if not. +* `concurrency` - an integer for determining how many `worker` functions should be + run in parallel. This property can be changed after a `queue` is created to + alter the concurrency on-the-fly. +* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once + the `worker` has finished processing the task. Instead of a single task, a `tasks` array + can be submitted. The respective callback is used for every task in the list. +* `unshift(task, [callback])` - add a new task to the front of the `queue`. +* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, + and further tasks will be queued. +* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`. +* `paused` - a boolean for determining whether the queue is in a paused state +* `pause()` - a function that pauses the processing of tasks until `resume()` is called. +* `resume()` - a function that resumes the processing of queued tasks when the queue is paused. +* `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle. + +__Example__ + +```js +// create a queue object with concurrency 2 + +var q = async.queue(function (task, callback) { + console.log('hello ' + task.name); + callback(); +}, 2); + + +// assign a callback +q.drain = function() { + console.log('all items have been processed'); +} + +// add some items to the queue + +q.push({name: 'foo'}, function (err) { + console.log('finished processing foo'); +}); +q.push({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); + +// add some items to the queue (batch-wise) + +q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { + console.log('finished processing item'); +}); + +// add some items to the front of the queue + +q.unshift({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); +``` + + +--------------------------------------- + +<a name="priorityQueue" /> +### priorityQueue(worker, concurrency) + +The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects: + +* `push(task, priority, [callback])` - `priority` should be a number. If an array of + `tasks` is given, all tasks will be assigned the same priority. +* The `unshift` method was removed. + +--------------------------------------- + +<a name="cargo" /> +### cargo(worker, [payload]) + +Creates a `cargo` object with the specified payload. Tasks added to the +cargo will be processed altogether (up to the `payload` limit). If the +`worker` is in progress, the task is queued until it becomes available. Once +the `worker` has completed some tasks, each callback of those tasks is called. +Check out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work. + +While [queue](#queue) passes only one task to one of a group of workers +at a time, cargo passes an array of tasks to a single worker, repeating +when the worker is finished. + +__Arguments__ + +* `worker(tasks, callback)` - An asynchronous function for processing an array of + queued tasks, which must call its `callback(err)` argument when finished, with + an optional `err` argument. +* `payload` - An optional `integer` for determining how many tasks should be + processed per round; if omitted, the default is unlimited. + +__Cargo objects__ + +The `cargo` object returned by this function has the following properties and +methods: + +* `length()` - A function returning the number of items waiting to be processed. +* `payload` - An `integer` for determining how many tasks should be + process per round. This property can be changed after a `cargo` is created to + alter the payload on-the-fly. +* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called + once the `worker` has finished processing the task. Instead of a single task, an array of `tasks` + can be submitted. The respective callback is used for every task in the list. +* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued. +* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`. +* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`. + +__Example__ + +```js +// create a cargo object with payload 2 + +var cargo = async.cargo(function (tasks, callback) { + for(var i=0; i<tasks.length; i++){ + console.log('hello ' + tasks[i].name); + } + callback(); +}, 2); + + +// add some items + +cargo.push({name: 'foo'}, function (err) { + console.log('finished processing foo'); +}); +cargo.push({name: 'bar'}, function (err) { + console.log('finished processing bar'); +}); +cargo.push({name: 'baz'}, function (err) { + console.log('finished processing baz'); +}); +``` + +--------------------------------------- + +<a name="auto" /> +### auto(tasks, [callback]) + +Determines the best order for running the functions in `tasks`, based on their +requirements. Each function can optionally depend on other functions being completed +first, and each function is run as soon as its requirements are satisfied. + +If any of the functions pass an error to their callback, it will not +complete (so any other functions depending on it will not run), and the main +`callback` is immediately called with the error. Functions also receive an +object containing the results of functions which have completed so far. + +Note, all functions are called with a `results` object as a second argument, +so it is unsafe to pass functions in the `tasks` object which cannot handle the +extra argument. + +For example, this snippet of code: + +```js +async.auto({ + readData: async.apply(fs.readFile, 'data.txt', 'utf-8') +}, callback); +``` + +will have the effect of calling `readFile` with the results object as the last +argument, which will fail: + +```js +fs.readFile('data.txt', 'utf-8', cb, {}); +``` + +Instead, wrap the call to `readFile` in a function which does not forward the +`results` object: + +```js +async.auto({ + readData: function(cb, results){ + fs.readFile('data.txt', 'utf-8', cb); + } +}, callback); +``` + +__Arguments__ + +* `tasks` - An object. Each of its properties is either a function or an array of + requirements, with the function itself the last item in the array. The object's key + of a property serves as the name of the task defined by that property, + i.e. can be used when specifying requirements for other tasks. + The function receives two arguments: (1) a `callback(err, result)` which must be + called when finished, passing an `error` (which can be `null`) and the result of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions. +* `callback(err, results)` - An optional callback which is called when all the + tasks have been completed. It receives the `err` argument if any `tasks` + pass an error to their callback. Results are always returned; however, if + an error occurs, no further `tasks` will be performed, and the results + object will only contain partial results. + + +__Example__ + +```js +async.auto({ + get_data: function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + make_folder: function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + }, + write_file: ['get_data', 'make_folder', function(callback, results){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + callback(null, 'filename'); + }], + email_link: ['write_file', function(callback, results){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + // results.write_file contains the filename returned by write_file. + callback(null, {'file':results.write_file, 'email':'user@example.com'}); + }] +}, function(err, results) { + console.log('err = ', err); + console.log('results = ', results); +}); +``` + +This is a fairly trivial example, but to do this using the basic parallel and +series functions would look like this: + +```js +async.parallel([ + function(callback){ + console.log('in get_data'); + // async code to get some data + callback(null, 'data', 'converted to array'); + }, + function(callback){ + console.log('in make_folder'); + // async code to create a directory to store a file in + // this is run at the same time as getting the data + callback(null, 'folder'); + } +], +function(err, results){ + async.series([ + function(callback){ + console.log('in write_file', JSON.stringify(results)); + // once there is some data and the directory exists, + // write the data to a file in the directory + results.push('filename'); + callback(null); + }, + function(callback){ + console.log('in email_link', JSON.stringify(results)); + // once the file is written let's email a link to it... + callback(null, {'file':results.pop(), 'email':'user@example.com'}); + } + ]); +}); +``` + +For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding +new tasks much easier (and the code more readable). + + +--------------------------------------- + +<a name="retry" /> +### retry([times = 5], task, [callback]) + +Attempts to get a successful response from `task` no more than `times` times before +returning an error. If the task is successful, the `callback` will be passed the result +of the successful task. If all attempts fail, the callback will be passed the error and +result (if any) of the final attempt. + +__Arguments__ + +* `times` - An integer indicating how many times to attempt the `task` before giving up. Defaults to 5. +* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)` + which must be called when finished, passing `err` (which can be `null`) and the `result` of + the function's execution, and (2) a `results` object, containing the results of + the previously executed functions (if nested inside another control flow). +* `callback(err, results)` - An optional callback which is called when the + task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`. + +The [`retry`](#retry) function can be used as a stand-alone control flow by passing a +callback, as shown below: + +```js +async.retry(3, apiMethod, function(err, result) { + // do something with the result +}); +``` + +It can also be embeded within other control flow functions to retry individual methods +that are not as reliable, like this: + +```js +async.auto({ + users: api.getUsers.bind(api), + payments: async.retry(3, api.getPayments.bind(api)) +}, function(err, results) { + // do something with the results +}); +``` + + +--------------------------------------- + +<a name="iterator" /> +### iterator(tasks) + +Creates an iterator function which calls the next function in the `tasks` array, +returning a continuation to call the next one after that. It's also possible to +“peek” at the next iterator with `iterator.next()`. + +This function is used internally by the `async` module, but can be useful when +you want to manually control the flow of functions in series. + +__Arguments__ + +* `tasks` - An array of functions to run. + +__Example__ + +```js +var iterator = async.iterator([ + function(){ sys.p('one'); }, + function(){ sys.p('two'); }, + function(){ sys.p('three'); } +]); + +node> var iterator2 = iterator(); +'one' +node> var iterator3 = iterator2(); +'two' +node> iterator3(); +'three' +node> var nextfn = iterator2.next(); +node> nextfn(); +'three' +``` + +--------------------------------------- + +<a name="apply" /> +### apply(function, arguments..) + +Creates a continuation function with some arguments already applied. + +Useful as a shorthand when combined with other control flow functions. Any arguments +passed to the returned function are added to the arguments originally passed +to apply. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to automatically apply when the + continuation is called. + +__Example__ + +```js +// using apply + +async.parallel([ + async.apply(fs.writeFile, 'testfile1', 'test1'), + async.apply(fs.writeFile, 'testfile2', 'test2'), +]); + + +// the same process without using apply + +async.parallel([ + function(callback){ + fs.writeFile('testfile1', 'test1', callback); + }, + function(callback){ + fs.writeFile('testfile2', 'test2', callback); + } +]); +``` + +It's possible to pass any number of additional arguments when calling the +continuation: + +```js +node> var fn = async.apply(sys.puts, 'one'); +node> fn('two', 'three'); +one +two +three +``` + +--------------------------------------- + +<a name="nextTick" /> +### nextTick(callback), setImmediate(callback) + +Calls `callback` on a later loop around the event loop. In Node.js this just +calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)` +if available, otherwise `setTimeout(callback, 0)`, which means other higher priority +events may precede the execution of `callback`. + +This is used internally for browser-compatibility purposes. + +__Arguments__ + +* `callback` - The function to call on a later loop around the event loop. + +__Example__ + +```js +var call_order = []; +async.nextTick(function(){ + call_order.push('two'); + // call_order now equals ['one','two'] +}); +call_order.push('one') +``` + +<a name="times" /> +### times(n, callback) + +Calls the `callback` function `n` times, and accumulates results in the same manner +you would use with [`map`](#map). + +__Arguments__ + +* `n` - The number of times to run the function. +* `iterator` - The function to call `n` times. +* `callback` - see [`map`](#map) + +__Example__ + +```js +// Pretend this is some complicated async factory +var createUser = function(id, callback) { + callback(null, { + id: 'user' + id + }) +} +// generate 5 users +async.times(5, function(n, next){ + createUser(n, function(err, user) { + next(err, user) + }) +}, function(err, users) { + // we should now have 5 users +}); +``` + +<a name="timesSeries" /> +### timesSeries(n, callback) + +The same as [`times`](#times), only the iterator is applied to each item in `arr` in +series. The next `iterator` is only called once the current one has completed. +The results array will be in the same order as the original. + + +## Utils + +<a name="memoize" /> +### memoize(fn, [hasher]) + +Caches the results of an `async` function. When creating a hash to store function +results against, the callback is omitted from the hash and an optional hash +function can be used. + +If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function. + +The cache of results is exposed as the `memo` property of the function returned +by `memoize`. + +__Arguments__ + +* `fn` - The function to proxy and cache results from. +* `hasher` - An optional function for generating a custom hash for storing + results. It has all the arguments applied to it apart from the callback, and + must be synchronous. + +__Example__ + +```js +var slow_fn = function (name, callback) { + // do something + callback(null, result); +}; +var fn = async.memoize(slow_fn); + +// fn can now be used as if it were slow_fn +fn('some name', function () { + // callback +}); +``` + +<a name="unmemoize" /> +### unmemoize(fn) + +Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized +form. Handy for testing. + +__Arguments__ + +* `fn` - the memoized function + +<a name="log" /> +### log(function, arguments) + +Logs the result of an `async` function to the `console`. Only works in Node.js or +in browsers that support `console.log` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.log` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, 'hello ' + name); + }, 1000); +}; +``` +```js +node> async.log(hello, 'world'); +'hello world' +``` + +--------------------------------------- + +<a name="dir" /> +### dir(function, arguments) + +Logs the result of an `async` function to the `console` using `console.dir` to +display the properties of the resulting object. Only works in Node.js or +in browsers that support `console.dir` and `console.error` (such as FF and Chrome). +If multiple arguments are returned from the async function, `console.dir` is +called on each argument in order. + +__Arguments__ + +* `function` - The function you want to eventually apply all arguments to. +* `arguments...` - Any number of arguments to apply to the function. + +__Example__ + +```js +var hello = function(name, callback){ + setTimeout(function(){ + callback(null, {hello: name}); + }, 1000); +}; +``` +```js +node> async.dir(hello, 'world'); +{hello: 'world'} +``` + +--------------------------------------- + +<a name="noConflict" /> +### noConflict() + +Changes the value of `async` back to its original value, returning a reference to the +`async` object. diff --git a/node_modules/winston/node_modules/async/bower.json b/node_modules/winston/node_modules/async/bower.json new file mode 100644 index 0000000..9e4156d --- /dev/null +++ b/node_modules/winston/node_modules/async/bower.json @@ -0,0 +1,40 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "1.0.0", + "main": "lib/async.js", + "keywords": [ + "async", + "callback", + "utility", + "module" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/caolan/async.git" + }, + "devDependencies": { + "benchmark": "~1.0.0", + "jshint": "~2.7.0", + "lodash": ">=2.4.1", + "mkdirp": "~0.5.1", + "nodeunit": ">0.0.0", + "uglify-js": "1.2.x" + }, + "moduleType": [ + "amd", + "globals", + "node" + ], + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ], + "authors": [ + "Caolan McMahon" + ] +}
\ No newline at end of file diff --git a/node_modules/winston/node_modules/async/component.json b/node_modules/winston/node_modules/async/component.json new file mode 100644 index 0000000..c876b0a --- /dev/null +++ b/node_modules/winston/node_modules/async/component.json @@ -0,0 +1,17 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "version": "1.0.0", + "keywords": [ + "async", + "callback", + "utility", + "module" + ], + "license": "MIT", + "main": "lib/async.js", + "repository": "caolan/async", + "scripts": [ + "lib/async.js" + ] +}
\ No newline at end of file diff --git a/node_modules/winston/node_modules/async/lib/async.js b/node_modules/winston/node_modules/async/lib/async.js new file mode 100644 index 0000000..1e76ee8 --- /dev/null +++ b/node_modules/winston/node_modules/async/lib/async.js @@ -0,0 +1,1283 @@ +/*! + * async + * https://github.com/caolan/async + * + * Copyright 2010-2014 Caolan McMahon + * Released under the MIT license + */ +(function () { + + var async = {}; + var noop = function () {}; + + // global on the server, window in the browser + var root, previous_async; + + if (typeof window == 'object' && this === window) { + root = window; + } + else if (typeof global == 'object' && this === global) { + root = global; + } + else { + root = this; + } + + if (root != null) { + previous_async = root.async; + } + + async.noConflict = function () { + root.async = previous_async; + return async; + }; + + function only_once(fn) { + var called = false; + return function() { + if (called) throw new Error("Callback was already called."); + called = true; + fn.apply(root, arguments); + }; + } + + //// cross-browser compatiblity functions //// + + var _toString = Object.prototype.toString; + + var _isArray = Array.isArray || function (obj) { + return _toString.call(obj) === '[object Array]'; + }; + + var _each = function (arr, iterator) { + var index = -1, + length = arr.length; + + while (++index < length) { + iterator(arr[index], index, arr); + } + }; + + var _map = function (arr, iterator) { + var index = -1, + length = arr.length, + result = Array(length); + + while (++index < length) { + result[index] = iterator(arr[index], index, arr); + } + return result; + }; + + var _reduce = function (arr, iterator, memo) { + _each(arr, function (x, i, a) { + memo = iterator(memo, x, i, a); + }); + return memo; + }; + + var _forEachOf = function (object, iterator) { + _each(_keys(object), function (key) { + iterator(object[key], key); + }); + }; + + var _keys = Object.keys || function (obj) { + var keys = []; + for (var k in obj) { + if (obj.hasOwnProperty(k)) { + keys.push(k); + } + } + return keys; + }; + + var _baseSlice = function (arr, start) { + start = start || 0; + var index = -1; + var length = arr.length; + + if (start) { + length -= start; + length = length < 0 ? 0 : length; + } + var result = Array(length); + + while (++index < length) { + result[index] = arr[index + start]; + } + return result; + }; + + //// exported async module functions //// + + //// nextTick implementation with browser-compatible fallback //// + + // capture the global reference to guard against fakeTimer mocks + var _setImmediate; + if (typeof setImmediate === 'function') { + _setImmediate = setImmediate; + } + + if (typeof process === 'undefined' || !(process.nextTick)) { + if (_setImmediate) { + async.nextTick = function (fn) { + // not a direct alias for IE10 compatibility + _setImmediate(fn); + }; + async.setImmediate = async.nextTick; + } + else { + async.nextTick = function (fn) { + setTimeout(fn, 0); + }; + async.setImmediate = async.nextTick; + } + } + else { + async.nextTick = process.nextTick; + if (_setImmediate) { + async.setImmediate = function (fn) { + // not a direct alias for IE10 compatibility + _setImmediate(fn); + }; + } + else { + async.setImmediate = async.nextTick; + } + } + + async.each = function (arr, iterator, callback) { + callback = callback || noop; + if (!arr.length) { + return callback(); + } + var completed = 0; + _each(arr, function (x) { + iterator(x, only_once(done) ); + }); + function done(err) { + if (err) { + callback(err); + callback = noop; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(); + } + } + } + }; + async.forEach = async.each; + + async.eachSeries = function (arr, iterator, callback) { + callback = callback || noop; + if (!arr.length) { + return callback(); + } + var completed = 0; + var iterate = function () { + iterator(arr[completed], function (err) { + if (err) { + callback(err); + callback = noop; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(); + } + else { + iterate(); + } + } + }); + }; + iterate(); + }; + async.forEachSeries = async.eachSeries; + + + async.eachLimit = function (arr, limit, iterator, callback) { + var fn = _eachLimit(limit); + fn.apply(null, [arr, iterator, callback]); + }; + async.forEachLimit = async.eachLimit; + + var _eachLimit = function (limit) { + + return function (arr, iterator, callback) { + callback = callback || noop; + if (!arr.length || limit <= 0) { + return callback(); + } + var completed = 0; + var started = 0; + var running = 0; + + (function replenish () { + if (completed >= arr.length) { + return callback(); + } + + while (running < limit && started < arr.length) { + started += 1; + running += 1; + iterator(arr[started - 1], function (err) { + if (err) { + callback(err); + callback = noop; + } + else { + completed += 1; + running -= 1; + if (completed >= arr.length) { + callback(); + } + else { + replenish(); + } + } + }); + } + })(); + }; + }; + + + + async.forEachOf = async.eachOf = function (object, iterator, callback) { + callback = callback || function () {}; + var size = object.length || _keys(object).length; + var completed = 0; + if (!size) { + return callback(); + } + _forEachOf(object, function (value, key) { + iterator(object[key], key, function (err) { + if (err) { + callback(err); + callback = function () {}; + } else { + completed += 1; + if (completed === size) { + callback(null); + } + } + }); + }); + }; + + async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { + callback = callback || function () {}; + var keys = _keys(obj); + var size = keys.length; + if (!size) { + return callback(); + } + var completed = 0; + var iterate = function () { + var sync = true; + var key = keys[completed]; + iterator(obj[key], key, function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + if (completed >= size) { + callback(null); + } + else { + if (sync) { + async.nextTick(iterate); + } + else { + iterate(); + } + } + } + }); + sync = false; + }; + iterate(); + }; + + + + async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { + _forEachOfLimit(limit)(obj, iterator, callback); + }; + + var _forEachOfLimit = function (limit) { + + return function (obj, iterator, callback) { + callback = callback || function () {}; + var keys = _keys(obj); + var size = keys.length; + if (!size || limit <= 0) { + return callback(); + } + var completed = 0; + var started = 0; + var running = 0; + + (function replenish () { + if (completed >= size) { + return callback(); + } + + while (running < limit && started < size) { + started += 1; + running += 1; + var key = keys[started - 1]; + iterator(obj[key], key, function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + running -= 1; + if (completed >= size) { + callback(); + } + else { + replenish(); + } + } + }); + } + })(); + }; + }; + + + var doParallel = function (fn) { + return function () { + var args = _baseSlice(arguments); + return fn.apply(null, [async.each].concat(args)); + }; + }; + var doParallelLimit = function(limit, fn) { + return function () { + var args = _baseSlice(arguments); + return fn.apply(null, [_eachLimit(limit)].concat(args)); + }; + }; + var doSeries = function (fn) { + return function () { + var args = _baseSlice(arguments); + return fn.apply(null, [async.eachSeries].concat(args)); + }; + }; + + + var _asyncMap = function (eachfn, arr, iterator, callback) { + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + if (!callback) { + eachfn(arr, function (x, callback) { + iterator(x.value, function (err) { + callback(err); + }); + }); + } else { + var results = []; + eachfn(arr, function (x, callback) { + iterator(x.value, function (err, v) { + results[x.index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + async.map = doParallel(_asyncMap); + async.mapSeries = doSeries(_asyncMap); + async.mapLimit = function (arr, limit, iterator, callback) { + return _mapLimit(limit)(arr, iterator, callback); + }; + + var _mapLimit = function(limit) { + return doParallelLimit(limit, _asyncMap); + }; + + // reduce only has a series version, as doing reduce in parallel won't + // work in many situations. + async.reduce = function (arr, memo, iterator, callback) { + async.eachSeries(arr, function (x, callback) { + iterator(memo, x, function (err, v) { + memo = v; + callback(err); + }); + }, function (err) { + callback(err, memo); + }); + }; + // inject alias + async.inject = async.reduce; + // foldl alias + async.foldl = async.reduce; + + async.reduceRight = function (arr, memo, iterator, callback) { + var reversed = _map(arr, function (x) { + return x; + }).reverse(); + async.reduce(reversed, memo, iterator, callback); + }; + // foldr alias + async.foldr = async.reduceRight; + + var _filter = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.filter = doParallel(_filter); + async.filterSeries = doSeries(_filter); + // select alias + async.select = async.filter; + async.selectSeries = async.filterSeries; + + var _reject = function (eachfn, arr, iterator, callback) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + eachfn(arr, function (x, callback) { + iterator(x.value, function (v) { + if (!v) { + results.push(x); + } + callback(); + }); + }, function (err) { + callback(_map(results.sort(function (a, b) { + return a.index - b.index; + }), function (x) { + return x.value; + })); + }); + }; + async.reject = doParallel(_reject); + async.rejectSeries = doSeries(_reject); + + var _detect = function (eachfn, arr, iterator, main_callback) { + eachfn(arr, function (x, callback) { + iterator(x, function (result) { + if (result) { + main_callback(x); + main_callback = noop; + } + else { + callback(); + } + }); + }, function (err) { + main_callback(); + }); + }; + async.detect = doParallel(_detect); + async.detectSeries = doSeries(_detect); + + async.some = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (v) { + main_callback(true); + main_callback = noop; + } + callback(); + }); + }, function (err) { + main_callback(false); + }); + }; + // any alias + async.any = async.some; + + async.every = function (arr, iterator, main_callback) { + async.each(arr, function (x, callback) { + iterator(x, function (v) { + if (!v) { + main_callback(false); + main_callback = noop; + } + callback(); + }); + }, function (err) { + main_callback(true); + }); + }; + // all alias + async.all = async.every; + + async.sortBy = function (arr, iterator, callback) { + async.map(arr, function (x, callback) { + iterator(x, function (err, criteria) { + if (err) { + callback(err); + } + else { + callback(null, {value: x, criteria: criteria}); + } + }); + }, function (err, results) { + if (err) { + return callback(err); + } + else { + var fn = function (left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }; + callback(null, _map(results.sort(fn), function (x) { + return x.value; + })); + } + }); + }; + + async.auto = function (tasks, callback) { + callback = callback || noop; + var keys = _keys(tasks); + var remainingTasks = keys.length; + if (!remainingTasks) { + return callback(); + } + + var results = {}; + + var listeners = []; + var addListener = function (fn) { + listeners.unshift(fn); + }; + var removeListener = function (fn) { + for (var i = 0; i < listeners.length; i += 1) { + if (listeners[i] === fn) { + listeners.splice(i, 1); + return; + } + } + }; + var taskComplete = function () { + remainingTasks--; + _each(listeners.slice(0), function (fn) { + fn(); + }); + }; + + addListener(function () { + if (!remainingTasks) { + var theCallback = callback; + // prevent final callback from calling itself if it errors + callback = noop; + + theCallback(null, results); + } + }); + + _each(keys, function (k) { + var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; + var taskCallback = function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + if (err) { + var safeResults = {}; + _each(_keys(results), function(rkey) { + safeResults[rkey] = results[rkey]; + }); + safeResults[k] = args; + callback(err, safeResults); + // stop subsequent errors hitting callback multiple times + callback = noop; + } + else { + results[k] = args; + async.setImmediate(taskComplete); + } + }; + var requires = task.slice(0, Math.abs(task.length - 1)) || []; + // prevent dead-locks + var len = requires.length; + var dep; + while (len--) { + if (!(dep = tasks[requires[len]])) { + throw new Error('Has inexistant dependency'); + } + if (_isArray(dep) && !!~dep.indexOf(k)) { + throw new Error('Has cyclic dependencies'); + } + } + var ready = function () { + return _reduce(requires, function (a, x) { + return (a && results.hasOwnProperty(x)); + }, true) && !results.hasOwnProperty(k); + }; + if (ready()) { + task[task.length - 1](taskCallback, results); + } + else { + var listener = function () { + if (ready()) { + removeListener(listener); + task[task.length - 1](taskCallback, results); + } + }; + addListener(listener); + } + }); + }; + + async.retry = function(times, task, callback) { + var DEFAULT_TIMES = 5; + var attempts = []; + // Use defaults if times not passed + if (typeof times === 'function') { + callback = task; + task = times; + times = DEFAULT_TIMES; + } + // Make sure times is a number + times = parseInt(times, 10) || DEFAULT_TIMES; + var wrappedTask = function(wrappedCallback, wrappedResults) { + var retryAttempt = function(task, finalAttempt) { + return function(seriesCallback) { + task(function(err, result){ + seriesCallback(!err || finalAttempt, {err: err, result: result}); + }, wrappedResults); + }; + }; + while (times) { + attempts.push(retryAttempt(task, !(times-=1))); + } + async.series(attempts, function(done, data){ + data = data[data.length - 1]; + (wrappedCallback || callback)(data.err, data.result); + }); + }; + // If a callback is passed, run this as a controll flow + return callback ? wrappedTask() : wrappedTask; + }; + + async.waterfall = function (tasks, callback) { + callback = callback || noop; + if (!_isArray(tasks)) { + var err = new Error('First argument to waterfall must be an array of functions'); + return callback(err); + } + if (!tasks.length) { + return callback(); + } + var wrapIterator = function (iterator) { + return function (err) { + if (err) { + callback.apply(null, arguments); + callback = noop; + } + else { + var args = _baseSlice(arguments, 1); + var next = iterator.next(); + if (next) { + args.push(wrapIterator(next)); + } + else { + args.push(callback); + } + async.setImmediate(function () { + iterator.apply(null, args); + }); + } + }; + }; + wrapIterator(async.iterator(tasks))(); + }; + + var _parallel = function(eachfn, tasks, callback) { + callback = callback || noop; + if (_isArray(tasks)) { + eachfn.map(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + eachfn.each(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.parallel = function (tasks, callback) { + _parallel({ map: async.map, each: async.each }, tasks, callback); + }; + + async.parallelLimit = function(tasks, limit, callback) { + _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); + }; + + async.series = function (tasks, callback) { + callback = callback || noop; + if (_isArray(tasks)) { + async.mapSeries(tasks, function (fn, callback) { + if (fn) { + fn(function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + callback.call(null, err, args); + }); + } + }, callback); + } + else { + var results = {}; + async.eachSeries(_keys(tasks), function (k, callback) { + tasks[k](function (err) { + var args = _baseSlice(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + } + }; + + async.iterator = function (tasks) { + var makeCallback = function (index) { + var fn = function () { + if (tasks.length) { + tasks[index].apply(null, arguments); + } + return fn.next(); + }; + fn.next = function () { + return (index < tasks.length - 1) ? makeCallback(index + 1): null; + }; + return fn; + }; + return makeCallback(0); + }; + + async.apply = function (fn) { + var args = _baseSlice(arguments, 1); + return function () { + return fn.apply( + null, args.concat(_baseSlice(arguments)) + ); + }; + }; + + var _concat = function (eachfn, arr, fn, callback) { + var r = []; + eachfn(arr, function (x, cb) { + fn(x, function (err, y) { + r = r.concat(y || []); + cb(err); + }); + }, function (err) { + callback(err, r); + }); + }; + async.concat = doParallel(_concat); + async.concatSeries = doSeries(_concat); + + async.whilst = function (test, iterator, callback) { + if (test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.whilst(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doWhilst = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + var args = _baseSlice(arguments, 1); + if (test.apply(null, args)) { + async.doWhilst(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.until = function (test, iterator, callback) { + if (!test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.until(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.doUntil = function (iterator, test, callback) { + iterator(function (err) { + if (err) { + return callback(err); + } + var args = _baseSlice(arguments, 1); + if (!test.apply(null, args)) { + async.doUntil(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.queue = function (worker, concurrency) { + if (concurrency === undefined) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + function _insert(q, data, pos, callback) { + if (!q.started){ + q.started = true; + } + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + if (q.drain) { + q.drain(); + } + }); + } + _each(data, function(task) { + var item = { + data: task, + callback: typeof callback === 'function' ? callback : null + }; + + if (pos) { + q.tasks.unshift(item); + } else { + q.tasks.push(item); + } + + if (q.saturated && q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + var workers = 0; + var q = { + tasks: [], + concurrency: concurrency, + saturated: null, + empty: null, + drain: null, + started: false, + paused: false, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + kill: function () { + q.drain = null; + q.tasks = []; + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + if (!q.paused && workers < q.concurrency && q.tasks.length) { + var task = q.tasks.shift(); + if (q.empty && q.tasks.length === 0) { + q.empty(); + } + workers += 1; + var next = function () { + workers -= 1; + if (task.callback) { + task.callback.apply(task, arguments); + } + if (q.drain && q.tasks.length + workers === 0) { + q.drain(); + } + q.process(); + }; + var cb = only_once(next); + worker(task.data, cb); + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + }, + idle: function() { + return q.tasks.length + workers === 0; + }, + pause: function () { + if (q.paused === true) { return; } + q.paused = true; + }, + resume: function () { + if (q.paused === false) { return; } + q.paused = false; + var resumeCount = Math.min(q.concurrency, q.tasks.length); + // Need to call q.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= resumeCount; w++) { + async.setImmediate(q.process); + } + } + }; + return q; + }; + + async.priorityQueue = function (worker, concurrency) { + + function _compareTasks(a, b){ + return a.priority - b.priority; + } + + function _binarySearch(sequence, item, compare) { + var beg = -1, + end = sequence.length - 1; + while (beg < end) { + var mid = beg + ((end - beg + 1) >>> 1); + if (compare(item, sequence[mid]) >= 0) { + beg = mid; + } else { + end = mid - 1; + } + } + return beg; + } + + function _insert(q, data, priority, callback) { + if (!q.started){ + q.started = true; + } + if (!_isArray(data)) { + data = [data]; + } + if(data.length === 0) { + // call drain immediately if there are no tasks + return async.setImmediate(function() { + if (q.drain) { + q.drain(); + } + }); + } + _each(data, function(task) { + var item = { + data: task, + priority: priority, + callback: typeof callback === 'function' ? callback : null + }; + + q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); + + if (q.saturated && q.tasks.length === q.concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + // Start with a normal queue + var q = async.queue(worker, concurrency); + + // Override push to accept second parameter representing priority + q.push = function (data, priority, callback) { + _insert(q, data, priority, callback); + }; + + // Remove unshift function + delete q.unshift; + + return q; + }; + + async.cargo = function (worker, payload) { + var working = false, + tasks = []; + + var cargo = { + tasks: tasks, + payload: payload, + saturated: null, + empty: null, + drain: null, + drained: true, + push: function (data, callback) { + if (!_isArray(data)) { + data = [data]; + } + _each(data, function(task) { + tasks.push({ + data: task, + callback: typeof callback === 'function' ? callback : null + }); + cargo.drained = false; + if (cargo.saturated && tasks.length === payload) { + cargo.saturated(); + } + }); + async.setImmediate(cargo.process); + }, + process: function process() { + if (working) return; + if (tasks.length === 0) { + if(cargo.drain && !cargo.drained) cargo.drain(); + cargo.drained = true; + return; + } + + var ts = typeof payload === 'number' ? + tasks.splice(0, payload) : + tasks.splice(0, tasks.length); + + var ds = _map(ts, function (task) { + return task.data; + }); + + if(cargo.empty) cargo.empty(); + working = true; + worker(ds, function () { + working = false; + + var args = arguments; + _each(ts, function (data) { + if (data.callback) { + data.callback.apply(null, args); + } + }); + + process(); + }); + }, + length: function () { + return tasks.length; + }, + running: function () { + return working; + } + }; + return cargo; + }; + + var _console_fn = function (name) { + return function (fn) { + var args = _baseSlice(arguments, 1); + fn.apply(null, args.concat([function (err) { + var args = _baseSlice(arguments, 1); + if (typeof console !== 'undefined') { + if (err) { + if (console.error) { + console.error(err); + } + } + else if (console[name]) { + _each(args, function (x) { + console[name](x); + }); + } + } + }])); + }; + }; + async.log = _console_fn('log'); + async.dir = _console_fn('dir'); + /*async.info = _console_fn('info'); + async.warn = _console_fn('warn'); + async.error = _console_fn('error');*/ + + async.memoize = function (fn, hasher) { + var memo = {}; + var queues = {}; + hasher = hasher || function (x) { + return x; + }; + var memoized = function () { + var args = _baseSlice(arguments); + var callback = args.pop(); + var key = hasher.apply(null, args); + if (key in memo) { + async.nextTick(function () { + callback.apply(null, memo[key]); + }); + } + else if (key in queues) { + queues[key].push(callback); + } + else { + queues[key] = [callback]; + fn.apply(null, args.concat([function () { + memo[key] = _baseSlice(arguments); + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i].apply(null, arguments); + } + }])); + } + }; + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + }; + + async.unmemoize = function (fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + }; + + async.times = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.map(counter, iterator, callback); + }; + + async.timesSeries = function (count, iterator, callback) { + var counter = []; + for (var i = 0; i < count; i++) { + counter.push(i); + } + return async.mapSeries(counter, iterator, callback); + }; + + async.seq = function (/* functions... */) { + var fns = arguments; + return function () { + var that = this; + var args = _baseSlice(arguments); + var callback = args.pop(); + async.reduce(fns, args, function (newargs, fn, cb) { + fn.apply(that, newargs.concat([function () { + var err = arguments[0]; + var nextargs = _baseSlice(arguments, 1); + cb(err, nextargs); + }])); + }, + function (err, results) { + callback.apply(that, [err].concat(results)); + }); + }; + }; + + async.compose = function (/* functions... */) { + return async.seq.apply(null, Array.prototype.reverse.call(arguments)); + }; + + var _applyEach = function (eachfn, fns /*args...*/) { + var go = function () { + var that = this; + var args = _baseSlice(arguments); + var callback = args.pop(); + return eachfn(fns, function (fn, cb) { + fn.apply(that, args.concat([cb])); + }, + callback); + }; + if (arguments.length > 2) { + var args = _baseSlice(arguments, 2); + return go.apply(this, args); + } + else { + return go; + } + }; + async.applyEach = doParallel(_applyEach); + async.applyEachSeries = doSeries(_applyEach); + + async.forever = function (fn, callback) { + function next(err) { + if (err) { + if (callback) { + return callback(err); + } + throw err; + } + fn(next); + } + next(); + }; + + // Node.js + if (typeof module !== 'undefined' && module.exports) { + module.exports = async; + } + // AMD / RequireJS + else if (typeof define !== 'undefined' && define.amd) { + define([], function () { + return async; + }); + } + // included directly via <script> tag + else { + root.async = async; + } + +}()); diff --git a/node_modules/winston/node_modules/async/package.json b/node_modules/winston/node_modules/async/package.json new file mode 100644 index 0000000..cc6e6bc --- /dev/null +++ b/node_modules/winston/node_modules/async/package.json @@ -0,0 +1,85 @@ +{ + "_from": "async@~1.0.0", + "_id": "async@1.0.0", + "_inBundle": false, + "_integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=", + "_location": "/winston/async", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "async@~1.0.0", + "name": "async", + "escapedName": "async", + "rawSpec": "~1.0.0", + "saveSpec": null, + "fetchSpec": "~1.0.0" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "_shasum": "f8fc04ca3a13784ade9e1641af98578cfbd647a9", + "_spec": "async@~1.0.0", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/winston", + "author": { + "name": "Caolan McMahon" + }, + "bugs": { + "url": "https://github.com/caolan/async/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Higher-order functions and common patterns for asynchronous code", + "devDependencies": { + "benchmark": "~1.0.0", + "jshint": "~2.7.0", + "lodash": ">=2.4.1", + "mkdirp": "~0.5.1", + "nodeunit": ">0.0.0", + "uglify-js": "1.2.x" + }, + "homepage": "https://github.com/caolan/async#readme", + "jam": { + "main": "lib/async.js", + "include": [ + "lib/async.js", + "README.md", + "LICENSE" + ], + "categories": [ + "Utilities" + ] + }, + "keywords": [ + "async", + "callback", + "utility", + "module" + ], + "license": "MIT", + "main": "lib/async.js", + "name": "async", + "repository": { + "type": "git", + "url": "git+https://github.com/caolan/async.git" + }, + "scripts": { + "lint": "jshint lib/*.js test/*.js perf/*.js", + "test": "npm run-script lint && nodeunit test/test-async.js" + }, + "spm": { + "main": "lib/async.js" + }, + "version": "1.0.0", + "volo": { + "main": "lib/async.js", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] + } +} diff --git a/node_modules/winston/node_modules/async/support/sync-package-managers.js b/node_modules/winston/node_modules/async/support/sync-package-managers.js new file mode 100644 index 0000000..5b26119 --- /dev/null +++ b/node_modules/winston/node_modules/async/support/sync-package-managers.js @@ -0,0 +1,53 @@ +#!/usr/bin/env node + +// This should probably be its own module but complaints about bower/etc. +// support keep coming up and I'd rather just enable the workflow here for now +// and figure out where this should live later. -- @beaugunderson + +var fs = require('fs'); +var _ = require('lodash'); + +var packageJson = require('../package.json'); + +var IGNORES = ['**/.*', 'node_modules', 'bower_components', 'test', 'tests']; +var INCLUDES = ['lib/async.js', 'README.md', 'LICENSE']; +var REPOSITORY_NAME = 'caolan/async'; + +packageJson.jam = { + main: packageJson.main, + include: INCLUDES, + categories: ['Utilities'] +}; + +packageJson.spm = { + main: packageJson.main +}; + +packageJson.volo = { + main: packageJson.main, + ignore: IGNORES +}; + +var bowerSpecific = { + moduleType: ['amd', 'globals', 'node'], + ignore: IGNORES, + authors: [packageJson.author] +}; + +var bowerInclude = ['name', 'description', 'version', 'main', 'keywords', + 'license', 'homepage', 'repository', 'devDependencies']; + +var componentSpecific = { + repository: REPOSITORY_NAME, + scripts: [packageJson.main] +}; + +var componentInclude = ['name', 'description', 'version', 'keywords', + 'license', 'main']; + +var bowerJson = _.merge({}, _.pick(packageJson, bowerInclude), bowerSpecific); +var componentJson = _.merge({}, _.pick(packageJson, componentInclude), componentSpecific); + +fs.writeFileSync('./bower.json', JSON.stringify(bowerJson, null, 2)); +fs.writeFileSync('./component.json', JSON.stringify(componentJson, null, 2)); +fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, 2)); diff --git a/node_modules/winston/node_modules/colors/.travis.yml b/node_modules/winston/node_modules/colors/.travis.yml new file mode 100644 index 0000000..ec43125 --- /dev/null +++ b/node_modules/winston/node_modules/colors/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.11" + - "0.10" + - "0.8" + - "0.6"
\ No newline at end of file diff --git a/node_modules/winston/node_modules/colors/MIT-LICENSE.txt b/node_modules/winston/node_modules/colors/MIT-LICENSE.txt new file mode 100644 index 0000000..3de4e33 --- /dev/null +++ b/node_modules/winston/node_modules/colors/MIT-LICENSE.txt @@ -0,0 +1,23 @@ +Original Library + - Copyright (c) Marak Squires + +Additional Functionality + - Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE.
\ No newline at end of file diff --git a/node_modules/winston/node_modules/colors/ReadMe.md b/node_modules/winston/node_modules/colors/ReadMe.md new file mode 100644 index 0000000..beb5b14 --- /dev/null +++ b/node_modules/winston/node_modules/colors/ReadMe.md @@ -0,0 +1,167 @@ +# colors.js + +## get color and style in your node.js console + +<img src="https://github.com/Marak/colors.js/raw/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")); +``` + +*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.*
\ No newline at end of file diff --git a/node_modules/winston/node_modules/colors/examples/normal-usage.js b/node_modules/winston/node_modules/colors/examples/normal-usage.js new file mode 100644 index 0000000..2818741 --- /dev/null +++ b/node_modules/winston/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/winston/node_modules/colors/examples/safe-string.js b/node_modules/winston/node_modules/colors/examples/safe-string.js new file mode 100644 index 0000000..111b363 --- /dev/null +++ b/node_modules/winston/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/winston/node_modules/colors/lib/colors.js b/node_modules/winston/node_modules/colors/lib/colors.js new file mode 100644 index 0000000..59898de --- /dev/null +++ b/node_modules/winston/node_modules/colors/lib/colors.js @@ -0,0 +1,176 @@ +/* + +The MIT License (MIT) + +Original Library + - Copyright (c) Marak Squires + +Additional functionality + - Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +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) { + 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){ + 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/winston/node_modules/colors/lib/custom/trap.js b/node_modules/winston/node_modules/colors/lib/custom/trap.js new file mode 100644 index 0000000..3f09143 --- /dev/null +++ b/node_modules/winston/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/winston/node_modules/colors/lib/custom/zalgo.js b/node_modules/winston/node_modules/colors/lib/custom/zalgo.js new file mode 100644 index 0000000..4dc20c8 --- /dev/null +++ b/node_modules/winston/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"] = options["up"] || true; + options["mid"] = options["mid"] || true; + options["down"] = options["down"] || true; + options["size"] = 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.min = randomNumber(2); + counts.down = randomNumber(8); + break; + case 'maxi': + counts.up = randomNumber(16) + 3; + counts.min = 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); +} diff --git a/node_modules/winston/node_modules/colors/lib/extendStringPrototype.js b/node_modules/winston/node_modules/colors/lib/extendStringPrototype.js new file mode 100644 index 0000000..b6b5b03 --- /dev/null +++ b/node_modules/winston/node_modules/colors/lib/extendStringPrototype.js @@ -0,0 +1,118 @@ +var colors = require('./colors'), + styles = require('./styles'); + +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(""); + } + }; + + var stylize = function stylize (str, style) { + return styles[style].open + str + styles[style].close; + } + + 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 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 = exports[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/winston/node_modules/colors/lib/index.js b/node_modules/winston/node_modules/colors/lib/index.js new file mode 100644 index 0000000..96d2b84 --- /dev/null +++ b/node_modules/winston/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") +// +// +var extendStringPrototype = require('./extendStringPrototype')();
\ No newline at end of file diff --git a/node_modules/winston/node_modules/colors/lib/maps/america.js b/node_modules/winston/node_modules/colors/lib/maps/america.js new file mode 100644 index 0000000..a07d832 --- /dev/null +++ b/node_modules/winston/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/winston/node_modules/colors/lib/maps/rainbow.js b/node_modules/winston/node_modules/colors/lib/maps/rainbow.js new file mode 100644 index 0000000..a7ce24e --- /dev/null +++ b/node_modules/winston/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/winston/node_modules/colors/lib/maps/random.js b/node_modules/winston/node_modules/colors/lib/maps/random.js new file mode 100644 index 0000000..5cd101f --- /dev/null +++ b/node_modules/winston/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/winston/node_modules/colors/lib/maps/zebra.js b/node_modules/winston/node_modules/colors/lib/maps/zebra.js new file mode 100644 index 0000000..bf7dcde --- /dev/null +++ b/node_modules/winston/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/winston/node_modules/colors/lib/styles.js b/node_modules/winston/node_modules/colors/lib/styles.js new file mode 100644 index 0000000..067d590 --- /dev/null +++ b/node_modules/winston/node_modules/colors/lib/styles.js @@ -0,0 +1,77 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +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/winston/node_modules/colors/lib/system/supports-colors.js b/node_modules/winston/node_modules/colors/lib/system/supports-colors.js new file mode 100644 index 0000000..3e008aa --- /dev/null +++ b/node_modules/winston/node_modules/colors/lib/system/supports-colors.js @@ -0,0 +1,61 @@ +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +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/winston/node_modules/colors/package.json b/node_modules/winston/node_modules/colors/package.json new file mode 100644 index 0000000..61f4a07 --- /dev/null +++ b/node_modules/winston/node_modules/colors/package.json @@ -0,0 +1,54 @@ +{ + "_from": "colors@1.0.x", + "_id": "colors@1.0.3", + "_inBundle": false, + "_integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=", + "_location": "/winston/colors", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "colors@1.0.x", + "name": "colors", + "escapedName": "colors", + "rawSpec": "1.0.x", + "saveSpec": null, + "fetchSpec": "1.0.x" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "_shasum": "0433f44d809680fdeb60ed260f1b0c262e82a40b", + "_spec": "colors@1.0.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/winston", + "author": { + "name": "Marak Squires" + }, + "bugs": { + "url": "https://github.com/Marak/colors.js/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "get colors in your node.js console", + "engines": { + "node": ">=0.1.90" + }, + "homepage": "https://github.com/Marak/colors.js", + "keywords": [ + "ansi", + "terminal", + "colors" + ], + "license": "MIT", + "main": "./lib/index", + "name": "colors", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Marak/colors.js.git" + }, + "scripts": { + "test": "node tests/basic-test.js && node tests/safe-test.js" + }, + "version": "1.0.3" +} diff --git a/node_modules/winston/node_modules/colors/safe.js b/node_modules/winston/node_modules/colors/safe.js new file mode 100644 index 0000000..a6a1f3a --- /dev/null +++ b/node_modules/winston/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/winston/node_modules/colors/screenshots/colors.png b/node_modules/winston/node_modules/colors/screenshots/colors.png Binary files differnew file mode 100644 index 0000000..7200a62 --- /dev/null +++ b/node_modules/winston/node_modules/colors/screenshots/colors.png diff --git a/node_modules/winston/node_modules/colors/tests/basic-test.js b/node_modules/winston/node_modules/colors/tests/basic-test.js new file mode 100644 index 0000000..fda8af4 --- /dev/null +++ b/node_modules/winston/node_modules/colors/tests/basic-test.js @@ -0,0 +1,50 @@ +var assert = require('assert'), + colors = require('../lib/index'); + +var s = 'string'; + +function a(s, code) { + return '\x1B[' + code.toString() + 'm' + s + '\x1B[39m'; +} + +function aE(s, color, code) { + assert.equal(s[color], a(s, code)); + assert.equal(colors[color](s), a(s, code)); + assert.equal(s[color], colors[color](s)); + assert.equal(s[color].strip, s); + assert.equal(s[color].strip, colors.strip(s)); +} + +function h(s, color) { + return '<span style="color:' + color + ';">' + s + '</span>'; +} + +var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow']; +var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']); + +colors.mode = 'console'; +assert.equal(s.bold, '\x1B[1m' + s + '\x1B[22m'); +assert.equal(s.italic, '\x1B[3m' + s + '\x1B[23m'); +assert.equal(s.underline, '\x1B[4m' + s + '\x1B[24m'); +assert.equal(s.strikethrough, '\x1B[9m' + s + '\x1B[29m'); +assert.equal(s.inverse, '\x1B[7m' + s + '\x1B[27m'); + +assert.ok(s.rainbow); + +aE(s, 'white', 37); +aE(s, 'grey', 90); +aE(s, 'black', 30); +aE(s, 'blue', 34); +aE(s, 'cyan', 36); +aE(s, 'green', 32); +aE(s, 'magenta', 35); +aE(s, 'red', 31); +aE(s, 'yellow', 33); + +assert.equal(s, 'string'); + +colors.setTheme({error:'red'}); + +assert.equal(typeof("astring".red),'string'); +assert.equal(typeof("astring".error),'string'); + diff --git a/node_modules/winston/node_modules/colors/tests/safe-test.js b/node_modules/winston/node_modules/colors/tests/safe-test.js new file mode 100644 index 0000000..daad4f9 --- /dev/null +++ b/node_modules/winston/node_modules/colors/tests/safe-test.js @@ -0,0 +1,45 @@ +var assert = require('assert'), + colors = require('../safe'); + +var s = 'string'; + +function a(s, code) { + return '\x1B[' + code.toString() + 'm' + s + '\x1B[39m'; +} + +function aE(s, color, code) { + assert.equal(colors[color](s), a(s, code)); + assert.equal(colors.strip(s), s); +} + +function h(s, color) { + return '<span style="color:' + color + ';">' + s + '</span>'; +} + +var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow']; +var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']); + +colors.mode = 'console'; +assert.equal(colors.bold(s), '\x1B[1m' + s + '\x1B[22m'); +assert.equal(colors.italic(s), '\x1B[3m' + s + '\x1B[23m'); +assert.equal(colors.underline(s), '\x1B[4m' + s + '\x1B[24m'); +assert.equal(colors.strikethrough(s), '\x1B[9m' + s + '\x1B[29m'); +assert.equal(colors.inverse(s), '\x1B[7m' + s + '\x1B[27m'); + +assert.ok(colors.rainbow); + +aE(s, 'white', 37); +aE(s, 'grey', 90); +aE(s, 'black', 30); +aE(s, 'blue', 34); +aE(s, 'cyan', 36); +aE(s, 'green', 32); +aE(s, 'magenta', 35); +aE(s, 'red', 31); +aE(s, 'yellow', 33); + +assert.equal(s, 'string'); +colors.setTheme({error:'red'}); + +assert.equal(typeof(colors.red("astring")), 'string'); +assert.equal(typeof(colors.error("astring")), 'string');
\ No newline at end of file diff --git a/node_modules/winston/node_modules/colors/themes/generic-logging.js b/node_modules/winston/node_modules/colors/themes/generic-logging.js new file mode 100644 index 0000000..571972c --- /dev/null +++ b/node_modules/winston/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/winston/node_modules/pkginfo/.npmignore b/node_modules/winston/node_modules/pkginfo/.npmignore new file mode 100644 index 0000000..9303c34 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/.npmignore @@ -0,0 +1,2 @@ +node_modules/ +npm-debug.log
\ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/LICENSE b/node_modules/winston/node_modules/pkginfo/LICENSE new file mode 100644 index 0000000..ed4a4e7 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 Charlie Robbins. + +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/winston/node_modules/pkginfo/README.md b/node_modules/winston/node_modules/pkginfo/README.md new file mode 100644 index 0000000..7a363bf --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/README.md @@ -0,0 +1,86 @@ +# node-pkginfo + +An easy way to expose properties on a module from a package.json + +## Installation + +### Installing npm (node package manager) +``` + curl http://npmjs.org/install.sh | sh +``` + +### Installing pkginfo +``` + [sudo] npm install pkginfo +``` + +## Motivation +How often when writing node.js modules have you written the following line(s) of code? + +* Hard code your version string into your code + +``` js + exports.version = '0.1.0'; +``` + +* Programmatically expose the version from the package.json + +``` js + exports.version = require('/path/to/package.json').version; +``` + +In other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!** + +## Usage + +Using `pkginfo` is idiot-proof, just require and invoke it. + +``` js + var pkginfo = require('pkginfo')(module); + + console.dir(module.exports); +``` + +By invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). + +Here's a sample of the output: + +``` + { name: 'simple-app', + description: 'A test fixture for pkginfo', + version: '0.1.0', + author: 'Charlie Robbins <charlie.robbins@gmail.com>', + keywords: [ 'test', 'fixture' ], + main: './index.js', + scripts: { test: 'vows test/*-test.js --spec' }, + engines: { node: '>= 0.4.0' } } +``` + +### Expose specific properties +If you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function: + +``` js + var pkginfo = require('pkginfo')(module, 'version', 'author'); + + console.dir(module.exports); +``` + +``` + { version: '0.1.0', + author: 'Charlie Robbins <charlie.robbins@gmail.com>' } +``` + +If you're looking for further usage see the [examples][0] included in this repository. + +## Run Tests +Tests are written in [vows][1] and give complete coverage of all APIs. + +``` + vows test/*-test.js --spec +``` + +[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples +[1]: http://vowsjs.org + +#### Author: [Charlie Robbins](http://nodejitsu.com) +#### License: MIT diff --git a/node_modules/winston/node_modules/pkginfo/docs/docco.css b/node_modules/winston/node_modules/pkginfo/docs/docco.css new file mode 100644 index 0000000..bd54134 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/docs/docco.css @@ -0,0 +1,194 @@ +/*--------------------- Layout and Typography ----------------------------*/ +body { + font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; + font-size: 15px; + line-height: 22px; + color: #252519; + margin: 0; padding: 0; +} +a { + color: #261a3b; +} + a:visited { + color: #261a3b; + } +p { + margin: 0 0 15px 0; +} +h4, h5, h6 { + color: #333; + margin: 6px 0 6px 0; + font-size: 13px; +} + h2, h3 { + margin-bottom: 0; + color: #000; + } + h1 { + margin-top: 40px; + margin-bottom: 15px; + color: #000; + } +#container { + position: relative; +} +#background { + position: fixed; + top: 0; left: 525px; right: 0; bottom: 0; + background: #f5f5ff; + border-left: 1px solid #e5e5ee; + z-index: -1; +} +#jump_to, #jump_page { + background: white; + -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; + -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; + font: 10px Arial; + text-transform: uppercase; + cursor: pointer; + text-align: right; +} +#jump_to, #jump_wrapper { + position: fixed; + right: 0; top: 0; + padding: 5px 10px; +} + #jump_wrapper { + padding: 0; + display: none; + } + #jump_to:hover #jump_wrapper { + display: block; + } + #jump_page { + padding: 5px 0 3px; + margin: 0 0 25px 25px; + } + #jump_page .source { + display: block; + padding: 5px 10px; + text-decoration: none; + border-top: 1px solid #eee; + } + #jump_page .source:hover { + background: #f5f5ff; + } + #jump_page .source:first-child { + } +table td { + border: 0; + outline: 0; +} + td.docs, th.docs { + max-width: 450px; + min-width: 450px; + min-height: 5px; + padding: 10px 25px 1px 50px; + overflow-x: hidden; + vertical-align: top; + text-align: left; + } + .docs pre { + margin: 15px 0 15px; + padding-left: 15px; + } + .docs p tt, .docs p code { + background: #f8f8ff; + border: 1px solid #dedede; + font-size: 12px; + padding: 0 0.2em; + } + .pilwrap { + position: relative; + } + .pilcrow { + font: 12px Arial; + text-decoration: none; + color: #454545; + position: absolute; + top: 3px; left: -20px; + padding: 1px 2px; + opacity: 0; + -webkit-transition: opacity 0.2s linear; + } + td.docs:hover .pilcrow { + opacity: 1; + } + td.code, th.code { + padding: 14px 15px 16px 25px; + width: 100%; + vertical-align: top; + background: #f5f5ff; + border-left: 1px solid #e5e5ee; + } + pre, tt, code { + font-size: 12px; line-height: 18px; + font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; + margin: 0; padding: 0; + } + + +/*---------------------- Syntax Highlighting -----------------------------*/ +td.linenos { background-color: #f0f0f0; padding-right: 10px; } +span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } +body .hll { background-color: #ffffcc } +body .c { color: #408080; font-style: italic } /* Comment */ +body .err { border: 1px solid #FF0000 } /* Error */ +body .k { color: #954121 } /* Keyword */ +body .o { color: #666666 } /* Operator */ +body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ +body .cp { color: #BC7A00 } /* Comment.Preproc */ +body .c1 { color: #408080; font-style: italic } /* Comment.Single */ +body .cs { color: #408080; font-style: italic } /* Comment.Special */ +body .gd { color: #A00000 } /* Generic.Deleted */ +body .ge { font-style: italic } /* Generic.Emph */ +body .gr { color: #FF0000 } /* Generic.Error */ +body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ +body .gi { color: #00A000 } /* Generic.Inserted */ +body .go { color: #808080 } /* Generic.Output */ +body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ +body .gs { font-weight: bold } /* Generic.Strong */ +body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ +body .gt { color: #0040D0 } /* Generic.Traceback */ +body .kc { color: #954121 } /* Keyword.Constant */ +body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ +body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ +body .kp { color: #954121 } /* Keyword.Pseudo */ +body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ +body .kt { color: #B00040 } /* Keyword.Type */ +body .m { color: #666666 } /* Literal.Number */ +body .s { color: #219161 } /* Literal.String */ +body .na { color: #7D9029 } /* Name.Attribute */ +body .nb { color: #954121 } /* Name.Builtin */ +body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ +body .no { color: #880000 } /* Name.Constant */ +body .nd { color: #AA22FF } /* Name.Decorator */ +body .ni { color: #999999; font-weight: bold } /* Name.Entity */ +body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ +body .nf { color: #0000FF } /* Name.Function */ +body .nl { color: #A0A000 } /* Name.Label */ +body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ +body .nt { color: #954121; font-weight: bold } /* Name.Tag */ +body .nv { color: #19469D } /* Name.Variable */ +body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ +body .w { color: #bbbbbb } /* Text.Whitespace */ +body .mf { color: #666666 } /* Literal.Number.Float */ +body .mh { color: #666666 } /* Literal.Number.Hex */ +body .mi { color: #666666 } /* Literal.Number.Integer */ +body .mo { color: #666666 } /* Literal.Number.Oct */ +body .sb { color: #219161 } /* Literal.String.Backtick */ +body .sc { color: #219161 } /* Literal.String.Char */ +body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ +body .s2 { color: #219161 } /* Literal.String.Double */ +body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ +body .sh { color: #219161 } /* Literal.String.Heredoc */ +body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ +body .sx { color: #954121 } /* Literal.String.Other */ +body .sr { color: #BB6688 } /* Literal.String.Regex */ +body .s1 { color: #219161 } /* Literal.String.Single */ +body .ss { color: #19469D } /* Literal.String.Symbol */ +body .bp { color: #954121 } /* Name.Builtin.Pseudo */ +body .vc { color: #19469D } /* Name.Variable.Class */ +body .vg { color: #19469D } /* Name.Variable.Global */ +body .vi { color: #19469D } /* Name.Variable.Instance */ +body .il { color: #666666 } /* Literal.Number.Integer.Long */
\ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/docs/pkginfo.html b/node_modules/winston/node_modules/pkginfo/docs/pkginfo.html new file mode 100644 index 0000000..bf615fa --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/docs/pkginfo.html @@ -0,0 +1,101 @@ +<!DOCTYPE html> <html> <head> <title>pkginfo.js</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" media="all" href="docco.css" /> </head> <body> <div id="container"> <div id="background"></div> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th class="docs"> <h1> pkginfo.js </h1> </th> <th class="code"> </th> </tr> </thead> <tbody> <tr id="section-1"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-1">¶</a> </div> </td> <td class="code"> <div class="highlight"><pre><span class="cm">/*</span> +<span class="cm"> * pkginfo.js: Top-level include for the pkginfo module</span> +<span class="cm"> *</span> +<span class="cm"> * (C) 2011, Charlie Robbins</span> +<span class="cm"> *</span> +<span class="cm"> */</span> + +<span class="kd">var</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'fs'</span><span class="p">),</span> + <span class="nx">path</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'path'</span><span class="p">);</span></pre></div> </td> </tr> <tr id="section-2"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-2">¶</a> </div> <h3>function pkginfo ([options, 'property', 'property' ..])</h3> + +<h4>@pmodule {Module} Parent module to read from.</h4> + +<h4>@options {Object|Array|string} <strong>Optional</strong> Options used when exposing properties.</h4> + +<h4>@arguments {string...} <strong>Optional</strong> Specified properties to expose.</h4> + +<p>Exposes properties from the package.json file for the parent module on +it's exports. Valid usage:</p> + +<p><code>require('pkginfo')()</code></p> + +<p><code>require('pkginfo')('version', 'author');</code></p> + +<p><code>require('pkginfo')(['version', 'author']);</code></p> + +<p><code>require('pkginfo')({ include: ['version', 'author'] });</code></p> </td> <td class="code"> <div class="highlight"><pre><span class="kd">var</span> <span class="nx">pkginfo</span> <span class="o">=</span> <span class="nx">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">pmodule</span><span class="p">,</span> <span class="nx">options</span><span class="p">)</span> <span class="p">{</span> + <span class="kd">var</span> <span class="nx">args</span> <span class="o">=</span> <span class="p">[].</span><span class="nx">slice</span><span class="p">.</span><span class="nx">call</span><span class="p">(</span><span class="nx">arguments</span><span class="p">,</span> <span class="mi">2</span><span class="p">).</span><span class="nx">filter</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">arg</span><span class="p">)</span> <span class="p">{</span> + <span class="k">return</span> <span class="k">typeof</span> <span class="nx">arg</span> <span class="o">===</span> <span class="s1">'string'</span><span class="p">;</span> + <span class="p">});</span> + </pre></div> </td> </tr> <tr id="section-3"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-3">¶</a> </div> <p><strong>Parse variable arguments</strong></p> </td> <td class="code"> <div class="highlight"><pre> <span class="k">if</span> <span class="p">(</span><span class="nb">Array</span><span class="p">.</span><span class="nx">isArray</span><span class="p">(</span><span class="nx">options</span><span class="p">))</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-4"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-4">¶</a> </div> <p>If the options passed in is an Array assume that +it is the Array of properties to expose from the +on the package.json file on the parent module.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">options</span> <span class="o">=</span> <span class="p">{</span> <span class="nx">include</span><span class="o">:</span> <span class="nx">options</span> <span class="p">};</span> + <span class="p">}</span> + <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="k">typeof</span> <span class="nx">options</span> <span class="o">===</span> <span class="s1">'string'</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-5"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-5">¶</a> </div> <p>Otherwise if the first argument is a string, then +assume that it is the first property to expose from +the package.json file on the parent module.</p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">options</span> <span class="o">=</span> <span class="p">{</span> <span class="nx">include</span><span class="o">:</span> <span class="p">[</span><span class="nx">options</span><span class="p">]</span> <span class="p">};</span> + <span class="p">}</span> + </pre></div> </td> </tr> <tr id="section-6"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-6">¶</a> </div> <p><strong>Setup default options</strong></p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">options</span> <span class="o">=</span> <span class="nx">options</span> <span class="o">||</span> <span class="p">{</span> <span class="nx">include</span><span class="o">:</span> <span class="p">[]</span> <span class="p">};</span> + + <span class="k">if</span> <span class="p">(</span><span class="nx">args</span><span class="p">.</span><span class="nx">length</span> <span class="o">></span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span></pre></div> </td> </tr> <tr id="section-7"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-7">¶</a> </div> <p>If additional string arguments have been passed in +then add them to the properties to expose on the +parent module. </p> </td> <td class="code"> <div class="highlight"><pre> <span class="nx">options</span><span class="p">.</span><span class="nx">include</span> <span class="o">=</span> <span class="nx">options</span><span class="p">.</span><span class="nx">include</span><span class="p">.</span><span class="nx">concat</span><span class="p">(</span><span class="nx">args</span><span class="p">);</span> + <span class="p">}</span> + + <span class="kd">var</span> <span class="nx">pkg</span> <span class="o">=</span> <span class="nx">pkginfo</span><span class="p">.</span><span class="nx">read</span><span class="p">(</span><span class="nx">pmodule</span><span class="p">,</span> <span class="nx">options</span><span class="p">.</span><span class="nx">dir</span><span class="p">).</span><span class="kr">package</span><span class="p">;</span> + <span class="nb">Object</span><span class="p">.</span><span class="nx">keys</span><span class="p">(</span><span class="nx">pkg</span><span class="p">).</span><span class="nx">forEach</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">key</span><span class="p">)</span> <span class="p">{</span> + <span class="k">if</span> <span class="p">(</span><span class="nx">options</span><span class="p">.</span><span class="nx">include</span><span class="p">.</span><span class="nx">length</span> <span class="o">></span> <span class="mi">0</span> <span class="o">&&</span> <span class="o">!~</span><span class="nx">options</span><span class="p">.</span><span class="nx">include</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="nx">key</span><span class="p">))</span> <span class="p">{</span> + <span class="k">return</span><span class="p">;</span> + <span class="p">}</span> + + <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">pmodule</span><span class="p">.</span><span class="nx">exports</span><span class="p">[</span><span class="nx">key</span><span class="p">])</span> <span class="p">{</span> + <span class="nx">pmodule</span><span class="p">.</span><span class="nx">exports</span><span class="p">[</span><span class="nx">key</span><span class="p">]</span> <span class="o">=</span> <span class="nx">pkg</span><span class="p">[</span><span class="nx">key</span><span class="p">];</span> + <span class="p">}</span> + <span class="p">});</span> + + <span class="k">return</span> <span class="nx">pkginfo</span><span class="p">;</span> +<span class="p">};</span></pre></div> </td> </tr> <tr id="section-8"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-8">¶</a> </div> <h3>function find (dir)</h3> + +<h4>@pmodule {Module} Parent module to read from.</h4> + +<h4>@dir {string} <strong>Optional</strong> Directory to start search from.</h4> + +<p>Searches up the directory tree from <code>dir</code> until it finds a directory +which contains a <code>package.json</code> file. </p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">pkginfo</span><span class="p">.</span><span class="nx">find</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">pmodule</span><span class="p">,</span> <span class="nx">dir</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">dir</span> <span class="o">=</span> <span class="nx">dir</span> <span class="o">||</span> <span class="nx">pmodule</span><span class="p">.</span><span class="nx">filename</span><span class="p">;</span> + <span class="nx">dir</span> <span class="o">=</span> <span class="nx">path</span><span class="p">.</span><span class="nx">dirname</span><span class="p">(</span><span class="nx">dir</span><span class="p">);</span> + + <span class="kd">var</span> <span class="nx">files</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">readdirSync</span><span class="p">(</span><span class="nx">dir</span><span class="p">);</span> + + <span class="k">if</span> <span class="p">(</span><span class="o">~</span><span class="nx">files</span><span class="p">.</span><span class="nx">indexOf</span><span class="p">(</span><span class="s1">'package.json'</span><span class="p">))</span> <span class="p">{</span> + <span class="k">return</span> <span class="nx">path</span><span class="p">.</span><span class="nx">join</span><span class="p">(</span><span class="nx">dir</span><span class="p">,</span> <span class="s1">'package.json'</span><span class="p">);</span> + <span class="p">}</span> + + <span class="k">if</span> <span class="p">(</span><span class="nx">dir</span> <span class="o">===</span> <span class="s1">'/'</span><span class="p">)</span> <span class="p">{</span> + <span class="k">throw</span> <span class="k">new</span> <span class="nb">Error</span><span class="p">(</span><span class="s1">'Could not find package.json up from: '</span> <span class="o">+</span> <span class="nx">dir</span><span class="p">);</span> + <span class="p">}</span> + + <span class="k">return</span> <span class="nx">pkginfo</span><span class="p">.</span><span class="nx">find</span><span class="p">(</span><span class="nx">dir</span><span class="p">);</span> +<span class="p">};</span></pre></div> </td> </tr> <tr id="section-9"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-9">¶</a> </div> <h3>function read (pmodule, dir)</h3> + +<h4>@pmodule {Module} Parent module to read from.</h4> + +<h4>@dir {string} <strong>Optional</strong> Directory to start search from.</h4> + +<p>Searches up the directory tree from <code>dir</code> until it finds a directory +which contains a <code>package.json</code> file and returns the package information.</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">pkginfo</span><span class="p">.</span><span class="nx">read</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">pmodule</span><span class="p">,</span> <span class="nx">dir</span><span class="p">)</span> <span class="p">{</span> + <span class="nx">dir</span> <span class="o">=</span> <span class="nx">pkginfo</span><span class="p">.</span><span class="nx">find</span><span class="p">(</span><span class="nx">pmodule</span><span class="p">,</span> <span class="nx">dir</span><span class="p">);</span> + + <span class="kd">var</span> <span class="nx">data</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">readFileSync</span><span class="p">(</span><span class="nx">dir</span><span class="p">).</span><span class="nx">toString</span><span class="p">();</span> + + <span class="k">return</span> <span class="p">{</span> + <span class="nx">dir</span><span class="o">:</span> <span class="nx">dir</span><span class="p">,</span> + <span class="kr">package</span><span class="o">:</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> + <span class="p">};</span> +<span class="p">};</span></pre></div> </td> </tr> <tr id="section-10"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-10">¶</a> </div> <p>Call <code>pkginfo</code> on this module and expose version.</p> </td> <td class="code"> <div class="highlight"><pre><span class="nx">pkginfo</span><span class="p">(</span><span class="nx">module</span><span class="p">,</span> <span class="p">{</span> + <span class="nx">dir</span><span class="o">:</span> <span class="nx">__dirname</span><span class="p">,</span> + <span class="nx">include</span><span class="o">:</span> <span class="p">[</span><span class="s1">'version'</span><span class="p">],</span> + <span class="nx">target</span><span class="o">:</span> <span class="nx">pkginfo</span> +<span class="p">});</span> + +</pre></div> </td> </tr> </tbody> </table> </div> </body> </html>
\ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/all-properties.js b/node_modules/winston/node_modules/pkginfo/examples/all-properties.js new file mode 100644 index 0000000..fd1d831 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/examples/all-properties.js @@ -0,0 +1,19 @@ +/* + * all-properties.js: Sample of including all properties from a package.json file + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + pkginfo = require('../lib/pkginfo')(module); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/array-argument.js b/node_modules/winston/node_modules/pkginfo/examples/array-argument.js new file mode 100644 index 0000000..b1b6848 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/examples/array-argument.js @@ -0,0 +1,20 @@ +/* + * array-argument.js: Sample of including specific properties from a package.json file + * using Array argument syntax. + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + pkginfo = require('../lib/pkginfo')(module, ['version', 'author']); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/multiple-properties.js b/node_modules/winston/node_modules/pkginfo/examples/multiple-properties.js new file mode 100644 index 0000000..b4b5fd6 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/examples/multiple-properties.js @@ -0,0 +1,19 @@ +/* + * multiple-properties.js: Sample of including multiple properties from a package.json file + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + pkginfo = require('../lib/pkginfo')(module, 'version', 'author'); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/object-argument.js b/node_modules/winston/node_modules/pkginfo/examples/object-argument.js new file mode 100644 index 0000000..28420c8 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/examples/object-argument.js @@ -0,0 +1,22 @@ +/* + * object-argument.js: Sample of including specific properties from a package.json file + * using Object argument syntax. + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + pkginfo = require('../lib/pkginfo')(module, { + include: ['version', 'author'] + }); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/package.json b/node_modules/winston/node_modules/pkginfo/examples/package.json new file mode 100644 index 0000000..1f2f01c --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/examples/package.json @@ -0,0 +1,10 @@ +{ + "name": "simple-app", + "description": "A test fixture for pkginfo", + "version": "0.1.0", + "author": "Charlie Robbins <charlie.robbins@gmail.com>", + "keywords": ["test", "fixture"], + "main": "./index.js", + "scripts": { "test": "vows test/*-test.js --spec" }, + "engines": { "node": ">= 0.4.0" } +} diff --git a/node_modules/winston/node_modules/pkginfo/examples/single-property.js b/node_modules/winston/node_modules/pkginfo/examples/single-property.js new file mode 100644 index 0000000..4f44561 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/examples/single-property.js @@ -0,0 +1,19 @@ +/* + * single-property.js: Sample of including a single specific properties from a package.json file + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + pkginfo = require('../lib/pkginfo')(module, 'version'); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/examples/subdir/package.json b/node_modules/winston/node_modules/pkginfo/examples/subdir/package.json new file mode 100644 index 0000000..aa85410 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/examples/subdir/package.json @@ -0,0 +1,11 @@ +{ + "name": "simple-app-subdir", + "description": "A test fixture for pkginfo", + "version": "0.1.0", + "author": "Charlie Robbins <charlie.robbins@gmail.com>", + "keywords": ["test", "fixture"], + "main": "./index.js", + "scripts": { "test": "vows test/*-test.js --spec" }, + "engines": { "node": ">= 0.4.0" }, + "subdironly": "true" +} diff --git a/node_modules/winston/node_modules/pkginfo/examples/target-dir.js b/node_modules/winston/node_modules/pkginfo/examples/target-dir.js new file mode 100644 index 0000000..88770e6 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/examples/target-dir.js @@ -0,0 +1,20 @@ +/* + * multiple-properties.js: Sample of including multiple properties from a package.json file + * + * (C) 2011, Charlie Robbins + * + */ + +var util = require('util'), + path = require('path'), + pkginfo = require('../lib/pkginfo')(module, { dir: path.resolve(__dirname, 'subdir' )}); + +exports.someFunction = function () { + console.log('some of your custom logic here'); +}; + +console.log('Inspecting module:'); +console.dir(module.exports); + +console.log('\nAll exports exposed:'); +console.error(Object.keys(module.exports));
\ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/lib/pkginfo.js b/node_modules/winston/node_modules/pkginfo/lib/pkginfo.js new file mode 100644 index 0000000..c5dc020 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/lib/pkginfo.js @@ -0,0 +1,136 @@ +/* + * pkginfo.js: Top-level include for the pkginfo module + * + * (C) 2011, Charlie Robbins + * + */ + +var fs = require('fs'), + path = require('path'); + +// +// ### function pkginfo ([options, 'property', 'property' ..]) +// #### @pmodule {Module} Parent module to read from. +// #### @options {Object|Array|string} **Optional** Options used when exposing properties. +// #### @arguments {string...} **Optional** Specified properties to expose. +// Exposes properties from the package.json file for the parent module on +// it's exports. Valid usage: +// +// `require('pkginfo')()` +// +// `require('pkginfo')('version', 'author');` +// +// `require('pkginfo')(['version', 'author']);` +// +// `require('pkginfo')({ include: ['version', 'author'] });` +// +var pkginfo = module.exports = function (pmodule, options) { + var args = [].slice.call(arguments, 2).filter(function (arg) { + return typeof arg === 'string'; + }); + + // + // **Parse variable arguments** + // + if (Array.isArray(options)) { + // + // If the options passed in is an Array assume that + // it is the Array of properties to expose from the + // on the package.json file on the parent module. + // + options = { include: options }; + } + else if (typeof options === 'string') { + // + // Otherwise if the first argument is a string, then + // assume that it is the first property to expose from + // the package.json file on the parent module. + // + options = { include: [options] }; + } + + // + // **Setup default options** + // + options = options || {}; + + // ensure that includes have been defined + options.include = options.include || []; + + if (args.length > 0) { + // + // If additional string arguments have been passed in + // then add them to the properties to expose on the + // parent module. + // + options.include = options.include.concat(args); + } + + var pkg = pkginfo.read(pmodule, options.dir).package; + Object.keys(pkg).forEach(function (key) { + if (options.include.length > 0 && !~options.include.indexOf(key)) { + return; + } + + if (!pmodule.exports[key]) { + pmodule.exports[key] = pkg[key]; + } + }); + + return pkginfo; +}; + +// +// ### function find (dir) +// #### @pmodule {Module} Parent module to read from. +// #### @dir {string} **Optional** Directory to start search from. +// Searches up the directory tree from `dir` until it finds a directory +// which contains a `package.json` file. +// +pkginfo.find = function (pmodule, dir) { + if (! dir) { + dir = path.dirname(pmodule.filename); + } + + var files = fs.readdirSync(dir); + + if (~files.indexOf('package.json')) { + return path.join(dir, 'package.json'); + } + + if (dir === '/') { + throw new Error('Could not find package.json up from: ' + dir); + } + else if (!dir || dir === '.') { + throw new Error('Cannot find package.json from unspecified directory'); + } + + return pkginfo.find(pmodule, path.dirname(dir)); +}; + +// +// ### function read (pmodule, dir) +// #### @pmodule {Module} Parent module to read from. +// #### @dir {string} **Optional** Directory to start search from. +// Searches up the directory tree from `dir` until it finds a directory +// which contains a `package.json` file and returns the package information. +// +pkginfo.read = function (pmodule, dir) { + dir = pkginfo.find(pmodule, dir); + + var data = fs.readFileSync(dir).toString(); + + return { + dir: dir, + package: JSON.parse(data) + }; +}; + +// +// Call `pkginfo` on this module and expose version. +// +pkginfo(module, { + dir: __dirname, + include: ['version'], + target: pkginfo +});
\ No newline at end of file diff --git a/node_modules/winston/node_modules/pkginfo/package.json b/node_modules/winston/node_modules/pkginfo/package.json new file mode 100644 index 0000000..79ac8ce --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/package.json @@ -0,0 +1,58 @@ +{ + "_from": "pkginfo@0.3.x", + "_id": "pkginfo@0.3.1", + "_inBundle": false, + "_integrity": "sha1-Wyn2qB9wcXFC4J52W76rl7T4HiE=", + "_location": "/winston/pkginfo", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "pkginfo@0.3.x", + "name": "pkginfo", + "escapedName": "pkginfo", + "rawSpec": "0.3.x", + "saveSpec": null, + "fetchSpec": "0.3.x" + }, + "_requiredBy": [ + "/winston" + ], + "_resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.3.1.tgz", + "_shasum": "5b29f6a81f70717142e09e765bbeab97b4f81e21", + "_spec": "pkginfo@0.3.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/winston", + "author": { + "name": "Charlie Robbins", + "email": "charlie.robbins@gmail.com" + }, + "bugs": { + "url": "https://github.com/indexzero/node-pkginfo/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "An easy way to expose properties on a module from a package.json", + "devDependencies": { + "vows": "0.7.x" + }, + "engines": { + "node": ">= 0.4.0" + }, + "homepage": "https://github.com/indexzero/node-pkginfo#readme", + "keywords": [ + "info", + "tools", + "package.json" + ], + "license": "MIT", + "main": "./lib/pkginfo.js", + "name": "pkginfo", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/indexzero/node-pkginfo.git" + }, + "scripts": { + "test": "vows test/*-test.js --spec" + }, + "version": "0.3.1" +} diff --git a/node_modules/winston/node_modules/pkginfo/test/pkginfo-test.js b/node_modules/winston/node_modules/pkginfo/test/pkginfo-test.js new file mode 100644 index 0000000..a59f077 --- /dev/null +++ b/node_modules/winston/node_modules/pkginfo/test/pkginfo-test.js @@ -0,0 +1,83 @@ +/* + * pkginfo-test.js: Tests for the pkginfo module. + * + * (C) 2011, Charlie Robbins + * + */ + +var assert = require('assert'), + exec = require('child_process').exec, + fs = require('fs'), + path = require('path'), + vows = require('vows'), + pkginfo = require('../lib/pkginfo'); + +function assertProperties (source, target) { + assert.lengthOf(source, target.length + 1); + target.forEach(function (prop) { + assert.isTrue(!!~source.indexOf(prop)); + }); +} + +function compareWithExample(targetPath) { + var examplePaths = ['package.json']; + + if (targetPath) { + examplePaths.unshift(targetPath); + } + + return function(exposed) { + var pkg = fs.readFileSync(path.join.apply(null, [__dirname, '..', 'examples'].concat(examplePaths))).toString(), + keys = Object.keys(JSON.parse(pkg)); + + assertProperties(exposed, keys); + }; +} + +function testExposes (options) { + return { + topic: function () { + exec('node ' + path.join(__dirname, '..', 'examples', options.script), this.callback); + }, + "should expose that property correctly": function (err, stdout, stderr) { + assert.isNull(err); + + var exposed = stderr.match(/'(\w+)'/ig).map(function (p) { + return p.substring(1, p.length - 1); + }); + + return !options.assert + ? assertProperties(exposed, options.properties) + : options.assert(exposed); + } + } +} + +vows.describe('pkginfo').addBatch({ + "When using the pkginfo module": { + "and passed a single `string` argument": testExposes({ + script: 'single-property.js', + properties: ['version'] + }), + "and passed multiple `string` arguments": testExposes({ + script: 'multiple-properties.js', + properties: ['version', 'author'] + }), + "and passed an `object` argument": testExposes({ + script: 'object-argument.js', + properties: ['version', 'author'] + }), + "and passed an `array` argument": testExposes({ + script: 'array-argument.js', + properties: ['version', 'author'] + }), + "and read from a specified directory": testExposes({ + script: 'target-dir.js', + assert: compareWithExample('subdir') + }), + "and passed no arguments": testExposes({ + script: 'all-properties.js', + assert: compareWithExample() + }) + } +}).export(module); diff --git a/node_modules/winston/package.json b/node_modules/winston/package.json new file mode 100644 index 0000000..39a3587 --- /dev/null +++ b/node_modules/winston/package.json @@ -0,0 +1,81 @@ +{ + "_from": "winston@2.1.x", + "_id": "winston@2.1.1", + "_inBundle": false, + "_integrity": "sha1-PJNJ0ZYgf9G9/51LxD73JRDjoS4=", + "_location": "/winston", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "winston@2.1.x", + "name": "winston", + "escapedName": "winston", + "rawSpec": "2.1.x", + "saveSpec": null, + "fetchSpec": "2.1.x" + }, + "_requiredBy": [ + "/prompt" + ], + "_resolved": "https://registry.npmjs.org/winston/-/winston-2.1.1.tgz", + "_shasum": "3c9349d196207fd1bdff9d4bc43ef72510e3a12e", + "_spec": "winston@2.1.x", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/prompt", + "author": { + "name": "Charlie Robbins", + "email": "charlie.robbins@gmail.com" + }, + "bugs": { + "url": "https://github.com/winstonjs/winston/issues" + }, + "bundleDependencies": false, + "dependencies": { + "async": "~1.0.0", + "colors": "1.0.x", + "cycle": "1.0.x", + "eyes": "0.1.x", + "isstream": "0.1.x", + "pkginfo": "0.3.x", + "stack-trace": "0.0.x" + }, + "deprecated": false, + "description": "A multi-transport async logging library for Node.js", + "devDependencies": { + "cross-spawn-async": "^2.0.0", + "hock": "1.x.x", + "std-mocks": "~1.0.0", + "vows": "0.7.x" + }, + "engines": { + "node": ">= 0.8.0" + }, + "homepage": "https://github.com/winstonjs/winston#readme", + "keywords": [ + "winston", + "logging", + "sysadmin", + "tools" + ], + "license": "MIT", + "main": "./lib/winston", + "maintainers": [ + { + "name": "Jarrett Cruger", + "email": "jcrugzz@gmail.com" + }, + { + "name": "Alberto Pose", + "email": "albertopose@gmail.com" + } + ], + "name": "winston", + "repository": { + "type": "git", + "url": "git+https://github.com/winstonjs/winston.git" + }, + "scripts": { + "test": "vows --spec --isolate" + }, + "version": "2.1.1" +} diff --git a/node_modules/winston/test/helpers.js b/node_modules/winston/test/helpers.js new file mode 100644 index 0000000..8575fb6 --- /dev/null +++ b/node_modules/winston/test/helpers.js @@ -0,0 +1,256 @@ +/* + * helpers.js: Test helpers for winston + * + * (C) 2010 Charlie Robbins + * MIT LICENSE + * + */ + +var assert = require('assert'), + fs = require('fs'), + path = require('path'), + spawn = require('child_process').spawn, + util = require('util'), + vows = require('vows'), + winston = require('../lib/winston'); + +var helpers = exports; + +helpers.size = function (obj) { + var size = 0, key; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + size++; + } + } + + return size; +}; + +helpers.tryUnlink = function (file) { + try { fs.unlinkSync(file) } + catch (ex) { } +}; + +helpers.assertDateInfo = function (info) { + assert.isNumber(Date.parse(info)); +}; + +helpers.assertProcessInfo = function (info) { + assert.isNumber(info.pid); + assert.isNumber(info.uid); + assert.isNumber(info.gid); + assert.isString(info.cwd); + assert.isString(info.execPath); + assert.isString(info.version); + assert.isArray(info.argv); + assert.isObject(info.memoryUsage); +}; + +helpers.assertOsInfo = function (info) { + assert.isArray(info.loadavg); + assert.isNumber(info.uptime); +}; + +helpers.assertTrace = function (trace) { + trace.forEach(function (site) { + assert.isTrue(!site.column || typeof site.column === 'number'); + assert.isTrue(!site.line || typeof site.line === 'number'); + assert.isTrue(!site.file || typeof site.file === 'string'); + assert.isTrue(!site.method || typeof site.method === 'string'); + assert.isTrue(!site.function || typeof site.function === 'string'); + assert.isTrue(typeof site.native === 'boolean'); + }); +}; + +helpers.assertLogger = function (logger, level) { + assert.instanceOf(logger, winston.Logger); + assert.isFunction(logger.log); + assert.isFunction(logger.add); + assert.isFunction(logger.remove); + assert.equal(logger.level, level || "info"); + Object.keys(logger.levels).forEach(function (method) { + assert.isFunction(logger[method]); + }); +}; + +helpers.assertConsole = function (transport) { + assert.instanceOf(transport, winston.transports.Console); + assert.isFunction(transport.log); +}; + +helpers.assertMemory = function (transport) { + assert.instanceOf(transport, winston.transports.Memory); + assert.isFunction(transport.log); +}; + +helpers.assertFile = function (transport) { + assert.instanceOf(transport, winston.transports.File); + assert.isFunction(transport.log); +}; + +helpers.assertCouchdb = function (transport) { + assert.instanceOf(transport, winston.transports.Couchdb); + assert.isFunction(transport.log); +}; + +helpers.assertHandleExceptions = function (options) { + return { + topic: function () { + var that = this, + child = spawn('node', [options.script]); + + helpers.tryUnlink(options.logfile); + child.on('exit', function () { + fs.readFile(options.logfile, that.callback); + }); + }, + "should save the error information to the specified file": function (err, data) { + assert.isTrue(!err); + data = JSON.parse(data); + + assert.isObject(data); + helpers.assertProcessInfo(data.process); + helpers.assertOsInfo(data.os); + helpers.assertTrace(data.trace); + if (options.message) { + assert.equal('uncaughtException: ' + options.message, data.message); + } + } + }; +}; + +helpers.assertFailedTransport = function (transport) { + return { + topic: function () { + var self = this; + transport.on('error', function(emitErr){ + transport.log('error', 'test message 2', {}, function(logErr, logged){ + self.callback(emitErr, logErr); + }); + }); + transport.log('error', 'test message'); + }, + "should emit an error": function (emitErr, logErr) { + assert.instanceOf(emitErr, Error); + assert.equal(emitErr.code, 'ENOENT'); + }, + "should enter noop failed state": function (emitErr, logErr) { + assert.instanceOf(logErr, Error); + assert.equal(transport._failures, transport.maxRetries); + } + }; +}; + +helpers.testNpmLevels = function (transport, assertMsg, assertFn) { + return helpers.testLevels(winston.config.npm.levels, transport, assertMsg, assertFn); +}; + +helpers.testSyslogLevels = function (transport, assertMsg, assertFn) { + return helpers.testLevels(winston.config.syslog.levels, transport, assertMsg, assertFn); +}; + +helpers.testLevels = function (levels, transport, assertMsg, assertFn) { + var tests = {}; + + Object.keys(levels).forEach(function (level) { + var test = { + topic: function () { + transport.log(level, 'test message', {}, this.callback.bind(this, null)); + } + }; + + test[assertMsg] = assertFn; + tests['with the ' + level + ' level'] = test; + }); + + var metadatatest = { + topic: function () { + transport.log('info', 'test message', { metadata: true }, this.callback.bind(this, null)); + } + }; + + metadatatest[assertMsg] = assertFn; + tests['when passed metadata'] = metadatatest; + + var primmetadatatest = { + topic: function () { + transport.log('info', 'test message', 'metadata', this.callback.bind(this, null)); + } + }; + + primmetadatatest[assertMsg] = assertFn; + tests['when passed primitive metadata'] = primmetadatatest; + + var circmetadata = { }; + circmetadata['metadata'] = circmetadata; + + var circmetadatatest = { + topic: function () { + transport.log('info', 'test message', circmetadata, this.callback.bind(this, null)); + } + }; + + circmetadatatest[assertMsg] = assertFn; + tests['when passed circular metadata'] = circmetadatatest; + + return tests; +}; + +helpers.assertOptionsThrow = function (options, errMsg) { + return function () { + assert.throws( + function () { + try { + new (winston.transports.Console)(options); + } catch (err) { + throw(err); + } + }, + new RegExp('^' + errMsg.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') + '$') + ); + } +}; + +helpers.assertStderrLevels = function (transport, stderrLevels) { + return function () { + assert.equal( + JSON.stringify(Object.keys(transport.stderrLevels).sort()), + JSON.stringify(stderrLevels.sort()) + ); + } +}; + +helpers.testLoggingToStreams = function (levels, transport, stderrLevels, stdMocks) { + return { + topic: function () { + stdMocks.use(); + transport.showLevel = true; + Object.keys(levels).forEach(function (level) { + transport.log( + level, + level + ' should go to ' + (stderrLevels.indexOf(level) > -1 ? 'stderr' : 'stdout'), + {}, + function () {} + ); + }); + var output = stdMocks.flush(); + stdMocks.restore(); + this.callback(null, output, levels); + }, + "output should go to the appropriate streams": function (ign, output, levels) { + var outCount = 0, + errCount = 0; + Object.keys(levels).forEach(function (level) { + var line; + if (stderrLevels.indexOf(level) > -1) { + line = output.stderr[errCount++]; + assert.equal(line, level + ': ' + level + ' should go to stderr\n'); + } else { + line = output.stdout[outCount++]; + assert.equal(line, level + ': ' + level + ' should go to stdout\n'); + } + }); + } + } +}; diff --git a/node_modules/winston/test/transports/console-test.js b/node_modules/winston/test/transports/console-test.js new file mode 100644 index 0000000..de868b3 --- /dev/null +++ b/node_modules/winston/test/transports/console-test.js @@ -0,0 +1,202 @@ +/* + * console-test.js: Tests for instances of the Console transport + * + * (C) 2010 Charlie Robbins + * MIT LICENSE + * + */ + +var path = require('path'), + vows = require('vows'), + assert = require('assert'), + winston = require('../../lib/winston'), + helpers = require('../helpers'), + stdMocks = require('std-mocks'); + +var npmTransport = new (winston.transports.Console)(), + syslogTransport = new (winston.transports.Console)({ levels: winston.config.syslog.levels }), + alignTransport = new (winston.transports.Console)({ showLevel: true, align: true }), + defaultTransport = new (winston.transports.Console)(), + rawTransport = new (winston.transports.Console)({ level: 'verbose', raw: true }), + debugStdoutTransport = new (winston.transports.Console)({ debugStdout: true }), + stderrLevelsTransport = new (winston.transports.Console)({ stderrLevels: ['info', 'warn'] }), + customLevels = { + alpha: 0, + beta: 1, + gamma: 2, + delta: 3, + epsilon: 4, + }, + customLevelsAndStderrTransport = new (winston.transports.Console)({ + levels: customLevels, + stderrLevels: ['delta', 'epsilon'] + }), + noStderrTransport = new (winston.transports.Console)({ stderrLevels: [] }); + +vows.describe('winston/transports/console').addBatch({ + "An instance of the Console Transport": { + "with showLevel off": { + topic : function() { + npmTransport.showLevel = false; + stdMocks.use(); + npmTransport.log('info', 'Le message', { meta: true }, this.callback); + }, + "should not have level prepended": function () { + stdMocks.restore(); + var output = stdMocks.flush(), + line = output.stdout[0]; + + assert.equal(line, 'Le message meta=true\n'); + } + } + } +}).addBatch({ + "An instance of the Console Transport": { + "with showLevel on": { + topic : function() { + npmTransport.showLevel = true; + stdMocks.use(); + npmTransport.log('info', ''); + }, + "should have level prepended": function () { + stdMocks.restore(); + var output = stdMocks.flush(), + line = output.stdout[0]; + + assert.equal(line, 'info: \n'); + } + }, + } +}).addBatch({ + "An instance of the Console Transport": { + "with npm levels": { + "should have the proper methods defined": function () { + helpers.assertConsole(npmTransport); + }, + "the log() method": helpers.testNpmLevels(npmTransport, "should respond with true", function (ign, err, logged) { + assert.isNull(err); + assert.isTrue(logged); + }) + }, + "with syslog levels": { + "should have the proper methods defined": function () { + helpers.assertConsole(syslogTransport); + }, + "the log() method": helpers.testSyslogLevels(syslogTransport, "should respond with true", function (ign, err, logged) { + assert.isNull(err); + assert.isTrue(logged); + }) + }, + "with end-of-line": { + topic : function() { + npmTransport.eol = 'X'; + stdMocks.use(); + npmTransport.log('info', 'Le message', { meta: true }, this.callback); + }, + "should have end-of-line character appended": function () { + stdMocks.restore(); + var output = stdMocks.flush(), + line = output.stdout[0]; + console.dir(line); + + assert.equal(line, 'info: Le message meta=trueX'); + } + } + } +}).addBatch({ + "An instance of the Console Transport with the align option on": { + topic : function() { + stdMocks.use(); + alignTransport.log('info', ''); + }, + "should have logs aligned": function () { + stdMocks.restore(); + var output = stdMocks.flush(), + line = output.stdout[0]; + + assert.equal(line, 'info\011: \n'); + } + } +}).addBatch({ + "with align off": { + topic : function() { + alignTransport.align = false; + stdMocks.use(); + alignTransport.log('info', ''); + }, + "should not have logs aligned": function () { + stdMocks.restore(); + var output = stdMocks.flush(), + line = output.stdout[0]; + + assert.equal(line, 'info: \n'); + } + } +}).addBatch({ + 'An instance of a raw Console transport': { + 'logging to stdout': { + topic: function () { + stdMocks.use(); + rawTransport.log('verbose', 'hello there'); + }, 'should output json with message property': function () { + stdMocks.restore(); + var output = stdMocks.flush(); + assert.ok(output.stdout[0].indexOf('"message":"hello there"') > -1); + } + } + } +}).addBatch({ + "An instance of the Console Transport with no options": { + "should set stderrLevels to 'error' and 'debug' by default": helpers.assertStderrLevels( + defaultTransport, + ['error', 'debug'] + ), + "should log only 'error' and 'debug' to stderr": helpers.testLoggingToStreams( + winston.config.npm.levels, defaultTransport, ['debug', 'error'], stdMocks + ) + } +}).addBatch({ + "An instance of the Console Transport with debugStdout set": { + "should throw an Error if stderrLevels is set": helpers.assertOptionsThrow( + { debugStdout: true, stderrLevels: ['debug'] }, + "Error: Cannot set debugStdout and stderrLevels together" + ), + "should set stderrLevels to 'error' by default": helpers.assertStderrLevels( + debugStdoutTransport, + ['error'] + ), + "should log only the 'error' level to stderr": helpers.testLoggingToStreams( + winston.config.npm.levels, debugStdoutTransport, ['error'], stdMocks + ) + } +}).addBatch({ + "An instance of the Console Transport with stderrLevels set": { + "should throw an Error if stderrLevels is set but not an Array": helpers.assertOptionsThrow( + { debugStdout: false, stderrLevels: new String('Not an Array') }, + "Error: Cannot set stderrLevels to type other than Array" + ), + "should throw an Error if stderrLevels contains non-string elements": helpers.assertOptionsThrow( + { debugStdout: false, stderrLevels: ["good", /^invalid$/, "valid"] }, + "Error: Cannot have non-string elements in stderrLevels Array" + ), + "should correctly set stderrLevels": helpers.assertStderrLevels( + stderrLevelsTransport, + ['info', 'warn'] + ), + "should log only the levels in stderrLevels to stderr": helpers.testLoggingToStreams( + winston.config.npm.levels, stderrLevelsTransport, ['info', 'warn'], stdMocks + ) + } +}).addBatch({ + "An instance of the Console Transport with stderrLevels set to an empty array": { + "should log only to stdout, and not to stderr": helpers.testLoggingToStreams( + winston.config.npm.levels, noStderrTransport, [], stdMocks + ) + } +}).addBatch({ + "An instance of the Console Transport with custom levels and stderrLevels set": { + "should log only the levels in stderrLevels to stderr": helpers.testLoggingToStreams( + customLevels, customLevelsAndStderrTransport, ['delta', 'epsilon'], stdMocks + ) + } +}).export(module); diff --git a/node_modules/winston/test/transports/file-archive-test.js b/node_modules/winston/test/transports/file-archive-test.js new file mode 100644 index 0000000..d076ce0 --- /dev/null +++ b/node_modules/winston/test/transports/file-archive-test.js @@ -0,0 +1,83 @@ +/* + * file-archive-test.js: Tests for instances of the File transport setting the archive option, + * + * (C) 2015 Nimrod Becker + * MIT LICENSE + * + */ + +var assert = require('assert'), + exec = require('child_process').exec, + fs = require('fs'), + path = require('path'), + vows = require('vows'), + winston = require('../../lib/winston'), + helpers = require('../helpers'); + +var archiveTransport = new winston.transports.File({ + timestamp: true, + json: false, + zippedArchive: true, + tailable: true, + filename: 'testarchive.log', + dirname: path.join(__dirname, '..', 'fixtures', 'logs'), + maxsize: 4096, + maxFiles: 3 +}); + +function data(ch) { + return new Array(1018).join(String.fromCharCode(65 + ch)); +} + +function logKbytes(kbytes, txt) { + // + // With no timestamp and at the info level, + // winston adds exactly 7 characters: + // [info](4)[ :](2)[\n](1) + // + for (var i = 0; i < kbytes; i++) { + archiveTransport.log('info', data(txt), null, function() {}); + } +} + +vows.describe('winston/transports/file/zippedArchive').addBatch({ + "An instance of the File Transport with tailable true": { + "when created archived files are rolled": { + topic: function() { + var that = this, + created = 0; + + archiveTransport.on('logged', function() { + if (++created === 6) { + return that.callback(); + } + + logKbytes(4, created); + }); + + logKbytes(4, created); + }, + "should be only 3 files called testarchive.log, testarchive1.log.gz and testarchive2.log.gz": function() { + //Give the archive a little time to settle + // setTimeout(function() { + for (var num = 0; num < 6; num++) { + var file = !num ? 'testarchive.log' : 'testarchive' + num + '.log.gz', + fullpath = path.join(__dirname, '..', 'fixtures', 'logs', file); + + // There should be no files with that name + if (num >= 3) { + assert.throws(function() { + fs.statSync(fullpath); + }, Error); + } else { + // The other files should exist + assert.doesNotThrow(function() { + fs.statSync(fullpath); + }, Error); + } + } + //},5000); + }, + } + }, +}).export(module); diff --git a/node_modules/winston/test/transports/file-maxfiles-test.js b/node_modules/winston/test/transports/file-maxfiles-test.js new file mode 100644 index 0000000..62564a2 --- /dev/null +++ b/node_modules/winston/test/transports/file-maxfiles-test.js @@ -0,0 +1,102 @@ +/* + * file-maxfiles-test.js: Tests for instances of the File transport setting the max file size, + * and setting a number for max files created. + * maxSize * maxFiles = total storage used by winston. + * + * (C) 2011 Daniel Aristizabal + * MIT LICENSE + * + */ + +var assert = require('assert'), + exec = require('child_process').exec, + fs = require('fs'), + path = require('path'), + vows = require('vows'), + winston = require('../../lib/winston'), + helpers = require('../helpers'); + +var maxfilesTransport = new winston.transports.File({ + timestamp: false, + json: false, + filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxfiles.log'), + maxsize: 4096, + maxFiles: 3 +}); + +vows.describe('winston/transports/file/maxfiles').addBatch({ + "An instance of the File Transport": { + "when passed a valid filename": { + topic: maxfilesTransport, + "should be a valid transporter": function (transportTest) { + helpers.assertFile(transportTest); + }, + "should set the maxFiles option correctly": function (transportTest) { + assert.isNumber(transportTest.maxFiles); + } + }, + "when delete old test files": { + topic: function () { + exec('rm -rf ' + path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxfiles*'), this.callback); + }, + "and when passed more files than the maxFiles": { + topic: function () { + var that = this, + created = 0; + + function data(ch) { + return new Array(1018).join(String.fromCharCode(65 + ch)); + }; + + function logKbytes(kbytes, txt) { + // + // With no timestamp and at the info level, + // winston adds exactly 7 characters: + // [info](4)[ :](2)[\n](1) + // + for (var i = 0; i < kbytes; i++) { + maxfilesTransport.log('info', data(txt), null, function () { }); + } + } + + maxfilesTransport.on('logged', function () { + if (++created === 6) { + return that.callback(); + } + + logKbytes(4, created); + }); + + logKbytes(4, created); + }, + "should be only 3 files called 5.log, 4.log and 3.log": function () { + for (var num = 0; num < 6; num++) { + var file = !num ? 'testmaxfiles.log' : 'testmaxfiles' + num + '.log', + fullpath = path.join(__dirname, '..', 'fixtures', 'logs', file); + + // There should be no files with that name + if (num >= 0 && num < 3) { + assert.throws(function () { + fs.statSync(fullpath); + }, Error); + } else { + // The other files should be exist + assert.doesNotThrow(function () { + fs.statSync(fullpath); + }, Error); + } + } + }, + "should have the correct content": function () { + ['D', 'E', 'F'].forEach(function (name, inx) { + var counter = inx + 3, + logsDir = path.join(__dirname, '..', 'fixtures', 'logs'), + content = fs.readFileSync(path.join(logsDir, 'testmaxfiles' + counter + '.log'), 'utf-8'); + // The content minus the 7 characters added by winston + assert.lengthOf(content.match(new RegExp(name, 'g')), 4068); + }); + } + } + } + } +}).export(module); diff --git a/node_modules/winston/test/transports/file-maxsize-test.js b/node_modules/winston/test/transports/file-maxsize-test.js new file mode 100644 index 0000000..7d20e08 --- /dev/null +++ b/node_modules/winston/test/transports/file-maxsize-test.js @@ -0,0 +1,82 @@ +/* + * file-test.js: Tests for instances of the File transport + * + * (C) 2010 Charlie Robbins + * MIT LICENSE + * + */ + +var assert = require('assert'), + exec = require('child_process').exec, + fs = require('fs'), + path = require('path'), + vows = require('vows'), + winston = require('../../lib/winston'), + helpers = require('../helpers'); + +var maxsizeTransport = new winston.transports.File({ + timestamp: false, + json: false, + filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxsize.log'), + maxsize: 4096 +}); + +vows.describe('winston/transports/file/maxsize').addBatch({ + "An instance of the File Transport": { + "when passed a valid filename": { + "the log() method": { + topic: function () { + exec('rm -rf ' + path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxsize*'), this.callback); + }, + "when passed more than the maxsize": { + topic: function () { + var that = this, + data = new Array(1018).join('-'); + + // + // Setup a list of files which we will later stat. + // + that.files = []; + + function logKbytes (kbytes) { + // + // With no timestamp and at the info level, + // winston adds exactly 7 characters: + // [info](4)[ :](2)[\n](1) + // + for (var i = 0; i < kbytes; i++) { + maxsizeTransport.log('info', data, null, function () { }); + } + } + + maxsizeTransport.on('open', function (file) { + var match = file.match(/(\d+)\.log$/), + count = match ? match[1] : 0; + + that.files.push(file); + + if (that.files.length === 5) { + return that.callback(); + } + + logKbytes(4); + }); + + logKbytes(4); + }, + "should create multiple files correctly": function () { + this.files.forEach(function (file) { + try { + var stats = fs.statSync(file); + assert.equal(stats.size, 4096); + } + catch (ex) { + assert.isNull(ex); + } + }); + } + } + } + } + } +}).export(module);
\ No newline at end of file diff --git a/node_modules/winston/test/transports/file-open-test.js b/node_modules/winston/test/transports/file-open-test.js new file mode 100644 index 0000000..15427a0 --- /dev/null +++ b/node_modules/winston/test/transports/file-open-test.js @@ -0,0 +1,57 @@ +/* + * file-open-test.js: Tests for File transport "open" event + * + * (C) 2014 William Wong + * MIT LICENSE + * + */ + +var assert = require('assert'), + fs = require('fs'), + os = require('os'), + path = require('path'), + vows = require('vows'), + winston = require('../../lib/winston'); + +vows.describe('winston/transports/file').addBatch({ + 'An instance of the File Transport': { + topic: function () { + var callback = this.callback.bind(this), + logPath = path.resolve(__dirname, '../fixtures/logs/file-open-test.log'); + + try { + fs.unlinkSync(logPath); + } catch (ex) { + if (ex && ex.code !== 'ENOENT') { return callback(ex); } + } + + var fileTransport = new (winston.transports.File)({ + filename: logPath + }), + logger = new (winston.Logger)({ + transports: [fileTransport] + }), + timeline = {}; + + fileTransport.open(function () { + timeline.open = Date.now(); + + setTimeout(function () { + logger.info('Hello, World!', function () { + timeline.logged = Date.now(); + }); + }, 100); + + setTimeout(function () { + callback(null, timeline); + }, 1000); + }); + }, + 'should fire "open" event': function (results) { + assert.isTrue(!!results.open); + }, + 'should fire "logged" event': function (results) { + assert.isTrue(!!results.logged); + } + } +}).export(module);
\ No newline at end of file diff --git a/node_modules/winston/test/transports/file-stress-test.js b/node_modules/winston/test/transports/file-stress-test.js new file mode 100644 index 0000000..8c4dcb9 --- /dev/null +++ b/node_modules/winston/test/transports/file-stress-test.js @@ -0,0 +1,72 @@ +/* + * file-stress-test.js: Tests for stressing File transport + * + * (C) 2014 William Wong + * MIT LICENSE + * + */ + +var assert = require('assert'), + fs = require('fs'), + os = require('os'), + path = require('path'), + vows = require('vows'), + winston = require('../../lib/winston'); + +vows.describe('winston/transports/file').addBatch({ + 'A stressed instance of the File Transport': { + topic: function () { + var callback = this.callback.bind(this), + logPath = path.resolve(__dirname, '../fixtures/logs/file-stress-test.log'); + + try { + fs.unlinkSync(logPath); + } catch (ex) { + if (ex && ex.code !== 'ENOENT') { return callback(ex); } + } + + var fileTransport = new (winston.transports.File)({ + filename: logPath + }), + logger = new (winston.Logger)({ + transports: [fileTransport] + }); + + fileTransport.on('open', function () { + setTimeout(function () { + clearInterval(interval); + + logger.query({ order: 'asc' }, function (err, results) { + callback(null, results); + }); + }, 100); + }); + + var logIndex = 0, + interval = setInterval(function () { + logger.info(++logIndex); + stress(200); + }, 0); + + logger.info(++logIndex); + stress(200); + + function stress(duration) { + var startTime = Date.now(); + + while (Date.now() - startTime < duration) { + Math.sqrt(Math.PI); + } + } + }, + 'should not skip any log lines': function (results) { + var testIndex = 0; + + results.file.forEach(function (log) { + if (+log.message !== ++testIndex) { + throw new Error('Number skipped'); + } + }); + } + } +}).export(module); diff --git a/node_modules/winston/test/transports/file-tailrolling-test.js b/node_modules/winston/test/transports/file-tailrolling-test.js new file mode 100644 index 0000000..60a0674 --- /dev/null +++ b/node_modules/winston/test/transports/file-tailrolling-test.js @@ -0,0 +1,92 @@ +var assert = require('assert'), + fs = require('fs'), + path = require('path'), + vows = require('vows'), + winston = require('../../lib/winston'), + helpers = require('../helpers'); + +var maxfilesTransport = new winston.transports.File({ + timestamp: false, + json: false, + filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testtailrollingfiles.log'), + maxsize: 4096, + maxFiles: 3, + tailable: true +}); + +process.on('uncaughtException', function (err) { + console.log('caught exception'); + console.error(err); +}); + +vows.describe('winston/transports/file/tailrolling').addBatch({ + "An instance of the File Transport": { + "when delete old test files": { + topic: function () { + var logs = path.join(__dirname, '..', 'fixtures', 'logs'); + fs.readdirSync(logs).forEach(function (file) { + if (~file.indexOf('testtailrollingfiles')) { + fs.unlinkSync(path.join(logs, file)); + } + }); + + this.callback(); + }, + "and when passed more files than the maxFiles": { + topic: function () { + var that = this, + created = 0; + + function data(ch) { + return new Array(1018).join(String.fromCharCode(65 + ch)); + }; + + function logKbytes(kbytes, txt) { + // + // With no timestamp and at the info level, + // winston adds exactly 7 characters: + // [info](4)[ :](2)[\n](1) + // + for (var i = 0; i < kbytes; i++) { + maxfilesTransport.log('info', data(txt), null, function () { }); + } + } + + maxfilesTransport.on('logged', function () { + if (++created == 4) { + return that.callback(); + } + + logKbytes(4, created); + }); + + logKbytes(4, created); + }, + "should be 3 log files, base to maxFiles - 1": function () { + var file, fullpath; + for (var num = 0; num < 4; num++) { + file = !num ? 'testtailrollingfiles.log' : 'testtailrollingfiles' + num + '.log'; + fullpath = path.join(__dirname, '..', 'fixtures', 'logs', file); + + if (num == 3) { + return assert.ok(!fs.existsSync(fullpath)); + } + + assert.ok(fs.existsSync(fullpath)); + } + + return false; + }, + "should have files in correct order": function () { + var file, fullpath, content; + ['D', 'C', 'B'].forEach(function (letter, i) { + file = !i ? 'testtailrollingfiles.log' : 'testtailrollingfiles' + i + '.log'; + content = fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'logs', file), 'ascii'); + + assert.lengthOf(content.match(new RegExp(letter, 'g')), 4068); + }); + } + } + } + } +}).export(module);
\ No newline at end of file diff --git a/node_modules/winston/test/transports/file-test.js b/node_modules/winston/test/transports/file-test.js new file mode 100644 index 0000000..e6f6b3a --- /dev/null +++ b/node_modules/winston/test/transports/file-test.js @@ -0,0 +1,134 @@ +/* + * file-test.js: Tests for instances of the File transport + * + * (C) 2010 Charlie Robbins + * MIT LICENSE + * + */ + +var path = require('path'), + vows = require('vows'), + fs = require('fs'), + assert = require('assert'), + winston = require('../../lib/winston'), + stdMocks = require('std-mocks'), + helpers = require('../helpers'); + +var transport = require('./transport'); + +var stream = fs.createWriteStream( + path.join(__dirname, '..', 'fixtures', 'logs', 'testfile.log') + ), + fileTransport = new (winston.transports.File)({ + filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testfilename.log') + }), + failedFileTransport = new (winston.transports.File)({ + filename: path.join(__dirname, '..', 'fixtures', 'logs', 'dir404', 'testfile.log') + }), + streamTransport = new (winston.transports.File)({ stream: stream }); + +vows.describe('winston/transports/file').addBatch({ + "An instance of the File Transport": { + "when passed a valid filename": { + "should have the proper methods defined": function () { + helpers.assertFile(fileTransport); + }, + "the log() method": helpers.testNpmLevels(fileTransport, "should respond with true", function (ign, err, logged) { + assert.isNull(err); + assert.isTrue(logged); + }) + }, + "when passed an invalid filename": { + "should have proper methods defined": function () { + helpers.assertFile(failedFileTransport); + }, + "should enter noop failed state": function () { + helpers.assertFailedTransport(failedFileTransport); + } + }, + "when passed a valid file stream": { + "should have the proper methods defined": function () { + helpers.assertFile(streamTransport); + }, + "the log() method": helpers.testNpmLevels(streamTransport, "should respond with true", function (ign, err, logged) { + assert.isNull(err); + assert.isTrue(logged); + }) + }, + "streaming to stdout": { + topic: function () { + var transport = new (winston.transports.File)({ + stream: process.stdout, timestamp: false, json: false + }); + stdMocks.use(); + return transport; + }, + "with showLevel off": { + topic: function (stdoutStreamTransport) { + stdoutStreamTransport.showLevel = false; + stdoutStreamTransport.log('info', '', undefined, this.callback); + }, + "should not have level prepended": function () { + var output = stdMocks.flush(), + line = output.stdout[0]; + + assert.equal(line, '\n'); + } + }, + // there would be a "with showLevel on" here but I think it's a bug in + // this version of vows. ugprading causes even more problems + teardown: function() { + stdMocks.restore(); + } + } + } +}).addBatch({ + "These tests have a non-deterministic end": { + topic: function () { + setTimeout(this.callback, 200); + }, + "and this should be fixed before releasing": function () { + assert.isTrue(true); + } + } +}).addBatch({ + "Error object in metadata #610": { + topic: function () { + var myErr = new Error("foo"); + + fileTransport.log('info', 'test message', myErr, this.callback.bind(this, null, myErr)); + }, + "should not be modified": function (err, myErr) { + assert.equal(myErr.message, "foo"); + // Not sure if this is the best possible way to check if additional props appeared + assert.deepEqual(Object.getOwnPropertyNames(myErr), Object.getOwnPropertyNames(new Error("foo"))); + } + } +}).addBatch({ + "Date object in metadata": { + topic: function () { + var obj = new Date(1000); + + fileTransport.log('info', 'test message', obj, this.callback.bind(this, null, obj)); + }, + "should not be modified": function (err, obj) { + // Not sure if this is the best possible way to check if additional props appeared + assert.deepEqual(Object.getOwnPropertyNames(obj), Object.getOwnPropertyNames(new Date())); + } + } +}).addBatch({ + "Plain object in metadata": { + topic: function () { + var obj = { message: "foo" }; + + fileTransport.log('info', 'test message', obj, this.callback.bind(this, null, obj)); + }, + "should not be modified": function (err, obj) { + assert.deepEqual(obj, { message: "foo" }); + } + } +}).addBatch({ + "An instance of the File Transport": transport(winston.transports.File, { + filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testfile.log') + }) +}).export(module); diff --git a/node_modules/winston/test/transports/http-test.js b/node_modules/winston/test/transports/http-test.js new file mode 100644 index 0000000..65f3cc7 --- /dev/null +++ b/node_modules/winston/test/transports/http-test.js @@ -0,0 +1,70 @@ +/* + * http-test.js: Tests for instances of the HTTP transport + * + * MIT LICENSE + */ + +var path = require('path'), + vows = require('vows'), + http = require('http'), + fs = require('fs'), + assert = require('assert'), + winston = require('../../lib/winston'), + helpers = require('../helpers'), + hock = require('hock'); + +var transport = require('./transport'); + +var host = '127.0.0.1'; + +vows.describe('winston/transports/http').addBatch({ + "When the HTTP endpoint": { + topic: function () { + var mock = this.mock = hock.createHock(), + self = this; + + mock + .post('/log', { + "method":"collect", + "params":{ + "level":"info", + "message":"hello", + "meta":{} + } + }) + .min(1) + .max(1) + .reply(200); + + var server = this.server = http.createServer(mock.handler); + server.listen(0, '0.0.0.0', this.callback); + }, + "is running": function (err) { + assert.ifError(err); + }, + "an instance of the Http transport": { + topic: function () { + + var port = this.server.address().port; + var self = this, + httpTransport = new (winston.transports.Http)({ + host: host, + port: port, + path: 'log' + }); + + httpTransport.log('info', 'hello', function (logErr, logged) { + self.mock.done(function (doneErr) { + self.callback(null, logErr, logged, doneErr); + }); + }); + }, + "should log to the specified URL": function (_, err, logged, requested) { + assert.ifError(err); + assert.isTrue(logged); + assert.ifError(requested); + this.server.close(); + } + } + } +}).export(module); diff --git a/node_modules/winston/test/transports/memory-test.js b/node_modules/winston/test/transports/memory-test.js new file mode 100644 index 0000000..e8e1043 --- /dev/null +++ b/node_modules/winston/test/transports/memory-test.js @@ -0,0 +1,31 @@ +var path = require('path'), + vows = require('vows'), + assert = require('assert'), + winston = require('../../lib/winston'), + helpers = require('../helpers'); + +var npmTransport = new (winston.transports.Memory)(), + syslogTransport = new (winston.transports.Memory)({ levels: winston.config.syslog.levels }); + +vows.describe('winston/transports/memory').addBatch({ + "An instance of the Memory Transport": { + "with npm levels": { + "should have the proper methods defined": function () { + helpers.assertMemory(npmTransport); + }, + "the log() method": helpers.testNpmLevels(npmTransport, "should respond with true", function (ign, err, logged) { + assert.isNull(err); + assert.isTrue(logged); + }) + }, + "with syslog levels": { + "should have the proper methods defined": function () { + helpers.assertMemory(syslogTransport); + }, + "the log() method": helpers.testSyslogLevels(syslogTransport, "should respond with true", function (ign, err, logged) { + assert.isNull(err); + assert.isTrue(logged); + }) + } + } +}).export(module);
\ No newline at end of file diff --git a/node_modules/winston/test/transports/transport.js b/node_modules/winston/test/transports/transport.js new file mode 100644 index 0000000..0abf80a --- /dev/null +++ b/node_modules/winston/test/transports/transport.js @@ -0,0 +1,212 @@ +var assert = require('assert'), + winston = require('../../lib/winston'), + helpers = require('../helpers'); + +module.exports = function (transport, options) { + var logger = transport instanceof winston.Logger + ? transport + : new winston.Logger({ + transports: [ + new transport(options) + ] + }); + + // hack to fix transports that don't log + // any unit of time smaller than seconds + var common = require('../../lib/winston/common'); + common.timestamp = function() { + return new Date().toISOString(); + }; + + var transport = logger.transports[logger._names[0]]; + + var out = { + 'topic': logger, + 'when passed valid options': { + 'should have the proper methods defined': function () { + switch (transport.name) { + case 'console': + helpers.assertConsole(transport); + break; + case 'file': + helpers.assertFile(transport); + break; + case 'couchdb': + helpers.assertCouchdb(transport); + break; + } + assert.isFunction(transport.log); + } + }, + 'the log() method': helpers.testNpmLevels(transport, + 'should respond with true', function (ign, err, logged) { + assert.isNull(err); + assert.isNotNull(logged); + } + ), + 'the stream() method': { + 'using no options': { + 'topic': function () { + if (!transport.stream) return; + + logger.log('info', 'hello world', {}); + + var cb = this.callback, + j = 10, + i = 10, + results = [], + stream = logger.stream(); + + stream.on('log', function (log) { + results.push(log); + results.stream = stream; + if (!--j) cb(null, results); + }); + + stream.on('error', function (err) { + j = -1; //don't call the callback again + cb(err); + }); + + while (i--) logger.log('info', 'hello world ' + i, {}); + }, + 'should stream logs': function (err, results) { + if (!transport.stream) return; + assert.isNull(err); + results.forEach(function (log) { + assert.ok(log.message.indexOf('hello world') === 0 + || log.message.indexOf('test message') === 0); + }); + results.stream.destroy(); + } + }, + 'using the `start` option': { + 'topic': function () { + if (!transport.stream) return; + + var cb = this.callback, + stream = logger.stream({ start: 0 }); + + stream.on('log', function (log) { + log.stream = stream; + if (cb) cb(null, log); + cb = null; + }); + }, + 'should stream logs': function (err, log) { + if (!transport.stream) return; + assert.isNull(err); + assert.isNotNull(log.message); + log.stream.destroy(); + } + } + }, + 'after the logs have flushed': { + topic: function () { + setTimeout(this.callback, 1000); + }, + 'the query() method': { + 'using basic querying': { + 'topic': function () { + if (!transport.query) return; + var cb = this.callback; + logger.log('info', 'hello world', {}, function () { + logger.query(cb); + }); + }, + 'should return matching results': function (err, results) { + if (!transport.query) return; + assert.isNull(err); + results = results[transport.name]; + while (!Array.isArray(results)) { + results = results[Object.keys(results).pop()]; + } + var log = results.pop(); + assert.ok(log.message.indexOf('hello world') === 0 + || log.message.indexOf('test message') === 0); + } + }, + 'using the `rows` option': { + 'topic': function () { + if (!transport.query) return; + var cb = this.callback; + logger.log('info', 'hello world', {}, function () { + logger.query({ rows: 1 }, cb); + }); + }, + 'should return one result': function (err, results) { + if (!transport.query) return; + assert.isNull(err); + results = results[transport.name]; + while (!Array.isArray(results)) { + results = results[Object.keys(results).pop()]; + } + assert.equal(results.length, 1); + } + }, + 'using `fields` and `order` option': { + 'topic': function () { + if (!transport.query) return; + var cb = this.callback; + logger.log('info', 'hello world', {}, function () { + logger.query({ order: 'asc', fields: ['timestamp'] }, cb); + }); + }, + 'should return matching results': function (err, results) { + if (!transport.query) return; + assert.isNull(err); + results = results[transport.name]; + while (!Array.isArray(results)) { + results = results[Object.keys(results).pop()]; + } + assert.equal(Object.keys(results[0]).length, 1); + assert.ok(new Date(results.shift().timestamp) + < new Date(results.pop().timestamp)); + } + }, + 'using the `from` and `until` option': { + 'topic': function () { + if (!transport.query) return; + var cb = this.callback; + var start = Date.now() - (100 * 1000); + var end = Date.now() + (100 * 1000); + logger.query({ from: start, until: end }, cb); + }, + 'should return matching results': function (err, results) { + if (!transport.query) return; + assert.isNull(err); + results = results[transport.name]; + while (!Array.isArray(results)) { + results = results[Object.keys(results).pop()]; + } + assert.ok(results.length >= 1); + } + }, + 'using a bad `from` and `until` option': { + 'topic': function () { + if (!transport.query) return; + var cb = this.callback; + logger.log('info', 'bad from and until', {}, function () { + var now = Date.now() + 1000000; + logger.query({ from: now, until: now }, cb); + }); + }, + 'should return no results': function (err, results) { + if (!transport.query) return; + assert.isNull(err); + results = results[transport.name]; + while (!Array.isArray(results)) { + results = results[Object.keys(results).pop()]; + } + results = [results.filter(function(log) { + return log.message === 'bad from and until'; + }).pop()]; + assert.isUndefined(results[0]); + } + } + } + } + }; + + return out; +}; diff --git a/node_modules/wrappy/LICENSE b/node_modules/wrappy/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/wrappy/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/wrappy/README.md b/node_modules/wrappy/README.md new file mode 100644 index 0000000..98eab25 --- /dev/null +++ b/node_modules/wrappy/README.md @@ -0,0 +1,36 @@ +# wrappy + +Callback wrapping utility + +## USAGE + +```javascript +var wrappy = require("wrappy") + +// var wrapper = wrappy(wrapperFunction) + +// make sure a cb is called only once +// See also: http://npm.im/once for this specific use case +var once = wrappy(function (cb) { + var called = false + return function () { + if (called) return + called = true + return cb.apply(this, arguments) + } +}) + +function printBoo () { + console.log('boo') +} +// has some rando property +printBoo.iAmBooPrinter = true + +var onlyPrintOnce = once(printBoo) + +onlyPrintOnce() // prints 'boo' +onlyPrintOnce() // does nothing + +// random property is retained! +assert.equal(onlyPrintOnce.iAmBooPrinter, true) +``` diff --git a/node_modules/wrappy/package.json b/node_modules/wrappy/package.json new file mode 100644 index 0000000..21e42de --- /dev/null +++ b/node_modules/wrappy/package.json @@ -0,0 +1,59 @@ +{ + "_from": "wrappy@1", + "_id": "wrappy@1.0.2", + "_inBundle": false, + "_integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "_location": "/wrappy", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "wrappy@1", + "name": "wrappy", + "escapedName": "wrappy", + "rawSpec": "1", + "saveSpec": null, + "fetchSpec": "1" + }, + "_requiredBy": [ + "/inflight", + "/once" + ], + "_resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "_shasum": "b5243d8f3ec1aa35f1364605bc0d1036e30ab69f", + "_spec": "wrappy@1", + "_where": "/data/dev/Projets/Bingoloto Remote/node_modules/inflight", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/npm/wrappy/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Callback wrapping utility", + "devDependencies": { + "tap": "^2.3.1" + }, + "directories": { + "test": "test" + }, + "files": [ + "wrappy.js" + ], + "homepage": "https://github.com/npm/wrappy", + "license": "ISC", + "main": "wrappy.js", + "name": "wrappy", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/wrappy.git" + }, + "scripts": { + "test": "tap --coverage test/*.js" + }, + "version": "1.0.2" +} diff --git a/node_modules/wrappy/wrappy.js b/node_modules/wrappy/wrappy.js new file mode 100644 index 0000000..bb7e7d6 --- /dev/null +++ b/node_modules/wrappy/wrappy.js @@ -0,0 +1,33 @@ +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..36eead2 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,382 @@ +{ + "name": "bingoloto-remote", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@types/color-name": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@types/color-name/-/color-name-1.1.1.tgz", + "integrity": "sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ==" + }, + "ansi-regex": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.0.tgz", + "integrity": "sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg==" + }, + "ansi-styles": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.2.1.tgz", + "integrity": "sha512-9VGjrMsG1vePxcSweQsN20KY/c4zN0h9fLjqAbwbPfahM3t+NL+M9HC8xeXG2I8pX5NoamTGNuomEUFI7fcUjA==", + "requires": { + "@types/color-name": "^1.1.1", + "color-convert": "^2.0.1" + } + }, + "async": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/async/-/async-0.9.2.tgz", + "integrity": "sha1-rqdNXmHB+JlhO/ZL2mbUx48v0X0=" + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "chalk": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.0.tgz", + "integrity": "sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A==", + "requires": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + } + }, + "cli-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", + "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", + "requires": { + "restore-cursor": "^3.1.0" + } + }, + "cli-spinners": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.4.0.tgz", + "integrity": "sha512-sJAofoarcm76ZGpuooaO0eDy8saEy+YoZBLjC4h8srt4jeBnkYeOgqxgsJQTpyt2LjI5PTfLJHSL+41Yu4fEJA==" + }, + "clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=" + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "colors": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.4.0.tgz", + "integrity": "sha512-a+UqTh4kgZg/SlGvfbzDHpgRu7AAQOmmqRHJnxhRZICKFUT91brVhNNt58CMWU9PsBbv3PDCZUHbVxuDiH2mtA==" + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, + "cycle": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz", + "integrity": "sha1-IegLK+hYD5i0aPN5QwZisEbDStI=" + }, + "deep-equal": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-0.2.2.tgz", + "integrity": "sha1-hLdFiW80xoTpjyzg5Cq69Du6AX0=" + }, + "defaults": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.3.tgz", + "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", + "requires": { + "clone": "^1.0.2" + } + }, + "eyes": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/eyes/-/eyes-0.1.8.tgz", + "integrity": "sha1-Ys8SAjTGg3hdkCNIqADvPgzCC8A=" + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=" + }, + "glob": { + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==" + }, + "i": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/i/-/i-0.3.6.tgz", + "integrity": "sha1-2WyScyB28HJxG2sQ/X1PZa2O4j0=" + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "is-interactive": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", + "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==" + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=" + }, + "log-symbols": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.0.0.tgz", + "integrity": "sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA==", + "requires": { + "chalk": "^4.0.0" + } + }, + "mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==" + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==" + }, + "mkdirp": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz", + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==", + "requires": { + "minimist": "^1.2.5" + } + }, + "mute-stream": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", + "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==" + }, + "ncp": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ncp/-/ncp-1.0.1.tgz", + "integrity": "sha1-0VNn5cuHQyuhF9K/gP30Wuz7QkY=" + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "ora": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ora/-/ora-5.0.0.tgz", + "integrity": "sha512-s26qdWqke2kjN/wC4dy+IQPBIMWBJlSU/0JZhk30ZDBLelW25rv66yutUWARMigpGPzcXHb+Nac5pNhN/WsARw==", + "requires": { + "chalk": "^4.1.0", + "cli-cursor": "^3.1.0", + "cli-spinners": "^2.4.0", + "is-interactive": "^1.0.0", + "log-symbols": "^4.0.0", + "mute-stream": "0.0.8", + "strip-ansi": "^6.0.0", + "wcwidth": "^1.0.1" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" + }, + "pkginfo": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.4.1.tgz", + "integrity": "sha1-tUGO8EOd5UJfxJlQQtztFPsqhP8=" + }, + "prompt": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/prompt/-/prompt-1.0.0.tgz", + "integrity": "sha1-jlcSPDlquYiJf7Mn/Trtw+c15P4=", + "requires": { + "colors": "^1.1.2", + "pkginfo": "0.x.x", + "read": "1.0.x", + "revalidator": "0.1.x", + "utile": "0.3.x", + "winston": "2.1.x" + } + }, + "read": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/read/-/read-1.0.7.tgz", + "integrity": "sha1-s9oZvQUkMal2cdRKQmNK33ELQMQ=", + "requires": { + "mute-stream": "~0.0.4" + } + }, + "restore-cursor": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", + "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", + "requires": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + } + }, + "revalidator": { + "version": "0.1.8", + "resolved": "https://registry.npmjs.org/revalidator/-/revalidator-0.1.8.tgz", + "integrity": "sha1-/s5hv6DBtSoga9axgZgYS91SOjs=" + }, + "rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "requires": { + "glob": "^7.1.3" + } + }, + "signal-exit": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", + "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==" + }, + "stack-trace": { + "version": "0.0.10", + "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz", + "integrity": "sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=" + }, + "strip-ansi": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.0.tgz", + "integrity": "sha512-AuvKTrTfQNYNIctbR1K/YGTR1756GycPsg7b9bdV9Duqur4gv6aKqHXah67Z8ImS7WEz5QVcOtlfW2rZEugt6w==", + "requires": { + "ansi-regex": "^5.0.0" + } + }, + "supports-color": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.1.0.tgz", + "integrity": "sha512-oRSIpR8pxT1Wr2FquTNnGet79b3BWljqOuoW/h4oBhxJ/HUbX5nX6JSruTkvXDCFMwDPvsaTTbvMLKZWSy0R5g==", + "requires": { + "has-flag": "^4.0.0" + } + }, + "utile": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/utile/-/utile-0.3.0.tgz", + "integrity": "sha1-E1LDQOuCDk2N26A5pPv6oy7U7zo=", + "requires": { + "async": "~0.9.0", + "deep-equal": "~0.2.1", + "i": "0.3.x", + "mkdirp": "0.x.x", + "ncp": "1.0.x", + "rimraf": "2.x.x" + } + }, + "wcwidth": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", + "integrity": "sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g=", + "requires": { + "defaults": "^1.0.3" + } + }, + "winston": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/winston/-/winston-2.1.1.tgz", + "integrity": "sha1-PJNJ0ZYgf9G9/51LxD73JRDjoS4=", + "requires": { + "async": "~1.0.0", + "colors": "1.0.x", + "cycle": "1.0.x", + "eyes": "0.1.x", + "isstream": "0.1.x", + "pkginfo": "0.3.x", + "stack-trace": "0.0.x" + }, + "dependencies": { + "async": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async/-/async-1.0.0.tgz", + "integrity": "sha1-+PwEyjoTeErenhZBr5hXjPvWR6k=" + }, + "colors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz", + "integrity": "sha1-BDP0TYCWgP3rYO0mDxsMJi6CpAs=" + }, + "pkginfo": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/pkginfo/-/pkginfo-0.3.1.tgz", + "integrity": "sha1-Wyn2qB9wcXFC4J52W76rl7T4HiE=" + } + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..5838c95 --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "bingoloto-remote", + "version": "1.0.0", + "description": "", + "main": "index.js", + "dependencies": { + "chalk": "^4.1.0", + "ora": "^5.0.0", + "prompt": "^1.0.0" + }, + "devDependencies": {}, + "scripts": { + "start": "node index.js" + }, + "author": "", + "license": "ISC" +} |