diff --git a/api/users.js b/api/users.js index db063f8..4faf5da 100644 --- a/api/users.js +++ b/api/users.js @@ -37,4 +37,31 @@ router.post('/', function(req,res,next){ }); }); + +// 로그인한 유저정보 가져오기 +router.get('/',auth,function(req,res,next){ + + var userId=req.decoded.userId; + + getConnection((conn)=>{ + var sql = "SELECT * FROM user WHERE id=?" + conn.query( + sql, // excute sql + [userId], // ? <- value + function(err, result){ + if(err){ + console.error(err); + res.json(util.successFalse(err)); + throw err; + } + else { + + res.json(util.successTrue(null,'유저 정보')) + } + }) + conn.release(); + }); +}); + + module.exports = router; \ No newline at end of file diff --git a/app.js b/app.js index f80552f..2210c4b 100644 --- a/app.js +++ b/app.js @@ -6,6 +6,10 @@ var bodyParser = require('body-parser'); const app = express(); const port = 3000; +app.set('views', path.join(__dirname, 'views')); // ejs file location +app.set('view engine', 'ejs'); //select view templet engine + + // Middlewares app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); @@ -17,10 +21,13 @@ app.use(function (req, res, next) { }); - +app.get('/', function(req, res){ + res.render('signup'); +}) + // API -app.use('/users', require('./api/users')); -app.use('/auth', require('./api/auth')); +//app.use('/users', require('./api/users')); +//app.use('/auth', require('./api/auth')); // Server app.listen(port, function(){ diff --git a/main.html b/main.html deleted file mode 100644 index 9b03313..0000000 --- a/main.html +++ /dev/null @@ -1 +0,0 @@ -dksjflsf \ No newline at end of file diff --git a/node_modules/.bin/ejs b/node_modules/.bin/ejs new file mode 100644 index 0000000..0b9c6b7 --- /dev/null +++ b/node_modules/.bin/ejs @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../ejs/bin/cli.js" "$@" + ret=$? +else + node "$basedir/../ejs/bin/cli.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/ejs.cmd b/node_modules/.bin/ejs.cmd new file mode 100644 index 0000000..3bb42ad --- /dev/null +++ b/node_modules/.bin/ejs.cmd @@ -0,0 +1,17 @@ +@ECHO off +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +"%_prog%" "%dp0%\..\ejs\bin\cli.js" %* +ENDLOCAL +EXIT /b %errorlevel% +:find_dp0 +SET dp0=%~dp0 +EXIT /b diff --git a/node_modules/.bin/ejs.ps1 b/node_modules/.bin/ejs.ps1 new file mode 100644 index 0000000..78e73c8 --- /dev/null +++ b/node_modules/.bin/ejs.ps1 @@ -0,0 +1,18 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + & "$basedir/node$exe" "$basedir/../ejs/bin/cli.js" $args + $ret=$LASTEXITCODE +} else { + & "node$exe" "$basedir/../ejs/bin/cli.js" $args + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/jake b/node_modules/.bin/jake new file mode 100644 index 0000000..df203c1 --- /dev/null +++ b/node_modules/.bin/jake @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../jake/bin/cli.js" "$@" + ret=$? +else + node "$basedir/../jake/bin/cli.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/jake.cmd b/node_modules/.bin/jake.cmd new file mode 100644 index 0000000..5b09dcb --- /dev/null +++ b/node_modules/.bin/jake.cmd @@ -0,0 +1,17 @@ +@ECHO off +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +"%_prog%" "%dp0%\..\jake\bin\cli.js" %* +ENDLOCAL +EXIT /b %errorlevel% +:find_dp0 +SET dp0=%~dp0 +EXIT /b diff --git a/node_modules/.bin/jake.ps1 b/node_modules/.bin/jake.ps1 new file mode 100644 index 0000000..bbe80ea --- /dev/null +++ b/node_modules/.bin/jake.ps1 @@ -0,0 +1,18 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + & "$basedir/node$exe" "$basedir/../jake/bin/cli.js" $args + $ret=$LASTEXITCODE +} else { + & "node$exe" "$basedir/../jake/bin/cli.js" $args + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/ansi-styles/index.js b/node_modules/ansi-styles/index.js new file mode 100644 index 0000000..90a871c --- /dev/null +++ b/node_modules/ansi-styles/index.js @@ -0,0 +1,165 @@ +'use strict'; +const colorConvert = require('color-convert'); + +const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +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], + gray: [90, 39], + + // Bright color + 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] + } + }; + + // Fix humans + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + + 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 + }); + } + + const ansi2ansi = n => n; + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + 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.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..9f18a56 --- /dev/null +++ b/node_modules/ansi-styles/package.json @@ -0,0 +1,88 @@ +{ + "_from": "ansi-styles@^3.2.1", + "_id": "ansi-styles@3.2.1", + "_inBundle": false, + "_integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "_location": "/ansi-styles", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "ansi-styles@^3.2.1", + "name": "ansi-styles", + "escapedName": "ansi-styles", + "rawSpec": "^3.2.1", + "saveSpec": null, + "fetchSpec": "^3.2.1" + }, + "_requiredBy": [ + "/chalk" + ], + "_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "_shasum": "41fbb20243e50b12be0f04b8dedbf07520ce841d", + "_spec": "ansi-styles@^3.2.1", + "_where": "C:\\angel\\node_modules\\chalk", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "ava": { + "require": "babel-polyfill" + }, + "bugs": { + "url": "https://github.com/chalk/ansi-styles/issues" + }, + "bundleDependencies": false, + "dependencies": { + "color-convert": "^1.9.0" + }, + "deprecated": false, + "description": "ANSI escape codes for styling strings in the terminal", + "devDependencies": { + "ava": "*", + "babel-polyfill": "^6.23.0", + "svg-term-cli": "^2.1.1", + "xo": "*" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js" + ], + "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" + }, + "version": "3.2.1" +} diff --git a/node_modules/ansi-styles/readme.md b/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000..3158e2d --- /dev/null +++ b/node_modules/ansi-styles/readme.md @@ -0,0 +1,147 @@ +# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) + +> [ANSI escape codes](http://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. + + + + +## 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` +- `gray` ("bright black") +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` +- `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. + +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-) + + +## License + +MIT 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 + + +``` + +## 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 + + + +### 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'); + } +}); +``` + +--------------------------------------- + + + +### 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. + + +--------------------------------------- + + + +### 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 +}); +``` + +--------------------------------------- + + +### 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 +}); +``` + +--------------------------------------- + + +### 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. + + +--------------------------------------- + + +### 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 +}); +``` + +--------------------------------------- + + + +### 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 +}); +``` + +--------------------------------------- + + + +### 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. + +--------------------------------------- + + +### reject(arr, iterator, callback) + +The opposite of [`filter`](#filter). Removes values that pass an `async` truth test. + +--------------------------------------- + + +### rejectSeries(arr, iterator, callback) + +The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr` +in series. + + +--------------------------------------- + + +### 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 +}); +``` + +--------------------------------------- + + +### reduceRight(arr, memo, iterator, callback) + +__Alias:__ `foldr` + +Same as [`reduce`](#reduce), only operates on `arr` in reverse order. + + +--------------------------------------- + + +### 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 +}); +``` + +--------------------------------------- + + +### 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. + + +--------------------------------------- + + +### 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 +} ); +``` + +--------------------------------------- + + +### 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 +}); +``` + +--------------------------------------- + + +### 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 +}); +``` + +--------------------------------------- + + +### 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 +}); +``` + +--------------------------------------- + + +### concatSeries(arr, iterator, callback) + +Same as [`concat`](#concat), but executes in series instead of parallel. + + +## Control Flow + + +### 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} +}); +``` + +--------------------------------------- + + +### 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} +}); +``` + +--------------------------------------- + + +### 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. + +--------------------------------------- + + +### 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 + } +); +``` + +--------------------------------------- + + +### 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. + +--------------------------------------- + + +### until(test, fn, callback) + +Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped, +or an error occurs. + +The inverse of [`whilst`](#whilst). + +--------------------------------------- + + +### doUntil(fn, test, callback) + +Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`. + +--------------------------------------- + + +### 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. + } +); +``` + +--------------------------------------- + + +### 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' +}); +``` + +--------------------------------------- + +### 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 +}); +``` + +--------------------------------------- + +### 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 }); + } + }); +}); +``` + +--------------------------------------- + +### 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 +); +``` + +--------------------------------------- + + +### applyEachSeries(arr, iterator, callback) + +The same as [`applyEach`](#applyEach) only the functions are applied in series. + +--------------------------------------- + + +### 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'); +}); +``` + + +--------------------------------------- + + +### 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. + +--------------------------------------- + + +### 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 +### 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). + + +--------------------------------------- + + +### 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 +}); +``` + + +--------------------------------------- + + +### 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' +``` + +--------------------------------------- + + +### 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 +``` + +--------------------------------------- + + +### 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') +``` + + +### 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 +}); +``` + + +### 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 + + +### 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 +}); +``` + + +### unmemoize(fn) + +Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized +form. Handy for testing. + +__Arguments__ + +* `fn` - the memoized function + + +### 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' +``` + +--------------------------------------- + + +### 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'} +``` + +--------------------------------------- + + +### 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 + +``` + +### Caveats + +Most of EJS will work as expected; however, there are a few things to note: + +1. Obviously, since you do not have access to the filesystem, `ejs.renderFile()` won't work. +2. For the same reason, `include`s do not work unless you use an `include callback`. Here is an example: + ```javascript + let str = "Hello <%= include('file', {person: 'John'}); %>", + fn = ejs.compile(str, {client: true}); + + fn(data, null, function(path, d){ // include callback + // path -> 'file' + // d -> {person: 'John'} + // Put your code here + // Return the contents of file as a string + }); // returns rendered string + ``` + +See the [examples folder](https://github.com/mde/ejs/tree/master/examples) for more details. + +## CLI + +EJS ships with a full-featured CLI. Available options are similar to those used in JavaScript code: + + - `-o / --output-file FILE` Write the rendered output to FILE rather than stdout. + - `-f / --data-file FILE` Must be JSON-formatted. Use parsed input from FILE as data for rendering. + - `-i / --data-input STRING` Must be JSON-formatted and URI-encoded. Use parsed input from STRING as data for rendering. + - `-m / --delimiter CHARACTER` Use CHARACTER with angle brackets for open/close (defaults to %). + - `-p / --open-delimiter CHARACTER` Use CHARACTER instead of left angle bracket to open. + - `-c / --close-delimiter CHARACTER` Use CHARACTER instead of right angle bracket to close. + - `-s / --strict` When set to `true`, generated function is in strict mode + - `-n / --no-with` Use 'locals' object for vars rather than using `with` (implies --strict). + - `-l / --locals-name` Name to use for the object storing local variables when not using `with`. + - `-w / --rm-whitespace` Remove all safe-to-remove whitespace, including leading and trailing whitespace. + - `-d / --debug` Outputs generated function body + - `-h / --help` Display this help message. + - `-V/v / --version` Display the EJS version. + +Here are some examples of usage: + +```shell +$ ejs -p [ -c ] ./template_file.ejs -o ./output.html +$ ejs ./test/fixtures/user.ejs name=Lerxst +$ ejs -n -l _ ./some_template.ejs -f ./data_file.json +``` + +### Data input + +There is a variety of ways to pass the CLI data for rendering. + +Stdin: + +```shell +$ ./test/fixtures/user_data.json | ./bin/cli.js ./test/fixtures/user.ejs +$ ./bin/cli.js ./test/fixtures/user.ejs < test/fixtures/user_data.json +``` + +A data file: + +```shell +$ ejs ./test/fixtures/user.ejs -f ./user_data.json +``` + +A command-line option (must be URI-encoded): + +```shell +./bin/cli.js -i %7B%22name%22%3A%20%22foo%22%7D ./test/fixtures/user.ejs +``` + +Or, passing values directly at the end of the invocation: + +```shell +./bin/cli.js -m $ ./test/fixtures/user.ejs name=foo +``` + +### Output + +The CLI by default send output to stdout, but you can use the `-o` or `--output-file` +flag to specify a target file to send the output to. + +## IDE Integration with Syntax Highlighting + +VSCode:Javascript EJS by *DigitalBrainstem* + +## Related projects + +There are a number of implementations of EJS: + + * TJ's implementation, the v1 of this library: https://github.com/tj/ejs + * EJS Embedded JavaScript Framework on Google Code: https://code.google.com/p/embeddedjavascript/ + * Sam Stephenson's Ruby implementation: https://rubygems.org/gems/ejs + * Erubis, an ERB implementation which also runs JavaScript: http://www.kuwata-lab.com/erubis/users-guide.04.html#lang-javascript + * DigitalBrainstem EJS Language support: https://github.com/Digitalbrainstem/ejs-grammar + +## License + +Licensed under the Apache License, Version 2.0 +() + +- - - +EJS Embedded JavaScript templates copyright 2112 +mde@fleegix.org. diff --git a/node_modules/ejs/bin/cli.js b/node_modules/ejs/bin/cli.js new file mode 100644 index 0000000..29408f1 --- /dev/null +++ b/node_modules/ejs/bin/cli.js @@ -0,0 +1,208 @@ +#!/usr/bin/env node +/* + * EJS Embedded JavaScript templates + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + + +let program = require('jake').program; +delete global.jake; // NO NOT WANT +program.setTaskNames = function (n) { this.taskNames = n; }; + +let ejs = require('../lib/ejs'); +let fs = require('fs'); +let args = process.argv.slice(2); +let usage = fs.readFileSync(`${__dirname}/../usage.txt`).toString(); + +const CLI_OPTS = [ + { full: 'output-file', + abbr: 'o', + expectValue: true, + }, + { full: 'data-file', + abbr: 'f', + expectValue: true, + }, + { full: 'data-input', + abbr: 'i', + expectValue: true, + }, + { full: 'delimiter', + abbr: 'm', + expectValue: true, + passThrough: true, + }, + { full: 'open-delimiter', + abbr: 'p', + expectValue: true, + passThrough: true, + }, + { full: 'close-delimiter', + abbr: 'c', + expectValue: true, + passThrough: true, + }, + { full: 'strict', + abbr: 's', + expectValue: false, + allowValue: false, + passThrough: true, + }, + { full: 'no-with', + abbr: 'n', + expectValue: false, + allowValue: false, + }, + { full: 'locals-name', + abbr: 'l', + expectValue: true, + passThrough: true, + }, + { full: 'rm-whitespace', + abbr: 'w', + expectValue: false, + allowValue: false, + passThrough: true, + }, + { full: 'debug', + abbr: 'd', + expectValue: false, + allowValue: false, + passThrough: true, + }, + { full: 'help', + abbr: 'h', + passThrough: true, + }, + { full: 'version', + abbr: 'V', + passThrough: true, + }, + // Alias lowercase v + { full: 'version', + abbr: 'v', + passThrough: true, + }, +]; + +let preempts = { + version: function () { + program.die(ejs.VERSION); + }, + help: function () { + program.die(usage); + } +}; + +let stdin = ''; +process.stdin.setEncoding('utf8'); +process.stdin.on('readable', () => { + let chunk; + while ((chunk = process.stdin.read()) !== null) { + stdin += chunk; + } +}); + +function run() { + + program.availableOpts = CLI_OPTS; + program.parseArgs(args); + + let templatePath = program.taskNames[0]; + let pVals = program.envVars; + let pOpts = {}; + + for (let p in program.opts) { + let name = p.replace(/-[a-z]/g, (match) => { return match[1].toUpperCase(); }); + pOpts[name] = program.opts[p]; + } + + let opts = {}; + let vals = {}; + + // Same-named 'passthrough' opts + CLI_OPTS.forEach((opt) => { + let optName = opt.full; + if (opt.passThrough && typeof pOpts[optName] != 'undefined') { + opts[optName] = pOpts[optName]; + } + }); + + // Bail out for help/version + for (let p in opts) { + if (preempts[p]) { + return preempts[p](); + } + } + + // Ensure there's a template to render + if (!templatePath) { + throw new Error('Please provide a template path. (Run ejs -h for help)'); + } + + if (opts.strict) { + pOpts.noWith = true; + } + if (pOpts.noWith) { + opts._with = false; + } + + // Grab and parse any input data, in order of precedence: + // 1. Stdin + // 2. CLI arg via -i + // 3. Data file via -f + // Any individual vals passed at the end (e.g., foo=bar) will override + // any vals previously set + let input; + let err = new Error('Please do not pass data multiple ways. Pick one of stdin, -f, or -i.'); + if (stdin) { + input = stdin; + } + else if (pOpts.dataInput) { + if (input) { + throw err; + } + input = decodeURIComponent(pOpts.dataInput); + } + else if (pOpts.dataFile) { + if (input) { + throw err; + } + input = fs.readFileSync(pOpts.dataFile).toString(); + } + + if (input) { + vals = JSON.parse(input); + } + + // Override / set any individual values passed from the command line + for (let p in pVals) { + vals[p] = pVals[p]; + } + + let template = fs.readFileSync(templatePath).toString(); + let output = ejs.render(template, vals, opts); + if (pOpts.outputFile) { + fs.writeFileSync(pOpts.outputFile, output); + } + else { + process.stdout.write(output); + } + process.exit(); +} + +// Defer execution so that stdin can be read if necessary +setImmediate(run); diff --git a/node_modules/ejs/ejs.js b/node_modules/ejs/ejs.js new file mode 100644 index 0000000..4b4c359 --- /dev/null +++ b/node_modules/ejs/ejs.js @@ -0,0 +1,1650 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ejs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i + * @author Tiancheng "Timothy" Gu + * @project EJS + * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0} + */ + +/** + * EJS internal functions. + * + * Technically this "module" lies in the same file as {@link module:ejs}, for + * the sake of organization all the private functions re grouped into this + * module. + * + * @module ejs-internal + * @private + */ + +/** + * Embedded JavaScript templating engine. + * + * @module ejs + * @public + */ + +var fs = require('fs'); +var path = require('path'); +var utils = require('./utils'); + +var scopeOptionWarned = false; +/** @type {string} */ +var _VERSION_STRING = require('../package.json').version; +var _DEFAULT_OPEN_DELIMITER = '<'; +var _DEFAULT_CLOSE_DELIMITER = '>'; +var _DEFAULT_DELIMITER = '%'; +var _DEFAULT_LOCALS_NAME = 'locals'; +var _NAME = 'ejs'; +var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)'; +var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug', + 'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async']; +// We don't allow 'cache' option to be passed in the data obj for +// the normal `render` call, but this is where Express 2 & 3 put it +// so we make an exception for `renderFile` +var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache'); +var _BOM = /^\uFEFF/; + +/** + * EJS template function cache. This can be a LRU object from lru-cache NPM + * module. By default, it is {@link module:utils.cache}, a simple in-process + * cache that grows continuously. + * + * @type {Cache} + */ + +exports.cache = utils.cache; + +/** + * Custom file loader. Useful for template preprocessing or restricting access + * to a certain part of the filesystem. + * + * @type {fileLoader} + */ + +exports.fileLoader = fs.readFileSync; + +/** + * Name of the object containing the locals. + * + * This variable is overridden by {@link Options}`.localsName` if it is not + * `undefined`. + * + * @type {String} + * @public + */ + +exports.localsName = _DEFAULT_LOCALS_NAME; + +/** + * Promise implementation -- defaults to the native implementation if available + * This is mostly just for testability + * + * @type {PromiseConstructorLike} + * @public + */ + +exports.promiseImpl = (new Function('return this;'))().Promise; + +/** + * Get the path to the included file from the parent file path and the + * specified path. + * + * @param {String} name specified path + * @param {String} filename parent file path + * @param {Boolean} [isDir=false] whether the parent file path is a directory + * @return {String} + */ +exports.resolveInclude = function(name, filename, isDir) { + var dirname = path.dirname; + var extname = path.extname; + var resolve = path.resolve; + var includePath = resolve(isDir ? filename : dirname(filename), name); + var ext = extname(name); + if (!ext) { + includePath += '.ejs'; + } + return includePath; +}; + +/** + * Try to resolve file path on multiple directories + * + * @param {String} name specified path + * @param {Array} paths list of possible parent directory paths + * @return {String} + */ +function resolvePaths(name, paths) { + var filePath; + if (paths.some(function (v) { + filePath = exports.resolveInclude(name, v, true); + return fs.existsSync(filePath); + })) { + return filePath; + } +} + +/** + * Get the path to the included file by Options + * + * @param {String} path specified path + * @param {Options} options compilation options + * @return {String} + */ +function getIncludePath(path, options) { + var includePath; + var filePath; + var views = options.views; + var match = /^[A-Za-z]+:\\|^\//.exec(path); + + // Abs path + if (match && match.length) { + path = path.replace(/^\/*/, ''); + if (Array.isArray(options.root)) { + includePath = resolvePaths(path, options.root); + } else { + includePath = exports.resolveInclude(path, options.root || '/', true); + } + } + // Relative paths + else { + // Look relative to a passed filename first + if (options.filename) { + filePath = exports.resolveInclude(path, options.filename); + if (fs.existsSync(filePath)) { + includePath = filePath; + } + } + // Then look in any views directories + if (!includePath && Array.isArray(views)) { + includePath = resolvePaths(path, views); + } + if (!includePath && typeof options.includer !== 'function') { + throw new Error('Could not find the include file "' + + options.escapeFunction(path) + '"'); + } + } + return includePath; +} + +/** + * Get the template from a string or a file, either compiled on-the-fly or + * read from cache (if enabled), and cache the template if needed. + * + * If `template` is not set, the file specified in `options.filename` will be + * read. + * + * If `options.cache` is true, this function reads the file from + * `options.filename` so it must be set prior to calling this function. + * + * @memberof module:ejs-internal + * @param {Options} options compilation options + * @param {String} [template] template source + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `options.client`, either type might be returned. + * @static + */ + +function handleCache(options, template) { + var func; + var filename = options.filename; + var hasTemplate = arguments.length > 1; + + if (options.cache) { + if (!filename) { + throw new Error('cache option requires a filename'); + } + func = exports.cache.get(filename); + if (func) { + return func; + } + if (!hasTemplate) { + template = fileLoader(filename).toString().replace(_BOM, ''); + } + } + else if (!hasTemplate) { + // istanbul ignore if: should not happen at all + if (!filename) { + throw new Error('Internal EJS error: no file name or template ' + + 'provided'); + } + template = fileLoader(filename).toString().replace(_BOM, ''); + } + func = exports.compile(template, options); + if (options.cache) { + exports.cache.set(filename, func); + } + return func; +} + +/** + * Try calling handleCache with the given options and data and call the + * callback with the result. If an error occurs, call the callback with + * the error. Used by renderFile(). + * + * @memberof module:ejs-internal + * @param {Options} options compilation options + * @param {Object} data template data + * @param {RenderFileCallback} cb callback + * @static + */ + +function tryHandleCache(options, data, cb) { + var result; + if (!cb) { + if (typeof exports.promiseImpl == 'function') { + return new exports.promiseImpl(function (resolve, reject) { + try { + result = handleCache(options)(data); + resolve(result); + } + catch (err) { + reject(err); + } + }); + } + else { + throw new Error('Please provide a callback function'); + } + } + else { + try { + result = handleCache(options)(data); + } + catch (err) { + return cb(err); + } + + cb(null, result); + } +} + +/** + * fileLoader is independent + * + * @param {String} filePath ejs file path. + * @return {String} The contents of the specified file. + * @static + */ + +function fileLoader(filePath){ + return exports.fileLoader(filePath); +} + +/** + * Get the template function. + * + * If `options.cache` is `true`, then the template is cached. + * + * @memberof module:ejs-internal + * @param {String} path path for the specified file + * @param {Options} options compilation options + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `options.client`, either type might be returned + * @static + */ + +function includeFile(path, options) { + var opts = utils.shallowCopy({}, options); + opts.filename = getIncludePath(path, opts); + if (typeof options.includer === 'function') { + var includerResult = options.includer(path, opts.filename); + if (includerResult) { + if (includerResult.filename) { + opts.filename = includerResult.filename; + } + if (includerResult.template) { + return handleCache(opts, includerResult.template); + } + } + } + return handleCache(opts); +} + +/** + * Re-throw the given `err` in context to the `str` of ejs, `filename`, and + * `lineno`. + * + * @implements {RethrowCallback} + * @memberof module:ejs-internal + * @param {Error} err Error object + * @param {String} str EJS source + * @param {String} flnm file name of the EJS file + * @param {Number} lineno line number of the error + * @param {EscapeCallback} esc + * @static + */ + +function rethrow(err, str, flnm, lineno, esc) { + var lines = str.split('\n'); + var start = Math.max(lineno - 3, 0); + var end = Math.min(lines.length, lineno + 3); + var filename = esc(flnm); + // Error context + var context = lines.slice(start, end).map(function (line, i){ + var curr = i + start + 1; + return (curr == lineno ? ' >> ' : ' ') + + curr + + '| ' + + line; + }).join('\n'); + + // Alter exception message + err.path = filename; + err.message = (filename || 'ejs') + ':' + + lineno + '\n' + + context + '\n\n' + + err.message; + + throw err; +} + +function stripSemi(str){ + return str.replace(/;(\s*$)/, '$1'); +} + +/** + * Compile the given `str` of ejs into a template function. + * + * @param {String} template EJS template + * + * @param {Options} [opts] compilation options + * + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `opts.client`, either type might be returned. + * Note that the return type of the function also depends on the value of `opts.async`. + * @public + */ + +exports.compile = function compile(template, opts) { + var templ; + + // v1 compat + // 'scope' is 'context' + // FIXME: Remove this in a future version + if (opts && opts.scope) { + if (!scopeOptionWarned){ + console.warn('`scope` option is deprecated and will be removed in EJS 3'); + scopeOptionWarned = true; + } + if (!opts.context) { + opts.context = opts.scope; + } + delete opts.scope; + } + templ = new Template(template, opts); + return templ.compile(); +}; + +/** + * Render the given `template` of ejs. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + * + * @param {String} template EJS template + * @param {Object} [data={}] template data + * @param {Options} [opts={}] compilation and rendering options + * @return {(String|Promise)} + * Return value type depends on `opts.async`. + * @public + */ + +exports.render = function (template, d, o) { + var data = d || {}; + var opts = o || {}; + + // No options object -- if there are optiony names + // in the data, copy them to options + if (arguments.length == 2) { + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA); + } + + return handleCache(opts, template)(data); +}; + +/** + * Render an EJS file at the given `path` and callback `cb(err, str)`. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + * + * @param {String} path path to the EJS file + * @param {Object} [data={}] template data + * @param {Options} [opts={}] compilation and rendering options + * @param {RenderFileCallback} cb callback + * @public + */ + +exports.renderFile = function () { + var args = Array.prototype.slice.call(arguments); + var filename = args.shift(); + var cb; + var opts = {filename: filename}; + var data; + var viewOpts; + + // Do we have a callback? + if (typeof arguments[arguments.length - 1] == 'function') { + cb = args.pop(); + } + // Do we have data/opts? + if (args.length) { + // Should always have data obj + data = args.shift(); + // Normal passed opts (data obj + opts obj) + if (args.length) { + // Use shallowCopy so we don't pollute passed in opts obj with new vals + utils.shallowCopy(opts, args.pop()); + } + // Special casing for Express (settings + opts-in-data) + else { + // Express 3 and 4 + if (data.settings) { + // Pull a few things from known locations + if (data.settings.views) { + opts.views = data.settings.views; + } + if (data.settings['view cache']) { + opts.cache = true; + } + // Undocumented after Express 2, but still usable, esp. for + // items that are unsafe to be passed along with data, like `root` + viewOpts = data.settings['view options']; + if (viewOpts) { + utils.shallowCopy(opts, viewOpts); + } + } + // Express 2 and lower, values set in app.locals, or people who just + // want to pass options in their data. NOTE: These values will override + // anything previously set in settings or settings['view options'] + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS); + } + opts.filename = filename; + } + else { + data = {}; + } + + return tryHandleCache(opts, data, cb); +}; + +/** + * Clear intermediate JavaScript cache. Calls {@link Cache#reset}. + * @public + */ + +/** + * EJS template class + * @public + */ +exports.Template = Template; + +exports.clearCache = function () { + exports.cache.reset(); +}; + +function Template(text, opts) { + opts = opts || {}; + var options = {}; + this.templateText = text; + /** @type {string | null} */ + this.mode = null; + this.truncate = false; + this.currentLine = 1; + this.source = ''; + options.client = opts.client || false; + options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML; + options.compileDebug = opts.compileDebug !== false; + options.debug = !!opts.debug; + options.filename = opts.filename; + options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER; + options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER; + options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER; + options.strict = opts.strict || false; + options.context = opts.context; + options.cache = opts.cache || false; + options.rmWhitespace = opts.rmWhitespace; + options.root = opts.root; + options.includer = opts.includer; + options.outputFunctionName = opts.outputFunctionName; + options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME; + options.views = opts.views; + options.async = opts.async; + options.destructuredLocals = opts.destructuredLocals; + options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true; + + if (options.strict) { + options._with = false; + } + else { + options._with = typeof opts._with != 'undefined' ? opts._with : true; + } + + this.opts = options; + + this.regex = this.createRegex(); +} + +Template.modes = { + EVAL: 'eval', + ESCAPED: 'escaped', + RAW: 'raw', + COMMENT: 'comment', + LITERAL: 'literal' +}; + +Template.prototype = { + createRegex: function () { + var str = _REGEX_STRING; + var delim = utils.escapeRegExpChars(this.opts.delimiter); + var open = utils.escapeRegExpChars(this.opts.openDelimiter); + var close = utils.escapeRegExpChars(this.opts.closeDelimiter); + str = str.replace(/%/g, delim) + .replace(//g, close); + return new RegExp(str); + }, + + compile: function () { + /** @type {string} */ + var src; + /** @type {ClientFunction} */ + var fn; + var opts = this.opts; + var prepended = ''; + var appended = ''; + /** @type {EscapeCallback} */ + var escapeFn = opts.escapeFunction; + /** @type {FunctionConstructor} */ + var ctor; + + if (!this.source) { + this.generateSource(); + prepended += + ' var __output = "";\n' + + ' function __append(s) { if (s !== undefined && s !== null) __output += s }\n'; + if (opts.outputFunctionName) { + prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n'; + } + if (opts.destructuredLocals && opts.destructuredLocals.length) { + var destructuring = ' var __locals = (' + opts.localsName + ' || {}),\n'; + for (var i = 0; i < opts.destructuredLocals.length; i++) { + var name = opts.destructuredLocals[i]; + if (i > 0) { + destructuring += ',\n '; + } + destructuring += name + ' = __locals.' + name; + } + prepended += destructuring + ';\n'; + } + if (opts._with !== false) { + prepended += ' with (' + opts.localsName + ' || {}) {' + '\n'; + appended += ' }' + '\n'; + } + appended += ' return __output;' + '\n'; + this.source = prepended + this.source + appended; + } + + if (opts.compileDebug) { + src = 'var __line = 1' + '\n' + + ' , __lines = ' + JSON.stringify(this.templateText) + '\n' + + ' , __filename = ' + (opts.filename ? + JSON.stringify(opts.filename) : 'undefined') + ';' + '\n' + + 'try {' + '\n' + + this.source + + '} catch (e) {' + '\n' + + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n' + + '}' + '\n'; + } + else { + src = this.source; + } + + if (opts.client) { + src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src; + if (opts.compileDebug) { + src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src; + } + } + + if (opts.strict) { + src = '"use strict";\n' + src; + } + if (opts.debug) { + console.log(src); + } + if (opts.compileDebug && opts.filename) { + src = src + '\n' + + '//# sourceURL=' + opts.filename + '\n'; + } + + try { + if (opts.async) { + // Have to use generated function for this, since in envs without support, + // it breaks in parsing + try { + ctor = (new Function('return (async function(){}).constructor;'))(); + } + catch(e) { + if (e instanceof SyntaxError) { + throw new Error('This environment does not support async/await'); + } + else { + throw e; + } + } + } + else { + ctor = Function; + } + fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src); + } + catch(e) { + // istanbul ignore else + if (e instanceof SyntaxError) { + if (opts.filename) { + e.message += ' in ' + opts.filename; + } + e.message += ' while compiling ejs\n\n'; + e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n'; + e.message += 'https://github.com/RyanZim/EJS-Lint'; + if (!opts.async) { + e.message += '\n'; + e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.'; + } + } + throw e; + } + + // Return a callable function which will execute the function + // created by the source-code, with the passed data as locals + // Adds a local `include` function which allows full recursive include + var returnedFn = opts.client ? fn : function anonymous(data) { + var include = function (path, includeData) { + var d = utils.shallowCopy({}, data); + if (includeData) { + d = utils.shallowCopy(d, includeData); + } + return includeFile(path, opts)(d); + }; + return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]); + }; + if (opts.filename && typeof Object.defineProperty === 'function') { + var filename = opts.filename; + var basename = path.basename(filename, path.extname(filename)); + try { + Object.defineProperty(returnedFn, 'name', { + value: basename, + writable: false, + enumerable: false, + configurable: true + }); + } catch (e) {/* ignore */} + } + return returnedFn; + }, + + generateSource: function () { + var opts = this.opts; + + if (opts.rmWhitespace) { + // Have to use two separate replace here as `^` and `$` operators don't + // work well with `\r` and empty lines don't work well with the `m` flag. + this.templateText = + this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, ''); + } + + // Slurp spaces and tabs before <%_ and after _%> + this.templateText = + this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>'); + + var self = this; + var matches = this.parseTemplateText(); + var d = this.opts.delimiter; + var o = this.opts.openDelimiter; + var c = this.opts.closeDelimiter; + + if (matches && matches.length) { + matches.forEach(function (line, index) { + var closing; + // If this is an opening tag, check for closing tags + // FIXME: May end up with some false positives here + // Better to store modes as k/v with openDelimiter + delimiter as key + // Then this can simply check against the map + if ( line.indexOf(o + d) === 0 // If it is a tag + && line.indexOf(o + d + d) !== 0) { // and is not escaped + closing = matches[index + 2]; + if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) { + throw new Error('Could not find matching close tag for "' + line + '".'); + } + } + self.scanLine(line); + }); + } + + }, + + parseTemplateText: function () { + var str = this.templateText; + var pat = this.regex; + var result = pat.exec(str); + var arr = []; + var firstPos; + + while (result) { + firstPos = result.index; + + if (firstPos !== 0) { + arr.push(str.substring(0, firstPos)); + str = str.slice(firstPos); + } + + arr.push(result[0]); + str = str.slice(result[0].length); + result = pat.exec(str); + } + + if (str) { + arr.push(str); + } + + return arr; + }, + + _addOutput: function (line) { + if (this.truncate) { + // Only replace single leading linebreak in the line after + // -%> tag -- this is the single, trailing linebreak + // after the tag that the truncation mode replaces + // Handle Win / Unix / old Mac linebreaks -- do the \r\n + // combo first in the regex-or + line = line.replace(/^(?:\r\n|\r|\n)/, ''); + this.truncate = false; + } + if (!line) { + return line; + } + + // Preserve literal slashes + line = line.replace(/\\/g, '\\\\'); + + // Convert linebreaks + line = line.replace(/\n/g, '\\n'); + line = line.replace(/\r/g, '\\r'); + + // Escape double-quotes + // - this will be the delimiter during execution + line = line.replace(/"/g, '\\"'); + this.source += ' ; __append("' + line + '")' + '\n'; + }, + + scanLine: function (line) { + var self = this; + var d = this.opts.delimiter; + var o = this.opts.openDelimiter; + var c = this.opts.closeDelimiter; + var newLineCount = 0; + + newLineCount = (line.split('\n').length - 1); + + switch (line) { + case o + d: + case o + d + '_': + this.mode = Template.modes.EVAL; + break; + case o + d + '=': + this.mode = Template.modes.ESCAPED; + break; + case o + d + '-': + this.mode = Template.modes.RAW; + break; + case o + d + '#': + this.mode = Template.modes.COMMENT; + break; + case o + d + d: + this.mode = Template.modes.LITERAL; + this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n'; + break; + case d + d + c: + this.mode = Template.modes.LITERAL; + this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n'; + break; + case d + c: + case '-' + d + c: + case '_' + d + c: + if (this.mode == Template.modes.LITERAL) { + this._addOutput(line); + } + + this.mode = null; + this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0; + break; + default: + // In script mode, depends on type of tag + if (this.mode) { + // If '//' is found without a line break, add a line break. + switch (this.mode) { + case Template.modes.EVAL: + case Template.modes.ESCAPED: + case Template.modes.RAW: + if (line.lastIndexOf('//') > line.lastIndexOf('\n')) { + line += '\n'; + } + } + switch (this.mode) { + // Just executing code + case Template.modes.EVAL: + this.source += ' ; ' + line + '\n'; + break; + // Exec, esc, and output + case Template.modes.ESCAPED: + this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n'; + break; + // Exec and output + case Template.modes.RAW: + this.source += ' ; __append(' + stripSemi(line) + ')' + '\n'; + break; + case Template.modes.COMMENT: + // Do nothing + break; + // Literal <%% mode, append as raw output + case Template.modes.LITERAL: + this._addOutput(line); + break; + } + } + // In string mode, just add the output + else { + this._addOutput(line); + } + } + + if (self.opts.compileDebug && newLineCount) { + this.currentLine += newLineCount; + this.source += ' ; __line = ' + this.currentLine + '\n'; + } + } +}; + +/** + * Escape characters reserved in XML. + * + * This is simply an export of {@link module:utils.escapeXML}. + * + * If `markup` is `undefined` or `null`, the empty string is returned. + * + * @param {String} markup Input string + * @return {String} Escaped string + * @public + * @func + * */ +exports.escapeXML = utils.escapeXML; + +/** + * Express.js support. + * + * This is an alias for {@link module:ejs.renderFile}, in order to support + * Express.js out-of-the-box. + * + * @func + */ + +exports.__express = exports.renderFile; + +/** + * Version of EJS. + * + * @readonly + * @type {String} + * @public + */ + +exports.VERSION = _VERSION_STRING; + +/** + * Name for detection of EJS. + * + * @readonly + * @type {String} + * @public + */ + +exports.name = _NAME; + +/* istanbul ignore if */ +if (typeof window != 'undefined') { + window.ejs = exports; +} + +},{"../package.json":6,"./utils":2,"fs":3,"path":4}],2:[function(require,module,exports){ +/* + * EJS Embedded JavaScript templates + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +/** + * Private utility functions + * @module utils + * @private + */ + +'use strict'; + +var regExpChars = /[|\\{}()[\]^$+*?.]/g; + +/** + * Escape characters reserved in regular expressions. + * + * If `string` is `undefined` or `null`, the empty string is returned. + * + * @param {String} string Input string + * @return {String} Escaped string + * @static + * @private + */ +exports.escapeRegExpChars = function (string) { + // istanbul ignore if + if (!string) { + return ''; + } + return String(string).replace(regExpChars, '\\$&'); +}; + +var _ENCODE_HTML_RULES = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; +var _MATCH_HTML = /[&<>'"]/g; + +function encode_char(c) { + return _ENCODE_HTML_RULES[c] || c; +} + +/** + * Stringified version of constants used by {@link module:utils.escapeXML}. + * + * It is used in the process of generating {@link ClientFunction}s. + * + * @readonly + * @type {String} + */ + +var escapeFuncStr = + 'var _ENCODE_HTML_RULES = {\n' ++ ' "&": "&"\n' ++ ' , "<": "<"\n' ++ ' , ">": ">"\n' ++ ' , \'"\': """\n' ++ ' , "\'": "'"\n' ++ ' }\n' ++ ' , _MATCH_HTML = /[&<>\'"]/g;\n' ++ 'function encode_char(c) {\n' ++ ' return _ENCODE_HTML_RULES[c] || c;\n' ++ '};\n'; + +/** + * Escape characters reserved in XML. + * + * If `markup` is `undefined` or `null`, the empty string is returned. + * + * @implements {EscapeCallback} + * @param {String} markup Input string + * @return {String} Escaped string + * @static + * @private + */ + +exports.escapeXML = function (markup) { + return markup == undefined + ? '' + : String(markup) + .replace(_MATCH_HTML, encode_char); +}; +exports.escapeXML.toString = function () { + return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr; +}; + +/** + * Naive copy of properties from one object to another. + * Does not recurse into non-scalar properties + * Does not check to see if the property has a value before copying + * + * @param {Object} to Destination object + * @param {Object} from Source object + * @return {Object} Destination object + * @static + * @private + */ +exports.shallowCopy = function (to, from) { + from = from || {}; + for (var p in from) { + to[p] = from[p]; + } + return to; +}; + +/** + * Naive copy of a list of key names, from one object to another. + * Only copies property if it is actually defined + * Does not recurse into non-scalar properties + * + * @param {Object} to Destination object + * @param {Object} from Source object + * @param {Array} list List of properties to copy + * @return {Object} Destination object + * @static + * @private + */ +exports.shallowCopyFromList = function (to, from, list) { + for (var i = 0; i < list.length; i++) { + var p = list[i]; + if (typeof from[p] != 'undefined') { + to[p] = from[p]; + } + } + return to; +}; + +/** + * Simple in-process cache implementation. Does not implement limits of any + * sort. + * + * @implements {Cache} + * @static + * @private + */ +exports.cache = { + _data: {}, + set: function (key, val) { + this._data[key] = val; + }, + get: function (key) { + return this._data[key]; + }, + remove: function (key) { + delete this._data[key]; + }, + reset: function () { + this._data = {}; + } +}; + +},{}],3:[function(require,module,exports){ + +},{}],4:[function(require,module,exports){ +(function (process){ +// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1, +// backported and transplited with Babel, with backwards-compat fixes + +// 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. + +// resolves . and .. elements in a path array with directory names there +// must be no slashes, empty elements, or device names (c:\) in the array +// (so also no leading and trailing slashes - it does not distinguish +// relative and absolute paths) +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; +} + +// path.resolve([from ...], to) +// posix version +exports.resolve = function() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : process.cwd(); + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; +}; + +// path.normalize(path) +// posix version +exports.normalize = function(path) { + var isAbsolute = exports.isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isAbsolute).join('/'); + + if (!path && !isAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isAbsolute ? '/' : '') + path; +}; + +// posix version +exports.isAbsolute = function(path) { + return path.charAt(0) === '/'; +}; + +// posix version +exports.join = function() { + var paths = Array.prototype.slice.call(arguments, 0); + return exports.normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); +}; + + +// path.relative(from, to) +// posix version +exports.relative = function(from, to) { + from = exports.resolve(from).substr(1); + to = exports.resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); +}; + +exports.sep = '/'; +exports.delimiter = ':'; + +exports.dirname = function (path) { + if (typeof path !== 'string') path = path + ''; + if (path.length === 0) return '.'; + var code = path.charCodeAt(0); + var hasRoot = code === 47 /*/*/; + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47 /*/*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) { + // return '//'; + // Backwards-compat fix: + return '/'; + } + return path.slice(0, end); +}; + +function basename(path) { + if (typeof path !== 'string') path = path + ''; + + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ''; + return path.slice(start, end); +} + +// Uses a mixed approach for backwards-compatibility, as ext behavior changed +// in new Node.js versions, so only basename() above is backported here +exports.basename = function (path, ext) { + var f = basename(path); + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; +}; + +exports.extname = function (path) { + if (typeof path !== 'string') path = path + ''; + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); +}; + +function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; +} + +// String.prototype.substr - negative index don't work in IE8 +var substr = 'ab'.substr(-1) === 'b' + ? function (str, start, len) { return str.substr(start, len) } + : function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } +; + +}).call(this,require('_process')) +},{"_process":5}],5:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],6:[function(require,module,exports){ +module.exports={ + "name": "ejs", + "description": "Embedded JavaScript templates", + "keywords": [ + "template", + "engine", + "ejs" + ], + "version": "3.1.3", + "author": "Matthew Eernisse (http://fleegix.org)", + "license": "Apache-2.0", + "bin": { + "ejs": "./bin/cli.js" + }, + "main": "./lib/ejs.js", + "jsdelivr": "ejs.min.js", + "unpkg": "ejs.min.js", + "repository": { + "type": "git", + "url": "git://github.com/mde/ejs.git" + }, + "bugs": "https://github.com/mde/ejs/issues", + "homepage": "https://github.com/mde/ejs", + "dependencies": { + "jake": "^10.6.1" + }, + "devDependencies": { + "browserify": "^16.5.1", + "eslint": "^6.8.0", + "git-directory-deploy": "^1.5.1", + "jsdoc": "^3.6.4", + "lru-cache": "^4.0.1", + "mocha": "^7.1.1", + "uglify-js": "^3.3.16" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha", + "postinstall": "node --harmony ./postinstall.js" + } +} + +},{}]},{},[1])(1) +}); diff --git a/node_modules/ejs/ejs.min.js b/node_modules/ejs/ejs.min.js new file mode 100644 index 0000000..d35b161 --- /dev/null +++ b/node_modules/ejs/ejs.min.js @@ -0,0 +1 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ejs=f()}})(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i1;if(options.cache){if(!filename){throw new Error("cache option requires a filename")}func=exports.cache.get(filename);if(func){return func}if(!hasTemplate){template=fileLoader(filename).toString().replace(_BOM,"")}}else if(!hasTemplate){if(!filename){throw new Error("Internal EJS error: no file name or template "+"provided")}template=fileLoader(filename).toString().replace(_BOM,"")}func=exports.compile(template,options);if(options.cache){exports.cache.set(filename,func)}return func}function tryHandleCache(options,data,cb){var result;if(!cb){if(typeof exports.promiseImpl=="function"){return new exports.promiseImpl(function(resolve,reject){try{result=handleCache(options)(data);resolve(result)}catch(err){reject(err)}})}else{throw new Error("Please provide a callback function")}}else{try{result=handleCache(options)(data)}catch(err){return cb(err)}cb(null,result)}}function fileLoader(filePath){return exports.fileLoader(filePath)}function includeFile(path,options){var opts=utils.shallowCopy({},options);opts.filename=getIncludePath(path,opts);if(typeof options.includer==="function"){var includerResult=options.includer(path,opts.filename);if(includerResult){if(includerResult.filename){opts.filename=includerResult.filename}if(includerResult.template){return handleCache(opts,includerResult.template)}}}return handleCache(opts)}function rethrow(err,str,flnm,lineno,esc){var lines=str.split("\n");var start=Math.max(lineno-3,0);var end=Math.min(lines.length,lineno+3);var filename=esc(flnm);var context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" >> ":" ")+curr+"| "+line}).join("\n");err.path=filename;err.message=(filename||"ejs")+":"+lineno+"\n"+context+"\n\n"+err.message;throw err}function stripSemi(str){return str.replace(/;(\s*$)/,"$1")}exports.compile=function compile(template,opts){var templ;if(opts&&opts.scope){if(!scopeOptionWarned){console.warn("`scope` option is deprecated and will be removed in EJS 3");scopeOptionWarned=true}if(!opts.context){opts.context=opts.scope}delete opts.scope}templ=new Template(template,opts);return templ.compile()};exports.render=function(template,d,o){var data=d||{};var opts=o||{};if(arguments.length==2){utils.shallowCopyFromList(opts,data,_OPTS_PASSABLE_WITH_DATA)}return handleCache(opts,template)(data)};exports.renderFile=function(){var args=Array.prototype.slice.call(arguments);var filename=args.shift();var cb;var opts={filename:filename};var data;var viewOpts;if(typeof arguments[arguments.length-1]=="function"){cb=args.pop()}if(args.length){data=args.shift();if(args.length){utils.shallowCopy(opts,args.pop())}else{if(data.settings){if(data.settings.views){opts.views=data.settings.views}if(data.settings["view cache"]){opts.cache=true}viewOpts=data.settings["view options"];if(viewOpts){utils.shallowCopy(opts,viewOpts)}}utils.shallowCopyFromList(opts,data,_OPTS_PASSABLE_WITH_DATA_EXPRESS)}opts.filename=filename}else{data={}}return tryHandleCache(opts,data,cb)};exports.Template=Template;exports.clearCache=function(){exports.cache.reset()};function Template(text,opts){opts=opts||{};var options={};this.templateText=text;this.mode=null;this.truncate=false;this.currentLine=1;this.source="";options.client=opts.client||false;options.escapeFunction=opts.escape||opts.escapeFunction||utils.escapeXML;options.compileDebug=opts.compileDebug!==false;options.debug=!!opts.debug;options.filename=opts.filename;options.openDelimiter=opts.openDelimiter||exports.openDelimiter||_DEFAULT_OPEN_DELIMITER;options.closeDelimiter=opts.closeDelimiter||exports.closeDelimiter||_DEFAULT_CLOSE_DELIMITER;options.delimiter=opts.delimiter||exports.delimiter||_DEFAULT_DELIMITER;options.strict=opts.strict||false;options.context=opts.context;options.cache=opts.cache||false;options.rmWhitespace=opts.rmWhitespace;options.root=opts.root;options.includer=opts.includer;options.outputFunctionName=opts.outputFunctionName;options.localsName=opts.localsName||exports.localsName||_DEFAULT_LOCALS_NAME;options.views=opts.views;options.async=opts.async;options.destructuredLocals=opts.destructuredLocals;options.legacyInclude=typeof opts.legacyInclude!="undefined"?!!opts.legacyInclude:true;if(options.strict){options._with=false}else{options._with=typeof opts._with!="undefined"?opts._with:true}this.opts=options;this.regex=this.createRegex()}Template.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};Template.prototype={createRegex:function(){var str=_REGEX_STRING;var delim=utils.escapeRegExpChars(this.opts.delimiter);var open=utils.escapeRegExpChars(this.opts.openDelimiter);var close=utils.escapeRegExpChars(this.opts.closeDelimiter);str=str.replace(/%/g,delim).replace(//g,close);return new RegExp(str)},compile:function(){var src;var fn;var opts=this.opts;var prepended="";var appended="";var escapeFn=opts.escapeFunction;var ctor;if(!this.source){this.generateSource();prepended+=' var __output = "";\n'+" function __append(s) { if (s !== undefined && s !== null) __output += s }\n";if(opts.outputFunctionName){prepended+=" var "+opts.outputFunctionName+" = __append;"+"\n"}if(opts.destructuredLocals&&opts.destructuredLocals.length){var destructuring=" var __locals = ("+opts.localsName+" || {}),\n";for(var i=0;i0){destructuring+=",\n "}destructuring+=name+" = __locals."+name}prepended+=destructuring+";\n"}if(opts._with!==false){prepended+=" with ("+opts.localsName+" || {}) {"+"\n";appended+=" }"+"\n"}appended+=" return __output;"+"\n";this.source=prepended+this.source+appended}if(opts.compileDebug){src="var __line = 1"+"\n"+" , __lines = "+JSON.stringify(this.templateText)+"\n"+" , __filename = "+(opts.filename?JSON.stringify(opts.filename):"undefined")+";"+"\n"+"try {"+"\n"+this.source+"} catch (e) {"+"\n"+" rethrow(e, __lines, __filename, __line, escapeFn);"+"\n"+"}"+"\n"}else{src=this.source}if(opts.client){src="escapeFn = escapeFn || "+escapeFn.toString()+";"+"\n"+src;if(opts.compileDebug){src="rethrow = rethrow || "+rethrow.toString()+";"+"\n"+src}}if(opts.strict){src='"use strict";\n'+src}if(opts.debug){console.log(src)}if(opts.compileDebug&&opts.filename){src=src+"\n"+"//# sourceURL="+opts.filename+"\n"}try{if(opts.async){try{ctor=new Function("return (async function(){}).constructor;")()}catch(e){if(e instanceof SyntaxError){throw new Error("This environment does not support async/await")}else{throw e}}}else{ctor=Function}fn=new ctor(opts.localsName+", escapeFn, include, rethrow",src)}catch(e){if(e instanceof SyntaxError){if(opts.filename){e.message+=" in "+opts.filename}e.message+=" while compiling ejs\n\n";e.message+="If the above error is not helpful, you may want to try EJS-Lint:\n";e.message+="https://github.com/RyanZim/EJS-Lint";if(!opts.async){e.message+="\n";e.message+="Or, if you meant to create an async function, pass `async: true` as an option."}}throw e}var returnedFn=opts.client?fn:function anonymous(data){var include=function(path,includeData){var d=utils.shallowCopy({},data);if(includeData){d=utils.shallowCopy(d,includeData)}return includeFile(path,opts)(d)};return fn.apply(opts.context,[data||{},escapeFn,include,rethrow])};if(opts.filename&&typeof Object.defineProperty==="function"){var filename=opts.filename;var basename=path.basename(filename,path.extname(filename));try{Object.defineProperty(returnedFn,"name",{value:basename,writable:false,enumerable:false,configurable:true})}catch(e){}}return returnedFn},generateSource:function(){var opts=this.opts;if(opts.rmWhitespace){this.templateText=this.templateText.replace(/[\r\n]+/g,"\n").replace(/^\s+|\s+$/gm,"")}this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var self=this;var matches=this.parseTemplateText();var d=this.opts.delimiter;var o=this.opts.openDelimiter;var c=this.opts.closeDelimiter;if(matches&&matches.length){matches.forEach(function(line,index){var closing;if(line.indexOf(o+d)===0&&line.indexOf(o+d+d)!==0){closing=matches[index+2];if(!(closing==d+c||closing=="-"+d+c||closing=="_"+d+c)){throw new Error('Could not find matching close tag for "'+line+'".')}}self.scanLine(line)})}},parseTemplateText:function(){var str=this.templateText;var pat=this.regex;var result=pat.exec(str);var arr=[];var firstPos;while(result){firstPos=result.index;if(firstPos!==0){arr.push(str.substring(0,firstPos));str=str.slice(firstPos)}arr.push(result[0]);str=str.slice(result[0].length);result=pat.exec(str)}if(str){arr.push(str)}return arr},_addOutput:function(line){if(this.truncate){line=line.replace(/^(?:\r\n|\r|\n)/,"");this.truncate=false}if(!line){return line}line=line.replace(/\\/g,"\\\\");line=line.replace(/\n/g,"\\n");line=line.replace(/\r/g,"\\r");line=line.replace(/"/g,'\\"');this.source+=' ; __append("'+line+'")'+"\n"},scanLine:function(line){var self=this;var d=this.opts.delimiter;var o=this.opts.openDelimiter;var c=this.opts.closeDelimiter;var newLineCount=0;newLineCount=line.split("\n").length-1;switch(line){case o+d:case o+d+"_":this.mode=Template.modes.EVAL;break;case o+d+"=":this.mode=Template.modes.ESCAPED;break;case o+d+"-":this.mode=Template.modes.RAW;break;case o+d+"#":this.mode=Template.modes.COMMENT;break;case o+d+d:this.mode=Template.modes.LITERAL;this.source+=' ; __append("'+line.replace(o+d+d,o+d)+'")'+"\n";break;case d+d+c:this.mode=Template.modes.LITERAL;this.source+=' ; __append("'+line.replace(d+d+c,d+c)+'")'+"\n";break;case d+c:case"-"+d+c:case"_"+d+c:if(this.mode==Template.modes.LITERAL){this._addOutput(line)}this.mode=null;this.truncate=line.indexOf("-")===0||line.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case Template.modes.EVAL:case Template.modes.ESCAPED:case Template.modes.RAW:if(line.lastIndexOf("//")>line.lastIndexOf("\n")){line+="\n"}}switch(this.mode){case Template.modes.EVAL:this.source+=" ; "+line+"\n";break;case Template.modes.ESCAPED:this.source+=" ; __append(escapeFn("+stripSemi(line)+"))"+"\n";break;case Template.modes.RAW:this.source+=" ; __append("+stripSemi(line)+")"+"\n";break;case Template.modes.COMMENT:break;case Template.modes.LITERAL:this._addOutput(line);break}}else{this._addOutput(line)}}if(self.opts.compileDebug&&newLineCount){this.currentLine+=newLineCount;this.source+=" ; __line = "+this.currentLine+"\n"}}};exports.escapeXML=utils.escapeXML;exports.__express=exports.renderFile;exports.VERSION=_VERSION_STRING;exports.name=_NAME;if(typeof window!="undefined"){window.ejs=exports}},{"../package.json":6,"./utils":2,fs:3,path:4}],2:[function(require,module,exports){"use strict";var regExpChars=/[|\\{}()[\]^$+*?.]/g;exports.escapeRegExpChars=function(string){if(!string){return""}return String(string).replace(regExpChars,"\\$&")};var _ENCODE_HTML_RULES={"&":"&","<":"<",">":">",'"':""","'":"'"};var _MATCH_HTML=/[&<>'"]/g;function encode_char(c){return _ENCODE_HTML_RULES[c]||c}var escapeFuncStr="var _ENCODE_HTML_RULES = {\n"+' "&": "&"\n'+' , "<": "<"\n'+' , ">": ">"\n'+' , \'"\': """\n'+' , "\'": "'"\n'+" }\n"+" , _MATCH_HTML = /[&<>'\"]/g;\n"+"function encode_char(c) {\n"+" return _ENCODE_HTML_RULES[c] || c;\n"+"};\n";exports.escapeXML=function(markup){return markup==undefined?"":String(markup).replace(_MATCH_HTML,encode_char)};exports.escapeXML.toString=function(){return Function.prototype.toString.call(this)+";\n"+escapeFuncStr};exports.shallowCopy=function(to,from){from=from||{};for(var p in from){to[p]=from[p]}return to};exports.shallowCopyFromList=function(to,from,list){for(var i=0;i=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i=1;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){end=i;break}}else{matchedSlash=false}}if(end===-1)return hasRoot?"/":".";if(hasRoot&&end===1){return"/"}return path.slice(0,end)};function basename(path){if(typeof path!=="string")path=path+"";var start=0;var end=-1;var matchedSlash=true;var i;for(i=path.length-1;i>=0;--i){if(path.charCodeAt(i)===47){if(!matchedSlash){start=i+1;break}}else if(end===-1){matchedSlash=false;end=i+1}}if(end===-1)return"";return path.slice(start,end)}exports.basename=function(path,ext){var f=basename(path);if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){if(typeof path!=="string")path=path+"";var startDot=-1;var startPart=0;var end=-1;var matchedSlash=true;var preDotState=0;for(var i=path.length-1;i>=0;--i){var code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){return""}return path.slice(startDot,end)};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i1){for(var i=1;i (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.6.1"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^3.6.4","lru-cache":"^4.0.1",mocha:"^7.1.1","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"mocha",postinstall:"node --harmony ./postinstall.js"}}},{}]},{},[1])(1)}); diff --git a/node_modules/ejs/jakefile.js b/node_modules/ejs/jakefile.js new file mode 100644 index 0000000..0eebf2e --- /dev/null +++ b/node_modules/ejs/jakefile.js @@ -0,0 +1,76 @@ +var fs = require('fs'); +var execSync = require('child_process').execSync; +var exec = function (cmd) { + execSync(cmd, {stdio: 'inherit'}); +}; + +/* global jake, task, desc, publishTask */ + +task('build', ['lint', 'clean', 'browserify', 'minify'], function () { + console.log('Build completed.'); +}); + +desc('Cleans browerified/minified files and package files'); +task('clean', ['clobber'], function () { + jake.rmRf('./ejs.js'); + jake.rmRf('./ejs.min.js'); + console.log('Cleaned up compiled files.'); +}); + +desc('Lints the source code'); +task('lint', ['clean'], function () { + exec('./node_modules/.bin/eslint "**/*.js"'); + console.log('Linting completed.'); +}); + +task('browserify', function () { + exec('./node_modules/browserify/bin/cmd.js --standalone ejs lib/ejs.js > ejs.js'); + console.log('Browserification completed.'); +}); + +task('minify', function () { + exec('./node_modules/uglify-js/bin/uglifyjs ejs.js > ejs.min.js'); + console.log('Minification completed.'); +}); + +desc('Generates the EJS API docs'); +task('doc', function (dev) { + jake.rmRf('out'); + var p = dev ? '-p' : ''; + exec('./node_modules/.bin/jsdoc ' + p + ' -c jsdoc.json lib/* docs/jsdoc/*'); + console.log('Documentation generated.'); +}); + +desc('Publishes the EJS API docs'); +task('docPublish', ['doc'], function () { + fs.writeFileSync('out/CNAME', 'api.ejs.co'); + console.log('Pushing docs to gh-pages...'); + exec('./node_modules/.bin/git-directory-deploy --directory out/'); + console.log('Docs published to gh-pages.'); +}); + +desc('Runs the EJS test suite'); +task('test', ['lint'], function () { + exec('./node_modules/.bin/mocha'); +}); + +publishTask('ejs', ['build'], function () { + this.packageFiles.include([ + 'jakefile.js', + 'README.md', + 'LICENSE', + 'package.json', + 'postinstall.js', + 'ejs.js', + 'ejs.min.js', + 'lib/**', + 'bin/**', + 'usage.txt' + ]); +}); + +jake.Task.publish.on('complete', function () { + console.log('Updating hosted docs...'); + console.log('If this fails, run jake docPublish to re-try.'); + jake.Task.docPublish.invoke(); +}); diff --git a/node_modules/ejs/lib/ejs.js b/node_modules/ejs/lib/ejs.js new file mode 100644 index 0000000..104aada --- /dev/null +++ b/node_modules/ejs/lib/ejs.js @@ -0,0 +1,938 @@ +/* + * EJS Embedded JavaScript templates + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +'use strict'; + +/** + * @file Embedded JavaScript templating engine. {@link http://ejs.co} + * @author Matthew Eernisse + * @author Tiancheng "Timothy" Gu + * @project EJS + * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0} + */ + +/** + * EJS internal functions. + * + * Technically this "module" lies in the same file as {@link module:ejs}, for + * the sake of organization all the private functions re grouped into this + * module. + * + * @module ejs-internal + * @private + */ + +/** + * Embedded JavaScript templating engine. + * + * @module ejs + * @public + */ + +var fs = require('fs'); +var path = require('path'); +var utils = require('./utils'); + +var scopeOptionWarned = false; +/** @type {string} */ +var _VERSION_STRING = require('../package.json').version; +var _DEFAULT_OPEN_DELIMITER = '<'; +var _DEFAULT_CLOSE_DELIMITER = '>'; +var _DEFAULT_DELIMITER = '%'; +var _DEFAULT_LOCALS_NAME = 'locals'; +var _NAME = 'ejs'; +var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)'; +var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug', + 'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async']; +// We don't allow 'cache' option to be passed in the data obj for +// the normal `render` call, but this is where Express 2 & 3 put it +// so we make an exception for `renderFile` +var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache'); +var _BOM = /^\uFEFF/; + +/** + * EJS template function cache. This can be a LRU object from lru-cache NPM + * module. By default, it is {@link module:utils.cache}, a simple in-process + * cache that grows continuously. + * + * @type {Cache} + */ + +exports.cache = utils.cache; + +/** + * Custom file loader. Useful for template preprocessing or restricting access + * to a certain part of the filesystem. + * + * @type {fileLoader} + */ + +exports.fileLoader = fs.readFileSync; + +/** + * Name of the object containing the locals. + * + * This variable is overridden by {@link Options}`.localsName` if it is not + * `undefined`. + * + * @type {String} + * @public + */ + +exports.localsName = _DEFAULT_LOCALS_NAME; + +/** + * Promise implementation -- defaults to the native implementation if available + * This is mostly just for testability + * + * @type {PromiseConstructorLike} + * @public + */ + +exports.promiseImpl = (new Function('return this;'))().Promise; + +/** + * Get the path to the included file from the parent file path and the + * specified path. + * + * @param {String} name specified path + * @param {String} filename parent file path + * @param {Boolean} [isDir=false] whether the parent file path is a directory + * @return {String} + */ +exports.resolveInclude = function(name, filename, isDir) { + var dirname = path.dirname; + var extname = path.extname; + var resolve = path.resolve; + var includePath = resolve(isDir ? filename : dirname(filename), name); + var ext = extname(name); + if (!ext) { + includePath += '.ejs'; + } + return includePath; +}; + +/** + * Try to resolve file path on multiple directories + * + * @param {String} name specified path + * @param {Array} paths list of possible parent directory paths + * @return {String} + */ +function resolvePaths(name, paths) { + var filePath; + if (paths.some(function (v) { + filePath = exports.resolveInclude(name, v, true); + return fs.existsSync(filePath); + })) { + return filePath; + } +} + +/** + * Get the path to the included file by Options + * + * @param {String} path specified path + * @param {Options} options compilation options + * @return {String} + */ +function getIncludePath(path, options) { + var includePath; + var filePath; + var views = options.views; + var match = /^[A-Za-z]+:\\|^\//.exec(path); + + // Abs path + if (match && match.length) { + path = path.replace(/^\/*/, ''); + if (Array.isArray(options.root)) { + includePath = resolvePaths(path, options.root); + } else { + includePath = exports.resolveInclude(path, options.root || '/', true); + } + } + // Relative paths + else { + // Look relative to a passed filename first + if (options.filename) { + filePath = exports.resolveInclude(path, options.filename); + if (fs.existsSync(filePath)) { + includePath = filePath; + } + } + // Then look in any views directories + if (!includePath && Array.isArray(views)) { + includePath = resolvePaths(path, views); + } + if (!includePath && typeof options.includer !== 'function') { + throw new Error('Could not find the include file "' + + options.escapeFunction(path) + '"'); + } + } + return includePath; +} + +/** + * Get the template from a string or a file, either compiled on-the-fly or + * read from cache (if enabled), and cache the template if needed. + * + * If `template` is not set, the file specified in `options.filename` will be + * read. + * + * If `options.cache` is true, this function reads the file from + * `options.filename` so it must be set prior to calling this function. + * + * @memberof module:ejs-internal + * @param {Options} options compilation options + * @param {String} [template] template source + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `options.client`, either type might be returned. + * @static + */ + +function handleCache(options, template) { + var func; + var filename = options.filename; + var hasTemplate = arguments.length > 1; + + if (options.cache) { + if (!filename) { + throw new Error('cache option requires a filename'); + } + func = exports.cache.get(filename); + if (func) { + return func; + } + if (!hasTemplate) { + template = fileLoader(filename).toString().replace(_BOM, ''); + } + } + else if (!hasTemplate) { + // istanbul ignore if: should not happen at all + if (!filename) { + throw new Error('Internal EJS error: no file name or template ' + + 'provided'); + } + template = fileLoader(filename).toString().replace(_BOM, ''); + } + func = exports.compile(template, options); + if (options.cache) { + exports.cache.set(filename, func); + } + return func; +} + +/** + * Try calling handleCache with the given options and data and call the + * callback with the result. If an error occurs, call the callback with + * the error. Used by renderFile(). + * + * @memberof module:ejs-internal + * @param {Options} options compilation options + * @param {Object} data template data + * @param {RenderFileCallback} cb callback + * @static + */ + +function tryHandleCache(options, data, cb) { + var result; + if (!cb) { + if (typeof exports.promiseImpl == 'function') { + return new exports.promiseImpl(function (resolve, reject) { + try { + result = handleCache(options)(data); + resolve(result); + } + catch (err) { + reject(err); + } + }); + } + else { + throw new Error('Please provide a callback function'); + } + } + else { + try { + result = handleCache(options)(data); + } + catch (err) { + return cb(err); + } + + cb(null, result); + } +} + +/** + * fileLoader is independent + * + * @param {String} filePath ejs file path. + * @return {String} The contents of the specified file. + * @static + */ + +function fileLoader(filePath){ + return exports.fileLoader(filePath); +} + +/** + * Get the template function. + * + * If `options.cache` is `true`, then the template is cached. + * + * @memberof module:ejs-internal + * @param {String} path path for the specified file + * @param {Options} options compilation options + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `options.client`, either type might be returned + * @static + */ + +function includeFile(path, options) { + var opts = utils.shallowCopy({}, options); + opts.filename = getIncludePath(path, opts); + if (typeof options.includer === 'function') { + var includerResult = options.includer(path, opts.filename); + if (includerResult) { + if (includerResult.filename) { + opts.filename = includerResult.filename; + } + if (includerResult.template) { + return handleCache(opts, includerResult.template); + } + } + } + return handleCache(opts); +} + +/** + * Re-throw the given `err` in context to the `str` of ejs, `filename`, and + * `lineno`. + * + * @implements {RethrowCallback} + * @memberof module:ejs-internal + * @param {Error} err Error object + * @param {String} str EJS source + * @param {String} flnm file name of the EJS file + * @param {Number} lineno line number of the error + * @param {EscapeCallback} esc + * @static + */ + +function rethrow(err, str, flnm, lineno, esc) { + var lines = str.split('\n'); + var start = Math.max(lineno - 3, 0); + var end = Math.min(lines.length, lineno + 3); + var filename = esc(flnm); + // Error context + var context = lines.slice(start, end).map(function (line, i){ + var curr = i + start + 1; + return (curr == lineno ? ' >> ' : ' ') + + curr + + '| ' + + line; + }).join('\n'); + + // Alter exception message + err.path = filename; + err.message = (filename || 'ejs') + ':' + + lineno + '\n' + + context + '\n\n' + + err.message; + + throw err; +} + +function stripSemi(str){ + return str.replace(/;(\s*$)/, '$1'); +} + +/** + * Compile the given `str` of ejs into a template function. + * + * @param {String} template EJS template + * + * @param {Options} [opts] compilation options + * + * @return {(TemplateFunction|ClientFunction)} + * Depending on the value of `opts.client`, either type might be returned. + * Note that the return type of the function also depends on the value of `opts.async`. + * @public + */ + +exports.compile = function compile(template, opts) { + var templ; + + // v1 compat + // 'scope' is 'context' + // FIXME: Remove this in a future version + if (opts && opts.scope) { + if (!scopeOptionWarned){ + console.warn('`scope` option is deprecated and will be removed in EJS 3'); + scopeOptionWarned = true; + } + if (!opts.context) { + opts.context = opts.scope; + } + delete opts.scope; + } + templ = new Template(template, opts); + return templ.compile(); +}; + +/** + * Render the given `template` of ejs. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + * + * @param {String} template EJS template + * @param {Object} [data={}] template data + * @param {Options} [opts={}] compilation and rendering options + * @return {(String|Promise)} + * Return value type depends on `opts.async`. + * @public + */ + +exports.render = function (template, d, o) { + var data = d || {}; + var opts = o || {}; + + // No options object -- if there are optiony names + // in the data, copy them to options + if (arguments.length == 2) { + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA); + } + + return handleCache(opts, template)(data); +}; + +/** + * Render an EJS file at the given `path` and callback `cb(err, str)`. + * + * If you would like to include options but not data, you need to explicitly + * call this function with `data` being an empty object or `null`. + * + * @param {String} path path to the EJS file + * @param {Object} [data={}] template data + * @param {Options} [opts={}] compilation and rendering options + * @param {RenderFileCallback} cb callback + * @public + */ + +exports.renderFile = function () { + var args = Array.prototype.slice.call(arguments); + var filename = args.shift(); + var cb; + var opts = {filename: filename}; + var data; + var viewOpts; + + // Do we have a callback? + if (typeof arguments[arguments.length - 1] == 'function') { + cb = args.pop(); + } + // Do we have data/opts? + if (args.length) { + // Should always have data obj + data = args.shift(); + // Normal passed opts (data obj + opts obj) + if (args.length) { + // Use shallowCopy so we don't pollute passed in opts obj with new vals + utils.shallowCopy(opts, args.pop()); + } + // Special casing for Express (settings + opts-in-data) + else { + // Express 3 and 4 + if (data.settings) { + // Pull a few things from known locations + if (data.settings.views) { + opts.views = data.settings.views; + } + if (data.settings['view cache']) { + opts.cache = true; + } + // Undocumented after Express 2, but still usable, esp. for + // items that are unsafe to be passed along with data, like `root` + viewOpts = data.settings['view options']; + if (viewOpts) { + utils.shallowCopy(opts, viewOpts); + } + } + // Express 2 and lower, values set in app.locals, or people who just + // want to pass options in their data. NOTE: These values will override + // anything previously set in settings or settings['view options'] + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS); + } + opts.filename = filename; + } + else { + data = {}; + } + + return tryHandleCache(opts, data, cb); +}; + +/** + * Clear intermediate JavaScript cache. Calls {@link Cache#reset}. + * @public + */ + +/** + * EJS template class + * @public + */ +exports.Template = Template; + +exports.clearCache = function () { + exports.cache.reset(); +}; + +function Template(text, opts) { + opts = opts || {}; + var options = {}; + this.templateText = text; + /** @type {string | null} */ + this.mode = null; + this.truncate = false; + this.currentLine = 1; + this.source = ''; + options.client = opts.client || false; + options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML; + options.compileDebug = opts.compileDebug !== false; + options.debug = !!opts.debug; + options.filename = opts.filename; + options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER; + options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER; + options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER; + options.strict = opts.strict || false; + options.context = opts.context; + options.cache = opts.cache || false; + options.rmWhitespace = opts.rmWhitespace; + options.root = opts.root; + options.includer = opts.includer; + options.outputFunctionName = opts.outputFunctionName; + options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME; + options.views = opts.views; + options.async = opts.async; + options.destructuredLocals = opts.destructuredLocals; + options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true; + + if (options.strict) { + options._with = false; + } + else { + options._with = typeof opts._with != 'undefined' ? opts._with : true; + } + + this.opts = options; + + this.regex = this.createRegex(); +} + +Template.modes = { + EVAL: 'eval', + ESCAPED: 'escaped', + RAW: 'raw', + COMMENT: 'comment', + LITERAL: 'literal' +}; + +Template.prototype = { + createRegex: function () { + var str = _REGEX_STRING; + var delim = utils.escapeRegExpChars(this.opts.delimiter); + var open = utils.escapeRegExpChars(this.opts.openDelimiter); + var close = utils.escapeRegExpChars(this.opts.closeDelimiter); + str = str.replace(/%/g, delim) + .replace(//g, close); + return new RegExp(str); + }, + + compile: function () { + /** @type {string} */ + var src; + /** @type {ClientFunction} */ + var fn; + var opts = this.opts; + var prepended = ''; + var appended = ''; + /** @type {EscapeCallback} */ + var escapeFn = opts.escapeFunction; + /** @type {FunctionConstructor} */ + var ctor; + + if (!this.source) { + this.generateSource(); + prepended += + ' var __output = "";\n' + + ' function __append(s) { if (s !== undefined && s !== null) __output += s }\n'; + if (opts.outputFunctionName) { + prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n'; + } + if (opts.destructuredLocals && opts.destructuredLocals.length) { + var destructuring = ' var __locals = (' + opts.localsName + ' || {}),\n'; + for (var i = 0; i < opts.destructuredLocals.length; i++) { + var name = opts.destructuredLocals[i]; + if (i > 0) { + destructuring += ',\n '; + } + destructuring += name + ' = __locals.' + name; + } + prepended += destructuring + ';\n'; + } + if (opts._with !== false) { + prepended += ' with (' + opts.localsName + ' || {}) {' + '\n'; + appended += ' }' + '\n'; + } + appended += ' return __output;' + '\n'; + this.source = prepended + this.source + appended; + } + + if (opts.compileDebug) { + src = 'var __line = 1' + '\n' + + ' , __lines = ' + JSON.stringify(this.templateText) + '\n' + + ' , __filename = ' + (opts.filename ? + JSON.stringify(opts.filename) : 'undefined') + ';' + '\n' + + 'try {' + '\n' + + this.source + + '} catch (e) {' + '\n' + + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n' + + '}' + '\n'; + } + else { + src = this.source; + } + + if (opts.client) { + src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src; + if (opts.compileDebug) { + src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src; + } + } + + if (opts.strict) { + src = '"use strict";\n' + src; + } + if (opts.debug) { + console.log(src); + } + if (opts.compileDebug && opts.filename) { + src = src + '\n' + + '//# sourceURL=' + opts.filename + '\n'; + } + + try { + if (opts.async) { + // Have to use generated function for this, since in envs without support, + // it breaks in parsing + try { + ctor = (new Function('return (async function(){}).constructor;'))(); + } + catch(e) { + if (e instanceof SyntaxError) { + throw new Error('This environment does not support async/await'); + } + else { + throw e; + } + } + } + else { + ctor = Function; + } + fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src); + } + catch(e) { + // istanbul ignore else + if (e instanceof SyntaxError) { + if (opts.filename) { + e.message += ' in ' + opts.filename; + } + e.message += ' while compiling ejs\n\n'; + e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n'; + e.message += 'https://github.com/RyanZim/EJS-Lint'; + if (!opts.async) { + e.message += '\n'; + e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.'; + } + } + throw e; + } + + // Return a callable function which will execute the function + // created by the source-code, with the passed data as locals + // Adds a local `include` function which allows full recursive include + var returnedFn = opts.client ? fn : function anonymous(data) { + var include = function (path, includeData) { + var d = utils.shallowCopy({}, data); + if (includeData) { + d = utils.shallowCopy(d, includeData); + } + return includeFile(path, opts)(d); + }; + return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]); + }; + if (opts.filename && typeof Object.defineProperty === 'function') { + var filename = opts.filename; + var basename = path.basename(filename, path.extname(filename)); + try { + Object.defineProperty(returnedFn, 'name', { + value: basename, + writable: false, + enumerable: false, + configurable: true + }); + } catch (e) {/* ignore */} + } + return returnedFn; + }, + + generateSource: function () { + var opts = this.opts; + + if (opts.rmWhitespace) { + // Have to use two separate replace here as `^` and `$` operators don't + // work well with `\r` and empty lines don't work well with the `m` flag. + this.templateText = + this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, ''); + } + + // Slurp spaces and tabs before <%_ and after _%> + this.templateText = + this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>'); + + var self = this; + var matches = this.parseTemplateText(); + var d = this.opts.delimiter; + var o = this.opts.openDelimiter; + var c = this.opts.closeDelimiter; + + if (matches && matches.length) { + matches.forEach(function (line, index) { + var closing; + // If this is an opening tag, check for closing tags + // FIXME: May end up with some false positives here + // Better to store modes as k/v with openDelimiter + delimiter as key + // Then this can simply check against the map + if ( line.indexOf(o + d) === 0 // If it is a tag + && line.indexOf(o + d + d) !== 0) { // and is not escaped + closing = matches[index + 2]; + if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) { + throw new Error('Could not find matching close tag for "' + line + '".'); + } + } + self.scanLine(line); + }); + } + + }, + + parseTemplateText: function () { + var str = this.templateText; + var pat = this.regex; + var result = pat.exec(str); + var arr = []; + var firstPos; + + while (result) { + firstPos = result.index; + + if (firstPos !== 0) { + arr.push(str.substring(0, firstPos)); + str = str.slice(firstPos); + } + + arr.push(result[0]); + str = str.slice(result[0].length); + result = pat.exec(str); + } + + if (str) { + arr.push(str); + } + + return arr; + }, + + _addOutput: function (line) { + if (this.truncate) { + // Only replace single leading linebreak in the line after + // -%> tag -- this is the single, trailing linebreak + // after the tag that the truncation mode replaces + // Handle Win / Unix / old Mac linebreaks -- do the \r\n + // combo first in the regex-or + line = line.replace(/^(?:\r\n|\r|\n)/, ''); + this.truncate = false; + } + if (!line) { + return line; + } + + // Preserve literal slashes + line = line.replace(/\\/g, '\\\\'); + + // Convert linebreaks + line = line.replace(/\n/g, '\\n'); + line = line.replace(/\r/g, '\\r'); + + // Escape double-quotes + // - this will be the delimiter during execution + line = line.replace(/"/g, '\\"'); + this.source += ' ; __append("' + line + '")' + '\n'; + }, + + scanLine: function (line) { + var self = this; + var d = this.opts.delimiter; + var o = this.opts.openDelimiter; + var c = this.opts.closeDelimiter; + var newLineCount = 0; + + newLineCount = (line.split('\n').length - 1); + + switch (line) { + case o + d: + case o + d + '_': + this.mode = Template.modes.EVAL; + break; + case o + d + '=': + this.mode = Template.modes.ESCAPED; + break; + case o + d + '-': + this.mode = Template.modes.RAW; + break; + case o + d + '#': + this.mode = Template.modes.COMMENT; + break; + case o + d + d: + this.mode = Template.modes.LITERAL; + this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n'; + break; + case d + d + c: + this.mode = Template.modes.LITERAL; + this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n'; + break; + case d + c: + case '-' + d + c: + case '_' + d + c: + if (this.mode == Template.modes.LITERAL) { + this._addOutput(line); + } + + this.mode = null; + this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0; + break; + default: + // In script mode, depends on type of tag + if (this.mode) { + // If '//' is found without a line break, add a line break. + switch (this.mode) { + case Template.modes.EVAL: + case Template.modes.ESCAPED: + case Template.modes.RAW: + if (line.lastIndexOf('//') > line.lastIndexOf('\n')) { + line += '\n'; + } + } + switch (this.mode) { + // Just executing code + case Template.modes.EVAL: + this.source += ' ; ' + line + '\n'; + break; + // Exec, esc, and output + case Template.modes.ESCAPED: + this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n'; + break; + // Exec and output + case Template.modes.RAW: + this.source += ' ; __append(' + stripSemi(line) + ')' + '\n'; + break; + case Template.modes.COMMENT: + // Do nothing + break; + // Literal <%% mode, append as raw output + case Template.modes.LITERAL: + this._addOutput(line); + break; + } + } + // In string mode, just add the output + else { + this._addOutput(line); + } + } + + if (self.opts.compileDebug && newLineCount) { + this.currentLine += newLineCount; + this.source += ' ; __line = ' + this.currentLine + '\n'; + } + } +}; + +/** + * Escape characters reserved in XML. + * + * This is simply an export of {@link module:utils.escapeXML}. + * + * If `markup` is `undefined` or `null`, the empty string is returned. + * + * @param {String} markup Input string + * @return {String} Escaped string + * @public + * @func + * */ +exports.escapeXML = utils.escapeXML; + +/** + * Express.js support. + * + * This is an alias for {@link module:ejs.renderFile}, in order to support + * Express.js out-of-the-box. + * + * @func + */ + +exports.__express = exports.renderFile; + +/** + * Version of EJS. + * + * @readonly + * @type {String} + * @public + */ + +exports.VERSION = _VERSION_STRING; + +/** + * Name for detection of EJS. + * + * @readonly + * @type {String} + * @public + */ + +exports.name = _NAME; + +/* istanbul ignore if */ +if (typeof window != 'undefined') { + window.ejs = exports; +} diff --git a/node_modules/ejs/lib/utils.js b/node_modules/ejs/lib/utils.js new file mode 100644 index 0000000..5715c17 --- /dev/null +++ b/node_modules/ejs/lib/utils.js @@ -0,0 +1,167 @@ +/* + * EJS Embedded JavaScript templates + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +/** + * Private utility functions + * @module utils + * @private + */ + +'use strict'; + +var regExpChars = /[|\\{}()[\]^$+*?.]/g; + +/** + * Escape characters reserved in regular expressions. + * + * If `string` is `undefined` or `null`, the empty string is returned. + * + * @param {String} string Input string + * @return {String} Escaped string + * @static + * @private + */ +exports.escapeRegExpChars = function (string) { + // istanbul ignore if + if (!string) { + return ''; + } + return String(string).replace(regExpChars, '\\$&'); +}; + +var _ENCODE_HTML_RULES = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; +var _MATCH_HTML = /[&<>'"]/g; + +function encode_char(c) { + return _ENCODE_HTML_RULES[c] || c; +} + +/** + * Stringified version of constants used by {@link module:utils.escapeXML}. + * + * It is used in the process of generating {@link ClientFunction}s. + * + * @readonly + * @type {String} + */ + +var escapeFuncStr = + 'var _ENCODE_HTML_RULES = {\n' ++ ' "&": "&"\n' ++ ' , "<": "<"\n' ++ ' , ">": ">"\n' ++ ' , \'"\': """\n' ++ ' , "\'": "'"\n' ++ ' }\n' ++ ' , _MATCH_HTML = /[&<>\'"]/g;\n' ++ 'function encode_char(c) {\n' ++ ' return _ENCODE_HTML_RULES[c] || c;\n' ++ '};\n'; + +/** + * Escape characters reserved in XML. + * + * If `markup` is `undefined` or `null`, the empty string is returned. + * + * @implements {EscapeCallback} + * @param {String} markup Input string + * @return {String} Escaped string + * @static + * @private + */ + +exports.escapeXML = function (markup) { + return markup == undefined + ? '' + : String(markup) + .replace(_MATCH_HTML, encode_char); +}; +exports.escapeXML.toString = function () { + return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr; +}; + +/** + * Naive copy of properties from one object to another. + * Does not recurse into non-scalar properties + * Does not check to see if the property has a value before copying + * + * @param {Object} to Destination object + * @param {Object} from Source object + * @return {Object} Destination object + * @static + * @private + */ +exports.shallowCopy = function (to, from) { + from = from || {}; + for (var p in from) { + to[p] = from[p]; + } + return to; +}; + +/** + * Naive copy of a list of key names, from one object to another. + * Only copies property if it is actually defined + * Does not recurse into non-scalar properties + * + * @param {Object} to Destination object + * @param {Object} from Source object + * @param {Array} list List of properties to copy + * @return {Object} Destination object + * @static + * @private + */ +exports.shallowCopyFromList = function (to, from, list) { + for (var i = 0; i < list.length; i++) { + var p = list[i]; + if (typeof from[p] != 'undefined') { + to[p] = from[p]; + } + } + return to; +}; + +/** + * Simple in-process cache implementation. Does not implement limits of any + * sort. + * + * @implements {Cache} + * @static + * @private + */ +exports.cache = { + _data: {}, + set: function (key, val) { + this._data[key] = val; + }, + get: function (key) { + return this._data[key]; + }, + remove: function (key) { + delete this._data[key]; + }, + reset: function () { + this._data = {}; + } +}; diff --git a/node_modules/ejs/package.json b/node_modules/ejs/package.json new file mode 100644 index 0000000..c2325d8 --- /dev/null +++ b/node_modules/ejs/package.json @@ -0,0 +1,75 @@ +{ + "_from": "ejs", + "_id": "ejs@3.1.3", + "_inBundle": false, + "_integrity": "sha512-wmtrUGyfSC23GC/B1SMv2ogAUgbQEtDmTIhfqielrG5ExIM9TP4UoYdi90jLF1aTcsWCJNEO0UrgKzP0y3nTSg==", + "_location": "/ejs", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "ejs", + "name": "ejs", + "escapedName": "ejs", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.3.tgz", + "_shasum": "514d967a8894084d18d3d47bd169a1c0560f093d", + "_spec": "ejs", + "_where": "C:\\angel", + "author": { + "name": "Matthew Eernisse", + "email": "mde@fleegix.org", + "url": "http://fleegix.org" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "bugs": { + "url": "https://github.com/mde/ejs/issues" + }, + "bundleDependencies": false, + "dependencies": { + "jake": "^10.6.1" + }, + "deprecated": false, + "description": "Embedded JavaScript templates", + "devDependencies": { + "browserify": "^16.5.1", + "eslint": "^6.8.0", + "git-directory-deploy": "^1.5.1", + "jsdoc": "^3.6.4", + "lru-cache": "^4.0.1", + "mocha": "^7.1.1", + "uglify-js": "^3.3.16" + }, + "engines": { + "node": ">=0.10.0" + }, + "homepage": "https://github.com/mde/ejs", + "jsdelivr": "ejs.min.js", + "keywords": [ + "template", + "engine", + "ejs" + ], + "license": "Apache-2.0", + "main": "./lib/ejs.js", + "name": "ejs", + "repository": { + "type": "git", + "url": "git://github.com/mde/ejs.git" + }, + "scripts": { + "postinstall": "node --harmony ./postinstall.js", + "test": "mocha" + }, + "unpkg": "ejs.min.js", + "version": "3.1.3" +} diff --git a/node_modules/ejs/postinstall.js b/node_modules/ejs/postinstall.js new file mode 100644 index 0000000..e62f3c6 --- /dev/null +++ b/node_modules/ejs/postinstall.js @@ -0,0 +1,17 @@ +#!/usr/bin/env node + +'use strict'; + +function isTrue(value) { + return !!value && value !== '0' && value !== 'false'; +} + +let envDisable = isTrue(process.env.DISABLE_OPENCOLLECTIVE) || isTrue(process.env.CI); +let logLevel = process.env.npm_config_loglevel; +let logLevelDisplay = ['silent', 'error', 'warn'].indexOf(logLevel) > -1; + +if (!(envDisable || logLevelDisplay)) { + console.log('Thank you for installing \u001b[35mEJS\u001b[0m: built with the \u001b[32mJake\u001b[0m JavaScript build tool (\u001b[32mhttps://jakejs.com/\u001b[0m\)\n'); +} + + diff --git a/node_modules/ejs/usage.txt b/node_modules/ejs/usage.txt new file mode 100644 index 0000000..7469f7f --- /dev/null +++ b/node_modules/ejs/usage.txt @@ -0,0 +1,24 @@ +EJS Embedded JavaScript templates +{Usage}: ejs [options ...] template-file [data variables ...] + +{Options}: + -o, --output-file FILE Write the rendered output to FILE rather than stdout. + -f, --data-file FILE Must be JSON-formatted. Use parsed input from FILE as data for rendering. + -i, --data-input STRING Must be JSON-formatted and URI-encoded. Use parsed input from STRING as data for rendering. + -m, --delimiter CHARACTER Use CHARACTER with angle brackets for open/close (defaults to %). + -p, --open-delimiter CHARACTER Use CHARACTER instead of left angle bracket to open. + -c, --close-delimiter CHARACTER Use CHARACTER instead of right angle bracket to close. + -s, --strict When set to `true`, generated function is in strict mode + -n --no-with Use 'locals' object for vars rather than using `with` (implies --strict). + -l --locals-name Name to use for the object storing local variables when not using `with`. + -w --rm-whitespace Remove all safe-to-remove whitespace, including leading and trailing whitespace. + -d --debug Outputs generated function body + -h, --help Display this help message. + -V/v, --version Display the EJS version. + +{Examples}: + ejs -m $ ./test/fixtures/user.ejs -f ./user_data.json + ejs -m $ ./test/fixtures/user.ejs name=Lerxst + ejs -p [ -c ] ./template_file.ejs -o ./output.html + ejs -n -l _ ./some_template.ejs -f ./data_file.json + ejs -w ./template_with_whitspace.ejs -o ./output_file.html diff --git a/node_modules/escape-string-regexp/index.js b/node_modules/escape-string-regexp/index.js new file mode 100644 index 0000000..7834bf9 --- /dev/null +++ b/node_modules/escape-string-regexp/index.js @@ -0,0 +1,11 @@ +'use strict'; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; diff --git a/node_modules/escape-string-regexp/license b/node_modules/escape-string-regexp/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/escape-string-regexp/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/escape-string-regexp/package.json b/node_modules/escape-string-regexp/package.json new file mode 100644 index 0000000..64c2def --- /dev/null +++ b/node_modules/escape-string-regexp/package.json @@ -0,0 +1,81 @@ +{ + "_from": "escape-string-regexp@^1.0.5", + "_id": "escape-string-regexp@1.0.5", + "_inBundle": false, + "_integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "_location": "/escape-string-regexp", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "escape-string-regexp@^1.0.5", + "name": "escape-string-regexp", + "escapedName": "escape-string-regexp", + "rawSpec": "^1.0.5", + "saveSpec": null, + "fetchSpec": "^1.0.5" + }, + "_requiredBy": [ + "/chalk" + ], + "_resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "_shasum": "1b61c0562190a8dff6ae3bb2cf0200ca130b86d4", + "_spec": "escape-string-regexp@^1.0.5", + "_where": "C:\\angel\\node_modules\\chalk", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/escape-string-regexp/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Escape RegExp special characters", + "devDependencies": { + "ava": "*", + "xo": "*" + }, + "engines": { + "node": ">=0.8.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/escape-string-regexp#readme", + "keywords": [ + "escape", + "regex", + "regexp", + "re", + "regular", + "expression", + "string", + "str", + "special", + "characters" + ], + "license": "MIT", + "maintainers": [ + { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + { + "name": "Joshua Boy Nicolai Appelman", + "email": "joshua@jbna.nl", + "url": "jbna.nl" + } + ], + "name": "escape-string-regexp", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/escape-string-regexp.git" + }, + "scripts": { + "test": "xo && ava" + }, + "version": "1.0.5" +} diff --git a/node_modules/escape-string-regexp/readme.md b/node_modules/escape-string-regexp/readme.md new file mode 100644 index 0000000..87ac82d --- /dev/null +++ b/node_modules/escape-string-regexp/readme.md @@ -0,0 +1,27 @@ +# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp) + +> Escape RegExp special characters + + +## Install + +``` +$ npm install --save escape-string-regexp +``` + + +## Usage + +```js +const escapeStringRegexp = require('escape-string-regexp'); + +const escapedString = escapeStringRegexp('how much $ for a unicorn?'); +//=> 'how much \$ for a unicorn\?' + +new RegExp(escapedString); +``` + + +## License + +MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/filelist/Jakefile b/node_modules/filelist/Jakefile new file mode 100644 index 0000000..ef22ba0 --- /dev/null +++ b/node_modules/filelist/Jakefile @@ -0,0 +1,14 @@ +testTask('FileList', function () { + this.testFiles.include('test/*.js'); +}); + +publishTask('FileList', function () { + this.packageFiles.include([ + 'Jakefile' + , 'README.md' + , 'package.json' + , 'index.js' + ]); +}); + + diff --git a/node_modules/filelist/README.md b/node_modules/filelist/README.md new file mode 100644 index 0000000..b52ebe7 --- /dev/null +++ b/node_modules/filelist/README.md @@ -0,0 +1,84 @@ +## FileList + +A FileList is a lazy-evaluated list of files. When given a list +of glob patterns for possible files to be included in the file +list, instead of searching the file structures to find the files, +a FileList holds the pattern for latter use. + +This allows you to define a FileList to match any number of +files, but only search out the actual files when then FileList +itself is actually used. The key is that the first time an +element of the FileList/Array is requested, the pending patterns +are resolved into a real list of file names. + +### Usage + +Add files to the list with the `include` method. You can add glob +patterns, individual files, or RegExp objects. When the Array +methods are invoked on the FileList, these items are resolved to +an actual list of files. + +```javascript +var fl = new FileList(); +fl.include('test/*.js'); +fl.exclude('test/helpers.js'); +``` + +Use the `exclude` method to override inclusions. You can use this +when your inclusions are too broad. + +### Array methods + +FileList has lazy-evaluated versions of most of the array +methods, including the following: + +* join +* pop +* push +* concat +* reverse +* shift +* unshift +* slice +* splice +* sort +* filter +* forEach +* some +* every +* map +* indexOf +* lastIndexOf +* reduce +* reduceRight + +When you call one of these methods, the items in the FileList +will be resolved to the full list of files, and the method will +be invoked on that result. + +### Special `length` method + +`length`: FileList includes a length *method* (instead of a +property) which returns the number of actual files in the list +once it's been resolved. + +### FileList-specific methods + +`include`: Add a filename/glob/regex to the list + +`exclude`: Override inclusions by excluding a filename/glob/regex + +`resolve`: Resolve the items in the FileList to the full list of +files. This method is invoked automatically when one of the array +methods is called. + +`toArray`: Immediately resolves the list of items, and returns an +actual array of filepaths. + +`clearInclusions`: Clears any pending items -- must be used +before resolving the list. + +`clearExclusions`: Clears the list of exclusions rules. + + + diff --git a/node_modules/filelist/index.js b/node_modules/filelist/index.js new file mode 100644 index 0000000..3362e3b --- /dev/null +++ b/node_modules/filelist/index.js @@ -0,0 +1,484 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +var fs = require('fs') +, path = require('path') +, minimatch = require('minimatch') +, escapeRegExpChars +, merge +, basedir +, _readDir +, readdirR +, globSync; + + /** + @name escapeRegExpChars + @function + @return {String} A string of escaped characters + @description Escapes regex control-characters in strings + used to build regexes dynamically + @param {String} string The string of chars to escape + */ + escapeRegExpChars = (function () { + var specials = [ '^', '$', '/', '.', '*', '+', '?', '|', '(', ')', + '[', ']', '{', '}', '\\' ]; + var sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g'); + return function (string) { + var str = string || ''; + str = String(str); + return str.replace(sRE, '\\$1'); + }; + })(); + + /** + @name merge + @function + @return {Object} Returns the merged object + @description Merge merges `otherObject` into `object` and takes care of deep + merging of objects + @param {Object} object Object to merge into + @param {Object} otherObject Object to read from + */ + merge = function (object, otherObject) { + var obj = object || {} + , otherObj = otherObject || {} + , key, value; + + for (key in otherObj) { + value = otherObj[key]; + + // Check if a value is an Object, if so recursively add it's key/values + if (typeof value === 'object' && !(value instanceof Array)) { + // Update value of object to the one from otherObj + obj[key] = merge(obj[key], value); + } + // Value is anything other than an Object, so just add it + else { + obj[key] = value; + } + } + + return obj; + }; + /** + Given a patern, return the base directory of it (ie. the folder + that will contain all the files matching the path). + eg. file.basedir('/test/**') => '/test/' + Path ending by '/' are considerd as folder while other are considerd + as files, eg.: + file.basedir('/test/a/') => '/test/a' + file.basedir('/test/a') => '/test' + The returned path always end with a '/' so we have: + file.basedir(file.basedir(x)) == file.basedir(x) + */ + basedir = function (pathParam) { + var bd = '' + , parts + , part + , pos = 0 + , p = pathParam || ''; + + // If the path has a leading asterisk, basedir is the current dir + if (p.indexOf('*') == 0 || p.indexOf('**') == 0) { + return '.'; + } + + // always consider .. at the end as a folder and not a filename + if (/(?:^|\/|\\)\.\.$/.test(p.slice(-3))) { + p += '/'; + } + + parts = p.split(/\\|\//); + for (var i = 0, l = parts.length - 1; i < l; i++) { + part = parts[i]; + if (part.indexOf('*') > -1 || part.indexOf('**') > -1) { + break; + } + pos += part.length + 1; + bd += part + p[pos - 1]; + } + if (!bd) { + bd = '.'; + } + // Strip trailing slashes + if (!(bd == '\\' || bd == '/')) { + bd = bd.replace(/\\$|\/$/, ''); + } + return bd; + + }; + + // Return the contents of a given directory + _readDir = function (dirPath) { + var dir = path.normalize(dirPath) + , paths = [] + , ret = [dir] + , msg; + + try { + paths = fs.readdirSync(dir); + } + catch (e) { + msg = 'Could not read path ' + dir + '\n'; + if (e.stack) { + msg += e.stack; + } + throw new Error(msg); + } + + paths.forEach(function (p) { + var curr = path.join(dir, p); + var stat = fs.statSync(curr); + if (stat.isDirectory()) { + ret = ret.concat(_readDir(curr)); + } + else { + ret.push(curr); + } + }); + + return ret; + }; + + /** + @name file#readdirR + @function + @return {Array} Returns the contents as an Array, can be configured via opts.format + @description Reads the given directory returning it's contents + @param {String} dir The directory to read + @param {Object} opts Options to use + @param {String} [opts.format] Set the format to return(Default: Array) + */ + readdirR = function (dir, opts) { + var options = opts || {} + , format = options.format || 'array' + , ret; + ret = _readDir(dir); + return format == 'string' ? ret.join('\n') : ret; + }; + + +globSync = function (pat, opts) { + var dirname = basedir(pat) + , files + , matches; + + try { + files = readdirR(dirname).map(function(file){ + return file.replace(/\\/g, '/'); + }); + } + // Bail if path doesn't exist -- assume no files + catch(e) { + console.error(e.message); + } + + if (files) { + pat = path.normalize(pat); + matches = minimatch.match(files, pat, opts || {}); + } + return matches || []; +}; + +// Constants +// --------------- +// List of all the builtin Array methods we want to override +var ARRAY_METHODS = Object.getOwnPropertyNames(Array.prototype) +// Array methods that return a copy instead of affecting the original + , SPECIAL_RETURN = { + 'concat': true + , 'slice': true + , 'filter': true + , 'map': true + } +// Default file-patterns we want to ignore + , DEFAULT_IGNORE_PATTERNS = [ + /(^|[\/\\])CVS([\/\\]|$)/ + , /(^|[\/\\])\.svn([\/\\]|$)/ + , /(^|[\/\\])\.git([\/\\]|$)/ + , /\.bak$/ + , /~$/ + ] +// Ignore core files + , DEFAULT_IGNORE_FUNCS = [ + function (name) { + var isDir = false + , stats; + try { + stats = fs.statSync(name); + isDir = stats.isDirectory(); + } + catch(e) {} + return (/(^|[\/\\])core$/).test(name) && !isDir; + } + ]; + +var FileList = function () { + var self = this + , wrap; + + // List of glob-patterns or specific filenames + this.pendingAdd = []; + // Switched to false after lazy-eval of files + this.pending = true; + // Used to calculate exclusions from the list of files + this.excludes = { + pats: DEFAULT_IGNORE_PATTERNS.slice() + , funcs: DEFAULT_IGNORE_FUNCS.slice() + , regex: null + }; + this.items = []; + + // Wrap the array methods with the delegates + wrap = function (prop) { + var arr; + self[prop] = function () { + if (self.pending) { + self.resolve(); + } + if (typeof self.items[prop] == 'function') { + // Special method that return a copy + if (SPECIAL_RETURN[prop]) { + arr = self.items[prop].apply(self.items, arguments); + return FileList.clone(self, arr); + } + else { + return self.items[prop].apply(self.items, arguments); + } + } + else { + return self.items[prop]; + } + }; + }; + for (var i = 0, ii = ARRAY_METHODS.length; i < ii; i++) { + wrap(ARRAY_METHODS[i]); + } + + // Include whatever files got passed to the constructor + this.include.apply(this, arguments); + + // Fix constructor linkage + this.constructor = FileList; +}; + +FileList.prototype = new (function () { + var globPattern = /[*?\[\{]/; + + var _addMatching = function (item) { + var matches = globSync(item.path, item.options); + this.items = this.items.concat(matches); + } + + , _resolveAdd = function (item) { + if (globPattern.test(item.path)) { + _addMatching.call(this, item); + } + else { + this.push(item.path); + } + } + + , _calculateExcludeRe = function () { + var pats = this.excludes.pats + , pat + , excl = [] + , matches = []; + + for (var i = 0, ii = pats.length; i < ii; i++) { + pat = pats[i]; + if (typeof pat == 'string') { + // Glob, look up files + if (/[*?]/.test(pat)) { + matches = globSync(pat); + matches = matches.map(function (m) { + return escapeRegExpChars(m); + }); + excl = excl.concat(matches); + } + // String for regex + else { + excl.push(escapeRegExpChars(pat)); + } + } + // Regex, grab the string-representation + else if (pat instanceof RegExp) { + excl.push(pat.toString().replace(/^\/|\/$/g, '')); + } + } + if (excl.length) { + this.excludes.regex = new RegExp('(' + excl.join(')|(') + ')'); + } + else { + this.excludes.regex = /^$/; + } + } + + , _resolveExclude = function () { + var self = this; + _calculateExcludeRe.call(this); + // No `reject` method, so use reverse-filter + this.items = this.items.filter(function (name) { + return !self.shouldExclude(name); + }); + }; + + /** + * Includes file-patterns in the FileList. Should be called with one or more + * pattern for finding file to include in the list. Arguments should be strings + * for either a glob-pattern or a specific file-name, or an array of them + */ + this.include = function () { + var args = Array.prototype.slice.call(arguments) + , arg + , includes = { items: [], options: {} }; + + for (var i = 0, ilen = args.length; i < ilen; i++) { + arg = args[i]; + + if (typeof arg === 'object' && !Array.isArray(arg)) { + merge(includes.options, arg); + } else { + includes.items = includes.items.concat(arg).filter(function (item) { + return !!item; + }); + } + } + + var items = includes.items.map(function(item) { + return { path: item, options: includes.options }; + }); + + this.pendingAdd = this.pendingAdd.concat(items); + + return this; + }; + + /** + * Indicates whether a particular file would be filtered out by the current + * exclusion rules for this FileList. + * @param {String} name The filename to check + * @return {Boolean} Whether or not the file should be excluded + */ + this.shouldExclude = function (name) { + if (!this.excludes.regex) { + _calculateExcludeRe.call(this); + } + var excl = this.excludes; + return excl.regex.test(name) || excl.funcs.some(function (f) { + return !!f(name); + }); + }; + + /** + * Excludes file-patterns from the FileList. Should be called with one or more + * pattern for finding file to include in the list. Arguments can be: + * 1. Strings for either a glob-pattern or a specific file-name + * 2. Regular expression literals + * 3. Functions to be run on the filename that return a true/false + */ + this.exclude = function () { + var args = Array.isArray(arguments[0]) ? arguments[0] : arguments + , arg; + for (var i = 0, ii = args.length; i < ii; i++) { + arg = args[i]; + if (typeof arg == 'function' && !(arg instanceof RegExp)) { + this.excludes.funcs.push(arg); + } + else { + this.excludes.pats.push(arg); + } + } + if (!this.pending) { + _resolveExclude.call(this); + } + return this; + }; + + /** + * Populates the FileList from the include/exclude rules with a list of + * actual files + */ + this.resolve = function () { + var item + , uniqueFunc = function (p, c) { + if (p.indexOf(c) < 0) { + p.push(c); + } + return p; + }; + if (this.pending) { + this.pending = false; + while ((item = this.pendingAdd.shift())) { + _resolveAdd.call(this, item); + } + // Reduce to a unique list + this.items = this.items.reduce(uniqueFunc, []); + // Remove exclusions + _resolveExclude.call(this); + } + return this; + }; + + /** + * Convert to a plain-jane array + */ + this.toArray = function () { + // Call slice to ensure lazy-resolution before slicing items + var ret = this.slice().items.slice(); + return ret; + }; + + /** + * Clear any pending items -- only useful before + * calling `resolve` + */ + this.clearInclusions = function () { + this.pendingAdd = []; + return this; + }; + + /** + * Clear any current exclusion rules + */ + this.clearExclusions = function () { + this.excludes = { + pats: [] + , funcs: [] + , regex: null + }; + return this; + }; + +})(); + +// Static method, used to create copy returned by special +// array methods +FileList.clone = function (list, items) { + var clone = new FileList(); + if (items) { + clone.items = items; + } + clone.pendingAdd = list.pendingAdd; + clone.pending = list.pending; + for (var p in list.excludes) { + clone.excludes[p] = list.excludes[p]; + } + return clone; +}; + +exports.FileList = FileList; diff --git a/node_modules/filelist/package.json b/node_modules/filelist/package.json new file mode 100644 index 0000000..2cf0458 --- /dev/null +++ b/node_modules/filelist/package.json @@ -0,0 +1,56 @@ +{ + "_from": "filelist@^1.0.1", + "_id": "filelist@1.0.1", + "_inBundle": false, + "_integrity": "sha512-8zSK6Nu0DQIC08mUC46sWGXi+q3GGpKydAG36k+JDba6VRpkevvOWUW5a/PhShij4+vHT9M+ghgG7eM+a9JDUQ==", + "_location": "/filelist", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "filelist@^1.0.1", + "name": "filelist", + "escapedName": "filelist", + "rawSpec": "^1.0.1", + "saveSpec": null, + "fetchSpec": "^1.0.1" + }, + "_requiredBy": [ + "/jake" + ], + "_resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.1.tgz", + "_shasum": "f10d1a3ae86c1694808e8f20906f43d4c9132dbb", + "_spec": "filelist@^1.0.1", + "_where": "C:\\angel\\node_modules\\jake", + "author": { + "name": "Matthew Eernisse", + "email": "mde@fleegix.org", + "url": "http://fleegix.org" + }, + "bugs": { + "url": "https://github.com/mde/filelist/issues" + }, + "bundleDependencies": false, + "dependencies": { + "minimatch": "^3.0.4" + }, + "deprecated": false, + "description": "Lazy-evaluating list of files, based on globs or regex patterns", + "homepage": "https://github.com/mde/filelist", + "keywords": [ + "file", + "utility", + "glob" + ], + "license": "Apache-2.0", + "main": "index.js", + "name": "filelist", + "repository": { + "type": "git", + "url": "git://github.com/mde/filelist.git" + }, + "scripts": { + "test": "jake test" + }, + "version": "1.0.1" +} diff --git a/node_modules/has-flag/index.js b/node_modules/has-flag/index.js new file mode 100644 index 0000000..5139728 --- /dev/null +++ b/node_modules/has-flag/index.js @@ -0,0 +1,8 @@ +'use strict'; +module.exports = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; 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.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..8b5ceae --- /dev/null +++ b/node_modules/has-flag/package.json @@ -0,0 +1,76 @@ +{ + "_from": "has-flag@^3.0.0", + "_id": "has-flag@3.0.0", + "_inBundle": false, + "_integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "_location": "/has-flag", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "has-flag@^3.0.0", + "name": "has-flag", + "escapedName": "has-flag", + "rawSpec": "^3.0.0", + "saveSpec": null, + "fetchSpec": "^3.0.0" + }, + "_requiredBy": [ + "/supports-color" + ], + "_resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "_shasum": "b5d454dc2199ae225699f3467e5a07f3b955bafd", + "_spec": "has-flag@^3.0.0", + "_where": "C:\\angel\\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": "*", + "xo": "*" + }, + "engines": { + "node": ">=4" + }, + "files": [ + "index.js" + ], + "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" + }, + "version": "3.0.0" +} diff --git a/node_modules/has-flag/readme.md b/node_modules/has-flag/readme.md new file mode 100644 index 0000000..677893c --- /dev/null +++ b/node_modules/has-flag/readme.md @@ -0,0 +1,70 @@ +# 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. + + +## 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[]`
+Default: `process.argv` + +CLI arguments. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/jake/Makefile b/node_modules/jake/Makefile new file mode 100644 index 0000000..3d0574e --- /dev/null +++ b/node_modules/jake/Makefile @@ -0,0 +1,44 @@ +# +# Jake JavaScript build tool +# Copyright 2112 Matthew Eernisse (mde@fleegix.org) +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +.PHONY: all build install clean uninstall + +PREFIX=/usr/local +DESTDIR= + +all: build + +build: + @echo 'Jake built.' + +install: + @mkdir -p $(DESTDIR)$(PREFIX)/bin && \ + mkdir -p $(DESTDIR)$(PREFIX)/lib/node_modules/jake && \ + mkdir -p ./node_modules && \ + npm install utilities minimatch && \ + cp -R ./* $(DESTDIR)$(PREFIX)/lib/node_modules/jake/ && \ + ln -snf ../lib/node_modules/jake/bin/cli.js $(DESTDIR)$(PREFIX)/bin/jake && \ + chmod 755 $(DESTDIR)$(PREFIX)/lib/node_modules/jake/bin/cli.js && \ + echo 'Jake installed.' + +clean: + @true + +uninstall: + @rm -f $(DESTDIR)$(PREFIX)/bin/jake && \ + rm -fr $(DESTDIR)$(PREFIX)/lib/node_modules/jake/ && \ + echo 'Jake uninstalled.' diff --git a/node_modules/jake/README.md b/node_modules/jake/README.md new file mode 100644 index 0000000..e938850 --- /dev/null +++ b/node_modules/jake/README.md @@ -0,0 +1,17 @@ +### Jake -- the JavaScript build tool for Node.js + +[![Build Status](https://travis-ci.org/jakejs/jake.svg?branch=master)](https://travis-ci.org/jakejs/jake) + +Documentation site at [http://jakejs.com](http://jakejs.com/) + +### Contributing +1. [Install node](http://nodejs.org/#download). +2. Clone this repository `$ git clone git@github.com:jakejs/jake.git`. +3. Install dependencies `$ npm install`. +4. Run tests with `$ npm test`. +5. Start Hacking! + +### License + +Licensed under the Apache License, Version 2.0 +() diff --git a/node_modules/jake/bin/bash_completion.sh b/node_modules/jake/bin/bash_completion.sh new file mode 100644 index 0000000..bb25995 --- /dev/null +++ b/node_modules/jake/bin/bash_completion.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +# http://stackoverflow.com/a/246128 +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + SOURCE="$(readlink "$SOURCE")" + [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located +done +JAKE_BIN_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + +# http://stackoverflow.com/a/12495480 +# http://stackoverflow.com/a/28647824 +_auto_jake() +{ + local cur + local -a COMPGEN=() + _get_comp_words_by_ref -n : -c cur + + # run auto-completions in jake via our auto_complete.js wrapper + local -a auto_complete_info=( $(export COMP_LINE="${COMP_LINE}" && ${JAKE_BIN_DIR}/auto_complete.js "$cur" "${3}") ) + # check reply flag + local reply_flag="${auto_complete_info[0]}" + if [[ "${reply_flag}" == "no-complete" ]]; then + return 1 + fi + local auto_completions=("${auto_complete_info[@]:1}") + COMPGEN=( $(compgen -W "${auto_completions[*]}" -- "$cur") ) + COMPREPLY=( "${COMPGEN[@]}" ) + + __ltrim_colon_completions "$cur" + + # do we need another space?? + if [[ "${reply_flag}" == "yes-space" ]]; then + COMPREPLY=( "${COMPGEN[@]}" " " ) + fi + + return 0 +} + +complete -o default -F _auto_jake jake diff --git a/node_modules/jake/bin/cli.js b/node_modules/jake/bin/cli.js new file mode 100644 index 0000000..9f68abb --- /dev/null +++ b/node_modules/jake/bin/cli.js @@ -0,0 +1,31 @@ +#!/usr/bin/env node +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +// Try to load a local jake +try { + require(`${ process.cwd() }/node_modules/jake`); +} +// If that fails, likely running globally +catch(e) { + require('../lib/jake'); +} + +var args = process.argv.slice(2); + +jake.run.apply(jake, args); diff --git a/node_modules/jake/jakefile.js b/node_modules/jake/jakefile.js new file mode 100644 index 0000000..b0ae79b --- /dev/null +++ b/node_modules/jake/jakefile.js @@ -0,0 +1,105 @@ +let fs = require('fs') +let path = require('path'); +let proc = require('child_process'); + +const PROJECT_DIR = process.cwd(); +process.env.PROJECT_DIR = PROJECT_DIR; + +namespace('doc', function () { + task('generate', ['doc:clobber'], function () { + var cmd = '../node-jsdoc-toolkit/app/run.js -n -r=100 ' + + '-t=../node-jsdoc-toolkit/templates/codeview -d=./doc/ ./lib'; + jake.logger.log('Generating docs ...'); + jake.exec([cmd], function () { + jake.logger.log('Done.'); + complete(); + }); + }, {async: true}); + + task('clobber', function () { + var cmd = 'rm -fr ./doc/*'; + jake.exec([cmd], function () { + jake.logger.log('Clobbered old docs.'); + complete(); + }); + }, {async: true}); + +}); + +desc('Generate docs for Jake'); +task('doc', ['doc:generate']); + +npmPublishTask('jake', function () { + this.packageFiles.include([ + 'Makefile', + 'jakefile.js', + 'README.md', + 'package.json', + 'usage.txt', + 'lib/**', + 'bin/**', + 'test/**' + ]); + this.packageFiles.exclude([ + 'test/tmp' + ]); +}); + +jake.Task['publish:package'].directory = PROJECT_DIR; + +namespace('test', function () { + + let integrationTest = task('integration', ['publish:package'], async function () { + let pkg = JSON.parse(fs.readFileSync(`${PROJECT_DIR}/package.json`).toString()); + let version = pkg.version; + + proc.execSync('rm -rf ./node_modules'); + // Install from the actual package, run tests from the packaged binary + proc.execSync(`mkdir -p node_modules/.bin && mv ${PROJECT_DIR}/pkg/jake-v` + + `${version} node_modules/jake && ln -s ${process.cwd()}` + + '/node_modules/jake/bin/cli.js ./node_modules/.bin/jake'); + + let testArgs = []; + if (process.env.filter) { + testArgs.push(process.env.filter); + } + else { + testArgs.push('*.js'); + } + let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, { + stdio: 'inherit' + }); + return new Promise((resolve, reject) => { + spawned.on('exit', () => { + if (!(process.env.noclobber || process.env.noClobber)) { + proc.execSync('rm -rf tmp_publish && rm -rf package.json' + + ' && rm -rf package-lock.json && rm -rf node_modules'); + // Rather than invoking 'clobber' task + jake.rmRf(`${PROJECT_DIR}/pkg`); + } + resolve(); + }); + }); + + }); + + integrationTest.directory = `${PROJECT_DIR}/test/integration`; + + let unitTest = task('unit', async function () { + let testArgs = []; + if (process.env.filter) { + testArgs.push(process.env.filter); + } + else { + testArgs.push('*.js'); + } + let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, { + stdio: 'inherit' + }); + }); + + unitTest.directory = `${PROJECT_DIR}/test/unit`; +}); + +desc('Runs all tests'); +task('test', ['test:unit', 'test:integration']); diff --git a/node_modules/jake/lib/api.js b/node_modules/jake/lib/api.js new file mode 100644 index 0000000..9f09140 --- /dev/null +++ b/node_modules/jake/lib/api.js @@ -0,0 +1,409 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ +let { uuid } = require('./utils'); + +let api = new (function () { + /** + @name task + @static + @function + @description Creates a Jake Task + ` + @param {String} name The name of the Task + @param {Array} [prereqs] Prerequisites to be run before this task + @param {Function} [action] The action to perform for this task + @param {Object} [opts] + @param {Boolean} [opts.asyc=false] Perform this task asynchronously. + If you flag a task with this option, you must call the global + `complete` method inside the task's action, for execution to proceed + to the next task. + + @example + desc('This is the default task.'); + task('default', function (params) { + console.log('This is the default task.'); + }); + + desc('This task has prerequisites.'); + task('hasPrereqs', ['foo', 'bar', 'baz'], function (params) { + console.log('Ran some prereqs first.'); + }); + + desc('This is an asynchronous task.'); + task('asyncTask', function () { + setTimeout(complete, 1000); + }, {async: true}); + */ + this.task = function (name, prereqs, action, opts) { + let args = Array.prototype.slice.call(arguments); + let createdTask; + args.unshift('task'); + createdTask = jake.createTask.apply(global, args); + jake.currentTaskDescription = null; + return createdTask; + }; + + /** + @name rule + @static + @function + @description Creates a Jake Suffix Rule + ` + @param {String} pattern The suffix name of the objective + @param {String} source The suffix name of the objective + @param {Array} [prereqs] Prerequisites to be run before this task + @param {Function} [action] The action to perform for this task + @param {Object} [opts] + @param {Boolean} [opts.asyc=false] Perform this task asynchronously. + If you flag a task with this option, you must call the global + `complete` method inside the task's action, for execution to proceed + to the next task. + @example + desc('This is a rule, which does not support namespace or pattern.'); + rule('.o', '.c', {async: true}, function () { + let cmd = util.format('gcc -o %s %s', this.name, this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + desc('This rule has prerequisites.'); + rule('.o', '.c', ['util.h'], {async: true}, function () { + let cmd = util.format('gcc -o %s %s', this.name, this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + desc('This is a rule with patterns.'); + rule('%.o', '%.c', {async: true}, function () { + let cmd = util.format('gcc -o %s %s', this.name, this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + desc('This is another rule with patterns.'); + rule('obj/%.o', 'src/%.c', {async: true}, function () { + let cmd = util.format('gcc -o %s %s', this.name, this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + desc('This is an example with chain rules.'); + rule('%.pdf', '%.dvi', {async: true}, function () { + let cmd = util.format('dvipdfm %s',this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + rule('%.dvi', '%.tex', {async: true}, function () { + let cmd = util.format('latex %s',this.source); + jake.exec([cmd], function () { + complete(); + }, {printStdout: true}); + }); + + desc('This rule has a namespace.'); + task('default', ['debug:obj/main.o]); + + namespace('debug', {async: true}, function() { + rule('obj/%.o', 'src/%.c', function () { + // ... + }); + } + */ + this.rule = function () { + let args = Array.prototype.slice.call(arguments); + let arg; + let pattern = args.shift(); + let source = args.shift(); + let prereqs = []; + let action = function () {}; + let opts = {}; + let key = pattern.toString(); // May be a RegExp + + while ((arg = args.shift())) { + if (typeof arg == 'function') { + action = arg; + } + else if (Array.isArray(arg)) { + prereqs = arg; + } + else { + opts = arg; + } + } + + jake.currentNamespace.rules[key] = new jake.Rule({ + pattern: pattern, + source: source, + prereqs: prereqs, + action: action, + opts: opts, + desc: jake.currentTaskDescription, + ns: jake.currentNamespace + }); + jake.currentTaskDescription = null; + }; + + /** + @name directory + @static + @function + @description Creates a Jake DirectoryTask. Can be used as a prerequisite + for FileTasks, or for simply ensuring a directory exists for use with a + Task's action. + ` + @param {String} name The name of the DiretoryTask + + @example + + // Creates the package directory for distribution + directory('pkg'); + */ + this.directory = function (name) { + let args = Array.prototype.slice.call(arguments); + let createdTask; + args.unshift('directory'); + createdTask = jake.createTask.apply(global, args); + jake.currentTaskDescription = null; + return createdTask; + }; + + /** + @name file + @static + @function + @description Creates a Jake FileTask. + ` + @param {String} name The name of the FileTask + @param {Array} [prereqs] Prerequisites to be run before this task + @param {Function} [action] The action to create this file, if it doesn't + exist already. + @param {Object} [opts] + @param {Array} [opts.asyc=false] Perform this task asynchronously. + If you flag a task with this option, you must call the global + `complete` method inside the task's action, for execution to proceed + to the next task. + + */ + this.file = function (name, prereqs, action, opts) { + let args = Array.prototype.slice.call(arguments); + let createdTask; + args.unshift('file'); + createdTask = jake.createTask.apply(global, args); + jake.currentTaskDescription = null; + return createdTask; + }; + + /** + @name desc + @static + @function + @description Creates a description for a Jake Task (or FileTask, + DirectoryTask). When invoked, the description that iscreated will + be associated with whatever Task is created next. + ` + @param {String} description The description for the Task + */ + this.desc = function (description) { + jake.currentTaskDescription = description; + }; + + /** + @name namespace + @static + @function + @description Creates a namespace which allows logical grouping + of tasks, and prevents name-collisions with task-names. Namespaces + can be nested inside of other namespaces. + ` + @param {String} name The name of the namespace + @param {Function} scope The enclosing scope for the namespaced tasks + + @example + namespace('doc', function () { + task('generate', ['doc:clobber'], function () { + // Generate some docs + }); + + task('clobber', function () { + // Clobber the doc directory first + }); + }); + */ + this.namespace = function (name, closure) { + let curr = jake.currentNamespace; + let ns = curr.childNamespaces[name] || new jake.Namespace(name, curr); + let fn = closure || function () {}; + curr.childNamespaces[name] = ns; + jake.currentNamespace = ns; + fn(); + jake.currentNamespace = curr; + jake.currentTaskDescription = null; + return ns; + }; + + /** + @name complete + @static + @function + @description Completes an asynchronous task, allowing Jake's + execution to proceed to the next task. Calling complete globally or without + arguments completes the last task on the invocationChain. If you use parallel + execution of prereqs this will probably complete a wrong task. You should call this + function with this task as the first argument, before the optional return value. + Alternatively you can call task.complete() + ` + @example + task('generate', ['doc:clobber'], function () { + exec('./generate_docs.sh', function (err, stdout, stderr) { + if (err || stderr) { + fail(err || stderr); + } + else { + console.log(stdout); + complete(); + } + }); + }, {async: true}); + */ + this.complete = function (task, val) { + //this should detect if the first arg is a task, but I guess it should be more thorough + if(task && task. _currentPrereqIndex >=0 ) { + task.complete(val); + } + else { + val = task; + if(jake._invocationChain.length > 0) { + jake._invocationChain[jake._invocationChain.length-1].complete(val); + } + } + }; + + /** + @name fail + @static + @function + @description Causes Jake execution to abort with an error. + Allows passing an optional error code, which will be used to + set the exit-code of exiting process. + ` + @param {Error|String} err The error to thow when aborting execution. + If this argument is an Error object, it will simply be thrown. If + a String, it will be used as the error-message. (If it is a multi-line + String, the first line will be used as the Error message, and the + remaining lines will be used as the error-stack.) + + @example + task('createTests, function () { + if (!fs.existsSync('./tests')) { + fail('Test directory does not exist.'); + } + else { + // Do some testing stuff ... + } + }); + */ + this.fail = function (err, code) { + let msg; + let errObj; + if (code) { + jake.errorCode = code; + } + if (err) { + if (typeof err == 'string') { + // Use the initial or only line of the error as the error-message + // If there was a multi-line error, use the rest as the stack + msg = err.split('\n'); + errObj = new Error(msg.shift()); + if (msg.length) { + errObj.stack = msg.join('\n'); + } + throw errObj; + } + else if (err instanceof Error) { + throw err; + } + else { + throw new Error(err.toString()); + } + } + else { + throw new Error(); + } + }; + + this.packageTask = function (name, version, prereqs, definition) { + return new jake.PackageTask(name, version, prereqs, definition); + }; + + this.publishTask = function (name, prereqs, opts, definition) { + return new jake.PublishTask(name, prereqs, opts, definition); + }; + + // Backward-compat + this.npmPublishTask = function (name, prereqs, opts, definition) { + return new jake.PublishTask(name, prereqs, opts, definition); + }; + + this.testTask = function () { + let ctor = function () {}; + let t; + ctor.prototype = jake.TestTask.prototype; + t = new ctor(); + jake.TestTask.apply(t, arguments); + return t; + }; + + this.setTaskTimeout = function (t) { + this._taskTimeout = t; + }; + + this.setSeriesAutoPrefix = function (prefix) { + this._seriesAutoPrefix = prefix; + }; + + this.series = function (...args) { + let prereqs = args.map((arg) => { + let name = (this._seriesAutoPrefix || '') + arg.name; + jake.task(name, arg); + return name; + }); + let seriesName = uuid(); + let seriesTask = jake.task(seriesName, prereqs); + seriesTask._internal = true; + let res = function () { + return new Promise((resolve) => { + seriesTask.invoke(); + seriesTask.on('complete', (val) => { + resolve(val); + }); + }); + }; + Object.defineProperty(res, 'name', {value: uuid(), + writable: false}); + return res; + }; + +})(); + +module.exports = api; diff --git a/node_modules/jake/lib/jake.js b/node_modules/jake/lib/jake.js new file mode 100644 index 0000000..a463163 --- /dev/null +++ b/node_modules/jake/lib/jake.js @@ -0,0 +1,319 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +if (!global.jake) { + + let EventEmitter = require('events').EventEmitter; + // And so it begins + global.jake = new EventEmitter(); + + let fs = require('fs'); + let chalk = require('chalk'); + let taskNs = require('./task'); + let Task = taskNs.Task; + let FileTask = taskNs.FileTask; + let DirectoryTask = taskNs.DirectoryTask; + let Rule = require('./rule').Rule; + let Namespace = require('./namespace').Namespace; + let RootNamespace = require('./namespace').RootNamespace; + let api = require('./api'); + let utils = require('./utils'); + let Program = require('./program').Program; + let loader = require('./loader')(); + let pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString()); + + const MAX_RULE_RECURSION_LEVEL = 16; + + // Globalize jake and top-level API methods (e.g., `task`, `desc`) + Object.assign(global, api); + + // Copy utils onto base jake + jake.logger = utils.logger; + jake.exec = utils.exec; + + // File utils should be aliased directly on base jake as well + Object.assign(jake, utils.file); + + // Also add top-level API methods to exported object for those who don't want to + // use the globals (`file` here will overwrite the 'file' utils namespace) + Object.assign(jake, api); + + Object.assign(jake, new (function () { + + this._invocationChain = []; + this._taskTimeout = 30000; + + // Public properties + // ================= + this.version = pkg.version; + // Used when Jake exits with a specific error-code + this.errorCode = null; + // Loads Jakefiles/jakelibdirs + this.loader = loader; + // The root of all ... namespaces + this.rootNamespace = new RootNamespace(); + // Non-namespaced tasks are placed into the default + this.defaultNamespace = this.rootNamespace; + // Start in the default + this.currentNamespace = this.defaultNamespace; + // Saves the description created by a 'desc' call that prefaces a + // 'task' call that defines a task. + this.currentTaskDescription = null; + this.program = new Program(); + this.FileList = require('filelist').FileList; + this.PackageTask = require('./package_task').PackageTask; + this.PublishTask = require('./publish_task').PublishTask; + this.TestTask = require('./test_task').TestTask; + this.Task = Task; + this.FileTask = FileTask; + this.DirectoryTask = DirectoryTask; + this.Namespace = Namespace; + this.Rule = Rule; + + this.parseAllTasks = function () { + let _parseNs = function (ns) { + let nsTasks = ns.tasks; + let nsNamespaces = ns.childNamespaces; + for (let q in nsTasks) { + let nsTask = nsTasks[q]; + jake.Task[nsTask.fullName] = nsTask; + } + for (let p in nsNamespaces) { + let nsNamespace = nsNamespaces[p]; + _parseNs(nsNamespace); + } + }; + _parseNs(jake.defaultNamespace); + }; + + /** + * Displays the list of descriptions avaliable for tasks defined in + * a Jakefile + */ + this.showAllTaskDescriptions = function (f) { + let p; + let maxTaskNameLength = 0; + let task; + let padding; + let name; + let descr; + let filter = typeof f == 'string' ? f : null; + + for (p in jake.Task) { + if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) { + continue; + } + if (filter && p.indexOf(filter) == -1) { + continue; + } + task = jake.Task[p]; + // Record the length of the longest task name -- used for + // pretty alignment of the task descriptions + if (task.description) { + maxTaskNameLength = p.length > maxTaskNameLength ? + p.length : maxTaskNameLength; + } + } + // Print out each entry with descriptions neatly aligned + for (p in jake.Task) { + if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) { + continue; + } + if (filter && p.indexOf(filter) == -1) { + continue; + } + task = jake.Task[p]; + + //name = '\033[32m' + p + '\033[39m '; + name = chalk.green(p); + + descr = task.description; + if (descr) { + descr = chalk.gray('# ' + descr); + + // Create padding-string with calculated length + padding = (new Array(maxTaskNameLength - p.length + 2)).join(' '); + + console.log('jake ' + name + padding + descr); + } + } + }; + + this.createTask = function () { + let args = Array.prototype.slice.call(arguments); + let arg; + let obj; + let task; + let type; + let name; + let action; + let opts = {}; + let prereqs = []; + + type = args.shift(); + + // name, [deps], [action] + // Name (string) + deps (array) format + if (typeof args[0] == 'string') { + name = args.shift(); + if (Array.isArray(args[0])) { + prereqs = args.shift(); + } + } + // name:deps, [action] + // Legacy object-literal syntax, e.g.: {'name': ['depA', 'depB']} + else { + obj = args.shift(); + for (let p in obj) { + prereqs = prereqs.concat(obj[p]); + name = p; + } + } + + // Optional opts/callback or callback/opts + while ((arg = args.shift())) { + if (typeof arg == 'function') { + action = arg; + } + else { + opts = Object.assign(Object.create(null), arg); + } + } + + task = jake.currentNamespace.resolveTask(name); + if (task && !action) { + // Task already exists and no action, just update prereqs, and return it. + task.prereqs = task.prereqs.concat(prereqs); + return task; + } + + switch (type) { + case 'directory': + action = function () { + jake.mkdirP(name); + }; + task = new DirectoryTask(name, prereqs, action, opts); + break; + case 'file': + task = new FileTask(name, prereqs, action, opts); + break; + default: + task = new Task(name, prereqs, action, opts); + } + + jake.currentNamespace.addTask(task); + + if (jake.currentTaskDescription) { + task.description = jake.currentTaskDescription; + jake.currentTaskDescription = null; + } + + // FIXME: Should only need to add a new entry for the current + // task-definition, not reparse the entire structure + jake.parseAllTasks(); + + return task; + }; + + this.attemptRule = function (name, ns, level) { + let prereqRule; + let prereq; + if (level > MAX_RULE_RECURSION_LEVEL) { + return null; + } + // Check Rule + prereqRule = ns.matchRule(name); + if (prereqRule) { + prereq = prereqRule.createTask(name, level); + } + return prereq || null; + }; + + this.createPlaceholderFileTask = function (name, namespace) { + let parsed = name.split(':'); + let filePath = parsed.pop(); // Strip any namespace + let task; + + task = namespace.resolveTask(name); + + // If there's not already an existing dummy FileTask for it, + // create one + if (!task) { + // Create a dummy FileTask only if file actually exists + if (fs.existsSync(filePath)) { + task = new jake.FileTask(filePath); + task.dummy = true; + let ns; + if (parsed.length) { + ns = namespace.resolveNamespace(parsed.join(':')); + } + else { + ns = namespace; + } + if (!namespace) { + throw new Error('Invalid namespace, cannot add FileTask'); + } + ns.addTask(task); + // Put this dummy Task in the global Tasks list so + // modTime will be eval'd correctly + jake.Task[`${ns.path}:${filePath}`] = task; + } + } + + return task || null; + }; + + + this.run = function () { + let args = Array.prototype.slice.call(arguments); + let program = this.program; + let loader = this.loader; + let preempt; + let opts; + + program.parseArgs(args); + program.init(); + + preempt = program.firstPreemptiveOption(); + if (preempt) { + preempt(); + } + else { + opts = program.opts; + // jakefile flag set but no jakefile yet + if (opts.autocomplete && opts.jakefile === true) { + process.stdout.write('no-complete'); + return; + } + // Load Jakefile and jakelibdir files + let jakefileLoaded = loader.loadFile(opts.jakefile); + let jakelibdirLoaded = loader.loadDirectory(opts.jakelibdir); + + if(!jakefileLoaded && !jakelibdirLoaded && !opts.autocomplete) { + fail('No Jakefile. Specify a valid path with -f/--jakefile, ' + + 'or place one in the current directory.'); + } + + program.run(); + } + }; + + })()); +} + +module.exports = jake; diff --git a/node_modules/jake/lib/loader.js b/node_modules/jake/lib/loader.js new file mode 100644 index 0000000..02ad262 --- /dev/null +++ b/node_modules/jake/lib/loader.js @@ -0,0 +1,165 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let path = require('path'); +let fs = require('fs'); +let existsSync = fs.existsSync; +let utils = require('./utils'); + +// Files like jakelib/foobar.jake.js +const JAKELIB_FILE_PAT = /\.jake$|\.js$/; +const SUPPORTED_EXTENSIONS = { + 'js': null, + 'coffee': function () { + try { + let cs = require('coffeescript'); + if (typeof cs.register == 'function') { + cs.register(); + } + } + catch(e) { + throw new Error('You have a CoffeeScript Jakefile, but have not installed CoffeeScript'); + } + }, + 'ls': function () { + try { + require('livescript'); + } + catch (e) { + throw new Error('You have a LiveScript Jakefile, but have not installed LiveScript'); + } + } +}; +const IMPLICIT_JAKEFILE_NAMES = [ + 'Jakefile', + 'Gulpfile' +]; + +let Loader = function () { + // Load a Jakefile, running the code inside -- this may result in + // tasks getting defined using the original Jake API, e.g., + // `task('foo' ['bar', 'baz']);`, or can also auto-create tasks + // from any functions exported from the file + function loadFile(filePath) { + let exported = require(filePath); + for (let [key, value] of Object.entries(exported)) { + let t; + if (typeof value == 'function') { + t = jake.task(key, value); + t.description = '(Exported function)'; + } + } + } + + function fileExists(name) { + let nameWithExt = null; + // Support no file extension as well + let exts = Object.keys(SUPPORTED_EXTENSIONS).concat(['']); + exts.some((ext) => { + let fname = ext ? `${name}.${ext}` : name; + if (existsSync(fname)) { + nameWithExt = fname; + return true; + } + }); + return nameWithExt; + } + + // Recursive + function findImplicitJakefile() { + let cwd = process.cwd(); + let names = IMPLICIT_JAKEFILE_NAMES; + let found = null; + names.some((name) => { + let n; + // Prefer all-lowercase + n = name.toLowerCase(); + if ((found = fileExists(n))) { + return found; + } + // Check mixed-case as well + n = name; + if ((found = fileExists(n))) { + return found; + } + }); + if (found) { + return found; + } + else { + process.chdir(".."); + // If we've walked all the way up the directory tree, + // bail out with no result + if (cwd === process.cwd()) { + return null; + } + return findImplicitJakefile(); + } + } + + this.loadFile = function (fileSpecified) { + let jakefile; + let origCwd = process.cwd(); + + if (fileSpecified) { + if (existsSync(fileSpecified)) { + jakefile = fileSpecified; + } + } + else { + jakefile = findImplicitJakefile(); + } + + if (jakefile) { + let ext = jakefile.split('.')[1]; + let loaderFunc = SUPPORTED_EXTENSIONS[ext]; + loaderFunc && loaderFunc(); + + loadFile(utils.file.absolutize(jakefile)); + return true; + } + else { + if (!fileSpecified) { + // Restore the working directory on failure + process.chdir(origCwd); + } + return false; + } + }; + + this.loadDirectory = function (d) { + let dirname = d || 'jakelib'; + let dirlist; + dirname = utils.file.absolutize(dirname); + if (existsSync(dirname)) { + dirlist = fs.readdirSync(dirname); + dirlist.forEach(function (filePath) { + if (JAKELIB_FILE_PAT.test(filePath)) { + loadFile(path.join(dirname, filePath)); + } + }); + return true; + } + return false; + }; + +}; + +module.exports = function () { + return new Loader(); +}; diff --git a/node_modules/jake/lib/namespace.js b/node_modules/jake/lib/namespace.js new file mode 100644 index 0000000..a3c2787 --- /dev/null +++ b/node_modules/jake/lib/namespace.js @@ -0,0 +1,115 @@ +const ROOT_NAMESPACE_NAME = '__rootNamespace__'; + +class Namespace { + constructor(name, parentNamespace) { + this.name = name; + this.parentNamespace = parentNamespace; + this.childNamespaces = {}; + this.tasks = {}; + this.rules = {}; + this.path = this.getPath(); + } + + get fullName() { + return this._getFullName(); + } + + addTask(task) { + this.tasks[task.name] = task; + task.namespace = this; + } + + resolveTask(name) { + if (!name) { + return; + } + + let taskPath = name.split(':'); + let taskName = taskPath.pop(); + let task; + let ns; + + // Namespaced, return either relative to current, or from root + if (taskPath.length) { + taskPath = taskPath.join(':'); + ns = this.resolveNamespace(taskPath) || + Namespace.ROOT_NAMESPACE.resolveNamespace(taskPath); + task = (ns && ns.resolveTask(taskName)); + } + // Bare task, return either local, or top-level + else { + task = this.tasks[name] || Namespace.ROOT_NAMESPACE.tasks[name]; + } + + return task || null; + } + + + resolveNamespace(relativeName) { + if (!relativeName) { + return this; + } + + let parts = relativeName.split(':'); + let ns = this; + + for (let i = 0, ii = parts.length; (ns && i < ii); i++) { + ns = ns.childNamespaces[parts[i]]; + } + + return ns || null; + } + + matchRule(relativeName) { + let parts = relativeName.split(':'); + parts.pop(); + let ns = this.resolveNamespace(parts.join(':')); + let rules = ns ? ns.rules : []; + let r; + let match; + + for (let p in rules) { + r = rules[p]; + if (r.match(relativeName)) { + match = r; + } + } + + return (ns && match) || + (this.parentNamespace && + this.parentNamespace.matchRule(relativeName)); + } + + getPath() { + let parts = []; + let next = this.parentNamespace; + while (next) { + parts.push(next.name); + next = next.parentNamespace; + } + parts.pop(); // Remove '__rootNamespace__' + return parts.reverse().join(':'); + } + + _getFullName() { + let path = this.path; + path = (path && path.split(':')) || []; + path.push(this.name); + return path.join(':'); + } + + isRootNamespace() { + return !this.parentNamespace; + } +} + +class RootNamespace extends Namespace { + constructor() { + super(ROOT_NAMESPACE_NAME, null); + Namespace.ROOT_NAMESPACE = this; + } +} + +module.exports.Namespace = Namespace; +module.exports.RootNamespace = RootNamespace; + diff --git a/node_modules/jake/lib/package_task.js b/node_modules/jake/lib/package_task.js new file mode 100644 index 0000000..527aca7 --- /dev/null +++ b/node_modules/jake/lib/package_task.js @@ -0,0 +1,406 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let path = require('path'); +let fs = require('fs'); +let exec = require('child_process').exec; +let FileList = require('filelist').FileList; + +/** + @name jake + @namespace jake +*/ +/** + @name jake.PackageTask + @constructor + @description Instantiating a PackageTask creates a number of Jake + Tasks that make packaging and distributing your software easy. + + @param {String} name The name of the project + @param {String} version The current project version (will be + appended to the project-name in the package-archive + @param {Function} definition Defines the contents of the package, + and format of the package-archive. Will be executed on the instantiated + PackageTask (i.e., 'this', will be the PackageTask instance), + to set the various instance-propertiess. + + @example + let t = new jake.PackageTask('rous', 'v' + version, function () { + let files = [ + 'Capfile' + , 'Jakefile' + , 'README.md' + , 'package.json' + , 'app/*' + , 'bin/*' + , 'config/*' + , 'lib/*' + , 'node_modules/*' + ]; + this.packageFiles.include(files); + this.packageFiles.exclude('node_modules/foobar'); + this.needTarGz = true; + }); + + */ +let PackageTask = function () { + let args = Array.prototype.slice.call(arguments); + let name = args.shift(); + let version = args.shift(); + let definition = args.pop(); + let prereqs = args.pop() || []; // Optional + + prereqs = [].concat(prereqs); // Accept string or list + + /** + @name jake.PackageTask#name + @public + @type {String} + @description The name of the project + */ + this.name = name; + /** + @name jake.PackageTask#version + @public + @type {String} + @description The project version-string + */ + this.version = version; + /** + @name jake.PackageTask#prereqs + @public + @type {Array} + @description Tasks to run before packaging + */ + this.prereqs = prereqs; + /** + @name jake.PackageTask#packageDir + @public + @type {String='pkg'} + @description The directory-name to use for packaging the software + */ + this.packageDir = 'pkg'; + /** + @name jake.PackageTask#packageFiles + @public + @type {jake.FileList} + @description The list of files and directories to include in the + package-archive + */ + this.packageFiles = new FileList(); + /** + @name jake.PackageTask#needTar + @public + @type {Boolean=false} + @description If set to true, uses the `tar` utility to create + a gzip .tgz archive of the package + */ + this.needTar = false; + /** + @name jake.PackageTask#needTarGz + @public + @type {Boolean=false} + @description If set to true, uses the `tar` utility to create + a gzip .tar.gz archive of the package + */ + this.needTarGz = false; + /** + @name jake.PackageTask#needTarBz2 + @public + @type {Boolean=false} + @description If set to true, uses the `tar` utility to create + a bzip2 .bz2 archive of the package + */ + this.needTarBz2 = false; + /** + @name jake.PackageTask#needJar + @public + @type {Boolean=false} + @description If set to true, uses the `jar` utility to create + a .jar archive of the package + */ + this.needJar = false; + /** + @name jake.PackageTask#needZip + @public + @type {Boolean=false} + @description If set to true, uses the `zip` utility to create + a .zip archive of the package + */ + this.needZip = false; + /** + @name jake.PackageTask#manifestFile + @public + @type {String=null} + @description Can be set to point the `jar` utility at a manifest + file to use in a .jar archive. If unset, one will be automatically + created by the `jar` utility. This path should be relative to the + root of the package directory (this.packageDir above, likely 'pkg') + */ + this.manifestFile = null; + /** + @name jake.PackageTask#tarCommand + @public + @type {String='tar'} + @description The shell-command to use for creating tar archives. + */ + this.tarCommand = 'tar'; + /** + @name jake.PackageTask#jarCommand + @public + @type {String='jar'} + @description The shell-command to use for creating jar archives. + */ + this.jarCommand = 'jar'; + /** + @name jake.PackageTask#zipCommand + @public + @type {String='zip'} + @description The shell-command to use for creating zip archives. + */ + this.zipCommand = 'zip'; + /** + @name jake.PackageTask#archiveNoBaseDir + @public + @type {Boolean=false} + @description Simple option for performing the archive on the + contents of the directory instead of the directory itself + */ + this.archiveNoBaseDir = false; + /** + @name jake.PackageTask#archiveChangeDir + @public + @type {String=null} + @description Equivalent to the '-C' command for the `tar` and `jar` + commands. ("Change to this directory before adding files.") + */ + this.archiveChangeDir = null; + /** + @name jake.PackageTask#archiveContentDir + @public + @type {String=null} + @description Specifies the files and directories to include in the + package-archive. If unset, this will default to the main package + directory -- i.e., name + version. + */ + this.archiveContentDir = null; + + if (typeof definition == 'function') { + definition.call(this); + } + this.define(); +}; + +PackageTask.prototype = new (function () { + + let _compressOpts = { + Tar: { + ext: '.tgz', + flags: 'czf', + cmd: 'tar' + }, + TarGz: { + ext: '.tar.gz', + flags: 'czf', + cmd: 'tar' + }, + TarBz2: { + ext: '.tar.bz2', + flags: 'cjf', + cmd: 'tar' + }, + Jar: { + ext: '.jar', + flags: 'cf', + cmd: 'jar' + }, + Zip: { + ext: '.zip', + flags: 'qr', + cmd: 'zip' + } + }; + + this.define = function () { + let self = this; + let packageDirPath = this.packageDirPath(); + let compressTaskArr = []; + + desc('Build the package for distribution'); + task('package', self.prereqs.concat(['clobberPackage', 'buildPackage'])); + // Backward-compat alias + task('repackage', ['package']); + + task('clobberPackage', function () { + jake.rmRf(self.packageDir, {silent: true}); + }); + + desc('Remove the package'); + task('clobber', ['clobberPackage']); + + let doCommand = function (p) { + let filename = path.resolve(self.packageDir + '/' + self.packageName() + + _compressOpts[p].ext); + if (process.platform == 'win32') { + // Windows full path may have drive letter, which is going to cause + // namespace problems, so strip it. + if (filename.length > 2 && filename[1] == ':') { + filename = filename.substr(2); + } + } + compressTaskArr.push(filename); + + file(filename, [packageDirPath], function () { + let cmd; + let opts = _compressOpts[p]; + // Directory to move to when doing the compression-task + // Changes in the case of zip for emulating -C option + let chdir = self.packageDir; + // Save the current dir so it's possible to pop back up + // after compressing + let currDir = process.cwd(); + let archiveChangeDir; + let archiveContentDir; + + if (self.archiveNoBaseDir) { + archiveChangeDir = self.packageName(); + archiveContentDir = '.'; + } + else { + archiveChangeDir = self.archiveChangeDir; + archiveContentDir = self.archiveContentDir; + } + + cmd = self[opts.cmd + 'Command']; + cmd += ' -' + opts.flags; + if (opts.cmd == 'jar' && self.manifestFile) { + cmd += 'm'; + } + + // The name of the archive to create -- use full path + // so compression can be performed from a different dir + // if needed + cmd += ' ' + filename; + + if (opts.cmd == 'jar' && self.manifestFile) { + cmd += ' ' + self.manifestFile; + } + + // Where to perform the compression -- -C option isn't + // supported in zip, so actually do process.chdir for this + if (archiveChangeDir) { + if (opts.cmd == 'zip') { + chdir = path.join(chdir, archiveChangeDir); + } + else { + cmd += ' -C ' + archiveChangeDir; + } + } + + // Where to get the archive content + if (archiveContentDir) { + cmd += ' ' + archiveContentDir; + } + else { + cmd += ' ' + self.packageName(); + } + + // Move into the desired dir (usually packageDir) to compress + // Return back up to the current dir after the exec + process.chdir(chdir); + + exec(cmd, function (err, stdout, stderr) { + if (err) { throw err; } + + // Return back up to the starting directory (see above, + // before exec) + process.chdir(currDir); + + complete(); + }); + }, {async: true}); + }; + + for (let p in _compressOpts) { + if (this['need' + p]) { + doCommand(p); + } + } + + task('buildPackage', compressTaskArr, function () {}); + + directory(this.packageDir); + + file(packageDirPath, this.packageFiles, function () { + jake.mkdirP(packageDirPath); + let fileList = []; + self.packageFiles.forEach(function (name) { + let f = path.join(self.packageDirPath(), name); + let fDir = path.dirname(f); + jake.mkdirP(fDir, {silent: true}); + + // Add both files and directories + fileList.push({ + from: name, + to: f + }); + }); + let _copyFile = function () { + let file = fileList.pop(); + let stat; + if (file) { + stat = fs.statSync(file.from); + // Target is a directory, just create it + if (stat.isDirectory()) { + jake.mkdirP(file.to, {silent: true}); + _copyFile(); + } + // Otherwise copy the file + else { + jake.cpR(file.from, file.to, {silent: true}); + _copyFile(); + } + } + else { + complete(); + } + }; + _copyFile(); + }, {async: true}); + + + }; + + this.packageName = function () { + if (this.version) { + return this.name + '-' + this.version; + } + else { + return this.name; + } + }; + + this.packageDirPath = function () { + return this.packageDir + '/' + this.packageName(); + }; + +})(); + +jake.PackageTask = PackageTask; +exports.PackageTask = PackageTask; + diff --git a/node_modules/jake/lib/parseargs.js b/node_modules/jake/lib/parseargs.js new file mode 100644 index 0000000..1bd24c9 --- /dev/null +++ b/node_modules/jake/lib/parseargs.js @@ -0,0 +1,134 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let parseargs = {}; +let isOpt = function (arg) { return arg.indexOf('-') === 0 }; +let removeOptPrefix = function (opt) { return opt.replace(/^--/, '').replace(/^-/, '') }; + +/** + * @constructor + * Parses a list of command-line args into a key/value object of + * options and an array of positional commands. + * @ param {Array} opts A list of options in the following format: + * [{full: 'foo', abbr: 'f'}, {full: 'bar', abbr: 'b'}]] + */ +parseargs.Parser = function (opts) { + // A key/value object of matching options parsed out of the args + this.opts = {}; + this.taskNames = null; + this.envVars = null; + + // Data structures used for parsing + this.reg = opts; + this.shortOpts = {}; + this.longOpts = {}; + + let self = this; + [].forEach.call(opts, function (item) { + self.shortOpts[item.abbr] = item; + self.longOpts[item.full] = item; + }); +}; + +parseargs.Parser.prototype = new function () { + + let _trueOrNextVal = function (argParts, args) { + if (argParts[1]) { + return argParts[1]; + } + else { + return (!args[0] || isOpt(args[0])) ? + true : args.shift(); + } + }; + + /** + * Parses an array of arguments into options and positional commands + * @param {Array} args The command-line args to parse + */ + this.parse = function (args) { + let cmds = []; + let cmd; + let envVars = {}; + let opts = {}; + let arg; + let argItem; + let argParts; + let cmdItems; + let taskNames = []; + let preempt; + + while (args.length) { + arg = args.shift(); + + if (isOpt(arg)) { + arg = removeOptPrefix(arg); + argParts = arg.split('='); + argItem = this.longOpts[argParts[0]] || this.shortOpts[argParts[0]]; + if (argItem) { + // First-encountered preemptive opt takes precedence -- no further opts + // or possibility of ambiguity, so just look for a value, or set to + // true and then bail + if (argItem.preempts) { + opts[argItem.full] = _trueOrNextVal(argParts, args); + preempt = true; + break; + } + // If the opt requires a value, see if we can get a value from the + // next arg, or infer true from no-arg -- if it's followed by another + // opt, throw an error + if (argItem.expectValue || argItem.allowValue) { + opts[argItem.full] = _trueOrNextVal(argParts, args); + if (argItem.expectValue && !opts[argItem.full]) { + throw new Error(argItem.full + ' option expects a value.'); + } + } + else { + opts[argItem.full] = true; + } + } + } + else { + cmds.unshift(arg); + } + } + + if (!preempt) { + // Parse out any env-vars and task-name + while ((cmd = cmds.pop())) { + cmdItems = cmd.split('='); + if (cmdItems.length > 1) { + envVars[cmdItems[0]] = cmdItems[1]; + } + else { + taskNames.push(cmd); + } + } + + } + + return { + opts: opts, + envVars: envVars, + taskNames: taskNames + }; + }; + +}; + +module.exports = parseargs; diff --git a/node_modules/jake/lib/program.js b/node_modules/jake/lib/program.js new file mode 100644 index 0000000..121632f --- /dev/null +++ b/node_modules/jake/lib/program.js @@ -0,0 +1,282 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let fs = require('fs'); +let parseargs = require('./parseargs'); +let utils = require('./utils'); +let Program; +let usage = require('fs').readFileSync(`${__dirname}/../usage.txt`).toString(); +let { Task } = require('./task/task'); + +function die(msg) { + console.log(msg); + process.stdout.write('', function () { + process.stderr.write('', function () { + process.exit(); + }); + }); +} + +let preempts = { + version: function () { + die(jake.version); + }, + help: function () { + die(usage); + } +}; + +let AVAILABLE_OPTS = [ + { full: 'jakefile', + abbr: 'f', + expectValue: true + }, + { full: 'quiet', + abbr: 'q', + expectValue: false + }, + { full: 'directory', + abbr: 'C', + expectValue: true + }, + { full: 'always-make', + abbr: 'B', + expectValue: false + }, + { full: 'tasks', + abbr: 'T', + expectValue: false, + allowValue: true + }, + // Alias t + { full: 'tasks', + abbr: 't', + expectValue: false, + allowValue: true + }, + // Alias ls + { full: 'tasks', + abbr: 'ls', + expectValue: false, + allowValue: true + }, + { full: 'help', + abbr: 'h', + }, + { full: 'version', + abbr: 'V', + }, + // Alias lowercase v + { full: 'version', + abbr: 'v', + }, + { full: 'jakelibdir', + abbr: 'J', + expectValue: true + }, + { full: 'allow-rejection', + abbr: 'ar', + expectValue: false + } +]; + +Program = function () { + this.availableOpts = AVAILABLE_OPTS; + this.opts = {}; + this.taskNames = null; + this.taskArgs = null; + this.envVars = null; + this.die = die; +}; + +Program.prototype = new (function () { + + this.handleErr = function (err) { + if (jake.listeners('error').length !== 0) { + jake.emit('error', err); + return; + } + + if (jake.listeners('error').length) { + jake.emit('error', err); + return; + } + + utils.logger.error('jake aborted.'); + if (err.stack) { + utils.logger.error(err.stack); + } + else { + utils.logger.error(err.message); + } + + process.stdout.write('', function () { + process.stderr.write('', function () { + jake.errorCode = jake.errorCode || 1; + process.exit(jake.errorCode); + }); + }); + }; + + this.parseArgs = function (args) { + let result = (new parseargs.Parser(this.availableOpts)).parse(args); + this.setOpts(result.opts); + this.setTaskNames(result.taskNames); + this.setEnvVars(result.envVars); + }; + + this.setOpts = function (options) { + let opts = options || {}; + Object.assign(this.opts, opts); + }; + + this.internalOpts = function (options) { + this.availableOpts = this.availableOpts.concat(options); + }; + + this.autocompletions = function (cur) { + let p; let i; let task; + let commonPrefix = ''; + let matches = []; + + for (p in jake.Task) { + task = jake.Task[p]; + if ( + 'fullName' in task + && ( + // if empty string, program converts to true + cur === true || + task.fullName.indexOf(cur) === 0 + ) + ) { + if (matches.length === 0) { + commonPrefix = task.fullName; + } + else { + for (i = commonPrefix.length; i > -1; --i) { + commonPrefix = commonPrefix.substr(0, i); + if (task.fullName.indexOf(commonPrefix) === 0) { + break; + } + } + } + matches.push(task.fullName); + } + } + + if (matches.length > 1 && commonPrefix === cur) { + matches.unshift('yes-space'); + } + else { + matches.unshift('no-space'); + } + + process.stdout.write(matches.join(' ')); + }; + + this.setTaskNames = function (names) { + if (names && !Array.isArray(names)) { + throw new Error('Task names must be an array'); + } + this.taskNames = (names && names.length) ? names : ['default']; + }; + + this.setEnvVars = function (vars) { + this.envVars = vars || null; + }; + + this.firstPreemptiveOption = function () { + let opts = this.opts; + for (let p in opts) { + if (preempts[p]) { + return preempts[p]; + } + } + return false; + }; + + this.init = function (configuration) { + let self = this; + let config = configuration || {}; + if (config.options) { + this.setOpts(config.options); + } + if (config.taskNames) { + this.setTaskNames(config.taskNames); + } + if (config.envVars) { + this.setEnvVars(config.envVars); + } + process.addListener('uncaughtException', function (err) { + self.handleErr(err); + }); + if (!this.opts['allow-rejection']) { + process.addListener('unhandledRejection', (reason, promise) => { + utils.logger.error('Unhandled rejection at:', promise, 'reason:', reason); + self.handleErr(reason); + }); + } + if (this.envVars) { + Object.assign(process.env, this.envVars); + } + }; + + this.run = function () { + let rootTask; + let taskNames; + let dirname; + let opts = this.opts; + + if (opts.autocomplete) { + return this.autocompletions(opts['autocomplete-cur'], opts['autocomplete-prev']); + } + // Run with `jake -T`, just show descriptions + if (opts.tasks) { + return jake.showAllTaskDescriptions(opts.tasks); + } + + taskNames = this.taskNames; + if (!(Array.isArray(taskNames) && taskNames.length)) { + throw new Error('Please pass jake.runTasks an array of task-names'); + } + + // Set working dir + dirname = opts.directory; + if (dirname) { + if (fs.existsSync(dirname) && + fs.statSync(dirname).isDirectory()) { + process.chdir(dirname); + } + else { + throw new Error(dirname + ' is not a valid directory path'); + } + } + + rootTask = task(Task.ROOT_TASK_NAME, taskNames, function () {}); + rootTask._internal = true; + + rootTask.once('complete', function () { + jake.emit('complete'); + }); + jake.emit('start'); + rootTask.invoke(); + }; + +})(); + +module.exports.Program = Program; diff --git a/node_modules/jake/lib/publish_task.js b/node_modules/jake/lib/publish_task.js new file mode 100644 index 0000000..f0cacfd --- /dev/null +++ b/node_modules/jake/lib/publish_task.js @@ -0,0 +1,290 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let fs = require('fs'); +let path = require('path'); +let exec = require('child_process').execSync; +let FileList = require('filelist').FileList; + +let PublishTask = function () { + let args = Array.prototype.slice.call(arguments).filter(function (item) { + return typeof item != 'undefined'; + }); + let arg; + let opts = {}; + let definition; + let prereqs = []; + let createDef = function (arg) { + return function () { + this.packageFiles.include(arg); + }; + }; + + this.name = args.shift(); + + // Old API, just name + list of files + if (args.length == 1 && (Array.isArray(args[0]) || typeof args[0] == 'string')) { + definition = createDef(args.pop()); + } + // Current API, name + [prereqs] + [opts] + definition + else { + while ((arg = args.pop())) { + // Definition func + if (typeof arg == 'function') { + definition = arg; + } + // Prereqs + else if (Array.isArray(arg) || typeof arg == 'string') { + prereqs = arg; + } + // Opts + else { + opts = arg; + } + } + } + + this.prereqs = prereqs; + this.packageFiles = new FileList(); + this.publishCmd = opts.publishCmd || 'npm publish %filename'; + this.publishMessage = opts.publishMessage || 'BOOM! Published.'; + this.gitCmd = opts.gitCmd || 'git'; + this.versionFiles = opts.versionFiles || ['package.json']; + this.scheduleDelay = 5000; + + // Override utility funcs for testing + this._ensureRepoClean = function (stdout) { + if (stdout.length) { + fail(new Error('Git repository is not clean.')); + } + }; + this._getCurrentBranch = function (stdout) { + return String(stdout).trim(); + }; + + if (typeof definition == 'function') { + definition.call(this); + } + this.define(); +}; + + +PublishTask.prototype = new (function () { + + let _currentBranch = null; + + let getPackage = function () { + let pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), + '/package.json')).toString()); + return pkg; + }; + let getPackageVersionNumber = function () { + return getPackage().version; + }; + + this.define = function () { + let self = this; + + namespace('publish', function () { + task('fetchTags', function () { + // Make sure local tags are up to date + exec(self.gitCmd + ' fetch --tags'); + console.log('Fetched remote tags.'); + }); + + task('getCurrentBranch', function () { + // Figure out what branch to push to + let stdout = exec(self.gitCmd + ' symbolic-ref --short HEAD').toString(); + if (!stdout) { + throw new Error('No current Git branch found'); + } + _currentBranch = self._getCurrentBranch(stdout); + console.log('On branch ' + _currentBranch); + }); + + task('ensureClean', function () { + // Only bump, push, and tag if the Git repo is clean + let stdout = exec(self.gitCmd + ' status --porcelain --untracked-files=no').toString(); + // Throw if there's output + self._ensureRepoClean(stdout); + }); + + task('updateVersionFiles', function () { + let pkg; + let version; + let arr; + let patch; + + // Grab the current version-string + pkg = getPackage(); + version = pkg.version; + // Increment the patch-number for the version + arr = version.split('.'); + patch = parseInt(arr.pop(), 10) + 1; + arr.push(patch); + version = arr.join('.'); + + // Update package.json or other files with the new version-info + self.versionFiles.forEach(function (file) { + let p = path.join(process.cwd(), file); + let data = JSON.parse(fs.readFileSync(p).toString()); + data.version = version; + fs.writeFileSync(p, JSON.stringify(data, true, 2) + '\n'); + }); + // Return the version string so that listeners for the 'complete' event + // for this task can use it (e.g., to update other files before pushing + // to Git) + return version; + }); + + task('pushVersion', ['ensureClean', 'updateVersionFiles'], function () { + let version = getPackageVersionNumber(); + let message = 'Version ' + version; + let cmds = [ + self.gitCmd + ' commit -a -m "' + message + '"', + self.gitCmd + ' push origin ' + _currentBranch, + self.gitCmd + ' tag -a v' + version + ' -m "' + message + '"', + self.gitCmd + ' push --tags' + ]; + cmds.forEach((cmd) => { + exec(cmd); + }); + version = getPackageVersionNumber(); + console.log('Bumped version number to v' + version + '.'); + }); + + let defineTask = task('definePackage', function () { + let version = getPackageVersionNumber(); + new jake.PackageTask(self.name, 'v' + version, self.prereqs, function () { + // Replace the PackageTask's FileList with the PublishTask's FileList + this.packageFiles = self.packageFiles; + this.needTarGz = true; // Default to tar.gz + // If any of the need or archive opts are set + // proxy them to the PackageTask + for (let p in this) { + if (p.indexOf('need') === 0 || p.indexOf('archive') === 0) { + if (typeof self[p] != 'undefined') { + this[p] = self[p]; + } + } + } + }); + }); + defineTask._internal = true; + + task('package', function () { + let definePack = jake.Task['publish:definePackage']; + let pack = jake.Task['package']; + let version = getPackageVersionNumber(); + + // May have already been run + if (definePack.taskStatus == jake.Task.runStatuses.DONE) { + definePack.reenable(true); + } + definePack.invoke(); + // Set manually, completion happens in next tick, creating deadlock + definePack.taskStatus = jake.Task.runStatuses.DONE; + pack.invoke(); + console.log('Created package for ' + self.name + ' v' + version); + }); + + task('publish', function () { + return new Promise((resolve) => { + let version = getPackageVersionNumber(); + let filename; + let cmd; + + console.log('Publishing ' + self.name + ' v' + version); + + if (typeof self.createPublishCommand == 'function') { + cmd = self.createPublishCommand(version); + } + else { + filename = './pkg/' + self.name + '-v' + version + '.tar.gz'; + cmd = self.publishCmd.replace(/%filename/gi, filename); + } + + if (typeof cmd == 'function') { + cmd(function (err) { + if (err) { + throw err; + } + console.log(self.publishMessage); + resolve(); + }); + } + else { + // Hackity hack -- NPM publish sometimes returns errror like: + // Error sending version data\nnpm ERR! + // Error: forbidden 0.2.4 is modified, should match modified time + setTimeout(function () { + let stdout = exec(cmd).toString() || ''; + stdout = stdout.trim(); + if (stdout) { + console.log(stdout); + } + console.log(self.publishMessage); + resolve(); + }, self.scheduleDelay); + } + }); + }); + + task('cleanup', function () { + return new Promise((resolve) => { + let clobber = jake.Task.clobber; + clobber.reenable(true); + clobber.on('complete', function () { + console.log('Cleaned up package'); + resolve(); + }); + clobber.invoke(); + }); + }); + + }); + + let prefixNs = function (item) { + return 'publish:' + item; + }; + + // Create aliases in the default namespace + desc('Create a new version and release.'); + task('publish', self.prereqs.concat(['version', 'release'] + .map(prefixNs))); + + desc('Release the existing version.'); + task('publishExisting', self.prereqs.concat(['release'] + .map(prefixNs))); + + task('version', ['fetchTags', 'getCurrentBranch', 'pushVersion'] + .map(prefixNs)); + + task('release', ['package', 'publish', 'cleanup'] + .map(prefixNs)); + + // Invoke proactively so there will be a callable 'package' task + // which can be used apart from 'publish' + jake.Task['publish:definePackage'].invoke(); + }; + +})(); + +jake.PublishTask = PublishTask; +exports.PublishTask = PublishTask; + diff --git a/node_modules/jake/lib/rule.js b/node_modules/jake/lib/rule.js new file mode 100644 index 0000000..25f51ae --- /dev/null +++ b/node_modules/jake/lib/rule.js @@ -0,0 +1,311 @@ +let path = require('path'); +let fs = require('fs'); +let Task = require('./task/task').Task; + +// Split a task to two parts, name space and task name. +// For example, given 'foo:bin/a%.c', return an object with +// - 'ns' : foo +// - 'name' : bin/a%.c +function splitNs(task) { + let parts = task.split(':'); + let name = parts.pop(); + let ns = resolveNs(parts); + return { + 'name' : name, + 'ns' : ns + }; +} + +// Return the namespace based on an array of names. +// For example, given ['foo', 'baz' ], return the namespace +// +// default -> foo -> baz +// +// where default is the global root namespace +// and -> means child namespace. +function resolveNs(parts) { + let ns = jake.defaultNamespace; + for(let i = 0, l = parts.length; ns && i < l; i++) { + ns = ns.childNamespaces[parts[i]]; + } + return ns; +} + +// Given a pattern p, say 'foo:bin/a%.c' +// Return an object with +// - 'ns' : foo +// - 'dir' : bin +// - 'prefix' : a +// - 'suffix' : .c +function resolve(p) { + let task = splitNs(p); + let name = task.name; + let ns = task.ns; + let split = path.basename(name).split('%'); + return { + ns: ns, + dir: path.dirname(name), + prefix: split[0], + suffix: split[1] + }; +} + +// Test whether string a is a suffix of string b +function stringEndWith(a, b) { + let l; + return (l = b.lastIndexOf(a)) == -1 ? false : l + a.length == b.length; +} + +// Replace the suffix a of the string s with b. +// Note that, it is assumed a is a suffix of s. +function stringReplaceSuffix(s, a, b) { + return s.slice(0, s.lastIndexOf(a)) + b; +} + +class Rule { + constructor(opts) { + this.pattern = opts.pattern; + this.source = opts.source; + this.prereqs = opts.prereqs; + this.action = opts.action; + this.opts = opts.opts; + this.desc = opts.desc; + this.ns = opts.ns; + } + + // Create a file task based on this rule for the specified + // task-name + // ====== + // FIXME: Right now this just throws away any passed-in args + // for the synthsized task (taskArgs param) + // ====== + createTask(fullName, level) { + let self = this; + let pattern; + let source; + let action; + let opts; + let prereqs; + let valid; + let src; + let tNs; + let createdTask; + let name = Task.getBaseTaskName(fullName); + let nsPath = Task.getBaseNamespacePath(fullName); + let ns = this.ns.resolveNamespace(nsPath); + + pattern = this.pattern; + source = this.source; + + if (typeof source == 'string') { + src = Rule.getSource(name, pattern, source); + } + else { + src = source(name); + } + + // TODO: Write a utility function that appends a + // taskname to a namespace path + src = nsPath.split(':').filter(function (item) { + return !!item; + }).concat(src).join(':'); + + // Generate the prerequisite for the matching task. + // It is the original prerequisites plus the prerequisite + // representing source file, i.e., + // + // rule( '%.o', '%.c', ['some.h'] ... + // + // If the objective is main.o, then new task should be + // + // file( 'main.o', ['main.c', 'some.h' ] ... + prereqs = this.prereqs.slice(); // Get a copy to work with + prereqs.unshift(src); + + // Prereq should be: + // 1. an existing task + // 2. an existing file on disk + // 3. a valid rule (i.e., not at too deep a level) + valid = prereqs.some(function (p) { + let ns = self.ns; + return ns.resolveTask(p) || + fs.existsSync(Task.getBaseTaskName(p)) || + jake.attemptRule(p, ns, level + 1); + }); + + // If any of the prereqs aren't valid, the rule isn't valid + if (!valid) { + return null; + } + // Otherwise, hunky-dory, finish creating the task for the rule + else { + // Create the action for the task + action = function () { + let task = this; + self.action.apply(task); + }; + + opts = this.opts; + + // Insert the file task into Jake + // + // Since createTask function stores the task as a child task + // of currentNamespace. Here we temporariliy switch the namespace. + // FIXME: Should allow optional ns passed in instead of this hack + tNs = jake.currentNamespace; + jake.currentNamespace = ns; + createdTask = jake.createTask('file', name, prereqs, action, opts); + createdTask.source = src.split(':').pop(); + jake.currentNamespace = tNs; + + return createdTask; + } + } + + match(name) { + return Rule.match(this.pattern, name); + } + + // Test wether the a prerequisite matchs the pattern. + // The arg 'pattern' does not have namespace as prefix. + // For example, the following tests are true + // + // pattern | name + // bin/%.o | bin/main.o + // bin/%.o | foo:bin/main.o + // + // The following tests are false (trivally) + // + // pattern | name + // bin/%.o | foobin/main.o + // bin/%.o | bin/main.oo + static match(pattern, name) { + let p; + let task; + let obj; + let filename; + + if (pattern instanceof RegExp) { + return pattern.test(name); + } + else if (pattern.indexOf('%') == -1) { + // No Pattern. No Folder. No Namespace. + // A Simple Suffix Rule. Just test suffix + return stringEndWith(pattern, name); + } + else { + // Resolve the dir, prefix and suffix of pattern + p = resolve(pattern); + + // Resolve the namespace and task-name + task = splitNs(name); + name = task.name; + + // Set the objective as the task-name + obj = name; + + // Namespace is already matched. + + // Check dir + if (path.dirname(obj) != p.dir) { + return false; + } + + filename = path.basename(obj); + + // Check file name length + if ((p.prefix.length + p.suffix.length + 1) > filename.length) { + // Length does not match. + return false; + } + + // Check prefix + if (filename.indexOf(p.prefix) !== 0) { + return false; + } + + // Check suffix + if (!stringEndWith(p.suffix, filename)) { + return false; + } + + // OK. Find a match. + return true; + } + } + + // Generate the source based on + // - name name for the synthesized task + // - pattern pattern for the objective + // - source pattern for the source + // + // Return the source with properties + // - dep the prerequisite of source + // (with the namespace) + // + // - file the file name of source + // (without the namespace) + // + // For example, given + // + // - name foo:bin/main.o + // - pattern bin/%.o + // - source src/%.c + // + // return 'foo:src/main.c', + // + static getSource(name, pattern, source) { + let dep; + let pat; + let match; + let file; + let src; + + // Regex pattern -- use to look up the extension + if (pattern instanceof RegExp) { + match = pattern.exec(name); + if (match) { + if (typeof source == 'function') { + src = source(name); + } + else { + src = stringReplaceSuffix(name, match[0], source); + } + } + } + // Assume string + else { + // Simple string suffix replacement + if (pattern.indexOf('%') == -1) { + if (typeof source == 'function') { + src = source(name); + } + else { + src = stringReplaceSuffix(name, pattern, source); + } + } + // Percent-based substitution + else { + pat = pattern.replace('%', '(.*?)'); + pat = new RegExp(pat); + match = pat.exec(name); + if (match) { + if (typeof source == 'function') { + src = source(name); + } + else { + file = match[1]; + file = source.replace('%', file); + dep = match[0]; + src = name.replace(dep, file); + } + } + } + } + + return src; + } +} + + +exports.Rule = Rule; diff --git a/node_modules/jake/lib/task/directory_task.js b/node_modules/jake/lib/task/directory_task.js new file mode 100644 index 0000000..b17b624 --- /dev/null +++ b/node_modules/jake/lib/task/directory_task.js @@ -0,0 +1,30 @@ +let fs = require('fs'); +let FileTask = require('./file_task').FileTask; + +/** + @name jake + @namespace jake +*/ +/** + @name jake.DirectoryTask + @constructor + @augments EventEmitter + @augments jake.Task + @augments jake.FileTask + @description A Jake DirectoryTask + + @param {String} name The name of the directory to create. + */ +class DirectoryTask extends FileTask { + constructor(...args) { + super(...args); + if (fs.existsSync(this.name)) { + this.updateModTime(); + } + else { + this.modTime = null; + } + } +} + +exports.DirectoryTask = DirectoryTask; diff --git a/node_modules/jake/lib/task/file_task.js b/node_modules/jake/lib/task/file_task.js new file mode 100644 index 0000000..6fad84b --- /dev/null +++ b/node_modules/jake/lib/task/file_task.js @@ -0,0 +1,124 @@ +let fs = require('fs'); +let Task = require('./task').Task; + +function isFileOrDirectory(t) { + return (t instanceof FileTask || + t instanceof DirectoryTask); +} + +function isFile(t) { + return (t instanceof FileTask && !(t instanceof DirectoryTask)); +} + +/** + @name jake + @namespace jake +*/ +/** + @name jake.FileTask + @class` + @extentds Task + @description A Jake FileTask + + @param {String} name The name of the Task + @param {Array} [prereqs] Prerequisites to be run before this task + @param {Function} [action] The action to perform to create this file + @param {Object} [opts] + @param {Array} [opts.asyc=false] Perform this task asynchronously. + If you flag a task with this option, you must call the global + `complete` method inside the task's action, for execution to proceed + to the next task. + */ +class FileTask extends Task { + constructor(...args) { + super(...args); + this.dummy = false; + if (fs.existsSync(this.name)) { + this.updateModTime(); + } + else { + this.modTime = null; + } + } + + isNeeded() { + let prereqs = this.prereqs; + let prereqName; + let prereqTask; + + // No repeatsies + if (this.taskStatus == Task.runStatuses.DONE) { + return false; + } + // The always-make override + else if (jake.program.opts['always-make']) { + return true; + } + // Default case + else { + + // We need either an existing file, or an action to create one. + // First try grabbing the actual mod-time of the file + try { + this.updateModTime(); + } + // Then fall back to looking for an action + catch(e) { + if (typeof this.action == 'function') { + return true; + } + else { + throw new Error('File-task ' + this.fullName + ' has no ' + + 'existing file, and no action to create one.'); + } + } + + // Compare mod-time of all the prereqs with its mod-time + // If any prereqs are newer, need to run the action to update + if (prereqs && prereqs.length) { + for (let i = 0, ii = prereqs.length; i < ii; i++) { + prereqName = prereqs[i]; + prereqTask = this.namespace.resolveTask(prereqName) || + jake.createPlaceholderFileTask(prereqName, this.namespace); + // Run the action if: + // 1. The prereq is a normal task (not file/dir) + // 2. The prereq is a file-task with a mod-date more recent than + // the one for this file/dir + if (prereqTask) { + if (!isFileOrDirectory(prereqTask) || + (isFile(prereqTask) && prereqTask.modTime > this.modTime)) { + return true; + } + } + } + } + // File/dir has no prereqs, and exists -- no need to run + else { + // Effectively done + this.taskStatus = Task.runStatuses.DONE; + return false; + } + } + } + + updateModTime() { + let stats = fs.statSync(this.name); + this.modTime = stats.mtime; + } + + complete() { + if (!this.dummy) { + this.updateModTime(); + } + // Hackity hack + Task.prototype.complete.apply(this, arguments); + } + +} + +exports.FileTask = FileTask; + +// DirectoryTask is a subclass of FileTask, depends on it +// being defined +let DirectoryTask = require('./directory_task').DirectoryTask; + diff --git a/node_modules/jake/lib/task/index.js b/node_modules/jake/lib/task/index.js new file mode 100644 index 0000000..bc93f41 --- /dev/null +++ b/node_modules/jake/lib/task/index.js @@ -0,0 +1,9 @@ + +let Task = require('./task').Task; +let FileTask = require('./file_task').FileTask; +let DirectoryTask = require('./directory_task').DirectoryTask; + +exports.Task = Task; +exports.FileTask = FileTask; +exports.DirectoryTask = DirectoryTask; + diff --git a/node_modules/jake/lib/task/task.js b/node_modules/jake/lib/task/task.js new file mode 100644 index 0000000..9e8886f --- /dev/null +++ b/node_modules/jake/lib/task/task.js @@ -0,0 +1,439 @@ +let EventEmitter = require('events').EventEmitter; +let async = require('async'); +let chalk = require('chalk'); +// 'rule' module is required at the bottom because circular deps + +// Used for task value, so better not to use +// null, since value should be unset/uninitialized +let UNDEFINED_VALUE; + +const ROOT_TASK_NAME = '__rootTask__'; +const POLLING_INTERVAL = 100; + +// Parse any positional args attached to the task-name +function parsePrereqName(name) { + let taskArr = name.split('['); + let taskName = taskArr[0]; + let taskArgs = []; + if (taskArr[1]) { + taskArgs = taskArr[1].replace(/\]$/, ''); + taskArgs = taskArgs.split(','); + } + return { + name: taskName, + args: taskArgs + }; +} + +/** + @name jake.Task + @class + @extends EventEmitter + @description A Jake Task + + @param {String} name The name of the Task + @param {Array} [prereqs] Prerequisites to be run before this task + @param {Function} [action] The action to perform for this task + @param {Object} [opts] + @param {Array} [opts.asyc=false] Perform this task asynchronously. + If you flag a task with this option, you must call the global + `complete` method inside the task's action, for execution to proceed + to the next task. + */ +class Task extends EventEmitter { + + constructor(name, prereqs, action, options) { + // EventEmitter ctor takes no args + super(); + + if (name.indexOf(':') > -1) { + throw new Error('Task name cannot include a colon. It is used internally as namespace delimiter.'); + } + let opts = options || {}; + + this._currentPrereqIndex = 0; + this._internal = false; + this._skipped = false; + + this.name = name; + this.prereqs = prereqs; + this.action = action; + this.async = false; + this.taskStatus = Task.runStatuses.UNSTARTED; + this.description = null; + this.args = []; + this.value = UNDEFINED_VALUE; + this.concurrency = 1; + this.startTime = null; + this.endTime = null; + this.directory = null; + this.namespace = null; + + // Support legacy async-flag -- if not explicitly passed or falsy, will + // be set to empty-object + if (typeof opts == 'boolean' && opts === true) { + this.async = true; + } + else { + if (opts.async) { + this.async = true; + } + if (opts.concurrency) { + this.concurrency = opts.concurrency; + } + } + + //Do a test on self dependencies for this task + if(Array.isArray(this.prereqs) && this.prereqs.indexOf(this.name) !== -1) { + throw new Error("Cannot use prereq " + this.name + " as a dependency of itself"); + } + } + + get fullName() { + return this._getFullName(); + } + + _initInvocationChain() { + // Legacy global invocation chain + jake._invocationChain.push(this); + + // New root chain + if (!this._invocationChain) { + this._invocationChainRoot = true; + this._invocationChain = []; + if (jake.currentRunningTask) { + jake.currentRunningTask._waitForChains = jake.currentRunningTask._waitForChains || []; + jake.currentRunningTask._waitForChains.push(this._invocationChain); + } + } + } + + /** + @name jake.Task#invoke + @function + @description Runs prerequisites, then this task. If the task has already + been run, will not run the task again. + */ + invoke() { + this._initInvocationChain(); + + this.args = Array.prototype.slice.call(arguments); + this.reenabled = false + this.runPrereqs(); + } + + /** + @name jake.Task#execute + @function + @description Run only this task, without prereqs. If the task has already + been run, *will* run the task again. + */ + execute() { + this._initInvocationChain(); + + this.args = Array.prototype.slice.call(arguments); + this.reenable(); + this.reenabled = true + this.run(); + } + + runPrereqs() { + if (this.prereqs && this.prereqs.length) { + + if (this.concurrency > 1) { + async.eachLimit(this.prereqs, this.concurrency, + + (name, cb) => { + let parsed = parsePrereqName(name); + + let prereq = this.namespace.resolveTask(parsed.name) || + jake.attemptRule(name, this.namespace, 0) || + jake.createPlaceholderFileTask(name, this.namespace); + + if (!prereq) { + throw new Error('Unknown task "' + name + '"'); + } + + //Test for circular invocation + if(prereq === this) { + setImmediate(function () { + cb(new Error("Cannot use prereq " + prereq.name + " as a dependency of itself")); + }); + } + + if (prereq.taskStatus == Task.runStatuses.DONE) { + //prereq already done, return + setImmediate(cb); + } + else { + //wait for complete before calling cb + prereq.once('_done', () => { + prereq.removeAllListeners('_done'); + setImmediate(cb); + }); + // Start the prereq if we are the first to encounter it + if (prereq.taskStatus === Task.runStatuses.UNSTARTED) { + prereq.taskStatus = Task.runStatuses.STARTED; + prereq.invoke.apply(prereq, parsed.args); + } + } + }, + + (err) => { + //async callback is called after all prereqs have run. + if (err) { + throw err; + } + else { + setImmediate(this.run.bind(this)); + } + } + ); + } + else { + setImmediate(this.nextPrereq.bind(this)); + } + } + else { + setImmediate(this.run.bind(this)); + } + } + + nextPrereq() { + let self = this; + let index = this._currentPrereqIndex; + let name = this.prereqs[index]; + let prereq; + let parsed; + + if (name) { + + parsed = parsePrereqName(name); + + prereq = this.namespace.resolveTask(parsed.name) || + jake.attemptRule(name, this.namespace, 0) || + jake.createPlaceholderFileTask(name, this.namespace); + + if (!prereq) { + throw new Error('Unknown task "' + name + '"'); + } + + // Do when done + if (prereq.taskStatus == Task.runStatuses.DONE) { + self.handlePrereqDone(prereq); + } + else { + prereq.once('_done', () => { + this.handlePrereqDone(prereq); + prereq.removeAllListeners('_done'); + }); + if (prereq.taskStatus == Task.runStatuses.UNSTARTED) { + prereq.taskStatus = Task.runStatuses.STARTED; + prereq._invocationChain = this._invocationChain; + prereq.invoke.apply(prereq, parsed.args); + } + } + } + } + + /** + @name jake.Task#reenable + @function + @description Reenables a task so that it can be run again. + */ + reenable(deep) { + let prereqs; + let prereq; + this._skipped = false; + this.taskStatus = Task.runStatuses.UNSTARTED; + this.value = UNDEFINED_VALUE; + if (deep && this.prereqs) { + prereqs = this.prereqs; + for (let i = 0, ii = prereqs.length; i < ii; i++) { + prereq = jake.Task[prereqs[i]]; + if (prereq) { + prereq.reenable(deep); + } + } + } + } + + handlePrereqDone(prereq) { + this._currentPrereqIndex++; + if (this._currentPrereqIndex < this.prereqs.length) { + setImmediate(this.nextPrereq.bind(this)); + } + else { + setImmediate(this.run.bind(this)); + } + } + + isNeeded() { + let needed = true; + if (this.taskStatus == Task.runStatuses.DONE) { + needed = false; + } + return needed; + } + + run() { + let val, previous; + let hasAction = typeof this.action == 'function'; + + if (!this.isNeeded()) { + this.emit('skip'); + this.emit('_done'); + } + else { + if (this._invocationChain.length) { + previous = this._invocationChain[this._invocationChain.length - 1]; + // If this task is repeating and its previous is equal to this, don't check its status because it was set to UNSTARTED by the reenable() method + if (!(this.reenabled && previous == this)) { + if (previous.taskStatus != Task.runStatuses.DONE) { + let now = (new Date()).getTime(); + if (now - this.startTime > jake._taskTimeout) { + return jake.fail(`Timed out waiting for task: ${previous.name} with status of ${previous.taskStatus}`); + } + setTimeout(this.run.bind(this), POLLING_INTERVAL); + return; + } + } + } + if (!(this.reenabled && previous == this)) { + this._invocationChain.push(this); + } + + if (!(this._internal || jake.program.opts.quiet)) { + console.log("Starting '" + chalk.green(this.fullName) + "'..."); + } + + this.startTime = (new Date()).getTime(); + this.emit('start'); + + jake.currentRunningTask = this; + + if (hasAction) { + try { + if (this.directory) { + process.chdir(this.directory); + } + + val = this.action.apply(this, this.args); + + if (typeof val == 'object' && typeof val.then == 'function') { + this.async = true; + + val.then( + (result) => { + setImmediate(() => { + this.complete(result); + }); + }, + (err) => { + setImmediate(() => { + this.errorOut(err); + }); + }); + } + } + catch (err) { + this.errorOut(err); + return; // Bail out, not complete + } + } + + if (!(hasAction && this.async)) { + setImmediate(() => { + this.complete(val); + }); + } + } + } + + errorOut(err) { + this.taskStatus = Task.runStatuses.ERROR; + this._invocationChain.chainStatus = Task.runStatuses.ERROR; + this.emit('error', err); + } + + complete(val) { + + if (Array.isArray(this._waitForChains)) { + let stillWaiting = this._waitForChains.some((chain) => { + return !(chain.chainStatus == Task.runStatuses.DONE || + chain.chainStatus == Task.runStatuses.ERROR); + }); + if (stillWaiting) { + let now = (new Date()).getTime(); + let elapsed = now - this.startTime; + if (elapsed > jake._taskTimeout) { + return jake.fail(`Timed out waiting for task: ${this.name} with status of ${this.taskStatus}. Elapsed: ${elapsed}`); + } + setTimeout(() => { + this.complete(val); + }, POLLING_INTERVAL); + return; + } + } + + jake._invocationChain.splice(jake._invocationChain.indexOf(this), 1); + + if (this._invocationChainRoot) { + this._invocationChain.chainStatus = Task.runStatuses.DONE; + } + + this._currentPrereqIndex = 0; + + // If 'complete' getting called because task has been + // run already, value will not be passed -- leave in place + if (!this._skipped) { + this.taskStatus = Task.runStatuses.DONE; + this.value = val; + + this.emit('complete', this.value); + this.emit('_done'); + + this.endTime = (new Date()).getTime(); + let taskTime = this.endTime - this.startTime; + + if (!(this._internal || jake.program.opts.quiet)) { + console.log("Finished '" + chalk.green(this.fullName) + "' after " + chalk.magenta(taskTime + ' ms')); + } + + } + } + + _getFullName() { + let ns = this.namespace; + let path = (ns && ns.path) || ''; + path = (path && path.split(':')) || []; + if (this.namespace !== jake.defaultNamespace) { + path.push(this.namespace.name); + } + path.push(this.name); + return path.join(':'); + } + + static getBaseNamespacePath(fullName) { + return fullName.split(':').slice(0, -1).join(':'); + } + + static getBaseTaskName(fullName) { + return fullName.split(':').pop(); + } +} + +Task.runStatuses = { + UNSTARTED: 'unstarted', + DONE: 'done', + STARTED: 'started', + ERROR: 'error' +}; + +Task.ROOT_TASK_NAME = ROOT_TASK_NAME; + +exports.Task = Task; + +// Required here because circular deps +require('../rule'); + diff --git a/node_modules/jake/lib/test_task.js b/node_modules/jake/lib/test_task.js new file mode 100644 index 0000000..6482bf1 --- /dev/null +++ b/node_modules/jake/lib/test_task.js @@ -0,0 +1,270 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let path = require('path'); +let currDir = process.cwd(); + +/** + @name jake + @namespace jake +*/ +/** + @name jake.TestTask + @constructor + @description Instantiating a TestTask creates a number of Jake + Tasks that make running tests for your software easy. + + @param {String} name The name of the project + @param {Function} definition Defines the list of files containing the tests, + and the name of the namespace/task for running them. Will be executed on the + instantiated TestTask (i.e., 'this', will be the TestTask instance), to set + the various instance-propertiess. + + @example + let t = new jake.TestTask('bij-js', function () { + this.testName = 'testSpecial'; + this.testFiles.include('test/**'); + }); + + */ +let TestTask = function () { + let self = this; + let args = Array.prototype.slice.call(arguments); + let name = args.shift(); + let definition = args.pop(); + let prereqs = args.pop() || []; + + /** + @name jake.TestTask#testNam + @public + @type {String} + @description The name of the namespace to place the tests in, and + the top-level task for running tests. Defaults to "test" + */ + this.testName = 'test'; + + /** + @name jake.TestTask#testFiles + @public + @type {jake.FileList} + @description The list of files containing tests to load + */ + this.testFiles = new jake.FileList(); + + /** + @name jake.TestTask#showDescription + @public + @type {Boolean} + @description Show the created task when doing Jake -T + */ + this.showDescription = true; + + /* + @name jake.TestTask#totalTests + @public + @type {Number} + @description The total number of tests to run + */ + this.totalTests = 0; + + /* + @name jake.TestTask#executedTests + @public + @type {Number} + @description The number of tests successfully run + */ + this.executedTests = 0; + + if (typeof definition == 'function') { + definition.call(this); + } + + if (this.showDescription) { + desc('Run the tests for ' + name); + } + + task(this.testName, prereqs, {async: true}, function () { + let t = jake.Task[this.fullName + ':run']; + t.on('complete', function () { + complete(); + }); + // Pass args to the namespaced test + t.invoke.apply(t, arguments); + }); + + namespace(self.testName, function () { + + let runTask = task('run', {async: true}, function (pat) { + let re; + let testFiles; + + // Don't nest; make a top-level namespace. Don't want + // re-calling from inside to nest infinitely + jake.currentNamespace = jake.defaultNamespace; + + re = new RegExp(pat); + // Get test files that match the passed-in pattern + testFiles = self.testFiles.toArray() + .filter(function (f) { + return (re).test(f); + }) // Don't load the same file multiple times -- should this be in FileList? + .reduce(function (p, c) { + if (p.indexOf(c) < 0) { + p.push(c); + } + return p; + }, []); + + // Create a namespace for all the testing tasks to live in + namespace(self.testName + 'Exec', function () { + // Each test will be a prereq for the dummy top-level task + let prereqs = []; + // Continuation to pass to the async tests, wrapping `continune` + let next = function () { + complete(); + }; + // Create the task for this test-function + let createTask = function (name, action) { + // If the test-function is defined with a continuation + // param, flag the task as async + let t; + let isAsync = !!action.length; + + // Define the actual namespaced task with the name, the + // wrapped action, and the correc async-flag + t = task(name, createAction(name, action), { + async: isAsync + }); + t.once('complete', function () { + self.executedTests++; + }); + t._internal = true; + return t; + }; + // Used as the action for the defined task for each test. + let createAction = function (n, a) { + // A wrapped function that passes in the `next` function + // for any tasks that run asynchronously + return function () { + let cb; + if (a.length) { + cb = next; + } + if (!(n == 'before' || n == 'after' || + /_beforeEach$/.test(n) || /_afterEach$/.test(n))) { + jake.logger.log(n); + } + // 'this' will be the task when action is run + return a.call(this, cb); + }; + }; + // Dummy top-level task for everything to be prereqs for + let topLevel; + + // Pull in each test-file, and iterate over any exported + // test-functions. Register each test-function as a prereq task + testFiles.forEach(function (file) { + let exp = require(path.join(currDir, file)); + + // Create a namespace for each filename, so test-name collisions + // won't be a problem + namespace(file, function () { + let testPrefix = self.testName + 'Exec:' + file + ':'; + let testName; + // Dummy task for displaying file banner + testName = '*** Running ' + file + ' ***'; + prereqs.push(testPrefix + testName); + createTask(testName, function () {}); + + // 'before' setup + if (typeof exp.before == 'function') { + prereqs.push(testPrefix + 'before'); + // Create the task + createTask('before', exp.before); + } + + // Walk each exported function, and create a task for each + for (let p in exp) { + if (p == 'before' || p == 'after' || + p == 'beforeEach' || p == 'afterEach') { + continue; + } + + if (typeof exp.beforeEach == 'function') { + prereqs.push(testPrefix + p + '_beforeEach'); + // Create the task + createTask(p + '_beforeEach', exp.beforeEach); + } + + // Add the namespace:name of this test to the list of prereqs + // for the dummy top-level task + prereqs.push(testPrefix + p); + // Create the task + createTask(p, exp[p]); + + if (typeof exp.afterEach == 'function') { + prereqs.push(testPrefix + p + '_afterEach'); + // Create the task + createTask(p + '_afterEach', exp.afterEach); + } + } + + // 'after' teardown + if (typeof exp.after == 'function') { + prereqs.push(testPrefix + 'after'); + // Create the task + let afterTask = createTask('after', exp.after); + afterTask._internal = true; + } + + }); + }); + + self.totalTests = prereqs.length; + process.on('exit', function () { + // Throw in the case where the process exits without + // finishing tests, but no error was thrown + if (!jake.errorCode && (self.totalTests > self.executedTests)) { + throw new Error('Process exited without all tests completing.'); + } + }); + + // Create the dummy top-level task. When calling a task internally + // with `invoke` that is async (or has async prereqs), have to listen + // for the 'complete' event to know when it's done + topLevel = task('__top__', prereqs); + topLevel._internal = true; + topLevel.addListener('complete', function () { + jake.logger.log('All tests ran successfully'); + complete(); + }); + + topLevel.invoke(); // Do the thing! + }); + + }); + runTask._internal = true; + + }); + + +}; + +jake.TestTask = TestTask; +exports.TestTask = TestTask; + diff --git a/node_modules/jake/lib/utils/file.js b/node_modules/jake/lib/utils/file.js new file mode 100644 index 0000000..a436def --- /dev/null +++ b/node_modules/jake/lib/utils/file.js @@ -0,0 +1,286 @@ +/* + * Utilities: A classic collection of JavaScript utilities + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +let fs = require('fs'); +let path = require('path'); + +/** + @name file + @namespace file +*/ + +let fileUtils = new (function () { + + // Recursively copy files and directories + let _copyFile = function (fromPath, toPath, opts) { + let from = path.normalize(fromPath) + let to = path.normalize(toPath) + let options = opts || {} + let fromStat; + let toStat; + let destExists; + let destDoesNotExistErr; + let content; + let filename; + let dirContents; + let targetDir; + + fromStat = fs.statSync(from); + + try { + //console.dir(to + ' destExists'); + toStat = fs.statSync(to); + destExists = true; + } + catch(e) { + //console.dir(to + ' does not exist'); + destDoesNotExistErr = e; + destExists = false; + } + // Destination dir or file exists, copy into (directory) + // or overwrite (file) + if (destExists) { + + // If there's a rename-via-copy file/dir name passed, use it. + // Otherwise use the actual file/dir name + filename = options.rename || path.basename(from); + + // Copying a directory + if (fromStat.isDirectory()) { + dirContents = fs.readdirSync(from); + targetDir = path.join(to, filename); + // We don't care if the target dir already exists + try { + fs.mkdirSync(targetDir, {mode: fromStat.mode & 0o777}); + } + catch(e) { + if (e.code !== 'EEXIST') { + throw e; + } + } + for (let i = 0, ii = dirContents.length; i < ii; i++) { + _copyFile(path.join(from, dirContents[i]), targetDir, {preserveMode: options.preserveMode}); + } + } + // Copying a file + else { + content = fs.readFileSync(from); + let mode = fromStat.mode & 0o777; + let targetFile = to; + + if (toStat.isDirectory()) { + targetFile = path.join(to, filename); + } + + let fileExists = fs.existsSync(targetFile); + fs.writeFileSync(targetFile, content); + + // If the file didn't already exist, use the original file mode. + // Otherwise, only update the mode if preserverMode is true. + if(!fileExists || options.preserveMode) { + fs.chmodSync(targetFile, mode); + } + } + } + // Dest doesn't exist, can't create it + else { + throw destDoesNotExistErr; + } + }; + + // Remove the given directory + let _rmDir = function (dirPath) { + let dir = path.normalize(dirPath); + let paths = []; + paths = fs.readdirSync(dir); + paths.forEach(function (p) { + let curr = path.join(dir, p); + let stat = fs.lstatSync(curr); + if (stat.isDirectory()) { + _rmDir(curr); + } + else { + try { + fs.unlinkSync(curr); + } catch(e) { + if (e.code === 'EPERM') { + fs.chmodSync(curr, parseInt(666, 8)); + fs.unlinkSync(curr); + } else { + throw e; + } + } + } + }); + fs.rmdirSync(dir); + }; + + /** + @name file#cpR + @public + @function + @description Copies a directory/file to a destination + @param {String} fromPath The source path to copy from + @param {String} toPath The destination path to copy to + @param {Object} opts Options to use + @param {Boolean} [opts.preserveMode] If target file already exists, this + determines whether the original file's mode is copied over. The default of + false mimics the behavior of the `cp` command line tool. (Default: false) + */ + this.cpR = function (fromPath, toPath, options) { + let from = path.normalize(fromPath); + let to = path.normalize(toPath); + let toStat; + let doesNotExistErr; + let filename; + let opts = options || {}; + + if (from == to) { + throw new Error('Cannot copy ' + from + ' to itself.'); + } + + // Handle rename-via-copy + try { + toStat = fs.statSync(to); + } + catch(e) { + doesNotExistErr = e; + + // Get abs path so it's possible to check parent dir + if (!this.isAbsolute(to)) { + to = path.join(process.cwd(), to); + } + + // Save the file/dir name + filename = path.basename(to); + // See if a parent dir exists, so there's a place to put the + /// renamed file/dir (resets the destination for the copy) + to = path.dirname(to); + try { + toStat = fs.statSync(to); + } + catch(e) {} + if (toStat && toStat.isDirectory()) { + // Set the rename opt to pass to the copy func, will be used + // as the new file/dir name + opts.rename = filename; + //console.log('filename ' + filename); + } + else { + throw doesNotExistErr; + } + } + + _copyFile(from, to, opts); + }; + + /** + @name file#mkdirP + @public + @function + @description Create the given directory(ies) using the given mode permissions + @param {String} dir The directory to create + @param {Number} mode The mode to give the created directory(ies)(Default: 0755) + */ + this.mkdirP = function (dir, mode) { + let dirPath = path.normalize(dir); + let paths = dirPath.split(/\/|\\/); + let currPath = ''; + let next; + + if (paths[0] == '' || /^[A-Za-z]+:/.test(paths[0])) { + currPath = paths.shift() || '/'; + currPath = path.join(currPath, paths.shift()); + //console.log('basedir'); + } + while ((next = paths.shift())) { + if (next == '..') { + currPath = path.join(currPath, next); + continue; + } + currPath = path.join(currPath, next); + try { + //console.log('making ' + currPath); + fs.mkdirSync(currPath, mode || parseInt(755, 8)); + } + catch(e) { + if (e.code != 'EEXIST') { + throw e; + } + } + } + }; + + /** + @name file#rmRf + @public + @function + @description Deletes the given directory/file + @param {String} p The path to delete, can be a directory or file + */ + this.rmRf = function (p, options) { + let stat; + try { + stat = fs.lstatSync(p); + if (stat.isDirectory()) { + _rmDir(p); + } + else { + fs.unlinkSync(p); + } + } + catch (e) {} + }; + + /** + @name file#isAbsolute + @public + @function + @return {Boolean/String} If it's absolute the first character is returned otherwise false + @description Checks if a given path is absolute or relative + @param {String} p Path to check + */ + this.isAbsolute = function (p) { + let match = /^[A-Za-z]+:\\|^\//.exec(p); + if (match && match.length) { + return match[0]; + } + return false; + }; + + /** + @name file#absolutize + @public + @function + @return {String} Returns the absolute path for the given path + @description Returns the absolute path for the given path + @param {String} p The path to get the absolute path for + */ + this.absolutize = function (p) { + if (this.isAbsolute(p)) { + return p; + } + else { + return path.join(process.cwd(), p); + } + }; + +})(); + +module.exports = fileUtils; + diff --git a/node_modules/jake/lib/utils/index.js b/node_modules/jake/lib/utils/index.js new file mode 100644 index 0000000..17d686b --- /dev/null +++ b/node_modules/jake/lib/utils/index.js @@ -0,0 +1,297 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + + +let util = require('util'); // Native Node util module +let spawn = require('child_process').spawn; +let EventEmitter = require('events').EventEmitter; +let logger = require('./logger'); +let file = require('./file'); +let Exec; + +const _UUID_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); + +let parseArgs = function (argumentsObj) { + let args; + let arg; + let cmds; + let callback; + let opts = { + interactive: false, + printStdout: false, + printStderr: false, + breakOnError: true + }; + + args = Array.prototype.slice.call(argumentsObj); + + cmds = args.shift(); + // Arrayize if passed a single string command + if (typeof cmds == 'string') { + cmds = [cmds]; + } + // Make a copy if it's an actual list + else { + cmds = cmds.slice(); + } + + // Get optional callback or opts + while((arg = args.shift())) { + if (typeof arg == 'function') { + callback = arg; + } + else if (typeof arg == 'object') { + opts = Object.assign(opts, arg); + } + } + + // Backward-compat shim + if (typeof opts.stdout != 'undefined') { + opts.printStdout = opts.stdout; + delete opts.stdout; + } + if (typeof opts.stderr != 'undefined') { + opts.printStderr = opts.stderr; + delete opts.stderr; + } + + return { + cmds: cmds, + opts: opts, + callback: callback + }; +}; + +/** + @name jake + @namespace jake +*/ +let utils = new (function () { + /** + @name jake.exec + @static + @function + @description Executes shell-commands asynchronously with an optional + final callback. + ` + @param {String[]} cmds The list of shell-commands to execute + @param {Object} [opts] + @param {Boolean} [opts.printStdout=false] Print stdout from each command + @param {Boolean} [opts.printStderr=false] Print stderr from each command + @param {Boolean} [opts.breakOnError=true] Stop further execution on + the first error. + @param {Boolean} [opts.windowsVerbatimArguments=false] Don't translate + arguments on Windows. + @param {Function} [callback] Callback to run after executing the + commands + + @example + let cmds = [ + 'echo "showing directories"' + , 'ls -al | grep ^d' + , 'echo "moving up a directory"' + , 'cd ../' + ] + , callback = function () { + console.log('Finished running commands.'); + } + jake.exec(cmds, {stdout: true}, callback); + */ + this.exec = function (a, b, c) { + let parsed = parseArgs(arguments); + let cmds = parsed.cmds; + let opts = parsed.opts; + let callback = parsed.callback; + + let ex = new Exec(cmds, opts, callback); + + ex.addListener('error', function (msg, code) { + if (opts.breakOnError) { + fail(msg, code); + } + }); + ex.run(); + + return ex; + }; + + this.createExec = function (a, b, c) { + return new Exec(a, b, c); + }; + + // From Math.uuid.js, https://github.com/broofa/node-uuid + // Robert Kieffer (robert@broofa.com), MIT license + this.uuid = function (length, radix) { + var chars = _UUID_CHARS + , uuid = [] + , r + , i; + + radix = radix || chars.length; + + if (length) { + // Compact form + i = -1; + while (++i < length) { + uuid[i] = chars[0 | Math.random()*radix]; + } + } else { + // rfc4122, version 4 form + + // rfc4122 requires these characters + uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; + uuid[14] = '4'; + + // Fill in random data. At i==19 set the high bits of clock sequence as + // per rfc4122, sec. 4.1.5 + i = -1; + while (++i < 36) { + if (!uuid[i]) { + r = 0 | Math.random()*16; + uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; + } + } + } + + return uuid.join(''); + }; + +})(); + +Exec = function () { + let parsed = parseArgs(arguments); + let cmds = parsed.cmds; + let opts = parsed.opts; + let callback = parsed.callback; + + this._cmds = cmds; + this._callback = callback; + this._config = opts; +}; + +util.inherits(Exec, EventEmitter); + +Object.assign(Exec.prototype, new (function () { + + let _run = function () { + let self = this; + let sh; + let cmd; + let args; + let next = this._cmds.shift(); + let config = this._config; + let errData = ''; + let shStdio; + let handleStdoutData = function (data) { + self.emit('stdout', data); + }; + let handleStderrData = function (data) { + let d = data.toString(); + self.emit('stderr', data); + // Accumulate the error-data so we can use it as the + // stack if the process exits with an error + errData += d; + }; + + // Keep running as long as there are commands in the array + if (next) { + let spawnOpts = {}; + this.emit('cmdStart', next); + + // Ganking part of Node's child_process.exec to get cmdline args parsed + if (process.platform == 'win32') { + cmd = 'cmd'; + args = ['/c', next]; + if (config.windowsVerbatimArguments) { + spawnOpts.windowsVerbatimArguments = true; + } + } + else { + cmd = '/bin/sh'; + args = ['-c', next]; + } + + if (config.interactive) { + spawnOpts.stdio = 'inherit'; + sh = spawn(cmd, args, spawnOpts); + } + else { + shStdio = [ + process.stdin + ]; + if (config.printStdout) { + shStdio.push(process.stdout); + } + else { + shStdio.push('pipe'); + } + if (config.printStderr) { + shStdio.push(process.stderr); + } + else { + shStdio.push('pipe'); + } + spawnOpts.stdio = shStdio; + sh = spawn(cmd, args, spawnOpts); + if (!config.printStdout) { + sh.stdout.addListener('data', handleStdoutData); + } + if (!config.printStderr) { + sh.stderr.addListener('data', handleStderrData); + } + } + + // Exit, handle err or run next + sh.on('exit', function (code) { + let msg; + if (code !== 0) { + msg = errData || 'Process exited with error.'; + msg = msg.trim(); + self.emit('error', msg, code); + } + if (code === 0 || !config.breakOnError) { + self.emit('cmdEnd', next); + setTimeout(function () { _run.call(self); }, 0); + } + }); + + } + else { + self.emit('end'); + if (typeof self._callback == 'function') { + self._callback(); + } + } + }; + + this.append = function (cmd) { + this._cmds.push(cmd); + }; + + this.run = function () { + _run.call(this); + }; + +})()); + +utils.Exec = Exec; +utils.file = file; +utils.logger = logger; + +module.exports = utils; + diff --git a/node_modules/jake/lib/utils/logger.js b/node_modules/jake/lib/utils/logger.js new file mode 100644 index 0000000..8f72686 --- /dev/null +++ b/node_modules/jake/lib/utils/logger.js @@ -0,0 +1,24 @@ +let util = require('util'); + +let logger = new (function () { + let _output = function (type, out) { + let quiet = typeof jake != 'undefined' && jake.program && + jake.program.opts && jake.program.opts.quiet; + let msg; + if (!quiet) { + msg = typeof out == 'string' ? out : util.inspect(out); + console[type](msg); + } + }; + + this.log = function (out) { + _output('log', out); + }; + + this.error = function (out) { + _output('error', out); + }; + +})(); + +module.exports = logger; diff --git a/node_modules/jake/package.json b/node_modules/jake/package.json new file mode 100644 index 0000000..2d3c009 --- /dev/null +++ b/node_modules/jake/package.json @@ -0,0 +1,75 @@ +{ + "_from": "jake@^10.6.1", + "_id": "jake@10.8.2", + "_inBundle": false, + "_integrity": "sha512-eLpKyrfG3mzvGE2Du8VoPbeSkRry093+tyNjdYaBbJS9v17knImYGNXQCUV0gLxQtF82m3E8iRb/wdSQZLoq7A==", + "_location": "/jake", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jake@^10.6.1", + "name": "jake", + "escapedName": "jake", + "rawSpec": "^10.6.1", + "saveSpec": null, + "fetchSpec": "^10.6.1" + }, + "_requiredBy": [ + "/ejs" + ], + "_resolved": "https://registry.npmjs.org/jake/-/jake-10.8.2.tgz", + "_shasum": "ebc9de8558160a66d82d0eadc6a2e58fbc500a7b", + "_spec": "jake@^10.6.1", + "_where": "C:\\angel\\node_modules\\ejs", + "author": { + "name": "Matthew Eernisse", + "email": "mde@fleegix.org", + "url": "http://fleegix.org" + }, + "bin": { + "jake": "bin/cli.js" + }, + "bugs": { + "url": "https://github.com/jakejs/jake/issues" + }, + "bundleDependencies": false, + "dependencies": { + "async": "0.9.x", + "chalk": "^2.4.2", + "filelist": "^1.0.1", + "minimatch": "^3.0.4" + }, + "deprecated": false, + "description": "JavaScript build tool, similar to Make or Rake", + "devDependencies": { + "eslint": "^6.8.0", + "mocha": "^7.1.1", + "q": "^1.5.1" + }, + "engines": { + "node": "*" + }, + "homepage": "https://github.com/jakejs/jake#readme", + "keywords": [ + "build", + "cli", + "make", + "rake" + ], + "license": "Apache-2.0", + "main": "./lib/jake.js", + "name": "jake", + "preferGlobal": true, + "repository": { + "type": "git", + "url": "git://github.com/jakejs/jake.git" + }, + "scripts": { + "lint": "eslint --format codeframe \"lib/**/*.js\" \"test/**/*.js\"", + "lint:fix": "eslint --fix \"lib/**/*.js\" \"test/**/*.js\"", + "test": "./bin/cli.js test", + "test:ci": "npm run lint && npm run test" + }, + "version": "10.8.2" +} diff --git a/node_modules/jake/test/integration/concurrent.js b/node_modules/jake/test/integration/concurrent.js new file mode 100644 index 0000000..4ae41e8 --- /dev/null +++ b/node_modules/jake/test/integration/concurrent.js @@ -0,0 +1,42 @@ +let assert = require('assert'); +let exec = require('child_process').execSync; + +suite('concurrent', function () { + + this.timeout(7000); + + test(' simple concurrent prerequisites 1', function () { + let out = exec('./node_modules/.bin/jake -q concurrent:simple1').toString().trim() + assert.equal('Started A\nStarted B\nFinished B\nFinished A', out); + }); + + test(' simple concurrent prerequisites 2', function () { + let out = exec('./node_modules/.bin/jake -q concurrent:simple2').toString().trim() + assert.equal('Started C\nStarted D\nFinished C\nFinished D', out); + }); + + test(' sequential concurrent prerequisites', function () { + let out = exec('./node_modules/.bin/jake -q concurrent:seqconcurrent').toString().trim() + assert.equal('Started A\nStarted B\nFinished B\nFinished A\nStarted C\nStarted D\nFinished C\nFinished D', out); + }); + + test(' concurrent concurrent prerequisites', function () { + let out = exec('./node_modules/.bin/jake -q concurrent:concurrentconcurrent').toString().trim() + assert.equal('Started A\nStarted B\nStarted C\nStarted D\nFinished B\nFinished C\nFinished A\nFinished D', out); + }); + + test(' concurrent prerequisites with subdependency', function () { + let out = exec('./node_modules/.bin/jake -q concurrent:subdep').toString().trim() + assert.equal('Started A\nFinished A\nStarted Ba\nFinished Ba', out); + }); + + test(' failing in concurrent prerequisites', function () { + try { + exec('./node_modules/.bin/jake -q concurrent:Cfail'); + } + catch(err) { + assert(err.message.indexOf('Command failed') > -1); + } + }); + +}); diff --git a/node_modules/jake/test/integration/file.js b/node_modules/jake/test/integration/file.js new file mode 100644 index 0000000..97ed0d6 --- /dev/null +++ b/node_modules/jake/test/integration/file.js @@ -0,0 +1,228 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +let assert = require('assert'); +let fs = require('fs'); +let path = require('path'); +let file = require(`${PROJECT_DIR}/lib/utils/file`); +let existsSync = fs.existsSync || path.existsSync; +let exec = require('child_process').execSync; + +suite('fileUtils', function () { + + test('mkdirP', function () { + let expected = [ + ['foo'], + ['foo', 'bar'], + ['foo', 'bar', 'baz'], + ['foo', 'bar', 'baz', 'qux'] + ]; + file.mkdirP('foo/bar/baz/qux'); + let res = exec('find foo').toString().trim().split('\n'); + for (let i = 0, ii = res.length; i < ii; i++) { + assert.equal(path.join.apply(path, expected[i]), res[i]); + } + file.rmRf('foo'); + }); + + test('rmRf', function () { + file.mkdirP('foo/bar/baz/qux'); + file.rmRf('foo/bar'); + let res = exec('find foo').toString().trim().split('\n'); + assert.equal(1, res.length); + assert.equal('foo', res[0]); + fs.rmdirSync('foo'); + }); + + test('rmRf with symlink subdir', function () { + file.mkdirP('foo'); + file.mkdirP('bar'); + fs.writeFileSync('foo/hello.txt', 'hello, it\'s me'); + fs.symlinkSync('../foo', 'bar/foo'); file.rmRf('bar'); + + // Make sure the bar directory was successfully deleted + let barDeleted = false; + try { + fs.statSync('bar'); + } catch(err) { + if(err.code == 'ENOENT') { + barDeleted = true; + } + } + assert.equal(true, barDeleted); + + // Make sure that the file inside the linked folder wasn't deleted + let res = fs.readdirSync('foo'); + assert.equal(1, res.length); + assert.equal('hello.txt', res[0]); + + // Cleanup + fs.unlinkSync('foo/hello.txt'); + fs.rmdirSync('foo'); + }); + + test('rmRf with symlinked dir', function () { + file.mkdirP('foo'); + fs.writeFileSync('foo/hello.txt', 'hello!'); + fs.symlinkSync('foo', 'bar'); + file.rmRf('bar'); + + // Make sure the bar directory was successfully deleted + let barDeleted = false; + try { + fs.statSync('bar'); + } catch(err) { + if(err.code == 'ENOENT') { + barDeleted = true; + } + } + assert.equal(true, barDeleted); + + // Make sure that the file inside the linked folder wasn't deleted + let res = fs.readdirSync('foo'); + assert.equal(1, res.length); + assert.equal('hello.txt', res[0]); + + // Cleanup + fs.unlinkSync('foo/hello.txt'); + fs.rmdirSync('foo'); + }); + + test('cpR with same name and different directory', function () { + file.mkdirP('foo'); + fs.writeFileSync('foo/bar.txt', 'w00t'); + file.cpR('foo', 'bar'); + assert.ok(existsSync('bar/bar.txt')); + file.rmRf('foo'); + file.rmRf('bar'); + }); + + test('cpR with same to and from will throw', function () { + assert.throws(function () { + file.cpR('foo.txt', 'foo.txt'); + }); + }); + + test('cpR rename via copy in directory', function () { + file.mkdirP('foo'); + fs.writeFileSync('foo/bar.txt', 'w00t'); + file.cpR('foo/bar.txt', 'foo/baz.txt'); + assert.ok(existsSync('foo/baz.txt')); + file.rmRf('foo'); + }); + + test('cpR rename via copy in base', function () { + fs.writeFileSync('bar.txt', 'w00t'); + file.cpR('bar.txt', 'baz.txt'); + assert.ok(existsSync('baz.txt')); + file.rmRf('bar.txt'); + file.rmRf('baz.txt'); + }); + + test('cpR keeps file mode', function () { + fs.writeFileSync('bar.txt', 'w00t', {mode: 0o750}); + fs.writeFileSync('bar1.txt', 'w00t!', {mode: 0o744}); + file.cpR('bar.txt', 'baz.txt'); + file.cpR('bar1.txt', 'baz1.txt'); + + assert.ok(existsSync('baz.txt')); + assert.ok(existsSync('baz1.txt')); + let bazStat = fs.statSync('baz.txt'); + let bazStat1 = fs.statSync('baz1.txt'); + assert.equal(0o750, bazStat.mode & 0o7777); + assert.equal(0o744, bazStat1.mode & 0o7777); + + file.rmRf('bar.txt'); + file.rmRf('baz.txt'); + file.rmRf('bar1.txt'); + file.rmRf('baz1.txt'); + }); + + test('cpR keeps file mode when overwriting with preserveMode', function () { + fs.writeFileSync('bar.txt', 'w00t', {mode: 0o755}); + fs.writeFileSync('baz.txt', 'w00t!', {mode: 0o744}); + file.cpR('bar.txt', 'baz.txt', {silent: true, preserveMode: true}); + + assert.ok(existsSync('baz.txt')); + let bazStat = fs.statSync('baz.txt'); + assert.equal(0o755, bazStat.mode & 0o777); + + file.rmRf('bar.txt'); + file.rmRf('baz.txt'); + }); + + test('cpR does not keep file mode when overwriting', function () { + fs.writeFileSync('bar.txt', 'w00t', {mode: 0o766}); + fs.writeFileSync('baz.txt', 'w00t!', {mode: 0o744}); + file.cpR('bar.txt', 'baz.txt'); + + assert.ok(existsSync('baz.txt')); + let bazStat = fs.statSync('baz.txt'); + assert.equal(0o744, bazStat.mode & 0o777); + + file.rmRf('bar.txt'); + file.rmRf('baz.txt'); + }); + + test('cpR copies file mode recursively', function () { + fs.mkdirSync('foo'); + fs.writeFileSync('foo/bar.txt', 'w00t', {mode: 0o740}); + file.cpR('foo', 'baz'); + + assert.ok(existsSync('baz')); + let barStat = fs.statSync('baz/bar.txt'); + assert.equal(0o740, barStat.mode & 0o777); + + file.rmRf('foo'); + file.rmRf('baz'); + }); + + test('cpR keeps file mode recursively', function () { + fs.mkdirSync('foo'); + fs.writeFileSync('foo/bar.txt', 'w00t', {mode: 0o740}); + fs.mkdirSync('baz'); + fs.mkdirSync('baz/foo'); + fs.writeFileSync('baz/foo/bar.txt', 'w00t!', {mode: 0o755}); + file.cpR('foo', 'baz', {silent: true, preserveMode: true}); + + assert.ok(existsSync('baz')); + let barStat = fs.statSync('baz/foo/bar.txt'); + assert.equal(0o740, barStat.mode & 0o777); + + file.rmRf('foo'); + file.rmRf('baz'); + }); + + test('cpR copies directory mode recursively', function () { + fs.mkdirSync('foo', 0o755); + fs.mkdirSync('foo/bar', 0o700); + file.cpR('foo', 'bar'); + + assert.ok(existsSync('foo')); + let fooBarStat = fs.statSync('bar/bar'); + assert.equal(0o700, fooBarStat.mode & 0o777); + + file.rmRf('foo'); + file.rmRf('bar'); + }); + +}); + + diff --git a/node_modules/jake/test/integration/file_task.js b/node_modules/jake/test/integration/file_task.js new file mode 100644 index 0000000..b48f07e --- /dev/null +++ b/node_modules/jake/test/integration/file_task.js @@ -0,0 +1,125 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +let assert = require('assert'); +let fs = require('fs'); +let exec = require('child_process').execSync; +let { rmRf } = require(`${PROJECT_DIR}/lib/jake`); + +let cleanUpAndNext = function (callback) { + rmRf('./foo', { + silent: true + }); + callback && callback(); +}; + +suite('fileTask', function () { + this.timeout(7000); + + setup(function () { + cleanUpAndNext(); + }); + + test('where a file-task prereq does not change with --always-make', function () { + let out; + out = exec('./node_modules/.bin/jake -q fileTest:foo/from-src1.txt').toString().trim(); + assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task', + out); + out = exec('./node_modules/.bin/jake -q -B fileTest:foo/from-src1.txt').toString().trim(); + assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task', + out); + cleanUpAndNext(); + }); + + test('concating two files', function () { + let out; + out = exec('./node_modules/.bin/jake -q fileTest:foo/concat.txt').toString().trim(); + assert.equal('fileTest:foo/src1.txt task\ndefault task\nfileTest:foo/src2.txt task\n' + + 'fileTest:foo/concat.txt task', out); + // Check to see the two files got concat'd + let data = fs.readFileSync(process.cwd() + '/foo/concat.txt'); + assert.equal('src1src2', data.toString()); + cleanUpAndNext(); + }); + + test('where a file-task prereq does not change', function () { + let out; + out = exec('./node_modules/.bin/jake -q fileTest:foo/from-src1.txt').toString().trim(); + assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task', out); + out = exec('./node_modules/.bin/jake -q fileTest:foo/from-src1.txt').toString().trim(); + // Second time should be a no-op + assert.equal('', out); + cleanUpAndNext(); + }); + + test('where a file-task prereq does change, then does not', function (next) { + exec('mkdir -p ./foo'); + exec('touch ./foo/from-src1.txt'); + setTimeout(() => { + fs.writeFileSync('./foo/src1.txt', '-SRC'); + // Task should run the first time + let out; + out = exec('./node_modules/.bin/jake -q fileTest:foo/from-src1.txt').toString().trim(); + assert.equal('fileTest:foo/from-src1.txt task', out); + // Task should not run on subsequent invocation + out = exec('./node_modules/.bin/jake -q fileTest:foo/from-src1.txt').toString().trim(); + assert.equal('', out); + cleanUpAndNext(next); + }, 1000); + }); + + test('a preexisting file', function () { + let prereqData = 'howdy'; + exec('mkdir -p ./foo'); + fs.writeFileSync('foo/prereq.txt', prereqData); + let out; + out = exec('./node_modules/.bin/jake -q fileTest:foo/from-prereq.txt').toString().trim(); + assert.equal('fileTest:foo/from-prereq.txt task', out); + let data = fs.readFileSync(process.cwd() + '/foo/from-prereq.txt'); + assert.equal(prereqData, data.toString()); + out = exec('./node_modules/.bin/jake -q fileTest:foo/from-prereq.txt').toString().trim(); + // Second time should be a no-op + assert.equal('', out); + cleanUpAndNext(); + }); + + test('a preexisting file with --always-make flag', function () { + let prereqData = 'howdy'; + exec('mkdir -p ./foo'); + fs.writeFileSync('foo/prereq.txt', prereqData); + let out; + out = exec('./node_modules/.bin/jake -q fileTest:foo/from-prereq.txt').toString().trim(); + assert.equal('fileTest:foo/from-prereq.txt task', out); + let data = fs.readFileSync(process.cwd() + '/foo/from-prereq.txt'); + assert.equal(prereqData, data.toString()); + out = exec('./node_modules/.bin/jake -q -B fileTest:foo/from-prereq.txt').toString().trim(); + assert.equal('fileTest:foo/from-prereq.txt task', out); + cleanUpAndNext(); + }); + + test('nested directory-task', function () { + exec('./node_modules/.bin/jake -q fileTest:foo/bar/baz/bamf.txt'); + let data = fs.readFileSync(process.cwd() + '/foo/bar/baz/bamf.txt'); + assert.equal('w00t', data); + cleanUpAndNext(); + }); + +}); + diff --git a/node_modules/jake/test/integration/helpers.js b/node_modules/jake/test/integration/helpers.js new file mode 100644 index 0000000..9caaa4e --- /dev/null +++ b/node_modules/jake/test/integration/helpers.js @@ -0,0 +1,80 @@ +var exec = require('child_process').exec; + +var helpers = new (function () { + var _tests; + var _names = []; + var _name; + var _callback; + var _runner = function () { + if ((_name = _names.shift())) { + console.log('Running ' + _name); + _tests[_name](); + } + else { + _callback(); + } + }; + + this.exec = function () { + var args = Array.prototype.slice.call(arguments); + var arg; + var cmd = args.shift(); + var opts = {}; + var callback; + // Optional opts/callback or callback/opts + while ((arg = args.shift())) { + if (typeof arg == 'function') { + callback = arg; + } + else { + opts = arg; + } + } + + cmd += ' --trace'; + var execOpts = opts.execOpts ? opts.execOpts : {}; + exec(cmd, execOpts, function (err, stdout, stderr) { + var out = helpers.trim(stdout); + if (err) { + if (opts.breakOnError === false) { + return callback(err); + } + else { + throw err; + } + } + if (stderr) { + callback(stderr); + } + else { + callback(out); + } + }); + }; + + this.trim = function (s) { + var str = s || ''; + return str.replace(/^\s*|\s*$/g, ''); + }; + + this.parse = function (s) { + var str = s || ''; + str = helpers.trim(str); + str = str.replace(/'/g, '"'); + return JSON.parse(str); + }; + + this.run = function (tests, callback) { + _tests = tests; + _names = Object.keys(tests); + _callback = callback; + _runner(); + }; + + this.next = function () { + _runner(); + }; + +})(); + +module.exports = helpers; diff --git a/node_modules/jake/test/integration/jakefile.js b/node_modules/jake/test/integration/jakefile.js new file mode 100644 index 0000000..f3b7d1a --- /dev/null +++ b/node_modules/jake/test/integration/jakefile.js @@ -0,0 +1,337 @@ +let fs = require('fs'); +let Q = require('q'); + +desc('The default t.'); +task('default', function () { + console.log('default task'); +}); + +desc('No action.'); +task({'noAction': ['default']}); + +desc('No action, no prereqs.'); +task('noActionNoPrereqs'); + +desc('Top-level zerbofrangazoomy task'); +task('zerbofrangazoomy', function () { + console.log('Whaaaaaaaa? Ran the zerbofrangazoomy task!') +}); + +desc('Task that throws'); +task('throwy', function () { + let errorListener = function (err) { + console.log('Emitted'); + console.log(err.toString()); + + jake.removeListener('error', errorListener); + }; + + jake.on('error', errorListener); + + throw new Error('I am bad'); +}); + +desc('Task that rejects a Promise'); +task('promiseRejecter', function () { + const originalOption = jake.program.opts['allow-rejection']; + + const errorListener = function (err) { + console.log(err.toString()); + jake.removeListener('error', errorListener); + jake.program.opts['allow-rejection'] = originalOption; // Restore original 'allow-rejection' option + }; + jake.on('error', errorListener); + + jake.program.opts['allow-rejection'] = false; // Do not allow rejection so the rejection is passed to error handlers + + Promise.reject(''); +}); + +desc('Accepts args and env vars.'); +task('argsEnvVars', function () { + let res = { + args: arguments + , env: { + foo: process.env.foo + , baz: process.env.baz + } + }; + console.log(JSON.stringify(res)); +}); + +namespace('foo', function () { + desc('The foo:bar t.'); + task('bar', function () { + if (arguments.length) { + console.log('foo:bar[' + + Array.prototype.join.call(arguments, ',') + + '] task'); + } + else { + console.log('foo:bar task'); + } + }); + + desc('The foo:baz task, calls foo:bar as a prerequisite.'); + task('baz', ['foo:bar'], function () { + console.log('foo:baz task'); + }); + + desc('The foo:qux task, calls foo:bar with cmdline args as a prerequisite.'); + task('qux', ['foo:bar[asdf,qwer]'], function () { + console.log('foo:qux task'); + }); + + desc('The foo:frang task,`invokes` foo:bar with passed args as a prerequisite.'); + task('frang', function () { + let t = jake.Task['foo:bar']; + // Do args pass-through + t.invoke.apply(t, arguments); + t.on('complete', () => { + console.log('foo:frang task'); + }); + }); + + desc('The foo:zerb task, `executes` foo:bar with passed args as a prerequisite.'); + task('zerb', function () { + let t = jake.Task['foo:bar']; + // Do args pass-through + t.execute.apply(t, arguments); + t.on('complete', () => { + console.log('foo:zerb task'); + }); + }); + + desc('The foo:zoobie task, has no prerequisites.'); + task('zoobie', function () { + console.log('foo:zoobie task'); + }); + + desc('The foo:voom task, run the foo:zoobie task repeatedly.'); + task('voom', function () { + let t = jake.Task['foo:bar']; + t.on('complete', function () { + console.log('complete'); + }); + t.execute.apply(t); + t.execute.apply(t); + }); + + desc('The foo:asdf task, has the same prereq twice.'); + task('asdf', ['foo:bar', 'foo:baz'], function () { + console.log('foo:asdf task'); + }); + +}); + +namespace('bar', function () { + desc('The bar:foo task, has no prerequisites, is async, returns Promise which resolves.'); + task('foo', async function () { + return new Promise((resolve, reject) => { + console.log('bar:foo task'); + resolve(); + }); + }); + + desc('The bar:promise task has no prerequisites, is async, returns Q-based promise.'); + task('promise', function () { + return Q() + .then(function () { + console.log('bar:promise task'); + return 123654; + }); + }); + + desc('The bar:dependOnpromise task waits for a promise based async test'); + task('dependOnpromise', ['promise'], function () { + console.log('bar:dependOnpromise task saw value', jake.Task["bar:promise"].value); + }); + + desc('The bar:brokenPromise task is a failing Q-promise based async task.'); + task('brokenPromise', function () { + return Q() + .then(function () { + throw new Error("nom nom nom"); + }); + }); + + desc('The bar:bar task, has the async bar:foo task as a prerequisite.'); + task('bar', ['bar:foo'], function () { + console.log('bar:bar task'); + }); + +}); + +namespace('hoge', function () { + desc('The hoge:hoge task, has no prerequisites.'); + task('hoge', function () { + console.log('hoge:hoge task'); + }); + + desc('The hoge:piyo task, has no prerequisites.'); + task('piyo', function () { + console.log('hoge:piyo task'); + }); + + desc('The hoge:fuga task, has hoge:hoge and hoge:piyo as prerequisites.'); + task('fuga', ['hoge:hoge', 'hoge:piyo'], function () { + console.log('hoge:fuga task'); + }); + + desc('The hoge:charan task, has hoge:fuga as a prerequisite.'); + task('charan', ['hoge:fuga'], function () { + console.log('hoge:charan task'); + }); + + desc('The hoge:gero task, has hoge:fuga as a prerequisite.'); + task('gero', ['hoge:fuga'], function () { + console.log('hoge:gero task'); + }); + + desc('The hoge:kira task, has hoge:charan and hoge:gero as prerequisites.'); + task('kira', ['hoge:charan', 'hoge:gero'], function () { + console.log('hoge:kira task'); + }); + +}); + +namespace('fileTest', function () { + directory('foo'); + + desc('File task, concatenating two files together'); + file('foo/concat.txt', ['fileTest:foo', 'fileTest:foo/src1.txt', 'fileTest:foo/src2.txt'], function () { + console.log('fileTest:foo/concat.txt task'); + let data1 = fs.readFileSync('foo/src1.txt'); + let data2 = fs.readFileSync('foo/src2.txt'); + fs.writeFileSync('foo/concat.txt', data1 + data2); + }); + + desc('File task, async creation with writeFile'); + file('foo/src1.txt', function () { + return new Promise(function (resolve, reject) { + fs.writeFile('foo/src1.txt', 'src1', function (err) { + if (err) { + reject(err); + } + else { + console.log('fileTest:foo/src1.txt task'); + resolve(); + } + }); + }); + }); + + desc('File task, sync creation with writeFileSync'); + file('foo/src2.txt', ['default'], function () { + fs.writeFileSync('foo/src2.txt', 'src2'); + console.log('fileTest:foo/src2.txt task'); + }); + + desc('File task, do not run unless the prereq file changes'); + file('foo/from-src1.txt', ['fileTest:foo', 'fileTest:foo/src1.txt'], function () { + let data = fs.readFileSync('foo/src1.txt').toString(); + fs.writeFileSync('foo/from-src1.txt', data); + console.log('fileTest:foo/from-src1.txt task'); + }); + + desc('File task, run if the prereq file changes'); + task('touch-prereq', function () { + fs.writeFileSync('foo/prereq.txt', 'UPDATED'); + }) + + desc('File task, has a preexisting file (with no associated task) as a prereq'); + file('foo/from-prereq.txt', ['fileTest:foo', 'foo/prereq.txt'], function () { + let data = fs.readFileSync('foo/prereq.txt'); + fs.writeFileSync('foo/from-prereq.txt', data); + console.log('fileTest:foo/from-prereq.txt task'); + }); + + directory('foo/bar/baz'); + + desc('Write a file in a nested subdirectory'); + file('foo/bar/baz/bamf.txt', ['foo/bar/baz'], function () { + fs.writeFileSync('foo/bar/baz/bamf.txt', 'w00t'); + }); + +}); + +task('blammo'); +// Define task +task('voom', ['blammo'], function () { + console.log(this.prereqs.length); +}); + +// Modify, add a prereq +task('voom', ['noActionNoPrereqs']); + +namespace('vronk', function () { + task('groo', function () { + let t = jake.Task['vronk:zong']; + t.addListener('error', function (e) { + console.log(e.message); + }); + t.invoke(); + }); + task('zong', function () { + throw new Error('OMFGZONG'); + }); +}); + +// define namespace +namespace('one', function () { + task('one', function () { + console.log('one:one'); + }); +}); + +// modify namespace (add task) +namespace('one', function () { + task('two', ['one:one'], function () { + console.log('one:two'); + }); +}); + +task('selfdepconst', [], function () { + task('selfdep', ['selfdep'], function () { + console.log("I made a task that depends on itself"); + }); +}); +task('selfdepdyn', function () { + task('selfdeppar', [], {concurrency: 2}, function () { + console.log("I will depend on myself and will fail at runtime"); + }); + task('selfdeppar', ['selfdeppar']); + jake.Task['selfdeppar'].invoke(); +}); + +namespace("large", function () { + task("leaf", function () { + console.log("large:leaf"); + }); + + const same = []; + for (let i = 0; i < 2000; i++) { + same.push("leaf"); + } + + desc("Task with a large number of same prereqs"); + task("same", same, { concurrency: 2 }, function () { + console.log("large:same"); + }); + + const different = []; + for (let i = 0; i < 2000; i++) { + const name = "leaf-" + i; + task(name, function () { + if (name === "leaf-12" || name === "leaf-123") { + console.log(name); + } + }); + different.push(name); + } + + desc("Task with a large number of different prereqs"); + task("different", different, { concurrency: 2 } , function () { + console.log("large:different") + }) +}); diff --git a/node_modules/jake/test/integration/jakelib/concurrent.jake.js b/node_modules/jake/test/integration/jakelib/concurrent.jake.js new file mode 100644 index 0000000..684c86f --- /dev/null +++ b/node_modules/jake/test/integration/jakelib/concurrent.jake.js @@ -0,0 +1,113 @@ + +namespace('concurrent', function () { + task('A', function () { + console.log('Started A'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Finished A'); + resolve(); + }, 200); + }); + }); + + task('B', function () { + console.log('Started B'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Finished B'); + resolve(); + }, 50); + }); + }); + + task('C', function () { + console.log('Started C'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Finished C'); + resolve(); + }, 100); + }); + }); + + task('D', function () { + console.log('Started D'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Finished D'); + resolve(); + }, 300); + }); + }); + + task('Ba', ['A'], function () { + console.log('Started Ba'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Finished Ba'); + resolve(); + }, 50); + }); + }); + + task('Afail', function () { + console.log('Started failing task'); + return new Promise((resolve, reject) => { + setTimeout(() => { + console.log('Failing B with error'); + throw new Error('I failed'); + }, 50); + }); + }); + + task('simple1', ['A','B'], {concurrency: 2}, function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + + task('simple2', ['C','D'], {concurrency: 2}, function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + + task('seqconcurrent', ['simple1','simple2'], function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + + task('concurrentconcurrent', ['simple1','simple2'], {concurrency: 2}, function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + + task('subdep', ['A','Ba'], {concurrency: 2}, function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + + task('fail', ['A', 'B', 'Afail'], {concurrency: 3}, function () { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(); + }, 50); + }); + }); + +}); + + diff --git a/node_modules/jake/test/integration/jakelib/publish.jake.js b/node_modules/jake/test/integration/jakelib/publish.jake.js new file mode 100644 index 0000000..52dd04a --- /dev/null +++ b/node_modules/jake/test/integration/jakelib/publish.jake.js @@ -0,0 +1,49 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +let fs = require('fs'); +let { publishTask, rmRf, mkdirP } = require(`${PROJECT_DIR}/lib/jake`); + +fs.writeFileSync('package.json', '{"version": "0.0.1"}'); +mkdirP('tmp_publish'); +fs.writeFileSync('tmp_publish/foo.txt', 'FOO'); + +publishTask('zerb', function () { + this.packageFiles.include([ + 'package.json' + , 'tmp_publish/**' + ]); + this.publishCmd = 'node -p -e "\'%filename\'"'; + this.gitCmd = 'echo' + this.scheduleDelay = 0; + + this._ensureRepoClean = function () {}; + this._getCurrentBranch = function () { + return 'v0.0' + }; +}); + +jake.setTaskTimeout(5000); + +jake.Task['publish'].on('complete', function () { + rmRf('tmp_publish', {silent: true}); + rmRf('package.json', {silent: true}); +}); + diff --git a/node_modules/jake/test/integration/jakelib/required_module.jake.js b/node_modules/jake/test/integration/jakelib/required_module.jake.js new file mode 100644 index 0000000..c63751d --- /dev/null +++ b/node_modules/jake/test/integration/jakelib/required_module.jake.js @@ -0,0 +1,10 @@ +let { task, namespace } = require("jake"); + +namespace('usingRequire', function () { + task('test', () => { + console.log('howdy test'); + }); +}); + + + diff --git a/node_modules/jake/test/integration/jakelib/rule.jake.js b/node_modules/jake/test/integration/jakelib/rule.jake.js new file mode 100644 index 0000000..8e977dd --- /dev/null +++ b/node_modules/jake/test/integration/jakelib/rule.jake.js @@ -0,0 +1,222 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +let exec = require('child_process').execSync; +let fs = require('fs'); +let util = require('util'); +let { rule, rmRf } = require(`${PROJECT_DIR}/lib/jake`); + +directory('tmpsrc'); +directory('tmpbin'); + +//////////////////////////////////////////////////////////// +// Simple Suffix Rule +file('tmp', ['tmp_init', 'tmp_dep1.o', 'tmp_dep2.o'], function (params) { + console.log('tmp task'); + let data1 = fs.readFileSync('tmp_dep1.o'); + let data2 = fs.readFileSync('tmp_dep2.o'); + fs.writeFileSync('tmp', data1 + data2); +}); + +rule('.o', '.c', function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' task'); + exec(cmd); +}); + +file('tmp_dep1.c', function () { + fs.writeFileSync('tmp_dep1.c', 'src_1'); + console.log('tmp_dep1.c task'); +}); + +// note that tmp_dep2.o depends on tmp_dep2.c, which is a +// static file. +task('tmp_init', function () { + fs.writeFileSync('tmp_dep2.c', 'src_2'); + console.log('tmp_dep2.c task'); +}); +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// Pattern Rule +file('tmp_p', ['tmp_init', 'tmp_dep1.oo', 'tmp_dep2.oo'], function (params) { + console.log('tmp pattern task'); + let data1 = fs.readFileSync('tmp_dep1.oo'); + let data2 = fs.readFileSync('tmp_dep2.oo'); + fs.writeFileSync('tmp_p', data1 + data2 + ' pattern'); +}); + +rule('%.oo', '%.c', function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' task'); + exec(cmd); +}); +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// Pattern Rule with Folder +// i.e. rule('tmpbin/%.oo', 'tmpsrc/%.c', ... +file('tmp_pf', [ + 'tmp_src_init' + , 'tmpbin' + , 'tmpbin/tmp_dep1.oo' + , 'tmpbin/tmp_dep2.oo' ], function (params) { + console.log('tmp pattern folder task'); + let data1 = fs.readFileSync('tmpbin/tmp_dep1.oo'); + let data2 = fs.readFileSync('tmpbin/tmp_dep2.oo'); + fs.writeFileSync('tmp_pf', data1 + data2 + ' pattern folder'); +}); + +rule('tmpbin/%.oo', 'tmpsrc/%.c', function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' task'); + exec(cmd); +}); + +file('tmpsrc/tmp_dep2.c',['tmpsrc'], function () { + fs.writeFileSync('tmpsrc/tmp_dep2.c', 'src/src_2'); + console.log('tmpsrc/tmp_dep2.c task'); +}); + +// Create static files in folder tmpsrc. +task('tmp_src_init', ['tmpsrc'], function () { + fs.writeFileSync('tmpsrc/tmp_dep1.c', 'src/src_1'); + console.log('tmpsrc/tmp_dep1.c task'); +}); +//////////////////////////////////////////////////////////// + + +//////////////////////////////////////////////////////////// +// Namespace Test. This is a Mixed Test. +// Test for +// - rules belonging to different namespace. +// - rules with folder and pattern +task('tmp_ns', [ + 'tmpbin' + , 'rule:init' + , 'tmpbin/tmp_dep2.oo' // *** This relies on a rule defined before. + , 'rule:tmpbin/dep1.oo' + , 'rule:tmpbin/file2.oo' ], function () { + console.log('tmp pattern folder namespace task'); + let data1 = fs.readFileSync('tmpbin/dep1.oo'); + let data2 = fs.readFileSync('tmpbin/tmp_dep2.oo'); + let data3 = fs.readFileSync('tmpbin/file2.oo'); + fs.writeFileSync('tmp_ns', data1 + data2 + data3 + ' pattern folder namespace'); +}); + +namespace('rule', function () { + task('init', ['tmpsrc'], function () { + fs.writeFileSync('tmpsrc/file2.c', 'src/src_3'); + console.log('tmpsrc/file2.c init task'); + }); + + file('tmpsrc/dep1.c',['tmpsrc'], function () { + fs.writeFileSync('tmpsrc/dep1.c', 'src/src_1'); + console.log('tmpsrc/dep1.c task'); + }, {async: true}); + + rule('tmpbin/%.oo', 'tmpsrc/%.c', function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' ns task'); + exec(cmd); + }); +}); +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// Chain rule +// rule('tmpbin/%.pdf', 'tmpbin/%.dvi', function() { ... +// rule('tmpbin/%.dvi', 'tmpsrc/%.tex', ['tmpbin'], function() { ... +task('tmp_cr', [ + 'chainrule:init' + , 'chainrule:tmpbin/file1.pdf' + , 'chainrule:tmpbin/file2.pdf' ], function () { + console.log('tmp chainrule namespace task'); + let data1 = fs.readFileSync('tmpbin/file1.pdf'); + let data2 = fs.readFileSync('tmpbin/file2.pdf'); + fs.writeFileSync('tmp_cr', data1 + data2 + ' chainrule namespace'); +}); + +namespace('chainrule', function () { + task('init', ['tmpsrc', 'tmpbin'], function () { + fs.writeFileSync('tmpsrc/file1.tex', 'tex1 '); + fs.writeFileSync('tmpsrc/file2.tex', 'tex2 '); + console.log('chainrule init task'); + }); + + rule('tmpbin/%.pdf', 'tmpbin/%.dvi', function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' dvi->pdf task'); + exec(cmd); + }); + + rule('tmpbin/%.dvi', 'tmpsrc/%.tex', ['tmpbin'], function () { + let cmd = util.format('cp %s %s', this.source, this.name); + console.log(cmd + ' tex->dvi task'); + exec(cmd); + }); +}); +//////////////////////////////////////////////////////////// +namespace('precedence', function () { + task('test', ['foo.html'], function () { + console.log('ran test'); + }); + + rule('.html', '.txt', function () { + console.log('created html'); + let data = fs.readFileSync(this.source); + fs.writeFileSync(this.name, data.toString()); + }); +}); + +namespace('regexPattern', function () { + task('test', ['foo.html'], function () { + console.log('ran test'); + }); + + rule(/\.html$/, '.txt', function () { + console.log('created html'); + let data = fs.readFileSync(this.source); + fs.writeFileSync(this.name, data.toString()); + }); +}); + +namespace('sourceFunction', function () { + + let srcFunc = function (taskName) { + return taskName.replace(/\.[^.]+$/, '.txt'); + }; + + task('test', ['foo.html'], function () { + console.log('ran test'); + }); + + rule('.html', srcFunc, function () { + console.log('created html'); + let data = fs.readFileSync(this.source); + fs.writeFileSync(this.name, data.toString()); + }); +}); + +//////////////////////////////////////////////////////////// +task('clean', function () { + rmRf('./foo'); + rmRf('./tmp'); +}); diff --git a/node_modules/jake/test/integration/publish_task.js b/node_modules/jake/test/integration/publish_task.js new file mode 100644 index 0000000..034fd94 --- /dev/null +++ b/node_modules/jake/test/integration/publish_task.js @@ -0,0 +1,24 @@ +let assert = require('assert'); +let exec = require('child_process').execSync; + +suite('publishTask', function () { + + this.timeout(7000); + + test('default task', function () { + let out = exec('./node_modules/.bin/jake -q publish').toString().trim(); + let expected = [ + 'Fetched remote tags.' + , 'On branch v0.0' + , 'Bumped version number to v0.0.2.' + , 'Created package for zerb v0.0.2' + , 'Publishing zerb v0.0.2' + , './pkg/zerb-v0.0.2.tar.gz' + , 'BOOM! Published.' + , 'Cleaned up package' + ].join('\n'); + assert.equal(expected, out); + }); + +}); + diff --git a/node_modules/jake/test/integration/rule.js b/node_modules/jake/test/integration/rule.js new file mode 100644 index 0000000..b837b1d --- /dev/null +++ b/node_modules/jake/test/integration/rule.js @@ -0,0 +1,216 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +let assert = require('assert'); +let exec = require('child_process').execSync; +let fs = require('fs'); +let { Rule } = require(`${PROJECT_DIR}/lib/rule`); +let { rmRf } = require(`${PROJECT_DIR}/lib/jake`); + +let cleanUpAndNext = function (callback) { + // Gotta add globbing to file utils rmRf + let tmpFiles = [ + 'tmp' + , 'tmp_ns' + , 'tmp_cr' + , 'tmp_p' + , 'tmp_pf' + , 'tmpbin' + , 'tmpsrc' + , 'tmp_dep1.c' + , 'tmp_dep1.o' + , 'tmp_dep1.oo' + , 'tmp_dep2.c' + , 'tmp_dep2.o' + , 'tmp_dep2.oo' + , 'foo' + , 'foo.html' + ]; + tmpFiles.forEach(function (f) { + rmRf(f, { + silent: true + }); + }); + callback && callback(); +}; + +suite('rule', function () { + + this.timeout(7000); + + setup(function (next) { + cleanUpAndNext(next); + }); + + + // - name foo:bin/main.o + // - pattern bin/%.o + // - source src/%.c + // + // return { + // 'dep' : 'foo:src/main.c', + // 'file': 'src/main.c' + // }; + test('Rule.getSource', function () { + let src = Rule.getSource('foo:bin/main.o', 'bin/%.o', 'src/%.c'); + assert.equal('foo:src/main.c', src); + }); + + test('rule w/o pattern', function () { + let out = exec( './node_modules/.bin/jake -q tmp').toString().trim(); + let output = [ + "tmp_dep2.c task" + , "tmp_dep1.c task" + , "cp tmp_dep1.c tmp_dep1.o task" + , "cp tmp_dep2.c tmp_dep2.o task" + , "tmp task"]; + assert.equal( output.join('\n'), out); + let data = fs.readFileSync(process.cwd() + '/tmp'); + assert.equal('src_1src_2', data.toString()); + cleanUpAndNext(); + }); + + test('rule w pattern w/o folder w/o namespace', function () { + let out = exec( './node_modules/.bin/jake -q tmp_p').toString().trim(); + let output = [ + "tmp_dep2.c task" + , "tmp_dep1.c task" + , "cp tmp_dep1.c tmp_dep1.oo task" + , "cp tmp_dep2.c tmp_dep2.oo task" + , "tmp pattern task"]; + let data; + assert.equal( output.join('\n'), out); + data = fs.readFileSync(process.cwd() + '/tmp_p'); + assert.equal('src_1src_2 pattern', data.toString()); + cleanUpAndNext(); + }); + + test('rule w pattern w folder w/o namespace', function () { + let out = exec( './node_modules/.bin/jake -q tmp_pf').toString().trim(); + let output = [ + "tmpsrc/tmp_dep1.c task" + , "cp tmpsrc/tmp_dep1.c tmpbin/tmp_dep1.oo task" + , "tmpsrc/tmp_dep2.c task" + , "cp tmpsrc/tmp_dep2.c tmpbin/tmp_dep2.oo task" + , "tmp pattern folder task"]; + let data; + assert.equal( output.join('\n'), out); + data = fs.readFileSync(process.cwd() + '/tmp_pf'); + assert.equal('src/src_1src/src_2 pattern folder', data.toString()); + cleanUpAndNext(); + }); + + test.skip('rule w pattern w folder w namespace', function () { + let out = exec( './node_modules/.bin/jake -q tmp_ns').toString().trim(); + let output = [ + "tmpsrc/file2.c init task" // yes + , "tmpsrc/tmp_dep2.c task" // no + , "cp tmpsrc/tmp_dep2.c tmpbin/tmp_dep2.oo task" // no + , "tmpsrc/dep1.c task" // no + , "cp tmpsrc/dep1.c tmpbin/dep1.oo ns task" // no + , "cp tmpsrc/file2.c tmpbin/file2.oo ns task" // yes + , "tmp pattern folder namespace task"]; // yes + let data; + assert.equal( output.join('\n'), out); + data = fs.readFileSync(process.cwd() + '/tmp_ns'); + assert.equal('src/src_1src/src_2src/src_3 pattern folder namespace', data.toString()); + cleanUpAndNext(); + }); + + test.skip('rule w chain w pattern w folder w namespace', function () { + let out = exec( './node_modules/.bin/jake -q tmp_cr').toString().trim(); + let output = [ + "chainrule init task" + , "cp tmpsrc/file1.tex tmpbin/file1.dvi tex->dvi task" + , "cp tmpbin/file1.dvi tmpbin/file1.pdf dvi->pdf task" + , "cp tmpsrc/file2.tex tmpbin/file2.dvi tex->dvi task" + , "cp tmpbin/file2.dvi tmpbin/file2.pdf dvi->pdf task" + , "tmp chainrule namespace task"]; + let data; + assert.equal( output.join('\n'), out); + data = fs.readFileSync(process.cwd() + '/tmp_cr'); + assert.equal('tex1 tex2 chainrule namespace', data.toString()); + cleanUpAndNext(); + }); + + + ['precedence', 'regexPattern', 'sourceFunction'].forEach(function (key) { + + test('rule with source file not created yet (' + key + ')', function () { + let write = process.stderr.write; + process.stderr.write = () => {}; + rmRf('foo.txt', {silent: true}); + rmRf('foo.html', {silent: true}); + try { + exec('./node_modules/.bin/jake ' + key + ':test'); + } + catch(err) { + // foo.txt prereq doesn't exist yet + assert.ok(err.message.indexOf('Unknown task "foo.html"') > -1); + } + process.stderr.write = write; + }); + + test('rule with source file now created (' + key + ')', function () { + fs.writeFileSync('foo.txt', ''); + let out = exec('./node_modules/.bin/jake -q ' + key + ':test').toString().trim(); + // Should run prereq and test task + let output = [ + 'created html' + , 'ran test' + ]; + assert.equal(output.join('\n'), out); + }); + + test('rule with source file modified (' + key + ')', function (next) { + setTimeout(function () { + fs.writeFileSync('foo.txt', ''); + let out = exec('./node_modules/.bin/jake -q ' + key + ':test').toString().trim(); + // Should again run both prereq and test task + let output = [ + 'created html' + , 'ran test' + ]; + assert.equal(output.join('\n'), out); + //next(); + cleanUpAndNext(next); + }, 1000); // Wait to do the touch to ensure mod-time is different + }); + + test('rule with existing objective file and no source ' + + ' (should be normal file-task) (' + key + ')', function () { + // Remove just the source file + fs.writeFileSync('foo.html', ''); + rmRf('foo.txt', {silent: true}); + let out = exec('./node_modules/.bin/jake -q ' + key + ':test').toString().trim(); + // Should treat existing objective file as plain file-task, + // and just run test-task + let output = [ + 'ran test' + ]; + assert.equal(output.join('\n'), out); + cleanUpAndNext(); + }); + + }); + +}); + + diff --git a/node_modules/jake/test/integration/selfdep.js b/node_modules/jake/test/integration/selfdep.js new file mode 100644 index 0000000..22d58d1 --- /dev/null +++ b/node_modules/jake/test/integration/selfdep.js @@ -0,0 +1,39 @@ +let assert = require('assert'); +let exec = require('child_process').execSync; + +suite('selfDep', function () { + + this.timeout(7000); + + let origStderrWrite; + + setup(function () { + origStderrWrite = process.stderr.write; + process.stderr.write = function () {}; + }); + + teardown(function () { + process.stderr.write = origStderrWrite; + }); + + test('self dep const', function () { + try { + exec('./node_modules/.bin/jake selfdepconst'); + } + catch(e) { + assert(e.message.indexOf('dependency of itself') > -1) + } + }); + + test('self dep dyn', function () { + try { + exec('./node_modules/.bin/jake selfdepdyn'); + } + catch(e) { + assert(e.message.indexOf('dependency of itself') > -1) + } + }); + +}); + + diff --git a/node_modules/jake/test/integration/task_base.js b/node_modules/jake/test/integration/task_base.js new file mode 100644 index 0000000..36e20e8 --- /dev/null +++ b/node_modules/jake/test/integration/task_base.js @@ -0,0 +1,164 @@ +let assert = require('assert'); +let h = require('./helpers'); +let exec = require('child_process').execSync; + +suite('taskBase', function () { + + this.timeout(7000); + + test('default task', function () { + let out; + out = exec('./node_modules/.bin/jake -q').toString().trim(); + assert.equal(out, 'default task'); + out = exec('./node_modules/.bin/jake -q default').toString().trim(); + assert.equal(out, 'default task'); + }); + + test('task with no action', function () { + let out = exec('./node_modules/.bin/jake -q noAction').toString().trim(); + assert.equal(out, 'default task'); + }); + + test('a task with no action and no prereqs', function () { + exec('./node_modules/.bin/jake noActionNoPrereqs'); + }); + + test('a task that exists at the top-level, and not in the specified namespace, should error', function () { + let res = require('child_process').spawnSync('./node_modules/.bin/jake', + ['asdfasdfasdf:zerbofrangazoomy']); + let err = res.stderr.toString(); + assert.ok(err.indexOf('Unknown task' > -1)); + }); + + test('passing args to a task', function () { + let out = exec('./node_modules/.bin/jake -q argsEnvVars[foo,bar]').toString().trim(); + let parsed = h.parse(out); + let args = parsed.args; + assert.equal(args[0], 'foo'); + assert.equal(args[1], 'bar'); + }); + + test('a task with environment vars', function () { + let out = exec('./node_modules/.bin/jake -q argsEnvVars foo=bar baz=qux').toString().trim(); + let parsed = h.parse(out); + let env = parsed.env; + assert.equal(env.foo, 'bar'); + assert.equal(env.baz, 'qux'); + }); + + test('passing args and using environment vars', function () { + let out = exec('./node_modules/.bin/jake -q argsEnvVars[foo,bar] foo=bar baz=qux').toString().trim(); + let parsed = h.parse(out); + let args = parsed.args; + let env = parsed.env; + assert.equal(args[0], 'foo'); + assert.equal(args[1], 'bar'); + assert.equal(env.foo, 'bar'); + assert.equal(env.baz, 'qux'); + }); + + test('a simple prereq', function () { + let out = exec('./node_modules/.bin/jake -q foo:baz').toString().trim(); + assert.equal(out, 'foo:bar task\nfoo:baz task'); + }); + + test('a duplicate prereq only runs once', function () { + let out = exec('./node_modules/.bin/jake -q foo:asdf').toString().trim(); + assert.equal(out, 'foo:bar task\nfoo:baz task\nfoo:asdf task'); + }); + + test('a prereq with command-line args', function () { + let out = exec('./node_modules/.bin/jake -q foo:qux').toString().trim(); + assert.equal(out, 'foo:bar[asdf,qwer] task\nfoo:qux task'); + }); + + test('a prereq with args via invoke', function () { + let out = exec('./node_modules/.bin/jake -q foo:frang[zxcv,uiop]').toString().trim(); + assert.equal(out, 'foo:bar[zxcv,uiop] task\nfoo:frang task'); + }); + + test('a prereq with args via execute', function () { + let out = exec('./node_modules/.bin/jake -q foo:zerb[zxcv,uiop]').toString().trim(); + assert.equal(out, 'foo:bar[zxcv,uiop] task\nfoo:zerb task'); + }); + + test('repeating the task via execute', function () { + let out = exec('./node_modules/.bin/jake -q foo:voom').toString().trim(); + assert.equal(out, 'foo:bar task\nfoo:bar task\ncomplete\ncomplete'); + }); + + test('prereq execution-order', function () { + let out = exec('./node_modules/.bin/jake -q hoge:fuga').toString().trim(); + assert.equal(out, 'hoge:hoge task\nhoge:piyo task\nhoge:fuga task'); + }); + + test('basic async task', function () { + let out = exec('./node_modules/.bin/jake -q bar:bar').toString().trim(); + assert.equal(out, 'bar:foo task\nbar:bar task'); + }); + + test('promise async task', function () { + let out = exec('./node_modules/.bin/jake -q bar:dependOnpromise').toString().trim(); + assert.equal(out, 'bar:promise task\nbar:dependOnpromise task saw value 123654'); + }); + + test('failing promise async task', function () { + try { + exec('./node_modules/.bin/jake -q bar:brokenPromise'); + } + catch(e) { + assert(e.message.indexOf('Command failed') > -1); + } + }); + + test('that current-prereq index gets reset', function () { + let out = exec('./node_modules/.bin/jake -q hoge:kira').toString().trim(); + assert.equal(out, 'hoge:hoge task\nhoge:piyo task\nhoge:fuga task\n' + + 'hoge:charan task\nhoge:gero task\nhoge:kira task'); + }); + + test('modifying a task by adding prereq during execution', function () { + let out = exec('./node_modules/.bin/jake -q voom').toString().trim(); + assert.equal(out, 2); + }); + + test('listening for task error-event', function () { + try { + exec('./node_modules/.bin/jake -q vronk:groo').toString().trim(); + } + catch(e) { + assert(e.message.indexOf('OMFGZONG') > -1); + } + }); + + test('listening for jake error-event', function () { + let out = exec('./node_modules/.bin/jake -q throwy').toString().trim(); + assert(out.indexOf('Emitted\nError: I am bad') > -1); + }); + + test('listening for jake unhandledRejection-event', function () { + let out = exec('./node_modules/.bin/jake -q promiseRejecter').toString().trim(); + assert.equal(out, ''); + }); + + test('large number of same prereqs', function () { + let out = exec('./node_modules/.bin/jake -q large:same').toString().trim(); + assert.equal(out, 'large:leaf\nlarge:same'); + }); + + test('large number of different prereqs', function () { + let out = exec('./node_modules/.bin/jake -q large:different').toString().trim(); + assert.equal(out, 'leaf-12\nleaf-123\nlarge:different'); + }); + + test('large number of different prereqs', function () { + let out = exec('./node_modules/.bin/jake -q usingRequire:test').toString().trim(); + assert.equal(out, 'howdy test'); + }); + + test('modifying a namespace by adding a new task', function () { + let out = exec('./node_modules/.bin/jake -q one:two').toString().trim(); + assert.equal('one:one\none:two', out); + }); + +}); diff --git a/node_modules/jake/test/unit/jakefile.js b/node_modules/jake/test/unit/jakefile.js new file mode 100644 index 0000000..89ff523 --- /dev/null +++ b/node_modules/jake/test/unit/jakefile.js @@ -0,0 +1,36 @@ + +task('foo', function () { + console.log('ran top-level foo'); +}); + +task('bar', function () { + console.log('ran top-level bar'); +}); + +task('zerb', function () { + console.log('ran zerb'); +}); + +namespace('zooby', function () { + task('zerp', function () {}); + + task('derp', ['zerp'], function () {}); + + namespace('frang', function () { + + namespace('w00t', function () { + task('bar', function () { + console.log('ran zooby:frang:w00t:bar'); + }); + }); + + task('asdf', function () {}); + }); + +}); + +namespace('hurr', function () { + namespace('durr'); +}); + + diff --git a/node_modules/jake/test/unit/namespace.js b/node_modules/jake/test/unit/namespace.js new file mode 100644 index 0000000..c6b3ff5 --- /dev/null +++ b/node_modules/jake/test/unit/namespace.js @@ -0,0 +1,77 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +// Load the jake global +require(`${PROJECT_DIR}/lib/jake`); +let { Namespace } = require(`${PROJECT_DIR}/lib/namespace`); + +require('./jakefile'); + +let assert = require('assert'); + +suite('namespace', function () { + + this.timeout(7000); + + test('resolve namespace by relative name', function () { + let aaa, bbb, ccc; + aaa = namespace('aaa', function () { + bbb = namespace('bbb', function () { + ccc = namespace('ccc', function () { + }); + }); + }); + + assert.ok(aaa, Namespace.ROOT_NAMESPACE.resolveNamespace('aaa')); + assert.ok(bbb === aaa.resolveNamespace('bbb')); + assert.ok(ccc === aaa.resolveNamespace('bbb:ccc')); + }); + + test('resolve task in sub-namespace by relative path', function () { + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby'); + let task = curr.resolveTask('frang:w00t:bar'); + assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1); + }); + + test('prefer local to top-level', function () { + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby:frang:w00t'); + let task = curr.resolveTask('bar'); + assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1); + }); + + test('does resolve top-level', function () { + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby:frang:w00t'); + let task = curr.resolveTask('foo'); + assert.ok(task.action.toString().indexOf('top-level foo') > -1); + }); + + test('absolute lookup works from sub-namespaces', function () { + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('hurr:durr'); + let task = curr.resolveTask('zooby:frang:w00t:bar'); + assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1); + }); + + test('resolution miss with throw error', function () { + let curr = Namespace.ROOT_NAMESPACE; + let task = curr.resolveTask('asdf:qwer'); + assert.ok(!task); + }); + +}); diff --git a/node_modules/jake/test/unit/parseargs.js b/node_modules/jake/test/unit/parseargs.js new file mode 100644 index 0000000..7a3ddd5 --- /dev/null +++ b/node_modules/jake/test/unit/parseargs.js @@ -0,0 +1,169 @@ +/* + * Jake JavaScript build tool + * Copyright 2112 Matthew Eernisse (mde@fleegix.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +const PROJECT_DIR = process.env.PROJECT_DIR; + +let parseargs = require(`${PROJECT_DIR}/lib/parseargs`); +let assert = require('assert'); +let optsReg = [ + { full: 'directory', + abbr: 'C', + preempts: false, + expectValue: true + }, + { full: 'jakefile', + abbr: 'f', + preempts: false, + expectValue: true + }, + { full: 'tasks', + abbr: 'T', + preempts: true + }, + { full: 'tasks', + abbr: 'ls', + preempts: true + }, + { full: 'trace', + abbr: 't', + preempts: false, + expectValue: false + }, + { full: 'help', + abbr: 'h', + preempts: true + }, + { full: 'version', + abbr: 'V', + preempts: true + } +]; +let p = new parseargs.Parser(optsReg); +let z = function (s) { return s.split(' '); }; +let res; + +suite('parseargs', function () { + + test('long preemptive opt and val with equal-sign, ignore further opts', function () { + res = p.parse(z('--tasks=foo --jakefile=asdf')); + assert.equal('foo', res.opts.tasks); + assert.equal(undefined, res.opts.jakefile); + }); + + test('long preemptive opt and val without equal-sign, ignore further opts', function () { + res = p.parse(z('--tasks foo --jakefile=asdf')); + assert.equal('foo', res.opts.tasks); + assert.equal(undefined, res.opts.jakefile); + }); + + test('long preemptive opt and no val, ignore further opts', function () { + res = p.parse(z('--tasks --jakefile=asdf')); + assert.equal(true, res.opts.tasks); + assert.equal(undefined, res.opts.jakefile); + }); + + test('preemptive opt with no val, should be true', function () { + res = p.parse(z('-T')); + assert.equal(true, res.opts.tasks); + }); + + test('preemptive opt with no val, should be true and ignore further opts', function () { + res = p.parse(z('-T -f')); + assert.equal(true, res.opts.tasks); + assert.equal(undefined, res.opts.jakefile); + }); + + test('preemptive opt with val, should be val', function () { + res = p.parse(z('-T zoobie -f foo/bar/baz')); + assert.equal('zoobie', res.opts.tasks); + assert.equal(undefined, res.opts.jakefile); + }); + + test('-f expects a value, -t does not (howdy is task-name)', function () { + res = p.parse(z('-f zoobie -t howdy')); + assert.equal('zoobie', res.opts.jakefile); + assert.equal(true, res.opts.trace); + assert.equal('howdy', res.taskNames[0]); + }); + + test('different order, -f expects a value, -t does not (howdy is task-name)', function () { + res = p.parse(z('-f zoobie howdy -t')); + assert.equal('zoobie', res.opts.jakefile); + assert.equal(true, res.opts.trace); + assert.equal('howdy', res.taskNames[0]); + }); + + test('-f expects a value, -t does not (foo=bar is env var)', function () { + res = p.parse(z('-f zoobie -t foo=bar')); + assert.equal('zoobie', res.opts.jakefile); + assert.equal(true, res.opts.trace); + assert.equal('bar', res.envVars.foo); + assert.equal(undefined, res.taskNames[0]); + }); + + test('-f expects a value, -t does not (foo=bar is env-var, task-name follows)', function () { + res = p.parse(z('-f zoobie -t howdy foo=bar')); + assert.equal('zoobie', res.opts.jakefile); + assert.equal(true, res.opts.trace); + assert.equal('bar', res.envVars.foo); + assert.equal('howdy', res.taskNames[0]); + }); + + test('-t does not expect a value, -f does (howdy is task-name)', function () { + res = p.parse(z('-t howdy -f zoobie')); + assert.equal(true, res.opts.trace); + assert.equal('zoobie', res.opts.jakefile); + assert.equal('howdy', res.taskNames[0]); + }); + + test('--trace does not expect a value, -f does (howdy is task-name)', function () { + res = p.parse(z('--trace howdy --jakefile zoobie')); + assert.equal(true, res.opts.trace); + assert.equal('zoobie', res.opts.jakefile); + assert.equal('howdy', res.taskNames[0]); + }); + + test('--trace does not expect a value (equal), -f does (throw howdy away)', function () { + res = p.parse(z('--trace=howdy --jakefile=zoobie')); + assert.equal(true, res.opts.trace); + assert.equal('zoobie', res.opts.jakefile); + assert.equal(undefined, res.taskNames[0]); + }); + + /* +, test('task-name with positional args', function () { + res = p.parse(z('foo:bar[asdf,qwer]')); + assert.equal('asdf', p.taskArgs[0]); + assert.equal('qwer', p.taskArgs[1]); + } + +, test('opts, env vars, task-name with positional args', function () { + res = p.parse(z('-f ./tests/Jakefile -t default[asdf,qwer] foo=bar')); + assert.equal('./tests/Jakefile', res.opts.jakefile); + assert.equal(true, res.opts.trace); + assert.equal('bar', res.envVars.foo); + assert.equal('default', res.taskName); + assert.equal('asdf', p.taskArgs[0]); + assert.equal('qwer', p.taskArgs[1]); + } +*/ + + +}); + + diff --git a/node_modules/jake/usage.txt b/node_modules/jake/usage.txt new file mode 100644 index 0000000..392b6d8 --- /dev/null +++ b/node_modules/jake/usage.txt @@ -0,0 +1,16 @@ +Jake JavaScript build tool +******************************************************************************** +If no flags are given, Jake looks for a Jakefile or Jakefile.js in the current directory. +******************************************************************************** +{Usage}: jake [options ...] [env variables ...] target + +{Options}: + -f, --jakefile FILE Use FILE as the Jakefile. + -C, --directory DIRECTORY Change to DIRECTORY before running tasks. + -B, --always-make Unconditionally make all targets. + -T/ls, --tasks Display the tasks (matching optional PATTERN) with descriptions, then exit. + -J, --jakelibdir JAKELIBDIR Auto-import any .jake files in JAKELIBDIR. (default is \'jakelib\') + -h, --help Display this help message. + -V/v, --version Display the Jake version. + -ar, --allow-rejection Keep running even after unhandled promise rejection + 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 (?:) + 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..a5898b8 --- /dev/null +++ b/node_modules/minimatch/package.json @@ -0,0 +1,64 @@ +{ + "_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": [ + "/filelist", + "/jake" + ], + "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "_shasum": "5166e286457f03306064be5497e8dbb0c3d32083", + "_spec": "minimatch@^3.0.4", + "_where": "C:\\angel\\node_modules\\jake", + "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/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..1704131 --- /dev/null +++ b/node_modules/supports-color/index.js @@ -0,0 +1,131 @@ +'use strict'; +const os = require('os'); +const hasFlag = require('has-flag'); + +const env = process.env; + +let forceColor; +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, + 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; + } + + const 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. + const 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(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 (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; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; 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.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..e6c39c8 --- /dev/null +++ b/node_modules/supports-color/package.json @@ -0,0 +1,85 @@ +{ + "_from": "supports-color@^5.3.0", + "_id": "supports-color@5.5.0", + "_inBundle": false, + "_integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "_location": "/supports-color", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "supports-color@^5.3.0", + "name": "supports-color", + "escapedName": "supports-color", + "rawSpec": "^5.3.0", + "saveSpec": null, + "fetchSpec": "^5.3.0" + }, + "_requiredBy": [ + "/chalk" + ], + "_resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "_shasum": "e2e69a44ac8772f78a1ec0b35b689df6530efc8f", + "_spec": "supports-color@^5.3.0", + "_where": "C:\\angel\\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": "^3.0.0" + }, + "deprecated": false, + "description": "Detect whether a terminal supports color", + "devDependencies": { + "ava": "^0.25.0", + "import-fresh": "^2.0.0", + "xo": "^0.20.0" + }, + "engines": { + "node": ">=4" + }, + "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": "5.5.0" +} diff --git a/node_modules/supports-color/readme.md b/node_modules/supports-color/readme.md new file mode 100644 index 0000000..f6e4019 --- /dev/null +++ b/node_modules/supports-color/readme.md @@ -0,0 +1,66 @@ +# 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. + +Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, add the environment variable `FORCE_COLOR=1` 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-) + + +## License + +MIT diff --git a/package-lock.json b/package-lock.json index 0166c79..f5d131c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,11 +13,29 @@ "negotiator": "0.6.2" } }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, "array-flatten": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" }, + "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=" + }, "bignumber.js": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.0.tgz", @@ -40,6 +58,15 @@ "type-is": "~1.6.17" } }, + "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" + } + }, "buffer-equal-constant-time": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", @@ -50,6 +77,34 @@ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==" }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + }, "content-disposition": { "version": "0.5.3", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", @@ -109,6 +164,14 @@ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" }, + "ejs": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.3.tgz", + "integrity": "sha512-wmtrUGyfSC23GC/B1SMv2ogAUgbQEtDmTIhfqielrG5ExIM9TP4UoYdi90jLF1aTcsWCJNEO0UrgKzP0y3nTSg==", + "requires": { + "jake": "^10.6.1" + } + }, "encodeurl": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", @@ -119,6 +182,11 @@ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, "etag": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", @@ -161,6 +229,14 @@ "vary": "~1.1.2" } }, + "filelist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.1.tgz", + "integrity": "sha512-8zSK6Nu0DQIC08mUC46sWGXi+q3GGpKydAG36k+JDba6VRpkevvOWUW5a/PhShij4+vHT9M+ghgG7eM+a9JDUQ==", + "requires": { + "minimatch": "^3.0.4" + } + }, "finalhandler": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", @@ -185,6 +261,11 @@ "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + }, "http-errors": { "version": "1.7.2", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", @@ -220,6 +301,17 @@ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" }, + "jake": { + "version": "10.8.2", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.8.2.tgz", + "integrity": "sha512-eLpKyrfG3mzvGE2Du8VoPbeSkRry093+tyNjdYaBbJS9v17knImYGNXQCUV0gLxQtF82m3E8iRb/wdSQZLoq7A==", + "requires": { + "async": "0.9.x", + "chalk": "^2.4.2", + "filelist": "^1.0.1", + "minimatch": "^3.0.4" + } + }, "jsonwebtoken": { "version": "8.5.1", "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", @@ -331,6 +423,14 @@ "mime-db": "1.44.0" } }, + "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" + } + }, "ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", @@ -509,6 +609,14 @@ "safe-buffer": "~5.1.0" } }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + }, "toidentifier": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", diff --git a/package.json b/package.json index 6db8546..4b05444 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "homepage": "https://github.com/juju-0/angel#readme", "dependencies": { "body-parser": "^1.19.0", + "ejs": "^3.1.3", "express": "^4.17.1", "jsonwebtoken": "^8.5.1", "mysql": "^2.18.1", diff --git a/views/signup.ejs b/views/signup.ejs new file mode 100644 index 0000000..7163143 --- /dev/null +++ b/views/signup.ejs @@ -0,0 +1 @@ +dkfldnfldfnsofsn \ No newline at end of file