공태현

Routing HTML File on server.js

Showing 266 changed files with 29660 additions and 2 deletions
1 +#!/bin/sh
2 +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3 +
4 +case `uname` in
5 + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
6 +esac
7 +
8 +if [ -x "$basedir/node" ]; then
9 + "$basedir/node" "$basedir/../ejs/bin/cli.js" "$@"
10 + ret=$?
11 +else
12 + node "$basedir/../ejs/bin/cli.js" "$@"
13 + ret=$?
14 +fi
15 +exit $ret
1 +@ECHO off
2 +SETLOCAL
3 +CALL :find_dp0
4 +
5 +IF EXIST "%dp0%\node.exe" (
6 + SET "_prog=%dp0%\node.exe"
7 +) ELSE (
8 + SET "_prog=node"
9 + SET PATHEXT=%PATHEXT:;.JS;=;%
10 +)
11 +
12 +"%_prog%" "%dp0%\..\ejs\bin\cli.js" %*
13 +ENDLOCAL
14 +EXIT /b %errorlevel%
15 +:find_dp0
16 +SET dp0=%~dp0
17 +EXIT /b
1 +#!/usr/bin/env pwsh
2 +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
3 +
4 +$exe=""
5 +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
6 + # Fix case when both the Windows and Linux builds of Node
7 + # are installed in the same directory
8 + $exe=".exe"
9 +}
10 +$ret=0
11 +if (Test-Path "$basedir/node$exe") {
12 + & "$basedir/node$exe" "$basedir/../ejs/bin/cli.js" $args
13 + $ret=$LASTEXITCODE
14 +} else {
15 + & "node$exe" "$basedir/../ejs/bin/cli.js" $args
16 + $ret=$LASTEXITCODE
17 +}
18 +exit $ret
1 +#!/bin/sh
2 +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3 +
4 +case `uname` in
5 + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
6 +esac
7 +
8 +if [ -x "$basedir/node" ]; then
9 + "$basedir/node" "$basedir/../jake/bin/cli.js" "$@"
10 + ret=$?
11 +else
12 + node "$basedir/../jake/bin/cli.js" "$@"
13 + ret=$?
14 +fi
15 +exit $ret
1 +@ECHO off
2 +SETLOCAL
3 +CALL :find_dp0
4 +
5 +IF EXIST "%dp0%\node.exe" (
6 + SET "_prog=%dp0%\node.exe"
7 +) ELSE (
8 + SET "_prog=node"
9 + SET PATHEXT=%PATHEXT:;.JS;=;%
10 +)
11 +
12 +"%_prog%" "%dp0%\..\jake\bin\cli.js" %*
13 +ENDLOCAL
14 +EXIT /b %errorlevel%
15 +:find_dp0
16 +SET dp0=%~dp0
17 +EXIT /b
1 +#!/usr/bin/env pwsh
2 +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
3 +
4 +$exe=""
5 +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
6 + # Fix case when both the Windows and Linux builds of Node
7 + # are installed in the same directory
8 + $exe=".exe"
9 +}
10 +$ret=0
11 +if (Test-Path "$basedir/node$exe") {
12 + & "$basedir/node$exe" "$basedir/../jake/bin/cli.js" $args
13 + $ret=$LASTEXITCODE
14 +} else {
15 + & "node$exe" "$basedir/../jake/bin/cli.js" $args
16 + $ret=$LASTEXITCODE
17 +}
18 +exit $ret
1 +declare type CSSColor =
2 + | 'aliceblue'
3 + | 'antiquewhite'
4 + | 'aqua'
5 + | 'aquamarine'
6 + | 'azure'
7 + | 'beige'
8 + | 'bisque'
9 + | 'black'
10 + | 'blanchedalmond'
11 + | 'blue'
12 + | 'blueviolet'
13 + | 'brown'
14 + | 'burlywood'
15 + | 'cadetblue'
16 + | 'chartreuse'
17 + | 'chocolate'
18 + | 'coral'
19 + | 'cornflowerblue'
20 + | 'cornsilk'
21 + | 'crimson'
22 + | 'cyan'
23 + | 'darkblue'
24 + | 'darkcyan'
25 + | 'darkgoldenrod'
26 + | 'darkgray'
27 + | 'darkgreen'
28 + | 'darkgrey'
29 + | 'darkkhaki'
30 + | 'darkmagenta'
31 + | 'darkolivegreen'
32 + | 'darkorange'
33 + | 'darkorchid'
34 + | 'darkred'
35 + | 'darksalmon'
36 + | 'darkseagreen'
37 + | 'darkslateblue'
38 + | 'darkslategray'
39 + | 'darkslategrey'
40 + | 'darkturquoise'
41 + | 'darkviolet'
42 + | 'deeppink'
43 + | 'deepskyblue'
44 + | 'dimgray'
45 + | 'dimgrey'
46 + | 'dodgerblue'
47 + | 'firebrick'
48 + | 'floralwhite'
49 + | 'forestgreen'
50 + | 'fuchsia'
51 + | 'gainsboro'
52 + | 'ghostwhite'
53 + | 'gold'
54 + | 'goldenrod'
55 + | 'gray'
56 + | 'green'
57 + | 'greenyellow'
58 + | 'grey'
59 + | 'honeydew'
60 + | 'hotpink'
61 + | 'indianred'
62 + | 'indigo'
63 + | 'ivory'
64 + | 'khaki'
65 + | 'lavender'
66 + | 'lavenderblush'
67 + | 'lawngreen'
68 + | 'lemonchiffon'
69 + | 'lightblue'
70 + | 'lightcoral'
71 + | 'lightcyan'
72 + | 'lightgoldenrodyellow'
73 + | 'lightgray'
74 + | 'lightgreen'
75 + | 'lightgrey'
76 + | 'lightpink'
77 + | 'lightsalmon'
78 + | 'lightseagreen'
79 + | 'lightskyblue'
80 + | 'lightslategray'
81 + | 'lightslategrey'
82 + | 'lightsteelblue'
83 + | 'lightyellow'
84 + | 'lime'
85 + | 'limegreen'
86 + | 'linen'
87 + | 'magenta'
88 + | 'maroon'
89 + | 'mediumaquamarine'
90 + | 'mediumblue'
91 + | 'mediumorchid'
92 + | 'mediumpurple'
93 + | 'mediumseagreen'
94 + | 'mediumslateblue'
95 + | 'mediumspringgreen'
96 + | 'mediumturquoise'
97 + | 'mediumvioletred'
98 + | 'midnightblue'
99 + | 'mintcream'
100 + | 'mistyrose'
101 + | 'moccasin'
102 + | 'navajowhite'
103 + | 'navy'
104 + | 'oldlace'
105 + | 'olive'
106 + | 'olivedrab'
107 + | 'orange'
108 + | 'orangered'
109 + | 'orchid'
110 + | 'palegoldenrod'
111 + | 'palegreen'
112 + | 'paleturquoise'
113 + | 'palevioletred'
114 + | 'papayawhip'
115 + | 'peachpuff'
116 + | 'peru'
117 + | 'pink'
118 + | 'plum'
119 + | 'powderblue'
120 + | 'purple'
121 + | 'rebeccapurple'
122 + | 'red'
123 + | 'rosybrown'
124 + | 'royalblue'
125 + | 'saddlebrown'
126 + | 'salmon'
127 + | 'sandybrown'
128 + | 'seagreen'
129 + | 'seashell'
130 + | 'sienna'
131 + | 'silver'
132 + | 'skyblue'
133 + | 'slateblue'
134 + | 'slategray'
135 + | 'slategrey'
136 + | 'snow'
137 + | 'springgreen'
138 + | 'steelblue'
139 + | 'tan'
140 + | 'teal'
141 + | 'thistle'
142 + | 'tomato'
143 + | 'turquoise'
144 + | 'violet'
145 + | 'wheat'
146 + | 'white'
147 + | 'whitesmoke'
148 + | 'yellow'
149 + | 'yellowgreen';
150 +
151 +declare namespace ansiStyles {
152 + interface ColorConvert {
153 + /**
154 + The RGB color space.
155 +
156 + @param red - (`0`-`255`)
157 + @param green - (`0`-`255`)
158 + @param blue - (`0`-`255`)
159 + */
160 + rgb(red: number, green: number, blue: number): string;
161 +
162 + /**
163 + The RGB HEX color space.
164 +
165 + @param hex - A hexadecimal string containing RGB data.
166 + */
167 + hex(hex: string): string;
168 +
169 + /**
170 + @param keyword - A CSS color name.
171 + */
172 + keyword(keyword: CSSColor): string;
173 +
174 + /**
175 + The HSL color space.
176 +
177 + @param hue - (`0`-`360`)
178 + @param saturation - (`0`-`100`)
179 + @param lightness - (`0`-`100`)
180 + */
181 + hsl(hue: number, saturation: number, lightness: number): string;
182 +
183 + /**
184 + The HSV color space.
185 +
186 + @param hue - (`0`-`360`)
187 + @param saturation - (`0`-`100`)
188 + @param value - (`0`-`100`)
189 + */
190 + hsv(hue: number, saturation: number, value: number): string;
191 +
192 + /**
193 + The HSV color space.
194 +
195 + @param hue - (`0`-`360`)
196 + @param whiteness - (`0`-`100`)
197 + @param blackness - (`0`-`100`)
198 + */
199 + hwb(hue: number, whiteness: number, blackness: number): string;
200 +
201 + /**
202 + Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color.
203 + */
204 + ansi(ansi: number): string;
205 +
206 + /**
207 + Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
208 + */
209 + ansi256(ansi: number): string;
210 + }
211 +
212 + interface CSPair {
213 + /**
214 + The ANSI terminal control sequence for starting this style.
215 + */
216 + readonly open: string;
217 +
218 + /**
219 + The ANSI terminal control sequence for ending this style.
220 + */
221 + readonly close: string;
222 + }
223 +
224 + interface ColorBase {
225 + readonly ansi: ColorConvert;
226 + readonly ansi256: ColorConvert;
227 + readonly ansi16m: ColorConvert;
228 +
229 + /**
230 + The ANSI terminal control sequence for ending this color.
231 + */
232 + readonly close: string;
233 + }
234 +
235 + interface Modifier {
236 + /**
237 + Resets the current color chain.
238 + */
239 + readonly reset: CSPair;
240 +
241 + /**
242 + Make text bold.
243 + */
244 + readonly bold: CSPair;
245 +
246 + /**
247 + Emitting only a small amount of light.
248 + */
249 + readonly dim: CSPair;
250 +
251 + /**
252 + Make text italic. (Not widely supported)
253 + */
254 + readonly italic: CSPair;
255 +
256 + /**
257 + Make text underline. (Not widely supported)
258 + */
259 + readonly underline: CSPair;
260 +
261 + /**
262 + Inverse background and foreground colors.
263 + */
264 + readonly inverse: CSPair;
265 +
266 + /**
267 + Prints the text, but makes it invisible.
268 + */
269 + readonly hidden: CSPair;
270 +
271 + /**
272 + Puts a horizontal line through the center of the text. (Not widely supported)
273 + */
274 + readonly strikethrough: CSPair;
275 + }
276 +
277 + interface ForegroundColor {
278 + readonly black: CSPair;
279 + readonly red: CSPair;
280 + readonly green: CSPair;
281 + readonly yellow: CSPair;
282 + readonly blue: CSPair;
283 + readonly cyan: CSPair;
284 + readonly magenta: CSPair;
285 + readonly white: CSPair;
286 +
287 + /**
288 + Alias for `blackBright`.
289 + */
290 + readonly gray: CSPair;
291 +
292 + /**
293 + Alias for `blackBright`.
294 + */
295 + readonly grey: CSPair;
296 +
297 + readonly blackBright: CSPair;
298 + readonly redBright: CSPair;
299 + readonly greenBright: CSPair;
300 + readonly yellowBright: CSPair;
301 + readonly blueBright: CSPair;
302 + readonly cyanBright: CSPair;
303 + readonly magentaBright: CSPair;
304 + readonly whiteBright: CSPair;
305 + }
306 +
307 + interface BackgroundColor {
308 + readonly bgBlack: CSPair;
309 + readonly bgRed: CSPair;
310 + readonly bgGreen: CSPair;
311 + readonly bgYellow: CSPair;
312 + readonly bgBlue: CSPair;
313 + readonly bgCyan: CSPair;
314 + readonly bgMagenta: CSPair;
315 + readonly bgWhite: CSPair;
316 +
317 + /**
318 + Alias for `bgBlackBright`.
319 + */
320 + readonly bgGray: CSPair;
321 +
322 + /**
323 + Alias for `bgBlackBright`.
324 + */
325 + readonly bgGrey: CSPair;
326 +
327 + readonly bgBlackBright: CSPair;
328 + readonly bgRedBright: CSPair;
329 + readonly bgGreenBright: CSPair;
330 + readonly bgYellowBright: CSPair;
331 + readonly bgBlueBright: CSPair;
332 + readonly bgCyanBright: CSPair;
333 + readonly bgMagentaBright: CSPair;
334 + readonly bgWhiteBright: CSPair;
335 + }
336 +}
337 +
338 +declare const ansiStyles: {
339 + readonly modifier: ansiStyles.Modifier;
340 + readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase;
341 + readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase;
342 + readonly codes: ReadonlyMap<number, number>;
343 +} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier;
344 +
345 +export = ansiStyles;
1 +'use strict';
2 +
3 +const wrapAnsi16 = (fn, offset) => (...args) => {
4 + const code = fn(...args);
5 + return `\u001B[${code + offset}m`;
6 +};
7 +
8 +const wrapAnsi256 = (fn, offset) => (...args) => {
9 + const code = fn(...args);
10 + return `\u001B[${38 + offset};5;${code}m`;
11 +};
12 +
13 +const wrapAnsi16m = (fn, offset) => (...args) => {
14 + const rgb = fn(...args);
15 + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
16 +};
17 +
18 +const ansi2ansi = n => n;
19 +const rgb2rgb = (r, g, b) => [r, g, b];
20 +
21 +const setLazyProperty = (object, property, get) => {
22 + Object.defineProperty(object, property, {
23 + get: () => {
24 + const value = get();
25 +
26 + Object.defineProperty(object, property, {
27 + value,
28 + enumerable: true,
29 + configurable: true
30 + });
31 +
32 + return value;
33 + },
34 + enumerable: true,
35 + configurable: true
36 + });
37 +};
38 +
39 +/** @type {typeof import('color-convert')} */
40 +let colorConvert;
41 +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
42 + if (colorConvert === undefined) {
43 + colorConvert = require('color-convert');
44 + }
45 +
46 + const offset = isBackground ? 10 : 0;
47 + const styles = {};
48 +
49 + for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
50 + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
51 + if (sourceSpace === targetSpace) {
52 + styles[name] = wrap(identity, offset);
53 + } else if (typeof suite === 'object') {
54 + styles[name] = wrap(suite[targetSpace], offset);
55 + }
56 + }
57 +
58 + return styles;
59 +};
60 +
61 +function assembleStyles() {
62 + const codes = new Map();
63 + const styles = {
64 + modifier: {
65 + reset: [0, 0],
66 + // 21 isn't widely supported and 22 does the same thing
67 + bold: [1, 22],
68 + dim: [2, 22],
69 + italic: [3, 23],
70 + underline: [4, 24],
71 + inverse: [7, 27],
72 + hidden: [8, 28],
73 + strikethrough: [9, 29]
74 + },
75 + color: {
76 + black: [30, 39],
77 + red: [31, 39],
78 + green: [32, 39],
79 + yellow: [33, 39],
80 + blue: [34, 39],
81 + magenta: [35, 39],
82 + cyan: [36, 39],
83 + white: [37, 39],
84 +
85 + // Bright color
86 + blackBright: [90, 39],
87 + redBright: [91, 39],
88 + greenBright: [92, 39],
89 + yellowBright: [93, 39],
90 + blueBright: [94, 39],
91 + magentaBright: [95, 39],
92 + cyanBright: [96, 39],
93 + whiteBright: [97, 39]
94 + },
95 + bgColor: {
96 + bgBlack: [40, 49],
97 + bgRed: [41, 49],
98 + bgGreen: [42, 49],
99 + bgYellow: [43, 49],
100 + bgBlue: [44, 49],
101 + bgMagenta: [45, 49],
102 + bgCyan: [46, 49],
103 + bgWhite: [47, 49],
104 +
105 + // Bright color
106 + bgBlackBright: [100, 49],
107 + bgRedBright: [101, 49],
108 + bgGreenBright: [102, 49],
109 + bgYellowBright: [103, 49],
110 + bgBlueBright: [104, 49],
111 + bgMagentaBright: [105, 49],
112 + bgCyanBright: [106, 49],
113 + bgWhiteBright: [107, 49]
114 + }
115 + };
116 +
117 + // Alias bright black as gray (and grey)
118 + styles.color.gray = styles.color.blackBright;
119 + styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
120 + styles.color.grey = styles.color.blackBright;
121 + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
122 +
123 + for (const [groupName, group] of Object.entries(styles)) {
124 + for (const [styleName, style] of Object.entries(group)) {
125 + styles[styleName] = {
126 + open: `\u001B[${style[0]}m`,
127 + close: `\u001B[${style[1]}m`
128 + };
129 +
130 + group[styleName] = styles[styleName];
131 +
132 + codes.set(style[0], style[1]);
133 + }
134 +
135 + Object.defineProperty(styles, groupName, {
136 + value: group,
137 + enumerable: false
138 + });
139 + }
140 +
141 + Object.defineProperty(styles, 'codes', {
142 + value: codes,
143 + enumerable: false
144 + });
145 +
146 + styles.color.close = '\u001B[39m';
147 + styles.bgColor.close = '\u001B[49m';
148 +
149 + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
150 + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
151 + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
152 + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
153 + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
154 + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
155 +
156 + return styles;
157 +}
158 +
159 +// Make the export immutable
160 +Object.defineProperty(module, 'exports', {
161 + enumerable: true,
162 + get: assembleStyles
163 +});
1 +MIT License
2 +
3 +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
4 +
5 +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:
6 +
7 +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 +
9 +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.
1 +{
2 + "_from": "ansi-styles@^4.1.0",
3 + "_id": "ansi-styles@4.3.0",
4 + "_inBundle": false,
5 + "_integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
6 + "_location": "/ansi-styles",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "ansi-styles@^4.1.0",
12 + "name": "ansi-styles",
13 + "escapedName": "ansi-styles",
14 + "rawSpec": "^4.1.0",
15 + "saveSpec": null,
16 + "fetchSpec": "^4.1.0"
17 + },
18 + "_requiredBy": [
19 + "/chalk"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
22 + "_shasum": "edd803628ae71c04c85ae7a0906edad34b648937",
23 + "_spec": "ansi-styles@^4.1.0",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\chalk",
25 + "author": {
26 + "name": "Sindre Sorhus",
27 + "email": "sindresorhus@gmail.com",
28 + "url": "sindresorhus.com"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/chalk/ansi-styles/issues"
32 + },
33 + "bundleDependencies": false,
34 + "dependencies": {
35 + "color-convert": "^2.0.1"
36 + },
37 + "deprecated": false,
38 + "description": "ANSI escape codes for styling strings in the terminal",
39 + "devDependencies": {
40 + "@types/color-convert": "^1.9.0",
41 + "ava": "^2.3.0",
42 + "svg-term-cli": "^2.1.1",
43 + "tsd": "^0.11.0",
44 + "xo": "^0.25.3"
45 + },
46 + "engines": {
47 + "node": ">=8"
48 + },
49 + "files": [
50 + "index.js",
51 + "index.d.ts"
52 + ],
53 + "funding": "https://github.com/chalk/ansi-styles?sponsor=1",
54 + "homepage": "https://github.com/chalk/ansi-styles#readme",
55 + "keywords": [
56 + "ansi",
57 + "styles",
58 + "color",
59 + "colour",
60 + "colors",
61 + "terminal",
62 + "console",
63 + "cli",
64 + "string",
65 + "tty",
66 + "escape",
67 + "formatting",
68 + "rgb",
69 + "256",
70 + "shell",
71 + "xterm",
72 + "log",
73 + "logging",
74 + "command-line",
75 + "text"
76 + ],
77 + "license": "MIT",
78 + "name": "ansi-styles",
79 + "repository": {
80 + "type": "git",
81 + "url": "git+https://github.com/chalk/ansi-styles.git"
82 + },
83 + "scripts": {
84 + "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor",
85 + "test": "xo && ava && tsd"
86 + },
87 + "version": "4.3.0"
88 +}
1 +# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles)
2 +
3 +> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal
4 +
5 +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings.
6 +
7 +<img src="screenshot.svg" width="900">
8 +
9 +## Install
10 +
11 +```
12 +$ npm install ansi-styles
13 +```
14 +
15 +## Usage
16 +
17 +```js
18 +const style = require('ansi-styles');
19 +
20 +console.log(`${style.green.open}Hello world!${style.green.close}`);
21 +
22 +
23 +// Color conversion between 16/256/truecolor
24 +// NOTE: If conversion goes to 16 colors or 256 colors, the original color
25 +// may be degraded to fit that color palette. This means terminals
26 +// that do not support 16 million colors will best-match the
27 +// original color.
28 +console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close);
29 +console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close);
30 +console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close);
31 +```
32 +
33 +## API
34 +
35 +Each style has an `open` and `close` property.
36 +
37 +## Styles
38 +
39 +### Modifiers
40 +
41 +- `reset`
42 +- `bold`
43 +- `dim`
44 +- `italic` *(Not widely supported)*
45 +- `underline`
46 +- `inverse`
47 +- `hidden`
48 +- `strikethrough` *(Not widely supported)*
49 +
50 +### Colors
51 +
52 +- `black`
53 +- `red`
54 +- `green`
55 +- `yellow`
56 +- `blue`
57 +- `magenta`
58 +- `cyan`
59 +- `white`
60 +- `blackBright` (alias: `gray`, `grey`)
61 +- `redBright`
62 +- `greenBright`
63 +- `yellowBright`
64 +- `blueBright`
65 +- `magentaBright`
66 +- `cyanBright`
67 +- `whiteBright`
68 +
69 +### Background colors
70 +
71 +- `bgBlack`
72 +- `bgRed`
73 +- `bgGreen`
74 +- `bgYellow`
75 +- `bgBlue`
76 +- `bgMagenta`
77 +- `bgCyan`
78 +- `bgWhite`
79 +- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
80 +- `bgRedBright`
81 +- `bgGreenBright`
82 +- `bgYellowBright`
83 +- `bgBlueBright`
84 +- `bgMagentaBright`
85 +- `bgCyanBright`
86 +- `bgWhiteBright`
87 +
88 +## Advanced usage
89 +
90 +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.
91 +
92 +- `style.modifier`
93 +- `style.color`
94 +- `style.bgColor`
95 +
96 +###### Example
97 +
98 +```js
99 +console.log(style.color.green.open);
100 +```
101 +
102 +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.
103 +
104 +###### Example
105 +
106 +```js
107 +console.log(style.codes.get(36));
108 +//=> 39
109 +```
110 +
111 +## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728)
112 +
113 +`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.
114 +
115 +The following color spaces from `color-convert` are supported:
116 +
117 +- `rgb`
118 +- `hex`
119 +- `keyword`
120 +- `hsl`
121 +- `hsv`
122 +- `hwb`
123 +- `ansi`
124 +- `ansi256`
125 +
126 +To use these, call the associated conversion function with the intended output, for example:
127 +
128 +```js
129 +style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code
130 +style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code
131 +
132 +style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code
133 +style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code
134 +
135 +style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code
136 +style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code
137 +```
138 +
139 +## Related
140 +
141 +- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal
142 +
143 +## Maintainers
144 +
145 +- [Sindre Sorhus](https://github.com/sindresorhus)
146 +- [Josh Junon](https://github.com/qix-)
147 +
148 +## For enterprise
149 +
150 +Available as part of the Tidelift Subscription.
151 +
152 +The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
1 +# v3.2.3
2 +- Fix bugs in comment parsing in `autoInject`. (#1767, #1780)
3 +
4 +# v3.2.2
5 +- Fix potential prototype pollution exploit
6 +
7 +# v3.2.1
8 +- Use `queueMicrotask` if available to the environment (#1761)
9 +- Minor perf improvement in `priorityQueue` (#1727)
10 +- More examples in documentation (#1726)
11 +- Various doc fixes (#1708, #1712, #1717, #1740, #1739, #1749, #1756)
12 +- Improved test coverage (#1754)
13 +
14 +# v3.2.0
15 +- Fix a bug in Safari related to overwriting `func.name`
16 +- Remove built-in browserify configuration (#1653)
17 +- Varios doc fixes (#1688, #1703, #1704)
18 +
19 +# v3.1.1
20 +- Allow redefining `name` property on wrapped functions.
21 +
22 +# v3.1.0
23 +
24 +- Added `q.pushAsync` and `q.unshiftAsync`, analagous to `q.push` and `q.unshift`, except they always do not accept a callback, and reject if processing the task errors. (#1659)
25 +- Promises returned from `q.push` and `q.unshift` when a callback is not passed now resolve even if an error ocurred. (#1659)
26 +- Fixed a parsing bug in `autoInject` with complicated function bodies (#1663)
27 +- Added ES6+ configuration for Browserify bundlers (#1653)
28 +- Various doc fixes (#1664, #1658, #1665, #1652)
29 +
30 +# v3.0.1
31 +
32 +## Bug fixes
33 +- Fixed a regression where arrays passed to `queue` and `cargo` would be completely flattened. (#1645)
34 +- Clarified Async's browser support (#1643)
35 +
36 +
37 +# v3.0.0
38 +
39 +The `async`/`await` release!
40 +
41 +There are a lot of new features and subtle breaking changes in this major version, but the biggest feature is that most Async methods return a Promise if you omit the callback, meaning you can `await` them from within an `async` function.
42 +
43 +```js
44 +const results = await async.mapLimit(urls, 5, async url => {
45 + const resp = await fetch(url)
46 + return resp.body
47 +})
48 +```
49 +
50 +## Breaking Changes
51 +- Most Async methods return a Promise when the final callback is omitted, making them `await`-able! (#1572)
52 +- We are now making heavy use of ES2015 features, this means we have dropped out-of-the-box support for Node 4 and earlier, and many old versions of browsers. (#1541, #1553)
53 +- In `queue`, `priorityQueue`, `cargo` and `cargoQueue`, the "event"-style methods, like `q.drain` and `q.saturated` are now methods that register a callback, rather than properties you assign a callback to. They are now of the form `q.drain(callback)`. If you do not pass a callback a Promise will be returned for the next occurrence of the event, making them `await`-able, e.g. `await q.drain()`. (#1586, #1641)
54 +- Calling `callback(false)` will cancel an async method, preventing further iteration and callback calls. This is useful for preventing memory leaks when you break out of an async flow by calling an outer callback. (#1064, #1542)
55 +- `during` and `doDuring` have been removed, and instead `whilst`, `doWhilst`, `until` and `doUntil` now have asynchronous `test` functions. (#850, #1557)
56 +- `limits` of less than 1 now cause an error to be thrown in queues and collection methods. (#1249, #1552)
57 +- `memoize` no longer memoizes errors (#1465, #1466)
58 +- `applyEach`/`applyEachSeries` have a simpler interface, to make them more easily type-able. It always returns a function that takes in a single callback argument. If that callback is omitted, a promise is returned, making it awaitable. (#1228, #1640)
59 +
60 +## New Features
61 +- Async generators are now supported in all the Collection methods. (#1560)
62 +- Added `cargoQueue`, a queue with both `concurrency` and `payload` size parameters. (#1567)
63 +- Queue objects returned from `queue` now have a `Symbol.iterator` method, meaning they can be iterated over to inspect the current list of items in the queue. (#1459, #1556)
64 +- A ESM-flavored `async.mjs` is included in the `async` package. This is described in the `package.json` `"module"` field, meaning it should be automatically used by Webpack and other compatible bundlers.
65 +
66 +## Bug fixes
67 +- Better handle arbitrary error objects in `asyncify` (#1568, #1569)
68 +
69 +## Other
70 +- Removed Lodash as a dependency (#1283, #1528)
71 +- Miscellaneous docs fixes (#1393, #1501, #1540, #1543, #1558, #1563, #1564, #1579, #1581)
72 +- Miscellaneous test fixes (#1538)
73 +
74 +-------
75 +
76 +# v2.6.1
77 +- Updated lodash to prevent `npm audit` warnings. (#1532, #1533)
78 +- Made `async-es` more optimized for webpack users (#1517)
79 +- Fixed a stack overflow with large collections and a synchronous iterator (#1514)
80 +- Various small fixes/chores (#1505, #1511, #1527, #1530)
81 +
82 +# v2.6.0
83 +- Added missing aliases for many methods. Previously, you could not (e.g.) `require('async/find')` or use `async.anyLimit`. (#1483)
84 +- Improved `queue` performance. (#1448, #1454)
85 +- Add missing sourcemap (#1452, #1453)
86 +- Various doc updates (#1448, #1471, #1483)
87 +
88 +# v2.5.0
89 +- Added `concatLimit`, the `Limit` equivalent of [`concat`](https://caolan.github.io/async/docs.html#concat) ([#1426](https://github.com/caolan/async/issues/1426), [#1430](https://github.com/caolan/async/pull/1430))
90 +- `concat` improvements: it now preserves order, handles falsy values and the `iteratee` callback takes a variable number of arguments ([#1437](https://github.com/caolan/async/issues/1437), [#1436](https://github.com/caolan/async/pull/1436))
91 +- Fixed an issue in `queue` where there was a size discrepancy between `workersList().length` and `running()` ([#1428](https://github.com/caolan/async/issues/1428), [#1429](https://github.com/caolan/async/pull/1429))
92 +- Various doc fixes ([#1422](https://github.com/caolan/async/issues/1422), [#1424](https://github.com/caolan/async/pull/1424))
93 +
94 +# v2.4.1
95 +- Fixed a bug preventing functions wrapped with `timeout()` from being re-used. ([#1418](https://github.com/caolan/async/issues/1418), [#1419](https://github.com/caolan/async/issues/1419))
96 +
97 +# v2.4.0
98 +- Added `tryEach`, for running async functions in parallel, where you only expect one to succeed. ([#1365](https://github.com/caolan/async/issues/1365), [#687](https://github.com/caolan/async/issues/687))
99 +- Improved performance, most notably in `parallel` and `waterfall` ([#1395](https://github.com/caolan/async/issues/1395))
100 +- Added `queue.remove()`, for removing items in a `queue` ([#1397](https://github.com/caolan/async/issues/1397), [#1391](https://github.com/caolan/async/issues/1391))
101 +- Fixed using `eval`, preventing Async from running in pages with Content Security Policy ([#1404](https://github.com/caolan/async/issues/1404), [#1403](https://github.com/caolan/async/issues/1403))
102 +- Fixed errors thrown in an `asyncify`ed function's callback being caught by the underlying Promise ([#1408](https://github.com/caolan/async/issues/1408))
103 +- Fixed timing of `queue.empty()` ([#1367](https://github.com/caolan/async/issues/1367))
104 +- Various doc fixes ([#1314](https://github.com/caolan/async/issues/1314), [#1394](https://github.com/caolan/async/issues/1394), [#1412](https://github.com/caolan/async/issues/1412))
105 +
106 +# v2.3.0
107 +- Added support for ES2017 `async` functions. Wherever you can pass a Node-style/CPS function that uses a callback, you can also pass an `async` function. Previously, you had to wrap `async` functions with `asyncify`. The caveat is that it will only work if `async` functions are supported natively in your environment, transpiled implementations can't be detected. ([#1386](https://github.com/caolan/async/issues/1386), [#1390](https://github.com/caolan/async/issues/1390))
108 +- Small doc fix ([#1392](https://github.com/caolan/async/issues/1392))
109 +
110 +# v2.2.0
111 +- Added `groupBy`, and the `Series`/`Limit` equivalents, analogous to [`_.groupBy`](http://lodash.com/docs#groupBy) ([#1364](https://github.com/caolan/async/issues/1364))
112 +- Fixed `transform` bug when `callback` was not passed ([#1381](https://github.com/caolan/async/issues/1381))
113 +- Added note about `reflect` to `parallel` docs ([#1385](https://github.com/caolan/async/issues/1385))
114 +
115 +# v2.1.5
116 +- Fix `auto` bug when function names collided with Array.prototype ([#1358](https://github.com/caolan/async/issues/1358))
117 +- Improve some error messages ([#1349](https://github.com/caolan/async/issues/1349))
118 +- Avoid stack overflow case in queue
119 +- Fixed an issue in `some`, `every` and `find` where processing would continue after the result was determined.
120 +- Cleanup implementations of `some`, `every` and `find`
121 +
122 +# v2.1.3
123 +- Make bundle size smaller
124 +- Create optimized hotpath for `filter` in array case.
125 +
126 +# v2.1.2
127 +- Fixed a stackoverflow bug with `detect`, `some`, `every` on large inputs ([#1293](https://github.com/caolan/async/issues/1293)).
128 +
129 +# v2.1.0
130 +
131 +- `retry` and `retryable` now support an optional `errorFilter` function that determines if the `task` should retry on the error ([#1256](https://github.com/caolan/async/issues/1256), [#1261](https://github.com/caolan/async/issues/1261))
132 +- Optimized array iteration in `race`, `cargo`, `queue`, and `priorityQueue` ([#1253](https://github.com/caolan/async/issues/1253))
133 +- Added alias documentation to doc site ([#1251](https://github.com/caolan/async/issues/1251), [#1254](https://github.com/caolan/async/issues/1254))
134 +- Added [BootStrap scrollspy](http://getbootstrap.com/javascript/#scrollspy) to docs to highlight in the sidebar the current method being viewed ([#1289](https://github.com/caolan/async/issues/1289), [#1300](https://github.com/caolan/async/issues/1300))
135 +- Various minor doc fixes ([#1263](https://github.com/caolan/async/issues/1263), [#1264](https://github.com/caolan/async/issues/1264), [#1271](https://github.com/caolan/async/issues/1271), [#1278](https://github.com/caolan/async/issues/1278), [#1280](https://github.com/caolan/async/issues/1280), [#1282](https://github.com/caolan/async/issues/1282), [#1302](https://github.com/caolan/async/issues/1302))
136 +
137 +# v2.0.1
138 +
139 +- Significantly optimized all iteration based collection methods such as `each`, `map`, `filter`, etc ([#1245](https://github.com/caolan/async/issues/1245), [#1246](https://github.com/caolan/async/issues/1246), [#1247](https://github.com/caolan/async/issues/1247)).
140 +
141 +# v2.0.0
142 +
143 +Lots of changes here!
144 +
145 +First and foremost, we have a slick new [site for docs](https://caolan.github.io/async/). Special thanks to [**@hargasinski**](https://github.com/hargasinski) for his work converting our old docs to `jsdoc` format and implementing the new website. Also huge ups to [**@ivanseidel**](https://github.com/ivanseidel) for designing our new logo. It was a long process for both of these tasks, but I think these changes turned out extraordinary well.
146 +
147 +The biggest feature is modularization. You can now `require("async/series")` to only require the `series` function. Every Async library function is available this way. You still can `require("async")` to require the entire library, like you could do before.
148 +
149 +We also provide Async as a collection of ES2015 modules. You can now `import {each} from 'async-es'` or `import waterfall from 'async-es/waterfall'`. If you are using only a few Async functions, and are using a ES bundler such as Rollup, this can significantly lower your build size.
150 +
151 +Major thanks to [**@Kikobeats**](github.com/Kikobeats), [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for doing the majority of the modularization work, as well as [**@jdalton**](github.com/jdalton) and [**@Rich-Harris**](github.com/Rich-Harris) for advisory work on the general modularization strategy.
152 +
153 +Another one of the general themes of the 2.0 release is standardization of what an "async" function is. We are now more strictly following the node-style continuation passing style. That is, an async function is a function that:
154 +
155 +1. Takes a variable number of arguments
156 +2. The last argument is always a callback
157 +3. The callback can accept any number of arguments
158 +4. The first argument passed to the callback will be treated as an error result, if the argument is truthy
159 +5. Any number of result arguments can be passed after the "error" argument
160 +6. The callback is called once and exactly once, either on the same tick or later tick of the JavaScript event loop.
161 +
162 +There were several cases where Async accepted some functions that did not strictly have these properties, most notably `auto`, `every`, `some`, `filter`, `reject` and `detect`.
163 +
164 +Another theme is performance. We have eliminated internal deferrals in all cases where they make sense. For example, in `waterfall` and `auto`, there was a `setImmediate` between each task -- these deferrals have been removed. A `setImmediate` call can add up to 1ms of delay. This might not seem like a lot, but it can add up if you are using many Async functions in the course of processing a HTTP request, for example. Nearly all asynchronous functions that do I/O already have some sort of deferral built in, so the extra deferral is unnecessary. The trade-off of this change is removing our built-in stack-overflow defense. Many synchronous callback calls in series can quickly overflow the JS call stack. If you do have a function that is sometimes synchronous (calling its callback on the same tick), and are running into stack overflows, wrap it with `async.ensureAsync()`.
165 +
166 +Another big performance win has been re-implementing `queue`, `cargo`, and `priorityQueue` with [doubly linked lists](https://en.wikipedia.org/wiki/Doubly_linked_list) instead of arrays. This has lead to queues being an order of [magnitude faster on large sets of tasks](https://github.com/caolan/async/pull/1205).
167 +
168 +## New Features
169 +
170 +- Async is now modularized. Individual functions can be `require()`d from the main package. (`require('async/auto')`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996))
171 +- Async is also available as a collection of ES2015 modules in the new `async-es` package. (`import {forEachSeries} from 'async-es'`) ([#984](https://github.com/caolan/async/issues/984), [#996](https://github.com/caolan/async/issues/996))
172 +- Added `race`, analogous to `Promise.race()`. It will run an array of async tasks in parallel and will call its callback with the result of the first task to respond. ([#568](https://github.com/caolan/async/issues/568), [#1038](https://github.com/caolan/async/issues/1038))
173 +- Collection methods now accept ES2015 iterators. Maps, Sets, and anything that implements the iterator spec can now be passed directly to `each`, `map`, `parallel`, etc.. ([#579](https://github.com/caolan/async/issues/579), [#839](https://github.com/caolan/async/issues/839), [#1074](https://github.com/caolan/async/issues/1074))
174 +- Added `mapValues`, for mapping over the properties of an object and returning an object with the same keys. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177))
175 +- Added `timeout`, a wrapper for an async function that will make the task time-out after the specified time. ([#1007](https://github.com/caolan/async/issues/1007), [#1027](https://github.com/caolan/async/issues/1027))
176 +- Added `reflect` and `reflectAll`, analagous to [`Promise.reflect()`](http://bluebirdjs.com/docs/api/reflect.html), a wrapper for async tasks that always succeeds, by gathering results and errors into an object. ([#942](https://github.com/caolan/async/issues/942), [#1012](https://github.com/caolan/async/issues/1012), [#1095](https://github.com/caolan/async/issues/1095))
177 +- `constant` supports dynamic arguments -- it will now always use its last argument as the callback. ([#1016](https://github.com/caolan/async/issues/1016), [#1052](https://github.com/caolan/async/issues/1052))
178 +- `setImmediate` and `nextTick` now support arguments to partially apply to the deferred function, like the node-native versions do. ([#940](https://github.com/caolan/async/issues/940), [#1053](https://github.com/caolan/async/issues/1053))
179 +- `auto` now supports resolving cyclic dependencies using [Kahn's algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm) ([#1140](https://github.com/caolan/async/issues/1140)).
180 +- Added `autoInject`, a relative of `auto` that automatically spreads a task's dependencies as arguments to the task function. ([#608](https://github.com/caolan/async/issues/608), [#1055](https://github.com/caolan/async/issues/1055), [#1099](https://github.com/caolan/async/issues/1099), [#1100](https://github.com/caolan/async/issues/1100))
181 +- You can now limit the concurrency of `auto` tasks. ([#635](https://github.com/caolan/async/issues/635), [#637](https://github.com/caolan/async/issues/637))
182 +- Added `retryable`, a relative of `retry` that wraps an async function, making it retry when called. ([#1058](https://github.com/caolan/async/issues/1058))
183 +- `retry` now supports specifying a function that determines the next time interval, useful for exponential backoff, logging and other retry strategies. ([#1161](https://github.com/caolan/async/issues/1161))
184 +- `retry` will now pass all of the arguments the task function was resolved with to the callback ([#1231](https://github.com/caolan/async/issues/1231)).
185 +- Added `q.unsaturated` -- callback called when a `queue`'s number of running workers falls below a threshold. ([#868](https://github.com/caolan/async/issues/868), [#1030](https://github.com/caolan/async/issues/1030), [#1033](https://github.com/caolan/async/issues/1033), [#1034](https://github.com/caolan/async/issues/1034))
186 +- Added `q.error` -- a callback called whenever a `queue` task calls its callback with an error. ([#1170](https://github.com/caolan/async/issues/1170))
187 +- `applyEach` and `applyEachSeries` now pass results to the final callback. ([#1088](https://github.com/caolan/async/issues/1088))
188 +
189 +## Breaking changes
190 +
191 +- Calling a callback more than once is considered an error, and an error will be thrown. This had an explicit breaking change in `waterfall`. If you were relying on this behavior, you should more accurately represent your control flow as an event emitter or stream. ([#814](https://github.com/caolan/async/issues/814), [#815](https://github.com/caolan/async/issues/815), [#1048](https://github.com/caolan/async/issues/1048), [#1050](https://github.com/caolan/async/issues/1050))
192 +- `auto` task functions now always take the callback as the last argument. If a task has dependencies, the `results` object will be passed as the first argument. To migrate old task functions, wrap them with [`_.flip`](https://lodash.com/docs#flip) ([#1036](https://github.com/caolan/async/issues/1036), [#1042](https://github.com/caolan/async/issues/1042))
193 +- Internal `setImmediate` calls have been refactored away. This may make existing flows vulnerable to stack overflows if you use many synchronous functions in series. Use `ensureAsync` to work around this. ([#696](https://github.com/caolan/async/issues/696), [#704](https://github.com/caolan/async/issues/704), [#1049](https://github.com/caolan/async/issues/1049), [#1050](https://github.com/caolan/async/issues/1050))
194 +- `map` used to return an object when iterating over an object. `map` now always returns an array, like in other libraries. The previous object behavior has been split out into `mapValues`. ([#1157](https://github.com/caolan/async/issues/1157), [#1177](https://github.com/caolan/async/issues/1177))
195 +- `filter`, `reject`, `some`, `every`, `detect` and their families like `{METHOD}Series` and `{METHOD}Limit` now expect an error as the first callback argument, rather than just a simple boolean. Pass `null` as the first argument, or use `fs.access` instead of `fs.exists`. ([#118](https://github.com/caolan/async/issues/118), [#774](https://github.com/caolan/async/issues/774), [#1028](https://github.com/caolan/async/issues/1028), [#1041](https://github.com/caolan/async/issues/1041))
196 +- `{METHOD}` and `{METHOD}Series` are now implemented in terms of `{METHOD}Limit`. This is a major internal simplification, and is not expected to cause many problems, but it does subtly affect how functions execute internally. ([#778](https://github.com/caolan/async/issues/778), [#847](https://github.com/caolan/async/issues/847))
197 +- `retry`'s callback is now optional. Previously, omitting the callback would partially apply the function, meaning it could be passed directly as a task to `series` or `auto`. The partially applied "control-flow" behavior has been separated out into `retryable`. ([#1054](https://github.com/caolan/async/issues/1054), [#1058](https://github.com/caolan/async/issues/1058))
198 +- The test function for `whilst`, `until`, and `during` used to be passed non-error args from the iteratee function's callback, but this led to weirdness where the first call of the test function would be passed no args. We have made it so the test function is never passed extra arguments, and only the `doWhilst`, `doUntil`, and `doDuring` functions pass iteratee callback arguments to the test function ([#1217](https://github.com/caolan/async/issues/1217), [#1224](https://github.com/caolan/async/issues/1224))
199 +- The `q.tasks` array has been renamed `q._tasks` and is now implemented as a doubly linked list (DLL). Any code that used to interact with this array will need to be updated to either use the provided helpers or support DLLs ([#1205](https://github.com/caolan/async/issues/1205)).
200 +- The timing of the `q.saturated()` callback in a `queue` has been modified to better reflect when tasks pushed to the queue will start queueing. ([#724](https://github.com/caolan/async/issues/724), [#1078](https://github.com/caolan/async/issues/1078))
201 +- Removed `iterator` method in favour of [ES2015 iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators ) which natively supports arrays ([#1237](https://github.com/caolan/async/issues/1237))
202 +- Dropped support for Component, Jam, SPM, and Volo ([#1175](https://github.com/caolan/async/issues/1175), #[#176](https://github.com/caolan/async/issues/176))
203 +
204 +## Bug Fixes
205 +
206 +- Improved handling of no dependency cases in `auto` & `autoInject` ([#1147](https://github.com/caolan/async/issues/1147)).
207 +- Fixed a bug where the callback generated by `asyncify` with `Promises` could resolve twice ([#1197](https://github.com/caolan/async/issues/1197)).
208 +- Fixed several documented optional callbacks not actually being optional ([#1223](https://github.com/caolan/async/issues/1223)).
209 +
210 +## Other
211 +
212 +- Added `someSeries` and `everySeries` for symmetry, as well as a complete set of `any`/`anyLimit`/`anySeries` and `all`/`/allLmit`/`allSeries` aliases.
213 +- Added `find` as an alias for `detect. (as well as `findLimit` and `findSeries`).
214 +- Various doc fixes ([#1005](https://github.com/caolan/async/issues/1005), [#1008](https://github.com/caolan/async/issues/1008), [#1010](https://github.com/caolan/async/issues/1010), [#1015](https://github.com/caolan/async/issues/1015), [#1021](https://github.com/caolan/async/issues/1021), [#1037](https://github.com/caolan/async/issues/1037), [#1039](https://github.com/caolan/async/issues/1039), [#1051](https://github.com/caolan/async/issues/1051), [#1102](https://github.com/caolan/async/issues/1102), [#1107](https://github.com/caolan/async/issues/1107), [#1121](https://github.com/caolan/async/issues/1121), [#1123](https://github.com/caolan/async/issues/1123), [#1129](https://github.com/caolan/async/issues/1129), [#1135](https://github.com/caolan/async/issues/1135), [#1138](https://github.com/caolan/async/issues/1138), [#1141](https://github.com/caolan/async/issues/1141), [#1153](https://github.com/caolan/async/issues/1153), [#1216](https://github.com/caolan/async/issues/1216), [#1217](https://github.com/caolan/async/issues/1217), [#1232](https://github.com/caolan/async/issues/1232), [#1233](https://github.com/caolan/async/issues/1233), [#1236](https://github.com/caolan/async/issues/1236), [#1238](https://github.com/caolan/async/issues/1238))
215 +
216 +Thank you [**@aearly**](github.com/aearly) and [**@megawac**](github.com/megawac) for taking the lead on version 2 of async.
217 +
218 +------------------------------------------
219 +
220 +# v1.5.2
221 +- Allow using `"constructor"` as an argument in `memoize` ([#998](https://github.com/caolan/async/issues/998))
222 +- Give a better error messsage when `auto` dependency checking fails ([#994](https://github.com/caolan/async/issues/994))
223 +- Various doc updates ([#936](https://github.com/caolan/async/issues/936), [#956](https://github.com/caolan/async/issues/956), [#979](https://github.com/caolan/async/issues/979), [#1002](https://github.com/caolan/async/issues/1002))
224 +
225 +# v1.5.1
226 +- Fix issue with `pause` in `queue` with concurrency enabled ([#946](https://github.com/caolan/async/issues/946))
227 +- `while` and `until` now pass the final result to callback ([#963](https://github.com/caolan/async/issues/963))
228 +- `auto` will properly handle concurrency when there is no callback ([#966](https://github.com/caolan/async/issues/966))
229 +- `auto` will no. properly stop execution when an error occurs ([#988](https://github.com/caolan/async/issues/988), [#993](https://github.com/caolan/async/issues/993))
230 +- Various doc fixes ([#971](https://github.com/caolan/async/issues/971), [#980](https://github.com/caolan/async/issues/980))
231 +
232 +# v1.5.0
233 +
234 +- Added `transform`, analogous to [`_.transform`](http://lodash.com/docs#transform) ([#892](https://github.com/caolan/async/issues/892))
235 +- `map` now returns an object when an object is passed in, rather than array with non-numeric keys. `map` will begin always returning an array with numeric indexes in the next major release. ([#873](https://github.com/caolan/async/issues/873))
236 +- `auto` now accepts an optional `concurrency` argument to limit the number o. running tasks ([#637](https://github.com/caolan/async/issues/637))
237 +- Added `queue#workersList()`, to retrieve the lis. of currently running tasks. ([#891](https://github.com/caolan/async/issues/891))
238 +- Various code simplifications ([#896](https://github.com/caolan/async/issues/896), [#904](https://github.com/caolan/async/issues/904))
239 +- Various doc fixes :scroll: ([#890](https://github.com/caolan/async/issues/890), [#894](https://github.com/caolan/async/issues/894), [#903](https://github.com/caolan/async/issues/903), [#905](https://github.com/caolan/async/issues/905), [#912](https://github.com/caolan/async/issues/912))
240 +
241 +# v1.4.2
242 +
243 +- Ensure coverage files don't get published on npm ([#879](https://github.com/caolan/async/issues/879))
244 +
245 +# v1.4.1
246 +
247 +- Add in overlooked `detectLimit` method ([#866](https://github.com/caolan/async/issues/866))
248 +- Removed unnecessary files from npm releases ([#861](https://github.com/caolan/async/issues/861))
249 +- Removed usage of a reserved word to prevent :boom: in older environments ([#870](https://github.com/caolan/async/issues/870))
250 +
251 +# v1.4.0
252 +
253 +- `asyncify` now supports promises ([#840](https://github.com/caolan/async/issues/840))
254 +- Added `Limit` versions of `filter` and `reject` ([#836](https://github.com/caolan/async/issues/836))
255 +- Add `Limit` versions of `detect`, `some` and `every` ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829))
256 +- `some`, `every` and `detect` now short circuit early ([#828](https://github.com/caolan/async/issues/828), [#829](https://github.com/caolan/async/issues/829))
257 +- Improve detection of the global object ([#804](https://github.com/caolan/async/issues/804)), enabling use in WebWorkers
258 +- `whilst` now called with arguments from iterator ([#823](https://github.com/caolan/async/issues/823))
259 +- `during` now gets called with arguments from iterator ([#824](https://github.com/caolan/async/issues/824))
260 +- Code simplifications and optimizations aplenty ([diff](https://github.com/caolan/async/compare/v1.3.0...v1.4.0))
261 +
262 +
263 +# v1.3.0
264 +
265 +New Features:
266 +- Added `constant`
267 +- Added `asyncify`/`wrapSync` for making sync functions work with callbacks. ([#671](https://github.com/caolan/async/issues/671), [#806](https://github.com/caolan/async/issues/806))
268 +- Added `during` and `doDuring`, which are like `whilst` with an async truth test. ([#800](https://github.com/caolan/async/issues/800))
269 +- `retry` now accepts an `interval` parameter to specify a delay between retries. ([#793](https://github.com/caolan/async/issues/793))
270 +- `async` should work better in Web Workers due to better `root` detection ([#804](https://github.com/caolan/async/issues/804))
271 +- Callbacks are now optional in `whilst`, `doWhilst`, `until`, and `doUntil` ([#642](https://github.com/caolan/async/issues/642))
272 +- Various internal updates ([#786](https://github.com/caolan/async/issues/786), [#801](https://github.com/caolan/async/issues/801), [#802](https://github.com/caolan/async/issues/802), [#803](https://github.com/caolan/async/issues/803))
273 +- Various doc fixes ([#790](https://github.com/caolan/async/issues/790), [#794](https://github.com/caolan/async/issues/794))
274 +
275 +Bug Fixes:
276 +- `cargo` now exposes the `payload` size, and `cargo.payload` can be changed on the fly after the `cargo` is created. ([#740](https://github.com/caolan/async/issues/740), [#744](https://github.com/caolan/async/issues/744), [#783](https://github.com/caolan/async/issues/783))
277 +
278 +
279 +# v1.2.1
280 +
281 +Bug Fix:
282 +
283 +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782))
284 +
285 +
286 +# v1.2.0
287 +
288 +New Features:
289 +
290 +- Added `timesLimit` ([#743](https://github.com/caolan/async/issues/743))
291 +- `concurrency` can be changed after initialization in `queue` by setting `q.concurrency`. The new concurrency will be reflected the next time a task is processed. ([#747](https://github.com/caolan/async/issues/747), [#772](https://github.com/caolan/async/issues/772))
292 +
293 +Bug Fixes:
294 +
295 +- Fixed a regression in `each` and family with empty arrays that have additional properties. ([#775](https://github.com/caolan/async/issues/775), [#777](https://github.com/caolan/async/issues/777))
296 +
297 +
298 +# v1.1.1
299 +
300 +Bug Fix:
301 +
302 +- Small regression with synchronous iterator behavior in `eachSeries` with a 1-element array. Before 1.1.0, `eachSeries`'s callback was called on the same tick, which this patch restores. In 2.0.0, it will be called on the next tick. ([#782](https://github.com/caolan/async/issues/782))
303 +
304 +
305 +# v1.1.0
306 +
307 +New Features:
308 +
309 +- `cargo` now supports all of the same methods and event callbacks as `queue`.
310 +- Added `ensureAsync` - A wrapper that ensures an async function calls its callback on a later tick. ([#769](https://github.com/caolan/async/issues/769))
311 +- Optimized `map`, `eachOf`, and `waterfall` families of functions
312 +- Passing a `null` or `undefined` array to `map`, `each`, `parallel` and families will be treated as an empty array ([#667](https://github.com/caolan/async/issues/667)).
313 +- The callback is now optional for the composed results of `compose` and `seq`. ([#618](https://github.com/caolan/async/issues/618))
314 +- Reduced file size by 4kb, (minified version by 1kb)
315 +- Added code coverage through `nyc` and `coveralls` ([#768](https://github.com/caolan/async/issues/768))
316 +
317 +Bug Fixes:
318 +
319 +- `forever` will no longer stack overflow with a synchronous iterator ([#622](https://github.com/caolan/async/issues/622))
320 +- `eachLimit` and other limit functions will stop iterating once an error occurs ([#754](https://github.com/caolan/async/issues/754))
321 +- Always pass `null` in callbacks when there is no error ([#439](https://github.com/caolan/async/issues/439))
322 +- Ensure proper conditions when calling `drain()` after pushing an empty data set to a queue ([#668](https://github.com/caolan/async/issues/668))
323 +- `each` and family will properly handle an empty array ([#578](https://github.com/caolan/async/issues/578))
324 +- `eachSeries` and family will finish if the underlying array is modified during execution ([#557](https://github.com/caolan/async/issues/557))
325 +- `queue` will throw if a non-function is passed to `q.push()` ([#593](https://github.com/caolan/async/issues/593))
326 +- Doc fixes ([#629](https://github.com/caolan/async/issues/629), [#766](https://github.com/caolan/async/issues/766))
327 +
328 +
329 +# v1.0.0
330 +
331 +No known breaking changes, we are simply complying with semver from here on out.
332 +
333 +Changes:
334 +
335 +- Start using a changelog!
336 +- Add `forEachOf` for iterating over Objects (or to iterate Arrays with indexes available) ([#168](https://github.com/caolan/async/issues/168) [#704](https://github.com/caolan/async/issues/704) [#321](https://github.com/caolan/async/issues/321))
337 +- Detect deadlocks in `auto` ([#663](https://github.com/caolan/async/issues/663))
338 +- Better support for require.js ([#527](https://github.com/caolan/async/issues/527))
339 +- Throw if queue created with concurrency `0` ([#714](https://github.com/caolan/async/issues/714))
340 +- Fix unneeded iteration in `queue.resume()` ([#758](https://github.com/caolan/async/issues/758))
341 +- Guard against timer mocking overriding `setImmediate` ([#609](https://github.com/caolan/async/issues/609) [#611](https://github.com/caolan/async/issues/611))
342 +- Miscellaneous doc fixes ([#542](https://github.com/caolan/async/issues/542) [#596](https://github.com/caolan/async/issues/596) [#615](https://github.com/caolan/async/issues/615) [#628](https://github.com/caolan/async/issues/628) [#631](https://github.com/caolan/async/issues/631) [#690](https://github.com/caolan/async/issues/690) [#729](https://github.com/caolan/async/issues/729))
343 +- Use single noop function internally ([#546](https://github.com/caolan/async/issues/546))
344 +- Optimize internal `_each`, `_map` and `_keys` functions.
1 +Copyright (c) 2010-2018 Caolan McMahon
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to deal
5 +in the Software without restriction, including without limitation the rights
6 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 +copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in
11 +all copies or substantial portions of the Software.
12 +
13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 +THE SOFTWARE.
1 +![Async Logo](https://raw.githubusercontent.com/caolan/async/master/logo/async-logo_readme.jpg)
2 +
3 +[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async)
4 +[![Build Status via Azure Pipelines](https://dev.azure.com/caolanmcmahon/async/_apis/build/status/caolan.async?branchName=master)](https://dev.azure.com/caolanmcmahon/async/_build/latest?definitionId=1&branchName=master)
5 +[![NPM version](https://img.shields.io/npm/v/async.svg)](https://www.npmjs.com/package/async)
6 +[![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master)
7 +[![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
8 +[![jsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/async/badge?style=rounded)](https://www.jsdelivr.com/package/npm/async)
9 +
10 +<!--
11 +|Linux|Windows|MacOS|
12 +|-|-|-|
13 +|[![Linux Build Status](https://dev.azure.com/caolanmcmahon/async/_apis/build/status/caolan.async?branchName=master&jobName=Linux&configuration=Linux%20node_10_x)](https://dev.azure.com/caolanmcmahon/async/_build/latest?definitionId=1&branchName=master) | [![Windows Build Status](https://dev.azure.com/caolanmcmahon/async/_apis/build/status/caolan.async?branchName=master&jobName=Windows&configuration=Windows%20node_10_x)](https://dev.azure.com/caolanmcmahon/async/_build/latest?definitionId=1&branchName=master) | [![MacOS Build Status](https://dev.azure.com/caolanmcmahon/async/_apis/build/status/caolan.async?branchName=master&jobName=OSX&configuration=OSX%20node_10_x)](https://dev.azure.com/caolanmcmahon/async/_build/latest?definitionId=1&branchName=master)| -->
14 +
15 +Async is a utility module which provides straight-forward, powerful functions for working with [asynchronous JavaScript](http://caolan.github.io/async/v3/global.html). Although originally designed for use with [Node.js](https://nodejs.org/) and installable via `npm i async`, it can also be used directly in the browser. A ESM/MJS version is included in the main `async` package that should automatically be used with compatible bundlers such as Webpack and Rollup.
16 +
17 +A pure ESM version of Async is available as [`async-es`](https://www.npmjs.com/package/async-es).
18 +
19 +For Documentation, visit <https://caolan.github.io/async/>
20 +
21 +*For Async v1.5.x documentation, go [HERE](https://github.com/caolan/async/blob/v1.5.2/README.md)*
22 +
23 +
24 +```javascript
25 +// for use with Node-style callbacks...
26 +var async = require("async");
27 +
28 +var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
29 +var configs = {};
30 +
31 +async.forEachOf(obj, (value, key, callback) => {
32 + fs.readFile(__dirname + value, "utf8", (err, data) => {
33 + if (err) return callback(err);
34 + try {
35 + configs[key] = JSON.parse(data);
36 + } catch (e) {
37 + return callback(e);
38 + }
39 + callback();
40 + });
41 +}, err => {
42 + if (err) console.error(err.message);
43 + // configs is now a map of JSON data
44 + doSomethingWith(configs);
45 +});
46 +```
47 +
48 +```javascript
49 +var async = require("async");
50 +
51 +// ...or ES2017 async functions
52 +async.mapLimit(urls, 5, async function(url) {
53 + const response = await fetch(url)
54 + return response.body
55 +}, (err, results) => {
56 + if (err) throw err
57 + // results is now an array of the response bodies
58 + console.log(results)
59 +})
60 +```
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOf = require('./eachOf.js');
12 +
13 +var _eachOf2 = _interopRequireDefault(_eachOf);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Returns `true` if every element in `coll` satisfies an async test. If any
23 + * iteratee call returns `false`, the main `callback` is immediately called.
24 + *
25 + * @name every
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @alias all
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
33 + * in the collection in parallel.
34 + * The iteratee must complete with a boolean result value.
35 + * Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called after all the
37 + * `iteratee` functions have finished. Result will be either `true` or `false`
38 + * depending on the values of the async tests. Invoked with (err, result).
39 + * @returns {Promise} a promise, if no callback provided
40 + * @example
41 + *
42 + * // dir1 is a directory that contains file1.txt, file2.txt
43 + * // dir2 is a directory that contains file3.txt, file4.txt
44 + * // dir3 is a directory that contains file5.txt
45 + * // dir4 does not exist
46 + *
47 + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];
48 + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
49 + *
50 + * // asynchronous function that checks if a file exists
51 + * function fileExists(file, callback) {
52 + * fs.access(file, fs.constants.F_OK, (err) => {
53 + * callback(null, !err);
54 + * });
55 + * }
56 + *
57 + * // Using callbacks
58 + * async.every(fileList, fileExists, function(err, result) {
59 + * console.log(result);
60 + * // true
61 + * // result is true since every file exists
62 + * });
63 + *
64 + * async.every(withMissingFileList, fileExists, function(err, result) {
65 + * console.log(result);
66 + * // false
67 + * // result is false since NOT every file exists
68 + * });
69 + *
70 + * // Using Promises
71 + * async.every(fileList, fileExists)
72 + * .then( result => {
73 + * console.log(result);
74 + * // true
75 + * // result is true since every file exists
76 + * }).catch( err => {
77 + * console.log(err);
78 + * });
79 + *
80 + * async.every(withMissingFileList, fileExists)
81 + * .then( result => {
82 + * console.log(result);
83 + * // false
84 + * // result is false since NOT every file exists
85 + * }).catch( err => {
86 + * console.log(err);
87 + * });
88 + *
89 + * // Using async/await
90 + * async () => {
91 + * try {
92 + * let result = await async.every(fileList, fileExists);
93 + * console.log(result);
94 + * // true
95 + * // result is true since every file exists
96 + * }
97 + * catch (err) {
98 + * console.log(err);
99 + * }
100 + * }
101 + *
102 + * async () => {
103 + * try {
104 + * let result = await async.every(withMissingFileList, fileExists);
105 + * console.log(result);
106 + * // false
107 + * // result is false since NOT every file exists
108 + * }
109 + * catch (err) {
110 + * console.log(err);
111 + * }
112 + * }
113 + *
114 + */
115 +function every(coll, iteratee, callback) {
116 + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback);
117 +}
118 +exports.default = (0, _awaitify2.default)(every, 3);
119 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
23 + *
24 + * @name everyLimit
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.every]{@link module:Collections.every}
29 + * @alias allLimit
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {number} limit - The maximum number of async operations at a time.
33 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
34 + * in the collection in parallel.
35 + * The iteratee must complete with a boolean result value.
36 + * Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called after all the
38 + * `iteratee` functions have finished. Result will be either `true` or `false`
39 + * depending on the values of the async tests. Invoked with (err, result).
40 + * @returns {Promise} a promise, if no callback provided
41 + */
42 +function everyLimit(coll, limit, iteratee, callback) {
43 + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
44 +}
45 +exports.default = (0, _awaitify2.default)(everyLimit, 4);
46 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfSeries = require('./eachOfSeries.js');
12 +
13 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
23 + *
24 + * @name everySeries
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.every]{@link module:Collections.every}
29 + * @alias allSeries
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
33 + * in the collection in series.
34 + * The iteratee must complete with a boolean result value.
35 + * Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called after all the
37 + * `iteratee` functions have finished. Result will be either `true` or `false`
38 + * depending on the values of the async tests. Invoked with (err, result).
39 + * @returns {Promise} a promise, if no callback provided
40 + */
41 +function everySeries(coll, iteratee, callback) {
42 + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback);
43 +}
44 +exports.default = (0, _awaitify2.default)(everySeries, 3);
45 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOf = require('./eachOf.js');
12 +
13 +var _eachOf2 = _interopRequireDefault(_eachOf);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Returns `true` if at least one element in the `coll` satisfies an async test.
23 + * If any iteratee call returns `true`, the main `callback` is immediately
24 + * called.
25 + *
26 + * @name some
27 + * @static
28 + * @memberOf module:Collections
29 + * @method
30 + * @alias any
31 + * @category Collection
32 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
33 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
34 + * in the collections in parallel.
35 + * The iteratee should complete with a boolean `result` value.
36 + * Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called as soon as any
38 + * iteratee returns `true`, or after all the iteratee functions have finished.
39 + * Result will be either `true` or `false` depending on the values of the async
40 + * tests. Invoked with (err, result).
41 + * @returns {Promise} a promise, if no callback provided
42 + * @example
43 + *
44 + * // dir1 is a directory that contains file1.txt, file2.txt
45 + * // dir2 is a directory that contains file3.txt, file4.txt
46 + * // dir3 is a directory that contains file5.txt
47 + * // dir4 does not exist
48 + *
49 + * // asynchronous function that checks if a file exists
50 + * function fileExists(file, callback) {
51 + * fs.access(file, fs.constants.F_OK, (err) => {
52 + * callback(null, !err);
53 + * });
54 + * }
55 + *
56 + * // Using callbacks
57 + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,
58 + * function(err, result) {
59 + * console.log(result);
60 + * // true
61 + * // result is true since some file in the list exists
62 + * }
63 + *);
64 + *
65 + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,
66 + * function(err, result) {
67 + * console.log(result);
68 + * // false
69 + * // result is false since none of the files exists
70 + * }
71 + *);
72 + *
73 + * // Using Promises
74 + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)
75 + * .then( result => {
76 + * console.log(result);
77 + * // true
78 + * // result is true since some file in the list exists
79 + * }).catch( err => {
80 + * console.log(err);
81 + * });
82 + *
83 + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)
84 + * .then( result => {
85 + * console.log(result);
86 + * // false
87 + * // result is false since none of the files exists
88 + * }).catch( err => {
89 + * console.log(err);
90 + * });
91 + *
92 + * // Using async/await
93 + * async () => {
94 + * try {
95 + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);
96 + * console.log(result);
97 + * // true
98 + * // result is true since some file in the list exists
99 + * }
100 + * catch (err) {
101 + * console.log(err);
102 + * }
103 + * }
104 + *
105 + * async () => {
106 + * try {
107 + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);
108 + * console.log(result);
109 + * // false
110 + * // result is false since none of the files exists
111 + * }
112 + * catch (err) {
113 + * console.log(err);
114 + * }
115 + * }
116 + *
117 + */
118 +function some(coll, iteratee, callback) {
119 + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback);
120 +}
121 +exports.default = (0, _awaitify2.default)(some, 3);
122 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
23 + *
24 + * @name someLimit
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.some]{@link module:Collections.some}
29 + * @alias anyLimit
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {number} limit - The maximum number of async operations at a time.
33 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
34 + * in the collections in parallel.
35 + * The iteratee should complete with a boolean `result` value.
36 + * Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called as soon as any
38 + * iteratee returns `true`, or after all the iteratee functions have finished.
39 + * Result will be either `true` or `false` depending on the values of the async
40 + * tests. Invoked with (err, result).
41 + * @returns {Promise} a promise, if no callback provided
42 + */
43 +function someLimit(coll, limit, iteratee, callback) {
44 + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
45 +}
46 +exports.default = (0, _awaitify2.default)(someLimit, 4);
47 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfSeries = require('./eachOfSeries.js');
12 +
13 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
23 + *
24 + * @name someSeries
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.some]{@link module:Collections.some}
29 + * @alias anySeries
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
33 + * in the collections in series.
34 + * The iteratee should complete with a boolean `result` value.
35 + * Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called as soon as any
37 + * iteratee returns `true`, or after all the iteratee functions have finished.
38 + * Result will be either `true` or `false` depending on the values of the async
39 + * tests. Invoked with (err, result).
40 + * @returns {Promise} a promise, if no callback provided
41 + */
42 +function someSeries(coll, iteratee, callback) {
43 + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback);
44 +}
45 +exports.default = (0, _awaitify2.default)(someSeries, 3);
46 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +exports.default = function (fn, ...args) {
8 + return (...callArgs) => fn(...args, ...callArgs);
9 +};
10 +
11 +module.exports = exports["default"]; /**
12 + * Creates a continuation function with some arguments already applied.
13 + *
14 + * Useful as a shorthand when combined with other control flow functions. Any
15 + * arguments passed to the returned function are added to the arguments
16 + * originally passed to apply.
17 + *
18 + * @name apply
19 + * @static
20 + * @memberOf module:Utils
21 + * @method
22 + * @category Util
23 + * @param {Function} fn - The function you want to eventually apply all
24 + * arguments to. Invokes with (arguments...).
25 + * @param {...*} arguments... - Any number of arguments to automatically apply
26 + * when the continuation is called.
27 + * @returns {Function} the partially-applied function
28 + * @example
29 + *
30 + * // using apply
31 + * async.parallel([
32 + * async.apply(fs.writeFile, 'testfile1', 'test1'),
33 + * async.apply(fs.writeFile, 'testfile2', 'test2')
34 + * ]);
35 + *
36 + *
37 + * // the same process without using apply
38 + * async.parallel([
39 + * function(callback) {
40 + * fs.writeFile('testfile1', 'test1', callback);
41 + * },
42 + * function(callback) {
43 + * fs.writeFile('testfile2', 'test2', callback);
44 + * }
45 + * ]);
46 + *
47 + * // It's possible to pass any number of additional arguments when calling the
48 + * // continuation:
49 + *
50 + * node> var fn = async.apply(sys.puts, 'one');
51 + * node> fn('two', 'three');
52 + * one
53 + * two
54 + * three
55 + */
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _applyEach = require('./internal/applyEach.js');
8 +
9 +var _applyEach2 = _interopRequireDefault(_applyEach);
10 +
11 +var _map = require('./map.js');
12 +
13 +var _map2 = _interopRequireDefault(_map);
14 +
15 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16 +
17 +/**
18 + * Applies the provided arguments to each function in the array, calling
19 + * `callback` after all functions have completed. If you only provide the first
20 + * argument, `fns`, then it will return a function which lets you pass in the
21 + * arguments as if it were a single function call. If more arguments are
22 + * provided, `callback` is required while `args` is still optional. The results
23 + * for each of the applied async functions are passed to the final callback
24 + * as an array.
25 + *
26 + * @name applyEach
27 + * @static
28 + * @memberOf module:ControlFlow
29 + * @method
30 + * @category Control Flow
31 + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s
32 + * to all call with the same arguments
33 + * @param {...*} [args] - any number of separate arguments to pass to the
34 + * function.
35 + * @param {Function} [callback] - the final argument should be the callback,
36 + * called when all functions have completed processing.
37 + * @returns {AsyncFunction} - Returns a function that takes no args other than
38 + * an optional callback, that is the result of applying the `args` to each
39 + * of the functions.
40 + * @example
41 + *
42 + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')
43 + *
44 + * appliedFn((err, results) => {
45 + * // results[0] is the results for `enableSearch`
46 + * // results[1] is the results for `updateSchema`
47 + * });
48 + *
49 + * // partial application example:
50 + * async.each(
51 + * buckets,
52 + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),
53 + * callback
54 + * );
55 + */
56 +exports.default = (0, _applyEach2.default)(_map2.default);
57 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _applyEach = require('./internal/applyEach.js');
8 +
9 +var _applyEach2 = _interopRequireDefault(_applyEach);
10 +
11 +var _mapSeries = require('./mapSeries.js');
12 +
13 +var _mapSeries2 = _interopRequireDefault(_mapSeries);
14 +
15 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16 +
17 +/**
18 + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.
19 + *
20 + * @name applyEachSeries
21 + * @static
22 + * @memberOf module:ControlFlow
23 + * @method
24 + * @see [async.applyEach]{@link module:ControlFlow.applyEach}
25 + * @category Control Flow
26 + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all
27 + * call with the same arguments
28 + * @param {...*} [args] - any number of separate arguments to pass to the
29 + * function.
30 + * @param {Function} [callback] - the final argument should be the callback,
31 + * called when all functions have completed processing.
32 + * @returns {AsyncFunction} - A function, that when called, is the result of
33 + * appling the `args` to the list of functions. It takes no args, other than
34 + * a callback.
35 + */
36 +exports.default = (0, _applyEach2.default)(_mapSeries2.default);
37 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = asyncify;
7 +
8 +var _initialParams = require('./internal/initialParams.js');
9 +
10 +var _initialParams2 = _interopRequireDefault(_initialParams);
11 +
12 +var _setImmediate = require('./internal/setImmediate.js');
13 +
14 +var _setImmediate2 = _interopRequireDefault(_setImmediate);
15 +
16 +var _wrapAsync = require('./internal/wrapAsync.js');
17 +
18 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19 +
20 +/**
21 + * Take a sync function and make it async, passing its return value to a
22 + * callback. This is useful for plugging sync functions into a waterfall,
23 + * series, or other async functions. Any arguments passed to the generated
24 + * function will be passed to the wrapped function (except for the final
25 + * callback argument). Errors thrown will be passed to the callback.
26 + *
27 + * If the function passed to `asyncify` returns a Promise, that promises's
28 + * resolved/rejected state will be used to call the callback, rather than simply
29 + * the synchronous return value.
30 + *
31 + * This also means you can asyncify ES2017 `async` functions.
32 + *
33 + * @name asyncify
34 + * @static
35 + * @memberOf module:Utils
36 + * @method
37 + * @alias wrapSync
38 + * @category Util
39 + * @param {Function} func - The synchronous function, or Promise-returning
40 + * function to convert to an {@link AsyncFunction}.
41 + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
42 + * invoked with `(args..., callback)`.
43 + * @example
44 + *
45 + * // passing a regular synchronous function
46 + * async.waterfall([
47 + * async.apply(fs.readFile, filename, "utf8"),
48 + * async.asyncify(JSON.parse),
49 + * function (data, next) {
50 + * // data is the result of parsing the text.
51 + * // If there was a parsing error, it would have been caught.
52 + * }
53 + * ], callback);
54 + *
55 + * // passing a function returning a promise
56 + * async.waterfall([
57 + * async.apply(fs.readFile, filename, "utf8"),
58 + * async.asyncify(function (contents) {
59 + * return db.model.create(contents);
60 + * }),
61 + * function (model, next) {
62 + * // `model` is the instantiated model object.
63 + * // If there was an error, this function would be skipped.
64 + * }
65 + * ], callback);
66 + *
67 + * // es2017 example, though `asyncify` is not needed if your JS environment
68 + * // supports async functions out of the box
69 + * var q = async.queue(async.asyncify(async function(file) {
70 + * var intermediateStep = await processFile(file);
71 + * return await somePromise(intermediateStep)
72 + * }));
73 + *
74 + * q.push(files);
75 + */
76 +function asyncify(func) {
77 + if ((0, _wrapAsync.isAsync)(func)) {
78 + return function (...args /*, callback*/) {
79 + const callback = args.pop();
80 + const promise = func.apply(this, args);
81 + return handlePromise(promise, callback);
82 + };
83 + }
84 +
85 + return (0, _initialParams2.default)(function (args, callback) {
86 + var result;
87 + try {
88 + result = func.apply(this, args);
89 + } catch (e) {
90 + return callback(e);
91 + }
92 + // if result is Promise object
93 + if (result && typeof result.then === 'function') {
94 + return handlePromise(result, callback);
95 + } else {
96 + callback(null, result);
97 + }
98 + });
99 +}
100 +
101 +function handlePromise(promise, callback) {
102 + return promise.then(value => {
103 + invokeCallback(callback, null, value);
104 + }, err => {
105 + invokeCallback(callback, err && err.message ? err : new Error(err));
106 + });
107 +}
108 +
109 +function invokeCallback(callback, error, value) {
110 + try {
111 + callback(error, value);
112 + } catch (err) {
113 + (0, _setImmediate2.default)(e => {
114 + throw e;
115 + }, err);
116 + }
117 +}
118 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = auto;
7 +
8 +var _once = require('./internal/once.js');
9 +
10 +var _once2 = _interopRequireDefault(_once);
11 +
12 +var _onlyOnce = require('./internal/onlyOnce.js');
13 +
14 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
15 +
16 +var _wrapAsync = require('./internal/wrapAsync.js');
17 +
18 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
19 +
20 +var _promiseCallback = require('./internal/promiseCallback.js');
21 +
22 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23 +
24 +/**
25 + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on
26 + * their requirements. Each function can optionally depend on other functions
27 + * being completed first, and each function is run as soon as its requirements
28 + * are satisfied.
29 + *
30 + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence
31 + * will stop. Further tasks will not execute (so any other functions depending
32 + * on it will not run), and the main `callback` is immediately called with the
33 + * error.
34 + *
35 + * {@link AsyncFunction}s also receive an object containing the results of functions which
36 + * have completed so far as the first argument, if they have dependencies. If a
37 + * task function has no dependencies, it will only be passed a callback.
38 + *
39 + * @name auto
40 + * @static
41 + * @memberOf module:ControlFlow
42 + * @method
43 + * @category Control Flow
44 + * @param {Object} tasks - An object. Each of its properties is either a
45 + * function or an array of requirements, with the {@link AsyncFunction} itself the last item
46 + * in the array. The object's key of a property serves as the name of the task
47 + * defined by that property, i.e. can be used when specifying requirements for
48 + * other tasks. The function receives one or two arguments:
49 + * * a `results` object, containing the results of the previously executed
50 + * functions, only passed if the task has any dependencies,
51 + * * a `callback(err, result)` function, which must be called when finished,
52 + * passing an `error` (which can be `null`) and the result of the function's
53 + * execution.
54 + * @param {number} [concurrency=Infinity] - An optional `integer` for
55 + * determining the maximum number of tasks that can be run in parallel. By
56 + * default, as many as possible.
57 + * @param {Function} [callback] - An optional callback which is called when all
58 + * the tasks have been completed. It receives the `err` argument if any `tasks`
59 + * pass an error to their callback. Results are always returned; however, if an
60 + * error occurs, no further `tasks` will be performed, and the results object
61 + * will only contain partial results. Invoked with (err, results).
62 + * @returns {Promise} a promise, if a callback is not passed
63 + * @example
64 + *
65 + * //Using Callbacks
66 + * async.auto({
67 + * get_data: function(callback) {
68 + * // async code to get some data
69 + * callback(null, 'data', 'converted to array');
70 + * },
71 + * make_folder: function(callback) {
72 + * // async code to create a directory to store a file in
73 + * // this is run at the same time as getting the data
74 + * callback(null, 'folder');
75 + * },
76 + * write_file: ['get_data', 'make_folder', function(results, callback) {
77 + * // once there is some data and the directory exists,
78 + * // write the data to a file in the directory
79 + * callback(null, 'filename');
80 + * }],
81 + * email_link: ['write_file', function(results, callback) {
82 + * // once the file is written let's email a link to it...
83 + * callback(null, {'file':results.write_file, 'email':'user@example.com'});
84 + * }]
85 + * }, function(err, results) {
86 + * if (err) {
87 + * console.log('err = ', err);
88 + * }
89 + * console.log('results = ', results);
90 + * // results = {
91 + * // get_data: ['data', 'converted to array']
92 + * // make_folder; 'folder',
93 + * // write_file: 'filename'
94 + * // email_link: { file: 'filename', email: 'user@example.com' }
95 + * // }
96 + * });
97 + *
98 + * //Using Promises
99 + * async.auto({
100 + * get_data: function(callback) {
101 + * console.log('in get_data');
102 + * // async code to get some data
103 + * callback(null, 'data', 'converted to array');
104 + * },
105 + * make_folder: function(callback) {
106 + * console.log('in make_folder');
107 + * // async code to create a directory to store a file in
108 + * // this is run at the same time as getting the data
109 + * callback(null, 'folder');
110 + * },
111 + * write_file: ['get_data', 'make_folder', function(results, callback) {
112 + * // once there is some data and the directory exists,
113 + * // write the data to a file in the directory
114 + * callback(null, 'filename');
115 + * }],
116 + * email_link: ['write_file', function(results, callback) {
117 + * // once the file is written let's email a link to it...
118 + * callback(null, {'file':results.write_file, 'email':'user@example.com'});
119 + * }]
120 + * }).then(results => {
121 + * console.log('results = ', results);
122 + * // results = {
123 + * // get_data: ['data', 'converted to array']
124 + * // make_folder; 'folder',
125 + * // write_file: 'filename'
126 + * // email_link: { file: 'filename', email: 'user@example.com' }
127 + * // }
128 + * }).catch(err => {
129 + * console.log('err = ', err);
130 + * });
131 + *
132 + * //Using async/await
133 + * async () => {
134 + * try {
135 + * let results = await async.auto({
136 + * get_data: function(callback) {
137 + * // async code to get some data
138 + * callback(null, 'data', 'converted to array');
139 + * },
140 + * make_folder: function(callback) {
141 + * // async code to create a directory to store a file in
142 + * // this is run at the same time as getting the data
143 + * callback(null, 'folder');
144 + * },
145 + * write_file: ['get_data', 'make_folder', function(results, callback) {
146 + * // once there is some data and the directory exists,
147 + * // write the data to a file in the directory
148 + * callback(null, 'filename');
149 + * }],
150 + * email_link: ['write_file', function(results, callback) {
151 + * // once the file is written let's email a link to it...
152 + * callback(null, {'file':results.write_file, 'email':'user@example.com'});
153 + * }]
154 + * });
155 + * console.log('results = ', results);
156 + * // results = {
157 + * // get_data: ['data', 'converted to array']
158 + * // make_folder; 'folder',
159 + * // write_file: 'filename'
160 + * // email_link: { file: 'filename', email: 'user@example.com' }
161 + * // }
162 + * }
163 + * catch (err) {
164 + * console.log(err);
165 + * }
166 + * }
167 + *
168 + */
169 +function auto(tasks, concurrency, callback) {
170 + if (typeof concurrency !== 'number') {
171 + // concurrency is optional, shift the args.
172 + callback = concurrency;
173 + concurrency = null;
174 + }
175 + callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)());
176 + var numTasks = Object.keys(tasks).length;
177 + if (!numTasks) {
178 + return callback(null);
179 + }
180 + if (!concurrency) {
181 + concurrency = numTasks;
182 + }
183 +
184 + var results = {};
185 + var runningTasks = 0;
186 + var canceled = false;
187 + var hasError = false;
188 +
189 + var listeners = Object.create(null);
190 +
191 + var readyTasks = [];
192 +
193 + // for cycle detection:
194 + var readyToCheck = []; // tasks that have been identified as reachable
195 + // without the possibility of returning to an ancestor task
196 + var uncheckedDependencies = {};
197 +
198 + Object.keys(tasks).forEach(key => {
199 + var task = tasks[key];
200 + if (!Array.isArray(task)) {
201 + // no dependencies
202 + enqueueTask(key, [task]);
203 + readyToCheck.push(key);
204 + return;
205 + }
206 +
207 + var dependencies = task.slice(0, task.length - 1);
208 + var remainingDependencies = dependencies.length;
209 + if (remainingDependencies === 0) {
210 + enqueueTask(key, task);
211 + readyToCheck.push(key);
212 + return;
213 + }
214 + uncheckedDependencies[key] = remainingDependencies;
215 +
216 + dependencies.forEach(dependencyName => {
217 + if (!tasks[dependencyName]) {
218 + throw new Error('async.auto task `' + key + '` has a non-existent dependency `' + dependencyName + '` in ' + dependencies.join(', '));
219 + }
220 + addListener(dependencyName, () => {
221 + remainingDependencies--;
222 + if (remainingDependencies === 0) {
223 + enqueueTask(key, task);
224 + }
225 + });
226 + });
227 + });
228 +
229 + checkForDeadlocks();
230 + processQueue();
231 +
232 + function enqueueTask(key, task) {
233 + readyTasks.push(() => runTask(key, task));
234 + }
235 +
236 + function processQueue() {
237 + if (canceled) return;
238 + if (readyTasks.length === 0 && runningTasks === 0) {
239 + return callback(null, results);
240 + }
241 + while (readyTasks.length && runningTasks < concurrency) {
242 + var run = readyTasks.shift();
243 + run();
244 + }
245 + }
246 +
247 + function addListener(taskName, fn) {
248 + var taskListeners = listeners[taskName];
249 + if (!taskListeners) {
250 + taskListeners = listeners[taskName] = [];
251 + }
252 +
253 + taskListeners.push(fn);
254 + }
255 +
256 + function taskComplete(taskName) {
257 + var taskListeners = listeners[taskName] || [];
258 + taskListeners.forEach(fn => fn());
259 + processQueue();
260 + }
261 +
262 + function runTask(key, task) {
263 + if (hasError) return;
264 +
265 + var taskCallback = (0, _onlyOnce2.default)((err, ...result) => {
266 + runningTasks--;
267 + if (err === false) {
268 + canceled = true;
269 + return;
270 + }
271 + if (result.length < 2) {
272 + [result] = result;
273 + }
274 + if (err) {
275 + var safeResults = {};
276 + Object.keys(results).forEach(rkey => {
277 + safeResults[rkey] = results[rkey];
278 + });
279 + safeResults[key] = result;
280 + hasError = true;
281 + listeners = Object.create(null);
282 + if (canceled) return;
283 + callback(err, safeResults);
284 + } else {
285 + results[key] = result;
286 + taskComplete(key);
287 + }
288 + });
289 +
290 + runningTasks++;
291 + var taskFn = (0, _wrapAsync2.default)(task[task.length - 1]);
292 + if (task.length > 1) {
293 + taskFn(results, taskCallback);
294 + } else {
295 + taskFn(taskCallback);
296 + }
297 + }
298 +
299 + function checkForDeadlocks() {
300 + // Kahn's algorithm
301 + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
302 + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
303 + var currentTask;
304 + var counter = 0;
305 + while (readyToCheck.length) {
306 + currentTask = readyToCheck.pop();
307 + counter++;
308 + getDependents(currentTask).forEach(dependent => {
309 + if (--uncheckedDependencies[dependent] === 0) {
310 + readyToCheck.push(dependent);
311 + }
312 + });
313 + }
314 +
315 + if (counter !== numTasks) {
316 + throw new Error('async.auto cannot execute tasks due to a recursive dependency');
317 + }
318 + }
319 +
320 + function getDependents(taskName) {
321 + var result = [];
322 + Object.keys(tasks).forEach(key => {
323 + const task = tasks[key];
324 + if (Array.isArray(task) && task.indexOf(taskName) >= 0) {
325 + result.push(key);
326 + }
327 + });
328 + return result;
329 + }
330 +
331 + return callback[_promiseCallback.PROMISE_SYMBOL];
332 +}
333 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = autoInject;
7 +
8 +var _auto = require('./auto.js');
9 +
10 +var _auto2 = _interopRequireDefault(_auto);
11 +
12 +var _wrapAsync = require('./internal/wrapAsync.js');
13 +
14 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/;
19 +var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/;
20 +var FN_ARG_SPLIT = /,/;
21 +var FN_ARG = /(=.+)?(\s*)$/;
22 +
23 +function stripComments(string) {
24 + let stripped = '';
25 + let index = 0;
26 + let endBlockComment = string.indexOf('*/');
27 + while (index < string.length) {
28 + if (string[index] === '/' && string[index + 1] === '/') {
29 + // inline comment
30 + let endIndex = string.indexOf('\n', index);
31 + index = endIndex === -1 ? string.length : endIndex;
32 + } else if (endBlockComment !== -1 && string[index] === '/' && string[index + 1] === '*') {
33 + // block comment
34 + let endIndex = string.indexOf('*/', index);
35 + if (endIndex !== -1) {
36 + index = endIndex + 2;
37 + endBlockComment = string.indexOf('*/', index);
38 + } else {
39 + stripped += string[index];
40 + index++;
41 + }
42 + } else {
43 + stripped += string[index];
44 + index++;
45 + }
46 + }
47 + return stripped;
48 +}
49 +
50 +function parseParams(func) {
51 + const src = stripComments(func.toString());
52 + let match = src.match(FN_ARGS);
53 + if (!match) {
54 + match = src.match(ARROW_FN_ARGS);
55 + }
56 + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src);
57 + let [, args] = match;
58 + return args.replace(/\s/g, '').split(FN_ARG_SPLIT).map(arg => arg.replace(FN_ARG, '').trim());
59 +}
60 +
61 +/**
62 + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent
63 + * tasks are specified as parameters to the function, after the usual callback
64 + * parameter, with the parameter names matching the names of the tasks it
65 + * depends on. This can provide even more readable task graphs which can be
66 + * easier to maintain.
67 + *
68 + * If a final callback is specified, the task results are similarly injected,
69 + * specified as named parameters after the initial error parameter.
70 + *
71 + * The autoInject function is purely syntactic sugar and its semantics are
72 + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.
73 + *
74 + * @name autoInject
75 + * @static
76 + * @memberOf module:ControlFlow
77 + * @method
78 + * @see [async.auto]{@link module:ControlFlow.auto}
79 + * @category Control Flow
80 + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of
81 + * the form 'func([dependencies...], callback). The object's key of a property
82 + * serves as the name of the task defined by that property, i.e. can be used
83 + * when specifying requirements for other tasks.
84 + * * The `callback` parameter is a `callback(err, result)` which must be called
85 + * when finished, passing an `error` (which can be `null`) and the result of
86 + * the function's execution. The remaining parameters name other tasks on
87 + * which the task is dependent, and the results from those tasks are the
88 + * arguments of those parameters.
89 + * @param {Function} [callback] - An optional callback which is called when all
90 + * the tasks have been completed. It receives the `err` argument if any `tasks`
91 + * pass an error to their callback, and a `results` object with any completed
92 + * task results, similar to `auto`.
93 + * @returns {Promise} a promise, if no callback is passed
94 + * @example
95 + *
96 + * // The example from `auto` can be rewritten as follows:
97 + * async.autoInject({
98 + * get_data: function(callback) {
99 + * // async code to get some data
100 + * callback(null, 'data', 'converted to array');
101 + * },
102 + * make_folder: function(callback) {
103 + * // async code to create a directory to store a file in
104 + * // this is run at the same time as getting the data
105 + * callback(null, 'folder');
106 + * },
107 + * write_file: function(get_data, make_folder, callback) {
108 + * // once there is some data and the directory exists,
109 + * // write the data to a file in the directory
110 + * callback(null, 'filename');
111 + * },
112 + * email_link: function(write_file, callback) {
113 + * // once the file is written let's email a link to it...
114 + * // write_file contains the filename returned by write_file.
115 + * callback(null, {'file':write_file, 'email':'user@example.com'});
116 + * }
117 + * }, function(err, results) {
118 + * console.log('err = ', err);
119 + * console.log('email_link = ', results.email_link);
120 + * });
121 + *
122 + * // If you are using a JS minifier that mangles parameter names, `autoInject`
123 + * // will not work with plain functions, since the parameter names will be
124 + * // collapsed to a single letter identifier. To work around this, you can
125 + * // explicitly specify the names of the parameters your task function needs
126 + * // in an array, similar to Angular.js dependency injection.
127 + *
128 + * // This still has an advantage over plain `auto`, since the results a task
129 + * // depends on are still spread into arguments.
130 + * async.autoInject({
131 + * //...
132 + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
133 + * callback(null, 'filename');
134 + * }],
135 + * email_link: ['write_file', function(write_file, callback) {
136 + * callback(null, {'file':write_file, 'email':'user@example.com'});
137 + * }]
138 + * //...
139 + * }, function(err, results) {
140 + * console.log('err = ', err);
141 + * console.log('email_link = ', results.email_link);
142 + * });
143 + */
144 +function autoInject(tasks, callback) {
145 + var newTasks = {};
146 +
147 + Object.keys(tasks).forEach(key => {
148 + var taskFn = tasks[key];
149 + var params;
150 + var fnIsAsync = (0, _wrapAsync.isAsync)(taskFn);
151 + var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0;
152 +
153 + if (Array.isArray(taskFn)) {
154 + params = [...taskFn];
155 + taskFn = params.pop();
156 +
157 + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
158 + } else if (hasNoDeps) {
159 + // no dependencies, use the function as-is
160 + newTasks[key] = taskFn;
161 + } else {
162 + params = parseParams(taskFn);
163 + if (taskFn.length === 0 && !fnIsAsync && params.length === 0) {
164 + throw new Error("autoInject task functions require explicit parameters.");
165 + }
166 +
167 + // remove callback param
168 + if (!fnIsAsync) params.pop();
169 +
170 + newTasks[key] = params.concat(newTask);
171 + }
172 +
173 + function newTask(results, taskCb) {
174 + var newArgs = params.map(name => results[name]);
175 + newArgs.push(taskCb);
176 + (0, _wrapAsync2.default)(taskFn)(...newArgs);
177 + }
178 + });
179 +
180 + return (0, _auto2.default)(newTasks, callback);
181 +}
182 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "name": "async",
3 + "main": "dist/async.js",
4 + "ignore": [
5 + "bower_components",
6 + "lib",
7 + "test",
8 + "node_modules",
9 + "perf",
10 + "support",
11 + "**/.*",
12 + "*.config.js",
13 + "*.json",
14 + "index.js",
15 + "Makefile"
16 + ]
17 +}
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = cargo;
7 +
8 +var _queue = require('./internal/queue.js');
9 +
10 +var _queue2 = _interopRequireDefault(_queue);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * Creates a `cargo` object with the specified payload. Tasks added to the
16 + * cargo will be processed altogether (up to the `payload` limit). If the
17 + * `worker` is in progress, the task is queued until it becomes available. Once
18 + * the `worker` has completed some tasks, each callback of those tasks is
19 + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
20 + * for how `cargo` and `queue` work.
21 + *
22 + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
23 + * at a time, cargo passes an array of tasks to a single worker, repeating
24 + * when the worker is finished.
25 + *
26 + * @name cargo
27 + * @static
28 + * @memberOf module:ControlFlow
29 + * @method
30 + * @see [async.queue]{@link module:ControlFlow.queue}
31 + * @category Control Flow
32 + * @param {AsyncFunction} worker - An asynchronous function for processing an array
33 + * of queued tasks. Invoked with `(tasks, callback)`.
34 + * @param {number} [payload=Infinity] - An optional `integer` for determining
35 + * how many tasks should be processed per round; if omitted, the default is
36 + * unlimited.
37 + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can
38 + * attached as certain properties to listen for specific events during the
39 + * lifecycle of the cargo and inner queue.
40 + * @example
41 + *
42 + * // create a cargo object with payload 2
43 + * var cargo = async.cargo(function(tasks, callback) {
44 + * for (var i=0; i<tasks.length; i++) {
45 + * console.log('hello ' + tasks[i].name);
46 + * }
47 + * callback();
48 + * }, 2);
49 + *
50 + * // add some items
51 + * cargo.push({name: 'foo'}, function(err) {
52 + * console.log('finished processing foo');
53 + * });
54 + * cargo.push({name: 'bar'}, function(err) {
55 + * console.log('finished processing bar');
56 + * });
57 + * await cargo.push({name: 'baz'});
58 + * console.log('finished processing baz');
59 + */
60 +function cargo(worker, payload) {
61 + return (0, _queue2.default)(worker, 1, payload);
62 +}
63 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = cargo;
7 +
8 +var _queue = require('./internal/queue.js');
9 +
10 +var _queue2 = _interopRequireDefault(_queue);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * Creates a `cargoQueue` object with the specified payload. Tasks added to the
16 + * cargoQueue will be processed together (up to the `payload` limit) in `concurrency` parallel workers.
17 + * If the all `workers` are in progress, the task is queued until one becomes available. Once
18 + * a `worker` has completed some tasks, each callback of those tasks is
19 + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
20 + * for how `cargo` and `queue` work.
21 + *
22 + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers
23 + * at a time, and [`cargo`]{@link module:ControlFlow.cargo} passes an array of tasks to a single worker,
24 + * the cargoQueue passes an array of tasks to multiple parallel workers.
25 + *
26 + * @name cargoQueue
27 + * @static
28 + * @memberOf module:ControlFlow
29 + * @method
30 + * @see [async.queue]{@link module:ControlFlow.queue}
31 + * @see [async.cargo]{@link module:ControlFLow.cargo}
32 + * @category Control Flow
33 + * @param {AsyncFunction} worker - An asynchronous function for processing an array
34 + * of queued tasks. Invoked with `(tasks, callback)`.
35 + * @param {number} [concurrency=1] - An `integer` for determining how many
36 + * `worker` functions should be run in parallel. If omitted, the concurrency
37 + * defaults to `1`. If the concurrency is `0`, an error is thrown.
38 + * @param {number} [payload=Infinity] - An optional `integer` for determining
39 + * how many tasks should be processed per round; if omitted, the default is
40 + * unlimited.
41 + * @returns {module:ControlFlow.QueueObject} A cargoQueue object to manage the tasks. Callbacks can
42 + * attached as certain properties to listen for specific events during the
43 + * lifecycle of the cargoQueue and inner queue.
44 + * @example
45 + *
46 + * // create a cargoQueue object with payload 2 and concurrency 2
47 + * var cargoQueue = async.cargoQueue(function(tasks, callback) {
48 + * for (var i=0; i<tasks.length; i++) {
49 + * console.log('hello ' + tasks[i].name);
50 + * }
51 + * callback();
52 + * }, 2, 2);
53 + *
54 + * // add some items
55 + * cargoQueue.push({name: 'foo'}, function(err) {
56 + * console.log('finished processing foo');
57 + * });
58 + * cargoQueue.push({name: 'bar'}, function(err) {
59 + * console.log('finished processing bar');
60 + * });
61 + * cargoQueue.push({name: 'baz'}, function(err) {
62 + * console.log('finished processing baz');
63 + * });
64 + * cargoQueue.push({name: 'boo'}, function(err) {
65 + * console.log('finished processing boo');
66 + * });
67 + */
68 +function cargo(worker, concurrency, payload) {
69 + return (0, _queue2.default)(worker, concurrency, payload);
70 +}
71 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = compose;
7 +
8 +var _seq = require('./seq.js');
9 +
10 +var _seq2 = _interopRequireDefault(_seq);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * Creates a function which is a composition of the passed asynchronous
16 + * functions. Each function consumes the return value of the function that
17 + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result
18 + * of `f(g(h()))`, only this version uses callbacks to obtain the return values.
19 + *
20 + * If the last argument to the composed function is not a function, a promise
21 + * is returned when you call it.
22 + *
23 + * Each function is executed with the `this` binding of the composed function.
24 + *
25 + * @name compose
26 + * @static
27 + * @memberOf module:ControlFlow
28 + * @method
29 + * @category Control Flow
30 + * @param {...AsyncFunction} functions - the asynchronous functions to compose
31 + * @returns {Function} an asynchronous function that is the composed
32 + * asynchronous `functions`
33 + * @example
34 + *
35 + * function add1(n, callback) {
36 + * setTimeout(function () {
37 + * callback(null, n + 1);
38 + * }, 10);
39 + * }
40 + *
41 + * function mul3(n, callback) {
42 + * setTimeout(function () {
43 + * callback(null, n * 3);
44 + * }, 10);
45 + * }
46 + *
47 + * var add1mul3 = async.compose(mul3, add1);
48 + * add1mul3(4, function (err, result) {
49 + * // result now equals 15
50 + * });
51 + */
52 +function compose(...args) {
53 + return (0, _seq2.default)(...args.reverse());
54 +}
55 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _concatLimit = require('./concatLimit.js');
8 +
9 +var _concatLimit2 = _interopRequireDefault(_concatLimit);
10 +
11 +var _awaitify = require('./internal/awaitify.js');
12 +
13 +var _awaitify2 = _interopRequireDefault(_awaitify);
14 +
15 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16 +
17 +/**
18 + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
19 + * the concatenated list. The `iteratee`s are called in parallel, and the
20 + * results are concatenated as they return. The results array will be returned in
21 + * the original order of `coll` passed to the `iteratee` function.
22 + *
23 + * @name concat
24 + * @static
25 + * @memberOf module:Collections
26 + * @method
27 + * @category Collection
28 + * @alias flatMap
29 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
30 + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
31 + * which should use an array as its result. Invoked with (item, callback).
32 + * @param {Function} [callback] - A callback which is called after all the
33 + * `iteratee` functions have finished, or an error occurs. Results is an array
34 + * containing the concatenated results of the `iteratee` function. Invoked with
35 + * (err, results).
36 + * @returns A Promise, if no callback is passed
37 + * @example
38 + *
39 + * // dir1 is a directory that contains file1.txt, file2.txt
40 + * // dir2 is a directory that contains file3.txt, file4.txt
41 + * // dir3 is a directory that contains file5.txt
42 + * // dir4 does not exist
43 + *
44 + * let directoryList = ['dir1','dir2','dir3'];
45 + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];
46 + *
47 + * // Using callbacks
48 + * async.concat(directoryList, fs.readdir, function(err, results) {
49 + * if (err) {
50 + * console.log(err);
51 + * } else {
52 + * console.log(results);
53 + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
54 + * }
55 + * });
56 + *
57 + * // Error Handling
58 + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {
59 + * if (err) {
60 + * console.log(err);
61 + * // [ Error: ENOENT: no such file or directory ]
62 + * // since dir4 does not exist
63 + * } else {
64 + * console.log(results);
65 + * }
66 + * });
67 + *
68 + * // Using Promises
69 + * async.concat(directoryList, fs.readdir)
70 + * .then(results => {
71 + * console.log(results);
72 + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
73 + * }).catch(err => {
74 + * console.log(err);
75 + * });
76 + *
77 + * // Error Handling
78 + * async.concat(withMissingDirectoryList, fs.readdir)
79 + * .then(results => {
80 + * console.log(results);
81 + * }).catch(err => {
82 + * console.log(err);
83 + * // [ Error: ENOENT: no such file or directory ]
84 + * // since dir4 does not exist
85 + * });
86 + *
87 + * // Using async/await
88 + * async () => {
89 + * try {
90 + * let results = await async.concat(directoryList, fs.readdir);
91 + * console.log(results);
92 + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
93 + * } catch (err) {
94 + * console.log(err);
95 + * }
96 + * }
97 + *
98 + * // Error Handling
99 + * async () => {
100 + * try {
101 + * let results = await async.concat(withMissingDirectoryList, fs.readdir);
102 + * console.log(results);
103 + * } catch (err) {
104 + * console.log(err);
105 + * // [ Error: ENOENT: no such file or directory ]
106 + * // since dir4 does not exist
107 + * }
108 + * }
109 + *
110 + */
111 +function concat(coll, iteratee, callback) {
112 + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback);
113 +}
114 +exports.default = (0, _awaitify2.default)(concat, 3);
115 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _wrapAsync = require('./internal/wrapAsync.js');
8 +
9 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
10 +
11 +var _mapLimit = require('./mapLimit.js');
12 +
13 +var _mapLimit2 = _interopRequireDefault(_mapLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
23 + *
24 + * @name concatLimit
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.concat]{@link module:Collections.concat}
29 + * @category Collection
30 + * @alias flatMapLimit
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {number} limit - The maximum number of async operations at a time.
33 + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
34 + * which should use an array as its result. Invoked with (item, callback).
35 + * @param {Function} [callback] - A callback which is called after all the
36 + * `iteratee` functions have finished, or an error occurs. Results is an array
37 + * containing the concatenated results of the `iteratee` function. Invoked with
38 + * (err, results).
39 + * @returns A Promise, if no callback is passed
40 + */
41 +function concatLimit(coll, limit, iteratee, callback) {
42 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
43 + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => {
44 + _iteratee(val, (err, ...args) => {
45 + if (err) return iterCb(err);
46 + return iterCb(err, args);
47 + });
48 + }, (err, mapResults) => {
49 + var result = [];
50 + for (var i = 0; i < mapResults.length; i++) {
51 + if (mapResults[i]) {
52 + result = result.concat(...mapResults[i]);
53 + }
54 + }
55 +
56 + return callback(err, result);
57 + });
58 +}
59 +exports.default = (0, _awaitify2.default)(concatLimit, 4);
60 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _concatLimit = require('./concatLimit.js');
8 +
9 +var _concatLimit2 = _interopRequireDefault(_concatLimit);
10 +
11 +var _awaitify = require('./internal/awaitify.js');
12 +
13 +var _awaitify2 = _interopRequireDefault(_awaitify);
14 +
15 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16 +
17 +/**
18 + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
19 + *
20 + * @name concatSeries
21 + * @static
22 + * @memberOf module:Collections
23 + * @method
24 + * @see [async.concat]{@link module:Collections.concat}
25 + * @category Collection
26 + * @alias flatMapSeries
27 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
28 + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
29 + * The iteratee should complete with an array an array of results.
30 + * Invoked with (item, callback).
31 + * @param {Function} [callback] - A callback which is called after all the
32 + * `iteratee` functions have finished, or an error occurs. Results is an array
33 + * containing the concatenated results of the `iteratee` function. Invoked with
34 + * (err, results).
35 + * @returns A Promise, if no callback is passed
36 + */
37 +function concatSeries(coll, iteratee, callback) {
38 + return (0, _concatLimit2.default)(coll, 1, iteratee, callback);
39 +}
40 +exports.default = (0, _awaitify2.default)(concatSeries, 3);
41 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +exports.default = function (...args) {
8 + return function (...ignoredArgs /*, callback*/) {
9 + var callback = ignoredArgs.pop();
10 + return callback(null, ...args);
11 + };
12 +};
13 +
14 +module.exports = exports["default"]; /**
15 + * Returns a function that when called, calls-back with the values provided.
16 + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to
17 + * [`auto`]{@link module:ControlFlow.auto}.
18 + *
19 + * @name constant
20 + * @static
21 + * @memberOf module:Utils
22 + * @method
23 + * @category Util
24 + * @param {...*} arguments... - Any number of arguments to automatically invoke
25 + * callback with.
26 + * @returns {AsyncFunction} Returns a function that when invoked, automatically
27 + * invokes the callback with the previous given arguments.
28 + * @example
29 + *
30 + * async.waterfall([
31 + * async.constant(42),
32 + * function (value, next) {
33 + * // value === 42
34 + * },
35 + * //...
36 + * ], callback);
37 + *
38 + * async.waterfall([
39 + * async.constant(filename, "utf8"),
40 + * fs.readFile,
41 + * function (fileData, next) {
42 + * //...
43 + * }
44 + * //...
45 + * ], callback);
46 + *
47 + * async.auto({
48 + * hostname: async.constant("https://server.net/"),
49 + * port: findFreePort,
50 + * launchServer: ["hostname", "port", function (options, cb) {
51 + * startServer(options, cb);
52 + * }],
53 + * //...
54 + * }, callback);
55 + */
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOf = require('./eachOf.js');
12 +
13 +var _eachOf2 = _interopRequireDefault(_eachOf);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Returns the first value in `coll` that passes an async truth test. The
23 + * `iteratee` is applied in parallel, meaning the first iteratee to return
24 + * `true` will fire the detect `callback` with that result. That means the
25 + * result might not be the first item in the original `coll` (in terms of order)
26 + * that passes the test.
27 +
28 + * If order within the original `coll` is important, then look at
29 + * [`detectSeries`]{@link module:Collections.detectSeries}.
30 + *
31 + * @name detect
32 + * @static
33 + * @memberOf module:Collections
34 + * @method
35 + * @alias find
36 + * @category Collections
37 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
38 + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
39 + * The iteratee must complete with a boolean value as its result.
40 + * Invoked with (item, callback).
41 + * @param {Function} [callback] - A callback which is called as soon as any
42 + * iteratee returns `true`, or after all the `iteratee` functions have finished.
43 + * Result will be the first item in the array that passes the truth test
44 + * (iteratee) or the value `undefined` if none passed. Invoked with
45 + * (err, result).
46 + * @returns A Promise, if no callback is passed
47 + * @example
48 + *
49 + * // dir1 is a directory that contains file1.txt, file2.txt
50 + * // dir2 is a directory that contains file3.txt, file4.txt
51 + * // dir3 is a directory that contains file5.txt
52 + *
53 + * // asynchronous function that checks if a file exists
54 + * function fileExists(file, callback) {
55 + * fs.access(file, fs.constants.F_OK, (err) => {
56 + * callback(null, !err);
57 + * });
58 + * }
59 + *
60 + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,
61 + * function(err, result) {
62 + * console.log(result);
63 + * // dir1/file1.txt
64 + * // result now equals the first file in the list that exists
65 + * }
66 + *);
67 + *
68 + * // Using Promises
69 + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)
70 + * .then(result => {
71 + * console.log(result);
72 + * // dir1/file1.txt
73 + * // result now equals the first file in the list that exists
74 + * }).catch(err => {
75 + * console.log(err);
76 + * });
77 + *
78 + * // Using async/await
79 + * async () => {
80 + * try {
81 + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists);
82 + * console.log(result);
83 + * // dir1/file1.txt
84 + * // result now equals the file in the list that exists
85 + * }
86 + * catch (err) {
87 + * console.log(err);
88 + * }
89 + * }
90 + *
91 + */
92 +function detect(coll, iteratee, callback) {
93 + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback);
94 +}
95 +exports.default = (0, _awaitify2.default)(detect, 3);
96 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
23 + * time.
24 + *
25 + * @name detectLimit
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @see [async.detect]{@link module:Collections.detect}
30 + * @alias findLimit
31 + * @category Collections
32 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
33 + * @param {number} limit - The maximum number of async operations at a time.
34 + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
35 + * The iteratee must complete with a boolean value as its result.
36 + * Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called as soon as any
38 + * iteratee returns `true`, or after all the `iteratee` functions have finished.
39 + * Result will be the first item in the array that passes the truth test
40 + * (iteratee) or the value `undefined` if none passed. Invoked with
41 + * (err, result).
42 + * @returns a Promise if no callback is passed
43 + */
44 +function detectLimit(coll, limit, iteratee, callback) {
45 + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
46 +}
47 +exports.default = (0, _awaitify2.default)(detectLimit, 4);
48 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
23 + *
24 + * @name detectSeries
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.detect]{@link module:Collections.detect}
29 + * @alias findSeries
30 + * @category Collections
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
33 + * The iteratee must complete with a boolean value as its result.
34 + * Invoked with (item, callback).
35 + * @param {Function} [callback] - A callback which is called as soon as any
36 + * iteratee returns `true`, or after all the `iteratee` functions have finished.
37 + * Result will be the first item in the array that passes the truth test
38 + * (iteratee) or the value `undefined` if none passed. Invoked with
39 + * (err, result).
40 + * @returns a Promise if no callback is passed
41 + */
42 +function detectSeries(coll, iteratee, callback) {
43 + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback);
44 +}
45 +
46 +exports.default = (0, _awaitify2.default)(detectSeries, 3);
47 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _consoleFunc = require('./internal/consoleFunc.js');
8 +
9 +var _consoleFunc2 = _interopRequireDefault(_consoleFunc);
10 +
11 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12 +
13 +/**
14 + * Logs the result of an [`async` function]{@link AsyncFunction} to the
15 + * `console` using `console.dir` to display the properties of the resulting object.
16 + * Only works in Node.js or in browsers that support `console.dir` and
17 + * `console.error` (such as FF and Chrome).
18 + * If multiple arguments are returned from the async function,
19 + * `console.dir` is called on each argument in order.
20 + *
21 + * @name dir
22 + * @static
23 + * @memberOf module:Utils
24 + * @method
25 + * @category Util
26 + * @param {AsyncFunction} function - The function you want to eventually apply
27 + * all arguments to.
28 + * @param {...*} arguments... - Any number of arguments to apply to the function.
29 + * @example
30 + *
31 + * // in a module
32 + * var hello = function(name, callback) {
33 + * setTimeout(function() {
34 + * callback(null, {hello: name});
35 + * }, 1000);
36 + * };
37 + *
38 + * // in the node repl
39 + * node> async.dir(hello, 'world');
40 + * {hello: 'world'}
41 + */
42 +exports.default = (0, _consoleFunc2.default)('dir');
43 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
This diff could not be displayed because it is too large.
1 +(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.async={})})(this,function(e){'use strict';function t(e,...t){return(...n)=>e(...t,...n)}function n(e){return function(...t){var n=t.pop();return e.call(this,t,n)}}function a(e){setTimeout(e,0)}function i(e){return(t,...n)=>e(()=>t(...n))}function r(e){return u(e)?function(...t){const n=t.pop(),a=e.apply(this,t);return s(a,n)}:n(function(t,n){var a;try{a=e.apply(this,t)}catch(t){return n(t)}return a&&"function"==typeof a.then?s(a,n):void n(null,a)})}function s(e,t){return e.then(e=>{l(t,null,e)},e=>{l(t,e&&e.message?e:new Error(e))})}function l(e,t,n){try{e(t,n)}catch(e){be(t=>{throw t},e)}}function u(e){return"AsyncFunction"===e[Symbol.toStringTag]}function d(e){return"AsyncGenerator"===e[Symbol.toStringTag]}function c(e){return"function"==typeof e[Symbol.asyncIterator]}function p(e){if("function"!=typeof e)throw new Error("expected a function");return u(e)?r(e):e}function o(e,t=e.length){if(!t)throw new Error("arity is undefined");return function(...n){return"function"==typeof n[t-1]?e.apply(this,n):new Promise((a,i)=>{n[t-1]=(e,...t)=>e?i(e):void a(1<t.length?t:t[0]),e.apply(this,n)})}}function h(e){return function(t,...n){const a=o(function(a){var i=this;return e(t,(e,t)=>{p(e).apply(i,n.concat(t))},a)});return a}}function f(e,t,n,a){t=t||[];var i=[],r=0,s=p(n);return e(t,(e,t,n)=>{var a=r++;s(e,(e,t)=>{i[a]=t,n(e)})},e=>{a(e,i)})}function y(e){return e&&"number"==typeof e.length&&0<=e.length&&0==e.length%1}function m(e){function t(...t){if(null!==e){var n=e;e=null,n.apply(this,t)}}return Object.assign(t,e),t}function g(e){return e[Symbol.iterator]&&e[Symbol.iterator]()}function k(e){var t=-1,n=e.length;return function(){return++t<n?{value:e[t],key:t}:null}}function v(e){var t=-1;return function(){var n=e.next();return n.done?null:(t++,{value:n.value,key:t})}}function S(e){var t=e?Object.keys(e):[],n=-1,a=t.length;return function i(){var r=t[++n];return"__proto__"===r?i():n<a?{value:e[r],key:r}:null}}function x(e){if(y(e))return k(e);var t=g(e);return t?v(t):S(e)}function L(e){return function(...t){if(null===e)throw new Error("Callback was already called.");var n=e;e=null,n.apply(this,t)}}function E(e,t,n,a){function i(){c>=t||d||l||(d=!0,e.next().then(({value:e,done:t})=>{if(!(u||l))return d=!1,t?(l=!0,void(0>=c&&a(null))):void(c++,n(e,p,r),p++,i())}).catch(s))}function r(e,t){return c-=1,u?void 0:e?s(e):!1===e?(l=!0,void(u=!0)):t===_e||l&&0>=c?(l=!0,a(null)):void i()}function s(e){u||(d=!1,l=!0,a(e))}let l=!1,u=!1,d=!1,c=0,p=0;i()}function O(e,t,n){function a(e,t){!1===e&&(l=!0);!0===l||(e?n(e):(++r===s||t===_e)&&n(null))}n=m(n);var i=0,r=0,{length:s}=e,l=!1;for(0===s&&n(null);i<s;i++)t(e[i],i,L(a))}function b(e,t,n){return Ae(e,1/0,t,n)}function _(){function e(e,...a){return e?n(e):void t(1<a.length?a:a[0])}let t,n;return e[Ce]=new Promise((e,a)=>{t=e,n=a}),e}function M(e,t,n){function a(e,t){g.push(()=>l(e,t))}function i(){if(!h){if(0===g.length&&0===o)return n(null,c);for(;g.length&&o<t;){var e=g.shift();e()}}}function r(e,t){var n=y[e];n||(n=y[e]=[]),n.push(t)}function s(e){var t=y[e]||[];t.forEach(e=>e()),i()}function l(e,t){if(!f){var a=L((t,...a)=>{if(o--,!1===t)return void(h=!0);if(2>a.length&&([a]=a),t){var i={};if(Object.keys(c).forEach(e=>{i[e]=c[e]}),i[e]=a,f=!0,y=Object.create(null),h)return;n(t,i)}else c[e]=a,s(e)});o++;var i=p(t[t.length-1]);1<t.length?i(c,a):i(a)}}function u(t){var n=[];return Object.keys(e).forEach(a=>{const i=e[a];Array.isArray(i)&&0<=i.indexOf(t)&&n.push(a)}),n}"number"!=typeof t&&(n=t,t=null),n=m(n||_());var d=Object.keys(e).length;if(!d)return n(null);t||(t=d);var c={},o=0,h=!1,f=!1,y=Object.create(null),g=[],k=[],v={};return Object.keys(e).forEach(t=>{var n=e[t];if(!Array.isArray(n))return a(t,[n]),void k.push(t);var i=n.slice(0,n.length-1),s=i.length;return 0===s?(a(t,n),void k.push(t)):void(v[t]=s,i.forEach(l=>{if(!e[l])throw new Error("async.auto task `"+t+"` has a non-existent dependency `"+l+"` in "+i.join(", "));r(l,()=>{s--,0===s&&a(t,n)})}))}),function(){for(var e,t=0;k.length;)e=k.pop(),t++,u(e).forEach(e=>{0==--v[e]&&k.push(e)});if(t!==d)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),i(),n[Ce]}function A(e){let t="",n=0,a=e.indexOf("*/");for(;n<e.length;)if("/"===e[n]&&"/"===e[n+1]){let t=e.indexOf("\n",n);n=-1===t?e.length:t}else if(-1!==a&&"/"===e[n]&&"*"===e[n+1]){let i=e.indexOf("*/",n);-1===i?(t+=e[n],n++):(n=i+2,a=e.indexOf("*/",n))}else t+=e[n],n++;return t}function I(e){const t=A(e.toString());let n=t.match(Pe);if(n||(n=t.match(Re)),!n)throw new Error("could not parse args in autoInject\nSource:\n"+t);let[,a]=n;return a.replace(/\s/g,"").split(ze).map(e=>e.replace(Ne,"").trim())}function j(e,t){var n={};return Object.keys(e).forEach(t=>{function a(e,t){var n=i.map(t=>e[t]);n.push(t),p(r)(...n)}var i,r=e[t],s=u(r),l=!s&&1===r.length||s&&0===r.length;if(Array.isArray(r))i=[...r],r=i.pop(),n[t]=i.concat(0<i.length?a:r);else if(l)n[t]=r;else{if(i=I(r),0===r.length&&!s&&0===i.length)throw new Error("autoInject task functions require explicit parameters.");s||i.pop(),n[t]=i.concat(a)}}),M(n,t)}function w(e,t){e.length=1,e.head=e.tail=t}function B(e,t,n){function a(e,t){f[e].push(t)}function i(e,t){const n=(...a)=>{r(e,n),t(...a)};f[e].push(n)}function r(e,t){return e?t?void(f[e]=f[e].filter(e=>e!==t)):f[e]=[]:Object.keys(f).forEach(e=>f[e]=[])}function s(e,...t){f[e].forEach(e=>e(...t))}function l(e,t,n,a){function i(e,...t){return e?n?s(e):r():1>=t.length?r(t[0]):void r(t)}if(null!=a&&"function"!=typeof a)throw new Error("task callback must be a function");k.started=!0;var r,s,l={data:e,callback:n?i:a||i};if(t?k._tasks.unshift(l):k._tasks.push(l),y||(y=!0,be(()=>{y=!1,k.process()})),n||!a)return new Promise((e,t)=>{r=e,s=t})}function u(e){return function(t,...n){o-=1;for(var a=0,r=e.length;a<r;a++){var l=e[a],u=h.indexOf(l);0===u?h.shift():0<u&&h.splice(u,1),l.callback(t,...n),null!=t&&s("error",t,l.data)}o<=k.concurrency-k.buffer&&s("unsaturated"),k.idle()&&s("drain"),k.process()}}function d(e){return!!(0===e.length&&k.idle())&&(be(()=>s("drain")),!0)}if(null==t)t=1;else if(0===t)throw new RangeError("Concurrency must not be zero");var c=p(e),o=0,h=[];const f={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};var y=!1;const m=e=>t=>t?void(r(e),a(e,t)):new Promise((t,n)=>{i(e,(e,a)=>e?n(e):void t(a))});var g=!1,k={_tasks:new Ve,*[Symbol.iterator](){yield*k._tasks[Symbol.iterator]()},concurrency:t,payload:n,buffer:t/4,started:!1,paused:!1,push(e,t){return Array.isArray(e)?d(e)?void 0:e.map(e=>l(e,!1,!1,t)):l(e,!1,!1,t)},pushAsync(e,t){return Array.isArray(e)?d(e)?void 0:e.map(e=>l(e,!1,!0,t)):l(e,!1,!0,t)},kill(){r(),k._tasks.empty()},unshift(e,t){return Array.isArray(e)?d(e)?void 0:e.map(e=>l(e,!0,!1,t)):l(e,!0,!1,t)},unshiftAsync(e,t){return Array.isArray(e)?d(e)?void 0:e.map(e=>l(e,!0,!0,t)):l(e,!0,!0,t)},remove(e){k._tasks.remove(e)},process(){var e=Math.min;if(!g){for(g=!0;!k.paused&&o<k.concurrency&&k._tasks.length;){var t=[],n=[],a=k._tasks.length;k.payload&&(a=e(a,k.payload));for(var r,d=0;d<a;d++)r=k._tasks.shift(),t.push(r),h.push(r),n.push(r.data);o+=1,0===k._tasks.length&&s("empty"),o===k.concurrency&&s("saturated");var p=L(u(t));c(n,p)}g=!1}},length(){return k._tasks.length},running(){return o},workersList(){return h},idle(){return 0===k._tasks.length+o},pause(){k.paused=!0},resume(){!1===k.paused||(k.paused=!1,be(k.process))}};return Object.defineProperties(k,{saturated:{writable:!1,value:m("saturated")},unsaturated:{writable:!1,value:m("unsaturated")},empty:{writable:!1,value:m("empty")},drain:{writable:!1,value:m("drain")},error:{writable:!1,value:m("error")}}),k}function F(e,t){return B(e,1,t)}function T(e,t,n){return B(e,t,n)}function C(...e){var t=e.map(p);return function(...e){var n=this,a=e[e.length-1];return"function"==typeof a?e.pop():a=_(),qe(t,e,(e,t,a)=>{t.apply(n,e.concat((e,...t)=>{a(e,t)}))},(e,t)=>a(e,...t)),a[Ce]}}function P(...e){return C(...e.reverse())}function R(...e){return function(...t){var n=t.pop();return n(null,...e)}}function z(e,t){return(n,a,i,r)=>{var s,l=!1;const u=p(i);n(a,(n,a,i)=>{u(n,(a,r)=>a||!1===a?i(a):e(r)&&!s?(l=!0,s=t(!0,n),i(null,_e)):void i())},e=>e?r(e):void r(null,l?s:t(!1)))}}function N(e){return(t,...n)=>p(t)(...n,(t,...n)=>{"object"==typeof console&&(t?console.error&&console.error(t):console[e]&&n.forEach(t=>console[e](t)))})}function V(e,t,n){const a=p(t);return Xe(e,(...e)=>{const t=e.pop();a(...e,(e,n)=>t(e,!n))},n)}function Y(e){return(t,n,a)=>e(t,a)}function q(e){return u(e)?e:function(...t){var n=t.pop(),a=!0;t.push((...e)=>{a?be(()=>n(...e)):n(...e)}),e.apply(this,t),a=!1}}function D(e,t,n,a){var r=Array(t.length);e(t,(e,t,a)=>{n(e,(e,n)=>{r[t]=!!n,a(e)})},e=>{if(e)return a(e);for(var n=[],s=0;s<t.length;s++)r[s]&&n.push(t[s]);a(null,n)})}function Q(e,t,n,a){var i=[];e(t,(e,t,a)=>{n(e,(n,r)=>n?a(n):void(r&&i.push({index:t,value:e}),a(n)))},e=>e?a(e):void a(null,i.sort((e,t)=>e.index-t.index).map(e=>e.value)))}function U(e,t,n,a){var i=y(t)?D:Q;return i(e,t,p(n),a)}function G(e,t,n){return ut(e,1/0,t,n)}function W(e,t,n){return ut(e,1,t,n)}function H(e,t,n){return ct(e,1/0,t,n)}function J(e,t,n){return ct(e,1,t,n)}function K(e,t=e=>e){var a=Object.create(null),r=Object.create(null),s=p(e),l=n((e,n)=>{var u=t(...e);u in a?be(()=>n(null,...a[u])):u in r?r[u].push(n):(r[u]=[n],s(...e,(e,...t)=>{e||(a[u]=t);var n=r[u];delete r[u];for(var s=0,d=n.length;s<d;s++)n[s](e,...t)}))});return l.memo=a,l.unmemoized=e,l}function X(e,t){return ot(Ie,e,t)}function Z(e,t,n){return ot(Me(t),e,n)}function $(e,t){var n=p(e);return B((e,t)=>{n(e[0],t)},t,1)}function ee(e){return(e<<1)+1}function te(e){return(e+1>>1)-1}function ne(e,t){return e.priority===t.priority?e.pushCount<t.pushCount:e.priority<t.priority}function ae(e,t){var n=$(e,t),a=!1;return n._tasks=new ht,n.push=function(e,t=0,r=()=>{}){if("function"!=typeof r)throw new Error("task callback must be a function");if(n.started=!0,Array.isArray(e)||(e=[e]),0===e.length&&n.idle())return be(()=>n.drain());for(var s,u=0,d=e.length;u<d;u++)s={data:e[u],priority:t,callback:r},n._tasks.push(s);a||(a=!0,be(()=>{a=!1,n.process()}))},delete n.unshift,n}function ie(e,t,n,a){var i=[...e].reverse();return qe(i,t,n,a)}function re(e){var t=p(e);return n(function(e,n){return e.push((e,...t)=>{let a={};if(e&&(a.error=e),0<t.length){var i=t;1>=t.length&&([i]=t),a.value=i}n(null,a)}),t.apply(this,e)})}function se(e){var t;return Array.isArray(e)?t=e.map(re):(t={},Object.keys(e).forEach(n=>{t[n]=re.call(this,e[n])})),t}function le(e,t,n,a){const i=p(n);return U(e,t,(e,t)=>{i(e,(e,n)=>{t(e,!n)})},a)}function ue(e){return function(){return e}}function de(e,t,n){function a(){r((e,...t)=>{!1===e||(e&&s++<i.times&&("function"!=typeof i.errorFilter||i.errorFilter(e))?setTimeout(a,i.intervalFunc(s-1)):n(e,...t))})}var i={times:kt,intervalFunc:ue(vt)};if(3>arguments.length&&"function"==typeof e?(n=t||_(),t=e):(ce(i,e),n=n||_()),"function"!=typeof t)throw new Error("Invalid arguments for async.retry");var r=p(t),s=1;return a(),n[Ce]}function ce(e,n){if("object"==typeof n)e.times=+n.times||kt,e.intervalFunc="function"==typeof n.interval?n.interval:ue(+n.interval||vt),e.errorFilter=n.errorFilter;else if("number"==typeof n||"string"==typeof n)e.times=+n||kt;else throw new Error("Invalid arguments for async.retry")}function pe(e,t){t||(t=e,e=null);let a=e&&e.arity||t.length;u(t)&&(a+=1);var i=p(t);return n((t,n)=>{function r(e){i(...t,e)}return(t.length<a-1||null==n)&&(t.push(n),n=_()),e?de(e,r,n):de(r,n),n[Ce]})}function oe(e,t){return ot(Be,e,t)}function he(e,t,a){var i=p(e);return n((n,r)=>{var s,l=!1;n.push((...e)=>{l||(r(...e),clearTimeout(s))}),s=setTimeout(function(){var t=e.name||"anonymous",n=new Error("Callback function \""+t+"\" timed out.");n.code="ETIMEDOUT",a&&(n.info=a),l=!0,r(n)},t),i(...n)})}function fe(e){for(var t=Array(e);e--;)t[e]=e;return t}function ye(e,t,n,a){var i=p(n);return De(fe(e),t,i,a)}function me(e,t,n){return ye(e,1/0,t,n)}function ge(e,t,n){return ye(e,1,t,n)}function ke(e,t,n,a){3>=arguments.length&&"function"==typeof t&&(a=n,n=t,t=Array.isArray(e)?[]:{}),a=m(a||_());var i=p(n);return Ie(e,(e,n,a)=>{i(t,e,n,a)},e=>a(e,t)),a[Ce]}function ve(e){return(...t)=>(e.unmemoized||e)(...t)}function Se(e,t,n){const a=p(e);return bt(e=>a((t,n)=>e(t,!n)),t,n)}var xe,Le="function"==typeof queueMicrotask&&queueMicrotask,Ee="function"==typeof setImmediate&&setImmediate,Oe="object"==typeof process&&"function"==typeof process.nextTick;xe=Le?queueMicrotask:Ee?setImmediate:Oe?process.nextTick:a;var be=i(xe);const _e={};var Me=e=>(t,n,a)=>{function i(e,t){if(!u)if(p-=1,e)l=!0,a(e);else if(!1===e)l=!0,u=!0;else{if(t===_e||l&&0>=p)return l=!0,a(null);o||r()}}function r(){for(o=!0;p<e&&!l;){var t=s();if(null===t)return l=!0,void(0>=p&&a(null));p+=1,n(t.value,t.key,L(i))}o=!1}if(a=m(a),0>=e)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return a(null);if(d(t))return E(t,e,n,a);if(c(t))return E(t[Symbol.asyncIterator](),e,n,a);var s=x(t),l=!1,u=!1,p=0,o=!1;r()},Ae=o(function(e,t,n,a){return Me(t)(e,p(n),a)},4),Ie=o(function(e,t,n){var a=y(e)?O:b;return a(e,p(t),n)},3),je=o(function(e,t,n){return f(Ie,e,t,n)},3),we=h(je),Be=o(function(e,t,n){return Ae(e,1,t,n)},3),Fe=o(function(e,t,n){return f(Be,e,t,n)},3),Te=h(Fe);const Ce=Symbol("promiseCallback");var Pe=/^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/,Re=/^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/,ze=/,/,Ne=/(=.+)?(\s*)$/;class Ve{constructor(){this.head=this.tail=null,this.length=0}removeLink(e){return e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=e.next=null,this.length-=1,e}empty(){for(;this.head;)this.shift();return this}insertAfter(e,t){t.prev=e,t.next=e.next,e.next?e.next.prev=t:this.tail=t,e.next=t,this.length+=1}insertBefore(e,t){t.prev=e.prev,t.next=e,e.prev?e.prev.next=t:this.head=t,e.prev=t,this.length+=1}unshift(e){this.head?this.insertBefore(this.head,e):w(this,e)}push(e){this.tail?this.insertAfter(this.tail,e):w(this,e)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){for(var e=this.head;e;)yield e.data,e=e.next}remove(e){for(var t=this.head;t;){var{next:n}=t;e(t)&&this.removeLink(t),t=n}return this}}var Ye,qe=o(function(e,t,n,a){a=m(a);var r=p(n);return Be(e,(e,n,a)=>{r(t,e,(e,n)=>{t=n,a(e)})},e=>a(e,t))},4),De=o(function(e,t,n,a){return f(Me(t),e,n,a)},4),Qe=o(function(e,t,n,a){var i=p(n);return De(e,t,(e,t)=>{i(e,(e,...n)=>e?t(e):t(e,n))},(e,t)=>{for(var n=[],r=0;r<t.length;r++)t[r]&&(n=n.concat(...t[r]));return a(e,n)})},4),Ue=o(function(e,t,n){return Qe(e,1/0,t,n)},3),Ge=o(function(e,t,n){return Qe(e,1,t,n)},3),We=o(function(e,t,n){return z(e=>e,(e,t)=>t)(Ie,e,t,n)},3),He=o(function(e,t,n,a){return z(e=>e,(e,t)=>t)(Me(t),e,n,a)},4),Je=o(function(e,t,n){return z(e=>e,(e,t)=>t)(Me(1),e,t,n)},3),Ke=N("dir"),Xe=o(function(e,t,n){function a(e,...t){return e?n(e):void(!1===e||(r=t,l(...t,i)))}function i(e,t){return e?n(e):!1===e?void 0:t?void s(a):n(null,...r)}n=L(n);var r,s=p(e),l=p(t);return i(null,!0)},3),Ze=o(function(e,t,n){return Ie(e,Y(p(t)),n)},3),$e=o(function(e,t,n,a){return Me(t)(e,Y(p(n)),a)},4),et=o(function(e,t,n){return $e(e,1,t,n)},3),tt=o(function(e,t,n){return z(e=>!e,e=>!e)(Ie,e,t,n)},3),nt=o(function(e,t,n,a){return z(e=>!e,e=>!e)(Me(t),e,n,a)},4),at=o(function(e,t,n){return z(e=>!e,e=>!e)(Be,e,t,n)},3),it=o(function(e,t,n){return U(Ie,e,t,n)},3),rt=o(function(e,t,n,a){return U(Me(t),e,n,a)},4),st=o(function(e,t,n){return U(Be,e,t,n)},3),lt=o(function(e,t){function n(e){return e?a(e):void(!1===e||i(n))}var a=L(t),i=p(q(e));return n()},2),ut=o(function(e,t,n,a){var i=p(n);return De(e,t,(e,t)=>{i(e,(n,a)=>n?t(n):t(n,{key:a,val:e}))},(e,t)=>{for(var n={},{hasOwnProperty:r}=Object.prototype,s=0;s<t.length;s++)if(t[s]){var{key:l}=t[s],{val:u}=t[s];r.call(n,l)?n[l].push(u):n[l]=[u]}return a(e,n)})},4),dt=N("log"),ct=o(function(e,t,n,a){a=m(a);var i={},r=p(n);return Me(t)(e,(e,t,n)=>{r(e,t,(e,a)=>e?n(e):void(i[t]=a,n(e)))},e=>a(e,i))},4);Ye=Oe?process.nextTick:Ee?setImmediate:a;var pt=i(Ye),ot=o((e,t,n)=>{var a=y(t)?[]:{};e(t,(e,t,n)=>{p(e)((e,...i)=>{2>i.length&&([i]=i),a[t]=i,n(e)})},e=>n(e,a))},3);class ht{constructor(){this.heap=[],this.pushCount=Number.MIN_SAFE_INTEGER}get length(){return this.heap.length}empty(){return this.heap=[],this}percUp(e){for(let n;0<e&&ne(this.heap[e],this.heap[n=te(e)]);){let a=this.heap[e];this.heap[e]=this.heap[n],this.heap[n]=a,e=n}}percDown(e){for(let n,a;(n=ee(e))<this.heap.length&&(n+1<this.heap.length&&ne(this.heap[n+1],this.heap[n])&&++n,!ne(this.heap[e],this.heap[n]));)a=this.heap[e],this.heap[e]=this.heap[n],this.heap[n]=a,e=n}push(e){e.pushCount=++this.pushCount,this.heap.push(e),this.percUp(this.heap.length-1)}unshift(e){return this.heap.push(e)}shift(){let[e]=this.heap;return this.heap[0]=this.heap[this.heap.length-1],this.heap.pop(),this.percDown(0),e}toArray(){return[...this]}*[Symbol.iterator](){for(let e=0;e<this.heap.length;e++)yield this.heap[e].data}remove(e){let t=0;for(let n=0;n<this.heap.length;n++)e(this.heap[n])||(this.heap[t]=this.heap[n],t++);this.heap.splice(t);for(let t=te(this.heap.length-1);0<=t;t--)this.percDown(t);return this}}var ft=o(function(e,t){if(t=m(t),!Array.isArray(e))return t(new TypeError("First argument to race must be an array of functions"));if(!e.length)return t();for(var n=0,a=e.length;n<a;n++)p(e[n])(t)},2),yt=o(function(e,t,n){return le(Ie,e,t,n)},3),mt=o(function(e,t,n,a){return le(Me(t),e,n,a)},4),gt=o(function(e,t,n){return le(Be,e,t,n)},3);const kt=5,vt=0;var St=o(function(e,t,n){return z(Boolean,e=>e)(Ie,e,t,n)},3),xt=o(function(e,t,n,a){return z(Boolean,e=>e)(Me(t),e,n,a)},4),Lt=o(function(e,t,n){return z(Boolean,e=>e)(Be,e,t,n)},3),Et=o(function(e,t,n){function a(e,t){var n=e.criteria,a=t.criteria;return n<a?-1:n>a?1:0}var i=p(t);return je(e,(e,t)=>{i(e,(n,a)=>n?t(n):void t(n,{value:e,criteria:a}))},(e,t)=>e?n(e):void n(null,t.sort(a).map(e=>e.value)))},3),Ot=o(function(e,t){var n,a=null;return et(e,(e,t)=>{p(e)((e,...i)=>!1===e?t(e):void(2>i.length?[n]=i:n=i,a=e,t(e?null:{})))},()=>t(a,n))}),bt=o(function(e,t,n){function a(e,...t){if(e)return n(e);l=t;!1===e||s(i)}function i(e,t){return e?n(e):!1===e?void 0:t?void r(a):n(null,...l)}n=L(n);var r=p(t),s=p(e),l=[];return s(i)},3),_t=o(function(e,t){function n(t){var n=p(e[i++]);n(...t,L(a))}function a(a,...r){return!1===a?void 0:a||i===e.length?t(a,...r):void n(r)}if(t=m(t),!Array.isArray(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var i=0;n([])});e.default={apply:t,applyEach:we,applyEachSeries:Te,asyncify:r,auto:M,autoInject:j,cargo:F,cargoQueue:T,compose:P,concat:Ue,concatLimit:Qe,concatSeries:Ge,constant:R,detect:We,detectLimit:He,detectSeries:Je,dir:Ke,doUntil:V,doWhilst:Xe,each:Ze,eachLimit:$e,eachOf:Ie,eachOfLimit:Ae,eachOfSeries:Be,eachSeries:et,ensureAsync:q,every:tt,everyLimit:nt,everySeries:at,filter:it,filterLimit:rt,filterSeries:st,forever:lt,groupBy:G,groupByLimit:ut,groupBySeries:W,log:dt,map:je,mapLimit:De,mapSeries:Fe,mapValues:H,mapValuesLimit:ct,mapValuesSeries:J,memoize:K,nextTick:pt,parallel:X,parallelLimit:Z,priorityQueue:ae,queue:$,race:ft,reduce:qe,reduceRight:ie,reflect:re,reflectAll:se,reject:yt,rejectLimit:mt,rejectSeries:gt,retry:de,retryable:pe,seq:C,series:oe,setImmediate:be,some:St,someLimit:xt,someSeries:Lt,sortBy:Et,timeout:he,times:me,timesLimit:ye,timesSeries:ge,transform:ke,tryEach:Ot,unmemoize:ve,until:Se,waterfall:_t,whilst:bt,all:tt,allLimit:nt,allSeries:at,any:St,anyLimit:xt,anySeries:Lt,find:We,findLimit:He,findSeries:Je,flatMap:Ue,flatMapLimit:Qe,flatMapSeries:Ge,forEach:Ze,forEachSeries:et,forEachLimit:$e,forEachOf:Ie,forEachOfSeries:Be,forEachOfLimit:Ae,inject:qe,foldl:qe,foldr:ie,select:it,selectLimit:rt,selectSeries:st,wrapSync:r,during:bt,doDuring:Xe},e.apply=t,e.applyEach=we,e.applyEachSeries=Te,e.asyncify=r,e.auto=M,e.autoInject=j,e.cargo=F,e.cargoQueue=T,e.compose=P,e.concat=Ue,e.concatLimit=Qe,e.concatSeries=Ge,e.constant=R,e.detect=We,e.detectLimit=He,e.detectSeries=Je,e.dir=Ke,e.doUntil=V,e.doWhilst=Xe,e.each=Ze,e.eachLimit=$e,e.eachOf=Ie,e.eachOfLimit=Ae,e.eachOfSeries=Be,e.eachSeries=et,e.ensureAsync=q,e.every=tt,e.everyLimit=nt,e.everySeries=at,e.filter=it,e.filterLimit=rt,e.filterSeries=st,e.forever=lt,e.groupBy=G,e.groupByLimit=ut,e.groupBySeries=W,e.log=dt,e.map=je,e.mapLimit=De,e.mapSeries=Fe,e.mapValues=H,e.mapValuesLimit=ct,e.mapValuesSeries=J,e.memoize=K,e.nextTick=pt,e.parallel=X,e.parallelLimit=Z,e.priorityQueue=ae,e.queue=$,e.race=ft,e.reduce=qe,e.reduceRight=ie,e.reflect=re,e.reflectAll=se,e.reject=yt,e.rejectLimit=mt,e.rejectSeries=gt,e.retry=de,e.retryable=pe,e.seq=C,e.series=oe,e.setImmediate=be,e.some=St,e.someLimit=xt,e.someSeries=Lt,e.sortBy=Et,e.timeout=he,e.times=me,e.timesLimit=ye,e.timesSeries=ge,e.transform=ke,e.tryEach=Ot,e.unmemoize=ve,e.until=Se,e.waterfall=_t,e.whilst=bt,e.all=tt,e.allLimit=nt,e.allSeries=at,e.any=St,e.anyLimit=xt,e.anySeries=Lt,e.find=We,e.findLimit=He,e.findSeries=Je,e.flatMap=Ue,e.flatMapLimit=Qe,e.flatMapSeries=Ge,e.forEach=Ze,e.forEachSeries=et,e.forEachLimit=$e,e.forEachOf=Ie,e.forEachOfSeries=Be,e.forEachOfLimit=Ae,e.inject=qe,e.foldl=qe,e.foldr=ie,e.select=it,e.selectLimit=rt,e.selectSeries=st,e.wrapSync=r,e.during=bt,e.doDuring=Xe,Object.defineProperty(e,"__esModule",{value:!0})});
...\ No newline at end of file ...\ No newline at end of file
This diff could not be displayed because it is too large.
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _onlyOnce = require('./internal/onlyOnce.js');
8 +
9 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
10 +
11 +var _wrapAsync = require('./internal/wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
23 + * the order of operations, the arguments `test` and `iteratee` are switched.
24 + *
25 + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
26 + *
27 + * @name doWhilst
28 + * @static
29 + * @memberOf module:ControlFlow
30 + * @method
31 + * @see [async.whilst]{@link module:ControlFlow.whilst}
32 + * @category Control Flow
33 + * @param {AsyncFunction} iteratee - A function which is called each time `test`
34 + * passes. Invoked with (callback).
35 + * @param {AsyncFunction} test - asynchronous truth test to perform after each
36 + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the
37 + * non-error args from the previous callback of `iteratee`.
38 + * @param {Function} [callback] - A callback which is called after the test
39 + * function has failed and repeated execution of `iteratee` has stopped.
40 + * `callback` will be passed an error and any arguments passed to the final
41 + * `iteratee`'s callback. Invoked with (err, [results]);
42 + * @returns {Promise} a promise, if no callback is passed
43 + */
44 +function doWhilst(iteratee, test, callback) {
45 + callback = (0, _onlyOnce2.default)(callback);
46 + var _fn = (0, _wrapAsync2.default)(iteratee);
47 + var _test = (0, _wrapAsync2.default)(test);
48 + var results;
49 +
50 + function next(err, ...args) {
51 + if (err) return callback(err);
52 + if (err === false) return;
53 + results = args;
54 + _test(...args, check);
55 + }
56 +
57 + function check(err, truth) {
58 + if (err) return callback(err);
59 + if (err === false) return;
60 + if (!truth) return callback(null, ...results);
61 + _fn(next);
62 + }
63 +
64 + return check(null, true);
65 +}
66 +
67 +exports.default = (0, _awaitify2.default)(doWhilst, 3);
68 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = doUntil;
7 +
8 +var _doWhilst = require('./doWhilst.js');
9 +
10 +var _doWhilst2 = _interopRequireDefault(_doWhilst);
11 +
12 +var _wrapAsync = require('./internal/wrapAsync.js');
13 +
14 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +/**
19 + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the
20 + * argument ordering differs from `until`.
21 + *
22 + * @name doUntil
23 + * @static
24 + * @memberOf module:ControlFlow
25 + * @method
26 + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}
27 + * @category Control Flow
28 + * @param {AsyncFunction} iteratee - An async function which is called each time
29 + * `test` fails. Invoked with (callback).
30 + * @param {AsyncFunction} test - asynchronous truth test to perform after each
31 + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the
32 + * non-error args from the previous callback of `iteratee`
33 + * @param {Function} [callback] - A callback which is called after the test
34 + * function has passed and repeated execution of `iteratee` has stopped. `callback`
35 + * will be passed an error and any arguments passed to the final `iteratee`'s
36 + * callback. Invoked with (err, [results]);
37 + * @returns {Promise} a promise, if no callback is passed
38 + */
39 +function doUntil(iteratee, test, callback) {
40 + const _test = (0, _wrapAsync2.default)(test);
41 + return (0, _doWhilst2.default)(iteratee, (...args) => {
42 + const cb = args.pop();
43 + _test(...args, (err, truth) => cb(err, !truth));
44 + }, callback);
45 +}
46 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _onlyOnce = require('./internal/onlyOnce.js');
8 +
9 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
10 +
11 +var _wrapAsync = require('./internal/wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
23 + * the order of operations, the arguments `test` and `iteratee` are switched.
24 + *
25 + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
26 + *
27 + * @name doWhilst
28 + * @static
29 + * @memberOf module:ControlFlow
30 + * @method
31 + * @see [async.whilst]{@link module:ControlFlow.whilst}
32 + * @category Control Flow
33 + * @param {AsyncFunction} iteratee - A function which is called each time `test`
34 + * passes. Invoked with (callback).
35 + * @param {AsyncFunction} test - asynchronous truth test to perform after each
36 + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the
37 + * non-error args from the previous callback of `iteratee`.
38 + * @param {Function} [callback] - A callback which is called after the test
39 + * function has failed and repeated execution of `iteratee` has stopped.
40 + * `callback` will be passed an error and any arguments passed to the final
41 + * `iteratee`'s callback. Invoked with (err, [results]);
42 + * @returns {Promise} a promise, if no callback is passed
43 + */
44 +function doWhilst(iteratee, test, callback) {
45 + callback = (0, _onlyOnce2.default)(callback);
46 + var _fn = (0, _wrapAsync2.default)(iteratee);
47 + var _test = (0, _wrapAsync2.default)(test);
48 + var results;
49 +
50 + function next(err, ...args) {
51 + if (err) return callback(err);
52 + if (err === false) return;
53 + results = args;
54 + _test(...args, check);
55 + }
56 +
57 + function check(err, truth) {
58 + if (err) return callback(err);
59 + if (err === false) return;
60 + if (!truth) return callback(null, ...results);
61 + _fn(next);
62 + }
63 +
64 + return check(null, true);
65 +}
66 +
67 +exports.default = (0, _awaitify2.default)(doWhilst, 3);
68 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _onlyOnce = require('./internal/onlyOnce.js');
8 +
9 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
10 +
11 +var _wrapAsync = require('./internal/wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
23 + * stopped, or an error occurs.
24 + *
25 + * @name whilst
26 + * @static
27 + * @memberOf module:ControlFlow
28 + * @method
29 + * @category Control Flow
30 + * @param {AsyncFunction} test - asynchronous truth test to perform before each
31 + * execution of `iteratee`. Invoked with ().
32 + * @param {AsyncFunction} iteratee - An async function which is called each time
33 + * `test` passes. Invoked with (callback).
34 + * @param {Function} [callback] - A callback which is called after the test
35 + * function has failed and repeated execution of `iteratee` has stopped. `callback`
36 + * will be passed an error and any arguments passed to the final `iteratee`'s
37 + * callback. Invoked with (err, [results]);
38 + * @returns {Promise} a promise, if no callback is passed
39 + * @example
40 + *
41 + * var count = 0;
42 + * async.whilst(
43 + * function test(cb) { cb(null, count < 5); },
44 + * function iter(callback) {
45 + * count++;
46 + * setTimeout(function() {
47 + * callback(null, count);
48 + * }, 1000);
49 + * },
50 + * function (err, n) {
51 + * // 5 seconds have passed, n = 5
52 + * }
53 + * );
54 + */
55 +function whilst(test, iteratee, callback) {
56 + callback = (0, _onlyOnce2.default)(callback);
57 + var _fn = (0, _wrapAsync2.default)(iteratee);
58 + var _test = (0, _wrapAsync2.default)(test);
59 + var results = [];
60 +
61 + function next(err, ...rest) {
62 + if (err) return callback(err);
63 + results = rest;
64 + if (err === false) return;
65 + _test(check);
66 + }
67 +
68 + function check(err, truth) {
69 + if (err) return callback(err);
70 + if (err === false) return;
71 + if (!truth) return callback(null, ...results);
72 + _fn(next);
73 + }
74 +
75 + return _test(check);
76 +}
77 +exports.default = (0, _awaitify2.default)(whilst, 3);
78 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOf = require('./eachOf.js');
8 +
9 +var _eachOf2 = _interopRequireDefault(_eachOf);
10 +
11 +var _withoutIndex = require('./internal/withoutIndex.js');
12 +
13 +var _withoutIndex2 = _interopRequireDefault(_withoutIndex);
14 +
15 +var _wrapAsync = require('./internal/wrapAsync.js');
16 +
17 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
18 +
19 +var _awaitify = require('./internal/awaitify.js');
20 +
21 +var _awaitify2 = _interopRequireDefault(_awaitify);
22 +
23 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24 +
25 +/**
26 + * Applies the function `iteratee` to each item in `coll`, in parallel.
27 + * The `iteratee` is called with an item from the list, and a callback for when
28 + * it has finished. If the `iteratee` passes an error to its `callback`, the
29 + * main `callback` (for the `each` function) is immediately called with the
30 + * error.
31 + *
32 + * Note, that since this function applies `iteratee` to each item in parallel,
33 + * there is no guarantee that the iteratee functions will complete in order.
34 + *
35 + * @name each
36 + * @static
37 + * @memberOf module:Collections
38 + * @method
39 + * @alias forEach
40 + * @category Collection
41 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
42 + * @param {AsyncFunction} iteratee - An async function to apply to
43 + * each item in `coll`. Invoked with (item, callback).
44 + * The array index is not passed to the iteratee.
45 + * If you need the index, use `eachOf`.
46 + * @param {Function} [callback] - A callback which is called when all
47 + * `iteratee` functions have finished, or an error occurs. Invoked with (err).
48 + * @returns {Promise} a promise, if a callback is omitted
49 + * @example
50 + *
51 + * // dir1 is a directory that contains file1.txt, file2.txt
52 + * // dir2 is a directory that contains file3.txt, file4.txt
53 + * // dir3 is a directory that contains file5.txt
54 + * // dir4 does not exist
55 + *
56 + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];
57 + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];
58 + *
59 + * // asynchronous function that deletes a file
60 + * const deleteFile = function(file, callback) {
61 + * fs.unlink(file, callback);
62 + * };
63 + *
64 + * // Using callbacks
65 + * async.each(fileList, deleteFile, function(err) {
66 + * if( err ) {
67 + * console.log(err);
68 + * } else {
69 + * console.log('All files have been deleted successfully');
70 + * }
71 + * });
72 + *
73 + * // Error Handling
74 + * async.each(withMissingFileList, deleteFile, function(err){
75 + * console.log(err);
76 + * // [ Error: ENOENT: no such file or directory ]
77 + * // since dir4/file2.txt does not exist
78 + * // dir1/file1.txt could have been deleted
79 + * });
80 + *
81 + * // Using Promises
82 + * async.each(fileList, deleteFile)
83 + * .then( () => {
84 + * console.log('All files have been deleted successfully');
85 + * }).catch( err => {
86 + * console.log(err);
87 + * });
88 + *
89 + * // Error Handling
90 + * async.each(fileList, deleteFile)
91 + * .then( () => {
92 + * console.log('All files have been deleted successfully');
93 + * }).catch( err => {
94 + * console.log(err);
95 + * // [ Error: ENOENT: no such file or directory ]
96 + * // since dir4/file2.txt does not exist
97 + * // dir1/file1.txt could have been deleted
98 + * });
99 + *
100 + * // Using async/await
101 + * async () => {
102 + * try {
103 + * await async.each(files, deleteFile);
104 + * }
105 + * catch (err) {
106 + * console.log(err);
107 + * }
108 + * }
109 + *
110 + * // Error Handling
111 + * async () => {
112 + * try {
113 + * await async.each(withMissingFileList, deleteFile);
114 + * }
115 + * catch (err) {
116 + * console.log(err);
117 + * // [ Error: ENOENT: no such file or directory ]
118 + * // since dir4/file2.txt does not exist
119 + * // dir1/file1.txt could have been deleted
120 + * }
121 + * }
122 + *
123 + */
124 +function eachLimit(coll, iteratee, callback) {
125 + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);
126 +}
127 +
128 +exports.default = (0, _awaitify2.default)(eachLimit, 3);
129 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOfLimit = require('./internal/eachOfLimit.js');
8 +
9 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
10 +
11 +var _withoutIndex = require('./internal/withoutIndex.js');
12 +
13 +var _withoutIndex2 = _interopRequireDefault(_withoutIndex);
14 +
15 +var _wrapAsync = require('./internal/wrapAsync.js');
16 +
17 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
18 +
19 +var _awaitify = require('./internal/awaitify.js');
20 +
21 +var _awaitify2 = _interopRequireDefault(_awaitify);
22 +
23 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24 +
25 +/**
26 + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
27 + *
28 + * @name eachLimit
29 + * @static
30 + * @memberOf module:Collections
31 + * @method
32 + * @see [async.each]{@link module:Collections.each}
33 + * @alias forEachLimit
34 + * @category Collection
35 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
36 + * @param {number} limit - The maximum number of async operations at a time.
37 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
38 + * `coll`.
39 + * The array index is not passed to the iteratee.
40 + * If you need the index, use `eachOfLimit`.
41 + * Invoked with (item, callback).
42 + * @param {Function} [callback] - A callback which is called when all
43 + * `iteratee` functions have finished, or an error occurs. Invoked with (err).
44 + * @returns {Promise} a promise, if a callback is omitted
45 + */
46 +function eachLimit(coll, limit, iteratee, callback) {
47 + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);
48 +}
49 +exports.default = (0, _awaitify2.default)(eachLimit, 4);
50 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _isArrayLike = require('./internal/isArrayLike.js');
8 +
9 +var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
10 +
11 +var _breakLoop = require('./internal/breakLoop.js');
12 +
13 +var _breakLoop2 = _interopRequireDefault(_breakLoop);
14 +
15 +var _eachOfLimit = require('./eachOfLimit.js');
16 +
17 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
18 +
19 +var _once = require('./internal/once.js');
20 +
21 +var _once2 = _interopRequireDefault(_once);
22 +
23 +var _onlyOnce = require('./internal/onlyOnce.js');
24 +
25 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
26 +
27 +var _wrapAsync = require('./internal/wrapAsync.js');
28 +
29 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
30 +
31 +var _awaitify = require('./internal/awaitify.js');
32 +
33 +var _awaitify2 = _interopRequireDefault(_awaitify);
34 +
35 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36 +
37 +// eachOf implementation optimized for array-likes
38 +function eachOfArrayLike(coll, iteratee, callback) {
39 + callback = (0, _once2.default)(callback);
40 + var index = 0,
41 + completed = 0,
42 + { length } = coll,
43 + canceled = false;
44 + if (length === 0) {
45 + callback(null);
46 + }
47 +
48 + function iteratorCallback(err, value) {
49 + if (err === false) {
50 + canceled = true;
51 + }
52 + if (canceled === true) return;
53 + if (err) {
54 + callback(err);
55 + } else if (++completed === length || value === _breakLoop2.default) {
56 + callback(null);
57 + }
58 + }
59 +
60 + for (; index < length; index++) {
61 + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback));
62 + }
63 +}
64 +
65 +// a generic version of eachOf which can handle array, object, and iterator cases.
66 +function eachOfGeneric(coll, iteratee, callback) {
67 + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback);
68 +}
69 +
70 +/**
71 + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
72 + * to the iteratee.
73 + *
74 + * @name eachOf
75 + * @static
76 + * @memberOf module:Collections
77 + * @method
78 + * @alias forEachOf
79 + * @category Collection
80 + * @see [async.each]{@link module:Collections.each}
81 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
82 + * @param {AsyncFunction} iteratee - A function to apply to each
83 + * item in `coll`.
84 + * The `key` is the item's key, or index in the case of an array.
85 + * Invoked with (item, key, callback).
86 + * @param {Function} [callback] - A callback which is called when all
87 + * `iteratee` functions have finished, or an error occurs. Invoked with (err).
88 + * @returns {Promise} a promise, if a callback is omitted
89 + * @example
90 + *
91 + * // dev.json is a file containing a valid json object config for dev environment
92 + * // dev.json is a file containing a valid json object config for test environment
93 + * // prod.json is a file containing a valid json object config for prod environment
94 + * // invalid.json is a file with a malformed json object
95 + *
96 + * let configs = {}; //global variable
97 + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};
98 + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};
99 + *
100 + * // asynchronous function that reads a json file and parses the contents as json object
101 + * function parseFile(file, key, callback) {
102 + * fs.readFile(file, "utf8", function(err, data) {
103 + * if (err) return calback(err);
104 + * try {
105 + * configs[key] = JSON.parse(data);
106 + * } catch (e) {
107 + * return callback(e);
108 + * }
109 + * callback();
110 + * });
111 + * }
112 + *
113 + * // Using callbacks
114 + * async.forEachOf(validConfigFileMap, parseFile, function (err) {
115 + * if (err) {
116 + * console.error(err);
117 + * } else {
118 + * console.log(configs);
119 + * // configs is now a map of JSON data, e.g.
120 + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
121 + * }
122 + * });
123 + *
124 + * //Error handing
125 + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) {
126 + * if (err) {
127 + * console.error(err);
128 + * // JSON parse error exception
129 + * } else {
130 + * console.log(configs);
131 + * }
132 + * });
133 + *
134 + * // Using Promises
135 + * async.forEachOf(validConfigFileMap, parseFile)
136 + * .then( () => {
137 + * console.log(configs);
138 + * // configs is now a map of JSON data, e.g.
139 + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
140 + * }).catch( err => {
141 + * console.error(err);
142 + * });
143 + *
144 + * //Error handing
145 + * async.forEachOf(invalidConfigFileMap, parseFile)
146 + * .then( () => {
147 + * console.log(configs);
148 + * }).catch( err => {
149 + * console.error(err);
150 + * // JSON parse error exception
151 + * });
152 + *
153 + * // Using async/await
154 + * async () => {
155 + * try {
156 + * let result = await async.forEachOf(validConfigFileMap, parseFile);
157 + * console.log(configs);
158 + * // configs is now a map of JSON data, e.g.
159 + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
160 + * }
161 + * catch (err) {
162 + * console.log(err);
163 + * }
164 + * }
165 + *
166 + * //Error handing
167 + * async () => {
168 + * try {
169 + * let result = await async.forEachOf(invalidConfigFileMap, parseFile);
170 + * console.log(configs);
171 + * }
172 + * catch (err) {
173 + * console.log(err);
174 + * // JSON parse error exception
175 + * }
176 + * }
177 + *
178 + */
179 +function eachOf(coll, iteratee, callback) {
180 + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric;
181 + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback);
182 +}
183 +
184 +exports.default = (0, _awaitify2.default)(eachOf, 3);
185 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOfLimit2 = require('./internal/eachOfLimit.js');
8 +
9 +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2);
10 +
11 +var _wrapAsync = require('./internal/wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
23 + * time.
24 + *
25 + * @name eachOfLimit
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @see [async.eachOf]{@link module:Collections.eachOf}
30 + * @alias forEachOfLimit
31 + * @category Collection
32 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
33 + * @param {number} limit - The maximum number of async operations at a time.
34 + * @param {AsyncFunction} iteratee - An async function to apply to each
35 + * item in `coll`. The `key` is the item's key, or index in the case of an
36 + * array.
37 + * Invoked with (item, key, callback).
38 + * @param {Function} [callback] - A callback which is called when all
39 + * `iteratee` functions have finished, or an error occurs. Invoked with (err).
40 + * @returns {Promise} a promise, if a callback is omitted
41 + */
42 +function eachOfLimit(coll, limit, iteratee, callback) {
43 + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback);
44 +}
45 +
46 +exports.default = (0, _awaitify2.default)(eachOfLimit, 4);
47 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOfLimit = require('./eachOfLimit.js');
8 +
9 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
10 +
11 +var _awaitify = require('./internal/awaitify.js');
12 +
13 +var _awaitify2 = _interopRequireDefault(_awaitify);
14 +
15 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16 +
17 +/**
18 + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
19 + *
20 + * @name eachOfSeries
21 + * @static
22 + * @memberOf module:Collections
23 + * @method
24 + * @see [async.eachOf]{@link module:Collections.eachOf}
25 + * @alias forEachOfSeries
26 + * @category Collection
27 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
28 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
29 + * `coll`.
30 + * Invoked with (item, key, callback).
31 + * @param {Function} [callback] - A callback which is called when all `iteratee`
32 + * functions have finished, or an error occurs. Invoked with (err).
33 + * @returns {Promise} a promise, if a callback is omitted
34 + */
35 +function eachOfSeries(coll, iteratee, callback) {
36 + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback);
37 +}
38 +exports.default = (0, _awaitify2.default)(eachOfSeries, 3);
39 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachLimit = require('./eachLimit.js');
8 +
9 +var _eachLimit2 = _interopRequireDefault(_eachLimit);
10 +
11 +var _awaitify = require('./internal/awaitify.js');
12 +
13 +var _awaitify2 = _interopRequireDefault(_awaitify);
14 +
15 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16 +
17 +/**
18 + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
19 + *
20 + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item
21 + * in series and therefore the iteratee functions will complete in order.
22 +
23 + * @name eachSeries
24 + * @static
25 + * @memberOf module:Collections
26 + * @method
27 + * @see [async.each]{@link module:Collections.each}
28 + * @alias forEachSeries
29 + * @category Collection
30 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
31 + * @param {AsyncFunction} iteratee - An async function to apply to each
32 + * item in `coll`.
33 + * The array index is not passed to the iteratee.
34 + * If you need the index, use `eachOfSeries`.
35 + * Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called when all
37 + * `iteratee` functions have finished, or an error occurs. Invoked with (err).
38 + * @returns {Promise} a promise, if a callback is omitted
39 + */
40 +function eachSeries(coll, iteratee, callback) {
41 + return (0, _eachLimit2.default)(coll, 1, iteratee, callback);
42 +}
43 +exports.default = (0, _awaitify2.default)(eachSeries, 3);
44 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = ensureAsync;
7 +
8 +var _setImmediate = require('./internal/setImmediate.js');
9 +
10 +var _setImmediate2 = _interopRequireDefault(_setImmediate);
11 +
12 +var _wrapAsync = require('./internal/wrapAsync.js');
13 +
14 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15 +
16 +/**
17 + * Wrap an async function and ensure it calls its callback on a later tick of
18 + * the event loop. If the function already calls its callback on a next tick,
19 + * no extra deferral is added. This is useful for preventing stack overflows
20 + * (`RangeError: Maximum call stack size exceeded`) and generally keeping
21 + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
22 + * contained. ES2017 `async` functions are returned as-is -- they are immune
23 + * to Zalgo's corrupting influences, as they always resolve on a later tick.
24 + *
25 + * @name ensureAsync
26 + * @static
27 + * @memberOf module:Utils
28 + * @method
29 + * @category Util
30 + * @param {AsyncFunction} fn - an async function, one that expects a node-style
31 + * callback as its last argument.
32 + * @returns {AsyncFunction} Returns a wrapped function with the exact same call
33 + * signature as the function passed in.
34 + * @example
35 + *
36 + * function sometimesAsync(arg, callback) {
37 + * if (cache[arg]) {
38 + * return callback(null, cache[arg]); // this would be synchronous!!
39 + * } else {
40 + * doSomeIO(arg, callback); // this IO would be asynchronous
41 + * }
42 + * }
43 + *
44 + * // this has a risk of stack overflows if many results are cached in a row
45 + * async.mapSeries(args, sometimesAsync, done);
46 + *
47 + * // this will defer sometimesAsync's callback if necessary,
48 + * // preventing stack overflows
49 + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
50 + */
51 +function ensureAsync(fn) {
52 + if ((0, _wrapAsync.isAsync)(fn)) return fn;
53 + return function (...args /*, callback*/) {
54 + var callback = args.pop();
55 + var sync = true;
56 + args.push((...innerArgs) => {
57 + if (sync) {
58 + (0, _setImmediate2.default)(() => callback(...innerArgs));
59 + } else {
60 + callback(...innerArgs);
61 + }
62 + });
63 + fn.apply(this, args);
64 + sync = false;
65 + };
66 +}
67 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOf = require('./eachOf.js');
12 +
13 +var _eachOf2 = _interopRequireDefault(_eachOf);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Returns `true` if every element in `coll` satisfies an async test. If any
23 + * iteratee call returns `false`, the main `callback` is immediately called.
24 + *
25 + * @name every
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @alias all
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
33 + * in the collection in parallel.
34 + * The iteratee must complete with a boolean result value.
35 + * Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called after all the
37 + * `iteratee` functions have finished. Result will be either `true` or `false`
38 + * depending on the values of the async tests. Invoked with (err, result).
39 + * @returns {Promise} a promise, if no callback provided
40 + * @example
41 + *
42 + * // dir1 is a directory that contains file1.txt, file2.txt
43 + * // dir2 is a directory that contains file3.txt, file4.txt
44 + * // dir3 is a directory that contains file5.txt
45 + * // dir4 does not exist
46 + *
47 + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];
48 + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
49 + *
50 + * // asynchronous function that checks if a file exists
51 + * function fileExists(file, callback) {
52 + * fs.access(file, fs.constants.F_OK, (err) => {
53 + * callback(null, !err);
54 + * });
55 + * }
56 + *
57 + * // Using callbacks
58 + * async.every(fileList, fileExists, function(err, result) {
59 + * console.log(result);
60 + * // true
61 + * // result is true since every file exists
62 + * });
63 + *
64 + * async.every(withMissingFileList, fileExists, function(err, result) {
65 + * console.log(result);
66 + * // false
67 + * // result is false since NOT every file exists
68 + * });
69 + *
70 + * // Using Promises
71 + * async.every(fileList, fileExists)
72 + * .then( result => {
73 + * console.log(result);
74 + * // true
75 + * // result is true since every file exists
76 + * }).catch( err => {
77 + * console.log(err);
78 + * });
79 + *
80 + * async.every(withMissingFileList, fileExists)
81 + * .then( result => {
82 + * console.log(result);
83 + * // false
84 + * // result is false since NOT every file exists
85 + * }).catch( err => {
86 + * console.log(err);
87 + * });
88 + *
89 + * // Using async/await
90 + * async () => {
91 + * try {
92 + * let result = await async.every(fileList, fileExists);
93 + * console.log(result);
94 + * // true
95 + * // result is true since every file exists
96 + * }
97 + * catch (err) {
98 + * console.log(err);
99 + * }
100 + * }
101 + *
102 + * async () => {
103 + * try {
104 + * let result = await async.every(withMissingFileList, fileExists);
105 + * console.log(result);
106 + * // false
107 + * // result is false since NOT every file exists
108 + * }
109 + * catch (err) {
110 + * console.log(err);
111 + * }
112 + * }
113 + *
114 + */
115 +function every(coll, iteratee, callback) {
116 + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback);
117 +}
118 +exports.default = (0, _awaitify2.default)(every, 3);
119 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
23 + *
24 + * @name everyLimit
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.every]{@link module:Collections.every}
29 + * @alias allLimit
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {number} limit - The maximum number of async operations at a time.
33 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
34 + * in the collection in parallel.
35 + * The iteratee must complete with a boolean result value.
36 + * Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called after all the
38 + * `iteratee` functions have finished. Result will be either `true` or `false`
39 + * depending on the values of the async tests. Invoked with (err, result).
40 + * @returns {Promise} a promise, if no callback provided
41 + */
42 +function everyLimit(coll, limit, iteratee, callback) {
43 + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
44 +}
45 +exports.default = (0, _awaitify2.default)(everyLimit, 4);
46 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfSeries = require('./eachOfSeries.js');
12 +
13 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.
23 + *
24 + * @name everySeries
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.every]{@link module:Collections.every}
29 + * @alias allSeries
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
33 + * in the collection in series.
34 + * The iteratee must complete with a boolean result value.
35 + * Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called after all the
37 + * `iteratee` functions have finished. Result will be either `true` or `false`
38 + * depending on the values of the async tests. Invoked with (err, result).
39 + * @returns {Promise} a promise, if no callback provided
40 + */
41 +function everySeries(coll, iteratee, callback) {
42 + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback);
43 +}
44 +exports.default = (0, _awaitify2.default)(everySeries, 3);
45 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _filter2 = require('./internal/filter.js');
8 +
9 +var _filter3 = _interopRequireDefault(_filter2);
10 +
11 +var _eachOf = require('./eachOf.js');
12 +
13 +var _eachOf2 = _interopRequireDefault(_eachOf);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Returns a new array of all the values in `coll` which pass an async truth
23 + * test. This operation is performed in parallel, but the results array will be
24 + * in the same order as the original.
25 + *
26 + * @name filter
27 + * @static
28 + * @memberOf module:Collections
29 + * @method
30 + * @alias select
31 + * @category Collection
32 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
33 + * @param {Function} iteratee - A truth test to apply to each item in `coll`.
34 + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
35 + * with a boolean argument once it has completed. Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called after all the
37 + * `iteratee` functions have finished. Invoked with (err, results).
38 + * @returns {Promise} a promise, if no callback provided
39 + * @example
40 + *
41 + * // dir1 is a directory that contains file1.txt, file2.txt
42 + * // dir2 is a directory that contains file3.txt, file4.txt
43 + * // dir3 is a directory that contains file5.txt
44 + *
45 + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
46 + *
47 + * // asynchronous function that checks if a file exists
48 + * function fileExists(file, callback) {
49 + * fs.access(file, fs.constants.F_OK, (err) => {
50 + * callback(null, !err);
51 + * });
52 + * }
53 + *
54 + * // Using callbacks
55 + * async.filter(files, fileExists, function(err, results) {
56 + * if(err) {
57 + * console.log(err);
58 + * } else {
59 + * console.log(results);
60 + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
61 + * // results is now an array of the existing files
62 + * }
63 + * });
64 + *
65 + * // Using Promises
66 + * async.filter(files, fileExists)
67 + * .then(results => {
68 + * console.log(results);
69 + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
70 + * // results is now an array of the existing files
71 + * }).catch(err => {
72 + * console.log(err);
73 + * });
74 + *
75 + * // Using async/await
76 + * async () => {
77 + * try {
78 + * let results = await async.filter(files, fileExists);
79 + * console.log(results);
80 + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
81 + * // results is now an array of the existing files
82 + * }
83 + * catch (err) {
84 + * console.log(err);
85 + * }
86 + * }
87 + *
88 + */
89 +function filter(coll, iteratee, callback) {
90 + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback);
91 +}
92 +exports.default = (0, _awaitify2.default)(filter, 3);
93 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _filter2 = require('./internal/filter.js');
8 +
9 +var _filter3 = _interopRequireDefault(_filter2);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
23 + * time.
24 + *
25 + * @name filterLimit
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @see [async.filter]{@link module:Collections.filter}
30 + * @alias selectLimit
31 + * @category Collection
32 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
33 + * @param {number} limit - The maximum number of async operations at a time.
34 + * @param {Function} iteratee - A truth test to apply to each item in `coll`.
35 + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
36 + * with a boolean argument once it has completed. Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called after all the
38 + * `iteratee` functions have finished. Invoked with (err, results).
39 + * @returns {Promise} a promise, if no callback provided
40 + */
41 +function filterLimit(coll, limit, iteratee, callback) {
42 + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
43 +}
44 +exports.default = (0, _awaitify2.default)(filterLimit, 4);
45 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _filter2 = require('./internal/filter.js');
8 +
9 +var _filter3 = _interopRequireDefault(_filter2);
10 +
11 +var _eachOfSeries = require('./eachOfSeries.js');
12 +
13 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
23 + *
24 + * @name filterSeries
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.filter]{@link module:Collections.filter}
29 + * @alias selectSeries
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {Function} iteratee - A truth test to apply to each item in `coll`.
33 + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
34 + * with a boolean argument once it has completed. Invoked with (item, callback).
35 + * @param {Function} [callback] - A callback which is called after all the
36 + * `iteratee` functions have finished. Invoked with (err, results)
37 + * @returns {Promise} a promise, if no callback provided
38 + */
39 +function filterSeries(coll, iteratee, callback) {
40 + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback);
41 +}
42 +exports.default = (0, _awaitify2.default)(filterSeries, 3);
43 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOf = require('./eachOf.js');
12 +
13 +var _eachOf2 = _interopRequireDefault(_eachOf);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Returns the first value in `coll` that passes an async truth test. The
23 + * `iteratee` is applied in parallel, meaning the first iteratee to return
24 + * `true` will fire the detect `callback` with that result. That means the
25 + * result might not be the first item in the original `coll` (in terms of order)
26 + * that passes the test.
27 +
28 + * If order within the original `coll` is important, then look at
29 + * [`detectSeries`]{@link module:Collections.detectSeries}.
30 + *
31 + * @name detect
32 + * @static
33 + * @memberOf module:Collections
34 + * @method
35 + * @alias find
36 + * @category Collections
37 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
38 + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
39 + * The iteratee must complete with a boolean value as its result.
40 + * Invoked with (item, callback).
41 + * @param {Function} [callback] - A callback which is called as soon as any
42 + * iteratee returns `true`, or after all the `iteratee` functions have finished.
43 + * Result will be the first item in the array that passes the truth test
44 + * (iteratee) or the value `undefined` if none passed. Invoked with
45 + * (err, result).
46 + * @returns A Promise, if no callback is passed
47 + * @example
48 + *
49 + * // dir1 is a directory that contains file1.txt, file2.txt
50 + * // dir2 is a directory that contains file3.txt, file4.txt
51 + * // dir3 is a directory that contains file5.txt
52 + *
53 + * // asynchronous function that checks if a file exists
54 + * function fileExists(file, callback) {
55 + * fs.access(file, fs.constants.F_OK, (err) => {
56 + * callback(null, !err);
57 + * });
58 + * }
59 + *
60 + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,
61 + * function(err, result) {
62 + * console.log(result);
63 + * // dir1/file1.txt
64 + * // result now equals the first file in the list that exists
65 + * }
66 + *);
67 + *
68 + * // Using Promises
69 + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)
70 + * .then(result => {
71 + * console.log(result);
72 + * // dir1/file1.txt
73 + * // result now equals the first file in the list that exists
74 + * }).catch(err => {
75 + * console.log(err);
76 + * });
77 + *
78 + * // Using async/await
79 + * async () => {
80 + * try {
81 + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists);
82 + * console.log(result);
83 + * // dir1/file1.txt
84 + * // result now equals the file in the list that exists
85 + * }
86 + * catch (err) {
87 + * console.log(err);
88 + * }
89 + * }
90 + *
91 + */
92 +function detect(coll, iteratee, callback) {
93 + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback);
94 +}
95 +exports.default = (0, _awaitify2.default)(detect, 3);
96 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a
23 + * time.
24 + *
25 + * @name detectLimit
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @see [async.detect]{@link module:Collections.detect}
30 + * @alias findLimit
31 + * @category Collections
32 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
33 + * @param {number} limit - The maximum number of async operations at a time.
34 + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
35 + * The iteratee must complete with a boolean value as its result.
36 + * Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called as soon as any
38 + * iteratee returns `true`, or after all the `iteratee` functions have finished.
39 + * Result will be the first item in the array that passes the truth test
40 + * (iteratee) or the value `undefined` if none passed. Invoked with
41 + * (err, result).
42 + * @returns a Promise if no callback is passed
43 + */
44 +function detectLimit(coll, limit, iteratee, callback) {
45 + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
46 +}
47 +exports.default = (0, _awaitify2.default)(detectLimit, 4);
48 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.
23 + *
24 + * @name detectSeries
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.detect]{@link module:Collections.detect}
29 + * @alias findSeries
30 + * @category Collections
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.
33 + * The iteratee must complete with a boolean value as its result.
34 + * Invoked with (item, callback).
35 + * @param {Function} [callback] - A callback which is called as soon as any
36 + * iteratee returns `true`, or after all the `iteratee` functions have finished.
37 + * Result will be the first item in the array that passes the truth test
38 + * (iteratee) or the value `undefined` if none passed. Invoked with
39 + * (err, result).
40 + * @returns a Promise if no callback is passed
41 + */
42 +function detectSeries(coll, iteratee, callback) {
43 + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback);
44 +}
45 +
46 +exports.default = (0, _awaitify2.default)(detectSeries, 3);
47 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _concatLimit = require('./concatLimit.js');
8 +
9 +var _concatLimit2 = _interopRequireDefault(_concatLimit);
10 +
11 +var _awaitify = require('./internal/awaitify.js');
12 +
13 +var _awaitify2 = _interopRequireDefault(_awaitify);
14 +
15 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16 +
17 +/**
18 + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns
19 + * the concatenated list. The `iteratee`s are called in parallel, and the
20 + * results are concatenated as they return. The results array will be returned in
21 + * the original order of `coll` passed to the `iteratee` function.
22 + *
23 + * @name concat
24 + * @static
25 + * @memberOf module:Collections
26 + * @method
27 + * @category Collection
28 + * @alias flatMap
29 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
30 + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
31 + * which should use an array as its result. Invoked with (item, callback).
32 + * @param {Function} [callback] - A callback which is called after all the
33 + * `iteratee` functions have finished, or an error occurs. Results is an array
34 + * containing the concatenated results of the `iteratee` function. Invoked with
35 + * (err, results).
36 + * @returns A Promise, if no callback is passed
37 + * @example
38 + *
39 + * // dir1 is a directory that contains file1.txt, file2.txt
40 + * // dir2 is a directory that contains file3.txt, file4.txt
41 + * // dir3 is a directory that contains file5.txt
42 + * // dir4 does not exist
43 + *
44 + * let directoryList = ['dir1','dir2','dir3'];
45 + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];
46 + *
47 + * // Using callbacks
48 + * async.concat(directoryList, fs.readdir, function(err, results) {
49 + * if (err) {
50 + * console.log(err);
51 + * } else {
52 + * console.log(results);
53 + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
54 + * }
55 + * });
56 + *
57 + * // Error Handling
58 + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {
59 + * if (err) {
60 + * console.log(err);
61 + * // [ Error: ENOENT: no such file or directory ]
62 + * // since dir4 does not exist
63 + * } else {
64 + * console.log(results);
65 + * }
66 + * });
67 + *
68 + * // Using Promises
69 + * async.concat(directoryList, fs.readdir)
70 + * .then(results => {
71 + * console.log(results);
72 + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
73 + * }).catch(err => {
74 + * console.log(err);
75 + * });
76 + *
77 + * // Error Handling
78 + * async.concat(withMissingDirectoryList, fs.readdir)
79 + * .then(results => {
80 + * console.log(results);
81 + * }).catch(err => {
82 + * console.log(err);
83 + * // [ Error: ENOENT: no such file or directory ]
84 + * // since dir4 does not exist
85 + * });
86 + *
87 + * // Using async/await
88 + * async () => {
89 + * try {
90 + * let results = await async.concat(directoryList, fs.readdir);
91 + * console.log(results);
92 + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]
93 + * } catch (err) {
94 + * console.log(err);
95 + * }
96 + * }
97 + *
98 + * // Error Handling
99 + * async () => {
100 + * try {
101 + * let results = await async.concat(withMissingDirectoryList, fs.readdir);
102 + * console.log(results);
103 + * } catch (err) {
104 + * console.log(err);
105 + * // [ Error: ENOENT: no such file or directory ]
106 + * // since dir4 does not exist
107 + * }
108 + * }
109 + *
110 + */
111 +function concat(coll, iteratee, callback) {
112 + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback);
113 +}
114 +exports.default = (0, _awaitify2.default)(concat, 3);
115 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _wrapAsync = require('./internal/wrapAsync.js');
8 +
9 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
10 +
11 +var _mapLimit = require('./mapLimit.js');
12 +
13 +var _mapLimit2 = _interopRequireDefault(_mapLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.
23 + *
24 + * @name concatLimit
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.concat]{@link module:Collections.concat}
29 + * @category Collection
30 + * @alias flatMapLimit
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {number} limit - The maximum number of async operations at a time.
33 + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,
34 + * which should use an array as its result. Invoked with (item, callback).
35 + * @param {Function} [callback] - A callback which is called after all the
36 + * `iteratee` functions have finished, or an error occurs. Results is an array
37 + * containing the concatenated results of the `iteratee` function. Invoked with
38 + * (err, results).
39 + * @returns A Promise, if no callback is passed
40 + */
41 +function concatLimit(coll, limit, iteratee, callback) {
42 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
43 + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => {
44 + _iteratee(val, (err, ...args) => {
45 + if (err) return iterCb(err);
46 + return iterCb(err, args);
47 + });
48 + }, (err, mapResults) => {
49 + var result = [];
50 + for (var i = 0; i < mapResults.length; i++) {
51 + if (mapResults[i]) {
52 + result = result.concat(...mapResults[i]);
53 + }
54 + }
55 +
56 + return callback(err, result);
57 + });
58 +}
59 +exports.default = (0, _awaitify2.default)(concatLimit, 4);
60 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _concatLimit = require('./concatLimit.js');
8 +
9 +var _concatLimit2 = _interopRequireDefault(_concatLimit);
10 +
11 +var _awaitify = require('./internal/awaitify.js');
12 +
13 +var _awaitify2 = _interopRequireDefault(_awaitify);
14 +
15 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16 +
17 +/**
18 + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.
19 + *
20 + * @name concatSeries
21 + * @static
22 + * @memberOf module:Collections
23 + * @method
24 + * @see [async.concat]{@link module:Collections.concat}
25 + * @category Collection
26 + * @alias flatMapSeries
27 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
28 + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.
29 + * The iteratee should complete with an array an array of results.
30 + * Invoked with (item, callback).
31 + * @param {Function} [callback] - A callback which is called after all the
32 + * `iteratee` functions have finished, or an error occurs. Results is an array
33 + * containing the concatenated results of the `iteratee` function. Invoked with
34 + * (err, results).
35 + * @returns A Promise, if no callback is passed
36 + */
37 +function concatSeries(coll, iteratee, callback) {
38 + return (0, _concatLimit2.default)(coll, 1, iteratee, callback);
39 +}
40 +exports.default = (0, _awaitify2.default)(concatSeries, 3);
41 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOfSeries = require('./eachOfSeries.js');
8 +
9 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
10 +
11 +var _once = require('./internal/once.js');
12 +
13 +var _once2 = _interopRequireDefault(_once);
14 +
15 +var _wrapAsync = require('./internal/wrapAsync.js');
16 +
17 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
18 +
19 +var _awaitify = require('./internal/awaitify.js');
20 +
21 +var _awaitify2 = _interopRequireDefault(_awaitify);
22 +
23 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24 +
25 +/**
26 + * Reduces `coll` into a single value using an async `iteratee` to return each
27 + * successive step. `memo` is the initial state of the reduction. This function
28 + * only operates in series.
29 + *
30 + * For performance reasons, it may make sense to split a call to this function
31 + * into a parallel map, and then use the normal `Array.prototype.reduce` on the
32 + * results. This function is for situations where each step in the reduction
33 + * needs to be async; if you can get the data before reducing it, then it's
34 + * probably a good idea to do so.
35 + *
36 + * @name reduce
37 + * @static
38 + * @memberOf module:Collections
39 + * @method
40 + * @alias inject
41 + * @alias foldl
42 + * @category Collection
43 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
44 + * @param {*} memo - The initial state of the reduction.
45 + * @param {AsyncFunction} iteratee - A function applied to each item in the
46 + * array to produce the next step in the reduction.
47 + * The `iteratee` should complete with the next state of the reduction.
48 + * If the iteratee completes with an error, the reduction is stopped and the
49 + * main `callback` is immediately called with the error.
50 + * Invoked with (memo, item, callback).
51 + * @param {Function} [callback] - A callback which is called after all the
52 + * `iteratee` functions have finished. Result is the reduced value. Invoked with
53 + * (err, result).
54 + * @returns {Promise} a promise, if no callback is passed
55 + * @example
56 + *
57 + * // file1.txt is a file that is 1000 bytes in size
58 + * // file2.txt is a file that is 2000 bytes in size
59 + * // file3.txt is a file that is 3000 bytes in size
60 + * // file4.txt does not exist
61 + *
62 + * const fileList = ['file1.txt','file2.txt','file3.txt'];
63 + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];
64 + *
65 + * // asynchronous function that computes the file size in bytes
66 + * // file size is added to the memoized value, then returned
67 + * function getFileSizeInBytes(memo, file, callback) {
68 + * fs.stat(file, function(err, stat) {
69 + * if (err) {
70 + * return callback(err);
71 + * }
72 + * callback(null, memo + stat.size);
73 + * });
74 + * }
75 + *
76 + * // Using callbacks
77 + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) {
78 + * if (err) {
79 + * console.log(err);
80 + * } else {
81 + * console.log(result);
82 + * // 6000
83 + * // which is the sum of the file sizes of the three files
84 + * }
85 + * });
86 + *
87 + * // Error Handling
88 + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) {
89 + * if (err) {
90 + * console.log(err);
91 + * // [ Error: ENOENT: no such file or directory ]
92 + * } else {
93 + * console.log(result);
94 + * }
95 + * });
96 + *
97 + * // Using Promises
98 + * async.reduce(fileList, 0, getFileSizeInBytes)
99 + * .then( result => {
100 + * console.log(result);
101 + * // 6000
102 + * // which is the sum of the file sizes of the three files
103 + * }).catch( err => {
104 + * console.log(err);
105 + * });
106 + *
107 + * // Error Handling
108 + * async.reduce(withMissingFileList, 0, getFileSizeInBytes)
109 + * .then( result => {
110 + * console.log(result);
111 + * }).catch( err => {
112 + * console.log(err);
113 + * // [ Error: ENOENT: no such file or directory ]
114 + * });
115 + *
116 + * // Using async/await
117 + * async () => {
118 + * try {
119 + * let result = await async.reduce(fileList, 0, getFileSizeInBytes);
120 + * console.log(result);
121 + * // 6000
122 + * // which is the sum of the file sizes of the three files
123 + * }
124 + * catch (err) {
125 + * console.log(err);
126 + * }
127 + * }
128 + *
129 + * // Error Handling
130 + * async () => {
131 + * try {
132 + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);
133 + * console.log(result);
134 + * }
135 + * catch (err) {
136 + * console.log(err);
137 + * // [ Error: ENOENT: no such file or directory ]
138 + * }
139 + * }
140 + *
141 + */
142 +function reduce(coll, memo, iteratee, callback) {
143 + callback = (0, _once2.default)(callback);
144 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
145 + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => {
146 + _iteratee(memo, x, (err, v) => {
147 + memo = v;
148 + iterCb(err);
149 + });
150 + }, err => callback(err, memo));
151 +}
152 +exports.default = (0, _awaitify2.default)(reduce, 4);
153 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = reduceRight;
7 +
8 +var _reduce = require('./reduce.js');
9 +
10 +var _reduce2 = _interopRequireDefault(_reduce);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
16 + *
17 + * @name reduceRight
18 + * @static
19 + * @memberOf module:Collections
20 + * @method
21 + * @see [async.reduce]{@link module:Collections.reduce}
22 + * @alias foldr
23 + * @category Collection
24 + * @param {Array} array - A collection to iterate over.
25 + * @param {*} memo - The initial state of the reduction.
26 + * @param {AsyncFunction} iteratee - A function applied to each item in the
27 + * array to produce the next step in the reduction.
28 + * The `iteratee` should complete with the next state of the reduction.
29 + * If the iteratee completes with an error, the reduction is stopped and the
30 + * main `callback` is immediately called with the error.
31 + * Invoked with (memo, item, callback).
32 + * @param {Function} [callback] - A callback which is called after all the
33 + * `iteratee` functions have finished. Result is the reduced value. Invoked with
34 + * (err, result).
35 + * @returns {Promise} a promise, if no callback is passed
36 + */
37 +function reduceRight(array, memo, iteratee, callback) {
38 + var reversed = [...array].reverse();
39 + return (0, _reduce2.default)(reversed, memo, iteratee, callback);
40 +}
41 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOf = require('./eachOf.js');
8 +
9 +var _eachOf2 = _interopRequireDefault(_eachOf);
10 +
11 +var _withoutIndex = require('./internal/withoutIndex.js');
12 +
13 +var _withoutIndex2 = _interopRequireDefault(_withoutIndex);
14 +
15 +var _wrapAsync = require('./internal/wrapAsync.js');
16 +
17 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
18 +
19 +var _awaitify = require('./internal/awaitify.js');
20 +
21 +var _awaitify2 = _interopRequireDefault(_awaitify);
22 +
23 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24 +
25 +/**
26 + * Applies the function `iteratee` to each item in `coll`, in parallel.
27 + * The `iteratee` is called with an item from the list, and a callback for when
28 + * it has finished. If the `iteratee` passes an error to its `callback`, the
29 + * main `callback` (for the `each` function) is immediately called with the
30 + * error.
31 + *
32 + * Note, that since this function applies `iteratee` to each item in parallel,
33 + * there is no guarantee that the iteratee functions will complete in order.
34 + *
35 + * @name each
36 + * @static
37 + * @memberOf module:Collections
38 + * @method
39 + * @alias forEach
40 + * @category Collection
41 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
42 + * @param {AsyncFunction} iteratee - An async function to apply to
43 + * each item in `coll`. Invoked with (item, callback).
44 + * The array index is not passed to the iteratee.
45 + * If you need the index, use `eachOf`.
46 + * @param {Function} [callback] - A callback which is called when all
47 + * `iteratee` functions have finished, or an error occurs. Invoked with (err).
48 + * @returns {Promise} a promise, if a callback is omitted
49 + * @example
50 + *
51 + * // dir1 is a directory that contains file1.txt, file2.txt
52 + * // dir2 is a directory that contains file3.txt, file4.txt
53 + * // dir3 is a directory that contains file5.txt
54 + * // dir4 does not exist
55 + *
56 + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];
57 + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];
58 + *
59 + * // asynchronous function that deletes a file
60 + * const deleteFile = function(file, callback) {
61 + * fs.unlink(file, callback);
62 + * };
63 + *
64 + * // Using callbacks
65 + * async.each(fileList, deleteFile, function(err) {
66 + * if( err ) {
67 + * console.log(err);
68 + * } else {
69 + * console.log('All files have been deleted successfully');
70 + * }
71 + * });
72 + *
73 + * // Error Handling
74 + * async.each(withMissingFileList, deleteFile, function(err){
75 + * console.log(err);
76 + * // [ Error: ENOENT: no such file or directory ]
77 + * // since dir4/file2.txt does not exist
78 + * // dir1/file1.txt could have been deleted
79 + * });
80 + *
81 + * // Using Promises
82 + * async.each(fileList, deleteFile)
83 + * .then( () => {
84 + * console.log('All files have been deleted successfully');
85 + * }).catch( err => {
86 + * console.log(err);
87 + * });
88 + *
89 + * // Error Handling
90 + * async.each(fileList, deleteFile)
91 + * .then( () => {
92 + * console.log('All files have been deleted successfully');
93 + * }).catch( err => {
94 + * console.log(err);
95 + * // [ Error: ENOENT: no such file or directory ]
96 + * // since dir4/file2.txt does not exist
97 + * // dir1/file1.txt could have been deleted
98 + * });
99 + *
100 + * // Using async/await
101 + * async () => {
102 + * try {
103 + * await async.each(files, deleteFile);
104 + * }
105 + * catch (err) {
106 + * console.log(err);
107 + * }
108 + * }
109 + *
110 + * // Error Handling
111 + * async () => {
112 + * try {
113 + * await async.each(withMissingFileList, deleteFile);
114 + * }
115 + * catch (err) {
116 + * console.log(err);
117 + * // [ Error: ENOENT: no such file or directory ]
118 + * // since dir4/file2.txt does not exist
119 + * // dir1/file1.txt could have been deleted
120 + * }
121 + * }
122 + *
123 + */
124 +function eachLimit(coll, iteratee, callback) {
125 + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);
126 +}
127 +
128 +exports.default = (0, _awaitify2.default)(eachLimit, 3);
129 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOfLimit = require('./internal/eachOfLimit.js');
8 +
9 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
10 +
11 +var _withoutIndex = require('./internal/withoutIndex.js');
12 +
13 +var _withoutIndex2 = _interopRequireDefault(_withoutIndex);
14 +
15 +var _wrapAsync = require('./internal/wrapAsync.js');
16 +
17 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
18 +
19 +var _awaitify = require('./internal/awaitify.js');
20 +
21 +var _awaitify2 = _interopRequireDefault(_awaitify);
22 +
23 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24 +
25 +/**
26 + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.
27 + *
28 + * @name eachLimit
29 + * @static
30 + * @memberOf module:Collections
31 + * @method
32 + * @see [async.each]{@link module:Collections.each}
33 + * @alias forEachLimit
34 + * @category Collection
35 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
36 + * @param {number} limit - The maximum number of async operations at a time.
37 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
38 + * `coll`.
39 + * The array index is not passed to the iteratee.
40 + * If you need the index, use `eachOfLimit`.
41 + * Invoked with (item, callback).
42 + * @param {Function} [callback] - A callback which is called when all
43 + * `iteratee` functions have finished, or an error occurs. Invoked with (err).
44 + * @returns {Promise} a promise, if a callback is omitted
45 + */
46 +function eachLimit(coll, limit, iteratee, callback) {
47 + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);
48 +}
49 +exports.default = (0, _awaitify2.default)(eachLimit, 4);
50 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _isArrayLike = require('./internal/isArrayLike.js');
8 +
9 +var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
10 +
11 +var _breakLoop = require('./internal/breakLoop.js');
12 +
13 +var _breakLoop2 = _interopRequireDefault(_breakLoop);
14 +
15 +var _eachOfLimit = require('./eachOfLimit.js');
16 +
17 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
18 +
19 +var _once = require('./internal/once.js');
20 +
21 +var _once2 = _interopRequireDefault(_once);
22 +
23 +var _onlyOnce = require('./internal/onlyOnce.js');
24 +
25 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
26 +
27 +var _wrapAsync = require('./internal/wrapAsync.js');
28 +
29 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
30 +
31 +var _awaitify = require('./internal/awaitify.js');
32 +
33 +var _awaitify2 = _interopRequireDefault(_awaitify);
34 +
35 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
36 +
37 +// eachOf implementation optimized for array-likes
38 +function eachOfArrayLike(coll, iteratee, callback) {
39 + callback = (0, _once2.default)(callback);
40 + var index = 0,
41 + completed = 0,
42 + { length } = coll,
43 + canceled = false;
44 + if (length === 0) {
45 + callback(null);
46 + }
47 +
48 + function iteratorCallback(err, value) {
49 + if (err === false) {
50 + canceled = true;
51 + }
52 + if (canceled === true) return;
53 + if (err) {
54 + callback(err);
55 + } else if (++completed === length || value === _breakLoop2.default) {
56 + callback(null);
57 + }
58 + }
59 +
60 + for (; index < length; index++) {
61 + iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback));
62 + }
63 +}
64 +
65 +// a generic version of eachOf which can handle array, object, and iterator cases.
66 +function eachOfGeneric(coll, iteratee, callback) {
67 + return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback);
68 +}
69 +
70 +/**
71 + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
72 + * to the iteratee.
73 + *
74 + * @name eachOf
75 + * @static
76 + * @memberOf module:Collections
77 + * @method
78 + * @alias forEachOf
79 + * @category Collection
80 + * @see [async.each]{@link module:Collections.each}
81 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
82 + * @param {AsyncFunction} iteratee - A function to apply to each
83 + * item in `coll`.
84 + * The `key` is the item's key, or index in the case of an array.
85 + * Invoked with (item, key, callback).
86 + * @param {Function} [callback] - A callback which is called when all
87 + * `iteratee` functions have finished, or an error occurs. Invoked with (err).
88 + * @returns {Promise} a promise, if a callback is omitted
89 + * @example
90 + *
91 + * // dev.json is a file containing a valid json object config for dev environment
92 + * // dev.json is a file containing a valid json object config for test environment
93 + * // prod.json is a file containing a valid json object config for prod environment
94 + * // invalid.json is a file with a malformed json object
95 + *
96 + * let configs = {}; //global variable
97 + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};
98 + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};
99 + *
100 + * // asynchronous function that reads a json file and parses the contents as json object
101 + * function parseFile(file, key, callback) {
102 + * fs.readFile(file, "utf8", function(err, data) {
103 + * if (err) return calback(err);
104 + * try {
105 + * configs[key] = JSON.parse(data);
106 + * } catch (e) {
107 + * return callback(e);
108 + * }
109 + * callback();
110 + * });
111 + * }
112 + *
113 + * // Using callbacks
114 + * async.forEachOf(validConfigFileMap, parseFile, function (err) {
115 + * if (err) {
116 + * console.error(err);
117 + * } else {
118 + * console.log(configs);
119 + * // configs is now a map of JSON data, e.g.
120 + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
121 + * }
122 + * });
123 + *
124 + * //Error handing
125 + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) {
126 + * if (err) {
127 + * console.error(err);
128 + * // JSON parse error exception
129 + * } else {
130 + * console.log(configs);
131 + * }
132 + * });
133 + *
134 + * // Using Promises
135 + * async.forEachOf(validConfigFileMap, parseFile)
136 + * .then( () => {
137 + * console.log(configs);
138 + * // configs is now a map of JSON data, e.g.
139 + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
140 + * }).catch( err => {
141 + * console.error(err);
142 + * });
143 + *
144 + * //Error handing
145 + * async.forEachOf(invalidConfigFileMap, parseFile)
146 + * .then( () => {
147 + * console.log(configs);
148 + * }).catch( err => {
149 + * console.error(err);
150 + * // JSON parse error exception
151 + * });
152 + *
153 + * // Using async/await
154 + * async () => {
155 + * try {
156 + * let result = await async.forEachOf(validConfigFileMap, parseFile);
157 + * console.log(configs);
158 + * // configs is now a map of JSON data, e.g.
159 + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}
160 + * }
161 + * catch (err) {
162 + * console.log(err);
163 + * }
164 + * }
165 + *
166 + * //Error handing
167 + * async () => {
168 + * try {
169 + * let result = await async.forEachOf(invalidConfigFileMap, parseFile);
170 + * console.log(configs);
171 + * }
172 + * catch (err) {
173 + * console.log(err);
174 + * // JSON parse error exception
175 + * }
176 + * }
177 + *
178 + */
179 +function eachOf(coll, iteratee, callback) {
180 + var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric;
181 + return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback);
182 +}
183 +
184 +exports.default = (0, _awaitify2.default)(eachOf, 3);
185 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOfLimit2 = require('./internal/eachOfLimit.js');
8 +
9 +var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2);
10 +
11 +var _wrapAsync = require('./internal/wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
23 + * time.
24 + *
25 + * @name eachOfLimit
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @see [async.eachOf]{@link module:Collections.eachOf}
30 + * @alias forEachOfLimit
31 + * @category Collection
32 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
33 + * @param {number} limit - The maximum number of async operations at a time.
34 + * @param {AsyncFunction} iteratee - An async function to apply to each
35 + * item in `coll`. The `key` is the item's key, or index in the case of an
36 + * array.
37 + * Invoked with (item, key, callback).
38 + * @param {Function} [callback] - A callback which is called when all
39 + * `iteratee` functions have finished, or an error occurs. Invoked with (err).
40 + * @returns {Promise} a promise, if a callback is omitted
41 + */
42 +function eachOfLimit(coll, limit, iteratee, callback) {
43 + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback);
44 +}
45 +
46 +exports.default = (0, _awaitify2.default)(eachOfLimit, 4);
47 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOfLimit = require('./eachOfLimit.js');
8 +
9 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
10 +
11 +var _awaitify = require('./internal/awaitify.js');
12 +
13 +var _awaitify2 = _interopRequireDefault(_awaitify);
14 +
15 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16 +
17 +/**
18 + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
19 + *
20 + * @name eachOfSeries
21 + * @static
22 + * @memberOf module:Collections
23 + * @method
24 + * @see [async.eachOf]{@link module:Collections.eachOf}
25 + * @alias forEachOfSeries
26 + * @category Collection
27 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
28 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
29 + * `coll`.
30 + * Invoked with (item, key, callback).
31 + * @param {Function} [callback] - A callback which is called when all `iteratee`
32 + * functions have finished, or an error occurs. Invoked with (err).
33 + * @returns {Promise} a promise, if a callback is omitted
34 + */
35 +function eachOfSeries(coll, iteratee, callback) {
36 + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback);
37 +}
38 +exports.default = (0, _awaitify2.default)(eachOfSeries, 3);
39 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachLimit = require('./eachLimit.js');
8 +
9 +var _eachLimit2 = _interopRequireDefault(_eachLimit);
10 +
11 +var _awaitify = require('./internal/awaitify.js');
12 +
13 +var _awaitify2 = _interopRequireDefault(_awaitify);
14 +
15 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16 +
17 +/**
18 + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.
19 + *
20 + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item
21 + * in series and therefore the iteratee functions will complete in order.
22 +
23 + * @name eachSeries
24 + * @static
25 + * @memberOf module:Collections
26 + * @method
27 + * @see [async.each]{@link module:Collections.each}
28 + * @alias forEachSeries
29 + * @category Collection
30 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
31 + * @param {AsyncFunction} iteratee - An async function to apply to each
32 + * item in `coll`.
33 + * The array index is not passed to the iteratee.
34 + * If you need the index, use `eachOfSeries`.
35 + * Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called when all
37 + * `iteratee` functions have finished, or an error occurs. Invoked with (err).
38 + * @returns {Promise} a promise, if a callback is omitted
39 + */
40 +function eachSeries(coll, iteratee, callback) {
41 + return (0, _eachLimit2.default)(coll, 1, iteratee, callback);
42 +}
43 +exports.default = (0, _awaitify2.default)(eachSeries, 3);
44 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _onlyOnce = require('./internal/onlyOnce.js');
8 +
9 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
10 +
11 +var _ensureAsync = require('./ensureAsync.js');
12 +
13 +var _ensureAsync2 = _interopRequireDefault(_ensureAsync);
14 +
15 +var _wrapAsync = require('./internal/wrapAsync.js');
16 +
17 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
18 +
19 +var _awaitify = require('./internal/awaitify.js');
20 +
21 +var _awaitify2 = _interopRequireDefault(_awaitify);
22 +
23 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24 +
25 +/**
26 + * Calls the asynchronous function `fn` with a callback parameter that allows it
27 + * to call itself again, in series, indefinitely.
28 +
29 + * If an error is passed to the callback then `errback` is called with the
30 + * error, and execution stops, otherwise it will never be called.
31 + *
32 + * @name forever
33 + * @static
34 + * @memberOf module:ControlFlow
35 + * @method
36 + * @category Control Flow
37 + * @param {AsyncFunction} fn - an async function to call repeatedly.
38 + * Invoked with (next).
39 + * @param {Function} [errback] - when `fn` passes an error to it's callback,
40 + * this function will be called, and execution stops. Invoked with (err).
41 + * @returns {Promise} a promise that rejects if an error occurs and an errback
42 + * is not passed
43 + * @example
44 + *
45 + * async.forever(
46 + * function(next) {
47 + * // next is suitable for passing to things that need a callback(err [, whatever]);
48 + * // it will result in this function being called again.
49 + * },
50 + * function(err) {
51 + * // if next is called with a value in its first parameter, it will appear
52 + * // in here as 'err', and execution will stop.
53 + * }
54 + * );
55 + */
56 +function forever(fn, errback) {
57 + var done = (0, _onlyOnce2.default)(errback);
58 + var task = (0, _wrapAsync2.default)((0, _ensureAsync2.default)(fn));
59 +
60 + function next(err) {
61 + if (err) return done(err);
62 + if (err === false) return;
63 + task(next);
64 + }
65 + return next();
66 +}
67 +exports.default = (0, _awaitify2.default)(forever, 2);
68 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = groupBy;
7 +
8 +var _groupByLimit = require('./groupByLimit.js');
9 +
10 +var _groupByLimit2 = _interopRequireDefault(_groupByLimit);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * Returns a new object, where each value corresponds to an array of items, from
16 + * `coll`, that returned the corresponding key. That is, the keys of the object
17 + * correspond to the values passed to the `iteratee` callback.
18 + *
19 + * Note: Since this function applies the `iteratee` to each item in parallel,
20 + * there is no guarantee that the `iteratee` functions will complete in order.
21 + * However, the values for each key in the `result` will be in the same order as
22 + * the original `coll`. For Objects, the values will roughly be in the order of
23 + * the original Objects' keys (but this can vary across JavaScript engines).
24 + *
25 + * @name groupBy
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @category Collection
30 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
31 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
32 + * `coll`.
33 + * The iteratee should complete with a `key` to group the value under.
34 + * Invoked with (value, callback).
35 + * @param {Function} [callback] - A callback which is called when all `iteratee`
36 + * functions have finished, or an error occurs. Result is an `Object` whoses
37 + * properties are arrays of values which returned the corresponding key.
38 + * @returns {Promise} a promise, if no callback is passed
39 + * @example
40 + *
41 + * // dir1 is a directory that contains file1.txt, file2.txt
42 + * // dir2 is a directory that contains file3.txt, file4.txt
43 + * // dir3 is a directory that contains file5.txt
44 + * // dir4 does not exist
45 + *
46 + * const files = ['dir1/file1.txt','dir2','dir4']
47 + *
48 + * // asynchronous function that detects file type as none, file, or directory
49 + * function detectFile(file, callback) {
50 + * fs.stat(file, function(err, stat) {
51 + * if (err) {
52 + * return callback(null, 'none');
53 + * }
54 + * callback(null, stat.isDirectory() ? 'directory' : 'file');
55 + * });
56 + * }
57 + *
58 + * //Using callbacks
59 + * async.groupBy(files, detectFile, function(err, result) {
60 + * if(err) {
61 + * console.log(err);
62 + * } else {
63 + * console.log(result);
64 + * // {
65 + * // file: [ 'dir1/file1.txt' ],
66 + * // none: [ 'dir4' ],
67 + * // directory: [ 'dir2']
68 + * // }
69 + * // result is object containing the files grouped by type
70 + * }
71 + * });
72 + *
73 + * // Using Promises
74 + * async.groupBy(files, detectFile)
75 + * .then( result => {
76 + * console.log(result);
77 + * // {
78 + * // file: [ 'dir1/file1.txt' ],
79 + * // none: [ 'dir4' ],
80 + * // directory: [ 'dir2']
81 + * // }
82 + * // result is object containing the files grouped by type
83 + * }).catch( err => {
84 + * console.log(err);
85 + * });
86 + *
87 + * // Using async/await
88 + * async () => {
89 + * try {
90 + * let result = await async.groupBy(files, detectFile);
91 + * console.log(result);
92 + * // {
93 + * // file: [ 'dir1/file1.txt' ],
94 + * // none: [ 'dir4' ],
95 + * // directory: [ 'dir2']
96 + * // }
97 + * // result is object containing the files grouped by type
98 + * }
99 + * catch (err) {
100 + * console.log(err);
101 + * }
102 + * }
103 + *
104 + */
105 +function groupBy(coll, iteratee, callback) {
106 + return (0, _groupByLimit2.default)(coll, Infinity, iteratee, callback);
107 +}
108 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _mapLimit = require('./mapLimit.js');
8 +
9 +var _mapLimit2 = _interopRequireDefault(_mapLimit);
10 +
11 +var _wrapAsync = require('./internal/wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.
23 + *
24 + * @name groupByLimit
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.groupBy]{@link module:Collections.groupBy}
29 + * @category Collection
30 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
31 + * @param {number} limit - The maximum number of async operations at a time.
32 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
33 + * `coll`.
34 + * The iteratee should complete with a `key` to group the value under.
35 + * Invoked with (value, callback).
36 + * @param {Function} [callback] - A callback which is called when all `iteratee`
37 + * functions have finished, or an error occurs. Result is an `Object` whoses
38 + * properties are arrays of values which returned the corresponding key.
39 + * @returns {Promise} a promise, if no callback is passed
40 + */
41 +function groupByLimit(coll, limit, iteratee, callback) {
42 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
43 + return (0, _mapLimit2.default)(coll, limit, (val, iterCb) => {
44 + _iteratee(val, (err, key) => {
45 + if (err) return iterCb(err);
46 + return iterCb(err, { key, val });
47 + });
48 + }, (err, mapResults) => {
49 + var result = {};
50 + // from MDN, handle object having an `hasOwnProperty` prop
51 + var { hasOwnProperty } = Object.prototype;
52 +
53 + for (var i = 0; i < mapResults.length; i++) {
54 + if (mapResults[i]) {
55 + var { key } = mapResults[i];
56 + var { val } = mapResults[i];
57 +
58 + if (hasOwnProperty.call(result, key)) {
59 + result[key].push(val);
60 + } else {
61 + result[key] = [val];
62 + }
63 + }
64 + }
65 +
66 + return callback(err, result);
67 + });
68 +}
69 +
70 +exports.default = (0, _awaitify2.default)(groupByLimit, 4);
71 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = groupBySeries;
7 +
8 +var _groupByLimit = require('./groupByLimit.js');
9 +
10 +var _groupByLimit2 = _interopRequireDefault(_groupByLimit);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.
16 + *
17 + * @name groupBySeries
18 + * @static
19 + * @memberOf module:Collections
20 + * @method
21 + * @see [async.groupBy]{@link module:Collections.groupBy}
22 + * @category Collection
23 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
24 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
25 + * `coll`.
26 + * The iteratee should complete with a `key` to group the value under.
27 + * Invoked with (value, callback).
28 + * @param {Function} [callback] - A callback which is called when all `iteratee`
29 + * functions have finished, or an error occurs. Result is an `Object` whose
30 + * properties are arrays of values which returned the corresponding key.
31 + * @returns {Promise} a promise, if no callback is passed
32 + */
33 +function groupBySeries(coll, iteratee, callback) {
34 + return (0, _groupByLimit2.default)(coll, 1, iteratee, callback);
35 +}
36 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.doDuring = exports.during = exports.wrapSync = undefined;
7 +exports.selectSeries = exports.selectLimit = exports.select = exports.foldr = exports.foldl = exports.inject = exports.forEachOfLimit = exports.forEachOfSeries = exports.forEachOf = exports.forEachLimit = exports.forEachSeries = exports.forEach = exports.flatMapSeries = exports.flatMapLimit = exports.flatMap = exports.findSeries = exports.findLimit = exports.find = exports.anySeries = exports.anyLimit = exports.any = exports.allSeries = exports.allLimit = exports.all = exports.whilst = exports.waterfall = exports.until = exports.unmemoize = exports.tryEach = exports.transform = exports.timesSeries = exports.timesLimit = exports.times = exports.timeout = exports.sortBy = exports.someSeries = exports.someLimit = exports.some = exports.setImmediate = exports.series = exports.seq = exports.retryable = exports.retry = exports.rejectSeries = exports.rejectLimit = exports.reject = exports.reflectAll = exports.reflect = exports.reduceRight = exports.reduce = exports.race = exports.queue = exports.priorityQueue = exports.parallelLimit = exports.parallel = exports.nextTick = exports.memoize = exports.mapValuesSeries = exports.mapValuesLimit = exports.mapValues = exports.mapSeries = exports.mapLimit = exports.map = exports.log = exports.groupBySeries = exports.groupByLimit = exports.groupBy = exports.forever = exports.filterSeries = exports.filterLimit = exports.filter = exports.everySeries = exports.everyLimit = exports.every = exports.ensureAsync = exports.eachSeries = exports.eachOfSeries = exports.eachOfLimit = exports.eachOf = exports.eachLimit = exports.each = exports.doWhilst = exports.doUntil = exports.dir = exports.detectSeries = exports.detectLimit = exports.detect = exports.constant = exports.concatSeries = exports.concatLimit = exports.concat = exports.compose = exports.cargoQueue = exports.cargo = exports.autoInject = exports.auto = exports.asyncify = exports.applyEachSeries = exports.applyEach = exports.apply = undefined;
8 +
9 +var _apply = require('./apply');
10 +
11 +var _apply2 = _interopRequireDefault(_apply);
12 +
13 +var _applyEach = require('./applyEach');
14 +
15 +var _applyEach2 = _interopRequireDefault(_applyEach);
16 +
17 +var _applyEachSeries = require('./applyEachSeries');
18 +
19 +var _applyEachSeries2 = _interopRequireDefault(_applyEachSeries);
20 +
21 +var _asyncify = require('./asyncify');
22 +
23 +var _asyncify2 = _interopRequireDefault(_asyncify);
24 +
25 +var _auto = require('./auto');
26 +
27 +var _auto2 = _interopRequireDefault(_auto);
28 +
29 +var _autoInject = require('./autoInject');
30 +
31 +var _autoInject2 = _interopRequireDefault(_autoInject);
32 +
33 +var _cargo = require('./cargo');
34 +
35 +var _cargo2 = _interopRequireDefault(_cargo);
36 +
37 +var _cargoQueue = require('./cargoQueue');
38 +
39 +var _cargoQueue2 = _interopRequireDefault(_cargoQueue);
40 +
41 +var _compose = require('./compose');
42 +
43 +var _compose2 = _interopRequireDefault(_compose);
44 +
45 +var _concat = require('./concat');
46 +
47 +var _concat2 = _interopRequireDefault(_concat);
48 +
49 +var _concatLimit = require('./concatLimit');
50 +
51 +var _concatLimit2 = _interopRequireDefault(_concatLimit);
52 +
53 +var _concatSeries = require('./concatSeries');
54 +
55 +var _concatSeries2 = _interopRequireDefault(_concatSeries);
56 +
57 +var _constant = require('./constant');
58 +
59 +var _constant2 = _interopRequireDefault(_constant);
60 +
61 +var _detect = require('./detect');
62 +
63 +var _detect2 = _interopRequireDefault(_detect);
64 +
65 +var _detectLimit = require('./detectLimit');
66 +
67 +var _detectLimit2 = _interopRequireDefault(_detectLimit);
68 +
69 +var _detectSeries = require('./detectSeries');
70 +
71 +var _detectSeries2 = _interopRequireDefault(_detectSeries);
72 +
73 +var _dir = require('./dir');
74 +
75 +var _dir2 = _interopRequireDefault(_dir);
76 +
77 +var _doUntil = require('./doUntil');
78 +
79 +var _doUntil2 = _interopRequireDefault(_doUntil);
80 +
81 +var _doWhilst = require('./doWhilst');
82 +
83 +var _doWhilst2 = _interopRequireDefault(_doWhilst);
84 +
85 +var _each = require('./each');
86 +
87 +var _each2 = _interopRequireDefault(_each);
88 +
89 +var _eachLimit = require('./eachLimit');
90 +
91 +var _eachLimit2 = _interopRequireDefault(_eachLimit);
92 +
93 +var _eachOf = require('./eachOf');
94 +
95 +var _eachOf2 = _interopRequireDefault(_eachOf);
96 +
97 +var _eachOfLimit = require('./eachOfLimit');
98 +
99 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
100 +
101 +var _eachOfSeries = require('./eachOfSeries');
102 +
103 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
104 +
105 +var _eachSeries = require('./eachSeries');
106 +
107 +var _eachSeries2 = _interopRequireDefault(_eachSeries);
108 +
109 +var _ensureAsync = require('./ensureAsync');
110 +
111 +var _ensureAsync2 = _interopRequireDefault(_ensureAsync);
112 +
113 +var _every = require('./every');
114 +
115 +var _every2 = _interopRequireDefault(_every);
116 +
117 +var _everyLimit = require('./everyLimit');
118 +
119 +var _everyLimit2 = _interopRequireDefault(_everyLimit);
120 +
121 +var _everySeries = require('./everySeries');
122 +
123 +var _everySeries2 = _interopRequireDefault(_everySeries);
124 +
125 +var _filter = require('./filter');
126 +
127 +var _filter2 = _interopRequireDefault(_filter);
128 +
129 +var _filterLimit = require('./filterLimit');
130 +
131 +var _filterLimit2 = _interopRequireDefault(_filterLimit);
132 +
133 +var _filterSeries = require('./filterSeries');
134 +
135 +var _filterSeries2 = _interopRequireDefault(_filterSeries);
136 +
137 +var _forever = require('./forever');
138 +
139 +var _forever2 = _interopRequireDefault(_forever);
140 +
141 +var _groupBy = require('./groupBy');
142 +
143 +var _groupBy2 = _interopRequireDefault(_groupBy);
144 +
145 +var _groupByLimit = require('./groupByLimit');
146 +
147 +var _groupByLimit2 = _interopRequireDefault(_groupByLimit);
148 +
149 +var _groupBySeries = require('./groupBySeries');
150 +
151 +var _groupBySeries2 = _interopRequireDefault(_groupBySeries);
152 +
153 +var _log = require('./log');
154 +
155 +var _log2 = _interopRequireDefault(_log);
156 +
157 +var _map = require('./map');
158 +
159 +var _map2 = _interopRequireDefault(_map);
160 +
161 +var _mapLimit = require('./mapLimit');
162 +
163 +var _mapLimit2 = _interopRequireDefault(_mapLimit);
164 +
165 +var _mapSeries = require('./mapSeries');
166 +
167 +var _mapSeries2 = _interopRequireDefault(_mapSeries);
168 +
169 +var _mapValues = require('./mapValues');
170 +
171 +var _mapValues2 = _interopRequireDefault(_mapValues);
172 +
173 +var _mapValuesLimit = require('./mapValuesLimit');
174 +
175 +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit);
176 +
177 +var _mapValuesSeries = require('./mapValuesSeries');
178 +
179 +var _mapValuesSeries2 = _interopRequireDefault(_mapValuesSeries);
180 +
181 +var _memoize = require('./memoize');
182 +
183 +var _memoize2 = _interopRequireDefault(_memoize);
184 +
185 +var _nextTick = require('./nextTick');
186 +
187 +var _nextTick2 = _interopRequireDefault(_nextTick);
188 +
189 +var _parallel = require('./parallel');
190 +
191 +var _parallel2 = _interopRequireDefault(_parallel);
192 +
193 +var _parallelLimit = require('./parallelLimit');
194 +
195 +var _parallelLimit2 = _interopRequireDefault(_parallelLimit);
196 +
197 +var _priorityQueue = require('./priorityQueue');
198 +
199 +var _priorityQueue2 = _interopRequireDefault(_priorityQueue);
200 +
201 +var _queue = require('./queue');
202 +
203 +var _queue2 = _interopRequireDefault(_queue);
204 +
205 +var _race = require('./race');
206 +
207 +var _race2 = _interopRequireDefault(_race);
208 +
209 +var _reduce = require('./reduce');
210 +
211 +var _reduce2 = _interopRequireDefault(_reduce);
212 +
213 +var _reduceRight = require('./reduceRight');
214 +
215 +var _reduceRight2 = _interopRequireDefault(_reduceRight);
216 +
217 +var _reflect = require('./reflect');
218 +
219 +var _reflect2 = _interopRequireDefault(_reflect);
220 +
221 +var _reflectAll = require('./reflectAll');
222 +
223 +var _reflectAll2 = _interopRequireDefault(_reflectAll);
224 +
225 +var _reject = require('./reject');
226 +
227 +var _reject2 = _interopRequireDefault(_reject);
228 +
229 +var _rejectLimit = require('./rejectLimit');
230 +
231 +var _rejectLimit2 = _interopRequireDefault(_rejectLimit);
232 +
233 +var _rejectSeries = require('./rejectSeries');
234 +
235 +var _rejectSeries2 = _interopRequireDefault(_rejectSeries);
236 +
237 +var _retry = require('./retry');
238 +
239 +var _retry2 = _interopRequireDefault(_retry);
240 +
241 +var _retryable = require('./retryable');
242 +
243 +var _retryable2 = _interopRequireDefault(_retryable);
244 +
245 +var _seq = require('./seq');
246 +
247 +var _seq2 = _interopRequireDefault(_seq);
248 +
249 +var _series = require('./series');
250 +
251 +var _series2 = _interopRequireDefault(_series);
252 +
253 +var _setImmediate = require('./setImmediate');
254 +
255 +var _setImmediate2 = _interopRequireDefault(_setImmediate);
256 +
257 +var _some = require('./some');
258 +
259 +var _some2 = _interopRequireDefault(_some);
260 +
261 +var _someLimit = require('./someLimit');
262 +
263 +var _someLimit2 = _interopRequireDefault(_someLimit);
264 +
265 +var _someSeries = require('./someSeries');
266 +
267 +var _someSeries2 = _interopRequireDefault(_someSeries);
268 +
269 +var _sortBy = require('./sortBy');
270 +
271 +var _sortBy2 = _interopRequireDefault(_sortBy);
272 +
273 +var _timeout = require('./timeout');
274 +
275 +var _timeout2 = _interopRequireDefault(_timeout);
276 +
277 +var _times = require('./times');
278 +
279 +var _times2 = _interopRequireDefault(_times);
280 +
281 +var _timesLimit = require('./timesLimit');
282 +
283 +var _timesLimit2 = _interopRequireDefault(_timesLimit);
284 +
285 +var _timesSeries = require('./timesSeries');
286 +
287 +var _timesSeries2 = _interopRequireDefault(_timesSeries);
288 +
289 +var _transform = require('./transform');
290 +
291 +var _transform2 = _interopRequireDefault(_transform);
292 +
293 +var _tryEach = require('./tryEach');
294 +
295 +var _tryEach2 = _interopRequireDefault(_tryEach);
296 +
297 +var _unmemoize = require('./unmemoize');
298 +
299 +var _unmemoize2 = _interopRequireDefault(_unmemoize);
300 +
301 +var _until = require('./until');
302 +
303 +var _until2 = _interopRequireDefault(_until);
304 +
305 +var _waterfall = require('./waterfall');
306 +
307 +var _waterfall2 = _interopRequireDefault(_waterfall);
308 +
309 +var _whilst = require('./whilst');
310 +
311 +var _whilst2 = _interopRequireDefault(_whilst);
312 +
313 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
314 +
315 +/**
316 + * An "async function" in the context of Async is an asynchronous function with
317 + * a variable number of parameters, with the final parameter being a callback.
318 + * (`function (arg1, arg2, ..., callback) {}`)
319 + * The final callback is of the form `callback(err, results...)`, which must be
320 + * called once the function is completed. The callback should be called with a
321 + * Error as its first argument to signal that an error occurred.
322 + * Otherwise, if no error occurred, it should be called with `null` as the first
323 + * argument, and any additional `result` arguments that may apply, to signal
324 + * successful completion.
325 + * The callback must be called exactly once, ideally on a later tick of the
326 + * JavaScript event loop.
327 + *
328 + * This type of function is also referred to as a "Node-style async function",
329 + * or a "continuation passing-style function" (CPS). Most of the methods of this
330 + * library are themselves CPS/Node-style async functions, or functions that
331 + * return CPS/Node-style async functions.
332 + *
333 + * Wherever we accept a Node-style async function, we also directly accept an
334 + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.
335 + * In this case, the `async` function will not be passed a final callback
336 + * argument, and any thrown error will be used as the `err` argument of the
337 + * implicit callback, and the return value will be used as the `result` value.
338 + * (i.e. a `rejected` of the returned Promise becomes the `err` callback
339 + * argument, and a `resolved` value becomes the `result`.)
340 + *
341 + * Note, due to JavaScript limitations, we can only detect native `async`
342 + * functions and not transpilied implementations.
343 + * Your environment must have `async`/`await` support for this to work.
344 + * (e.g. Node > v7.6, or a recent version of a modern browser).
345 + * If you are using `async` functions through a transpiler (e.g. Babel), you
346 + * must still wrap the function with [asyncify]{@link module:Utils.asyncify},
347 + * because the `async function` will be compiled to an ordinary function that
348 + * returns a promise.
349 + *
350 + * @typedef {Function} AsyncFunction
351 + * @static
352 + */
353 +
354 +/**
355 + * Async is a utility module which provides straight-forward, powerful functions
356 + * for working with asynchronous JavaScript. Although originally designed for
357 + * use with [Node.js](http://nodejs.org) and installable via
358 + * `npm install --save async`, it can also be used directly in the browser.
359 + * @module async
360 + * @see AsyncFunction
361 + */
362 +
363 +/**
364 + * A collection of `async` functions for manipulating collections, such as
365 + * arrays and objects.
366 + * @module Collections
367 + */
368 +
369 +/**
370 + * A collection of `async` functions for controlling the flow through a script.
371 + * @module ControlFlow
372 + */
373 +
374 +/**
375 + * A collection of `async` utility functions.
376 + * @module Utils
377 + */
378 +
379 +exports.default = {
380 + apply: _apply2.default,
381 + applyEach: _applyEach2.default,
382 + applyEachSeries: _applyEachSeries2.default,
383 + asyncify: _asyncify2.default,
384 + auto: _auto2.default,
385 + autoInject: _autoInject2.default,
386 + cargo: _cargo2.default,
387 + cargoQueue: _cargoQueue2.default,
388 + compose: _compose2.default,
389 + concat: _concat2.default,
390 + concatLimit: _concatLimit2.default,
391 + concatSeries: _concatSeries2.default,
392 + constant: _constant2.default,
393 + detect: _detect2.default,
394 + detectLimit: _detectLimit2.default,
395 + detectSeries: _detectSeries2.default,
396 + dir: _dir2.default,
397 + doUntil: _doUntil2.default,
398 + doWhilst: _doWhilst2.default,
399 + each: _each2.default,
400 + eachLimit: _eachLimit2.default,
401 + eachOf: _eachOf2.default,
402 + eachOfLimit: _eachOfLimit2.default,
403 + eachOfSeries: _eachOfSeries2.default,
404 + eachSeries: _eachSeries2.default,
405 + ensureAsync: _ensureAsync2.default,
406 + every: _every2.default,
407 + everyLimit: _everyLimit2.default,
408 + everySeries: _everySeries2.default,
409 + filter: _filter2.default,
410 + filterLimit: _filterLimit2.default,
411 + filterSeries: _filterSeries2.default,
412 + forever: _forever2.default,
413 + groupBy: _groupBy2.default,
414 + groupByLimit: _groupByLimit2.default,
415 + groupBySeries: _groupBySeries2.default,
416 + log: _log2.default,
417 + map: _map2.default,
418 + mapLimit: _mapLimit2.default,
419 + mapSeries: _mapSeries2.default,
420 + mapValues: _mapValues2.default,
421 + mapValuesLimit: _mapValuesLimit2.default,
422 + mapValuesSeries: _mapValuesSeries2.default,
423 + memoize: _memoize2.default,
424 + nextTick: _nextTick2.default,
425 + parallel: _parallel2.default,
426 + parallelLimit: _parallelLimit2.default,
427 + priorityQueue: _priorityQueue2.default,
428 + queue: _queue2.default,
429 + race: _race2.default,
430 + reduce: _reduce2.default,
431 + reduceRight: _reduceRight2.default,
432 + reflect: _reflect2.default,
433 + reflectAll: _reflectAll2.default,
434 + reject: _reject2.default,
435 + rejectLimit: _rejectLimit2.default,
436 + rejectSeries: _rejectSeries2.default,
437 + retry: _retry2.default,
438 + retryable: _retryable2.default,
439 + seq: _seq2.default,
440 + series: _series2.default,
441 + setImmediate: _setImmediate2.default,
442 + some: _some2.default,
443 + someLimit: _someLimit2.default,
444 + someSeries: _someSeries2.default,
445 + sortBy: _sortBy2.default,
446 + timeout: _timeout2.default,
447 + times: _times2.default,
448 + timesLimit: _timesLimit2.default,
449 + timesSeries: _timesSeries2.default,
450 + transform: _transform2.default,
451 + tryEach: _tryEach2.default,
452 + unmemoize: _unmemoize2.default,
453 + until: _until2.default,
454 + waterfall: _waterfall2.default,
455 + whilst: _whilst2.default,
456 +
457 + // aliases
458 + all: _every2.default,
459 + allLimit: _everyLimit2.default,
460 + allSeries: _everySeries2.default,
461 + any: _some2.default,
462 + anyLimit: _someLimit2.default,
463 + anySeries: _someSeries2.default,
464 + find: _detect2.default,
465 + findLimit: _detectLimit2.default,
466 + findSeries: _detectSeries2.default,
467 + flatMap: _concat2.default,
468 + flatMapLimit: _concatLimit2.default,
469 + flatMapSeries: _concatSeries2.default,
470 + forEach: _each2.default,
471 + forEachSeries: _eachSeries2.default,
472 + forEachLimit: _eachLimit2.default,
473 + forEachOf: _eachOf2.default,
474 + forEachOfSeries: _eachOfSeries2.default,
475 + forEachOfLimit: _eachOfLimit2.default,
476 + inject: _reduce2.default,
477 + foldl: _reduce2.default,
478 + foldr: _reduceRight2.default,
479 + select: _filter2.default,
480 + selectLimit: _filterLimit2.default,
481 + selectSeries: _filterSeries2.default,
482 + wrapSync: _asyncify2.default,
483 + during: _whilst2.default,
484 + doDuring: _doWhilst2.default
485 +};
486 +exports.apply = _apply2.default;
487 +exports.applyEach = _applyEach2.default;
488 +exports.applyEachSeries = _applyEachSeries2.default;
489 +exports.asyncify = _asyncify2.default;
490 +exports.auto = _auto2.default;
491 +exports.autoInject = _autoInject2.default;
492 +exports.cargo = _cargo2.default;
493 +exports.cargoQueue = _cargoQueue2.default;
494 +exports.compose = _compose2.default;
495 +exports.concat = _concat2.default;
496 +exports.concatLimit = _concatLimit2.default;
497 +exports.concatSeries = _concatSeries2.default;
498 +exports.constant = _constant2.default;
499 +exports.detect = _detect2.default;
500 +exports.detectLimit = _detectLimit2.default;
501 +exports.detectSeries = _detectSeries2.default;
502 +exports.dir = _dir2.default;
503 +exports.doUntil = _doUntil2.default;
504 +exports.doWhilst = _doWhilst2.default;
505 +exports.each = _each2.default;
506 +exports.eachLimit = _eachLimit2.default;
507 +exports.eachOf = _eachOf2.default;
508 +exports.eachOfLimit = _eachOfLimit2.default;
509 +exports.eachOfSeries = _eachOfSeries2.default;
510 +exports.eachSeries = _eachSeries2.default;
511 +exports.ensureAsync = _ensureAsync2.default;
512 +exports.every = _every2.default;
513 +exports.everyLimit = _everyLimit2.default;
514 +exports.everySeries = _everySeries2.default;
515 +exports.filter = _filter2.default;
516 +exports.filterLimit = _filterLimit2.default;
517 +exports.filterSeries = _filterSeries2.default;
518 +exports.forever = _forever2.default;
519 +exports.groupBy = _groupBy2.default;
520 +exports.groupByLimit = _groupByLimit2.default;
521 +exports.groupBySeries = _groupBySeries2.default;
522 +exports.log = _log2.default;
523 +exports.map = _map2.default;
524 +exports.mapLimit = _mapLimit2.default;
525 +exports.mapSeries = _mapSeries2.default;
526 +exports.mapValues = _mapValues2.default;
527 +exports.mapValuesLimit = _mapValuesLimit2.default;
528 +exports.mapValuesSeries = _mapValuesSeries2.default;
529 +exports.memoize = _memoize2.default;
530 +exports.nextTick = _nextTick2.default;
531 +exports.parallel = _parallel2.default;
532 +exports.parallelLimit = _parallelLimit2.default;
533 +exports.priorityQueue = _priorityQueue2.default;
534 +exports.queue = _queue2.default;
535 +exports.race = _race2.default;
536 +exports.reduce = _reduce2.default;
537 +exports.reduceRight = _reduceRight2.default;
538 +exports.reflect = _reflect2.default;
539 +exports.reflectAll = _reflectAll2.default;
540 +exports.reject = _reject2.default;
541 +exports.rejectLimit = _rejectLimit2.default;
542 +exports.rejectSeries = _rejectSeries2.default;
543 +exports.retry = _retry2.default;
544 +exports.retryable = _retryable2.default;
545 +exports.seq = _seq2.default;
546 +exports.series = _series2.default;
547 +exports.setImmediate = _setImmediate2.default;
548 +exports.some = _some2.default;
549 +exports.someLimit = _someLimit2.default;
550 +exports.someSeries = _someSeries2.default;
551 +exports.sortBy = _sortBy2.default;
552 +exports.timeout = _timeout2.default;
553 +exports.times = _times2.default;
554 +exports.timesLimit = _timesLimit2.default;
555 +exports.timesSeries = _timesSeries2.default;
556 +exports.transform = _transform2.default;
557 +exports.tryEach = _tryEach2.default;
558 +exports.unmemoize = _unmemoize2.default;
559 +exports.until = _until2.default;
560 +exports.waterfall = _waterfall2.default;
561 +exports.whilst = _whilst2.default;
562 +exports.all = _every2.default;
563 +exports.allLimit = _everyLimit2.default;
564 +exports.allSeries = _everySeries2.default;
565 +exports.any = _some2.default;
566 +exports.anyLimit = _someLimit2.default;
567 +exports.anySeries = _someSeries2.default;
568 +exports.find = _detect2.default;
569 +exports.findLimit = _detectLimit2.default;
570 +exports.findSeries = _detectSeries2.default;
571 +exports.flatMap = _concat2.default;
572 +exports.flatMapLimit = _concatLimit2.default;
573 +exports.flatMapSeries = _concatSeries2.default;
574 +exports.forEach = _each2.default;
575 +exports.forEachSeries = _eachSeries2.default;
576 +exports.forEachLimit = _eachLimit2.default;
577 +exports.forEachOf = _eachOf2.default;
578 +exports.forEachOfSeries = _eachOfSeries2.default;
579 +exports.forEachOfLimit = _eachOfLimit2.default;
580 +exports.inject = _reduce2.default;
581 +exports.foldl = _reduce2.default;
582 +exports.foldr = _reduceRight2.default;
583 +exports.select = _filter2.default;
584 +exports.selectLimit = _filterLimit2.default;
585 +exports.selectSeries = _filterSeries2.default;
586 +exports.wrapSync = _asyncify2.default;
587 +exports.during = _whilst2.default;
588 +exports.doDuring = _doWhilst2.default;
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOfSeries = require('./eachOfSeries.js');
8 +
9 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
10 +
11 +var _once = require('./internal/once.js');
12 +
13 +var _once2 = _interopRequireDefault(_once);
14 +
15 +var _wrapAsync = require('./internal/wrapAsync.js');
16 +
17 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
18 +
19 +var _awaitify = require('./internal/awaitify.js');
20 +
21 +var _awaitify2 = _interopRequireDefault(_awaitify);
22 +
23 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24 +
25 +/**
26 + * Reduces `coll` into a single value using an async `iteratee` to return each
27 + * successive step. `memo` is the initial state of the reduction. This function
28 + * only operates in series.
29 + *
30 + * For performance reasons, it may make sense to split a call to this function
31 + * into a parallel map, and then use the normal `Array.prototype.reduce` on the
32 + * results. This function is for situations where each step in the reduction
33 + * needs to be async; if you can get the data before reducing it, then it's
34 + * probably a good idea to do so.
35 + *
36 + * @name reduce
37 + * @static
38 + * @memberOf module:Collections
39 + * @method
40 + * @alias inject
41 + * @alias foldl
42 + * @category Collection
43 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
44 + * @param {*} memo - The initial state of the reduction.
45 + * @param {AsyncFunction} iteratee - A function applied to each item in the
46 + * array to produce the next step in the reduction.
47 + * The `iteratee` should complete with the next state of the reduction.
48 + * If the iteratee completes with an error, the reduction is stopped and the
49 + * main `callback` is immediately called with the error.
50 + * Invoked with (memo, item, callback).
51 + * @param {Function} [callback] - A callback which is called after all the
52 + * `iteratee` functions have finished. Result is the reduced value. Invoked with
53 + * (err, result).
54 + * @returns {Promise} a promise, if no callback is passed
55 + * @example
56 + *
57 + * // file1.txt is a file that is 1000 bytes in size
58 + * // file2.txt is a file that is 2000 bytes in size
59 + * // file3.txt is a file that is 3000 bytes in size
60 + * // file4.txt does not exist
61 + *
62 + * const fileList = ['file1.txt','file2.txt','file3.txt'];
63 + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];
64 + *
65 + * // asynchronous function that computes the file size in bytes
66 + * // file size is added to the memoized value, then returned
67 + * function getFileSizeInBytes(memo, file, callback) {
68 + * fs.stat(file, function(err, stat) {
69 + * if (err) {
70 + * return callback(err);
71 + * }
72 + * callback(null, memo + stat.size);
73 + * });
74 + * }
75 + *
76 + * // Using callbacks
77 + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) {
78 + * if (err) {
79 + * console.log(err);
80 + * } else {
81 + * console.log(result);
82 + * // 6000
83 + * // which is the sum of the file sizes of the three files
84 + * }
85 + * });
86 + *
87 + * // Error Handling
88 + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) {
89 + * if (err) {
90 + * console.log(err);
91 + * // [ Error: ENOENT: no such file or directory ]
92 + * } else {
93 + * console.log(result);
94 + * }
95 + * });
96 + *
97 + * // Using Promises
98 + * async.reduce(fileList, 0, getFileSizeInBytes)
99 + * .then( result => {
100 + * console.log(result);
101 + * // 6000
102 + * // which is the sum of the file sizes of the three files
103 + * }).catch( err => {
104 + * console.log(err);
105 + * });
106 + *
107 + * // Error Handling
108 + * async.reduce(withMissingFileList, 0, getFileSizeInBytes)
109 + * .then( result => {
110 + * console.log(result);
111 + * }).catch( err => {
112 + * console.log(err);
113 + * // [ Error: ENOENT: no such file or directory ]
114 + * });
115 + *
116 + * // Using async/await
117 + * async () => {
118 + * try {
119 + * let result = await async.reduce(fileList, 0, getFileSizeInBytes);
120 + * console.log(result);
121 + * // 6000
122 + * // which is the sum of the file sizes of the three files
123 + * }
124 + * catch (err) {
125 + * console.log(err);
126 + * }
127 + * }
128 + *
129 + * // Error Handling
130 + * async () => {
131 + * try {
132 + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);
133 + * console.log(result);
134 + * }
135 + * catch (err) {
136 + * console.log(err);
137 + * // [ Error: ENOENT: no such file or directory ]
138 + * }
139 + * }
140 + *
141 + */
142 +function reduce(coll, memo, iteratee, callback) {
143 + callback = (0, _once2.default)(callback);
144 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
145 + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => {
146 + _iteratee(memo, x, (err, v) => {
147 + memo = v;
148 + iterCb(err);
149 + });
150 + }, err => callback(err, memo));
151 +}
152 +exports.default = (0, _awaitify2.default)(reduce, 4);
153 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
7 +// used for queues. This implementation assumes that the node provided by the user can be modified
8 +// to adjust the next and last properties. We implement only the minimal functionality
9 +// for queue support.
10 +class DLL {
11 + constructor() {
12 + this.head = this.tail = null;
13 + this.length = 0;
14 + }
15 +
16 + removeLink(node) {
17 + if (node.prev) node.prev.next = node.next;else this.head = node.next;
18 + if (node.next) node.next.prev = node.prev;else this.tail = node.prev;
19 +
20 + node.prev = node.next = null;
21 + this.length -= 1;
22 + return node;
23 + }
24 +
25 + empty() {
26 + while (this.head) this.shift();
27 + return this;
28 + }
29 +
30 + insertAfter(node, newNode) {
31 + newNode.prev = node;
32 + newNode.next = node.next;
33 + if (node.next) node.next.prev = newNode;else this.tail = newNode;
34 + node.next = newNode;
35 + this.length += 1;
36 + }
37 +
38 + insertBefore(node, newNode) {
39 + newNode.prev = node.prev;
40 + newNode.next = node;
41 + if (node.prev) node.prev.next = newNode;else this.head = newNode;
42 + node.prev = newNode;
43 + this.length += 1;
44 + }
45 +
46 + unshift(node) {
47 + if (this.head) this.insertBefore(this.head, node);else setInitial(this, node);
48 + }
49 +
50 + push(node) {
51 + if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node);
52 + }
53 +
54 + shift() {
55 + return this.head && this.removeLink(this.head);
56 + }
57 +
58 + pop() {
59 + return this.tail && this.removeLink(this.tail);
60 + }
61 +
62 + toArray() {
63 + return [...this];
64 + }
65 +
66 + *[Symbol.iterator]() {
67 + var cur = this.head;
68 + while (cur) {
69 + yield cur.data;
70 + cur = cur.next;
71 + }
72 + }
73 +
74 + remove(testFn) {
75 + var curr = this.head;
76 + while (curr) {
77 + var { next } = curr;
78 + if (testFn(curr)) {
79 + this.removeLink(curr);
80 + }
81 + curr = next;
82 + }
83 + return this;
84 + }
85 +}
86 +
87 +exports.default = DLL;
88 +function setInitial(dll, node) {
89 + dll.length = 1;
90 + dll.head = dll.tail = node;
91 +}
92 +module.exports = exports["default"];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +// Binary min-heap implementation used for priority queue.
7 +// Implementation is stable, i.e. push time is considered for equal priorities
8 +class Heap {
9 + constructor() {
10 + this.heap = [];
11 + this.pushCount = Number.MIN_SAFE_INTEGER;
12 + }
13 +
14 + get length() {
15 + return this.heap.length;
16 + }
17 +
18 + empty() {
19 + this.heap = [];
20 + return this;
21 + }
22 +
23 + percUp(index) {
24 + let p;
25 +
26 + while (index > 0 && smaller(this.heap[index], this.heap[p = parent(index)])) {
27 + let t = this.heap[index];
28 + this.heap[index] = this.heap[p];
29 + this.heap[p] = t;
30 +
31 + index = p;
32 + }
33 + }
34 +
35 + percDown(index) {
36 + let l;
37 +
38 + while ((l = leftChi(index)) < this.heap.length) {
39 + if (l + 1 < this.heap.length && smaller(this.heap[l + 1], this.heap[l])) {
40 + l = l + 1;
41 + }
42 +
43 + if (smaller(this.heap[index], this.heap[l])) {
44 + break;
45 + }
46 +
47 + let t = this.heap[index];
48 + this.heap[index] = this.heap[l];
49 + this.heap[l] = t;
50 +
51 + index = l;
52 + }
53 + }
54 +
55 + push(node) {
56 + node.pushCount = ++this.pushCount;
57 + this.heap.push(node);
58 + this.percUp(this.heap.length - 1);
59 + }
60 +
61 + unshift(node) {
62 + return this.heap.push(node);
63 + }
64 +
65 + shift() {
66 + let [top] = this.heap;
67 +
68 + this.heap[0] = this.heap[this.heap.length - 1];
69 + this.heap.pop();
70 + this.percDown(0);
71 +
72 + return top;
73 + }
74 +
75 + toArray() {
76 + return [...this];
77 + }
78 +
79 + *[Symbol.iterator]() {
80 + for (let i = 0; i < this.heap.length; i++) {
81 + yield this.heap[i].data;
82 + }
83 + }
84 +
85 + remove(testFn) {
86 + let j = 0;
87 + for (let i = 0; i < this.heap.length; i++) {
88 + if (!testFn(this.heap[i])) {
89 + this.heap[j] = this.heap[i];
90 + j++;
91 + }
92 + }
93 +
94 + this.heap.splice(j);
95 +
96 + for (let i = parent(this.heap.length - 1); i >= 0; i--) {
97 + this.percDown(i);
98 + }
99 +
100 + return this;
101 + }
102 +}
103 +
104 +exports.default = Heap;
105 +function leftChi(i) {
106 + return (i << 1) + 1;
107 +}
108 +
109 +function parent(i) {
110 + return (i + 1 >> 1) - 1;
111 +}
112 +
113 +function smaller(x, y) {
114 + if (x.priority !== y.priority) {
115 + return x.priority < y.priority;
116 + } else {
117 + return x.pushCount < y.pushCount;
118 + }
119 +}
120 +module.exports = exports["default"];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +exports.default = function (eachfn) {
8 + return function applyEach(fns, ...callArgs) {
9 + const go = (0, _awaitify2.default)(function (callback) {
10 + var that = this;
11 + return eachfn(fns, (fn, cb) => {
12 + (0, _wrapAsync2.default)(fn).apply(that, callArgs.concat(cb));
13 + }, callback);
14 + });
15 + return go;
16 + };
17 +};
18 +
19 +var _wrapAsync = require('./wrapAsync.js');
20 +
21 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
22 +
23 +var _awaitify = require('./awaitify.js');
24 +
25 +var _awaitify2 = _interopRequireDefault(_awaitify);
26 +
27 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
28 +
29 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = asyncEachOfLimit;
7 +
8 +var _breakLoop = require('./breakLoop.js');
9 +
10 +var _breakLoop2 = _interopRequireDefault(_breakLoop);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +// for async generators
15 +function asyncEachOfLimit(generator, limit, iteratee, callback) {
16 + let done = false;
17 + let canceled = false;
18 + let awaiting = false;
19 + let running = 0;
20 + let idx = 0;
21 +
22 + function replenish() {
23 + //console.log('replenish')
24 + if (running >= limit || awaiting || done) return;
25 + //console.log('replenish awaiting')
26 + awaiting = true;
27 + generator.next().then(({ value, done: iterDone }) => {
28 + //console.log('got value', value)
29 + if (canceled || done) return;
30 + awaiting = false;
31 + if (iterDone) {
32 + done = true;
33 + if (running <= 0) {
34 + //console.log('done nextCb')
35 + callback(null);
36 + }
37 + return;
38 + }
39 + running++;
40 + iteratee(value, idx, iterateeCallback);
41 + idx++;
42 + replenish();
43 + }).catch(handleError);
44 + }
45 +
46 + function iterateeCallback(err, result) {
47 + //console.log('iterateeCallback')
48 + running -= 1;
49 + if (canceled) return;
50 + if (err) return handleError(err);
51 +
52 + if (err === false) {
53 + done = true;
54 + canceled = true;
55 + return;
56 + }
57 +
58 + if (result === _breakLoop2.default || done && running <= 0) {
59 + done = true;
60 + //console.log('done iterCb')
61 + return callback(null);
62 + }
63 + replenish();
64 + }
65 +
66 + function handleError(err) {
67 + if (canceled) return;
68 + awaiting = false;
69 + done = true;
70 + callback(err);
71 + }
72 +
73 + replenish();
74 +}
75 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = awaitify;
7 +// conditionally promisify a function.
8 +// only return a promise if a callback is omitted
9 +function awaitify(asyncFn, arity = asyncFn.length) {
10 + if (!arity) throw new Error('arity is undefined');
11 + function awaitable(...args) {
12 + if (typeof args[arity - 1] === 'function') {
13 + return asyncFn.apply(this, args);
14 + }
15 +
16 + return new Promise((resolve, reject) => {
17 + args[arity - 1] = (err, ...cbArgs) => {
18 + if (err) return reject(err);
19 + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
20 + };
21 + asyncFn.apply(this, args);
22 + });
23 + }
24 +
25 + return awaitable;
26 +}
27 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +// A temporary value used to identify if the loop should be broken.
7 +// See #1064, #1293
8 +const breakLoop = {};
9 +exports.default = breakLoop;
10 +module.exports = exports["default"];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = consoleFunc;
7 +
8 +var _wrapAsync = require('./wrapAsync.js');
9 +
10 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +function consoleFunc(name) {
15 + return (fn, ...args) => (0, _wrapAsync2.default)(fn)(...args, (err, ...resultArgs) => {
16 + /* istanbul ignore else */
17 + if (typeof console === 'object') {
18 + /* istanbul ignore else */
19 + if (err) {
20 + /* istanbul ignore else */
21 + if (console.error) {
22 + console.error(err);
23 + }
24 + } else if (console[name]) {
25 + /* istanbul ignore else */
26 + resultArgs.forEach(x => console[name](x));
27 + }
28 + }
29 + });
30 +}
31 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = _createTester;
7 +
8 +var _breakLoop = require('./breakLoop.js');
9 +
10 +var _breakLoop2 = _interopRequireDefault(_breakLoop);
11 +
12 +var _wrapAsync = require('./wrapAsync.js');
13 +
14 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +function _createTester(check, getResult) {
19 + return (eachfn, arr, _iteratee, cb) => {
20 + var testPassed = false;
21 + var testResult;
22 + const iteratee = (0, _wrapAsync2.default)(_iteratee);
23 + eachfn(arr, (value, _, callback) => {
24 + iteratee(value, (err, result) => {
25 + if (err || err === false) return callback(err);
26 +
27 + if (check(result) && !testResult) {
28 + testPassed = true;
29 + testResult = getResult(true, value);
30 + return callback(null, _breakLoop2.default);
31 + }
32 + callback();
33 + });
34 + }, err => {
35 + if (err) return cb(err);
36 + cb(null, testPassed ? testResult : getResult(false));
37 + });
38 + };
39 +}
40 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _once = require('./once.js');
8 +
9 +var _once2 = _interopRequireDefault(_once);
10 +
11 +var _iterator = require('./iterator.js');
12 +
13 +var _iterator2 = _interopRequireDefault(_iterator);
14 +
15 +var _onlyOnce = require('./onlyOnce.js');
16 +
17 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
18 +
19 +var _wrapAsync = require('./wrapAsync.js');
20 +
21 +var _asyncEachOfLimit = require('./asyncEachOfLimit.js');
22 +
23 +var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit);
24 +
25 +var _breakLoop = require('./breakLoop.js');
26 +
27 +var _breakLoop2 = _interopRequireDefault(_breakLoop);
28 +
29 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
30 +
31 +exports.default = limit => {
32 + return (obj, iteratee, callback) => {
33 + callback = (0, _once2.default)(callback);
34 + if (limit <= 0) {
35 + throw new RangeError('concurrency limit cannot be less than 1');
36 + }
37 + if (!obj) {
38 + return callback(null);
39 + }
40 + if ((0, _wrapAsync.isAsyncGenerator)(obj)) {
41 + return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback);
42 + }
43 + if ((0, _wrapAsync.isAsyncIterable)(obj)) {
44 + return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback);
45 + }
46 + var nextElem = (0, _iterator2.default)(obj);
47 + var done = false;
48 + var canceled = false;
49 + var running = 0;
50 + var looping = false;
51 +
52 + function iterateeCallback(err, value) {
53 + if (canceled) return;
54 + running -= 1;
55 + if (err) {
56 + done = true;
57 + callback(err);
58 + } else if (err === false) {
59 + done = true;
60 + canceled = true;
61 + } else if (value === _breakLoop2.default || done && running <= 0) {
62 + done = true;
63 + return callback(null);
64 + } else if (!looping) {
65 + replenish();
66 + }
67 + }
68 +
69 + function replenish() {
70 + looping = true;
71 + while (running < limit && !done) {
72 + var elem = nextElem();
73 + if (elem === null) {
74 + done = true;
75 + if (running <= 0) {
76 + callback(null);
77 + }
78 + return;
79 + }
80 + running += 1;
81 + iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback));
82 + }
83 + looping = false;
84 + }
85 +
86 + replenish();
87 + };
88 +};
89 +
90 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = _filter;
7 +
8 +var _isArrayLike = require('./isArrayLike.js');
9 +
10 +var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
11 +
12 +var _wrapAsync = require('./wrapAsync.js');
13 +
14 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +function filterArray(eachfn, arr, iteratee, callback) {
19 + var truthValues = new Array(arr.length);
20 + eachfn(arr, (x, index, iterCb) => {
21 + iteratee(x, (err, v) => {
22 + truthValues[index] = !!v;
23 + iterCb(err);
24 + });
25 + }, err => {
26 + if (err) return callback(err);
27 + var results = [];
28 + for (var i = 0; i < arr.length; i++) {
29 + if (truthValues[i]) results.push(arr[i]);
30 + }
31 + callback(null, results);
32 + });
33 +}
34 +
35 +function filterGeneric(eachfn, coll, iteratee, callback) {
36 + var results = [];
37 + eachfn(coll, (x, index, iterCb) => {
38 + iteratee(x, (err, v) => {
39 + if (err) return iterCb(err);
40 + if (v) {
41 + results.push({ index, value: x });
42 + }
43 + iterCb(err);
44 + });
45 + }, err => {
46 + if (err) return callback(err);
47 + callback(null, results.sort((a, b) => a.index - b.index).map(v => v.value));
48 + });
49 +}
50 +
51 +function _filter(eachfn, coll, iteratee, callback) {
52 + var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric;
53 + return filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback);
54 +}
55 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +exports.default = function (coll) {
8 + return coll[Symbol.iterator] && coll[Symbol.iterator]();
9 +};
10 +
11 +module.exports = exports["default"];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +exports.default = function (fn) {
8 + return function (...args /*, callback*/) {
9 + var callback = args.pop();
10 + return fn.call(this, args, callback);
11 + };
12 +};
13 +
14 +module.exports = exports["default"];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = isArrayLike;
7 +function isArrayLike(value) {
8 + return value && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0;
9 +}
10 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = createIterator;
7 +
8 +var _isArrayLike = require('./isArrayLike.js');
9 +
10 +var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
11 +
12 +var _getIterator = require('./getIterator.js');
13 +
14 +var _getIterator2 = _interopRequireDefault(_getIterator);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +function createArrayIterator(coll) {
19 + var i = -1;
20 + var len = coll.length;
21 + return function next() {
22 + return ++i < len ? { value: coll[i], key: i } : null;
23 + };
24 +}
25 +
26 +function createES2015Iterator(iterator) {
27 + var i = -1;
28 + return function next() {
29 + var item = iterator.next();
30 + if (item.done) return null;
31 + i++;
32 + return { value: item.value, key: i };
33 + };
34 +}
35 +
36 +function createObjectIterator(obj) {
37 + var okeys = obj ? Object.keys(obj) : [];
38 + var i = -1;
39 + var len = okeys.length;
40 + return function next() {
41 + var key = okeys[++i];
42 + if (key === '__proto__') {
43 + return next();
44 + }
45 + return i < len ? { value: obj[key], key } : null;
46 + };
47 +}
48 +
49 +function createIterator(coll) {
50 + if ((0, _isArrayLike2.default)(coll)) {
51 + return createArrayIterator(coll);
52 + }
53 +
54 + var iterator = (0, _getIterator2.default)(coll);
55 + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
56 +}
57 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = _asyncMap;
7 +
8 +var _wrapAsync = require('./wrapAsync.js');
9 +
10 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +function _asyncMap(eachfn, arr, iteratee, callback) {
15 + arr = arr || [];
16 + var results = [];
17 + var counter = 0;
18 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
19 +
20 + return eachfn(arr, (value, _, iterCb) => {
21 + var index = counter++;
22 + _iteratee(value, (err, v) => {
23 + results[index] = v;
24 + iterCb(err);
25 + });
26 + }, err => {
27 + callback(err, results);
28 + });
29 +}
30 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = once;
7 +function once(fn) {
8 + function wrapper(...args) {
9 + if (fn === null) return;
10 + var callFn = fn;
11 + fn = null;
12 + callFn.apply(this, args);
13 + }
14 + Object.assign(wrapper, fn);
15 + return wrapper;
16 +}
17 +module.exports = exports["default"];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = onlyOnce;
7 +function onlyOnce(fn) {
8 + return function (...args) {
9 + if (fn === null) throw new Error("Callback was already called.");
10 + var callFn = fn;
11 + fn = null;
12 + callFn.apply(this, args);
13 + };
14 +}
15 +module.exports = exports["default"];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _isArrayLike = require('./isArrayLike.js');
8 +
9 +var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
10 +
11 +var _wrapAsync = require('./wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +exports.default = (0, _awaitify2.default)((eachfn, tasks, callback) => {
22 + var results = (0, _isArrayLike2.default)(tasks) ? [] : {};
23 +
24 + eachfn(tasks, (task, key, taskCb) => {
25 + (0, _wrapAsync2.default)(task)((err, ...result) => {
26 + if (result.length < 2) {
27 + [result] = result;
28 + }
29 + results[key] = result;
30 + taskCb(err);
31 + });
32 + }, err => callback(err, results));
33 +}, 3);
34 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +const PROMISE_SYMBOL = Symbol('promiseCallback');
7 +
8 +function promiseCallback() {
9 + let resolve, reject;
10 + function callback(err, ...args) {
11 + if (err) return reject(err);
12 + resolve(args.length > 1 ? args : args[0]);
13 + }
14 +
15 + callback[PROMISE_SYMBOL] = new Promise((res, rej) => {
16 + resolve = res, reject = rej;
17 + });
18 +
19 + return callback;
20 +}
21 +
22 +exports.promiseCallback = promiseCallback;
23 +exports.PROMISE_SYMBOL = PROMISE_SYMBOL;
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = queue;
7 +
8 +var _onlyOnce = require('./onlyOnce.js');
9 +
10 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
11 +
12 +var _setImmediate = require('./setImmediate.js');
13 +
14 +var _setImmediate2 = _interopRequireDefault(_setImmediate);
15 +
16 +var _DoublyLinkedList = require('./DoublyLinkedList.js');
17 +
18 +var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList);
19 +
20 +var _wrapAsync = require('./wrapAsync.js');
21 +
22 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
23 +
24 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
25 +
26 +function queue(worker, concurrency, payload) {
27 + if (concurrency == null) {
28 + concurrency = 1;
29 + } else if (concurrency === 0) {
30 + throw new RangeError('Concurrency must not be zero');
31 + }
32 +
33 + var _worker = (0, _wrapAsync2.default)(worker);
34 + var numRunning = 0;
35 + var workersList = [];
36 + const events = {
37 + error: [],
38 + drain: [],
39 + saturated: [],
40 + unsaturated: [],
41 + empty: []
42 + };
43 +
44 + function on(event, handler) {
45 + events[event].push(handler);
46 + }
47 +
48 + function once(event, handler) {
49 + const handleAndRemove = (...args) => {
50 + off(event, handleAndRemove);
51 + handler(...args);
52 + };
53 + events[event].push(handleAndRemove);
54 + }
55 +
56 + function off(event, handler) {
57 + if (!event) return Object.keys(events).forEach(ev => events[ev] = []);
58 + if (!handler) return events[event] = [];
59 + events[event] = events[event].filter(ev => ev !== handler);
60 + }
61 +
62 + function trigger(event, ...args) {
63 + events[event].forEach(handler => handler(...args));
64 + }
65 +
66 + var processingScheduled = false;
67 + function _insert(data, insertAtFront, rejectOnError, callback) {
68 + if (callback != null && typeof callback !== 'function') {
69 + throw new Error('task callback must be a function');
70 + }
71 + q.started = true;
72 +
73 + var res, rej;
74 + function promiseCallback(err, ...args) {
75 + // we don't care about the error, let the global error handler
76 + // deal with it
77 + if (err) return rejectOnError ? rej(err) : res();
78 + if (args.length <= 1) return res(args[0]);
79 + res(args);
80 + }
81 +
82 + var item = {
83 + data,
84 + callback: rejectOnError ? promiseCallback : callback || promiseCallback
85 + };
86 +
87 + if (insertAtFront) {
88 + q._tasks.unshift(item);
89 + } else {
90 + q._tasks.push(item);
91 + }
92 +
93 + if (!processingScheduled) {
94 + processingScheduled = true;
95 + (0, _setImmediate2.default)(() => {
96 + processingScheduled = false;
97 + q.process();
98 + });
99 + }
100 +
101 + if (rejectOnError || !callback) {
102 + return new Promise((resolve, reject) => {
103 + res = resolve;
104 + rej = reject;
105 + });
106 + }
107 + }
108 +
109 + function _createCB(tasks) {
110 + return function (err, ...args) {
111 + numRunning -= 1;
112 +
113 + for (var i = 0, l = tasks.length; i < l; i++) {
114 + var task = tasks[i];
115 +
116 + var index = workersList.indexOf(task);
117 + if (index === 0) {
118 + workersList.shift();
119 + } else if (index > 0) {
120 + workersList.splice(index, 1);
121 + }
122 +
123 + task.callback(err, ...args);
124 +
125 + if (err != null) {
126 + trigger('error', err, task.data);
127 + }
128 + }
129 +
130 + if (numRunning <= q.concurrency - q.buffer) {
131 + trigger('unsaturated');
132 + }
133 +
134 + if (q.idle()) {
135 + trigger('drain');
136 + }
137 + q.process();
138 + };
139 + }
140 +
141 + function _maybeDrain(data) {
142 + if (data.length === 0 && q.idle()) {
143 + // call drain immediately if there are no tasks
144 + (0, _setImmediate2.default)(() => trigger('drain'));
145 + return true;
146 + }
147 + return false;
148 + }
149 +
150 + const eventMethod = name => handler => {
151 + if (!handler) {
152 + return new Promise((resolve, reject) => {
153 + once(name, (err, data) => {
154 + if (err) return reject(err);
155 + resolve(data);
156 + });
157 + });
158 + }
159 + off(name);
160 + on(name, handler);
161 + };
162 +
163 + var isProcessing = false;
164 + var q = {
165 + _tasks: new _DoublyLinkedList2.default(),
166 + *[Symbol.iterator]() {
167 + yield* q._tasks[Symbol.iterator]();
168 + },
169 + concurrency,
170 + payload,
171 + buffer: concurrency / 4,
172 + started: false,
173 + paused: false,
174 + push(data, callback) {
175 + if (Array.isArray(data)) {
176 + if (_maybeDrain(data)) return;
177 + return data.map(datum => _insert(datum, false, false, callback));
178 + }
179 + return _insert(data, false, false, callback);
180 + },
181 + pushAsync(data, callback) {
182 + if (Array.isArray(data)) {
183 + if (_maybeDrain(data)) return;
184 + return data.map(datum => _insert(datum, false, true, callback));
185 + }
186 + return _insert(data, false, true, callback);
187 + },
188 + kill() {
189 + off();
190 + q._tasks.empty();
191 + },
192 + unshift(data, callback) {
193 + if (Array.isArray(data)) {
194 + if (_maybeDrain(data)) return;
195 + return data.map(datum => _insert(datum, true, false, callback));
196 + }
197 + return _insert(data, true, false, callback);
198 + },
199 + unshiftAsync(data, callback) {
200 + if (Array.isArray(data)) {
201 + if (_maybeDrain(data)) return;
202 + return data.map(datum => _insert(datum, true, true, callback));
203 + }
204 + return _insert(data, true, true, callback);
205 + },
206 + remove(testFn) {
207 + q._tasks.remove(testFn);
208 + },
209 + process() {
210 + // Avoid trying to start too many processing operations. This can occur
211 + // when callbacks resolve synchronously (#1267).
212 + if (isProcessing) {
213 + return;
214 + }
215 + isProcessing = true;
216 + while (!q.paused && numRunning < q.concurrency && q._tasks.length) {
217 + var tasks = [],
218 + data = [];
219 + var l = q._tasks.length;
220 + if (q.payload) l = Math.min(l, q.payload);
221 + for (var i = 0; i < l; i++) {
222 + var node = q._tasks.shift();
223 + tasks.push(node);
224 + workersList.push(node);
225 + data.push(node.data);
226 + }
227 +
228 + numRunning += 1;
229 +
230 + if (q._tasks.length === 0) {
231 + trigger('empty');
232 + }
233 +
234 + if (numRunning === q.concurrency) {
235 + trigger('saturated');
236 + }
237 +
238 + var cb = (0, _onlyOnce2.default)(_createCB(tasks));
239 + _worker(data, cb);
240 + }
241 + isProcessing = false;
242 + },
243 + length() {
244 + return q._tasks.length;
245 + },
246 + running() {
247 + return numRunning;
248 + },
249 + workersList() {
250 + return workersList;
251 + },
252 + idle() {
253 + return q._tasks.length + numRunning === 0;
254 + },
255 + pause() {
256 + q.paused = true;
257 + },
258 + resume() {
259 + if (q.paused === false) {
260 + return;
261 + }
262 + q.paused = false;
263 + (0, _setImmediate2.default)(q.process);
264 + }
265 + };
266 + // define these as fixed properties, so people get useful errors when updating
267 + Object.defineProperties(q, {
268 + saturated: {
269 + writable: false,
270 + value: eventMethod('saturated')
271 + },
272 + unsaturated: {
273 + writable: false,
274 + value: eventMethod('unsaturated')
275 + },
276 + empty: {
277 + writable: false,
278 + value: eventMethod('empty')
279 + },
280 + drain: {
281 + writable: false,
282 + value: eventMethod('drain')
283 + },
284 + error: {
285 + writable: false,
286 + value: eventMethod('error')
287 + }
288 + });
289 + return q;
290 +}
291 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = range;
7 +function range(size) {
8 + var result = Array(size);
9 + while (size--) {
10 + result[size] = size;
11 + }
12 + return result;
13 +}
14 +module.exports = exports["default"];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = reject;
7 +
8 +var _filter = require('./filter.js');
9 +
10 +var _filter2 = _interopRequireDefault(_filter);
11 +
12 +var _wrapAsync = require('./wrapAsync.js');
13 +
14 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +function reject(eachfn, arr, _iteratee, callback) {
19 + const iteratee = (0, _wrapAsync2.default)(_iteratee);
20 + return (0, _filter2.default)(eachfn, arr, (value, cb) => {
21 + iteratee(value, (err, v) => {
22 + cb(err, !v);
23 + });
24 + }, callback);
25 +}
26 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.fallback = fallback;
7 +exports.wrap = wrap;
8 +/* istanbul ignore file */
9 +
10 +var hasQueueMicrotask = exports.hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;
11 +var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
12 +var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
13 +
14 +function fallback(fn) {
15 + setTimeout(fn, 0);
16 +}
17 +
18 +function wrap(defer) {
19 + return (fn, ...args) => defer(() => fn(...args));
20 +}
21 +
22 +var _defer;
23 +
24 +if (hasQueueMicrotask) {
25 + _defer = queueMicrotask;
26 +} else if (hasSetImmediate) {
27 + _defer = setImmediate;
28 +} else if (hasNextTick) {
29 + _defer = process.nextTick;
30 +} else {
31 + _defer = fallback;
32 +}
33 +
34 +exports.default = wrap(_defer);
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = _withoutIndex;
7 +function _withoutIndex(iteratee) {
8 + return (value, index, callback) => iteratee(value, callback);
9 +}
10 +module.exports = exports["default"];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.isAsyncIterable = exports.isAsyncGenerator = exports.isAsync = undefined;
7 +
8 +var _asyncify = require('../asyncify.js');
9 +
10 +var _asyncify2 = _interopRequireDefault(_asyncify);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +function isAsync(fn) {
15 + return fn[Symbol.toStringTag] === 'AsyncFunction';
16 +}
17 +
18 +function isAsyncGenerator(fn) {
19 + return fn[Symbol.toStringTag] === 'AsyncGenerator';
20 +}
21 +
22 +function isAsyncIterable(obj) {
23 + return typeof obj[Symbol.asyncIterator] === 'function';
24 +}
25 +
26 +function wrapAsync(asyncFn) {
27 + if (typeof asyncFn !== 'function') throw new Error('expected a function');
28 + return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn;
29 +}
30 +
31 +exports.default = wrapAsync;
32 +exports.isAsync = isAsync;
33 +exports.isAsyncGenerator = isAsyncGenerator;
34 +exports.isAsyncIterable = isAsyncIterable;
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _consoleFunc = require('./internal/consoleFunc.js');
8 +
9 +var _consoleFunc2 = _interopRequireDefault(_consoleFunc);
10 +
11 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12 +
13 +/**
14 + * Logs the result of an `async` function to the `console`. Only works in
15 + * Node.js or in browsers that support `console.log` and `console.error` (such
16 + * as FF and Chrome). If multiple arguments are returned from the async
17 + * function, `console.log` is called on each argument in order.
18 + *
19 + * @name log
20 + * @static
21 + * @memberOf module:Utils
22 + * @method
23 + * @category Util
24 + * @param {AsyncFunction} function - The function you want to eventually apply
25 + * all arguments to.
26 + * @param {...*} arguments... - Any number of arguments to apply to the function.
27 + * @example
28 + *
29 + * // in a module
30 + * var hello = function(name, callback) {
31 + * setTimeout(function() {
32 + * callback(null, 'hello ' + name);
33 + * }, 1000);
34 + * };
35 + *
36 + * // in the node repl
37 + * node> async.log(hello, 'world');
38 + * 'hello world'
39 + */
40 +exports.default = (0, _consoleFunc2.default)('log');
41 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _map2 = require('./internal/map.js');
8 +
9 +var _map3 = _interopRequireDefault(_map2);
10 +
11 +var _eachOf = require('./eachOf.js');
12 +
13 +var _eachOf2 = _interopRequireDefault(_eachOf);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Produces a new collection of values by mapping each value in `coll` through
23 + * the `iteratee` function. The `iteratee` is called with an item from `coll`
24 + * and a callback for when it has finished processing. Each of these callbacks
25 + * takes 2 arguments: an `error`, and the transformed item from `coll`. If
26 + * `iteratee` passes an error to its callback, the main `callback` (for the
27 + * `map` function) is immediately called with the error.
28 + *
29 + * Note, that since this function applies the `iteratee` to each item in
30 + * parallel, there is no guarantee that the `iteratee` functions will complete
31 + * in order. However, the results array will be in the same order as the
32 + * original `coll`.
33 + *
34 + * If `map` is passed an Object, the results will be an Array. The results
35 + * will roughly be in the order of the original Objects' keys (but this can
36 + * vary across JavaScript engines).
37 + *
38 + * @name map
39 + * @static
40 + * @memberOf module:Collections
41 + * @method
42 + * @category Collection
43 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
44 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
45 + * `coll`.
46 + * The iteratee should complete with the transformed item.
47 + * Invoked with (item, callback).
48 + * @param {Function} [callback] - A callback which is called when all `iteratee`
49 + * functions have finished, or an error occurs. Results is an Array of the
50 + * transformed items from the `coll`. Invoked with (err, results).
51 + * @returns {Promise} a promise, if no callback is passed
52 + * @example
53 + *
54 + * // file1.txt is a file that is 1000 bytes in size
55 + * // file2.txt is a file that is 2000 bytes in size
56 + * // file3.txt is a file that is 3000 bytes in size
57 + * // file4.txt does not exist
58 + *
59 + * const fileList = ['file1.txt','file2.txt','file3.txt'];
60 + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];
61 + *
62 + * // asynchronous function that returns the file size in bytes
63 + * function getFileSizeInBytes(file, callback) {
64 + * fs.stat(file, function(err, stat) {
65 + * if (err) {
66 + * return callback(err);
67 + * }
68 + * callback(null, stat.size);
69 + * });
70 + * }
71 + *
72 + * // Using callbacks
73 + * async.map(fileList, getFileSizeInBytes, function(err, results) {
74 + * if (err) {
75 + * console.log(err);
76 + * } else {
77 + * console.log(results);
78 + * // results is now an array of the file size in bytes for each file, e.g.
79 + * // [ 1000, 2000, 3000]
80 + * }
81 + * });
82 + *
83 + * // Error Handling
84 + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {
85 + * if (err) {
86 + * console.log(err);
87 + * // [ Error: ENOENT: no such file or directory ]
88 + * } else {
89 + * console.log(results);
90 + * }
91 + * });
92 + *
93 + * // Using Promises
94 + * async.map(fileList, getFileSizeInBytes)
95 + * .then( results => {
96 + * console.log(results);
97 + * // results is now an array of the file size in bytes for each file, e.g.
98 + * // [ 1000, 2000, 3000]
99 + * }).catch( err => {
100 + * console.log(err);
101 + * });
102 + *
103 + * // Error Handling
104 + * async.map(withMissingFileList, getFileSizeInBytes)
105 + * .then( results => {
106 + * console.log(results);
107 + * }).catch( err => {
108 + * console.log(err);
109 + * // [ Error: ENOENT: no such file or directory ]
110 + * });
111 + *
112 + * // Using async/await
113 + * async () => {
114 + * try {
115 + * let results = await async.map(fileList, getFileSizeInBytes);
116 + * console.log(results);
117 + * // results is now an array of the file size in bytes for each file, e.g.
118 + * // [ 1000, 2000, 3000]
119 + * }
120 + * catch (err) {
121 + * console.log(err);
122 + * }
123 + * }
124 + *
125 + * // Error Handling
126 + * async () => {
127 + * try {
128 + * let results = await async.map(withMissingFileList, getFileSizeInBytes);
129 + * console.log(results);
130 + * }
131 + * catch (err) {
132 + * console.log(err);
133 + * // [ Error: ENOENT: no such file or directory ]
134 + * }
135 + * }
136 + *
137 + */
138 +function map(coll, iteratee, callback) {
139 + return (0, _map3.default)(_eachOf2.default, coll, iteratee, callback);
140 +}
141 +exports.default = (0, _awaitify2.default)(map, 3);
142 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _map2 = require('./internal/map.js');
8 +
9 +var _map3 = _interopRequireDefault(_map2);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.
23 + *
24 + * @name mapLimit
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.map]{@link module:Collections.map}
29 + * @category Collection
30 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
31 + * @param {number} limit - The maximum number of async operations at a time.
32 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
33 + * `coll`.
34 + * The iteratee should complete with the transformed item.
35 + * Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called when all `iteratee`
37 + * functions have finished, or an error occurs. Results is an array of the
38 + * transformed items from the `coll`. Invoked with (err, results).
39 + * @returns {Promise} a promise, if no callback is passed
40 + */
41 +function mapLimit(coll, limit, iteratee, callback) {
42 + return (0, _map3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
43 +}
44 +exports.default = (0, _awaitify2.default)(mapLimit, 4);
45 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _map2 = require('./internal/map.js');
8 +
9 +var _map3 = _interopRequireDefault(_map2);
10 +
11 +var _eachOfSeries = require('./eachOfSeries.js');
12 +
13 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.
23 + *
24 + * @name mapSeries
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.map]{@link module:Collections.map}
29 + * @category Collection
30 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
31 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
32 + * `coll`.
33 + * The iteratee should complete with the transformed item.
34 + * Invoked with (item, callback).
35 + * @param {Function} [callback] - A callback which is called when all `iteratee`
36 + * functions have finished, or an error occurs. Results is an array of the
37 + * transformed items from the `coll`. Invoked with (err, results).
38 + * @returns {Promise} a promise, if no callback is passed
39 + */
40 +function mapSeries(coll, iteratee, callback) {
41 + return (0, _map3.default)(_eachOfSeries2.default, coll, iteratee, callback);
42 +}
43 +exports.default = (0, _awaitify2.default)(mapSeries, 3);
44 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = mapValues;
7 +
8 +var _mapValuesLimit = require('./mapValuesLimit.js');
9 +
10 +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.
16 + *
17 + * Produces a new Object by mapping each value of `obj` through the `iteratee`
18 + * function. The `iteratee` is called each `value` and `key` from `obj` and a
19 + * callback for when it has finished processing. Each of these callbacks takes
20 + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`
21 + * passes an error to its callback, the main `callback` (for the `mapValues`
22 + * function) is immediately called with the error.
23 + *
24 + * Note, the order of the keys in the result is not guaranteed. The keys will
25 + * be roughly in the order they complete, (but this is very engine-specific)
26 + *
27 + * @name mapValues
28 + * @static
29 + * @memberOf module:Collections
30 + * @method
31 + * @category Collection
32 + * @param {Object} obj - A collection to iterate over.
33 + * @param {AsyncFunction} iteratee - A function to apply to each value and key
34 + * in `coll`.
35 + * The iteratee should complete with the transformed value as its result.
36 + * Invoked with (value, key, callback).
37 + * @param {Function} [callback] - A callback which is called when all `iteratee`
38 + * functions have finished, or an error occurs. `result` is a new object consisting
39 + * of each key from `obj`, with each transformed value on the right-hand side.
40 + * Invoked with (err, result).
41 + * @returns {Promise} a promise, if no callback is passed
42 + * @example
43 + *
44 + * // file1.txt is a file that is 1000 bytes in size
45 + * // file2.txt is a file that is 2000 bytes in size
46 + * // file3.txt is a file that is 3000 bytes in size
47 + * // file4.txt does not exist
48 + *
49 + * const fileMap = {
50 + * f1: 'file1.txt',
51 + * f2: 'file2.txt',
52 + * f3: 'file3.txt'
53 + * };
54 + *
55 + * const withMissingFileMap = {
56 + * f1: 'file1.txt',
57 + * f2: 'file2.txt',
58 + * f3: 'file4.txt'
59 + * };
60 + *
61 + * // asynchronous function that returns the file size in bytes
62 + * function getFileSizeInBytes(file, key, callback) {
63 + * fs.stat(file, function(err, stat) {
64 + * if (err) {
65 + * return callback(err);
66 + * }
67 + * callback(null, stat.size);
68 + * });
69 + * }
70 + *
71 + * // Using callbacks
72 + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) {
73 + * if (err) {
74 + * console.log(err);
75 + * } else {
76 + * console.log(result);
77 + * // result is now a map of file size in bytes for each file, e.g.
78 + * // {
79 + * // f1: 1000,
80 + * // f2: 2000,
81 + * // f3: 3000
82 + * // }
83 + * }
84 + * });
85 + *
86 + * // Error handling
87 + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) {
88 + * if (err) {
89 + * console.log(err);
90 + * // [ Error: ENOENT: no such file or directory ]
91 + * } else {
92 + * console.log(result);
93 + * }
94 + * });
95 + *
96 + * // Using Promises
97 + * async.mapValues(fileMap, getFileSizeInBytes)
98 + * .then( result => {
99 + * console.log(result);
100 + * // result is now a map of file size in bytes for each file, e.g.
101 + * // {
102 + * // f1: 1000,
103 + * // f2: 2000,
104 + * // f3: 3000
105 + * // }
106 + * }).catch (err => {
107 + * console.log(err);
108 + * });
109 + *
110 + * // Error Handling
111 + * async.mapValues(withMissingFileMap, getFileSizeInBytes)
112 + * .then( result => {
113 + * console.log(result);
114 + * }).catch (err => {
115 + * console.log(err);
116 + * // [ Error: ENOENT: no such file or directory ]
117 + * });
118 + *
119 + * // Using async/await
120 + * async () => {
121 + * try {
122 + * let result = await async.mapValues(fileMap, getFileSizeInBytes);
123 + * console.log(result);
124 + * // result is now a map of file size in bytes for each file, e.g.
125 + * // {
126 + * // f1: 1000,
127 + * // f2: 2000,
128 + * // f3: 3000
129 + * // }
130 + * }
131 + * catch (err) {
132 + * console.log(err);
133 + * }
134 + * }
135 + *
136 + * // Error Handling
137 + * async () => {
138 + * try {
139 + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes);
140 + * console.log(result);
141 + * }
142 + * catch (err) {
143 + * console.log(err);
144 + * // [ Error: ENOENT: no such file or directory ]
145 + * }
146 + * }
147 + *
148 + */
149 +function mapValues(obj, iteratee, callback) {
150 + return (0, _mapValuesLimit2.default)(obj, Infinity, iteratee, callback);
151 +}
152 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOfLimit = require('./internal/eachOfLimit.js');
8 +
9 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
10 +
11 +var _awaitify = require('./internal/awaitify.js');
12 +
13 +var _awaitify2 = _interopRequireDefault(_awaitify);
14 +
15 +var _once = require('./internal/once.js');
16 +
17 +var _once2 = _interopRequireDefault(_once);
18 +
19 +var _wrapAsync = require('./internal/wrapAsync.js');
20 +
21 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
22 +
23 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24 +
25 +/**
26 + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a
27 + * time.
28 + *
29 + * @name mapValuesLimit
30 + * @static
31 + * @memberOf module:Collections
32 + * @method
33 + * @see [async.mapValues]{@link module:Collections.mapValues}
34 + * @category Collection
35 + * @param {Object} obj - A collection to iterate over.
36 + * @param {number} limit - The maximum number of async operations at a time.
37 + * @param {AsyncFunction} iteratee - A function to apply to each value and key
38 + * in `coll`.
39 + * The iteratee should complete with the transformed value as its result.
40 + * Invoked with (value, key, callback).
41 + * @param {Function} [callback] - A callback which is called when all `iteratee`
42 + * functions have finished, or an error occurs. `result` is a new object consisting
43 + * of each key from `obj`, with each transformed value on the right-hand side.
44 + * Invoked with (err, result).
45 + * @returns {Promise} a promise, if no callback is passed
46 + */
47 +function mapValuesLimit(obj, limit, iteratee, callback) {
48 + callback = (0, _once2.default)(callback);
49 + var newObj = {};
50 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
51 + return (0, _eachOfLimit2.default)(limit)(obj, (val, key, next) => {
52 + _iteratee(val, key, (err, result) => {
53 + if (err) return next(err);
54 + newObj[key] = result;
55 + next(err);
56 + });
57 + }, err => callback(err, newObj));
58 +}
59 +
60 +exports.default = (0, _awaitify2.default)(mapValuesLimit, 4);
61 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = mapValuesSeries;
7 +
8 +var _mapValuesLimit = require('./mapValuesLimit.js');
9 +
10 +var _mapValuesLimit2 = _interopRequireDefault(_mapValuesLimit);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.
16 + *
17 + * @name mapValuesSeries
18 + * @static
19 + * @memberOf module:Collections
20 + * @method
21 + * @see [async.mapValues]{@link module:Collections.mapValues}
22 + * @category Collection
23 + * @param {Object} obj - A collection to iterate over.
24 + * @param {AsyncFunction} iteratee - A function to apply to each value and key
25 + * in `coll`.
26 + * The iteratee should complete with the transformed value as its result.
27 + * Invoked with (value, key, callback).
28 + * @param {Function} [callback] - A callback which is called when all `iteratee`
29 + * functions have finished, or an error occurs. `result` is a new object consisting
30 + * of each key from `obj`, with each transformed value on the right-hand side.
31 + * Invoked with (err, result).
32 + * @returns {Promise} a promise, if no callback is passed
33 + */
34 +function mapValuesSeries(obj, iteratee, callback) {
35 + return (0, _mapValuesLimit2.default)(obj, 1, iteratee, callback);
36 +}
37 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = memoize;
7 +
8 +var _setImmediate = require('./internal/setImmediate.js');
9 +
10 +var _setImmediate2 = _interopRequireDefault(_setImmediate);
11 +
12 +var _initialParams = require('./internal/initialParams.js');
13 +
14 +var _initialParams2 = _interopRequireDefault(_initialParams);
15 +
16 +var _wrapAsync = require('./internal/wrapAsync.js');
17 +
18 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
19 +
20 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21 +
22 +/**
23 + * Caches the results of an async function. When creating a hash to store
24 + * function results against, the callback is omitted from the hash and an
25 + * optional hash function can be used.
26 + *
27 + * **Note: if the async function errs, the result will not be cached and
28 + * subsequent calls will call the wrapped function.**
29 + *
30 + * If no hash function is specified, the first argument is used as a hash key,
31 + * which may work reasonably if it is a string or a data type that converts to a
32 + * distinct string. Note that objects and arrays will not behave reasonably.
33 + * Neither will cases where the other arguments are significant. In such cases,
34 + * specify your own hash function.
35 + *
36 + * The cache of results is exposed as the `memo` property of the function
37 + * returned by `memoize`.
38 + *
39 + * @name memoize
40 + * @static
41 + * @memberOf module:Utils
42 + * @method
43 + * @category Util
44 + * @param {AsyncFunction} fn - The async function to proxy and cache results from.
45 + * @param {Function} hasher - An optional function for generating a custom hash
46 + * for storing results. It has all the arguments applied to it apart from the
47 + * callback, and must be synchronous.
48 + * @returns {AsyncFunction} a memoized version of `fn`
49 + * @example
50 + *
51 + * var slow_fn = function(name, callback) {
52 + * // do something
53 + * callback(null, result);
54 + * };
55 + * var fn = async.memoize(slow_fn);
56 + *
57 + * // fn can now be used as if it were slow_fn
58 + * fn('some name', function() {
59 + * // callback
60 + * });
61 + */
62 +function memoize(fn, hasher = v => v) {
63 + var memo = Object.create(null);
64 + var queues = Object.create(null);
65 + var _fn = (0, _wrapAsync2.default)(fn);
66 + var memoized = (0, _initialParams2.default)((args, callback) => {
67 + var key = hasher(...args);
68 + if (key in memo) {
69 + (0, _setImmediate2.default)(() => callback(null, ...memo[key]));
70 + } else if (key in queues) {
71 + queues[key].push(callback);
72 + } else {
73 + queues[key] = [callback];
74 + _fn(...args, (err, ...resultArgs) => {
75 + // #1465 don't memoize if an error occurred
76 + if (!err) {
77 + memo[key] = resultArgs;
78 + }
79 + var q = queues[key];
80 + delete queues[key];
81 + for (var i = 0, l = q.length; i < l; i++) {
82 + q[i](err, ...resultArgs);
83 + }
84 + });
85 + }
86 + });
87 + memoized.memo = memo;
88 + memoized.unmemoized = fn;
89 + return memoized;
90 +}
91 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _setImmediate = require('./internal/setImmediate.js');
8 +
9 +/**
10 + * Calls `callback` on a later loop around the event loop. In Node.js this just
11 + * calls `process.nextTick`. In the browser it will use `setImmediate` if
12 + * available, otherwise `setTimeout(callback, 0)`, which means other higher
13 + * priority events may precede the execution of `callback`.
14 + *
15 + * This is used internally for browser-compatibility purposes.
16 + *
17 + * @name nextTick
18 + * @static
19 + * @memberOf module:Utils
20 + * @method
21 + * @see [async.setImmediate]{@link module:Utils.setImmediate}
22 + * @category Util
23 + * @param {Function} callback - The function to call on a later loop around
24 + * the event loop. Invoked with (args...).
25 + * @param {...*} args... - any number of additional arguments to pass to the
26 + * callback on the next tick.
27 + * @example
28 + *
29 + * var call_order = [];
30 + * async.nextTick(function() {
31 + * call_order.push('two');
32 + * // call_order now equals ['one','two']
33 + * });
34 + * call_order.push('one');
35 + *
36 + * async.setImmediate(function (a, b, c) {
37 + * // a, b, and c equal 1, 2, and 3
38 + * }, 1, 2, 3);
39 + */
40 +var _defer; /* istanbul ignore file */
41 +
42 +
43 +if (_setImmediate.hasNextTick) {
44 + _defer = process.nextTick;
45 +} else if (_setImmediate.hasSetImmediate) {
46 + _defer = setImmediate;
47 +} else {
48 + _defer = _setImmediate.fallback;
49 +}
50 +
51 +exports.default = (0, _setImmediate.wrap)(_defer);
52 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "_from": "async@^3.2.3",
3 + "_id": "async@3.2.3",
4 + "_inBundle": false,
5 + "_integrity": "sha512-spZRyzKL5l5BZQrr/6m/SqFdBN0q3OCI0f9rjfBzCMBIP4p75P620rR3gTmaksNOhmzgdxcaxdNfMy6anrbM0g==",
6 + "_location": "/async",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "async@^3.2.3",
12 + "name": "async",
13 + "escapedName": "async",
14 + "rawSpec": "^3.2.3",
15 + "saveSpec": null,
16 + "fetchSpec": "^3.2.3"
17 + },
18 + "_requiredBy": [
19 + "/jake"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/async/-/async-3.2.3.tgz",
22 + "_shasum": "ac53dafd3f4720ee9e8a160628f18ea91df196c9",
23 + "_spec": "async@^3.2.3",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\jake",
25 + "author": {
26 + "name": "Caolan McMahon"
27 + },
28 + "bugs": {
29 + "url": "https://github.com/caolan/async/issues"
30 + },
31 + "bundleDependencies": false,
32 + "deprecated": false,
33 + "description": "Higher-order functions and common patterns for asynchronous code",
34 + "devDependencies": {
35 + "babel-core": "^6.26.3",
36 + "babel-eslint": "^8.2.6",
37 + "babel-minify": "^0.5.0",
38 + "babel-plugin-add-module-exports": "^0.2.1",
39 + "babel-plugin-istanbul": "^5.1.4",
40 + "babel-plugin-syntax-async-generators": "^6.13.0",
41 + "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
42 + "babel-preset-es2015": "^6.3.13",
43 + "babel-preset-es2017": "^6.22.0",
44 + "babel-register": "^6.26.0",
45 + "babelify": "^8.0.0",
46 + "benchmark": "^2.1.1",
47 + "bluebird": "^3.4.6",
48 + "browserify": "^16.2.3",
49 + "chai": "^4.2.0",
50 + "cheerio": "^0.22.0",
51 + "coveralls": "^3.0.4",
52 + "es6-promise": "^2.3.0",
53 + "eslint": "^6.0.1",
54 + "eslint-plugin-prefer-arrow": "^1.1.5",
55 + "fs-extra": "^0.26.7",
56 + "jsdoc": "^3.6.2",
57 + "karma": "^4.1.0",
58 + "karma-browserify": "^5.3.0",
59 + "karma-edge-launcher": "^0.4.2",
60 + "karma-firefox-launcher": "^1.1.0",
61 + "karma-junit-reporter": "^1.2.0",
62 + "karma-mocha": "^1.2.0",
63 + "karma-mocha-reporter": "^2.2.0",
64 + "karma-safari-launcher": "^1.0.0",
65 + "mocha": "^6.1.4",
66 + "mocha-junit-reporter": "^1.18.0",
67 + "native-promise-only": "^0.8.0-a",
68 + "nyc": "^14.1.1",
69 + "rollup": "^0.63.4",
70 + "rollup-plugin-node-resolve": "^2.0.0",
71 + "rollup-plugin-npm": "^2.0.0",
72 + "rsvp": "^3.0.18",
73 + "semver": "^5.5.0",
74 + "yargs": "^11.0.0"
75 + },
76 + "homepage": "https://caolan.github.io/async/",
77 + "keywords": [
78 + "async",
79 + "callback",
80 + "module",
81 + "utility"
82 + ],
83 + "license": "MIT",
84 + "main": "dist/async.js",
85 + "module": "dist/async.mjs",
86 + "name": "async",
87 + "nyc": {
88 + "exclude": [
89 + "test"
90 + ]
91 + },
92 + "repository": {
93 + "type": "git",
94 + "url": "git+https://github.com/caolan/async.git"
95 + },
96 + "scripts": {
97 + "coverage": "nyc npm run mocha-node-test -- --grep @nycinvalid --invert",
98 + "coveralls": "npm run coverage && nyc report --reporter=text-lcov | coveralls",
99 + "jsdoc": "jsdoc -c ./support/jsdoc/jsdoc.json && node support/jsdoc/jsdoc-fix-html.js",
100 + "lint": "eslint --fix lib/ test/ perf/memory.js perf/suites.js perf/benchmark.js support/build/ support/*.js karma.conf.js",
101 + "mocha-browser-test": "karma start",
102 + "mocha-node-test": "mocha",
103 + "mocha-test": "npm run mocha-node-test && npm run mocha-browser-test",
104 + "test": "npm run lint && npm run mocha-node-test"
105 + },
106 + "version": "3.2.3"
107 +}
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = parallel;
7 +
8 +var _eachOf = require('./eachOf.js');
9 +
10 +var _eachOf2 = _interopRequireDefault(_eachOf);
11 +
12 +var _parallel2 = require('./internal/parallel.js');
13 +
14 +var _parallel3 = _interopRequireDefault(_parallel2);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +/**
19 + * Run the `tasks` collection of functions in parallel, without waiting until
20 + * the previous function has completed. If any of the functions pass an error to
21 + * its callback, the main `callback` is immediately called with the value of the
22 + * error. Once the `tasks` have completed, the results are passed to the final
23 + * `callback` as an array.
24 + *
25 + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
26 + * parallel execution of code. If your tasks do not use any timers or perform
27 + * any I/O, they will actually be executed in series. Any synchronous setup
28 + * sections for each task will happen one after the other. JavaScript remains
29 + * single-threaded.
30 + *
31 + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the
32 + * execution of other tasks when a task fails.
33 + *
34 + * It is also possible to use an object instead of an array. Each property will
35 + * be run as a function and the results will be passed to the final `callback`
36 + * as an object instead of an array. This can be a more readable way of handling
37 + * results from {@link async.parallel}.
38 + *
39 + * @name parallel
40 + * @static
41 + * @memberOf module:ControlFlow
42 + * @method
43 + * @category Control Flow
44 + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of
45 + * [async functions]{@link AsyncFunction} to run.
46 + * Each async function can complete with any number of optional `result` values.
47 + * @param {Function} [callback] - An optional callback to run once all the
48 + * functions have completed successfully. This function gets a results array
49 + * (or object) containing all the result arguments passed to the task callbacks.
50 + * Invoked with (err, results).
51 + * @returns {Promise} a promise, if a callback is not passed
52 + *
53 + * @example
54 + *
55 + * //Using Callbacks
56 + * async.parallel([
57 + * function(callback) {
58 + * setTimeout(function() {
59 + * callback(null, 'one');
60 + * }, 200);
61 + * },
62 + * function(callback) {
63 + * setTimeout(function() {
64 + * callback(null, 'two');
65 + * }, 100);
66 + * }
67 + * ], function(err, results) {
68 + * console.log(results);
69 + * // results is equal to ['one','two'] even though
70 + * // the second function had a shorter timeout.
71 + * });
72 + *
73 + * // an example using an object instead of an array
74 + * async.parallel({
75 + * one: function(callback) {
76 + * setTimeout(function() {
77 + * callback(null, 1);
78 + * }, 200);
79 + * },
80 + * two: function(callback) {
81 + * setTimeout(function() {
82 + * callback(null, 2);
83 + * }, 100);
84 + * }
85 + * }, function(err, results) {
86 + * console.log(results);
87 + * // results is equal to: { one: 1, two: 2 }
88 + * });
89 + *
90 + * //Using Promises
91 + * async.parallel([
92 + * function(callback) {
93 + * setTimeout(function() {
94 + * callback(null, 'one');
95 + * }, 200);
96 + * },
97 + * function(callback) {
98 + * setTimeout(function() {
99 + * callback(null, 'two');
100 + * }, 100);
101 + * }
102 + * ]).then(results => {
103 + * console.log(results);
104 + * // results is equal to ['one','two'] even though
105 + * // the second function had a shorter timeout.
106 + * }).catch(err => {
107 + * console.log(err);
108 + * });
109 + *
110 + * // an example using an object instead of an array
111 + * async.parallel({
112 + * one: function(callback) {
113 + * setTimeout(function() {
114 + * callback(null, 1);
115 + * }, 200);
116 + * },
117 + * two: function(callback) {
118 + * setTimeout(function() {
119 + * callback(null, 2);
120 + * }, 100);
121 + * }
122 + * }).then(results => {
123 + * console.log(results);
124 + * // results is equal to: { one: 1, two: 2 }
125 + * }).catch(err => {
126 + * console.log(err);
127 + * });
128 + *
129 + * //Using async/await
130 + * async () => {
131 + * try {
132 + * let results = await async.parallel([
133 + * function(callback) {
134 + * setTimeout(function() {
135 + * callback(null, 'one');
136 + * }, 200);
137 + * },
138 + * function(callback) {
139 + * setTimeout(function() {
140 + * callback(null, 'two');
141 + * }, 100);
142 + * }
143 + * ]);
144 + * console.log(results);
145 + * // results is equal to ['one','two'] even though
146 + * // the second function had a shorter timeout.
147 + * }
148 + * catch (err) {
149 + * console.log(err);
150 + * }
151 + * }
152 + *
153 + * // an example using an object instead of an array
154 + * async () => {
155 + * try {
156 + * let results = await async.parallel({
157 + * one: function(callback) {
158 + * setTimeout(function() {
159 + * callback(null, 1);
160 + * }, 200);
161 + * },
162 + * two: function(callback) {
163 + * setTimeout(function() {
164 + * callback(null, 2);
165 + * }, 100);
166 + * }
167 + * });
168 + * console.log(results);
169 + * // results is equal to: { one: 1, two: 2 }
170 + * }
171 + * catch (err) {
172 + * console.log(err);
173 + * }
174 + * }
175 + *
176 + */
177 +function parallel(tasks, callback) {
178 + return (0, _parallel3.default)(_eachOf2.default, tasks, callback);
179 +}
180 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = parallelLimit;
7 +
8 +var _eachOfLimit = require('./internal/eachOfLimit.js');
9 +
10 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
11 +
12 +var _parallel = require('./internal/parallel.js');
13 +
14 +var _parallel2 = _interopRequireDefault(_parallel);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +/**
19 + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a
20 + * time.
21 + *
22 + * @name parallelLimit
23 + * @static
24 + * @memberOf module:ControlFlow
25 + * @method
26 + * @see [async.parallel]{@link module:ControlFlow.parallel}
27 + * @category Control Flow
28 + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of
29 + * [async functions]{@link AsyncFunction} to run.
30 + * Each async function can complete with any number of optional `result` values.
31 + * @param {number} limit - The maximum number of async operations at a time.
32 + * @param {Function} [callback] - An optional callback to run once all the
33 + * functions have completed successfully. This function gets a results array
34 + * (or object) containing all the result arguments passed to the task callbacks.
35 + * Invoked with (err, results).
36 + * @returns {Promise} a promise, if a callback is not passed
37 + */
38 +function parallelLimit(tasks, limit, callback) {
39 + return (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback);
40 +}
41 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +exports.default = function (worker, concurrency) {
8 + // Start with a normal queue
9 + var q = (0, _queue2.default)(worker, concurrency);
10 + var processingScheduled = false;
11 +
12 + q._tasks = new _Heap2.default();
13 +
14 + // Override push to accept second parameter representing priority
15 + q.push = function (data, priority = 0, callback = () => {}) {
16 + if (typeof callback !== 'function') {
17 + throw new Error('task callback must be a function');
18 + }
19 + q.started = true;
20 + if (!Array.isArray(data)) {
21 + data = [data];
22 + }
23 + if (data.length === 0 && q.idle()) {
24 + // call drain immediately if there are no tasks
25 + return (0, _setImmediate2.default)(() => q.drain());
26 + }
27 +
28 + for (var i = 0, l = data.length; i < l; i++) {
29 + var item = {
30 + data: data[i],
31 + priority,
32 + callback
33 + };
34 +
35 + q._tasks.push(item);
36 + }
37 +
38 + if (!processingScheduled) {
39 + processingScheduled = true;
40 + (0, _setImmediate2.default)(() => {
41 + processingScheduled = false;
42 + q.process();
43 + });
44 + }
45 + };
46 +
47 + // Remove unshift function
48 + delete q.unshift;
49 +
50 + return q;
51 +};
52 +
53 +var _setImmediate = require('./setImmediate.js');
54 +
55 +var _setImmediate2 = _interopRequireDefault(_setImmediate);
56 +
57 +var _queue = require('./queue.js');
58 +
59 +var _queue2 = _interopRequireDefault(_queue);
60 +
61 +var _Heap = require('./internal/Heap.js');
62 +
63 +var _Heap2 = _interopRequireDefault(_Heap);
64 +
65 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
66 +
67 +module.exports = exports['default'];
68 +
69 +/**
70 + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and
71 + * completed in ascending priority order.
72 + *
73 + * @name priorityQueue
74 + * @static
75 + * @memberOf module:ControlFlow
76 + * @method
77 + * @see [async.queue]{@link module:ControlFlow.queue}
78 + * @category Control Flow
79 + * @param {AsyncFunction} worker - An async function for processing a queued task.
80 + * If you want to handle errors from an individual task, pass a callback to
81 + * `q.push()`.
82 + * Invoked with (task, callback).
83 + * @param {number} concurrency - An `integer` for determining how many `worker`
84 + * functions should be run in parallel. If omitted, the concurrency defaults to
85 + * `1`. If the concurrency is `0`, an error is thrown.
86 + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two
87 + * differences between `queue` and `priorityQueue` objects:
88 + * * `push(task, priority, [callback])` - `priority` should be a number. If an
89 + * array of `tasks` is given, all tasks will be assigned the same priority.
90 + * * The `unshift` method was removed.
91 + */
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +exports.default = function (worker, concurrency) {
8 + var _worker = (0, _wrapAsync2.default)(worker);
9 + return (0, _queue2.default)((items, cb) => {
10 + _worker(items[0], cb);
11 + }, concurrency, 1);
12 +};
13 +
14 +var _queue = require('./internal/queue.js');
15 +
16 +var _queue2 = _interopRequireDefault(_queue);
17 +
18 +var _wrapAsync = require('./internal/wrapAsync.js');
19 +
20 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
21 +
22 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23 +
24 +module.exports = exports['default'];
25 +
26 +/**
27 + * A queue of tasks for the worker function to complete.
28 + * @typedef {Iterable} QueueObject
29 + * @memberOf module:ControlFlow
30 + * @property {Function} length - a function returning the number of items
31 + * waiting to be processed. Invoke with `queue.length()`.
32 + * @property {boolean} started - a boolean indicating whether or not any
33 + * items have been pushed and processed by the queue.
34 + * @property {Function} running - a function returning the number of items
35 + * currently being processed. Invoke with `queue.running()`.
36 + * @property {Function} workersList - a function returning the array of items
37 + * currently being processed. Invoke with `queue.workersList()`.
38 + * @property {Function} idle - a function returning false if there are items
39 + * waiting or being processed, or true if not. Invoke with `queue.idle()`.
40 + * @property {number} concurrency - an integer for determining how many `worker`
41 + * functions should be run in parallel. This property can be changed after a
42 + * `queue` is created to alter the concurrency on-the-fly.
43 + * @property {number} payload - an integer that specifies how many items are
44 + * passed to the worker function at a time. only applies if this is a
45 + * [cargo]{@link module:ControlFlow.cargo} object
46 + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`
47 + * once the `worker` has finished processing the task. Instead of a single task,
48 + * a `tasks` array can be submitted. The respective callback is used for every
49 + * task in the list. Invoke with `queue.push(task, [callback])`,
50 + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`.
51 + * Invoke with `queue.unshift(task, [callback])`.
52 + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns
53 + * a promise that rejects if an error occurs.
54 + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns
55 + * a promise that rejects if an error occurs.
56 + * @property {Function} remove - remove items from the queue that match a test
57 + * function. The test function will be passed an object with a `data` property,
58 + * and a `priority` property, if this is a
59 + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.
60 + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form
61 + * `function ({data, priority}) {}` and returns a Boolean.
62 + * @property {Function} saturated - a function that sets a callback that is
63 + * called when the number of running workers hits the `concurrency` limit, and
64 + * further tasks will be queued. If the callback is omitted, `q.saturated()`
65 + * returns a promise for the next occurrence.
66 + * @property {Function} unsaturated - a function that sets a callback that is
67 + * called when the number of running workers is less than the `concurrency` &
68 + * `buffer` limits, and further tasks will not be queued. If the callback is
69 + * omitted, `q.unsaturated()` returns a promise for the next occurrence.
70 + * @property {number} buffer - A minimum threshold buffer in order to say that
71 + * the `queue` is `unsaturated`.
72 + * @property {Function} empty - a function that sets a callback that is called
73 + * when the last item from the `queue` is given to a `worker`. If the callback
74 + * is omitted, `q.empty()` returns a promise for the next occurrence.
75 + * @property {Function} drain - a function that sets a callback that is called
76 + * when the last item from the `queue` has returned from the `worker`. If the
77 + * callback is omitted, `q.drain()` returns a promise for the next occurrence.
78 + * @property {Function} error - a function that sets a callback that is called
79 + * when a task errors. Has the signature `function(error, task)`. If the
80 + * callback is omitted, `error()` returns a promise that rejects on the next
81 + * error.
82 + * @property {boolean} paused - a boolean for determining whether the queue is
83 + * in a paused state.
84 + * @property {Function} pause - a function that pauses the processing of tasks
85 + * until `resume()` is called. Invoke with `queue.pause()`.
86 + * @property {Function} resume - a function that resumes the processing of
87 + * queued tasks when the queue is paused. Invoke with `queue.resume()`.
88 + * @property {Function} kill - a function that removes the `drain` callback and
89 + * empties remaining tasks from the queue forcing it to go idle. No more tasks
90 + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.
91 + *
92 + * @example
93 + * const q = async.queue(worker, 2)
94 + * q.push(item1)
95 + * q.push(item2)
96 + * q.push(item3)
97 + * // queues are iterable, spread into an array to inspect
98 + * const items = [...q] // [item1, item2, item3]
99 + * // or use for of
100 + * for (let item of q) {
101 + * console.log(item)
102 + * }
103 + *
104 + * q.drain(() => {
105 + * console.log('all done')
106 + * })
107 + * // or
108 + * await q.drain()
109 + */
110 +
111 +/**
112 + * Creates a `queue` object with the specified `concurrency`. Tasks added to the
113 + * `queue` are processed in parallel (up to the `concurrency` limit). If all
114 + * `worker`s are in progress, the task is queued until one becomes available.
115 + * Once a `worker` completes a `task`, that `task`'s callback is called.
116 + *
117 + * @name queue
118 + * @static
119 + * @memberOf module:ControlFlow
120 + * @method
121 + * @category Control Flow
122 + * @param {AsyncFunction} worker - An async function for processing a queued task.
123 + * If you want to handle errors from an individual task, pass a callback to
124 + * `q.push()`. Invoked with (task, callback).
125 + * @param {number} [concurrency=1] - An `integer` for determining how many
126 + * `worker` functions should be run in parallel. If omitted, the concurrency
127 + * defaults to `1`. If the concurrency is `0`, an error is thrown.
128 + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be
129 + * attached as certain properties to listen for specific events during the
130 + * lifecycle of the queue.
131 + * @example
132 + *
133 + * // create a queue object with concurrency 2
134 + * var q = async.queue(function(task, callback) {
135 + * console.log('hello ' + task.name);
136 + * callback();
137 + * }, 2);
138 + *
139 + * // assign a callback
140 + * q.drain(function() {
141 + * console.log('all items have been processed');
142 + * });
143 + * // or await the end
144 + * await q.drain()
145 + *
146 + * // assign an error callback
147 + * q.error(function(err, task) {
148 + * console.error('task experienced an error');
149 + * });
150 + *
151 + * // add some items to the queue
152 + * q.push({name: 'foo'}, function(err) {
153 + * console.log('finished processing foo');
154 + * });
155 + * // callback is optional
156 + * q.push({name: 'bar'});
157 + *
158 + * // add some items to the queue (batch-wise)
159 + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
160 + * console.log('finished processing item');
161 + * });
162 + *
163 + * // add some items to the front of the queue
164 + * q.unshift({name: 'bar'}, function (err) {
165 + * console.log('finished processing bar');
166 + * });
167 + */
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _once = require('./internal/once.js');
8 +
9 +var _once2 = _interopRequireDefault(_once);
10 +
11 +var _wrapAsync = require('./internal/wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Runs the `tasks` array of functions in parallel, without waiting until the
23 + * previous function has completed. Once any of the `tasks` complete or pass an
24 + * error to its callback, the main `callback` is immediately called. It's
25 + * equivalent to `Promise.race()`.
26 + *
27 + * @name race
28 + * @static
29 + * @memberOf module:ControlFlow
30 + * @method
31 + * @category Control Flow
32 + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}
33 + * to run. Each function can complete with an optional `result` value.
34 + * @param {Function} callback - A callback to run once any of the functions have
35 + * completed. This function gets an error or result from the first function that
36 + * completed. Invoked with (err, result).
37 + * @returns undefined
38 + * @example
39 + *
40 + * async.race([
41 + * function(callback) {
42 + * setTimeout(function() {
43 + * callback(null, 'one');
44 + * }, 200);
45 + * },
46 + * function(callback) {
47 + * setTimeout(function() {
48 + * callback(null, 'two');
49 + * }, 100);
50 + * }
51 + * ],
52 + * // main callback
53 + * function(err, result) {
54 + * // the result will be equal to 'two' as it finishes earlier
55 + * });
56 + */
57 +function race(tasks, callback) {
58 + callback = (0, _once2.default)(callback);
59 + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));
60 + if (!tasks.length) return callback();
61 + for (var i = 0, l = tasks.length; i < l; i++) {
62 + (0, _wrapAsync2.default)(tasks[i])(callback);
63 + }
64 +}
65 +
66 +exports.default = (0, _awaitify2.default)(race, 2);
67 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachOfSeries = require('./eachOfSeries.js');
8 +
9 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
10 +
11 +var _once = require('./internal/once.js');
12 +
13 +var _once2 = _interopRequireDefault(_once);
14 +
15 +var _wrapAsync = require('./internal/wrapAsync.js');
16 +
17 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
18 +
19 +var _awaitify = require('./internal/awaitify.js');
20 +
21 +var _awaitify2 = _interopRequireDefault(_awaitify);
22 +
23 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24 +
25 +/**
26 + * Reduces `coll` into a single value using an async `iteratee` to return each
27 + * successive step. `memo` is the initial state of the reduction. This function
28 + * only operates in series.
29 + *
30 + * For performance reasons, it may make sense to split a call to this function
31 + * into a parallel map, and then use the normal `Array.prototype.reduce` on the
32 + * results. This function is for situations where each step in the reduction
33 + * needs to be async; if you can get the data before reducing it, then it's
34 + * probably a good idea to do so.
35 + *
36 + * @name reduce
37 + * @static
38 + * @memberOf module:Collections
39 + * @method
40 + * @alias inject
41 + * @alias foldl
42 + * @category Collection
43 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
44 + * @param {*} memo - The initial state of the reduction.
45 + * @param {AsyncFunction} iteratee - A function applied to each item in the
46 + * array to produce the next step in the reduction.
47 + * The `iteratee` should complete with the next state of the reduction.
48 + * If the iteratee completes with an error, the reduction is stopped and the
49 + * main `callback` is immediately called with the error.
50 + * Invoked with (memo, item, callback).
51 + * @param {Function} [callback] - A callback which is called after all the
52 + * `iteratee` functions have finished. Result is the reduced value. Invoked with
53 + * (err, result).
54 + * @returns {Promise} a promise, if no callback is passed
55 + * @example
56 + *
57 + * // file1.txt is a file that is 1000 bytes in size
58 + * // file2.txt is a file that is 2000 bytes in size
59 + * // file3.txt is a file that is 3000 bytes in size
60 + * // file4.txt does not exist
61 + *
62 + * const fileList = ['file1.txt','file2.txt','file3.txt'];
63 + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt'];
64 + *
65 + * // asynchronous function that computes the file size in bytes
66 + * // file size is added to the memoized value, then returned
67 + * function getFileSizeInBytes(memo, file, callback) {
68 + * fs.stat(file, function(err, stat) {
69 + * if (err) {
70 + * return callback(err);
71 + * }
72 + * callback(null, memo + stat.size);
73 + * });
74 + * }
75 + *
76 + * // Using callbacks
77 + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) {
78 + * if (err) {
79 + * console.log(err);
80 + * } else {
81 + * console.log(result);
82 + * // 6000
83 + * // which is the sum of the file sizes of the three files
84 + * }
85 + * });
86 + *
87 + * // Error Handling
88 + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) {
89 + * if (err) {
90 + * console.log(err);
91 + * // [ Error: ENOENT: no such file or directory ]
92 + * } else {
93 + * console.log(result);
94 + * }
95 + * });
96 + *
97 + * // Using Promises
98 + * async.reduce(fileList, 0, getFileSizeInBytes)
99 + * .then( result => {
100 + * console.log(result);
101 + * // 6000
102 + * // which is the sum of the file sizes of the three files
103 + * }).catch( err => {
104 + * console.log(err);
105 + * });
106 + *
107 + * // Error Handling
108 + * async.reduce(withMissingFileList, 0, getFileSizeInBytes)
109 + * .then( result => {
110 + * console.log(result);
111 + * }).catch( err => {
112 + * console.log(err);
113 + * // [ Error: ENOENT: no such file or directory ]
114 + * });
115 + *
116 + * // Using async/await
117 + * async () => {
118 + * try {
119 + * let result = await async.reduce(fileList, 0, getFileSizeInBytes);
120 + * console.log(result);
121 + * // 6000
122 + * // which is the sum of the file sizes of the three files
123 + * }
124 + * catch (err) {
125 + * console.log(err);
126 + * }
127 + * }
128 + *
129 + * // Error Handling
130 + * async () => {
131 + * try {
132 + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);
133 + * console.log(result);
134 + * }
135 + * catch (err) {
136 + * console.log(err);
137 + * // [ Error: ENOENT: no such file or directory ]
138 + * }
139 + * }
140 + *
141 + */
142 +function reduce(coll, memo, iteratee, callback) {
143 + callback = (0, _once2.default)(callback);
144 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
145 + return (0, _eachOfSeries2.default)(coll, (x, i, iterCb) => {
146 + _iteratee(memo, x, (err, v) => {
147 + memo = v;
148 + iterCb(err);
149 + });
150 + }, err => callback(err, memo));
151 +}
152 +exports.default = (0, _awaitify2.default)(reduce, 4);
153 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = reduceRight;
7 +
8 +var _reduce = require('./reduce.js');
9 +
10 +var _reduce2 = _interopRequireDefault(_reduce);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.
16 + *
17 + * @name reduceRight
18 + * @static
19 + * @memberOf module:Collections
20 + * @method
21 + * @see [async.reduce]{@link module:Collections.reduce}
22 + * @alias foldr
23 + * @category Collection
24 + * @param {Array} array - A collection to iterate over.
25 + * @param {*} memo - The initial state of the reduction.
26 + * @param {AsyncFunction} iteratee - A function applied to each item in the
27 + * array to produce the next step in the reduction.
28 + * The `iteratee` should complete with the next state of the reduction.
29 + * If the iteratee completes with an error, the reduction is stopped and the
30 + * main `callback` is immediately called with the error.
31 + * Invoked with (memo, item, callback).
32 + * @param {Function} [callback] - A callback which is called after all the
33 + * `iteratee` functions have finished. Result is the reduced value. Invoked with
34 + * (err, result).
35 + * @returns {Promise} a promise, if no callback is passed
36 + */
37 +function reduceRight(array, memo, iteratee, callback) {
38 + var reversed = [...array].reverse();
39 + return (0, _reduce2.default)(reversed, memo, iteratee, callback);
40 +}
41 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = reflect;
7 +
8 +var _initialParams = require('./internal/initialParams.js');
9 +
10 +var _initialParams2 = _interopRequireDefault(_initialParams);
11 +
12 +var _wrapAsync = require('./internal/wrapAsync.js');
13 +
14 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +/**
19 + * Wraps the async function in another function that always completes with a
20 + * result object, even when it errors.
21 + *
22 + * The result object has either the property `error` or `value`.
23 + *
24 + * @name reflect
25 + * @static
26 + * @memberOf module:Utils
27 + * @method
28 + * @category Util
29 + * @param {AsyncFunction} fn - The async function you want to wrap
30 + * @returns {Function} - A function that always passes null to it's callback as
31 + * the error. The second argument to the callback will be an `object` with
32 + * either an `error` or a `value` property.
33 + * @example
34 + *
35 + * async.parallel([
36 + * async.reflect(function(callback) {
37 + * // do some stuff ...
38 + * callback(null, 'one');
39 + * }),
40 + * async.reflect(function(callback) {
41 + * // do some more stuff but error ...
42 + * callback('bad stuff happened');
43 + * }),
44 + * async.reflect(function(callback) {
45 + * // do some more stuff ...
46 + * callback(null, 'two');
47 + * })
48 + * ],
49 + * // optional callback
50 + * function(err, results) {
51 + * // values
52 + * // results[0].value = 'one'
53 + * // results[1].error = 'bad stuff happened'
54 + * // results[2].value = 'two'
55 + * });
56 + */
57 +function reflect(fn) {
58 + var _fn = (0, _wrapAsync2.default)(fn);
59 + return (0, _initialParams2.default)(function reflectOn(args, reflectCallback) {
60 + args.push((error, ...cbArgs) => {
61 + let retVal = {};
62 + if (error) {
63 + retVal.error = error;
64 + }
65 + if (cbArgs.length > 0) {
66 + var value = cbArgs;
67 + if (cbArgs.length <= 1) {
68 + [value] = cbArgs;
69 + }
70 + retVal.value = value;
71 + }
72 + reflectCallback(null, retVal);
73 + });
74 +
75 + return _fn.apply(this, args);
76 + });
77 +}
78 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = reflectAll;
7 +
8 +var _reflect = require('./reflect.js');
9 +
10 +var _reflect2 = _interopRequireDefault(_reflect);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * A helper function that wraps an array or an object of functions with `reflect`.
16 + *
17 + * @name reflectAll
18 + * @static
19 + * @memberOf module:Utils
20 + * @method
21 + * @see [async.reflect]{@link module:Utils.reflect}
22 + * @category Util
23 + * @param {Array|Object|Iterable} tasks - The collection of
24 + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.
25 + * @returns {Array} Returns an array of async functions, each wrapped in
26 + * `async.reflect`
27 + * @example
28 + *
29 + * let tasks = [
30 + * function(callback) {
31 + * setTimeout(function() {
32 + * callback(null, 'one');
33 + * }, 200);
34 + * },
35 + * function(callback) {
36 + * // do some more stuff but error ...
37 + * callback(new Error('bad stuff happened'));
38 + * },
39 + * function(callback) {
40 + * setTimeout(function() {
41 + * callback(null, 'two');
42 + * }, 100);
43 + * }
44 + * ];
45 + *
46 + * async.parallel(async.reflectAll(tasks),
47 + * // optional callback
48 + * function(err, results) {
49 + * // values
50 + * // results[0].value = 'one'
51 + * // results[1].error = Error('bad stuff happened')
52 + * // results[2].value = 'two'
53 + * });
54 + *
55 + * // an example using an object instead of an array
56 + * let tasks = {
57 + * one: function(callback) {
58 + * setTimeout(function() {
59 + * callback(null, 'one');
60 + * }, 200);
61 + * },
62 + * two: function(callback) {
63 + * callback('two');
64 + * },
65 + * three: function(callback) {
66 + * setTimeout(function() {
67 + * callback(null, 'three');
68 + * }, 100);
69 + * }
70 + * };
71 + *
72 + * async.parallel(async.reflectAll(tasks),
73 + * // optional callback
74 + * function(err, results) {
75 + * // values
76 + * // results.one.value = 'one'
77 + * // results.two.error = 'two'
78 + * // results.three.value = 'three'
79 + * });
80 + */
81 +function reflectAll(tasks) {
82 + var results;
83 + if (Array.isArray(tasks)) {
84 + results = tasks.map(_reflect2.default);
85 + } else {
86 + results = {};
87 + Object.keys(tasks).forEach(key => {
88 + results[key] = _reflect2.default.call(this, tasks[key]);
89 + });
90 + }
91 + return results;
92 +}
93 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _reject2 = require('./internal/reject.js');
8 +
9 +var _reject3 = _interopRequireDefault(_reject2);
10 +
11 +var _eachOf = require('./eachOf.js');
12 +
13 +var _eachOf2 = _interopRequireDefault(_eachOf);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
23 + *
24 + * @name reject
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.filter]{@link module:Collections.filter}
29 + * @category Collection
30 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
31 + * @param {Function} iteratee - An async truth test to apply to each item in
32 + * `coll`.
33 + * The should complete with a boolean value as its `result`.
34 + * Invoked with (item, callback).
35 + * @param {Function} [callback] - A callback which is called after all the
36 + * `iteratee` functions have finished. Invoked with (err, results).
37 + * @returns {Promise} a promise, if no callback is passed
38 + * @example
39 + *
40 + * // dir1 is a directory that contains file1.txt, file2.txt
41 + * // dir2 is a directory that contains file3.txt, file4.txt
42 + * // dir3 is a directory that contains file5.txt
43 + *
44 + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
45 + *
46 + * // asynchronous function that checks if a file exists
47 + * function fileExists(file, callback) {
48 + * fs.access(file, fs.constants.F_OK, (err) => {
49 + * callback(null, !err);
50 + * });
51 + * }
52 + *
53 + * // Using callbacks
54 + * async.reject(fileList, fileExists, function(err, results) {
55 + * // [ 'dir3/file6.txt' ]
56 + * // results now equals an array of the non-existing files
57 + * });
58 + *
59 + * // Using Promises
60 + * async.reject(fileList, fileExists)
61 + * .then( results => {
62 + * console.log(results);
63 + * // [ 'dir3/file6.txt' ]
64 + * // results now equals an array of the non-existing files
65 + * }).catch( err => {
66 + * console.log(err);
67 + * });
68 + *
69 + * // Using async/await
70 + * async () => {
71 + * try {
72 + * let results = await async.reject(fileList, fileExists);
73 + * console.log(results);
74 + * // [ 'dir3/file6.txt' ]
75 + * // results now equals an array of the non-existing files
76 + * }
77 + * catch (err) {
78 + * console.log(err);
79 + * }
80 + * }
81 + *
82 + */
83 +function reject(coll, iteratee, callback) {
84 + return (0, _reject3.default)(_eachOf2.default, coll, iteratee, callback);
85 +}
86 +exports.default = (0, _awaitify2.default)(reject, 3);
87 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _reject2 = require('./internal/reject.js');
8 +
9 +var _reject3 = _interopRequireDefault(_reject2);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a
23 + * time.
24 + *
25 + * @name rejectLimit
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @see [async.reject]{@link module:Collections.reject}
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {number} limit - The maximum number of async operations at a time.
33 + * @param {Function} iteratee - An async truth test to apply to each item in
34 + * `coll`.
35 + * The should complete with a boolean value as its `result`.
36 + * Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called after all the
38 + * `iteratee` functions have finished. Invoked with (err, results).
39 + * @returns {Promise} a promise, if no callback is passed
40 + */
41 +function rejectLimit(coll, limit, iteratee, callback) {
42 + return (0, _reject3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
43 +}
44 +exports.default = (0, _awaitify2.default)(rejectLimit, 4);
45 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _reject2 = require('./internal/reject.js');
8 +
9 +var _reject3 = _interopRequireDefault(_reject2);
10 +
11 +var _eachOfSeries = require('./eachOfSeries.js');
12 +
13 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.
23 + *
24 + * @name rejectSeries
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.reject]{@link module:Collections.reject}
29 + * @category Collection
30 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
31 + * @param {Function} iteratee - An async truth test to apply to each item in
32 + * `coll`.
33 + * The should complete with a boolean value as its `result`.
34 + * Invoked with (item, callback).
35 + * @param {Function} [callback] - A callback which is called after all the
36 + * `iteratee` functions have finished. Invoked with (err, results).
37 + * @returns {Promise} a promise, if no callback is passed
38 + */
39 +function rejectSeries(coll, iteratee, callback) {
40 + return (0, _reject3.default)(_eachOfSeries2.default, coll, iteratee, callback);
41 +}
42 +exports.default = (0, _awaitify2.default)(rejectSeries, 3);
43 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = retry;
7 +
8 +var _wrapAsync = require('./internal/wrapAsync.js');
9 +
10 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
11 +
12 +var _promiseCallback = require('./internal/promiseCallback.js');
13 +
14 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15 +
16 +function constant(value) {
17 + return function () {
18 + return value;
19 + };
20 +}
21 +
22 +/**
23 + * Attempts to get a successful response from `task` no more than `times` times
24 + * before returning an error. If the task is successful, the `callback` will be
25 + * passed the result of the successful task. If all attempts fail, the callback
26 + * will be passed the error and result (if any) of the final attempt.
27 + *
28 + * @name retry
29 + * @static
30 + * @memberOf module:ControlFlow
31 + * @method
32 + * @category Control Flow
33 + * @see [async.retryable]{@link module:ControlFlow.retryable}
34 + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
35 + * object with `times` and `interval` or a number.
36 + * * `times` - The number of attempts to make before giving up. The default
37 + * is `5`.
38 + * * `interval` - The time to wait between retries, in milliseconds. The
39 + * default is `0`. The interval may also be specified as a function of the
40 + * retry count (see example).
41 + * * `errorFilter` - An optional synchronous function that is invoked on
42 + * erroneous result. If it returns `true` the retry attempts will continue;
43 + * if the function returns `false` the retry flow is aborted with the current
44 + * attempt's error and result being returned to the final callback.
45 + * Invoked with (err).
46 + * * If `opts` is a number, the number specifies the number of times to retry,
47 + * with the default interval of `0`.
48 + * @param {AsyncFunction} task - An async function to retry.
49 + * Invoked with (callback).
50 + * @param {Function} [callback] - An optional callback which is called when the
51 + * task has succeeded, or after the final failed attempt. It receives the `err`
52 + * and `result` arguments of the last attempt at completing the `task`. Invoked
53 + * with (err, results).
54 + * @returns {Promise} a promise if no callback provided
55 + *
56 + * @example
57 + *
58 + * // The `retry` function can be used as a stand-alone control flow by passing
59 + * // a callback, as shown below:
60 + *
61 + * // try calling apiMethod 3 times
62 + * async.retry(3, apiMethod, function(err, result) {
63 + * // do something with the result
64 + * });
65 + *
66 + * // try calling apiMethod 3 times, waiting 200 ms between each retry
67 + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
68 + * // do something with the result
69 + * });
70 + *
71 + * // try calling apiMethod 10 times with exponential backoff
72 + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)
73 + * async.retry({
74 + * times: 10,
75 + * interval: function(retryCount) {
76 + * return 50 * Math.pow(2, retryCount);
77 + * }
78 + * }, apiMethod, function(err, result) {
79 + * // do something with the result
80 + * });
81 + *
82 + * // try calling apiMethod the default 5 times no delay between each retry
83 + * async.retry(apiMethod, function(err, result) {
84 + * // do something with the result
85 + * });
86 + *
87 + * // try calling apiMethod only when error condition satisfies, all other
88 + * // errors will abort the retry control flow and return to final callback
89 + * async.retry({
90 + * errorFilter: function(err) {
91 + * return err.message === 'Temporary error'; // only retry on a specific error
92 + * }
93 + * }, apiMethod, function(err, result) {
94 + * // do something with the result
95 + * });
96 + *
97 + * // to retry individual methods that are not as reliable within other
98 + * // control flow functions, use the `retryable` wrapper:
99 + * async.auto({
100 + * users: api.getUsers.bind(api),
101 + * payments: async.retryable(3, api.getPayments.bind(api))
102 + * }, function(err, results) {
103 + * // do something with the results
104 + * });
105 + *
106 + */
107 +const DEFAULT_TIMES = 5;
108 +const DEFAULT_INTERVAL = 0;
109 +
110 +function retry(opts, task, callback) {
111 + var options = {
112 + times: DEFAULT_TIMES,
113 + intervalFunc: constant(DEFAULT_INTERVAL)
114 + };
115 +
116 + if (arguments.length < 3 && typeof opts === 'function') {
117 + callback = task || (0, _promiseCallback.promiseCallback)();
118 + task = opts;
119 + } else {
120 + parseTimes(options, opts);
121 + callback = callback || (0, _promiseCallback.promiseCallback)();
122 + }
123 +
124 + if (typeof task !== 'function') {
125 + throw new Error("Invalid arguments for async.retry");
126 + }
127 +
128 + var _task = (0, _wrapAsync2.default)(task);
129 +
130 + var attempt = 1;
131 + function retryAttempt() {
132 + _task((err, ...args) => {
133 + if (err === false) return;
134 + if (err && attempt++ < options.times && (typeof options.errorFilter != 'function' || options.errorFilter(err))) {
135 + setTimeout(retryAttempt, options.intervalFunc(attempt - 1));
136 + } else {
137 + callback(err, ...args);
138 + }
139 + });
140 + }
141 +
142 + retryAttempt();
143 + return callback[_promiseCallback.PROMISE_SYMBOL];
144 +}
145 +
146 +function parseTimes(acc, t) {
147 + if (typeof t === 'object') {
148 + acc.times = +t.times || DEFAULT_TIMES;
149 +
150 + acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant(+t.interval || DEFAULT_INTERVAL);
151 +
152 + acc.errorFilter = t.errorFilter;
153 + } else if (typeof t === 'number' || typeof t === 'string') {
154 + acc.times = +t || DEFAULT_TIMES;
155 + } else {
156 + throw new Error("Invalid arguments for async.retry");
157 + }
158 +}
159 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = retryable;
7 +
8 +var _retry = require('./retry.js');
9 +
10 +var _retry2 = _interopRequireDefault(_retry);
11 +
12 +var _initialParams = require('./internal/initialParams.js');
13 +
14 +var _initialParams2 = _interopRequireDefault(_initialParams);
15 +
16 +var _wrapAsync = require('./internal/wrapAsync.js');
17 +
18 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
19 +
20 +var _promiseCallback = require('./internal/promiseCallback.js');
21 +
22 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23 +
24 +/**
25 + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method
26 + * wraps a task and makes it retryable, rather than immediately calling it
27 + * with retries.
28 + *
29 + * @name retryable
30 + * @static
31 + * @memberOf module:ControlFlow
32 + * @method
33 + * @see [async.retry]{@link module:ControlFlow.retry}
34 + * @category Control Flow
35 + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
36 + * options, exactly the same as from `retry`, except for a `opts.arity` that
37 + * is the arity of the `task` function, defaulting to `task.length`
38 + * @param {AsyncFunction} task - the asynchronous function to wrap.
39 + * This function will be passed any arguments passed to the returned wrapper.
40 + * Invoked with (...args, callback).
41 + * @returns {AsyncFunction} The wrapped function, which when invoked, will
42 + * retry on an error, based on the parameters specified in `opts`.
43 + * This function will accept the same parameters as `task`.
44 + * @example
45 + *
46 + * async.auto({
47 + * dep1: async.retryable(3, getFromFlakyService),
48 + * process: ["dep1", async.retryable(3, function (results, cb) {
49 + * maybeProcessData(results.dep1, cb);
50 + * })]
51 + * }, callback);
52 + */
53 +function retryable(opts, task) {
54 + if (!task) {
55 + task = opts;
56 + opts = null;
57 + }
58 + let arity = opts && opts.arity || task.length;
59 + if ((0, _wrapAsync.isAsync)(task)) {
60 + arity += 1;
61 + }
62 + var _task = (0, _wrapAsync2.default)(task);
63 + return (0, _initialParams2.default)((args, callback) => {
64 + if (args.length < arity - 1 || callback == null) {
65 + args.push(callback);
66 + callback = (0, _promiseCallback.promiseCallback)();
67 + }
68 + function taskFn(cb) {
69 + _task(...args, cb);
70 + }
71 +
72 + if (opts) (0, _retry2.default)(opts, taskFn, callback);else (0, _retry2.default)(taskFn, callback);
73 +
74 + return callback[_promiseCallback.PROMISE_SYMBOL];
75 + });
76 +}
77 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _filter2 = require('./internal/filter.js');
8 +
9 +var _filter3 = _interopRequireDefault(_filter2);
10 +
11 +var _eachOf = require('./eachOf.js');
12 +
13 +var _eachOf2 = _interopRequireDefault(_eachOf);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Returns a new array of all the values in `coll` which pass an async truth
23 + * test. This operation is performed in parallel, but the results array will be
24 + * in the same order as the original.
25 + *
26 + * @name filter
27 + * @static
28 + * @memberOf module:Collections
29 + * @method
30 + * @alias select
31 + * @category Collection
32 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
33 + * @param {Function} iteratee - A truth test to apply to each item in `coll`.
34 + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
35 + * with a boolean argument once it has completed. Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called after all the
37 + * `iteratee` functions have finished. Invoked with (err, results).
38 + * @returns {Promise} a promise, if no callback provided
39 + * @example
40 + *
41 + * // dir1 is a directory that contains file1.txt, file2.txt
42 + * // dir2 is a directory that contains file3.txt, file4.txt
43 + * // dir3 is a directory that contains file5.txt
44 + *
45 + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
46 + *
47 + * // asynchronous function that checks if a file exists
48 + * function fileExists(file, callback) {
49 + * fs.access(file, fs.constants.F_OK, (err) => {
50 + * callback(null, !err);
51 + * });
52 + * }
53 + *
54 + * // Using callbacks
55 + * async.filter(files, fileExists, function(err, results) {
56 + * if(err) {
57 + * console.log(err);
58 + * } else {
59 + * console.log(results);
60 + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
61 + * // results is now an array of the existing files
62 + * }
63 + * });
64 + *
65 + * // Using Promises
66 + * async.filter(files, fileExists)
67 + * .then(results => {
68 + * console.log(results);
69 + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
70 + * // results is now an array of the existing files
71 + * }).catch(err => {
72 + * console.log(err);
73 + * });
74 + *
75 + * // Using async/await
76 + * async () => {
77 + * try {
78 + * let results = await async.filter(files, fileExists);
79 + * console.log(results);
80 + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]
81 + * // results is now an array of the existing files
82 + * }
83 + * catch (err) {
84 + * console.log(err);
85 + * }
86 + * }
87 + *
88 + */
89 +function filter(coll, iteratee, callback) {
90 + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback);
91 +}
92 +exports.default = (0, _awaitify2.default)(filter, 3);
93 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _filter2 = require('./internal/filter.js');
8 +
9 +var _filter3 = _interopRequireDefault(_filter2);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a
23 + * time.
24 + *
25 + * @name filterLimit
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @see [async.filter]{@link module:Collections.filter}
30 + * @alias selectLimit
31 + * @category Collection
32 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
33 + * @param {number} limit - The maximum number of async operations at a time.
34 + * @param {Function} iteratee - A truth test to apply to each item in `coll`.
35 + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
36 + * with a boolean argument once it has completed. Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called after all the
38 + * `iteratee` functions have finished. Invoked with (err, results).
39 + * @returns {Promise} a promise, if no callback provided
40 + */
41 +function filterLimit(coll, limit, iteratee, callback) {
42 + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
43 +}
44 +exports.default = (0, _awaitify2.default)(filterLimit, 4);
45 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _filter2 = require('./internal/filter.js');
8 +
9 +var _filter3 = _interopRequireDefault(_filter2);
10 +
11 +var _eachOfSeries = require('./eachOfSeries.js');
12 +
13 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.
23 + *
24 + * @name filterSeries
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.filter]{@link module:Collections.filter}
29 + * @alias selectSeries
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {Function} iteratee - A truth test to apply to each item in `coll`.
33 + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called
34 + * with a boolean argument once it has completed. Invoked with (item, callback).
35 + * @param {Function} [callback] - A callback which is called after all the
36 + * `iteratee` functions have finished. Invoked with (err, results)
37 + * @returns {Promise} a promise, if no callback provided
38 + */
39 +function filterSeries(coll, iteratee, callback) {
40 + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback);
41 +}
42 +exports.default = (0, _awaitify2.default)(filterSeries, 3);
43 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = seq;
7 +
8 +var _reduce = require('./reduce.js');
9 +
10 +var _reduce2 = _interopRequireDefault(_reduce);
11 +
12 +var _wrapAsync = require('./internal/wrapAsync.js');
13 +
14 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
15 +
16 +var _promiseCallback = require('./internal/promiseCallback.js');
17 +
18 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19 +
20 +/**
21 + * Version of the compose function that is more natural to read. Each function
22 + * consumes the return value of the previous function. It is the equivalent of
23 + * [compose]{@link module:ControlFlow.compose} with the arguments reversed.
24 + *
25 + * Each function is executed with the `this` binding of the composed function.
26 + *
27 + * @name seq
28 + * @static
29 + * @memberOf module:ControlFlow
30 + * @method
31 + * @see [async.compose]{@link module:ControlFlow.compose}
32 + * @category Control Flow
33 + * @param {...AsyncFunction} functions - the asynchronous functions to compose
34 + * @returns {Function} a function that composes the `functions` in order
35 + * @example
36 + *
37 + * // Requires lodash (or underscore), express3 and dresende's orm2.
38 + * // Part of an app, that fetches cats of the logged user.
39 + * // This example uses `seq` function to avoid overnesting and error
40 + * // handling clutter.
41 + * app.get('/cats', function(request, response) {
42 + * var User = request.models.User;
43 + * async.seq(
44 + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data))
45 + * function(user, fn) {
46 + * user.getCats(fn); // 'getCats' has signature (callback(err, data))
47 + * }
48 + * )(req.session.user_id, function (err, cats) {
49 + * if (err) {
50 + * console.error(err);
51 + * response.json({ status: 'error', message: err.message });
52 + * } else {
53 + * response.json({ status: 'ok', message: 'Cats found', data: cats });
54 + * }
55 + * });
56 + * });
57 + */
58 +function seq(...functions) {
59 + var _functions = functions.map(_wrapAsync2.default);
60 + return function (...args) {
61 + var that = this;
62 +
63 + var cb = args[args.length - 1];
64 + if (typeof cb == 'function') {
65 + args.pop();
66 + } else {
67 + cb = (0, _promiseCallback.promiseCallback)();
68 + }
69 +
70 + (0, _reduce2.default)(_functions, args, (newargs, fn, iterCb) => {
71 + fn.apply(that, newargs.concat((err, ...nextargs) => {
72 + iterCb(err, nextargs);
73 + }));
74 + }, (err, results) => cb(err, ...results));
75 +
76 + return cb[_promiseCallback.PROMISE_SYMBOL];
77 + };
78 +}
79 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = series;
7 +
8 +var _parallel2 = require('./internal/parallel.js');
9 +
10 +var _parallel3 = _interopRequireDefault(_parallel2);
11 +
12 +var _eachOfSeries = require('./eachOfSeries.js');
13 +
14 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +/**
19 + * Run the functions in the `tasks` collection in series, each one running once
20 + * the previous function has completed. If any functions in the series pass an
21 + * error to its callback, no more functions are run, and `callback` is
22 + * immediately called with the value of the error. Otherwise, `callback`
23 + * receives an array of results when `tasks` have completed.
24 + *
25 + * It is also possible to use an object instead of an array. Each property will
26 + * be run as a function, and the results will be passed to the final `callback`
27 + * as an object instead of an array. This can be a more readable way of handling
28 + * results from {@link async.series}.
29 + *
30 + * **Note** that while many implementations preserve the order of object
31 + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
32 + * explicitly states that
33 + *
34 + * > The mechanics and order of enumerating the properties is not specified.
35 + *
36 + * So if you rely on the order in which your series of functions are executed,
37 + * and want this to work on all platforms, consider using an array.
38 + *
39 + * @name series
40 + * @static
41 + * @memberOf module:ControlFlow
42 + * @method
43 + * @category Control Flow
44 + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing
45 + * [async functions]{@link AsyncFunction} to run in series.
46 + * Each function can complete with any number of optional `result` values.
47 + * @param {Function} [callback] - An optional callback to run once all the
48 + * functions have completed. This function gets a results array (or object)
49 + * containing all the result arguments passed to the `task` callbacks. Invoked
50 + * with (err, result).
51 + * @return {Promise} a promise, if no callback is passed
52 + * @example
53 + *
54 + * //Using Callbacks
55 + * async.series([
56 + * function(callback) {
57 + * setTimeout(function() {
58 + * // do some async task
59 + * callback(null, 'one');
60 + * }, 200);
61 + * },
62 + * function(callback) {
63 + * setTimeout(function() {
64 + * // then do another async task
65 + * callback(null, 'two');
66 + * }, 100);
67 + * }
68 + * ], function(err, results) {
69 + * console.log(results);
70 + * // results is equal to ['one','two']
71 + * });
72 + *
73 + * // an example using objects instead of arrays
74 + * async.series({
75 + * one: function(callback) {
76 + * setTimeout(function() {
77 + * // do some async task
78 + * callback(null, 1);
79 + * }, 200);
80 + * },
81 + * two: function(callback) {
82 + * setTimeout(function() {
83 + * // then do another async task
84 + * callback(null, 2);
85 + * }, 100);
86 + * }
87 + * }, function(err, results) {
88 + * console.log(results);
89 + * // results is equal to: { one: 1, two: 2 }
90 + * });
91 + *
92 + * //Using Promises
93 + * async.series([
94 + * function(callback) {
95 + * setTimeout(function() {
96 + * callback(null, 'one');
97 + * }, 200);
98 + * },
99 + * function(callback) {
100 + * setTimeout(function() {
101 + * callback(null, 'two');
102 + * }, 100);
103 + * }
104 + * ]).then(results => {
105 + * console.log(results);
106 + * // results is equal to ['one','two']
107 + * }).catch(err => {
108 + * console.log(err);
109 + * });
110 + *
111 + * // an example using an object instead of an array
112 + * async.series({
113 + * one: function(callback) {
114 + * setTimeout(function() {
115 + * // do some async task
116 + * callback(null, 1);
117 + * }, 200);
118 + * },
119 + * two: function(callback) {
120 + * setTimeout(function() {
121 + * // then do another async task
122 + * callback(null, 2);
123 + * }, 100);
124 + * }
125 + * }).then(results => {
126 + * console.log(results);
127 + * // results is equal to: { one: 1, two: 2 }
128 + * }).catch(err => {
129 + * console.log(err);
130 + * });
131 + *
132 + * //Using async/await
133 + * async () => {
134 + * try {
135 + * let results = await async.series([
136 + * function(callback) {
137 + * setTimeout(function() {
138 + * // do some async task
139 + * callback(null, 'one');
140 + * }, 200);
141 + * },
142 + * function(callback) {
143 + * setTimeout(function() {
144 + * // then do another async task
145 + * callback(null, 'two');
146 + * }, 100);
147 + * }
148 + * ]);
149 + * console.log(results);
150 + * // results is equal to ['one','two']
151 + * }
152 + * catch (err) {
153 + * console.log(err);
154 + * }
155 + * }
156 + *
157 + * // an example using an object instead of an array
158 + * async () => {
159 + * try {
160 + * let results = await async.parallel({
161 + * one: function(callback) {
162 + * setTimeout(function() {
163 + * // do some async task
164 + * callback(null, 1);
165 + * }, 200);
166 + * },
167 + * two: function(callback) {
168 + * setTimeout(function() {
169 + * // then do another async task
170 + * callback(null, 2);
171 + * }, 100);
172 + * }
173 + * });
174 + * console.log(results);
175 + * // results is equal to: { one: 1, two: 2 }
176 + * }
177 + * catch (err) {
178 + * console.log(err);
179 + * }
180 + * }
181 + *
182 + */
183 +function series(tasks, callback) {
184 + return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback);
185 +}
186 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _setImmediate = require('./internal/setImmediate.js');
8 +
9 +var _setImmediate2 = _interopRequireDefault(_setImmediate);
10 +
11 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12 +
13 +/**
14 + * Calls `callback` on a later loop around the event loop. In Node.js this just
15 + * calls `setImmediate`. In the browser it will use `setImmediate` if
16 + * available, otherwise `setTimeout(callback, 0)`, which means other higher
17 + * priority events may precede the execution of `callback`.
18 + *
19 + * This is used internally for browser-compatibility purposes.
20 + *
21 + * @name setImmediate
22 + * @static
23 + * @memberOf module:Utils
24 + * @method
25 + * @see [async.nextTick]{@link module:Utils.nextTick}
26 + * @category Util
27 + * @param {Function} callback - The function to call on a later loop around
28 + * the event loop. Invoked with (args...).
29 + * @param {...*} args... - any number of additional arguments to pass to the
30 + * callback on the next tick.
31 + * @example
32 + *
33 + * var call_order = [];
34 + * async.nextTick(function() {
35 + * call_order.push('two');
36 + * // call_order now equals ['one','two']
37 + * });
38 + * call_order.push('one');
39 + *
40 + * async.setImmediate(function (a, b, c) {
41 + * // a, b, and c equal 1, 2, and 3
42 + * }, 1, 2, 3);
43 + */
44 +exports.default = _setImmediate2.default;
45 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOf = require('./eachOf.js');
12 +
13 +var _eachOf2 = _interopRequireDefault(_eachOf);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Returns `true` if at least one element in the `coll` satisfies an async test.
23 + * If any iteratee call returns `true`, the main `callback` is immediately
24 + * called.
25 + *
26 + * @name some
27 + * @static
28 + * @memberOf module:Collections
29 + * @method
30 + * @alias any
31 + * @category Collection
32 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
33 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
34 + * in the collections in parallel.
35 + * The iteratee should complete with a boolean `result` value.
36 + * Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called as soon as any
38 + * iteratee returns `true`, or after all the iteratee functions have finished.
39 + * Result will be either `true` or `false` depending on the values of the async
40 + * tests. Invoked with (err, result).
41 + * @returns {Promise} a promise, if no callback provided
42 + * @example
43 + *
44 + * // dir1 is a directory that contains file1.txt, file2.txt
45 + * // dir2 is a directory that contains file3.txt, file4.txt
46 + * // dir3 is a directory that contains file5.txt
47 + * // dir4 does not exist
48 + *
49 + * // asynchronous function that checks if a file exists
50 + * function fileExists(file, callback) {
51 + * fs.access(file, fs.constants.F_OK, (err) => {
52 + * callback(null, !err);
53 + * });
54 + * }
55 + *
56 + * // Using callbacks
57 + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,
58 + * function(err, result) {
59 + * console.log(result);
60 + * // true
61 + * // result is true since some file in the list exists
62 + * }
63 + *);
64 + *
65 + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,
66 + * function(err, result) {
67 + * console.log(result);
68 + * // false
69 + * // result is false since none of the files exists
70 + * }
71 + *);
72 + *
73 + * // Using Promises
74 + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)
75 + * .then( result => {
76 + * console.log(result);
77 + * // true
78 + * // result is true since some file in the list exists
79 + * }).catch( err => {
80 + * console.log(err);
81 + * });
82 + *
83 + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)
84 + * .then( result => {
85 + * console.log(result);
86 + * // false
87 + * // result is false since none of the files exists
88 + * }).catch( err => {
89 + * console.log(err);
90 + * });
91 + *
92 + * // Using async/await
93 + * async () => {
94 + * try {
95 + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);
96 + * console.log(result);
97 + * // true
98 + * // result is true since some file in the list exists
99 + * }
100 + * catch (err) {
101 + * console.log(err);
102 + * }
103 + * }
104 + *
105 + * async () => {
106 + * try {
107 + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);
108 + * console.log(result);
109 + * // false
110 + * // result is false since none of the files exists
111 + * }
112 + * catch (err) {
113 + * console.log(err);
114 + * }
115 + * }
116 + *
117 + */
118 +function some(coll, iteratee, callback) {
119 + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback);
120 +}
121 +exports.default = (0, _awaitify2.default)(some, 3);
122 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfLimit = require('./internal/eachOfLimit.js');
12 +
13 +var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.
23 + *
24 + * @name someLimit
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.some]{@link module:Collections.some}
29 + * @alias anyLimit
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {number} limit - The maximum number of async operations at a time.
33 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
34 + * in the collections in parallel.
35 + * The iteratee should complete with a boolean `result` value.
36 + * Invoked with (item, callback).
37 + * @param {Function} [callback] - A callback which is called as soon as any
38 + * iteratee returns `true`, or after all the iteratee functions have finished.
39 + * Result will be either `true` or `false` depending on the values of the async
40 + * tests. Invoked with (err, result).
41 + * @returns {Promise} a promise, if no callback provided
42 + */
43 +function someLimit(coll, limit, iteratee, callback) {
44 + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback);
45 +}
46 +exports.default = (0, _awaitify2.default)(someLimit, 4);
47 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _createTester = require('./internal/createTester.js');
8 +
9 +var _createTester2 = _interopRequireDefault(_createTester);
10 +
11 +var _eachOfSeries = require('./eachOfSeries.js');
12 +
13 +var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.
23 + *
24 + * @name someSeries
25 + * @static
26 + * @memberOf module:Collections
27 + * @method
28 + * @see [async.some]{@link module:Collections.some}
29 + * @alias anySeries
30 + * @category Collection
31 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
32 + * @param {AsyncFunction} iteratee - An async truth test to apply to each item
33 + * in the collections in series.
34 + * The iteratee should complete with a boolean `result` value.
35 + * Invoked with (item, callback).
36 + * @param {Function} [callback] - A callback which is called as soon as any
37 + * iteratee returns `true`, or after all the iteratee functions have finished.
38 + * Result will be either `true` or `false` depending on the values of the async
39 + * tests. Invoked with (err, result).
40 + * @returns {Promise} a promise, if no callback provided
41 + */
42 +function someSeries(coll, iteratee, callback) {
43 + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback);
44 +}
45 +exports.default = (0, _awaitify2.default)(someSeries, 3);
46 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _map = require('./map.js');
8 +
9 +var _map2 = _interopRequireDefault(_map);
10 +
11 +var _wrapAsync = require('./internal/wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Sorts a list by the results of running each `coll` value through an async
23 + * `iteratee`.
24 + *
25 + * @name sortBy
26 + * @static
27 + * @memberOf module:Collections
28 + * @method
29 + * @category Collection
30 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
31 + * @param {AsyncFunction} iteratee - An async function to apply to each item in
32 + * `coll`.
33 + * The iteratee should complete with a value to use as the sort criteria as
34 + * its `result`.
35 + * Invoked with (item, callback).
36 + * @param {Function} callback - A callback which is called after all the
37 + * `iteratee` functions have finished, or an error occurs. Results is the items
38 + * from the original `coll` sorted by the values returned by the `iteratee`
39 + * calls. Invoked with (err, results).
40 + * @returns {Promise} a promise, if no callback passed
41 + * @example
42 + *
43 + * // bigfile.txt is a file that is 251100 bytes in size
44 + * // mediumfile.txt is a file that is 11000 bytes in size
45 + * // smallfile.txt is a file that is 121 bytes in size
46 + *
47 + * // asynchronous function that returns the file size in bytes
48 + * function getFileSizeInBytes(file, callback) {
49 + * fs.stat(file, function(err, stat) {
50 + * if (err) {
51 + * return callback(err);
52 + * }
53 + * callback(null, stat.size);
54 + * });
55 + * }
56 + *
57 + * // Using callbacks
58 + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes,
59 + * function(err, results) {
60 + * if (err) {
61 + * console.log(err);
62 + * } else {
63 + * console.log(results);
64 + * // results is now the original array of files sorted by
65 + * // file size (ascending by default), e.g.
66 + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
67 + * }
68 + * }
69 + * );
70 + *
71 + * // By modifying the callback parameter the
72 + * // sorting order can be influenced:
73 + *
74 + * // ascending order
75 + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) {
76 + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {
77 + * if (getFileSizeErr) return callback(getFileSizeErr);
78 + * callback(null, fileSize);
79 + * });
80 + * }, function(err, results) {
81 + * if (err) {
82 + * console.log(err);
83 + * } else {
84 + * console.log(results);
85 + * // results is now the original array of files sorted by
86 + * // file size (ascending by default), e.g.
87 + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
88 + * }
89 + * }
90 + * );
91 + *
92 + * // descending order
93 + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) {
94 + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {
95 + * if (getFileSizeErr) {
96 + * return callback(getFileSizeErr);
97 + * }
98 + * callback(null, fileSize * -1);
99 + * });
100 + * }, function(err, results) {
101 + * if (err) {
102 + * console.log(err);
103 + * } else {
104 + * console.log(results);
105 + * // results is now the original array of files sorted by
106 + * // file size (ascending by default), e.g.
107 + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt']
108 + * }
109 + * }
110 + * );
111 + *
112 + * // Error handling
113 + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes,
114 + * function(err, results) {
115 + * if (err) {
116 + * console.log(err);
117 + * // [ Error: ENOENT: no such file or directory ]
118 + * } else {
119 + * console.log(results);
120 + * }
121 + * }
122 + * );
123 + *
124 + * // Using Promises
125 + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes)
126 + * .then( results => {
127 + * console.log(results);
128 + * // results is now the original array of files sorted by
129 + * // file size (ascending by default), e.g.
130 + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
131 + * }).catch( err => {
132 + * console.log(err);
133 + * });
134 + *
135 + * // Error handling
136 + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes)
137 + * .then( results => {
138 + * console.log(results);
139 + * }).catch( err => {
140 + * console.log(err);
141 + * // [ Error: ENOENT: no such file or directory ]
142 + * });
143 + *
144 + * // Using async/await
145 + * (async () => {
146 + * try {
147 + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);
148 + * console.log(results);
149 + * // results is now the original array of files sorted by
150 + * // file size (ascending by default), e.g.
151 + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']
152 + * }
153 + * catch (err) {
154 + * console.log(err);
155 + * }
156 + * })();
157 + *
158 + * // Error handling
159 + * async () => {
160 + * try {
161 + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);
162 + * console.log(results);
163 + * }
164 + * catch (err) {
165 + * console.log(err);
166 + * // [ Error: ENOENT: no such file or directory ]
167 + * }
168 + * }
169 + *
170 + */
171 +function sortBy(coll, iteratee, callback) {
172 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
173 + return (0, _map2.default)(coll, (x, iterCb) => {
174 + _iteratee(x, (err, criteria) => {
175 + if (err) return iterCb(err);
176 + iterCb(err, { value: x, criteria });
177 + });
178 + }, (err, results) => {
179 + if (err) return callback(err);
180 + callback(null, results.sort(comparator).map(v => v.value));
181 + });
182 +
183 + function comparator(left, right) {
184 + var a = left.criteria,
185 + b = right.criteria;
186 + return a < b ? -1 : a > b ? 1 : 0;
187 + }
188 +}
189 +exports.default = (0, _awaitify2.default)(sortBy, 3);
190 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = timeout;
7 +
8 +var _initialParams = require('./internal/initialParams.js');
9 +
10 +var _initialParams2 = _interopRequireDefault(_initialParams);
11 +
12 +var _wrapAsync = require('./internal/wrapAsync.js');
13 +
14 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +/**
19 + * Sets a time limit on an asynchronous function. If the function does not call
20 + * its callback within the specified milliseconds, it will be called with a
21 + * timeout error. The code property for the error object will be `'ETIMEDOUT'`.
22 + *
23 + * @name timeout
24 + * @static
25 + * @memberOf module:Utils
26 + * @method
27 + * @category Util
28 + * @param {AsyncFunction} asyncFn - The async function to limit in time.
29 + * @param {number} milliseconds - The specified time limit.
30 + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
31 + * to timeout Error for more information..
32 + * @returns {AsyncFunction} Returns a wrapped function that can be used with any
33 + * of the control flow functions.
34 + * Invoke this function with the same parameters as you would `asyncFunc`.
35 + * @example
36 + *
37 + * function myFunction(foo, callback) {
38 + * doAsyncTask(foo, function(err, data) {
39 + * // handle errors
40 + * if (err) return callback(err);
41 + *
42 + * // do some stuff ...
43 + *
44 + * // return processed data
45 + * return callback(null, data);
46 + * });
47 + * }
48 + *
49 + * var wrapped = async.timeout(myFunction, 1000);
50 + *
51 + * // call `wrapped` as you would `myFunction`
52 + * wrapped({ bar: 'bar' }, function(err, data) {
53 + * // if `myFunction` takes < 1000 ms to execute, `err`
54 + * // and `data` will have their expected values
55 + *
56 + * // else `err` will be an Error with the code 'ETIMEDOUT'
57 + * });
58 + */
59 +function timeout(asyncFn, milliseconds, info) {
60 + var fn = (0, _wrapAsync2.default)(asyncFn);
61 +
62 + return (0, _initialParams2.default)((args, callback) => {
63 + var timedOut = false;
64 + var timer;
65 +
66 + function timeoutCallback() {
67 + var name = asyncFn.name || 'anonymous';
68 + var error = new Error('Callback function "' + name + '" timed out.');
69 + error.code = 'ETIMEDOUT';
70 + if (info) {
71 + error.info = info;
72 + }
73 + timedOut = true;
74 + callback(error);
75 + }
76 +
77 + args.push((...cbArgs) => {
78 + if (!timedOut) {
79 + callback(...cbArgs);
80 + clearTimeout(timer);
81 + }
82 + });
83 +
84 + // setup timer and call original function
85 + timer = setTimeout(timeoutCallback, milliseconds);
86 + fn(...args);
87 + });
88 +}
89 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = times;
7 +
8 +var _timesLimit = require('./timesLimit.js');
9 +
10 +var _timesLimit2 = _interopRequireDefault(_timesLimit);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * Calls the `iteratee` function `n` times, and accumulates results in the same
16 + * manner you would use with [map]{@link module:Collections.map}.
17 + *
18 + * @name times
19 + * @static
20 + * @memberOf module:ControlFlow
21 + * @method
22 + * @see [async.map]{@link module:Collections.map}
23 + * @category Control Flow
24 + * @param {number} n - The number of times to run the function.
25 + * @param {AsyncFunction} iteratee - The async function to call `n` times.
26 + * Invoked with the iteration index and a callback: (n, next).
27 + * @param {Function} callback - see {@link module:Collections.map}.
28 + * @returns {Promise} a promise, if no callback is provided
29 + * @example
30 + *
31 + * // Pretend this is some complicated async factory
32 + * var createUser = function(id, callback) {
33 + * callback(null, {
34 + * id: 'user' + id
35 + * });
36 + * };
37 + *
38 + * // generate 5 users
39 + * async.times(5, function(n, next) {
40 + * createUser(n, function(err, user) {
41 + * next(err, user);
42 + * });
43 + * }, function(err, users) {
44 + * // we should now have 5 users
45 + * });
46 + */
47 +function times(n, iteratee, callback) {
48 + return (0, _timesLimit2.default)(n, Infinity, iteratee, callback);
49 +}
50 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = timesLimit;
7 +
8 +var _mapLimit = require('./mapLimit.js');
9 +
10 +var _mapLimit2 = _interopRequireDefault(_mapLimit);
11 +
12 +var _range = require('./internal/range.js');
13 +
14 +var _range2 = _interopRequireDefault(_range);
15 +
16 +var _wrapAsync = require('./internal/wrapAsync.js');
17 +
18 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
19 +
20 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
21 +
22 +/**
23 + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a
24 + * time.
25 + *
26 + * @name timesLimit
27 + * @static
28 + * @memberOf module:ControlFlow
29 + * @method
30 + * @see [async.times]{@link module:ControlFlow.times}
31 + * @category Control Flow
32 + * @param {number} count - The number of times to run the function.
33 + * @param {number} limit - The maximum number of async operations at a time.
34 + * @param {AsyncFunction} iteratee - The async function to call `n` times.
35 + * Invoked with the iteration index and a callback: (n, next).
36 + * @param {Function} callback - see [async.map]{@link module:Collections.map}.
37 + * @returns {Promise} a promise, if no callback is provided
38 + */
39 +function timesLimit(count, limit, iteratee, callback) {
40 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
41 + return (0, _mapLimit2.default)((0, _range2.default)(count), limit, _iteratee, callback);
42 +}
43 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = timesSeries;
7 +
8 +var _timesLimit = require('./timesLimit.js');
9 +
10 +var _timesLimit2 = _interopRequireDefault(_timesLimit);
11 +
12 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13 +
14 +/**
15 + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.
16 + *
17 + * @name timesSeries
18 + * @static
19 + * @memberOf module:ControlFlow
20 + * @method
21 + * @see [async.times]{@link module:ControlFlow.times}
22 + * @category Control Flow
23 + * @param {number} n - The number of times to run the function.
24 + * @param {AsyncFunction} iteratee - The async function to call `n` times.
25 + * Invoked with the iteration index and a callback: (n, next).
26 + * @param {Function} callback - see {@link module:Collections.map}.
27 + * @returns {Promise} a promise, if no callback is provided
28 + */
29 +function timesSeries(n, iteratee, callback) {
30 + return (0, _timesLimit2.default)(n, 1, iteratee, callback);
31 +}
32 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = transform;
7 +
8 +var _eachOf = require('./eachOf.js');
9 +
10 +var _eachOf2 = _interopRequireDefault(_eachOf);
11 +
12 +var _once = require('./internal/once.js');
13 +
14 +var _once2 = _interopRequireDefault(_once);
15 +
16 +var _wrapAsync = require('./internal/wrapAsync.js');
17 +
18 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
19 +
20 +var _promiseCallback = require('./internal/promiseCallback.js');
21 +
22 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23 +
24 +/**
25 + * A relative of `reduce`. Takes an Object or Array, and iterates over each
26 + * element in parallel, each step potentially mutating an `accumulator` value.
27 + * The type of the accumulator defaults to the type of collection passed in.
28 + *
29 + * @name transform
30 + * @static
31 + * @memberOf module:Collections
32 + * @method
33 + * @category Collection
34 + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
35 + * @param {*} [accumulator] - The initial state of the transform. If omitted,
36 + * it will default to an empty Object or Array, depending on the type of `coll`
37 + * @param {AsyncFunction} iteratee - A function applied to each item in the
38 + * collection that potentially modifies the accumulator.
39 + * Invoked with (accumulator, item, key, callback).
40 + * @param {Function} [callback] - A callback which is called after all the
41 + * `iteratee` functions have finished. Result is the transformed accumulator.
42 + * Invoked with (err, result).
43 + * @returns {Promise} a promise, if no callback provided
44 + * @example
45 + *
46 + * // file1.txt is a file that is 1000 bytes in size
47 + * // file2.txt is a file that is 2000 bytes in size
48 + * // file3.txt is a file that is 3000 bytes in size
49 + *
50 + * // helper function that returns human-readable size format from bytes
51 + * function formatBytes(bytes, decimals = 2) {
52 + * // implementation not included for brevity
53 + * return humanReadbleFilesize;
54 + * }
55 + *
56 + * const fileList = ['file1.txt','file2.txt','file3.txt'];
57 + *
58 + * // asynchronous function that returns the file size, transformed to human-readable format
59 + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.
60 + * function transformFileSize(acc, value, key, callback) {
61 + * fs.stat(value, function(err, stat) {
62 + * if (err) {
63 + * return callback(err);
64 + * }
65 + * acc[key] = formatBytes(stat.size);
66 + * callback(null);
67 + * });
68 + * }
69 + *
70 + * // Using callbacks
71 + * async.transform(fileList, transformFileSize, function(err, result) {
72 + * if(err) {
73 + * console.log(err);
74 + * } else {
75 + * console.log(result);
76 + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]
77 + * }
78 + * });
79 + *
80 + * // Using Promises
81 + * async.transform(fileList, transformFileSize)
82 + * .then(result => {
83 + * console.log(result);
84 + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]
85 + * }).catch(err => {
86 + * console.log(err);
87 + * });
88 + *
89 + * // Using async/await
90 + * (async () => {
91 + * try {
92 + * let result = await async.transform(fileList, transformFileSize);
93 + * console.log(result);
94 + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]
95 + * }
96 + * catch (err) {
97 + * console.log(err);
98 + * }
99 + * })();
100 + *
101 + * @example
102 + *
103 + * // file1.txt is a file that is 1000 bytes in size
104 + * // file2.txt is a file that is 2000 bytes in size
105 + * // file3.txt is a file that is 3000 bytes in size
106 + *
107 + * // helper function that returns human-readable size format from bytes
108 + * function formatBytes(bytes, decimals = 2) {
109 + * // implementation not included for brevity
110 + * return humanReadbleFilesize;
111 + * }
112 + *
113 + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' };
114 + *
115 + * // asynchronous function that returns the file size, transformed to human-readable format
116 + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.
117 + * function transformFileSize(acc, value, key, callback) {
118 + * fs.stat(value, function(err, stat) {
119 + * if (err) {
120 + * return callback(err);
121 + * }
122 + * acc[key] = formatBytes(stat.size);
123 + * callback(null);
124 + * });
125 + * }
126 + *
127 + * // Using callbacks
128 + * async.transform(fileMap, transformFileSize, function(err, result) {
129 + * if(err) {
130 + * console.log(err);
131 + * } else {
132 + * console.log(result);
133 + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
134 + * }
135 + * });
136 + *
137 + * // Using Promises
138 + * async.transform(fileMap, transformFileSize)
139 + * .then(result => {
140 + * console.log(result);
141 + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
142 + * }).catch(err => {
143 + * console.log(err);
144 + * });
145 + *
146 + * // Using async/await
147 + * async () => {
148 + * try {
149 + * let result = await async.transform(fileMap, transformFileSize);
150 + * console.log(result);
151 + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }
152 + * }
153 + * catch (err) {
154 + * console.log(err);
155 + * }
156 + * }
157 + *
158 + */
159 +function transform(coll, accumulator, iteratee, callback) {
160 + if (arguments.length <= 3 && typeof accumulator === 'function') {
161 + callback = iteratee;
162 + iteratee = accumulator;
163 + accumulator = Array.isArray(coll) ? [] : {};
164 + }
165 + callback = (0, _once2.default)(callback || (0, _promiseCallback.promiseCallback)());
166 + var _iteratee = (0, _wrapAsync2.default)(iteratee);
167 +
168 + (0, _eachOf2.default)(coll, (v, k, cb) => {
169 + _iteratee(accumulator, v, k, cb);
170 + }, err => callback(err, accumulator));
171 + return callback[_promiseCallback.PROMISE_SYMBOL];
172 +}
173 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _eachSeries = require('./eachSeries.js');
8 +
9 +var _eachSeries2 = _interopRequireDefault(_eachSeries);
10 +
11 +var _wrapAsync = require('./internal/wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * It runs each task in series but stops whenever any of the functions were
23 + * successful. If one of the tasks were successful, the `callback` will be
24 + * passed the result of the successful task. If all tasks fail, the callback
25 + * will be passed the error and result (if any) of the final attempt.
26 + *
27 + * @name tryEach
28 + * @static
29 + * @memberOf module:ControlFlow
30 + * @method
31 + * @category Control Flow
32 + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to
33 + * run, each function is passed a `callback(err, result)` it must call on
34 + * completion with an error `err` (which can be `null`) and an optional `result`
35 + * value.
36 + * @param {Function} [callback] - An optional callback which is called when one
37 + * of the tasks has succeeded, or all have failed. It receives the `err` and
38 + * `result` arguments of the last attempt at completing the `task`. Invoked with
39 + * (err, results).
40 + * @returns {Promise} a promise, if no callback is passed
41 + * @example
42 + * async.tryEach([
43 + * function getDataFromFirstWebsite(callback) {
44 + * // Try getting the data from the first website
45 + * callback(err, data);
46 + * },
47 + * function getDataFromSecondWebsite(callback) {
48 + * // First website failed,
49 + * // Try getting the data from the backup website
50 + * callback(err, data);
51 + * }
52 + * ],
53 + * // optional callback
54 + * function(err, results) {
55 + * Now do something with the data.
56 + * });
57 + *
58 + */
59 +function tryEach(tasks, callback) {
60 + var error = null;
61 + var result;
62 + return (0, _eachSeries2.default)(tasks, (task, taskCb) => {
63 + (0, _wrapAsync2.default)(task)((err, ...args) => {
64 + if (err === false) return taskCb(err);
65 +
66 + if (args.length < 2) {
67 + [result] = args;
68 + } else {
69 + result = args;
70 + }
71 + error = err;
72 + taskCb(err ? null : {});
73 + });
74 + }, () => callback(error, result));
75 +}
76 +
77 +exports.default = (0, _awaitify2.default)(tryEach);
78 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +"use strict";
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = unmemoize;
7 +/**
8 + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,
9 + * unmemoized form. Handy for testing.
10 + *
11 + * @name unmemoize
12 + * @static
13 + * @memberOf module:Utils
14 + * @method
15 + * @see [async.memoize]{@link module:Utils.memoize}
16 + * @category Util
17 + * @param {AsyncFunction} fn - the memoized function
18 + * @returns {AsyncFunction} a function that calls the original unmemoized function
19 + */
20 +function unmemoize(fn) {
21 + return (...args) => {
22 + return (fn.unmemoized || fn)(...args);
23 + };
24 +}
25 +module.exports = exports["default"];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = until;
7 +
8 +var _whilst = require('./whilst.js');
9 +
10 +var _whilst2 = _interopRequireDefault(_whilst);
11 +
12 +var _wrapAsync = require('./internal/wrapAsync.js');
13 +
14 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
15 +
16 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17 +
18 +/**
19 + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when
20 + * stopped, or an error occurs. `callback` will be passed an error and any
21 + * arguments passed to the final `iteratee`'s callback.
22 + *
23 + * The inverse of [whilst]{@link module:ControlFlow.whilst}.
24 + *
25 + * @name until
26 + * @static
27 + * @memberOf module:ControlFlow
28 + * @method
29 + * @see [async.whilst]{@link module:ControlFlow.whilst}
30 + * @category Control Flow
31 + * @param {AsyncFunction} test - asynchronous truth test to perform before each
32 + * execution of `iteratee`. Invoked with (callback).
33 + * @param {AsyncFunction} iteratee - An async function which is called each time
34 + * `test` fails. Invoked with (callback).
35 + * @param {Function} [callback] - A callback which is called after the test
36 + * function has passed and repeated execution of `iteratee` has stopped. `callback`
37 + * will be passed an error and any arguments passed to the final `iteratee`'s
38 + * callback. Invoked with (err, [results]);
39 + * @returns {Promise} a promise, if a callback is not passed
40 + *
41 + * @example
42 + * const results = []
43 + * let finished = false
44 + * async.until(function test(cb) {
45 + * cb(null, finished)
46 + * }, function iter(next) {
47 + * fetchPage(url, (err, body) => {
48 + * if (err) return next(err)
49 + * results = results.concat(body.objects)
50 + * finished = !!body.next
51 + * next(err)
52 + * })
53 + * }, function done (err) {
54 + * // all pages have been fetched
55 + * })
56 + */
57 +function until(test, iteratee, callback) {
58 + const _test = (0, _wrapAsync2.default)(test);
59 + return (0, _whilst2.default)(cb => _test((err, truth) => cb(err, !truth)), iteratee, callback);
60 +}
61 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _once = require('./internal/once.js');
8 +
9 +var _once2 = _interopRequireDefault(_once);
10 +
11 +var _onlyOnce = require('./internal/onlyOnce.js');
12 +
13 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
14 +
15 +var _wrapAsync = require('./internal/wrapAsync.js');
16 +
17 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
18 +
19 +var _awaitify = require('./internal/awaitify.js');
20 +
21 +var _awaitify2 = _interopRequireDefault(_awaitify);
22 +
23 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
24 +
25 +/**
26 + * Runs the `tasks` array of functions in series, each passing their results to
27 + * the next in the array. However, if any of the `tasks` pass an error to their
28 + * own callback, the next function is not executed, and the main `callback` is
29 + * immediately called with the error.
30 + *
31 + * @name waterfall
32 + * @static
33 + * @memberOf module:ControlFlow
34 + * @method
35 + * @category Control Flow
36 + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}
37 + * to run.
38 + * Each function should complete with any number of `result` values.
39 + * The `result` values will be passed as arguments, in order, to the next task.
40 + * @param {Function} [callback] - An optional callback to run once all the
41 + * functions have completed. This will be passed the results of the last task's
42 + * callback. Invoked with (err, [results]).
43 + * @returns undefined
44 + * @example
45 + *
46 + * async.waterfall([
47 + * function(callback) {
48 + * callback(null, 'one', 'two');
49 + * },
50 + * function(arg1, arg2, callback) {
51 + * // arg1 now equals 'one' and arg2 now equals 'two'
52 + * callback(null, 'three');
53 + * },
54 + * function(arg1, callback) {
55 + * // arg1 now equals 'three'
56 + * callback(null, 'done');
57 + * }
58 + * ], function (err, result) {
59 + * // result now equals 'done'
60 + * });
61 + *
62 + * // Or, with named functions:
63 + * async.waterfall([
64 + * myFirstFunction,
65 + * mySecondFunction,
66 + * myLastFunction,
67 + * ], function (err, result) {
68 + * // result now equals 'done'
69 + * });
70 + * function myFirstFunction(callback) {
71 + * callback(null, 'one', 'two');
72 + * }
73 + * function mySecondFunction(arg1, arg2, callback) {
74 + * // arg1 now equals 'one' and arg2 now equals 'two'
75 + * callback(null, 'three');
76 + * }
77 + * function myLastFunction(arg1, callback) {
78 + * // arg1 now equals 'three'
79 + * callback(null, 'done');
80 + * }
81 + */
82 +function waterfall(tasks, callback) {
83 + callback = (0, _once2.default)(callback);
84 + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));
85 + if (!tasks.length) return callback();
86 + var taskIndex = 0;
87 +
88 + function nextTask(args) {
89 + var task = (0, _wrapAsync2.default)(tasks[taskIndex++]);
90 + task(...args, (0, _onlyOnce2.default)(next));
91 + }
92 +
93 + function next(err, ...args) {
94 + if (err === false) return;
95 + if (err || taskIndex === tasks.length) {
96 + return callback(err, ...args);
97 + }
98 + nextTask(args);
99 + }
100 +
101 + nextTask([]);
102 +}
103 +
104 +exports.default = (0, _awaitify2.default)(waterfall);
105 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +
7 +var _onlyOnce = require('./internal/onlyOnce.js');
8 +
9 +var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
10 +
11 +var _wrapAsync = require('./internal/wrapAsync.js');
12 +
13 +var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
14 +
15 +var _awaitify = require('./internal/awaitify.js');
16 +
17 +var _awaitify2 = _interopRequireDefault(_awaitify);
18 +
19 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
20 +
21 +/**
22 + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
23 + * stopped, or an error occurs.
24 + *
25 + * @name whilst
26 + * @static
27 + * @memberOf module:ControlFlow
28 + * @method
29 + * @category Control Flow
30 + * @param {AsyncFunction} test - asynchronous truth test to perform before each
31 + * execution of `iteratee`. Invoked with ().
32 + * @param {AsyncFunction} iteratee - An async function which is called each time
33 + * `test` passes. Invoked with (callback).
34 + * @param {Function} [callback] - A callback which is called after the test
35 + * function has failed and repeated execution of `iteratee` has stopped. `callback`
36 + * will be passed an error and any arguments passed to the final `iteratee`'s
37 + * callback. Invoked with (err, [results]);
38 + * @returns {Promise} a promise, if no callback is passed
39 + * @example
40 + *
41 + * var count = 0;
42 + * async.whilst(
43 + * function test(cb) { cb(null, count < 5); },
44 + * function iter(callback) {
45 + * count++;
46 + * setTimeout(function() {
47 + * callback(null, count);
48 + * }, 1000);
49 + * },
50 + * function (err, n) {
51 + * // 5 seconds have passed, n = 5
52 + * }
53 + * );
54 + */
55 +function whilst(test, iteratee, callback) {
56 + callback = (0, _onlyOnce2.default)(callback);
57 + var _fn = (0, _wrapAsync2.default)(iteratee);
58 + var _test = (0, _wrapAsync2.default)(test);
59 + var results = [];
60 +
61 + function next(err, ...rest) {
62 + if (err) return callback(err);
63 + results = rest;
64 + if (err === false) return;
65 + _test(check);
66 + }
67 +
68 + function check(err, truth) {
69 + if (err) return callback(err);
70 + if (err === false) return;
71 + if (!truth) return callback(null, ...results);
72 + _fn(next);
73 + }
74 +
75 + return _test(check);
76 +}
77 +exports.default = (0, _awaitify2.default)(whilst, 3);
78 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +Object.defineProperty(exports, "__esModule", {
4 + value: true
5 +});
6 +exports.default = asyncify;
7 +
8 +var _initialParams = require('./internal/initialParams.js');
9 +
10 +var _initialParams2 = _interopRequireDefault(_initialParams);
11 +
12 +var _setImmediate = require('./internal/setImmediate.js');
13 +
14 +var _setImmediate2 = _interopRequireDefault(_setImmediate);
15 +
16 +var _wrapAsync = require('./internal/wrapAsync.js');
17 +
18 +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19 +
20 +/**
21 + * Take a sync function and make it async, passing its return value to a
22 + * callback. This is useful for plugging sync functions into a waterfall,
23 + * series, or other async functions. Any arguments passed to the generated
24 + * function will be passed to the wrapped function (except for the final
25 + * callback argument). Errors thrown will be passed to the callback.
26 + *
27 + * If the function passed to `asyncify` returns a Promise, that promises's
28 + * resolved/rejected state will be used to call the callback, rather than simply
29 + * the synchronous return value.
30 + *
31 + * This also means you can asyncify ES2017 `async` functions.
32 + *
33 + * @name asyncify
34 + * @static
35 + * @memberOf module:Utils
36 + * @method
37 + * @alias wrapSync
38 + * @category Util
39 + * @param {Function} func - The synchronous function, or Promise-returning
40 + * function to convert to an {@link AsyncFunction}.
41 + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
42 + * invoked with `(args..., callback)`.
43 + * @example
44 + *
45 + * // passing a regular synchronous function
46 + * async.waterfall([
47 + * async.apply(fs.readFile, filename, "utf8"),
48 + * async.asyncify(JSON.parse),
49 + * function (data, next) {
50 + * // data is the result of parsing the text.
51 + * // If there was a parsing error, it would have been caught.
52 + * }
53 + * ], callback);
54 + *
55 + * // passing a function returning a promise
56 + * async.waterfall([
57 + * async.apply(fs.readFile, filename, "utf8"),
58 + * async.asyncify(function (contents) {
59 + * return db.model.create(contents);
60 + * }),
61 + * function (model, next) {
62 + * // `model` is the instantiated model object.
63 + * // If there was an error, this function would be skipped.
64 + * }
65 + * ], callback);
66 + *
67 + * // es2017 example, though `asyncify` is not needed if your JS environment
68 + * // supports async functions out of the box
69 + * var q = async.queue(async.asyncify(async function(file) {
70 + * var intermediateStep = await processFile(file);
71 + * return await somePromise(intermediateStep)
72 + * }));
73 + *
74 + * q.push(files);
75 + */
76 +function asyncify(func) {
77 + if ((0, _wrapAsync.isAsync)(func)) {
78 + return function (...args /*, callback*/) {
79 + const callback = args.pop();
80 + const promise = func.apply(this, args);
81 + return handlePromise(promise, callback);
82 + };
83 + }
84 +
85 + return (0, _initialParams2.default)(function (args, callback) {
86 + var result;
87 + try {
88 + result = func.apply(this, args);
89 + } catch (e) {
90 + return callback(e);
91 + }
92 + // if result is Promise object
93 + if (result && typeof result.then === 'function') {
94 + return handlePromise(result, callback);
95 + } else {
96 + callback(null, result);
97 + }
98 + });
99 +}
100 +
101 +function handlePromise(promise, callback) {
102 + return promise.then(value => {
103 + invokeCallback(callback, null, value);
104 + }, err => {
105 + invokeCallback(callback, err && err.message ? err : new Error(err));
106 + });
107 +}
108 +
109 +function invokeCallback(callback, error, value) {
110 + try {
111 + callback(error, value);
112 + } catch (err) {
113 + (0, _setImmediate2.default)(e => {
114 + throw e;
115 + }, err);
116 + }
117 +}
118 +module.exports = exports['default'];
...\ No newline at end of file ...\ No newline at end of file
1 +tidelift: "npm/balanced-match"
2 +patreon: juliangruber
1 +(MIT)
2 +
3 +Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy of
6 +this software and associated documentation files (the "Software"), to deal in
7 +the Software without restriction, including without limitation the rights to
8 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 +of the Software, and to permit persons to whom the Software is furnished to do
10 +so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +SOFTWARE.
1 +# balanced-match
2 +
3 +Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well!
4 +
5 +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match)
6 +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match)
7 +
8 +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match)
9 +
10 +## Example
11 +
12 +Get the first matching pair of braces:
13 +
14 +```js
15 +var balanced = require('balanced-match');
16 +
17 +console.log(balanced('{', '}', 'pre{in{nested}}post'));
18 +console.log(balanced('{', '}', 'pre{first}between{second}post'));
19 +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post'));
20 +```
21 +
22 +The matches are:
23 +
24 +```bash
25 +$ node example.js
26 +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' }
27 +{ start: 3,
28 + end: 9,
29 + pre: 'pre',
30 + body: 'first',
31 + post: 'between{second}post' }
32 +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' }
33 +```
34 +
35 +## API
36 +
37 +### var m = balanced(a, b, str)
38 +
39 +For the first non-nested matching pair of `a` and `b` in `str`, return an
40 +object with those keys:
41 +
42 +* **start** the index of the first match of `a`
43 +* **end** the index of the matching `b`
44 +* **pre** the preamble, `a` and `b` not included
45 +* **body** the match, `a` and `b` not included
46 +* **post** the postscript, `a` and `b` not included
47 +
48 +If there's no match, `undefined` will be returned.
49 +
50 +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`.
51 +
52 +### var r = balanced.range(a, b, str)
53 +
54 +For the first non-nested matching pair of `a` and `b` in `str`, return an
55 +array with indexes: `[ <a index>, <b index> ]`.
56 +
57 +If there's no match, `undefined` will be returned.
58 +
59 +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`.
60 +
61 +## Installation
62 +
63 +With [npm](https://npmjs.org) do:
64 +
65 +```bash
66 +npm install balanced-match
67 +```
68 +
69 +## Security contact information
70 +
71 +To report a security vulnerability, please use the
72 +[Tidelift security contact](https://tidelift.com/security).
73 +Tidelift will coordinate the fix and disclosure.
74 +
75 +## License
76 +
77 +(MIT)
78 +
79 +Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
80 +
81 +Permission is hereby granted, free of charge, to any person obtaining a copy of
82 +this software and associated documentation files (the "Software"), to deal in
83 +the Software without restriction, including without limitation the rights to
84 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
85 +of the Software, and to permit persons to whom the Software is furnished to do
86 +so, subject to the following conditions:
87 +
88 +The above copyright notice and this permission notice shall be included in all
89 +copies or substantial portions of the Software.
90 +
91 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
92 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
93 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
94 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
95 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
96 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
97 +SOFTWARE.
1 +'use strict';
2 +module.exports = balanced;
3 +function balanced(a, b, str) {
4 + if (a instanceof RegExp) a = maybeMatch(a, str);
5 + if (b instanceof RegExp) b = maybeMatch(b, str);
6 +
7 + var r = range(a, b, str);
8 +
9 + return r && {
10 + start: r[0],
11 + end: r[1],
12 + pre: str.slice(0, r[0]),
13 + body: str.slice(r[0] + a.length, r[1]),
14 + post: str.slice(r[1] + b.length)
15 + };
16 +}
17 +
18 +function maybeMatch(reg, str) {
19 + var m = str.match(reg);
20 + return m ? m[0] : null;
21 +}
22 +
23 +balanced.range = range;
24 +function range(a, b, str) {
25 + var begs, beg, left, right, result;
26 + var ai = str.indexOf(a);
27 + var bi = str.indexOf(b, ai + 1);
28 + var i = ai;
29 +
30 + if (ai >= 0 && bi > 0) {
31 + if(a===b) {
32 + return [ai, bi];
33 + }
34 + begs = [];
35 + left = str.length;
36 +
37 + while (i >= 0 && !result) {
38 + if (i == ai) {
39 + begs.push(i);
40 + ai = str.indexOf(a, i + 1);
41 + } else if (begs.length == 1) {
42 + result = [ begs.pop(), bi ];
43 + } else {
44 + beg = begs.pop();
45 + if (beg < left) {
46 + left = beg;
47 + right = bi;
48 + }
49 +
50 + bi = str.indexOf(b, i + 1);
51 + }
52 +
53 + i = ai < bi && ai >= 0 ? ai : bi;
54 + }
55 +
56 + if (begs.length) {
57 + result = [ left, right ];
58 + }
59 + }
60 +
61 + return result;
62 +}
1 +{
2 + "_from": "balanced-match@^1.0.0",
3 + "_id": "balanced-match@1.0.2",
4 + "_inBundle": false,
5 + "_integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
6 + "_location": "/balanced-match",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "balanced-match@^1.0.0",
12 + "name": "balanced-match",
13 + "escapedName": "balanced-match",
14 + "rawSpec": "^1.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "^1.0.0"
17 + },
18 + "_requiredBy": [
19 + "/brace-expansion",
20 + "/minimatch/brace-expansion"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
23 + "_shasum": "e83e3a7e3f300b34cb9d87f615fa0cbf357690ee",
24 + "_spec": "balanced-match@^1.0.0",
25 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\brace-expansion",
26 + "author": {
27 + "name": "Julian Gruber",
28 + "email": "mail@juliangruber.com",
29 + "url": "http://juliangruber.com"
30 + },
31 + "bugs": {
32 + "url": "https://github.com/juliangruber/balanced-match/issues"
33 + },
34 + "bundleDependencies": false,
35 + "deprecated": false,
36 + "description": "Match balanced character pairs, like \"{\" and \"}\"",
37 + "devDependencies": {
38 + "matcha": "^0.7.0",
39 + "tape": "^4.6.0"
40 + },
41 + "homepage": "https://github.com/juliangruber/balanced-match",
42 + "keywords": [
43 + "match",
44 + "regexp",
45 + "test",
46 + "balanced",
47 + "parse"
48 + ],
49 + "license": "MIT",
50 + "main": "index.js",
51 + "name": "balanced-match",
52 + "repository": {
53 + "type": "git",
54 + "url": "git://github.com/juliangruber/balanced-match.git"
55 + },
56 + "scripts": {
57 + "bench": "matcha test/bench.js",
58 + "test": "tape test/test.js"
59 + },
60 + "testling": {
61 + "files": "test/*.js",
62 + "browsers": [
63 + "ie/8..latest",
64 + "firefox/20..latest",
65 + "firefox/nightly",
66 + "chrome/25..latest",
67 + "chrome/canary",
68 + "opera/12..latest",
69 + "opera/next",
70 + "safari/5.1..latest",
71 + "ipad/6.0..latest",
72 + "iphone/6.0..latest",
73 + "android-browser/4.2..latest"
74 + ]
75 + },
76 + "version": "1.0.2"
77 +}
1 +tidelift: "npm/brace-expansion"
2 +patreon: juliangruber
1 +MIT License
2 +
3 +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +SOFTWARE.
1 +# brace-expansion
2 +
3 +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
4 +as known from sh/bash, in JavaScript.
5 +
6 +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
7 +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
8 +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)
9 +
10 +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
11 +
12 +## Example
13 +
14 +```js
15 +var expand = require('brace-expansion');
16 +
17 +expand('file-{a,b,c}.jpg')
18 +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
19 +
20 +expand('-v{,,}')
21 +// => ['-v', '-v', '-v']
22 +
23 +expand('file{0..2}.jpg')
24 +// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
25 +
26 +expand('file-{a..c}.jpg')
27 +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
28 +
29 +expand('file{2..0}.jpg')
30 +// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
31 +
32 +expand('file{0..4..2}.jpg')
33 +// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
34 +
35 +expand('file-{a..e..2}.jpg')
36 +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
37 +
38 +expand('file{00..10..5}.jpg')
39 +// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
40 +
41 +expand('{{A..C},{a..c}}')
42 +// => ['A', 'B', 'C', 'a', 'b', 'c']
43 +
44 +expand('ppp{,config,oe{,conf}}')
45 +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
46 +```
47 +
48 +## API
49 +
50 +```js
51 +var expand = require('brace-expansion');
52 +```
53 +
54 +### var expanded = expand(str)
55 +
56 +Return an array of all possible and valid expansions of `str`. If none are
57 +found, `[str]` is returned.
58 +
59 +Valid expansions are:
60 +
61 +```js
62 +/^(.*,)+(.+)?$/
63 +// {a,b,...}
64 +```
65 +
66 +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
67 +
68 +```js
69 +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
70 +// {x..y[..incr]}
71 +```
72 +
73 +A numeric sequence from `x` to `y` inclusive, with optional increment.
74 +If `x` or `y` start with a leading `0`, all the numbers will be padded
75 +to have equal length. Negative numbers and backwards iteration work too.
76 +
77 +```js
78 +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
79 +// {x..y[..incr]}
80 +```
81 +
82 +An alphabetic sequence from `x` to `y` inclusive, with optional increment.
83 +`x` and `y` must be exactly one character, and if given, `incr` must be a
84 +number.
85 +
86 +For compatibility reasons, the string `${` is not eligible for brace expansion.
87 +
88 +## Installation
89 +
90 +With [npm](https://npmjs.org) do:
91 +
92 +```bash
93 +npm install brace-expansion
94 +```
95 +
96 +## Contributors
97 +
98 +- [Julian Gruber](https://github.com/juliangruber)
99 +- [Isaac Z. Schlueter](https://github.com/isaacs)
100 +
101 +## Sponsors
102 +
103 +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!
104 +
105 +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!
106 +
107 +## Security contact information
108 +
109 +To report a security vulnerability, please use the
110 +[Tidelift security contact](https://tidelift.com/security).
111 +Tidelift will coordinate the fix and disclosure.
112 +
113 +## License
114 +
115 +(MIT)
116 +
117 +Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
118 +
119 +Permission is hereby granted, free of charge, to any person obtaining a copy of
120 +this software and associated documentation files (the "Software"), to deal in
121 +the Software without restriction, including without limitation the rights to
122 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
123 +of the Software, and to permit persons to whom the Software is furnished to do
124 +so, subject to the following conditions:
125 +
126 +The above copyright notice and this permission notice shall be included in all
127 +copies or substantial portions of the Software.
128 +
129 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
130 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
131 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
132 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
133 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
134 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
135 +SOFTWARE.
1 +var balanced = require('balanced-match');
2 +
3 +module.exports = expandTop;
4 +
5 +var escSlash = '\0SLASH'+Math.random()+'\0';
6 +var escOpen = '\0OPEN'+Math.random()+'\0';
7 +var escClose = '\0CLOSE'+Math.random()+'\0';
8 +var escComma = '\0COMMA'+Math.random()+'\0';
9 +var escPeriod = '\0PERIOD'+Math.random()+'\0';
10 +
11 +function numeric(str) {
12 + return parseInt(str, 10) == str
13 + ? parseInt(str, 10)
14 + : str.charCodeAt(0);
15 +}
16 +
17 +function escapeBraces(str) {
18 + return str.split('\\\\').join(escSlash)
19 + .split('\\{').join(escOpen)
20 + .split('\\}').join(escClose)
21 + .split('\\,').join(escComma)
22 + .split('\\.').join(escPeriod);
23 +}
24 +
25 +function unescapeBraces(str) {
26 + return str.split(escSlash).join('\\')
27 + .split(escOpen).join('{')
28 + .split(escClose).join('}')
29 + .split(escComma).join(',')
30 + .split(escPeriod).join('.');
31 +}
32 +
33 +
34 +// Basically just str.split(","), but handling cases
35 +// where we have nested braced sections, which should be
36 +// treated as individual members, like {a,{b,c},d}
37 +function parseCommaParts(str) {
38 + if (!str)
39 + return [''];
40 +
41 + var parts = [];
42 + var m = balanced('{', '}', str);
43 +
44 + if (!m)
45 + return str.split(',');
46 +
47 + var pre = m.pre;
48 + var body = m.body;
49 + var post = m.post;
50 + var p = pre.split(',');
51 +
52 + p[p.length-1] += '{' + body + '}';
53 + var postParts = parseCommaParts(post);
54 + if (post.length) {
55 + p[p.length-1] += postParts.shift();
56 + p.push.apply(p, postParts);
57 + }
58 +
59 + parts.push.apply(parts, p);
60 +
61 + return parts;
62 +}
63 +
64 +function expandTop(str) {
65 + if (!str)
66 + return [];
67 +
68 + // I don't know why Bash 4.3 does this, but it does.
69 + // Anything starting with {} will have the first two bytes preserved
70 + // but *only* at the top level, so {},a}b will not expand to anything,
71 + // but a{},b}c will be expanded to [a}c,abc].
72 + // One could argue that this is a bug in Bash, but since the goal of
73 + // this module is to match Bash's rules, we escape a leading {}
74 + if (str.substr(0, 2) === '{}') {
75 + str = '\\{\\}' + str.substr(2);
76 + }
77 +
78 + return expand(escapeBraces(str), true).map(unescapeBraces);
79 +}
80 +
81 +function embrace(str) {
82 + return '{' + str + '}';
83 +}
84 +function isPadded(el) {
85 + return /^-?0\d/.test(el);
86 +}
87 +
88 +function lte(i, y) {
89 + return i <= y;
90 +}
91 +function gte(i, y) {
92 + return i >= y;
93 +}
94 +
95 +function expand(str, isTop) {
96 + var expansions = [];
97 +
98 + var m = balanced('{', '}', str);
99 + if (!m) return [str];
100 +
101 + // no need to expand pre, since it is guaranteed to be free of brace-sets
102 + var pre = m.pre;
103 + var post = m.post.length
104 + ? expand(m.post, false)
105 + : [''];
106 +
107 + if (/\$$/.test(m.pre)) {
108 + for (var k = 0; k < post.length; k++) {
109 + var expansion = pre+ '{' + m.body + '}' + post[k];
110 + expansions.push(expansion);
111 + }
112 + } else {
113 + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
114 + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
115 + var isSequence = isNumericSequence || isAlphaSequence;
116 + var isOptions = m.body.indexOf(',') >= 0;
117 + if (!isSequence && !isOptions) {
118 + // {a},b}
119 + if (m.post.match(/,.*\}/)) {
120 + str = m.pre + '{' + m.body + escClose + m.post;
121 + return expand(str);
122 + }
123 + return [str];
124 + }
125 +
126 + var n;
127 + if (isSequence) {
128 + n = m.body.split(/\.\./);
129 + } else {
130 + n = parseCommaParts(m.body);
131 + if (n.length === 1) {
132 + // x{{a,b}}y ==> x{a}y x{b}y
133 + n = expand(n[0], false).map(embrace);
134 + if (n.length === 1) {
135 + return post.map(function(p) {
136 + return m.pre + n[0] + p;
137 + });
138 + }
139 + }
140 + }
141 +
142 + // at this point, n is the parts, and we know it's not a comma set
143 + // with a single entry.
144 + var N;
145 +
146 + if (isSequence) {
147 + var x = numeric(n[0]);
148 + var y = numeric(n[1]);
149 + var width = Math.max(n[0].length, n[1].length)
150 + var incr = n.length == 3
151 + ? Math.abs(numeric(n[2]))
152 + : 1;
153 + var test = lte;
154 + var reverse = y < x;
155 + if (reverse) {
156 + incr *= -1;
157 + test = gte;
158 + }
159 + var pad = n.some(isPadded);
160 +
161 + N = [];
162 +
163 + for (var i = x; test(i, y); i += incr) {
164 + var c;
165 + if (isAlphaSequence) {
166 + c = String.fromCharCode(i);
167 + if (c === '\\')
168 + c = '';
169 + } else {
170 + c = String(i);
171 + if (pad) {
172 + var need = width - c.length;
173 + if (need > 0) {
174 + var z = new Array(need + 1).join('0');
175 + if (i < 0)
176 + c = '-' + z + c.slice(1);
177 + else
178 + c = z + c;
179 + }
180 + }
181 + }
182 + N.push(c);
183 + }
184 + } else {
185 + N = [];
186 +
187 + for (var j = 0; j < n.length; j++) {
188 + N.push.apply(N, expand(n[j], false));
189 + }
190 + }
191 +
192 + for (var j = 0; j < N.length; j++) {
193 + for (var k = 0; k < post.length; k++) {
194 + var expansion = pre + N[j] + post[k];
195 + if (!isTop || isSequence || expansion)
196 + expansions.push(expansion);
197 + }
198 + }
199 + }
200 +
201 + return expansions;
202 +}
203 +
1 +{
2 + "_from": "brace-expansion@^2.0.1",
3 + "_id": "brace-expansion@2.0.1",
4 + "_inBundle": false,
5 + "_integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
6 + "_location": "/brace-expansion",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "brace-expansion@^2.0.1",
12 + "name": "brace-expansion",
13 + "escapedName": "brace-expansion",
14 + "rawSpec": "^2.0.1",
15 + "saveSpec": null,
16 + "fetchSpec": "^2.0.1"
17 + },
18 + "_requiredBy": [
19 + "/filelist/minimatch"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
22 + "_shasum": "1edc459e0f0c548486ecf9fc99f2221364b9a0ae",
23 + "_spec": "brace-expansion@^2.0.1",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\filelist\\node_modules\\minimatch",
25 + "author": {
26 + "name": "Julian Gruber",
27 + "email": "mail@juliangruber.com",
28 + "url": "http://juliangruber.com"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/juliangruber/brace-expansion/issues"
32 + },
33 + "bundleDependencies": false,
34 + "dependencies": {
35 + "balanced-match": "^1.0.0"
36 + },
37 + "deprecated": false,
38 + "description": "Brace expansion as known from sh/bash",
39 + "devDependencies": {
40 + "@c4312/matcha": "^1.3.1",
41 + "tape": "^4.6.0"
42 + },
43 + "homepage": "https://github.com/juliangruber/brace-expansion",
44 + "keywords": [],
45 + "license": "MIT",
46 + "main": "index.js",
47 + "name": "brace-expansion",
48 + "repository": {
49 + "type": "git",
50 + "url": "git://github.com/juliangruber/brace-expansion.git"
51 + },
52 + "scripts": {
53 + "bench": "matcha test/perf/bench.js",
54 + "gentest": "bash test/generate.sh",
55 + "test": "tape test/*.js"
56 + },
57 + "testling": {
58 + "files": "test/*.js",
59 + "browsers": [
60 + "ie/8..latest",
61 + "firefox/20..latest",
62 + "firefox/nightly",
63 + "chrome/25..latest",
64 + "chrome/canary",
65 + "opera/12..latest",
66 + "opera/next",
67 + "safari/5.1..latest",
68 + "ipad/6.0..latest",
69 + "iphone/6.0..latest",
70 + "android-browser/4.2..latest"
71 + ]
72 + },
73 + "version": "2.0.1"
74 +}
1 +/**
2 +Basic foreground colors.
3 +
4 +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
5 +*/
6 +declare type ForegroundColor =
7 + | 'black'
8 + | 'red'
9 + | 'green'
10 + | 'yellow'
11 + | 'blue'
12 + | 'magenta'
13 + | 'cyan'
14 + | 'white'
15 + | 'gray'
16 + | 'grey'
17 + | 'blackBright'
18 + | 'redBright'
19 + | 'greenBright'
20 + | 'yellowBright'
21 + | 'blueBright'
22 + | 'magentaBright'
23 + | 'cyanBright'
24 + | 'whiteBright';
25 +
26 +/**
27 +Basic background colors.
28 +
29 +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
30 +*/
31 +declare type BackgroundColor =
32 + | 'bgBlack'
33 + | 'bgRed'
34 + | 'bgGreen'
35 + | 'bgYellow'
36 + | 'bgBlue'
37 + | 'bgMagenta'
38 + | 'bgCyan'
39 + | 'bgWhite'
40 + | 'bgGray'
41 + | 'bgGrey'
42 + | 'bgBlackBright'
43 + | 'bgRedBright'
44 + | 'bgGreenBright'
45 + | 'bgYellowBright'
46 + | 'bgBlueBright'
47 + | 'bgMagentaBright'
48 + | 'bgCyanBright'
49 + | 'bgWhiteBright';
50 +
51 +/**
52 +Basic colors.
53 +
54 +[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
55 +*/
56 +declare type Color = ForegroundColor | BackgroundColor;
57 +
58 +declare type Modifiers =
59 + | 'reset'
60 + | 'bold'
61 + | 'dim'
62 + | 'italic'
63 + | 'underline'
64 + | 'inverse'
65 + | 'hidden'
66 + | 'strikethrough'
67 + | 'visible';
68 +
69 +declare namespace chalk {
70 + /**
71 + Levels:
72 + - `0` - All colors disabled.
73 + - `1` - Basic 16 colors support.
74 + - `2` - ANSI 256 colors support.
75 + - `3` - Truecolor 16 million colors support.
76 + */
77 + type Level = 0 | 1 | 2 | 3;
78 +
79 + interface Options {
80 + /**
81 + Specify the color support for Chalk.
82 +
83 + By default, color support is automatically detected based on the environment.
84 +
85 + Levels:
86 + - `0` - All colors disabled.
87 + - `1` - Basic 16 colors support.
88 + - `2` - ANSI 256 colors support.
89 + - `3` - Truecolor 16 million colors support.
90 + */
91 + level?: Level;
92 + }
93 +
94 + /**
95 + Return a new Chalk instance.
96 + */
97 + type Instance = new (options?: Options) => Chalk;
98 +
99 + /**
100 + Detect whether the terminal supports color.
101 + */
102 + interface ColorSupport {
103 + /**
104 + The color level used by Chalk.
105 + */
106 + level: Level;
107 +
108 + /**
109 + Return whether Chalk supports basic 16 colors.
110 + */
111 + hasBasic: boolean;
112 +
113 + /**
114 + Return whether Chalk supports ANSI 256 colors.
115 + */
116 + has256: boolean;
117 +
118 + /**
119 + Return whether Chalk supports Truecolor 16 million colors.
120 + */
121 + has16m: boolean;
122 + }
123 +
124 + interface ChalkFunction {
125 + /**
126 + Use a template string.
127 +
128 + @remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341))
129 +
130 + @example
131 + ```
132 + import chalk = require('chalk');
133 +
134 + log(chalk`
135 + CPU: {red ${cpu.totalPercent}%}
136 + RAM: {green ${ram.used / ram.total * 100}%}
137 + DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
138 + `);
139 + ```
140 +
141 + @example
142 + ```
143 + import chalk = require('chalk');
144 +
145 + log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`)
146 + ```
147 + */
148 + (text: TemplateStringsArray, ...placeholders: unknown[]): string;
149 +
150 + (...text: unknown[]): string;
151 + }
152 +
153 + interface Chalk extends ChalkFunction {
154 + /**
155 + Return a new Chalk instance.
156 + */
157 + Instance: Instance;
158 +
159 + /**
160 + The color support for Chalk.
161 +
162 + By default, color support is automatically detected based on the environment.
163 +
164 + Levels:
165 + - `0` - All colors disabled.
166 + - `1` - Basic 16 colors support.
167 + - `2` - ANSI 256 colors support.
168 + - `3` - Truecolor 16 million colors support.
169 + */
170 + level: Level;
171 +
172 + /**
173 + Use HEX value to set text color.
174 +
175 + @param color - Hexadecimal value representing the desired color.
176 +
177 + @example
178 + ```
179 + import chalk = require('chalk');
180 +
181 + chalk.hex('#DEADED');
182 + ```
183 + */
184 + hex(color: string): Chalk;
185 +
186 + /**
187 + Use keyword color value to set text color.
188 +
189 + @param color - Keyword value representing the desired color.
190 +
191 + @example
192 + ```
193 + import chalk = require('chalk');
194 +
195 + chalk.keyword('orange');
196 + ```
197 + */
198 + keyword(color: string): Chalk;
199 +
200 + /**
201 + Use RGB values to set text color.
202 + */
203 + rgb(red: number, green: number, blue: number): Chalk;
204 +
205 + /**
206 + Use HSL values to set text color.
207 + */
208 + hsl(hue: number, saturation: number, lightness: number): Chalk;
209 +
210 + /**
211 + Use HSV values to set text color.
212 + */
213 + hsv(hue: number, saturation: number, value: number): Chalk;
214 +
215 + /**
216 + Use HWB values to set text color.
217 + */
218 + hwb(hue: number, whiteness: number, blackness: number): Chalk;
219 +
220 + /**
221 + Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color.
222 +
223 + 30 <= code && code < 38 || 90 <= code && code < 98
224 + For example, 31 for red, 91 for redBright.
225 + */
226 + ansi(code: number): Chalk;
227 +
228 + /**
229 + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
230 + */
231 + ansi256(index: number): Chalk;
232 +
233 + /**
234 + Use HEX value to set background color.
235 +
236 + @param color - Hexadecimal value representing the desired color.
237 +
238 + @example
239 + ```
240 + import chalk = require('chalk');
241 +
242 + chalk.bgHex('#DEADED');
243 + ```
244 + */
245 + bgHex(color: string): Chalk;
246 +
247 + /**
248 + Use keyword color value to set background color.
249 +
250 + @param color - Keyword value representing the desired color.
251 +
252 + @example
253 + ```
254 + import chalk = require('chalk');
255 +
256 + chalk.bgKeyword('orange');
257 + ```
258 + */
259 + bgKeyword(color: string): Chalk;
260 +
261 + /**
262 + Use RGB values to set background color.
263 + */
264 + bgRgb(red: number, green: number, blue: number): Chalk;
265 +
266 + /**
267 + Use HSL values to set background color.
268 + */
269 + bgHsl(hue: number, saturation: number, lightness: number): Chalk;
270 +
271 + /**
272 + Use HSV values to set background color.
273 + */
274 + bgHsv(hue: number, saturation: number, value: number): Chalk;
275 +
276 + /**
277 + Use HWB values to set background color.
278 + */
279 + bgHwb(hue: number, whiteness: number, blackness: number): Chalk;
280 +
281 + /**
282 + Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color.
283 +
284 + 30 <= code && code < 38 || 90 <= code && code < 98
285 + For example, 31 for red, 91 for redBright.
286 + Use the foreground code, not the background code (for example, not 41, nor 101).
287 + */
288 + bgAnsi(code: number): Chalk;
289 +
290 + /**
291 + Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
292 + */
293 + bgAnsi256(index: number): Chalk;
294 +
295 + /**
296 + Modifier: Resets the current color chain.
297 + */
298 + readonly reset: Chalk;
299 +
300 + /**
301 + Modifier: Make text bold.
302 + */
303 + readonly bold: Chalk;
304 +
305 + /**
306 + Modifier: Emitting only a small amount of light.
307 + */
308 + readonly dim: Chalk;
309 +
310 + /**
311 + Modifier: Make text italic. (Not widely supported)
312 + */
313 + readonly italic: Chalk;
314 +
315 + /**
316 + Modifier: Make text underline. (Not widely supported)
317 + */
318 + readonly underline: Chalk;
319 +
320 + /**
321 + Modifier: Inverse background and foreground colors.
322 + */
323 + readonly inverse: Chalk;
324 +
325 + /**
326 + Modifier: Prints the text, but makes it invisible.
327 + */
328 + readonly hidden: Chalk;
329 +
330 + /**
331 + Modifier: Puts a horizontal line through the center of the text. (Not widely supported)
332 + */
333 + readonly strikethrough: Chalk;
334 +
335 + /**
336 + Modifier: Prints the text only when Chalk has a color support level > 0.
337 + Can be useful for things that are purely cosmetic.
338 + */
339 + readonly visible: Chalk;
340 +
341 + readonly black: Chalk;
342 + readonly red: Chalk;
343 + readonly green: Chalk;
344 + readonly yellow: Chalk;
345 + readonly blue: Chalk;
346 + readonly magenta: Chalk;
347 + readonly cyan: Chalk;
348 + readonly white: Chalk;
349 +
350 + /*
351 + Alias for `blackBright`.
352 + */
353 + readonly gray: Chalk;
354 +
355 + /*
356 + Alias for `blackBright`.
357 + */
358 + readonly grey: Chalk;
359 +
360 + readonly blackBright: Chalk;
361 + readonly redBright: Chalk;
362 + readonly greenBright: Chalk;
363 + readonly yellowBright: Chalk;
364 + readonly blueBright: Chalk;
365 + readonly magentaBright: Chalk;
366 + readonly cyanBright: Chalk;
367 + readonly whiteBright: Chalk;
368 +
369 + readonly bgBlack: Chalk;
370 + readonly bgRed: Chalk;
371 + readonly bgGreen: Chalk;
372 + readonly bgYellow: Chalk;
373 + readonly bgBlue: Chalk;
374 + readonly bgMagenta: Chalk;
375 + readonly bgCyan: Chalk;
376 + readonly bgWhite: Chalk;
377 +
378 + /*
379 + Alias for `bgBlackBright`.
380 + */
381 + readonly bgGray: Chalk;
382 +
383 + /*
384 + Alias for `bgBlackBright`.
385 + */
386 + readonly bgGrey: Chalk;
387 +
388 + readonly bgBlackBright: Chalk;
389 + readonly bgRedBright: Chalk;
390 + readonly bgGreenBright: Chalk;
391 + readonly bgYellowBright: Chalk;
392 + readonly bgBlueBright: Chalk;
393 + readonly bgMagentaBright: Chalk;
394 + readonly bgCyanBright: Chalk;
395 + readonly bgWhiteBright: Chalk;
396 + }
397 +}
398 +
399 +/**
400 +Main Chalk object that allows to chain styles together.
401 +Call the last one as a method with a string argument.
402 +Order doesn't matter, and later styles take precedent in case of a conflict.
403 +This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
404 +*/
405 +declare const chalk: chalk.Chalk & chalk.ChalkFunction & {
406 + supportsColor: chalk.ColorSupport | false;
407 + Level: chalk.Level;
408 + Color: Color;
409 + ForegroundColor: ForegroundColor;
410 + BackgroundColor: BackgroundColor;
411 + Modifiers: Modifiers;
412 + stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false};
413 +};
414 +
415 +export = chalk;
1 +MIT License
2 +
3 +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
4 +
5 +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:
6 +
7 +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 +
9 +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.
1 +{
2 + "_from": "chalk@^4.0.2",
3 + "_id": "chalk@4.1.2",
4 + "_inBundle": false,
5 + "_integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
6 + "_location": "/chalk",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "chalk@^4.0.2",
12 + "name": "chalk",
13 + "escapedName": "chalk",
14 + "rawSpec": "^4.0.2",
15 + "saveSpec": null,
16 + "fetchSpec": "^4.0.2"
17 + },
18 + "_requiredBy": [
19 + "/jake"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
22 + "_shasum": "aac4e2b7734a740867aeb16bf02aad556a1e7a01",
23 + "_spec": "chalk@^4.0.2",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\jake",
25 + "bugs": {
26 + "url": "https://github.com/chalk/chalk/issues"
27 + },
28 + "bundleDependencies": false,
29 + "dependencies": {
30 + "ansi-styles": "^4.1.0",
31 + "supports-color": "^7.1.0"
32 + },
33 + "deprecated": false,
34 + "description": "Terminal string styling done right",
35 + "devDependencies": {
36 + "ava": "^2.4.0",
37 + "coveralls": "^3.0.7",
38 + "execa": "^4.0.0",
39 + "import-fresh": "^3.1.0",
40 + "matcha": "^0.7.0",
41 + "nyc": "^15.0.0",
42 + "resolve-from": "^5.0.0",
43 + "tsd": "^0.7.4",
44 + "xo": "^0.28.2"
45 + },
46 + "engines": {
47 + "node": ">=10"
48 + },
49 + "files": [
50 + "source",
51 + "index.d.ts"
52 + ],
53 + "funding": "https://github.com/chalk/chalk?sponsor=1",
54 + "homepage": "https://github.com/chalk/chalk#readme",
55 + "keywords": [
56 + "color",
57 + "colour",
58 + "colors",
59 + "terminal",
60 + "console",
61 + "cli",
62 + "string",
63 + "str",
64 + "ansi",
65 + "style",
66 + "styles",
67 + "tty",
68 + "formatting",
69 + "rgb",
70 + "256",
71 + "shell",
72 + "xterm",
73 + "log",
74 + "logging",
75 + "command-line",
76 + "text"
77 + ],
78 + "license": "MIT",
79 + "main": "source",
80 + "name": "chalk",
81 + "repository": {
82 + "type": "git",
83 + "url": "git+https://github.com/chalk/chalk.git"
84 + },
85 + "scripts": {
86 + "bench": "matcha benchmark.js",
87 + "test": "xo && nyc ava && tsd"
88 + },
89 + "version": "4.1.2",
90 + "xo": {
91 + "rules": {
92 + "unicorn/prefer-string-slice": "off",
93 + "unicorn/prefer-includes": "off",
94 + "@typescript-eslint/member-ordering": "off",
95 + "no-redeclare": "off",
96 + "unicorn/string-content": "off",
97 + "unicorn/better-regex": "off"
98 + }
99 + }
100 +}
1 +<h1 align="center">
2 + <br>
3 + <br>
4 + <img width="320" src="media/logo.svg" alt="Chalk">
5 + <br>
6 + <br>
7 + <br>
8 +</h1>
9 +
10 +> Terminal string styling done right
11 +
12 +[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk)
13 +
14 +<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
15 +
16 +<br>
17 +
18 +---
19 +
20 +<div align="center">
21 + <p>
22 + <p>
23 + <sup>
24 + Sindre Sorhus' open source work is supported by the community on <a href="https://github.com/sponsors/sindresorhus">GitHub Sponsors</a> and <a href="https://stakes.social/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15">Dev</a>
25 + </sup>
26 + </p>
27 + <sup>Special thanks to:</sup>
28 + <br>
29 + <br>
30 + <a href="https://standardresume.co/tech">
31 + <img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="160"/>
32 + </a>
33 + <br>
34 + <br>
35 + <a href="https://retool.com/?utm_campaign=sindresorhus">
36 + <img src="https://sindresorhus.com/assets/thanks/retool-logo.svg" width="230"/>
37 + </a>
38 + <br>
39 + <br>
40 + <a href="https://doppler.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=chalk&utm_source=github">
41 + <div>
42 + <img src="https://dashboard.doppler.com/imgs/logo-long.svg" width="240" alt="Doppler">
43 + </div>
44 + <b>All your environment variables, in one place</b>
45 + <div>
46 + <span>Stop struggling with scattered API keys, hacking together home-brewed tools,</span>
47 + <br>
48 + <span>and avoiding access controls. Keep your team and servers in sync with Doppler.</span>
49 + </div>
50 + </a>
51 + <br>
52 + <a href="https://uibakery.io/?utm_source=chalk&utm_medium=sponsor&utm_campaign=github">
53 + <div>
54 + <img src="https://sindresorhus.com/assets/thanks/uibakery-logo.jpg" width="270" alt="UI Bakery">
55 + </div>
56 + </a>
57 + </p>
58 +</div>
59 +
60 +---
61 +
62 +<br>
63 +
64 +## Highlights
65 +
66 +- Expressive API
67 +- Highly performant
68 +- Ability to nest styles
69 +- [256/Truecolor color support](#256-and-truecolor-color-support)
70 +- Auto-detects color support
71 +- Doesn't extend `String.prototype`
72 +- Clean and focused
73 +- Actively maintained
74 +- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020
75 +
76 +## Install
77 +
78 +```console
79 +$ npm install chalk
80 +```
81 +
82 +## Usage
83 +
84 +```js
85 +const chalk = require('chalk');
86 +
87 +console.log(chalk.blue('Hello world!'));
88 +```
89 +
90 +Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
91 +
92 +```js
93 +const chalk = require('chalk');
94 +const log = console.log;
95 +
96 +// Combine styled and normal strings
97 +log(chalk.blue('Hello') + ' World' + chalk.red('!'));
98 +
99 +// Compose multiple styles using the chainable API
100 +log(chalk.blue.bgRed.bold('Hello world!'));
101 +
102 +// Pass in multiple arguments
103 +log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
104 +
105 +// Nest styles
106 +log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
107 +
108 +// Nest styles of the same type even (color, underline, background)
109 +log(chalk.green(
110 + 'I am a green line ' +
111 + chalk.blue.underline.bold('with a blue substring') +
112 + ' that becomes green again!'
113 +));
114 +
115 +// ES2015 template literal
116 +log(`
117 +CPU: ${chalk.red('90%')}
118 +RAM: ${chalk.green('40%')}
119 +DISK: ${chalk.yellow('70%')}
120 +`);
121 +
122 +// ES2015 tagged template literal
123 +log(chalk`
124 +CPU: {red ${cpu.totalPercent}%}
125 +RAM: {green ${ram.used / ram.total * 100}%}
126 +DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
127 +`);
128 +
129 +// Use RGB colors in terminal emulators that support it.
130 +log(chalk.keyword('orange')('Yay for orange colored text!'));
131 +log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
132 +log(chalk.hex('#DEADED').bold('Bold gray!'));
133 +```
134 +
135 +Easily define your own themes:
136 +
137 +```js
138 +const chalk = require('chalk');
139 +
140 +const error = chalk.bold.red;
141 +const warning = chalk.keyword('orange');
142 +
143 +console.log(error('Error!'));
144 +console.log(warning('Warning!'));
145 +```
146 +
147 +Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
148 +
149 +```js
150 +const name = 'Sindre';
151 +console.log(chalk.green('Hello %s'), name);
152 +//=> 'Hello Sindre'
153 +```
154 +
155 +## API
156 +
157 +### chalk.`<style>[.<style>...](string, [string...])`
158 +
159 +Example: `chalk.red.bold.underline('Hello', 'world');`
160 +
161 +Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
162 +
163 +Multiple arguments will be separated by space.
164 +
165 +### chalk.level
166 +
167 +Specifies the level of color support.
168 +
169 +Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
170 +
171 +If you need to change this in a reusable module, create a new instance:
172 +
173 +```js
174 +const ctx = new chalk.Instance({level: 0});
175 +```
176 +
177 +| Level | Description |
178 +| :---: | :--- |
179 +| `0` | All colors disabled |
180 +| `1` | Basic color support (16 colors) |
181 +| `2` | 256 color support |
182 +| `3` | Truecolor support (16 million colors) |
183 +
184 +### chalk.supportsColor
185 +
186 +Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
187 +
188 +Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
189 +
190 +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
191 +
192 +### chalk.stderr and chalk.stderr.supportsColor
193 +
194 +`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience.
195 +
196 +## Styles
197 +
198 +### Modifiers
199 +
200 +- `reset` - Resets the current color chain.
201 +- `bold` - Make text bold.
202 +- `dim` - Emitting only a small amount of light.
203 +- `italic` - Make text italic. *(Not widely supported)*
204 +- `underline` - Make text underline. *(Not widely supported)*
205 +- `inverse`- Inverse background and foreground colors.
206 +- `hidden` - Prints the text, but makes it invisible.
207 +- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
208 +- `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.
209 +
210 +### Colors
211 +
212 +- `black`
213 +- `red`
214 +- `green`
215 +- `yellow`
216 +- `blue`
217 +- `magenta`
218 +- `cyan`
219 +- `white`
220 +- `blackBright` (alias: `gray`, `grey`)
221 +- `redBright`
222 +- `greenBright`
223 +- `yellowBright`
224 +- `blueBright`
225 +- `magentaBright`
226 +- `cyanBright`
227 +- `whiteBright`
228 +
229 +### Background colors
230 +
231 +- `bgBlack`
232 +- `bgRed`
233 +- `bgGreen`
234 +- `bgYellow`
235 +- `bgBlue`
236 +- `bgMagenta`
237 +- `bgCyan`
238 +- `bgWhite`
239 +- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
240 +- `bgRedBright`
241 +- `bgGreenBright`
242 +- `bgYellowBright`
243 +- `bgBlueBright`
244 +- `bgMagentaBright`
245 +- `bgCyanBright`
246 +- `bgWhiteBright`
247 +
248 +## Tagged template literal
249 +
250 +Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
251 +
252 +```js
253 +const chalk = require('chalk');
254 +
255 +const miles = 18;
256 +const calculateFeet = miles => miles * 5280;
257 +
258 +console.log(chalk`
259 + There are {bold 5280 feet} in a mile.
260 + In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
261 +`);
262 +```
263 +
264 +Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
265 +
266 +Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent:
267 +
268 +```js
269 +console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
270 +console.log(chalk.bold.rgb(10, 100, 200)`Hello!`);
271 +console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
272 +```
273 +
274 +Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
275 +
276 +All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
277 +
278 +## 256 and Truecolor color support
279 +
280 +Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
281 +
282 +Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
283 +
284 +Examples:
285 +
286 +- `chalk.hex('#DEADED').underline('Hello, world!')`
287 +- `chalk.keyword('orange')('Some orange text')`
288 +- `chalk.rgb(15, 100, 204).inverse('Hello!')`
289 +
290 +Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
291 +
292 +- `chalk.bgHex('#DEADED').underline('Hello, world!')`
293 +- `chalk.bgKeyword('orange')('Some orange text')`
294 +- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
295 +
296 +The following color models can be used:
297 +
298 +- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
299 +- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
300 +- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
301 +- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
302 +- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
303 +- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
304 +- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
305 +- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
306 +
307 +## Windows
308 +
309 +If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
310 +
311 +## Origin story
312 +
313 +[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
314 +
315 +## chalk for enterprise
316 +
317 +Available as part of the Tidelift Subscription.
318 +
319 +The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
320 +
321 +## Related
322 +
323 +- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
324 +- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
325 +- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
326 +- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
327 +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
328 +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
329 +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
330 +- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
331 +- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
332 +- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
333 +- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
334 +- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
335 +- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
336 +- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
337 +
338 +## Maintainers
339 +
340 +- [Sindre Sorhus](https://github.com/sindresorhus)
341 +- [Josh Junon](https://github.com/qix-)
1 +'use strict';
2 +const ansiStyles = require('ansi-styles');
3 +const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color');
4 +const {
5 + stringReplaceAll,
6 + stringEncaseCRLFWithFirstIndex
7 +} = require('./util');
8 +
9 +const {isArray} = Array;
10 +
11 +// `supportsColor.level` → `ansiStyles.color[name]` mapping
12 +const levelMapping = [
13 + 'ansi',
14 + 'ansi',
15 + 'ansi256',
16 + 'ansi16m'
17 +];
18 +
19 +const styles = Object.create(null);
20 +
21 +const applyOptions = (object, options = {}) => {
22 + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
23 + throw new Error('The `level` option should be an integer from 0 to 3');
24 + }
25 +
26 + // Detect level if not set manually
27 + const colorLevel = stdoutColor ? stdoutColor.level : 0;
28 + object.level = options.level === undefined ? colorLevel : options.level;
29 +};
30 +
31 +class ChalkClass {
32 + constructor(options) {
33 + // eslint-disable-next-line no-constructor-return
34 + return chalkFactory(options);
35 + }
36 +}
37 +
38 +const chalkFactory = options => {
39 + const chalk = {};
40 + applyOptions(chalk, options);
41 +
42 + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
43 +
44 + Object.setPrototypeOf(chalk, Chalk.prototype);
45 + Object.setPrototypeOf(chalk.template, chalk);
46 +
47 + chalk.template.constructor = () => {
48 + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
49 + };
50 +
51 + chalk.template.Instance = ChalkClass;
52 +
53 + return chalk.template;
54 +};
55 +
56 +function Chalk(options) {
57 + return chalkFactory(options);
58 +}
59 +
60 +for (const [styleName, style] of Object.entries(ansiStyles)) {
61 + styles[styleName] = {
62 + get() {
63 + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
64 + Object.defineProperty(this, styleName, {value: builder});
65 + return builder;
66 + }
67 + };
68 +}
69 +
70 +styles.visible = {
71 + get() {
72 + const builder = createBuilder(this, this._styler, true);
73 + Object.defineProperty(this, 'visible', {value: builder});
74 + return builder;
75 + }
76 +};
77 +
78 +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
79 +
80 +for (const model of usedModels) {
81 + styles[model] = {
82 + get() {
83 + const {level} = this;
84 + return function (...arguments_) {
85 + const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
86 + return createBuilder(this, styler, this._isEmpty);
87 + };
88 + }
89 + };
90 +}
91 +
92 +for (const model of usedModels) {
93 + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
94 + styles[bgModel] = {
95 + get() {
96 + const {level} = this;
97 + return function (...arguments_) {
98 + const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
99 + return createBuilder(this, styler, this._isEmpty);
100 + };
101 + }
102 + };
103 +}
104 +
105 +const proto = Object.defineProperties(() => {}, {
106 + ...styles,
107 + level: {
108 + enumerable: true,
109 + get() {
110 + return this._generator.level;
111 + },
112 + set(level) {
113 + this._generator.level = level;
114 + }
115 + }
116 +});
117 +
118 +const createStyler = (open, close, parent) => {
119 + let openAll;
120 + let closeAll;
121 + if (parent === undefined) {
122 + openAll = open;
123 + closeAll = close;
124 + } else {
125 + openAll = parent.openAll + open;
126 + closeAll = close + parent.closeAll;
127 + }
128 +
129 + return {
130 + open,
131 + close,
132 + openAll,
133 + closeAll,
134 + parent
135 + };
136 +};
137 +
138 +const createBuilder = (self, _styler, _isEmpty) => {
139 + const builder = (...arguments_) => {
140 + if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
141 + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
142 + return applyStyle(builder, chalkTag(builder, ...arguments_));
143 + }
144 +
145 + // Single argument is hot path, implicit coercion is faster than anything
146 + // eslint-disable-next-line no-implicit-coercion
147 + return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
148 + };
149 +
150 + // We alter the prototype because we must return a function, but there is
151 + // no way to create a function with a different prototype
152 + Object.setPrototypeOf(builder, proto);
153 +
154 + builder._generator = self;
155 + builder._styler = _styler;
156 + builder._isEmpty = _isEmpty;
157 +
158 + return builder;
159 +};
160 +
161 +const applyStyle = (self, string) => {
162 + if (self.level <= 0 || !string) {
163 + return self._isEmpty ? '' : string;
164 + }
165 +
166 + let styler = self._styler;
167 +
168 + if (styler === undefined) {
169 + return string;
170 + }
171 +
172 + const {openAll, closeAll} = styler;
173 + if (string.indexOf('\u001B') !== -1) {
174 + while (styler !== undefined) {
175 + // Replace any instances already present with a re-opening code
176 + // otherwise only the part of the string until said closing code
177 + // will be colored, and the rest will simply be 'plain'.
178 + string = stringReplaceAll(string, styler.close, styler.open);
179 +
180 + styler = styler.parent;
181 + }
182 + }
183 +
184 + // We can move both next actions out of loop, because remaining actions in loop won't have
185 + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
186 + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
187 + const lfIndex = string.indexOf('\n');
188 + if (lfIndex !== -1) {
189 + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
190 + }
191 +
192 + return openAll + string + closeAll;
193 +};
194 +
195 +let template;
196 +const chalkTag = (chalk, ...strings) => {
197 + const [firstString] = strings;
198 +
199 + if (!isArray(firstString) || !isArray(firstString.raw)) {
200 + // If chalk() was called by itself or with a string,
201 + // return the string itself as a string.
202 + return strings.join(' ');
203 + }
204 +
205 + const arguments_ = strings.slice(1);
206 + const parts = [firstString.raw[0]];
207 +
208 + for (let i = 1; i < firstString.length; i++) {
209 + parts.push(
210 + String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
211 + String(firstString.raw[i])
212 + );
213 + }
214 +
215 + if (template === undefined) {
216 + template = require('./templates');
217 + }
218 +
219 + return template(chalk, parts.join(''));
220 +};
221 +
222 +Object.defineProperties(Chalk.prototype, styles);
223 +
224 +const chalk = Chalk(); // eslint-disable-line new-cap
225 +chalk.supportsColor = stdoutColor;
226 +chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
227 +chalk.stderr.supportsColor = stderrColor;
228 +
229 +module.exports = chalk;
1 +'use strict';
2 +const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
3 +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
4 +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
5 +const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
6 +
7 +const ESCAPES = new Map([
8 + ['n', '\n'],
9 + ['r', '\r'],
10 + ['t', '\t'],
11 + ['b', '\b'],
12 + ['f', '\f'],
13 + ['v', '\v'],
14 + ['0', '\0'],
15 + ['\\', '\\'],
16 + ['e', '\u001B'],
17 + ['a', '\u0007']
18 +]);
19 +
20 +function unescape(c) {
21 + const u = c[0] === 'u';
22 + const bracket = c[1] === '{';
23 +
24 + if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
25 + return String.fromCharCode(parseInt(c.slice(1), 16));
26 + }
27 +
28 + if (u && bracket) {
29 + return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
30 + }
31 +
32 + return ESCAPES.get(c) || c;
33 +}
34 +
35 +function parseArguments(name, arguments_) {
36 + const results = [];
37 + const chunks = arguments_.trim().split(/\s*,\s*/g);
38 + let matches;
39 +
40 + for (const chunk of chunks) {
41 + const number = Number(chunk);
42 + if (!Number.isNaN(number)) {
43 + results.push(number);
44 + } else if ((matches = chunk.match(STRING_REGEX))) {
45 + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
46 + } else {
47 + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
48 + }
49 + }
50 +
51 + return results;
52 +}
53 +
54 +function parseStyle(style) {
55 + STYLE_REGEX.lastIndex = 0;
56 +
57 + const results = [];
58 + let matches;
59 +
60 + while ((matches = STYLE_REGEX.exec(style)) !== null) {
61 + const name = matches[1];
62 +
63 + if (matches[2]) {
64 + const args = parseArguments(name, matches[2]);
65 + results.push([name].concat(args));
66 + } else {
67 + results.push([name]);
68 + }
69 + }
70 +
71 + return results;
72 +}
73 +
74 +function buildStyle(chalk, styles) {
75 + const enabled = {};
76 +
77 + for (const layer of styles) {
78 + for (const style of layer.styles) {
79 + enabled[style[0]] = layer.inverse ? null : style.slice(1);
80 + }
81 + }
82 +
83 + let current = chalk;
84 + for (const [styleName, styles] of Object.entries(enabled)) {
85 + if (!Array.isArray(styles)) {
86 + continue;
87 + }
88 +
89 + if (!(styleName in current)) {
90 + throw new Error(`Unknown Chalk style: ${styleName}`);
91 + }
92 +
93 + current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
94 + }
95 +
96 + return current;
97 +}
98 +
99 +module.exports = (chalk, temporary) => {
100 + const styles = [];
101 + const chunks = [];
102 + let chunk = [];
103 +
104 + // eslint-disable-next-line max-params
105 + temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
106 + if (escapeCharacter) {
107 + chunk.push(unescape(escapeCharacter));
108 + } else if (style) {
109 + const string = chunk.join('');
110 + chunk = [];
111 + chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
112 + styles.push({inverse, styles: parseStyle(style)});
113 + } else if (close) {
114 + if (styles.length === 0) {
115 + throw new Error('Found extraneous } in Chalk template literal');
116 + }
117 +
118 + chunks.push(buildStyle(chalk, styles)(chunk.join('')));
119 + chunk = [];
120 + styles.pop();
121 + } else {
122 + chunk.push(character);
123 + }
124 + });
125 +
126 + chunks.push(chunk.join(''));
127 +
128 + if (styles.length > 0) {
129 + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
130 + throw new Error(errMessage);
131 + }
132 +
133 + return chunks.join('');
134 +};
1 +'use strict';
2 +
3 +const stringReplaceAll = (string, substring, replacer) => {
4 + let index = string.indexOf(substring);
5 + if (index === -1) {
6 + return string;
7 + }
8 +
9 + const substringLength = substring.length;
10 + let endIndex = 0;
11 + let returnValue = '';
12 + do {
13 + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
14 + endIndex = index + substringLength;
15 + index = string.indexOf(substring, endIndex);
16 + } while (index !== -1);
17 +
18 + returnValue += string.substr(endIndex);
19 + return returnValue;
20 +};
21 +
22 +const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
23 + let endIndex = 0;
24 + let returnValue = '';
25 + do {
26 + const gotCR = string[index - 1] === '\r';
27 + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
28 + endIndex = index + 1;
29 + index = string.indexOf('\n', endIndex);
30 + } while (index !== -1);
31 +
32 + returnValue += string.substr(endIndex);
33 + return returnValue;
34 +};
35 +
36 +module.exports = {
37 + stringReplaceAll,
38 + stringEncaseCRLFWithFirstIndex
39 +};
1 +# 1.0.0 - 2016-01-07
2 +
3 +- Removed: unused speed test
4 +- Added: Automatic routing between previously unsupported conversions
5 +([#27](https://github.com/Qix-/color-convert/pull/27))
6 +- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions
7 +([#27](https://github.com/Qix-/color-convert/pull/27))
8 +- Removed: `convert()` class
9 +([#27](https://github.com/Qix-/color-convert/pull/27))
10 +- Changed: all functions to lookup dictionary
11 +([#27](https://github.com/Qix-/color-convert/pull/27))
12 +- Changed: `ansi` to `ansi256`
13 +([#27](https://github.com/Qix-/color-convert/pull/27))
14 +- Fixed: argument grouping for functions requiring only one argument
15 +([#27](https://github.com/Qix-/color-convert/pull/27))
16 +
17 +# 0.6.0 - 2015-07-23
18 +
19 +- Added: methods to handle
20 +[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors:
21 + - rgb2ansi16
22 + - rgb2ansi
23 + - hsl2ansi16
24 + - hsl2ansi
25 + - hsv2ansi16
26 + - hsv2ansi
27 + - hwb2ansi16
28 + - hwb2ansi
29 + - cmyk2ansi16
30 + - cmyk2ansi
31 + - keyword2ansi16
32 + - keyword2ansi
33 + - ansi162rgb
34 + - ansi162hsl
35 + - ansi162hsv
36 + - ansi162hwb
37 + - ansi162cmyk
38 + - ansi162keyword
39 + - ansi2rgb
40 + - ansi2hsl
41 + - ansi2hsv
42 + - ansi2hwb
43 + - ansi2cmyk
44 + - ansi2keyword
45 +([#18](https://github.com/harthur/color-convert/pull/18))
46 +
47 +# 0.5.3 - 2015-06-02
48 +
49 +- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]`
50 +([#15](https://github.com/harthur/color-convert/issues/15))
51 +
52 +---
53 +
54 +Check out commit logs for older releases
1 +Copyright (c) 2011-2016 Heather Arthur <fayearthur@gmail.com>
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining
4 +a copy of this software and associated documentation files (the
5 +"Software"), to deal in the Software without restriction, including
6 +without limitation the rights to use, copy, modify, merge, publish,
7 +distribute, sublicense, and/or sell copies of the Software, and to
8 +permit persons to whom the Software is furnished to do so, subject to
9 +the following conditions:
10 +
11 +The above copyright notice and this permission notice shall be
12 +included in all copies or substantial portions of the Software.
13 +
14 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18 +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19 +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
1 +# color-convert
2 +
3 +[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert)
4 +
5 +Color-convert is a color conversion library for JavaScript and node.
6 +It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest):
7 +
8 +```js
9 +var convert = require('color-convert');
10 +
11 +convert.rgb.hsl(140, 200, 100); // [96, 48, 59]
12 +convert.keyword.rgb('blue'); // [0, 0, 255]
13 +
14 +var rgbChannels = convert.rgb.channels; // 3
15 +var cmykChannels = convert.cmyk.channels; // 4
16 +var ansiChannels = convert.ansi16.channels; // 1
17 +```
18 +
19 +# Install
20 +
21 +```console
22 +$ npm install color-convert
23 +```
24 +
25 +# API
26 +
27 +Simply get the property of the _from_ and _to_ conversion that you're looking for.
28 +
29 +All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function.
30 +
31 +All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha).
32 +
33 +```js
34 +var convert = require('color-convert');
35 +
36 +// Hex to LAB
37 +convert.hex.lab('DEADBF'); // [ 76, 21, -2 ]
38 +convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ]
39 +
40 +// RGB to CMYK
41 +convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ]
42 +convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ]
43 +```
44 +
45 +### Arrays
46 +All functions that accept multiple arguments also support passing an array.
47 +
48 +Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.)
49 +
50 +```js
51 +var convert = require('color-convert');
52 +
53 +convert.rgb.hex(123, 45, 67); // '7B2D43'
54 +convert.rgb.hex([123, 45, 67]); // '7B2D43'
55 +```
56 +
57 +## Routing
58 +
59 +Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex).
60 +
61 +Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js).
62 +
63 +# Contribute
64 +
65 +If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request.
66 +
67 +# License
68 +Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE).
1 +/* MIT license */
2 +/* eslint-disable no-mixed-operators */
3 +const cssKeywords = require('color-name');
4 +
5 +// NOTE: conversions should only return primitive values (i.e. arrays, or
6 +// values that give correct `typeof` results).
7 +// do not use box values types (i.e. Number(), String(), etc.)
8 +
9 +const reverseKeywords = {};
10 +for (const key of Object.keys(cssKeywords)) {
11 + reverseKeywords[cssKeywords[key]] = key;
12 +}
13 +
14 +const convert = {
15 + rgb: {channels: 3, labels: 'rgb'},
16 + hsl: {channels: 3, labels: 'hsl'},
17 + hsv: {channels: 3, labels: 'hsv'},
18 + hwb: {channels: 3, labels: 'hwb'},
19 + cmyk: {channels: 4, labels: 'cmyk'},
20 + xyz: {channels: 3, labels: 'xyz'},
21 + lab: {channels: 3, labels: 'lab'},
22 + lch: {channels: 3, labels: 'lch'},
23 + hex: {channels: 1, labels: ['hex']},
24 + keyword: {channels: 1, labels: ['keyword']},
25 + ansi16: {channels: 1, labels: ['ansi16']},
26 + ansi256: {channels: 1, labels: ['ansi256']},
27 + hcg: {channels: 3, labels: ['h', 'c', 'g']},
28 + apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
29 + gray: {channels: 1, labels: ['gray']}
30 +};
31 +
32 +module.exports = convert;
33 +
34 +// Hide .channels and .labels properties
35 +for (const model of Object.keys(convert)) {
36 + if (!('channels' in convert[model])) {
37 + throw new Error('missing channels property: ' + model);
38 + }
39 +
40 + if (!('labels' in convert[model])) {
41 + throw new Error('missing channel labels property: ' + model);
42 + }
43 +
44 + if (convert[model].labels.length !== convert[model].channels) {
45 + throw new Error('channel and label counts mismatch: ' + model);
46 + }
47 +
48 + const {channels, labels} = convert[model];
49 + delete convert[model].channels;
50 + delete convert[model].labels;
51 + Object.defineProperty(convert[model], 'channels', {value: channels});
52 + Object.defineProperty(convert[model], 'labels', {value: labels});
53 +}
54 +
55 +convert.rgb.hsl = function (rgb) {
56 + const r = rgb[0] / 255;
57 + const g = rgb[1] / 255;
58 + const b = rgb[2] / 255;
59 + const min = Math.min(r, g, b);
60 + const max = Math.max(r, g, b);
61 + const delta = max - min;
62 + let h;
63 + let s;
64 +
65 + if (max === min) {
66 + h = 0;
67 + } else if (r === max) {
68 + h = (g - b) / delta;
69 + } else if (g === max) {
70 + h = 2 + (b - r) / delta;
71 + } else if (b === max) {
72 + h = 4 + (r - g) / delta;
73 + }
74 +
75 + h = Math.min(h * 60, 360);
76 +
77 + if (h < 0) {
78 + h += 360;
79 + }
80 +
81 + const l = (min + max) / 2;
82 +
83 + if (max === min) {
84 + s = 0;
85 + } else if (l <= 0.5) {
86 + s = delta / (max + min);
87 + } else {
88 + s = delta / (2 - max - min);
89 + }
90 +
91 + return [h, s * 100, l * 100];
92 +};
93 +
94 +convert.rgb.hsv = function (rgb) {
95 + let rdif;
96 + let gdif;
97 + let bdif;
98 + let h;
99 + let s;
100 +
101 + const r = rgb[0] / 255;
102 + const g = rgb[1] / 255;
103 + const b = rgb[2] / 255;
104 + const v = Math.max(r, g, b);
105 + const diff = v - Math.min(r, g, b);
106 + const diffc = function (c) {
107 + return (v - c) / 6 / diff + 1 / 2;
108 + };
109 +
110 + if (diff === 0) {
111 + h = 0;
112 + s = 0;
113 + } else {
114 + s = diff / v;
115 + rdif = diffc(r);
116 + gdif = diffc(g);
117 + bdif = diffc(b);
118 +
119 + if (r === v) {
120 + h = bdif - gdif;
121 + } else if (g === v) {
122 + h = (1 / 3) + rdif - bdif;
123 + } else if (b === v) {
124 + h = (2 / 3) + gdif - rdif;
125 + }
126 +
127 + if (h < 0) {
128 + h += 1;
129 + } else if (h > 1) {
130 + h -= 1;
131 + }
132 + }
133 +
134 + return [
135 + h * 360,
136 + s * 100,
137 + v * 100
138 + ];
139 +};
140 +
141 +convert.rgb.hwb = function (rgb) {
142 + const r = rgb[0];
143 + const g = rgb[1];
144 + let b = rgb[2];
145 + const h = convert.rgb.hsl(rgb)[0];
146 + const w = 1 / 255 * Math.min(r, Math.min(g, b));
147 +
148 + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
149 +
150 + return [h, w * 100, b * 100];
151 +};
152 +
153 +convert.rgb.cmyk = function (rgb) {
154 + const r = rgb[0] / 255;
155 + const g = rgb[1] / 255;
156 + const b = rgb[2] / 255;
157 +
158 + const k = Math.min(1 - r, 1 - g, 1 - b);
159 + const c = (1 - r - k) / (1 - k) || 0;
160 + const m = (1 - g - k) / (1 - k) || 0;
161 + const y = (1 - b - k) / (1 - k) || 0;
162 +
163 + return [c * 100, m * 100, y * 100, k * 100];
164 +};
165 +
166 +function comparativeDistance(x, y) {
167 + /*
168 + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
169 + */
170 + return (
171 + ((x[0] - y[0]) ** 2) +
172 + ((x[1] - y[1]) ** 2) +
173 + ((x[2] - y[2]) ** 2)
174 + );
175 +}
176 +
177 +convert.rgb.keyword = function (rgb) {
178 + const reversed = reverseKeywords[rgb];
179 + if (reversed) {
180 + return reversed;
181 + }
182 +
183 + let currentClosestDistance = Infinity;
184 + let currentClosestKeyword;
185 +
186 + for (const keyword of Object.keys(cssKeywords)) {
187 + const value = cssKeywords[keyword];
188 +
189 + // Compute comparative distance
190 + const distance = comparativeDistance(rgb, value);
191 +
192 + // Check if its less, if so set as closest
193 + if (distance < currentClosestDistance) {
194 + currentClosestDistance = distance;
195 + currentClosestKeyword = keyword;
196 + }
197 + }
198 +
199 + return currentClosestKeyword;
200 +};
201 +
202 +convert.keyword.rgb = function (keyword) {
203 + return cssKeywords[keyword];
204 +};
205 +
206 +convert.rgb.xyz = function (rgb) {
207 + let r = rgb[0] / 255;
208 + let g = rgb[1] / 255;
209 + let b = rgb[2] / 255;
210 +
211 + // Assume sRGB
212 + r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
213 + g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
214 + b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
215 +
216 + const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
217 + const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
218 + const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
219 +
220 + return [x * 100, y * 100, z * 100];
221 +};
222 +
223 +convert.rgb.lab = function (rgb) {
224 + const xyz = convert.rgb.xyz(rgb);
225 + let x = xyz[0];
226 + let y = xyz[1];
227 + let z = xyz[2];
228 +
229 + x /= 95.047;
230 + y /= 100;
231 + z /= 108.883;
232 +
233 + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
234 + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
235 + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
236 +
237 + const l = (116 * y) - 16;
238 + const a = 500 * (x - y);
239 + const b = 200 * (y - z);
240 +
241 + return [l, a, b];
242 +};
243 +
244 +convert.hsl.rgb = function (hsl) {
245 + const h = hsl[0] / 360;
246 + const s = hsl[1] / 100;
247 + const l = hsl[2] / 100;
248 + let t2;
249 + let t3;
250 + let val;
251 +
252 + if (s === 0) {
253 + val = l * 255;
254 + return [val, val, val];
255 + }
256 +
257 + if (l < 0.5) {
258 + t2 = l * (1 + s);
259 + } else {
260 + t2 = l + s - l * s;
261 + }
262 +
263 + const t1 = 2 * l - t2;
264 +
265 + const rgb = [0, 0, 0];
266 + for (let i = 0; i < 3; i++) {
267 + t3 = h + 1 / 3 * -(i - 1);
268 + if (t3 < 0) {
269 + t3++;
270 + }
271 +
272 + if (t3 > 1) {
273 + t3--;
274 + }
275 +
276 + if (6 * t3 < 1) {
277 + val = t1 + (t2 - t1) * 6 * t3;
278 + } else if (2 * t3 < 1) {
279 + val = t2;
280 + } else if (3 * t3 < 2) {
281 + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
282 + } else {
283 + val = t1;
284 + }
285 +
286 + rgb[i] = val * 255;
287 + }
288 +
289 + return rgb;
290 +};
291 +
292 +convert.hsl.hsv = function (hsl) {
293 + const h = hsl[0];
294 + let s = hsl[1] / 100;
295 + let l = hsl[2] / 100;
296 + let smin = s;
297 + const lmin = Math.max(l, 0.01);
298 +
299 + l *= 2;
300 + s *= (l <= 1) ? l : 2 - l;
301 + smin *= lmin <= 1 ? lmin : 2 - lmin;
302 + const v = (l + s) / 2;
303 + const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
304 +
305 + return [h, sv * 100, v * 100];
306 +};
307 +
308 +convert.hsv.rgb = function (hsv) {
309 + const h = hsv[0] / 60;
310 + const s = hsv[1] / 100;
311 + let v = hsv[2] / 100;
312 + const hi = Math.floor(h) % 6;
313 +
314 + const f = h - Math.floor(h);
315 + const p = 255 * v * (1 - s);
316 + const q = 255 * v * (1 - (s * f));
317 + const t = 255 * v * (1 - (s * (1 - f)));
318 + v *= 255;
319 +
320 + switch (hi) {
321 + case 0:
322 + return [v, t, p];
323 + case 1:
324 + return [q, v, p];
325 + case 2:
326 + return [p, v, t];
327 + case 3:
328 + return [p, q, v];
329 + case 4:
330 + return [t, p, v];
331 + case 5:
332 + return [v, p, q];
333 + }
334 +};
335 +
336 +convert.hsv.hsl = function (hsv) {
337 + const h = hsv[0];
338 + const s = hsv[1] / 100;
339 + const v = hsv[2] / 100;
340 + const vmin = Math.max(v, 0.01);
341 + let sl;
342 + let l;
343 +
344 + l = (2 - s) * v;
345 + const lmin = (2 - s) * vmin;
346 + sl = s * vmin;
347 + sl /= (lmin <= 1) ? lmin : 2 - lmin;
348 + sl = sl || 0;
349 + l /= 2;
350 +
351 + return [h, sl * 100, l * 100];
352 +};
353 +
354 +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
355 +convert.hwb.rgb = function (hwb) {
356 + const h = hwb[0] / 360;
357 + let wh = hwb[1] / 100;
358 + let bl = hwb[2] / 100;
359 + const ratio = wh + bl;
360 + let f;
361 +
362 + // Wh + bl cant be > 1
363 + if (ratio > 1) {
364 + wh /= ratio;
365 + bl /= ratio;
366 + }
367 +
368 + const i = Math.floor(6 * h);
369 + const v = 1 - bl;
370 + f = 6 * h - i;
371 +
372 + if ((i & 0x01) !== 0) {
373 + f = 1 - f;
374 + }
375 +
376 + const n = wh + f * (v - wh); // Linear interpolation
377 +
378 + let r;
379 + let g;
380 + let b;
381 + /* eslint-disable max-statements-per-line,no-multi-spaces */
382 + switch (i) {
383 + default:
384 + case 6:
385 + case 0: r = v; g = n; b = wh; break;
386 + case 1: r = n; g = v; b = wh; break;
387 + case 2: r = wh; g = v; b = n; break;
388 + case 3: r = wh; g = n; b = v; break;
389 + case 4: r = n; g = wh; b = v; break;
390 + case 5: r = v; g = wh; b = n; break;
391 + }
392 + /* eslint-enable max-statements-per-line,no-multi-spaces */
393 +
394 + return [r * 255, g * 255, b * 255];
395 +};
396 +
397 +convert.cmyk.rgb = function (cmyk) {
398 + const c = cmyk[0] / 100;
399 + const m = cmyk[1] / 100;
400 + const y = cmyk[2] / 100;
401 + const k = cmyk[3] / 100;
402 +
403 + const r = 1 - Math.min(1, c * (1 - k) + k);
404 + const g = 1 - Math.min(1, m * (1 - k) + k);
405 + const b = 1 - Math.min(1, y * (1 - k) + k);
406 +
407 + return [r * 255, g * 255, b * 255];
408 +};
409 +
410 +convert.xyz.rgb = function (xyz) {
411 + const x = xyz[0] / 100;
412 + const y = xyz[1] / 100;
413 + const z = xyz[2] / 100;
414 + let r;
415 + let g;
416 + let b;
417 +
418 + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
419 + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
420 + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
421 +
422 + // Assume sRGB
423 + r = r > 0.0031308
424 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
425 + : r * 12.92;
426 +
427 + g = g > 0.0031308
428 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
429 + : g * 12.92;
430 +
431 + b = b > 0.0031308
432 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
433 + : b * 12.92;
434 +
435 + r = Math.min(Math.max(0, r), 1);
436 + g = Math.min(Math.max(0, g), 1);
437 + b = Math.min(Math.max(0, b), 1);
438 +
439 + return [r * 255, g * 255, b * 255];
440 +};
441 +
442 +convert.xyz.lab = function (xyz) {
443 + let x = xyz[0];
444 + let y = xyz[1];
445 + let z = xyz[2];
446 +
447 + x /= 95.047;
448 + y /= 100;
449 + z /= 108.883;
450 +
451 + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
452 + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
453 + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
454 +
455 + const l = (116 * y) - 16;
456 + const a = 500 * (x - y);
457 + const b = 200 * (y - z);
458 +
459 + return [l, a, b];
460 +};
461 +
462 +convert.lab.xyz = function (lab) {
463 + const l = lab[0];
464 + const a = lab[1];
465 + const b = lab[2];
466 + let x;
467 + let y;
468 + let z;
469 +
470 + y = (l + 16) / 116;
471 + x = a / 500 + y;
472 + z = y - b / 200;
473 +
474 + const y2 = y ** 3;
475 + const x2 = x ** 3;
476 + const z2 = z ** 3;
477 + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
478 + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
479 + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
480 +
481 + x *= 95.047;
482 + y *= 100;
483 + z *= 108.883;
484 +
485 + return [x, y, z];
486 +};
487 +
488 +convert.lab.lch = function (lab) {
489 + const l = lab[0];
490 + const a = lab[1];
491 + const b = lab[2];
492 + let h;
493 +
494 + const hr = Math.atan2(b, a);
495 + h = hr * 360 / 2 / Math.PI;
496 +
497 + if (h < 0) {
498 + h += 360;
499 + }
500 +
501 + const c = Math.sqrt(a * a + b * b);
502 +
503 + return [l, c, h];
504 +};
505 +
506 +convert.lch.lab = function (lch) {
507 + const l = lch[0];
508 + const c = lch[1];
509 + const h = lch[2];
510 +
511 + const hr = h / 360 * 2 * Math.PI;
512 + const a = c * Math.cos(hr);
513 + const b = c * Math.sin(hr);
514 +
515 + return [l, a, b];
516 +};
517 +
518 +convert.rgb.ansi16 = function (args, saturation = null) {
519 + const [r, g, b] = args;
520 + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
521 +
522 + value = Math.round(value / 50);
523 +
524 + if (value === 0) {
525 + return 30;
526 + }
527 +
528 + let ansi = 30
529 + + ((Math.round(b / 255) << 2)
530 + | (Math.round(g / 255) << 1)
531 + | Math.round(r / 255));
532 +
533 + if (value === 2) {
534 + ansi += 60;
535 + }
536 +
537 + return ansi;
538 +};
539 +
540 +convert.hsv.ansi16 = function (args) {
541 + // Optimization here; we already know the value and don't need to get
542 + // it converted for us.
543 + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
544 +};
545 +
546 +convert.rgb.ansi256 = function (args) {
547 + const r = args[0];
548 + const g = args[1];
549 + const b = args[2];
550 +
551 + // We use the extended greyscale palette here, with the exception of
552 + // black and white. normal palette only has 4 greyscale shades.
553 + if (r === g && g === b) {
554 + if (r < 8) {
555 + return 16;
556 + }
557 +
558 + if (r > 248) {
559 + return 231;
560 + }
561 +
562 + return Math.round(((r - 8) / 247) * 24) + 232;
563 + }
564 +
565 + const ansi = 16
566 + + (36 * Math.round(r / 255 * 5))
567 + + (6 * Math.round(g / 255 * 5))
568 + + Math.round(b / 255 * 5);
569 +
570 + return ansi;
571 +};
572 +
573 +convert.ansi16.rgb = function (args) {
574 + let color = args % 10;
575 +
576 + // Handle greyscale
577 + if (color === 0 || color === 7) {
578 + if (args > 50) {
579 + color += 3.5;
580 + }
581 +
582 + color = color / 10.5 * 255;
583 +
584 + return [color, color, color];
585 + }
586 +
587 + const mult = (~~(args > 50) + 1) * 0.5;
588 + const r = ((color & 1) * mult) * 255;
589 + const g = (((color >> 1) & 1) * mult) * 255;
590 + const b = (((color >> 2) & 1) * mult) * 255;
591 +
592 + return [r, g, b];
593 +};
594 +
595 +convert.ansi256.rgb = function (args) {
596 + // Handle greyscale
597 + if (args >= 232) {
598 + const c = (args - 232) * 10 + 8;
599 + return [c, c, c];
600 + }
601 +
602 + args -= 16;
603 +
604 + let rem;
605 + const r = Math.floor(args / 36) / 5 * 255;
606 + const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
607 + const b = (rem % 6) / 5 * 255;
608 +
609 + return [r, g, b];
610 +};
611 +
612 +convert.rgb.hex = function (args) {
613 + const integer = ((Math.round(args[0]) & 0xFF) << 16)
614 + + ((Math.round(args[1]) & 0xFF) << 8)
615 + + (Math.round(args[2]) & 0xFF);
616 +
617 + const string = integer.toString(16).toUpperCase();
618 + return '000000'.substring(string.length) + string;
619 +};
620 +
621 +convert.hex.rgb = function (args) {
622 + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
623 + if (!match) {
624 + return [0, 0, 0];
625 + }
626 +
627 + let colorString = match[0];
628 +
629 + if (match[0].length === 3) {
630 + colorString = colorString.split('').map(char => {
631 + return char + char;
632 + }).join('');
633 + }
634 +
635 + const integer = parseInt(colorString, 16);
636 + const r = (integer >> 16) & 0xFF;
637 + const g = (integer >> 8) & 0xFF;
638 + const b = integer & 0xFF;
639 +
640 + return [r, g, b];
641 +};
642 +
643 +convert.rgb.hcg = function (rgb) {
644 + const r = rgb[0] / 255;
645 + const g = rgb[1] / 255;
646 + const b = rgb[2] / 255;
647 + const max = Math.max(Math.max(r, g), b);
648 + const min = Math.min(Math.min(r, g), b);
649 + const chroma = (max - min);
650 + let grayscale;
651 + let hue;
652 +
653 + if (chroma < 1) {
654 + grayscale = min / (1 - chroma);
655 + } else {
656 + grayscale = 0;
657 + }
658 +
659 + if (chroma <= 0) {
660 + hue = 0;
661 + } else
662 + if (max === r) {
663 + hue = ((g - b) / chroma) % 6;
664 + } else
665 + if (max === g) {
666 + hue = 2 + (b - r) / chroma;
667 + } else {
668 + hue = 4 + (r - g) / chroma;
669 + }
670 +
671 + hue /= 6;
672 + hue %= 1;
673 +
674 + return [hue * 360, chroma * 100, grayscale * 100];
675 +};
676 +
677 +convert.hsl.hcg = function (hsl) {
678 + const s = hsl[1] / 100;
679 + const l = hsl[2] / 100;
680 +
681 + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
682 +
683 + let f = 0;
684 + if (c < 1.0) {
685 + f = (l - 0.5 * c) / (1.0 - c);
686 + }
687 +
688 + return [hsl[0], c * 100, f * 100];
689 +};
690 +
691 +convert.hsv.hcg = function (hsv) {
692 + const s = hsv[1] / 100;
693 + const v = hsv[2] / 100;
694 +
695 + const c = s * v;
696 + let f = 0;
697 +
698 + if (c < 1.0) {
699 + f = (v - c) / (1 - c);
700 + }
701 +
702 + return [hsv[0], c * 100, f * 100];
703 +};
704 +
705 +convert.hcg.rgb = function (hcg) {
706 + const h = hcg[0] / 360;
707 + const c = hcg[1] / 100;
708 + const g = hcg[2] / 100;
709 +
710 + if (c === 0.0) {
711 + return [g * 255, g * 255, g * 255];
712 + }
713 +
714 + const pure = [0, 0, 0];
715 + const hi = (h % 1) * 6;
716 + const v = hi % 1;
717 + const w = 1 - v;
718 + let mg = 0;
719 +
720 + /* eslint-disable max-statements-per-line */
721 + switch (Math.floor(hi)) {
722 + case 0:
723 + pure[0] = 1; pure[1] = v; pure[2] = 0; break;
724 + case 1:
725 + pure[0] = w; pure[1] = 1; pure[2] = 0; break;
726 + case 2:
727 + pure[0] = 0; pure[1] = 1; pure[2] = v; break;
728 + case 3:
729 + pure[0] = 0; pure[1] = w; pure[2] = 1; break;
730 + case 4:
731 + pure[0] = v; pure[1] = 0; pure[2] = 1; break;
732 + default:
733 + pure[0] = 1; pure[1] = 0; pure[2] = w;
734 + }
735 + /* eslint-enable max-statements-per-line */
736 +
737 + mg = (1.0 - c) * g;
738 +
739 + return [
740 + (c * pure[0] + mg) * 255,
741 + (c * pure[1] + mg) * 255,
742 + (c * pure[2] + mg) * 255
743 + ];
744 +};
745 +
746 +convert.hcg.hsv = function (hcg) {
747 + const c = hcg[1] / 100;
748 + const g = hcg[2] / 100;
749 +
750 + const v = c + g * (1.0 - c);
751 + let f = 0;
752 +
753 + if (v > 0.0) {
754 + f = c / v;
755 + }
756 +
757 + return [hcg[0], f * 100, v * 100];
758 +};
759 +
760 +convert.hcg.hsl = function (hcg) {
761 + const c = hcg[1] / 100;
762 + const g = hcg[2] / 100;
763 +
764 + const l = g * (1.0 - c) + 0.5 * c;
765 + let s = 0;
766 +
767 + if (l > 0.0 && l < 0.5) {
768 + s = c / (2 * l);
769 + } else
770 + if (l >= 0.5 && l < 1.0) {
771 + s = c / (2 * (1 - l));
772 + }
773 +
774 + return [hcg[0], s * 100, l * 100];
775 +};
776 +
777 +convert.hcg.hwb = function (hcg) {
778 + const c = hcg[1] / 100;
779 + const g = hcg[2] / 100;
780 + const v = c + g * (1.0 - c);
781 + return [hcg[0], (v - c) * 100, (1 - v) * 100];
782 +};
783 +
784 +convert.hwb.hcg = function (hwb) {
785 + const w = hwb[1] / 100;
786 + const b = hwb[2] / 100;
787 + const v = 1 - b;
788 + const c = v - w;
789 + let g = 0;
790 +
791 + if (c < 1) {
792 + g = (v - c) / (1 - c);
793 + }
794 +
795 + return [hwb[0], c * 100, g * 100];
796 +};
797 +
798 +convert.apple.rgb = function (apple) {
799 + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
800 +};
801 +
802 +convert.rgb.apple = function (rgb) {
803 + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
804 +};
805 +
806 +convert.gray.rgb = function (args) {
807 + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
808 +};
809 +
810 +convert.gray.hsl = function (args) {
811 + return [0, 0, args[0]];
812 +};
813 +
814 +convert.gray.hsv = convert.gray.hsl;
815 +
816 +convert.gray.hwb = function (gray) {
817 + return [0, 100, gray[0]];
818 +};
819 +
820 +convert.gray.cmyk = function (gray) {
821 + return [0, 0, 0, gray[0]];
822 +};
823 +
824 +convert.gray.lab = function (gray) {
825 + return [gray[0], 0, 0];
826 +};
827 +
828 +convert.gray.hex = function (gray) {
829 + const val = Math.round(gray[0] / 100 * 255) & 0xFF;
830 + const integer = (val << 16) + (val << 8) + val;
831 +
832 + const string = integer.toString(16).toUpperCase();
833 + return '000000'.substring(string.length) + string;
834 +};
835 +
836 +convert.rgb.gray = function (rgb) {
837 + const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
838 + return [val / 255 * 100];
839 +};
1 +const conversions = require('./conversions');
2 +const route = require('./route');
3 +
4 +const convert = {};
5 +
6 +const models = Object.keys(conversions);
7 +
8 +function wrapRaw(fn) {
9 + const wrappedFn = function (...args) {
10 + const arg0 = args[0];
11 + if (arg0 === undefined || arg0 === null) {
12 + return arg0;
13 + }
14 +
15 + if (arg0.length > 1) {
16 + args = arg0;
17 + }
18 +
19 + return fn(args);
20 + };
21 +
22 + // Preserve .conversion property if there is one
23 + if ('conversion' in fn) {
24 + wrappedFn.conversion = fn.conversion;
25 + }
26 +
27 + return wrappedFn;
28 +}
29 +
30 +function wrapRounded(fn) {
31 + const wrappedFn = function (...args) {
32 + const arg0 = args[0];
33 +
34 + if (arg0 === undefined || arg0 === null) {
35 + return arg0;
36 + }
37 +
38 + if (arg0.length > 1) {
39 + args = arg0;
40 + }
41 +
42 + const result = fn(args);
43 +
44 + // We're assuming the result is an array here.
45 + // see notice in conversions.js; don't use box types
46 + // in conversion functions.
47 + if (typeof result === 'object') {
48 + for (let len = result.length, i = 0; i < len; i++) {
49 + result[i] = Math.round(result[i]);
50 + }
51 + }
52 +
53 + return result;
54 + };
55 +
56 + // Preserve .conversion property if there is one
57 + if ('conversion' in fn) {
58 + wrappedFn.conversion = fn.conversion;
59 + }
60 +
61 + return wrappedFn;
62 +}
63 +
64 +models.forEach(fromModel => {
65 + convert[fromModel] = {};
66 +
67 + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
68 + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
69 +
70 + const routes = route(fromModel);
71 + const routeModels = Object.keys(routes);
72 +
73 + routeModels.forEach(toModel => {
74 + const fn = routes[toModel];
75 +
76 + convert[fromModel][toModel] = wrapRounded(fn);
77 + convert[fromModel][toModel].raw = wrapRaw(fn);
78 + });
79 +});
80 +
81 +module.exports = convert;
1 +{
2 + "_from": "color-convert@^2.0.1",
3 + "_id": "color-convert@2.0.1",
4 + "_inBundle": false,
5 + "_integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
6 + "_location": "/color-convert",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "color-convert@^2.0.1",
12 + "name": "color-convert",
13 + "escapedName": "color-convert",
14 + "rawSpec": "^2.0.1",
15 + "saveSpec": null,
16 + "fetchSpec": "^2.0.1"
17 + },
18 + "_requiredBy": [
19 + "/ansi-styles"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
22 + "_shasum": "72d3a68d598c9bdb3af2ad1e84f21d896abd4de3",
23 + "_spec": "color-convert@^2.0.1",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\ansi-styles",
25 + "author": {
26 + "name": "Heather Arthur",
27 + "email": "fayearthur@gmail.com"
28 + },
29 + "bugs": {
30 + "url": "https://github.com/Qix-/color-convert/issues"
31 + },
32 + "bundleDependencies": false,
33 + "dependencies": {
34 + "color-name": "~1.1.4"
35 + },
36 + "deprecated": false,
37 + "description": "Plain color conversion functions",
38 + "devDependencies": {
39 + "chalk": "^2.4.2",
40 + "xo": "^0.24.0"
41 + },
42 + "engines": {
43 + "node": ">=7.0.0"
44 + },
45 + "files": [
46 + "index.js",
47 + "conversions.js",
48 + "route.js"
49 + ],
50 + "homepage": "https://github.com/Qix-/color-convert#readme",
51 + "keywords": [
52 + "color",
53 + "colour",
54 + "convert",
55 + "converter",
56 + "conversion",
57 + "rgb",
58 + "hsl",
59 + "hsv",
60 + "hwb",
61 + "cmyk",
62 + "ansi",
63 + "ansi16"
64 + ],
65 + "license": "MIT",
66 + "name": "color-convert",
67 + "repository": {
68 + "type": "git",
69 + "url": "git+https://github.com/Qix-/color-convert.git"
70 + },
71 + "scripts": {
72 + "pretest": "xo",
73 + "test": "node test/basic.js"
74 + },
75 + "version": "2.0.1",
76 + "xo": {
77 + "rules": {
78 + "default-case": 0,
79 + "no-inline-comments": 0,
80 + "operator-linebreak": 0
81 + }
82 + }
83 +}
1 +const conversions = require('./conversions');
2 +
3 +/*
4 + This function routes a model to all other models.
5 +
6 + all functions that are routed have a property `.conversion` attached
7 + to the returned synthetic function. This property is an array
8 + of strings, each with the steps in between the 'from' and 'to'
9 + color models (inclusive).
10 +
11 + conversions that are not possible simply are not included.
12 +*/
13 +
14 +function buildGraph() {
15 + const graph = {};
16 + // https://jsperf.com/object-keys-vs-for-in-with-closure/3
17 + const models = Object.keys(conversions);
18 +
19 + for (let len = models.length, i = 0; i < len; i++) {
20 + graph[models[i]] = {
21 + // http://jsperf.com/1-vs-infinity
22 + // micro-opt, but this is simple.
23 + distance: -1,
24 + parent: null
25 + };
26 + }
27 +
28 + return graph;
29 +}
30 +
31 +// https://en.wikipedia.org/wiki/Breadth-first_search
32 +function deriveBFS(fromModel) {
33 + const graph = buildGraph();
34 + const queue = [fromModel]; // Unshift -> queue -> pop
35 +
36 + graph[fromModel].distance = 0;
37 +
38 + while (queue.length) {
39 + const current = queue.pop();
40 + const adjacents = Object.keys(conversions[current]);
41 +
42 + for (let len = adjacents.length, i = 0; i < len; i++) {
43 + const adjacent = adjacents[i];
44 + const node = graph[adjacent];
45 +
46 + if (node.distance === -1) {
47 + node.distance = graph[current].distance + 1;
48 + node.parent = current;
49 + queue.unshift(adjacent);
50 + }
51 + }
52 + }
53 +
54 + return graph;
55 +}
56 +
57 +function link(from, to) {
58 + return function (args) {
59 + return to(from(args));
60 + };
61 +}
62 +
63 +function wrapConversion(toModel, graph) {
64 + const path = [graph[toModel].parent, toModel];
65 + let fn = conversions[graph[toModel].parent][toModel];
66 +
67 + let cur = graph[toModel].parent;
68 + while (graph[cur].parent) {
69 + path.unshift(graph[cur].parent);
70 + fn = link(conversions[graph[cur].parent][cur], fn);
71 + cur = graph[cur].parent;
72 + }
73 +
74 + fn.conversion = path;
75 + return fn;
76 +}
77 +
78 +module.exports = function (fromModel) {
79 + const graph = deriveBFS(fromModel);
80 + const conversion = {};
81 +
82 + const models = Object.keys(graph);
83 + for (let len = models.length, i = 0; i < len; i++) {
84 + const toModel = models[i];
85 + const node = graph[toModel];
86 +
87 + if (node.parent === null) {
88 + // No possible conversion, or this node is the source model.
89 + continue;
90 + }
91 +
92 + conversion[toModel] = wrapConversion(toModel, graph);
93 + }
94 +
95 + return conversion;
96 +};
97 +
1 +The MIT License (MIT)
2 +Copyright (c) 2015 Dmitry Ivanov
3 +
4 +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:
5 +
6 +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7 +
8 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
...\ No newline at end of file ...\ No newline at end of file
1 +A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors.
2 +
3 +[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/)
4 +
5 +
6 +```js
7 +var colors = require('color-name');
8 +colors.red //[255,0,0]
9 +```
10 +
11 +<a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a>
1 +'use strict'
2 +
3 +module.exports = {
4 + "aliceblue": [240, 248, 255],
5 + "antiquewhite": [250, 235, 215],
6 + "aqua": [0, 255, 255],
7 + "aquamarine": [127, 255, 212],
8 + "azure": [240, 255, 255],
9 + "beige": [245, 245, 220],
10 + "bisque": [255, 228, 196],
11 + "black": [0, 0, 0],
12 + "blanchedalmond": [255, 235, 205],
13 + "blue": [0, 0, 255],
14 + "blueviolet": [138, 43, 226],
15 + "brown": [165, 42, 42],
16 + "burlywood": [222, 184, 135],
17 + "cadetblue": [95, 158, 160],
18 + "chartreuse": [127, 255, 0],
19 + "chocolate": [210, 105, 30],
20 + "coral": [255, 127, 80],
21 + "cornflowerblue": [100, 149, 237],
22 + "cornsilk": [255, 248, 220],
23 + "crimson": [220, 20, 60],
24 + "cyan": [0, 255, 255],
25 + "darkblue": [0, 0, 139],
26 + "darkcyan": [0, 139, 139],
27 + "darkgoldenrod": [184, 134, 11],
28 + "darkgray": [169, 169, 169],
29 + "darkgreen": [0, 100, 0],
30 + "darkgrey": [169, 169, 169],
31 + "darkkhaki": [189, 183, 107],
32 + "darkmagenta": [139, 0, 139],
33 + "darkolivegreen": [85, 107, 47],
34 + "darkorange": [255, 140, 0],
35 + "darkorchid": [153, 50, 204],
36 + "darkred": [139, 0, 0],
37 + "darksalmon": [233, 150, 122],
38 + "darkseagreen": [143, 188, 143],
39 + "darkslateblue": [72, 61, 139],
40 + "darkslategray": [47, 79, 79],
41 + "darkslategrey": [47, 79, 79],
42 + "darkturquoise": [0, 206, 209],
43 + "darkviolet": [148, 0, 211],
44 + "deeppink": [255, 20, 147],
45 + "deepskyblue": [0, 191, 255],
46 + "dimgray": [105, 105, 105],
47 + "dimgrey": [105, 105, 105],
48 + "dodgerblue": [30, 144, 255],
49 + "firebrick": [178, 34, 34],
50 + "floralwhite": [255, 250, 240],
51 + "forestgreen": [34, 139, 34],
52 + "fuchsia": [255, 0, 255],
53 + "gainsboro": [220, 220, 220],
54 + "ghostwhite": [248, 248, 255],
55 + "gold": [255, 215, 0],
56 + "goldenrod": [218, 165, 32],
57 + "gray": [128, 128, 128],
58 + "green": [0, 128, 0],
59 + "greenyellow": [173, 255, 47],
60 + "grey": [128, 128, 128],
61 + "honeydew": [240, 255, 240],
62 + "hotpink": [255, 105, 180],
63 + "indianred": [205, 92, 92],
64 + "indigo": [75, 0, 130],
65 + "ivory": [255, 255, 240],
66 + "khaki": [240, 230, 140],
67 + "lavender": [230, 230, 250],
68 + "lavenderblush": [255, 240, 245],
69 + "lawngreen": [124, 252, 0],
70 + "lemonchiffon": [255, 250, 205],
71 + "lightblue": [173, 216, 230],
72 + "lightcoral": [240, 128, 128],
73 + "lightcyan": [224, 255, 255],
74 + "lightgoldenrodyellow": [250, 250, 210],
75 + "lightgray": [211, 211, 211],
76 + "lightgreen": [144, 238, 144],
77 + "lightgrey": [211, 211, 211],
78 + "lightpink": [255, 182, 193],
79 + "lightsalmon": [255, 160, 122],
80 + "lightseagreen": [32, 178, 170],
81 + "lightskyblue": [135, 206, 250],
82 + "lightslategray": [119, 136, 153],
83 + "lightslategrey": [119, 136, 153],
84 + "lightsteelblue": [176, 196, 222],
85 + "lightyellow": [255, 255, 224],
86 + "lime": [0, 255, 0],
87 + "limegreen": [50, 205, 50],
88 + "linen": [250, 240, 230],
89 + "magenta": [255, 0, 255],
90 + "maroon": [128, 0, 0],
91 + "mediumaquamarine": [102, 205, 170],
92 + "mediumblue": [0, 0, 205],
93 + "mediumorchid": [186, 85, 211],
94 + "mediumpurple": [147, 112, 219],
95 + "mediumseagreen": [60, 179, 113],
96 + "mediumslateblue": [123, 104, 238],
97 + "mediumspringgreen": [0, 250, 154],
98 + "mediumturquoise": [72, 209, 204],
99 + "mediumvioletred": [199, 21, 133],
100 + "midnightblue": [25, 25, 112],
101 + "mintcream": [245, 255, 250],
102 + "mistyrose": [255, 228, 225],
103 + "moccasin": [255, 228, 181],
104 + "navajowhite": [255, 222, 173],
105 + "navy": [0, 0, 128],
106 + "oldlace": [253, 245, 230],
107 + "olive": [128, 128, 0],
108 + "olivedrab": [107, 142, 35],
109 + "orange": [255, 165, 0],
110 + "orangered": [255, 69, 0],
111 + "orchid": [218, 112, 214],
112 + "palegoldenrod": [238, 232, 170],
113 + "palegreen": [152, 251, 152],
114 + "paleturquoise": [175, 238, 238],
115 + "palevioletred": [219, 112, 147],
116 + "papayawhip": [255, 239, 213],
117 + "peachpuff": [255, 218, 185],
118 + "peru": [205, 133, 63],
119 + "pink": [255, 192, 203],
120 + "plum": [221, 160, 221],
121 + "powderblue": [176, 224, 230],
122 + "purple": [128, 0, 128],
123 + "rebeccapurple": [102, 51, 153],
124 + "red": [255, 0, 0],
125 + "rosybrown": [188, 143, 143],
126 + "royalblue": [65, 105, 225],
127 + "saddlebrown": [139, 69, 19],
128 + "salmon": [250, 128, 114],
129 + "sandybrown": [244, 164, 96],
130 + "seagreen": [46, 139, 87],
131 + "seashell": [255, 245, 238],
132 + "sienna": [160, 82, 45],
133 + "silver": [192, 192, 192],
134 + "skyblue": [135, 206, 235],
135 + "slateblue": [106, 90, 205],
136 + "slategray": [112, 128, 144],
137 + "slategrey": [112, 128, 144],
138 + "snow": [255, 250, 250],
139 + "springgreen": [0, 255, 127],
140 + "steelblue": [70, 130, 180],
141 + "tan": [210, 180, 140],
142 + "teal": [0, 128, 128],
143 + "thistle": [216, 191, 216],
144 + "tomato": [255, 99, 71],
145 + "turquoise": [64, 224, 208],
146 + "violet": [238, 130, 238],
147 + "wheat": [245, 222, 179],
148 + "white": [255, 255, 255],
149 + "whitesmoke": [245, 245, 245],
150 + "yellow": [255, 255, 0],
151 + "yellowgreen": [154, 205, 50]
152 +};
1 +{
2 + "_from": "color-name@~1.1.4",
3 + "_id": "color-name@1.1.4",
4 + "_inBundle": false,
5 + "_integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
6 + "_location": "/color-name",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "color-name@~1.1.4",
12 + "name": "color-name",
13 + "escapedName": "color-name",
14 + "rawSpec": "~1.1.4",
15 + "saveSpec": null,
16 + "fetchSpec": "~1.1.4"
17 + },
18 + "_requiredBy": [
19 + "/color-convert"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
22 + "_shasum": "c2a09a87acbde69543de6f63fa3995c826c536a2",
23 + "_spec": "color-name@~1.1.4",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\color-convert",
25 + "author": {
26 + "name": "DY",
27 + "email": "dfcreative@gmail.com"
28 + },
29 + "bugs": {
30 + "url": "https://github.com/colorjs/color-name/issues"
31 + },
32 + "bundleDependencies": false,
33 + "deprecated": false,
34 + "description": "A list of color names and its values",
35 + "files": [
36 + "index.js"
37 + ],
38 + "homepage": "https://github.com/colorjs/color-name",
39 + "keywords": [
40 + "color-name",
41 + "color",
42 + "color-keyword",
43 + "keyword"
44 + ],
45 + "license": "MIT",
46 + "main": "index.js",
47 + "name": "color-name",
48 + "repository": {
49 + "type": "git",
50 + "url": "git+ssh://git@github.com/colorjs/color-name.git"
51 + },
52 + "scripts": {
53 + "test": "node test.js"
54 + },
55 + "version": "1.1.4"
56 +}
1 +language: node_js
2 +node_js:
3 + - 0.4
4 + - 0.6
1 +This software is released under the MIT license:
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy of
4 +this software and associated documentation files (the "Software"), to deal in
5 +the Software without restriction, including without limitation the rights to
6 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7 +the Software, and to permit persons to whom the Software is furnished to do so,
8 +subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in all
11 +copies or substantial portions of the Software.
12 +
13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15 +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16 +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17 +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18 +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1 +concat-map
2 +==========
3 +
4 +Concatenative mapdashery.
5 +
6 +[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map)
7 +
8 +[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map)
9 +
10 +example
11 +=======
12 +
13 +``` js
14 +var concatMap = require('concat-map');
15 +var xs = [ 1, 2, 3, 4, 5, 6 ];
16 +var ys = concatMap(xs, function (x) {
17 + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
18 +});
19 +console.dir(ys);
20 +```
21 +
22 +***
23 +
24 +```
25 +[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]
26 +```
27 +
28 +methods
29 +=======
30 +
31 +``` js
32 +var concatMap = require('concat-map')
33 +```
34 +
35 +concatMap(xs, fn)
36 +-----------------
37 +
38 +Return an array of concatenated elements by calling `fn(x, i)` for each element
39 +`x` and each index `i` in the array `xs`.
40 +
41 +When `fn(x, i)` returns an array, its result will be concatenated with the
42 +result array. If `fn(x, i)` returns anything else, that value will be pushed
43 +onto the end of the result array.
44 +
45 +install
46 +=======
47 +
48 +With [npm](http://npmjs.org) do:
49 +
50 +```
51 +npm install concat-map
52 +```
53 +
54 +license
55 +=======
56 +
57 +MIT
58 +
59 +notes
60 +=====
61 +
62 +This module was written while sitting high above the ground in a tree.
1 +var concatMap = require('../');
2 +var xs = [ 1, 2, 3, 4, 5, 6 ];
3 +var ys = concatMap(xs, function (x) {
4 + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
5 +});
6 +console.dir(ys);
1 +module.exports = function (xs, fn) {
2 + var res = [];
3 + for (var i = 0; i < xs.length; i++) {
4 + var x = fn(xs[i], i);
5 + if (isArray(x)) res.push.apply(res, x);
6 + else res.push(x);
7 + }
8 + return res;
9 +};
10 +
11 +var isArray = Array.isArray || function (xs) {
12 + return Object.prototype.toString.call(xs) === '[object Array]';
13 +};
1 +{
2 + "_from": "concat-map@0.0.1",
3 + "_id": "concat-map@0.0.1",
4 + "_inBundle": false,
5 + "_integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=",
6 + "_location": "/concat-map",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "version",
10 + "registry": true,
11 + "raw": "concat-map@0.0.1",
12 + "name": "concat-map",
13 + "escapedName": "concat-map",
14 + "rawSpec": "0.0.1",
15 + "saveSpec": null,
16 + "fetchSpec": "0.0.1"
17 + },
18 + "_requiredBy": [
19 + "/minimatch/brace-expansion"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
22 + "_shasum": "d8a96bd77fd68df7793a73036a3ba0d5405d477b",
23 + "_spec": "concat-map@0.0.1",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\minimatch\\node_modules\\brace-expansion",
25 + "author": {
26 + "name": "James Halliday",
27 + "email": "mail@substack.net",
28 + "url": "http://substack.net"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/substack/node-concat-map/issues"
32 + },
33 + "bundleDependencies": false,
34 + "deprecated": false,
35 + "description": "concatenative mapdashery",
36 + "devDependencies": {
37 + "tape": "~2.4.0"
38 + },
39 + "directories": {
40 + "example": "example",
41 + "test": "test"
42 + },
43 + "homepage": "https://github.com/substack/node-concat-map#readme",
44 + "keywords": [
45 + "concat",
46 + "concatMap",
47 + "map",
48 + "functional",
49 + "higher-order"
50 + ],
51 + "license": "MIT",
52 + "main": "index.js",
53 + "name": "concat-map",
54 + "repository": {
55 + "type": "git",
56 + "url": "git://github.com/substack/node-concat-map.git"
57 + },
58 + "scripts": {
59 + "test": "tape test/*.js"
60 + },
61 + "testling": {
62 + "files": "test/*.js",
63 + "browsers": {
64 + "ie": [
65 + 6,
66 + 7,
67 + 8,
68 + 9
69 + ],
70 + "ff": [
71 + 3.5,
72 + 10,
73 + 15
74 + ],
75 + "chrome": [
76 + 10,
77 + 22
78 + ],
79 + "safari": [
80 + 5.1
81 + ],
82 + "opera": [
83 + 12
84 + ]
85 + }
86 + },
87 + "version": "0.0.1"
88 +}
1 +var concatMap = require('../');
2 +var test = require('tape');
3 +
4 +test('empty or not', function (t) {
5 + var xs = [ 1, 2, 3, 4, 5, 6 ];
6 + var ixes = [];
7 + var ys = concatMap(xs, function (x, ix) {
8 + ixes.push(ix);
9 + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
10 + });
11 + t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]);
12 + t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]);
13 + t.end();
14 +});
15 +
16 +test('always something', function (t) {
17 + var xs = [ 'a', 'b', 'c', 'd' ];
18 + var ys = concatMap(xs, function (x) {
19 + return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ];
20 + });
21 + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]);
22 + t.end();
23 +});
24 +
25 +test('scalars', function (t) {
26 + var xs = [ 'a', 'b', 'c', 'd' ];
27 + var ys = concatMap(xs, function (x) {
28 + return x === 'b' ? [ 'B', 'B', 'B' ] : x;
29 + });
30 + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]);
31 + t.end();
32 +});
33 +
34 +test('undefs', function (t) {
35 + var xs = [ 'a', 'b', 'c', 'd' ];
36 + var ys = concatMap(xs, function () {});
37 + t.same(ys, [ undefined, undefined, undefined, undefined ]);
38 + t.end();
39 +});
1 +
2 + Apache License
3 + Version 2.0, January 2004
4 + http://www.apache.org/licenses/
5 +
6 + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 +
8 + 1. Definitions.
9 +
10 + "License" shall mean the terms and conditions for use, reproduction,
11 + and distribution as defined by Sections 1 through 9 of this document.
12 +
13 + "Licensor" shall mean the copyright owner or entity authorized by
14 + the copyright owner that is granting the License.
15 +
16 + "Legal Entity" shall mean the union of the acting entity and all
17 + other entities that control, are controlled by, or are under common
18 + control with that entity. For the purposes of this definition,
19 + "control" means (i) the power, direct or indirect, to cause the
20 + direction or management of such entity, whether by contract or
21 + otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 + outstanding shares, or (iii) beneficial ownership of such entity.
23 +
24 + "You" (or "Your") shall mean an individual or Legal Entity
25 + exercising permissions granted by this License.
26 +
27 + "Source" form shall mean the preferred form for making modifications,
28 + including but not limited to software source code, documentation
29 + source, and configuration files.
30 +
31 + "Object" form shall mean any form resulting from mechanical
32 + transformation or translation of a Source form, including but
33 + not limited to compiled object code, generated documentation,
34 + and conversions to other media types.
35 +
36 + "Work" shall mean the work of authorship, whether in Source or
37 + Object form, made available under the License, as indicated by a
38 + copyright notice that is included in or attached to the work
39 + (an example is provided in the Appendix below).
40 +
41 + "Derivative Works" shall mean any work, whether in Source or Object
42 + form, that is based on (or derived from) the Work and for which the
43 + editorial revisions, annotations, elaborations, or other modifications
44 + represent, as a whole, an original work of authorship. For the purposes
45 + of this License, Derivative Works shall not include works that remain
46 + separable from, or merely link (or bind by name) to the interfaces of,
47 + the Work and Derivative Works thereof.
48 +
49 + "Contribution" shall mean any work of authorship, including
50 + the original version of the Work and any modifications or additions
51 + to that Work or Derivative Works thereof, that is intentionally
52 + submitted to Licensor for inclusion in the Work by the copyright owner
53 + or by an individual or Legal Entity authorized to submit on behalf of
54 + the copyright owner. For the purposes of this definition, "submitted"
55 + means any form of electronic, verbal, or written communication sent
56 + to the Licensor or its representatives, including but not limited to
57 + communication on electronic mailing lists, source code control systems,
58 + and issue tracking systems that are managed by, or on behalf of, the
59 + Licensor for the purpose of discussing and improving the Work, but
60 + excluding communication that is conspicuously marked or otherwise
61 + designated in writing by the copyright owner as "Not a Contribution."
62 +
63 + "Contributor" shall mean Licensor and any individual or Legal Entity
64 + on behalf of whom a Contribution has been received by Licensor and
65 + subsequently incorporated within the Work.
66 +
67 + 2. Grant of Copyright License. Subject to the terms and conditions of
68 + this License, each Contributor hereby grants to You a perpetual,
69 + worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 + copyright license to reproduce, prepare Derivative Works of,
71 + publicly display, publicly perform, sublicense, and distribute the
72 + Work and such Derivative Works in Source or Object form.
73 +
74 + 3. Grant of Patent License. Subject to the terms and conditions of
75 + this License, each Contributor hereby grants to You a perpetual,
76 + worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 + (except as stated in this section) patent license to make, have made,
78 + use, offer to sell, sell, import, and otherwise transfer the Work,
79 + where such license applies only to those patent claims licensable
80 + by such Contributor that are necessarily infringed by their
81 + Contribution(s) alone or by combination of their Contribution(s)
82 + with the Work to which such Contribution(s) was submitted. If You
83 + institute patent litigation against any entity (including a
84 + cross-claim or counterclaim in a lawsuit) alleging that the Work
85 + or a Contribution incorporated within the Work constitutes direct
86 + or contributory patent infringement, then any patent licenses
87 + granted to You under this License for that Work shall terminate
88 + as of the date such litigation is filed.
89 +
90 + 4. Redistribution. You may reproduce and distribute copies of the
91 + Work or Derivative Works thereof in any medium, with or without
92 + modifications, and in Source or Object form, provided that You
93 + meet the following conditions:
94 +
95 + (a) You must give any other recipients of the Work or
96 + Derivative Works a copy of this License; and
97 +
98 + (b) You must cause any modified files to carry prominent notices
99 + stating that You changed the files; and
100 +
101 + (c) You must retain, in the Source form of any Derivative Works
102 + that You distribute, all copyright, patent, trademark, and
103 + attribution notices from the Source form of the Work,
104 + excluding those notices that do not pertain to any part of
105 + the Derivative Works; and
106 +
107 + (d) If the Work includes a "NOTICE" text file as part of its
108 + distribution, then any Derivative Works that You distribute must
109 + include a readable copy of the attribution notices contained
110 + within such NOTICE file, excluding those notices that do not
111 + pertain to any part of the Derivative Works, in at least one
112 + of the following places: within a NOTICE text file distributed
113 + as part of the Derivative Works; within the Source form or
114 + documentation, if provided along with the Derivative Works; or,
115 + within a display generated by the Derivative Works, if and
116 + wherever such third-party notices normally appear. The contents
117 + of the NOTICE file are for informational purposes only and
118 + do not modify the License. You may add Your own attribution
119 + notices within Derivative Works that You distribute, alongside
120 + or as an addendum to the NOTICE text from the Work, provided
121 + that such additional attribution notices cannot be construed
122 + as modifying the License.
123 +
124 + You may add Your own copyright statement to Your modifications and
125 + may provide additional or different license terms and conditions
126 + for use, reproduction, or distribution of Your modifications, or
127 + for any such Derivative Works as a whole, provided Your use,
128 + reproduction, and distribution of the Work otherwise complies with
129 + the conditions stated in this License.
130 +
131 + 5. Submission of Contributions. Unless You explicitly state otherwise,
132 + any Contribution intentionally submitted for inclusion in the Work
133 + by You to the Licensor shall be under the terms and conditions of
134 + this License, without any additional terms or conditions.
135 + Notwithstanding the above, nothing herein shall supersede or modify
136 + the terms of any separate license agreement you may have executed
137 + with Licensor regarding such Contributions.
138 +
139 + 6. Trademarks. This License does not grant permission to use the trade
140 + names, trademarks, service marks, or product names of the Licensor,
141 + except as required for reasonable and customary use in describing the
142 + origin of the Work and reproducing the content of the NOTICE file.
143 +
144 + 7. Disclaimer of Warranty. Unless required by applicable law or
145 + agreed to in writing, Licensor provides the Work (and each
146 + Contributor provides its Contributions) on an "AS IS" BASIS,
147 + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 + implied, including, without limitation, any warranties or conditions
149 + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 + PARTICULAR PURPOSE. You are solely responsible for determining the
151 + appropriateness of using or redistributing the Work and assume any
152 + risks associated with Your exercise of permissions under this License.
153 +
154 + 8. Limitation of Liability. In no event and under no legal theory,
155 + whether in tort (including negligence), contract, or otherwise,
156 + unless required by applicable law (such as deliberate and grossly
157 + negligent acts) or agreed to in writing, shall any Contributor be
158 + liable to You for damages, including any direct, indirect, special,
159 + incidental, or consequential damages of any character arising as a
160 + result of this License or out of the use or inability to use the
161 + Work (including but not limited to damages for loss of goodwill,
162 + work stoppage, computer failure or malfunction, or any and all
163 + other commercial damages or losses), even if such Contributor
164 + has been advised of the possibility of such damages.
165 +
166 + 9. Accepting Warranty or Additional Liability. While redistributing
167 + the Work or Derivative Works thereof, You may choose to offer,
168 + and charge a fee for, acceptance of support, warranty, indemnity,
169 + or other liability obligations and/or rights consistent with this
170 + License. However, in accepting such obligations, You may act only
171 + on Your own behalf and on Your sole responsibility, not on behalf
172 + of any other Contributor, and only if You agree to indemnify,
173 + defend, and hold each Contributor harmless for any liability
174 + incurred by, or claims asserted against, such Contributor by reason
175 + of your accepting any such warranty or additional liability.
176 +
177 + END OF TERMS AND CONDITIONS
178 +
179 + APPENDIX: How to apply the Apache License to your work.
180 +
181 + To apply the Apache License to your work, attach the following
182 + boilerplate notice, with the fields enclosed by brackets "[]"
183 + replaced with your own identifying information. (Don't include
184 + the brackets!) The text should be enclosed in the appropriate
185 + comment syntax for the file format. We also recommend that a
186 + file or class name and description of purpose be included on the
187 + same "printed page" as the copyright notice for easier
188 + identification within third-party archives.
189 +
190 + Copyright [yyyy] [name of copyright owner]
191 +
192 + Licensed under the Apache License, Version 2.0 (the "License");
193 + you may not use this file except in compliance with the License.
194 + You may obtain a copy of the License at
195 +
196 + http://www.apache.org/licenses/LICENSE-2.0
197 +
198 + Unless required by applicable law or agreed to in writing, software
199 + distributed under the License is distributed on an "AS IS" BASIS,
200 + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 + See the License for the specific language governing permissions and
202 + limitations under the License.
1 +Embedded JavaScript templates<br/>
2 +[![Build Status](https://img.shields.io/travis/mde/ejs/master.svg?style=flat)](https://travis-ci.org/mde/ejs)
3 +[![Developing Dependencies](https://img.shields.io/david/dev/mde/ejs.svg?style=flat)](https://david-dm.org/mde/ejs?type=dev)
4 +[![Known Vulnerabilities](https://snyk.io/test/npm/ejs/badge.svg?style=flat)](https://snyk.io/test/npm/ejs)
5 +=============================
6 +
7 +## Installation
8 +
9 +```bash
10 +$ npm install ejs
11 +```
12 +
13 +## Features
14 +
15 + * Control flow with `<% %>`
16 + * Escaped output with `<%= %>` (escape function configurable)
17 + * Unescaped raw output with `<%- %>`
18 + * Newline-trim mode ('newline slurping') with `-%>` ending tag
19 + * Whitespace-trim mode (slurp all whitespace) for control flow with `<%_ _%>`
20 + * Custom delimiters (e.g. `[? ?]` instead of `<% %>`)
21 + * Includes
22 + * Client-side support
23 + * Static caching of intermediate JavaScript
24 + * Static caching of templates
25 + * Complies with the [Express](http://expressjs.com) view system
26 +
27 +## Example
28 +
29 +```ejs
30 +<% if (user) { %>
31 + <h2><%= user.name %></h2>
32 +<% } %>
33 +```
34 +
35 +Try EJS online at: https://ionicabizau.github.io/ejs-playground/.
36 +
37 +## Basic usage
38 +
39 +```javascript
40 +let template = ejs.compile(str, options);
41 +template(data);
42 +// => Rendered HTML string
43 +
44 +ejs.render(str, data, options);
45 +// => Rendered HTML string
46 +
47 +ejs.renderFile(filename, data, options, function(err, str){
48 + // str => Rendered HTML string
49 +});
50 +```
51 +
52 +It is also possible to use `ejs.render(dataAndOptions);` where you pass
53 +everything in a single object. In that case, you'll end up with local variables
54 +for all the passed options. However, be aware that your code could break if we
55 +add an option with the same name as one of your data object's properties.
56 +Therefore, we do not recommend using this shortcut.
57 +
58 +### Important
59 +You should never give end-users unfettered access to the EJS render method, If you do so you are using EJS in an inherently un-secure way.
60 +
61 +### Options
62 +
63 + - `cache` Compiled functions are cached, requires `filename`
64 + - `filename` The name of the file being rendered. Not required if you
65 + are using `renderFile()`. Used by `cache` to key caches, and for includes.
66 + - `root` Set project root for includes with an absolute path (e.g, /file.ejs).
67 + Can be array to try to resolve include from multiple directories.
68 + - `views` An array of paths to use when resolving includes with relative paths.
69 + - `context` Function execution context
70 + - `compileDebug` When `false` no debug instrumentation is compiled
71 + - `client` When `true`, compiles a function that can be rendered
72 + in the browser without needing to load the EJS Runtime
73 + ([ejs.min.js](https://github.com/mde/ejs/releases/latest)).
74 + - `delimiter` Character to use for inner delimiter, by default '%'
75 + - `openDelimiter` Character to use for opening delimiter, by default '<'
76 + - `closeDelimiter` Character to use for closing delimiter, by default '>'
77 + - `debug` Outputs generated function body
78 + - `strict` When set to `true`, generated function is in strict mode
79 + - `_with` Whether or not to use `with() {}` constructs. If `false`
80 + then the locals will be stored in the `locals` object. Set to `false` in strict mode.
81 + - `destructuredLocals` An array of local variables that are always destructured from
82 + the locals object, available even in strict mode.
83 + - `localsName` Name to use for the object storing local variables when not using
84 + `with` Defaults to `locals`
85 + - `rmWhitespace` Remove all safe-to-remove whitespace, including leading
86 + and trailing whitespace. It also enables a safer version of `-%>` line
87 + slurping for all scriptlet tags (it does not strip new lines of tags in
88 + the middle of a line).
89 + - `escape` The escaping function used with `<%=` construct. It is
90 + used in rendering and is `.toString()`ed in the generation of client functions.
91 + (By default escapes XML).
92 + - `outputFunctionName` Set to a string (e.g., 'echo' or 'print') for a function to print
93 + output inside scriptlet tags.
94 + - `async` When `true`, EJS will use an async function for rendering. (Depends
95 + on async/await support in the JS runtime.
96 + - `includer` Custom function to handle EJS includes, receives `(originalPath, parsedPath)`
97 + parameters, where `originalPath` is the path in include as-is and `parsedPath` is the
98 + previously resolved path. Should return an object `{ filename, template }`,
99 + you may return only one of the properties, where `filename` is the final parsed path and `template`
100 + is the included content.
101 +
102 +This project uses [JSDoc](http://usejsdoc.org/). For the full public API
103 +documentation, clone the repository and run `jake doc`. This will run JSDoc
104 +with the proper options and output the documentation to `out/`. If you want
105 +the both the public & private API docs, run `jake devdoc` instead.
106 +
107 +### Tags
108 +
109 + - `<%` 'Scriptlet' tag, for control-flow, no output
110 + - `<%_` 'Whitespace Slurping' Scriptlet tag, strips all whitespace before it
111 + - `<%=` Outputs the value into the template (escaped)
112 + - `<%-` Outputs the unescaped value into the template
113 + - `<%#` Comment tag, no execution, no output
114 + - `<%%` Outputs a literal '<%'
115 + - `%%>` Outputs a literal '%>'
116 + - `%>` Plain ending tag
117 + - `-%>` Trim-mode ('newline slurp') tag, trims following newline
118 + - `_%>` 'Whitespace Slurping' ending tag, removes all whitespace after it
119 +
120 +For the full syntax documentation, please see [docs/syntax.md](https://github.com/mde/ejs/blob/master/docs/syntax.md).
121 +
122 +### Includes
123 +
124 +Includes either have to be an absolute path, or, if not, are assumed as
125 +relative to the template with the `include` call. For example if you are
126 +including `./views/user/show.ejs` from `./views/users.ejs` you would
127 +use `<%- include('user/show') %>`.
128 +
129 +You must specify the `filename` option for the template with the `include`
130 +call unless you are using `renderFile()`.
131 +
132 +You'll likely want to use the raw output tag (`<%-`) with your include to avoid
133 +double-escaping the HTML output.
134 +
135 +```ejs
136 +<ul>
137 + <% users.forEach(function(user){ %>
138 + <%- include('user/show', {user: user}) %>
139 + <% }); %>
140 +</ul>
141 +```
142 +
143 +Includes are inserted at runtime, so you can use variables for the path in the
144 +`include` call (for example `<%- include(somePath) %>`). Variables in your
145 +top-level data object are available to all your includes, but local variables
146 +need to be passed down.
147 +
148 +NOTE: Include preprocessor directives (`<% include user/show %>`) are
149 +not supported in v3.0+.
150 +
151 +## Custom delimiters
152 +
153 +Custom delimiters can be applied on a per-template basis, or globally:
154 +
155 +```javascript
156 +let ejs = require('ejs'),
157 + users = ['geddy', 'neil', 'alex'];
158 +
159 +// Just one template
160 +ejs.render('<p>[?= users.join(" | "); ?]</p>', {users: users}, {delimiter: '?', openDelimiter: '[', closeDelimiter: ']'});
161 +// => '<p>geddy | neil | alex</p>'
162 +
163 +// Or globally
164 +ejs.delimiter = '?';
165 +ejs.openDelimiter = '[';
166 +ejs.closeDelimiter = ']';
167 +ejs.render('<p>[?= users.join(" | "); ?]</p>', {users: users});
168 +// => '<p>geddy | neil | alex</p>'
169 +```
170 +
171 +### Caching
172 +
173 +EJS ships with a basic in-process cache for caching the intermediate JavaScript
174 +functions used to render templates. It's easy to plug in LRU caching using
175 +Node's `lru-cache` library:
176 +
177 +```javascript
178 +let ejs = require('ejs'),
179 + LRU = require('lru-cache');
180 +ejs.cache = LRU(100); // LRU cache with 100-item limit
181 +```
182 +
183 +If you want to clear the EJS cache, call `ejs.clearCache`. If you're using the
184 +LRU cache and need a different limit, simple reset `ejs.cache` to a new instance
185 +of the LRU.
186 +
187 +### Custom file loader
188 +
189 +The default file loader is `fs.readFileSync`, if you want to customize it, you can set ejs.fileLoader.
190 +
191 +```javascript
192 +let ejs = require('ejs');
193 +let myFileLoad = function (filePath) {
194 + return 'myFileLoad: ' + fs.readFileSync(filePath);
195 +};
196 +
197 +ejs.fileLoader = myFileLoad;
198 +```
199 +
200 +With this feature, you can preprocess the template before reading it.
201 +
202 +### Layouts
203 +
204 +EJS does not specifically support blocks, but layouts can be implemented by
205 +including headers and footers, like so:
206 +
207 +
208 +```ejs
209 +<%- include('header') -%>
210 +<h1>
211 + Title
212 +</h1>
213 +<p>
214 + My page
215 +</p>
216 +<%- include('footer') -%>
217 +```
218 +
219 +## Client-side support
220 +
221 +Go to the [Latest Release](https://github.com/mde/ejs/releases/latest), download
222 +`./ejs.js` or `./ejs.min.js`. Alternately, you can compile it yourself by cloning
223 +the repository and running `jake build` (or `$(npm bin)/jake build` if jake is
224 +not installed globally).
225 +
226 +Include one of these files on your page, and `ejs` should be available globally.
227 +
228 +### Example
229 +
230 +```html
231 +<div id="output"></div>
232 +<script src="ejs.min.js"></script>
233 +<script>
234 + let people = ['geddy', 'neil', 'alex'],
235 + html = ejs.render('<%= people.join(", "); %>', {people: people});
236 + // With jQuery:
237 + $('#output').html(html);
238 + // Vanilla JS:
239 + document.getElementById('output').innerHTML = html;
240 +</script>
241 +```
242 +
243 +### Caveats
244 +
245 +Most of EJS will work as expected; however, there are a few things to note:
246 +
247 +1. Obviously, since you do not have access to the filesystem, `ejs.renderFile()` won't work.
248 +2. For the same reason, `include`s do not work unless you use an `include callback`. Here is an example:
249 + ```javascript
250 + let str = "Hello <%= include('file', {person: 'John'}); %>",
251 + fn = ejs.compile(str, {client: true});
252 +
253 + fn(data, null, function(path, d){ // include callback
254 + // path -> 'file'
255 + // d -> {person: 'John'}
256 + // Put your code here
257 + // Return the contents of file as a string
258 + }); // returns rendered string
259 + ```
260 +
261 +See the [examples folder](https://github.com/mde/ejs/tree/master/examples) for more details.
262 +
263 +## CLI
264 +
265 +EJS ships with a full-featured CLI. Options are similar to those used in JavaScript code:
266 +
267 + - `-o / --output-file FILE` Write the rendered output to FILE rather than stdout.
268 + - `-f / --data-file FILE` Must be JSON-formatted. Use parsed input from FILE as data for rendering.
269 + - `-i / --data-input STRING` Must be JSON-formatted and URI-encoded. Use parsed input from STRING as data for rendering.
270 + - `-m / --delimiter CHARACTER` Use CHARACTER with angle brackets for open/close (defaults to %).
271 + - `-p / --open-delimiter CHARACTER` Use CHARACTER instead of left angle bracket to open.
272 + - `-c / --close-delimiter CHARACTER` Use CHARACTER instead of right angle bracket to close.
273 + - `-s / --strict` When set to `true`, generated function is in strict mode
274 + - `-n / --no-with` Use 'locals' object for vars rather than using `with` (implies --strict).
275 + - `-l / --locals-name` Name to use for the object storing local variables when not using `with`.
276 + - `-w / --rm-whitespace` Remove all safe-to-remove whitespace, including leading and trailing whitespace.
277 + - `-d / --debug` Outputs generated function body
278 + - `-h / --help` Display this help message.
279 + - `-V/v / --version` Display the EJS version.
280 +
281 +Here are some examples of usage:
282 +
283 +```shell
284 +$ ejs -p [ -c ] ./template_file.ejs -o ./output.html
285 +$ ejs ./test/fixtures/user.ejs name=Lerxst
286 +$ ejs -n -l _ ./some_template.ejs -f ./data_file.json
287 +```
288 +
289 +### Data input
290 +
291 +There is a variety of ways to pass the CLI data for rendering.
292 +
293 +Stdin:
294 +
295 +```shell
296 +$ ./test/fixtures/user_data.json | ejs ./test/fixtures/user.ejs
297 +$ ejs ./test/fixtures/user.ejs < test/fixtures/user_data.json
298 +```
299 +
300 +A data file:
301 +
302 +```shell
303 +$ ejs ./test/fixtures/user.ejs -f ./user_data.json
304 +```
305 +
306 +A command-line option (must be URI-encoded):
307 +
308 +```shell
309 +./bin/cli.js -i %7B%22name%22%3A%20%22foo%22%7D ./test/fixtures/user.ejs
310 +```
311 +
312 +Or, passing values directly at the end of the invocation:
313 +
314 +```shell
315 +./bin/cli.js -m $ ./test/fixtures/user.ejs name=foo
316 +```
317 +
318 +### Output
319 +
320 +The CLI by default send output to stdout, but you can use the `-o` or `--output-file`
321 +flag to specify a target file to send the output to.
322 +
323 +## IDE Integration with Syntax Highlighting
324 +
325 +VSCode:Javascript EJS by *DigitalBrainstem*
326 +
327 +## Related projects
328 +
329 +There are a number of implementations of EJS:
330 +
331 + * TJ's implementation, the v1 of this library: https://github.com/tj/ejs
332 + * EJS Embedded JavaScript Framework on Google Code: https://code.google.com/p/embeddedjavascript/
333 + * Sam Stephenson's Ruby implementation: https://rubygems.org/gems/ejs
334 + * Erubis, an ERB implementation which also runs JavaScript: http://www.kuwata-lab.com/erubis/users-guide.04.html#lang-javascript
335 + * DigitalBrainstem EJS Language support: https://github.com/Digitalbrainstem/ejs-grammar
336 +
337 +## License
338 +
339 +Licensed under the Apache License, Version 2.0
340 +(<http://www.apache.org/licenses/LICENSE-2.0>)
341 +
342 +- - -
343 +EJS Embedded JavaScript templates copyright 2112
344 +mde@fleegix.org.
1 +#!/usr/bin/env node
2 +/*
3 + * EJS Embedded JavaScript templates
4 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
5 + *
6 + * Licensed under the Apache License, Version 2.0 (the "License");
7 + * you may not use this file except in compliance with the License.
8 + * You may obtain a copy of the License at
9 + *
10 + * http://www.apache.org/licenses/LICENSE-2.0
11 + *
12 + * Unless required by applicable law or agreed to in writing, software
13 + * distributed under the License is distributed on an "AS IS" BASIS,
14 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 + * See the License for the specific language governing permissions and
16 + * limitations under the License.
17 + *
18 +*/
19 +
20 +
21 +let program = require('jake').program;
22 +delete global.jake; // NO NOT WANT
23 +program.setTaskNames = function (n) { this.taskNames = n; };
24 +
25 +let ejs = require('../lib/ejs');
26 +let { hyphenToCamel } = require('../lib/utils');
27 +let fs = require('fs');
28 +let args = process.argv.slice(2);
29 +let usage = fs.readFileSync(`${__dirname}/../usage.txt`).toString();
30 +
31 +const CLI_OPTS = [
32 + { full: 'output-file',
33 + abbr: 'o',
34 + expectValue: true,
35 + },
36 + { full: 'data-file',
37 + abbr: 'f',
38 + expectValue: true,
39 + },
40 + { full: 'data-input',
41 + abbr: 'i',
42 + expectValue: true,
43 + },
44 + { full: 'delimiter',
45 + abbr: 'm',
46 + expectValue: true,
47 + passThrough: true,
48 + },
49 + { full: 'open-delimiter',
50 + abbr: 'p',
51 + expectValue: true,
52 + passThrough: true,
53 + },
54 + { full: 'close-delimiter',
55 + abbr: 'c',
56 + expectValue: true,
57 + passThrough: true,
58 + },
59 + { full: 'strict',
60 + abbr: 's',
61 + expectValue: false,
62 + allowValue: false,
63 + passThrough: true,
64 + },
65 + { full: 'no-with',
66 + abbr: 'n',
67 + expectValue: false,
68 + allowValue: false,
69 + },
70 + { full: 'locals-name',
71 + abbr: 'l',
72 + expectValue: true,
73 + passThrough: true,
74 + },
75 + { full: 'rm-whitespace',
76 + abbr: 'w',
77 + expectValue: false,
78 + allowValue: false,
79 + passThrough: true,
80 + },
81 + { full: 'debug',
82 + abbr: 'd',
83 + expectValue: false,
84 + allowValue: false,
85 + passThrough: true,
86 + },
87 + { full: 'help',
88 + abbr: 'h',
89 + passThrough: true,
90 + },
91 + { full: 'version',
92 + abbr: 'V',
93 + passThrough: true,
94 + },
95 + // Alias lowercase v
96 + { full: 'version',
97 + abbr: 'v',
98 + passThrough: true,
99 + },
100 +];
101 +
102 +let preempts = {
103 + version: function () {
104 + program.die(ejs.VERSION);
105 + },
106 + help: function () {
107 + program.die(usage);
108 + }
109 +};
110 +
111 +let stdin = '';
112 +process.stdin.setEncoding('utf8');
113 +process.stdin.on('readable', () => {
114 + let chunk;
115 + while ((chunk = process.stdin.read()) !== null) {
116 + stdin += chunk;
117 + }
118 +});
119 +
120 +function run() {
121 +
122 + program.availableOpts = CLI_OPTS;
123 + program.parseArgs(args);
124 +
125 + let templatePath = program.taskNames[0];
126 + let pVals = program.envVars;
127 + let pOpts = {};
128 +
129 + for (let p in program.opts) {
130 + let name = hyphenToCamel(p);
131 + pOpts[name] = program.opts[p];
132 + }
133 +
134 + let opts = {};
135 + let vals = {};
136 +
137 + // Same-named 'passthrough' opts
138 + CLI_OPTS.forEach((opt) => {
139 + let optName = hyphenToCamel(opt.full);
140 + if (opt.passThrough && typeof pOpts[optName] != 'undefined') {
141 + opts[optName] = pOpts[optName];
142 + }
143 + });
144 +
145 + // Bail out for help/version
146 + for (let p in opts) {
147 + if (preempts[p]) {
148 + return preempts[p]();
149 + }
150 + }
151 +
152 + // Default to having views relative from the current working directory
153 + opts.views = ['.'];
154 +
155 + // Ensure there's a template to render
156 + if (!templatePath) {
157 + throw new Error('Please provide a template path. (Run ejs -h for help)');
158 + }
159 +
160 + if (opts.strict) {
161 + pOpts.noWith = true;
162 + }
163 + if (pOpts.noWith) {
164 + opts._with = false;
165 + }
166 +
167 + // Grab and parse any input data, in order of precedence:
168 + // 1. Stdin
169 + // 2. CLI arg via -i
170 + // 3. Data file via -f
171 + // Any individual vals passed at the end (e.g., foo=bar) will override
172 + // any vals previously set
173 + let input;
174 + let err = new Error('Please do not pass data multiple ways. Pick one of stdin, -f, or -i.');
175 + if (stdin) {
176 + input = stdin;
177 + }
178 + else if (pOpts.dataInput) {
179 + if (input) {
180 + throw err;
181 + }
182 + input = decodeURIComponent(pOpts.dataInput);
183 + }
184 + else if (pOpts.dataFile) {
185 + if (input) {
186 + throw err;
187 + }
188 + input = fs.readFileSync(pOpts.dataFile).toString();
189 + }
190 +
191 + if (input) {
192 + vals = JSON.parse(input);
193 + }
194 +
195 + // Override / set any individual values passed from the command line
196 + for (let p in pVals) {
197 + vals[p] = pVals[p];
198 + }
199 +
200 + let template = fs.readFileSync(templatePath).toString();
201 + let output = ejs.render(template, vals, opts);
202 + if (pOpts.outputFile) {
203 + fs.writeFileSync(pOpts.outputFile, output);
204 + }
205 + else {
206 + process.stdout.write(output);
207 + }
208 + process.exit();
209 +}
210 +
211 +// Defer execution so that stdin can be read if necessary
212 +setImmediate(run);
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;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2 +/*
3 + * EJS Embedded JavaScript templates
4 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
5 + *
6 + * Licensed under the Apache License, Version 2.0 (the "License");
7 + * you may not use this file except in compliance with the License.
8 + * You may obtain a copy of the License at
9 + *
10 + * http://www.apache.org/licenses/LICENSE-2.0
11 + *
12 + * Unless required by applicable law or agreed to in writing, software
13 + * distributed under the License is distributed on an "AS IS" BASIS,
14 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 + * See the License for the specific language governing permissions and
16 + * limitations under the License.
17 + *
18 +*/
19 +
20 +'use strict';
21 +
22 +/**
23 + * @file Embedded JavaScript templating engine. {@link http://ejs.co}
24 + * @author Matthew Eernisse <mde@fleegix.org>
25 + * @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
26 + * @project EJS
27 + * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0}
28 + */
29 +
30 +/**
31 + * EJS internal functions.
32 + *
33 + * Technically this "module" lies in the same file as {@link module:ejs}, for
34 + * the sake of organization all the private functions re grouped into this
35 + * module.
36 + *
37 + * @module ejs-internal
38 + * @private
39 + */
40 +
41 +/**
42 + * Embedded JavaScript templating engine.
43 + *
44 + * @module ejs
45 + * @public
46 + */
47 +
48 +
49 +var fs = require('fs');
50 +var path = require('path');
51 +var utils = require('./utils');
52 +
53 +var scopeOptionWarned = false;
54 +/** @type {string} */
55 +var _VERSION_STRING = require('../package.json').version;
56 +var _DEFAULT_OPEN_DELIMITER = '<';
57 +var _DEFAULT_CLOSE_DELIMITER = '>';
58 +var _DEFAULT_DELIMITER = '%';
59 +var _DEFAULT_LOCALS_NAME = 'locals';
60 +var _NAME = 'ejs';
61 +var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)';
62 +var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug',
63 + 'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async'];
64 +// We don't allow 'cache' option to be passed in the data obj for
65 +// the normal `render` call, but this is where Express 2 & 3 put it
66 +// so we make an exception for `renderFile`
67 +var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache');
68 +var _BOM = /^\uFEFF/;
69 +var _JS_IDENTIFIER = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/;
70 +
71 +/**
72 + * EJS template function cache. This can be a LRU object from lru-cache NPM
73 + * module. By default, it is {@link module:utils.cache}, a simple in-process
74 + * cache that grows continuously.
75 + *
76 + * @type {Cache}
77 + */
78 +
79 +exports.cache = utils.cache;
80 +
81 +/**
82 + * Custom file loader. Useful for template preprocessing or restricting access
83 + * to a certain part of the filesystem.
84 + *
85 + * @type {fileLoader}
86 + */
87 +
88 +exports.fileLoader = fs.readFileSync;
89 +
90 +/**
91 + * Name of the object containing the locals.
92 + *
93 + * This variable is overridden by {@link Options}`.localsName` if it is not
94 + * `undefined`.
95 + *
96 + * @type {String}
97 + * @public
98 + */
99 +
100 +exports.localsName = _DEFAULT_LOCALS_NAME;
101 +
102 +/**
103 + * Promise implementation -- defaults to the native implementation if available
104 + * This is mostly just for testability
105 + *
106 + * @type {PromiseConstructorLike}
107 + * @public
108 + */
109 +
110 +exports.promiseImpl = (new Function('return this;'))().Promise;
111 +
112 +/**
113 + * Get the path to the included file from the parent file path and the
114 + * specified path.
115 + *
116 + * @param {String} name specified path
117 + * @param {String} filename parent file path
118 + * @param {Boolean} [isDir=false] whether the parent file path is a directory
119 + * @return {String}
120 + */
121 +exports.resolveInclude = function(name, filename, isDir) {
122 + var dirname = path.dirname;
123 + var extname = path.extname;
124 + var resolve = path.resolve;
125 + var includePath = resolve(isDir ? filename : dirname(filename), name);
126 + var ext = extname(name);
127 + if (!ext) {
128 + includePath += '.ejs';
129 + }
130 + return includePath;
131 +};
132 +
133 +/**
134 + * Try to resolve file path on multiple directories
135 + *
136 + * @param {String} name specified path
137 + * @param {Array<String>} paths list of possible parent directory paths
138 + * @return {String}
139 + */
140 +function resolvePaths(name, paths) {
141 + var filePath;
142 + if (paths.some(function (v) {
143 + filePath = exports.resolveInclude(name, v, true);
144 + return fs.existsSync(filePath);
145 + })) {
146 + return filePath;
147 + }
148 +}
149 +
150 +/**
151 + * Get the path to the included file by Options
152 + *
153 + * @param {String} path specified path
154 + * @param {Options} options compilation options
155 + * @return {String}
156 + */
157 +function getIncludePath(path, options) {
158 + var includePath;
159 + var filePath;
160 + var views = options.views;
161 + var match = /^[A-Za-z]+:\\|^\//.exec(path);
162 +
163 + // Abs path
164 + if (match && match.length) {
165 + path = path.replace(/^\/*/, '');
166 + if (Array.isArray(options.root)) {
167 + includePath = resolvePaths(path, options.root);
168 + } else {
169 + includePath = exports.resolveInclude(path, options.root || '/', true);
170 + }
171 + }
172 + // Relative paths
173 + else {
174 + // Look relative to a passed filename first
175 + if (options.filename) {
176 + filePath = exports.resolveInclude(path, options.filename);
177 + if (fs.existsSync(filePath)) {
178 + includePath = filePath;
179 + }
180 + }
181 + // Then look in any views directories
182 + if (!includePath && Array.isArray(views)) {
183 + includePath = resolvePaths(path, views);
184 + }
185 + if (!includePath && typeof options.includer !== 'function') {
186 + throw new Error('Could not find the include file "' +
187 + options.escapeFunction(path) + '"');
188 + }
189 + }
190 + return includePath;
191 +}
192 +
193 +/**
194 + * Get the template from a string or a file, either compiled on-the-fly or
195 + * read from cache (if enabled), and cache the template if needed.
196 + *
197 + * If `template` is not set, the file specified in `options.filename` will be
198 + * read.
199 + *
200 + * If `options.cache` is true, this function reads the file from
201 + * `options.filename` so it must be set prior to calling this function.
202 + *
203 + * @memberof module:ejs-internal
204 + * @param {Options} options compilation options
205 + * @param {String} [template] template source
206 + * @return {(TemplateFunction|ClientFunction)}
207 + * Depending on the value of `options.client`, either type might be returned.
208 + * @static
209 + */
210 +
211 +function handleCache(options, template) {
212 + var func;
213 + var filename = options.filename;
214 + var hasTemplate = arguments.length > 1;
215 +
216 + if (options.cache) {
217 + if (!filename) {
218 + throw new Error('cache option requires a filename');
219 + }
220 + func = exports.cache.get(filename);
221 + if (func) {
222 + return func;
223 + }
224 + if (!hasTemplate) {
225 + template = fileLoader(filename).toString().replace(_BOM, '');
226 + }
227 + }
228 + else if (!hasTemplate) {
229 + // istanbul ignore if: should not happen at all
230 + if (!filename) {
231 + throw new Error('Internal EJS error: no file name or template '
232 + + 'provided');
233 + }
234 + template = fileLoader(filename).toString().replace(_BOM, '');
235 + }
236 + func = exports.compile(template, options);
237 + if (options.cache) {
238 + exports.cache.set(filename, func);
239 + }
240 + return func;
241 +}
242 +
243 +/**
244 + * Try calling handleCache with the given options and data and call the
245 + * callback with the result. If an error occurs, call the callback with
246 + * the error. Used by renderFile().
247 + *
248 + * @memberof module:ejs-internal
249 + * @param {Options} options compilation options
250 + * @param {Object} data template data
251 + * @param {RenderFileCallback} cb callback
252 + * @static
253 + */
254 +
255 +function tryHandleCache(options, data, cb) {
256 + var result;
257 + if (!cb) {
258 + if (typeof exports.promiseImpl == 'function') {
259 + return new exports.promiseImpl(function (resolve, reject) {
260 + try {
261 + result = handleCache(options)(data);
262 + resolve(result);
263 + }
264 + catch (err) {
265 + reject(err);
266 + }
267 + });
268 + }
269 + else {
270 + throw new Error('Please provide a callback function');
271 + }
272 + }
273 + else {
274 + try {
275 + result = handleCache(options)(data);
276 + }
277 + catch (err) {
278 + return cb(err);
279 + }
280 +
281 + cb(null, result);
282 + }
283 +}
284 +
285 +/**
286 + * fileLoader is independent
287 + *
288 + * @param {String} filePath ejs file path.
289 + * @return {String} The contents of the specified file.
290 + * @static
291 + */
292 +
293 +function fileLoader(filePath){
294 + return exports.fileLoader(filePath);
295 +}
296 +
297 +/**
298 + * Get the template function.
299 + *
300 + * If `options.cache` is `true`, then the template is cached.
301 + *
302 + * @memberof module:ejs-internal
303 + * @param {String} path path for the specified file
304 + * @param {Options} options compilation options
305 + * @return {(TemplateFunction|ClientFunction)}
306 + * Depending on the value of `options.client`, either type might be returned
307 + * @static
308 + */
309 +
310 +function includeFile(path, options) {
311 + var opts = utils.shallowCopy(utils.createNullProtoObjWherePossible(), options);
312 + opts.filename = getIncludePath(path, opts);
313 + if (typeof options.includer === 'function') {
314 + var includerResult = options.includer(path, opts.filename);
315 + if (includerResult) {
316 + if (includerResult.filename) {
317 + opts.filename = includerResult.filename;
318 + }
319 + if (includerResult.template) {
320 + return handleCache(opts, includerResult.template);
321 + }
322 + }
323 + }
324 + return handleCache(opts);
325 +}
326 +
327 +/**
328 + * Re-throw the given `err` in context to the `str` of ejs, `filename`, and
329 + * `lineno`.
330 + *
331 + * @implements {RethrowCallback}
332 + * @memberof module:ejs-internal
333 + * @param {Error} err Error object
334 + * @param {String} str EJS source
335 + * @param {String} flnm file name of the EJS file
336 + * @param {Number} lineno line number of the error
337 + * @param {EscapeCallback} esc
338 + * @static
339 + */
340 +
341 +function rethrow(err, str, flnm, lineno, esc) {
342 + var lines = str.split('\n');
343 + var start = Math.max(lineno - 3, 0);
344 + var end = Math.min(lines.length, lineno + 3);
345 + var filename = esc(flnm);
346 + // Error context
347 + var context = lines.slice(start, end).map(function (line, i){
348 + var curr = i + start + 1;
349 + return (curr == lineno ? ' >> ' : ' ')
350 + + curr
351 + + '| '
352 + + line;
353 + }).join('\n');
354 +
355 + // Alter exception message
356 + err.path = filename;
357 + err.message = (filename || 'ejs') + ':'
358 + + lineno + '\n'
359 + + context + '\n\n'
360 + + err.message;
361 +
362 + throw err;
363 +}
364 +
365 +function stripSemi(str){
366 + return str.replace(/;(\s*$)/, '$1');
367 +}
368 +
369 +/**
370 + * Compile the given `str` of ejs into a template function.
371 + *
372 + * @param {String} template EJS template
373 + *
374 + * @param {Options} [opts] compilation options
375 + *
376 + * @return {(TemplateFunction|ClientFunction)}
377 + * Depending on the value of `opts.client`, either type might be returned.
378 + * Note that the return type of the function also depends on the value of `opts.async`.
379 + * @public
380 + */
381 +
382 +exports.compile = function compile(template, opts) {
383 + var templ;
384 +
385 + // v1 compat
386 + // 'scope' is 'context'
387 + // FIXME: Remove this in a future version
388 + if (opts && opts.scope) {
389 + if (!scopeOptionWarned){
390 + console.warn('`scope` option is deprecated and will be removed in EJS 3');
391 + scopeOptionWarned = true;
392 + }
393 + if (!opts.context) {
394 + opts.context = opts.scope;
395 + }
396 + delete opts.scope;
397 + }
398 + templ = new Template(template, opts);
399 + return templ.compile();
400 +};
401 +
402 +/**
403 + * Render the given `template` of ejs.
404 + *
405 + * If you would like to include options but not data, you need to explicitly
406 + * call this function with `data` being an empty object or `null`.
407 + *
408 + * @param {String} template EJS template
409 + * @param {Object} [data={}] template data
410 + * @param {Options} [opts={}] compilation and rendering options
411 + * @return {(String|Promise<String>)}
412 + * Return value type depends on `opts.async`.
413 + * @public
414 + */
415 +
416 +exports.render = function (template, d, o) {
417 + var data = d || utils.createNullProtoObjWherePossible();
418 + var opts = o || utils.createNullProtoObjWherePossible();
419 +
420 + // No options object -- if there are optiony names
421 + // in the data, copy them to options
422 + if (arguments.length == 2) {
423 + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
424 + }
425 +
426 + return handleCache(opts, template)(data);
427 +};
428 +
429 +/**
430 + * Render an EJS file at the given `path` and callback `cb(err, str)`.
431 + *
432 + * If you would like to include options but not data, you need to explicitly
433 + * call this function with `data` being an empty object or `null`.
434 + *
435 + * @param {String} path path to the EJS file
436 + * @param {Object} [data={}] template data
437 + * @param {Options} [opts={}] compilation and rendering options
438 + * @param {RenderFileCallback} cb callback
439 + * @public
440 + */
441 +
442 +exports.renderFile = function () {
443 + var args = Array.prototype.slice.call(arguments);
444 + var filename = args.shift();
445 + var cb;
446 + var opts = {filename: filename};
447 + var data;
448 + var viewOpts;
449 +
450 + // Do we have a callback?
451 + if (typeof arguments[arguments.length - 1] == 'function') {
452 + cb = args.pop();
453 + }
454 + // Do we have data/opts?
455 + if (args.length) {
456 + // Should always have data obj
457 + data = args.shift();
458 + // Normal passed opts (data obj + opts obj)
459 + if (args.length) {
460 + // Use shallowCopy so we don't pollute passed in opts obj with new vals
461 + utils.shallowCopy(opts, args.pop());
462 + }
463 + // Special casing for Express (settings + opts-in-data)
464 + else {
465 + // Express 3 and 4
466 + if (data.settings) {
467 + // Pull a few things from known locations
468 + if (data.settings.views) {
469 + opts.views = data.settings.views;
470 + }
471 + if (data.settings['view cache']) {
472 + opts.cache = true;
473 + }
474 + // Undocumented after Express 2, but still usable, esp. for
475 + // items that are unsafe to be passed along with data, like `root`
476 + viewOpts = data.settings['view options'];
477 + if (viewOpts) {
478 + utils.shallowCopy(opts, viewOpts);
479 + }
480 + }
481 + // Express 2 and lower, values set in app.locals, or people who just
482 + // want to pass options in their data. NOTE: These values will override
483 + // anything previously set in settings or settings['view options']
484 + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
485 + }
486 + opts.filename = filename;
487 + }
488 + else {
489 + data = utils.createNullProtoObjWherePossible();
490 + }
491 +
492 + return tryHandleCache(opts, data, cb);
493 +};
494 +
495 +/**
496 + * Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
497 + * @public
498 + */
499 +
500 +/**
501 + * EJS template class
502 + * @public
503 + */
504 +exports.Template = Template;
505 +
506 +exports.clearCache = function () {
507 + exports.cache.reset();
508 +};
509 +
510 +function Template(text, opts) {
511 + opts = opts || utils.createNullProtoObjWherePossible();
512 + var options = utils.createNullProtoObjWherePossible();
513 + this.templateText = text;
514 + /** @type {string | null} */
515 + this.mode = null;
516 + this.truncate = false;
517 + this.currentLine = 1;
518 + this.source = '';
519 + options.client = opts.client || false;
520 + options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
521 + options.compileDebug = opts.compileDebug !== false;
522 + options.debug = !!opts.debug;
523 + options.filename = opts.filename;
524 + options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
525 + options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
526 + options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
527 + options.strict = opts.strict || false;
528 + options.context = opts.context;
529 + options.cache = opts.cache || false;
530 + options.rmWhitespace = opts.rmWhitespace;
531 + options.root = opts.root;
532 + options.includer = opts.includer;
533 + options.outputFunctionName = opts.outputFunctionName;
534 + options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
535 + options.views = opts.views;
536 + options.async = opts.async;
537 + options.destructuredLocals = opts.destructuredLocals;
538 + options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true;
539 +
540 + if (options.strict) {
541 + options._with = false;
542 + }
543 + else {
544 + options._with = typeof opts._with != 'undefined' ? opts._with : true;
545 + }
546 +
547 + this.opts = options;
548 +
549 + this.regex = this.createRegex();
550 +}
551 +
552 +Template.modes = {
553 + EVAL: 'eval',
554 + ESCAPED: 'escaped',
555 + RAW: 'raw',
556 + COMMENT: 'comment',
557 + LITERAL: 'literal'
558 +};
559 +
560 +Template.prototype = {
561 + createRegex: function () {
562 + var str = _REGEX_STRING;
563 + var delim = utils.escapeRegExpChars(this.opts.delimiter);
564 + var open = utils.escapeRegExpChars(this.opts.openDelimiter);
565 + var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
566 + str = str.replace(/%/g, delim)
567 + .replace(/</g, open)
568 + .replace(/>/g, close);
569 + return new RegExp(str);
570 + },
571 +
572 + compile: function () {
573 + /** @type {string} */
574 + var src;
575 + /** @type {ClientFunction} */
576 + var fn;
577 + var opts = this.opts;
578 + var prepended = '';
579 + var appended = '';
580 + /** @type {EscapeCallback} */
581 + var escapeFn = opts.escapeFunction;
582 + /** @type {FunctionConstructor} */
583 + var ctor;
584 + /** @type {string} */
585 + var sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : 'undefined';
586 +
587 + if (!this.source) {
588 + this.generateSource();
589 + prepended +=
590 + ' var __output = "";\n' +
591 + ' function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
592 + if (opts.outputFunctionName) {
593 + if (!_JS_IDENTIFIER.test(opts.outputFunctionName)) {
594 + throw new Error('outputFunctionName is not a valid JS identifier.');
595 + }
596 + prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
597 + }
598 + if (opts.localsName && !_JS_IDENTIFIER.test(opts.localsName)) {
599 + throw new Error('localsName is not a valid JS identifier.');
600 + }
601 + if (opts.destructuredLocals && opts.destructuredLocals.length) {
602 + var destructuring = ' var __locals = (' + opts.localsName + ' || {}),\n';
603 + for (var i = 0; i < opts.destructuredLocals.length; i++) {
604 + var name = opts.destructuredLocals[i];
605 + if (!_JS_IDENTIFIER.test(name)) {
606 + throw new Error('destructuredLocals[' + i + '] is not a valid JS identifier.');
607 + }
608 + if (i > 0) {
609 + destructuring += ',\n ';
610 + }
611 + destructuring += name + ' = __locals.' + name;
612 + }
613 + prepended += destructuring + ';\n';
614 + }
615 + if (opts._with !== false) {
616 + prepended += ' with (' + opts.localsName + ' || {}) {' + '\n';
617 + appended += ' }' + '\n';
618 + }
619 + appended += ' return __output;' + '\n';
620 + this.source = prepended + this.source + appended;
621 + }
622 +
623 + if (opts.compileDebug) {
624 + src = 'var __line = 1' + '\n'
625 + + ' , __lines = ' + JSON.stringify(this.templateText) + '\n'
626 + + ' , __filename = ' + sanitizedFilename + ';' + '\n'
627 + + 'try {' + '\n'
628 + + this.source
629 + + '} catch (e) {' + '\n'
630 + + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
631 + + '}' + '\n';
632 + }
633 + else {
634 + src = this.source;
635 + }
636 +
637 + if (opts.client) {
638 + src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src;
639 + if (opts.compileDebug) {
640 + src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
641 + }
642 + }
643 +
644 + if (opts.strict) {
645 + src = '"use strict";\n' + src;
646 + }
647 + if (opts.debug) {
648 + console.log(src);
649 + }
650 + if (opts.compileDebug && opts.filename) {
651 + src = src + '\n'
652 + + '//# sourceURL=' + sanitizedFilename + '\n';
653 + }
654 +
655 + try {
656 + if (opts.async) {
657 + // Have to use generated function for this, since in envs without support,
658 + // it breaks in parsing
659 + try {
660 + ctor = (new Function('return (async function(){}).constructor;'))();
661 + }
662 + catch(e) {
663 + if (e instanceof SyntaxError) {
664 + throw new Error('This environment does not support async/await');
665 + }
666 + else {
667 + throw e;
668 + }
669 + }
670 + }
671 + else {
672 + ctor = Function;
673 + }
674 + fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src);
675 + }
676 + catch(e) {
677 + // istanbul ignore else
678 + if (e instanceof SyntaxError) {
679 + if (opts.filename) {
680 + e.message += ' in ' + opts.filename;
681 + }
682 + e.message += ' while compiling ejs\n\n';
683 + e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n';
684 + e.message += 'https://github.com/RyanZim/EJS-Lint';
685 + if (!opts.async) {
686 + e.message += '\n';
687 + e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.';
688 + }
689 + }
690 + throw e;
691 + }
692 +
693 + // Return a callable function which will execute the function
694 + // created by the source-code, with the passed data as locals
695 + // Adds a local `include` function which allows full recursive include
696 + var returnedFn = opts.client ? fn : function anonymous(data) {
697 + var include = function (path, includeData) {
698 + var d = utils.shallowCopy(utils.createNullProtoObjWherePossible(), data);
699 + if (includeData) {
700 + d = utils.shallowCopy(d, includeData);
701 + }
702 + return includeFile(path, opts)(d);
703 + };
704 + return fn.apply(opts.context,
705 + [data || utils.createNullProtoObjWherePossible(), escapeFn, include, rethrow]);
706 + };
707 + if (opts.filename && typeof Object.defineProperty === 'function') {
708 + var filename = opts.filename;
709 + var basename = path.basename(filename, path.extname(filename));
710 + try {
711 + Object.defineProperty(returnedFn, 'name', {
712 + value: basename,
713 + writable: false,
714 + enumerable: false,
715 + configurable: true
716 + });
717 + } catch (e) {/* ignore */}
718 + }
719 + return returnedFn;
720 + },
721 +
722 + generateSource: function () {
723 + var opts = this.opts;
724 +
725 + if (opts.rmWhitespace) {
726 + // Have to use two separate replace here as `^` and `$` operators don't
727 + // work well with `\r` and empty lines don't work well with the `m` flag.
728 + this.templateText =
729 + this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '');
730 + }
731 +
732 + // Slurp spaces and tabs before <%_ and after _%>
733 + this.templateText =
734 + this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>');
735 +
736 + var self = this;
737 + var matches = this.parseTemplateText();
738 + var d = this.opts.delimiter;
739 + var o = this.opts.openDelimiter;
740 + var c = this.opts.closeDelimiter;
741 +
742 + if (matches && matches.length) {
743 + matches.forEach(function (line, index) {
744 + var closing;
745 + // If this is an opening tag, check for closing tags
746 + // FIXME: May end up with some false positives here
747 + // Better to store modes as k/v with openDelimiter + delimiter as key
748 + // Then this can simply check against the map
749 + if ( line.indexOf(o + d) === 0 // If it is a tag
750 + && line.indexOf(o + d + d) !== 0) { // and is not escaped
751 + closing = matches[index + 2];
752 + if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) {
753 + throw new Error('Could not find matching close tag for "' + line + '".');
754 + }
755 + }
756 + self.scanLine(line);
757 + });
758 + }
759 +
760 + },
761 +
762 + parseTemplateText: function () {
763 + var str = this.templateText;
764 + var pat = this.regex;
765 + var result = pat.exec(str);
766 + var arr = [];
767 + var firstPos;
768 +
769 + while (result) {
770 + firstPos = result.index;
771 +
772 + if (firstPos !== 0) {
773 + arr.push(str.substring(0, firstPos));
774 + str = str.slice(firstPos);
775 + }
776 +
777 + arr.push(result[0]);
778 + str = str.slice(result[0].length);
779 + result = pat.exec(str);
780 + }
781 +
782 + if (str) {
783 + arr.push(str);
784 + }
785 +
786 + return arr;
787 + },
788 +
789 + _addOutput: function (line) {
790 + if (this.truncate) {
791 + // Only replace single leading linebreak in the line after
792 + // -%> tag -- this is the single, trailing linebreak
793 + // after the tag that the truncation mode replaces
794 + // Handle Win / Unix / old Mac linebreaks -- do the \r\n
795 + // combo first in the regex-or
796 + line = line.replace(/^(?:\r\n|\r|\n)/, '');
797 + this.truncate = false;
798 + }
799 + if (!line) {
800 + return line;
801 + }
802 +
803 + // Preserve literal slashes
804 + line = line.replace(/\\/g, '\\\\');
805 +
806 + // Convert linebreaks
807 + line = line.replace(/\n/g, '\\n');
808 + line = line.replace(/\r/g, '\\r');
809 +
810 + // Escape double-quotes
811 + // - this will be the delimiter during execution
812 + line = line.replace(/"/g, '\\"');
813 + this.source += ' ; __append("' + line + '")' + '\n';
814 + },
815 +
816 + scanLine: function (line) {
817 + var self = this;
818 + var d = this.opts.delimiter;
819 + var o = this.opts.openDelimiter;
820 + var c = this.opts.closeDelimiter;
821 + var newLineCount = 0;
822 +
823 + newLineCount = (line.split('\n').length - 1);
824 +
825 + switch (line) {
826 + case o + d:
827 + case o + d + '_':
828 + this.mode = Template.modes.EVAL;
829 + break;
830 + case o + d + '=':
831 + this.mode = Template.modes.ESCAPED;
832 + break;
833 + case o + d + '-':
834 + this.mode = Template.modes.RAW;
835 + break;
836 + case o + d + '#':
837 + this.mode = Template.modes.COMMENT;
838 + break;
839 + case o + d + d:
840 + this.mode = Template.modes.LITERAL;
841 + this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n';
842 + break;
843 + case d + d + c:
844 + this.mode = Template.modes.LITERAL;
845 + this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n';
846 + break;
847 + case d + c:
848 + case '-' + d + c:
849 + case '_' + d + c:
850 + if (this.mode == Template.modes.LITERAL) {
851 + this._addOutput(line);
852 + }
853 +
854 + this.mode = null;
855 + this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0;
856 + break;
857 + default:
858 + // In script mode, depends on type of tag
859 + if (this.mode) {
860 + // If '//' is found without a line break, add a line break.
861 + switch (this.mode) {
862 + case Template.modes.EVAL:
863 + case Template.modes.ESCAPED:
864 + case Template.modes.RAW:
865 + if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
866 + line += '\n';
867 + }
868 + }
869 + switch (this.mode) {
870 + // Just executing code
871 + case Template.modes.EVAL:
872 + this.source += ' ; ' + line + '\n';
873 + break;
874 + // Exec, esc, and output
875 + case Template.modes.ESCAPED:
876 + this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n';
877 + break;
878 + // Exec and output
879 + case Template.modes.RAW:
880 + this.source += ' ; __append(' + stripSemi(line) + ')' + '\n';
881 + break;
882 + case Template.modes.COMMENT:
883 + // Do nothing
884 + break;
885 + // Literal <%% mode, append as raw output
886 + case Template.modes.LITERAL:
887 + this._addOutput(line);
888 + break;
889 + }
890 + }
891 + // In string mode, just add the output
892 + else {
893 + this._addOutput(line);
894 + }
895 + }
896 +
897 + if (self.opts.compileDebug && newLineCount) {
898 + this.currentLine += newLineCount;
899 + this.source += ' ; __line = ' + this.currentLine + '\n';
900 + }
901 + }
902 +};
903 +
904 +/**
905 + * Escape characters reserved in XML.
906 + *
907 + * This is simply an export of {@link module:utils.escapeXML}.
908 + *
909 + * If `markup` is `undefined` or `null`, the empty string is returned.
910 + *
911 + * @param {String} markup Input string
912 + * @return {String} Escaped string
913 + * @public
914 + * @func
915 + * */
916 +exports.escapeXML = utils.escapeXML;
917 +
918 +/**
919 + * Express.js support.
920 + *
921 + * This is an alias for {@link module:ejs.renderFile}, in order to support
922 + * Express.js out-of-the-box.
923 + *
924 + * @func
925 + */
926 +
927 +exports.__express = exports.renderFile;
928 +
929 +/**
930 + * Version of EJS.
931 + *
932 + * @readonly
933 + * @type {String}
934 + * @public
935 + */
936 +
937 +exports.VERSION = _VERSION_STRING;
938 +
939 +/**
940 + * Name for detection of EJS.
941 + *
942 + * @readonly
943 + * @type {String}
944 + * @public
945 + */
946 +
947 +exports.name = _NAME;
948 +
949 +/* istanbul ignore if */
950 +if (typeof window != 'undefined') {
951 + window.ejs = exports;
952 +}
953 +
954 +},{"../package.json":6,"./utils":2,"fs":3,"path":4}],2:[function(require,module,exports){
955 +/*
956 + * EJS Embedded JavaScript templates
957 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
958 + *
959 + * Licensed under the Apache License, Version 2.0 (the "License");
960 + * you may not use this file except in compliance with the License.
961 + * You may obtain a copy of the License at
962 + *
963 + * http://www.apache.org/licenses/LICENSE-2.0
964 + *
965 + * Unless required by applicable law or agreed to in writing, software
966 + * distributed under the License is distributed on an "AS IS" BASIS,
967 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
968 + * See the License for the specific language governing permissions and
969 + * limitations under the License.
970 + *
971 +*/
972 +
973 +/**
974 + * Private utility functions
975 + * @module utils
976 + * @private
977 + */
978 +
979 +'use strict';
980 +
981 +var regExpChars = /[|\\{}()[\]^$+*?.]/g;
982 +var hasOwnProperty = Object.prototype.hasOwnProperty;
983 +var hasOwn = function (obj, key) { return hasOwnProperty.apply(obj, [key]); };
984 +
985 +/**
986 + * Escape characters reserved in regular expressions.
987 + *
988 + * If `string` is `undefined` or `null`, the empty string is returned.
989 + *
990 + * @param {String} string Input string
991 + * @return {String} Escaped string
992 + * @static
993 + * @private
994 + */
995 +exports.escapeRegExpChars = function (string) {
996 + // istanbul ignore if
997 + if (!string) {
998 + return '';
999 + }
1000 + return String(string).replace(regExpChars, '\\$&');
1001 +};
1002 +
1003 +var _ENCODE_HTML_RULES = {
1004 + '&': '&amp;',
1005 + '<': '&lt;',
1006 + '>': '&gt;',
1007 + '"': '&#34;',
1008 + "'": '&#39;'
1009 +};
1010 +var _MATCH_HTML = /[&<>'"]/g;
1011 +
1012 +function encode_char(c) {
1013 + return _ENCODE_HTML_RULES[c] || c;
1014 +}
1015 +
1016 +/**
1017 + * Stringified version of constants used by {@link module:utils.escapeXML}.
1018 + *
1019 + * It is used in the process of generating {@link ClientFunction}s.
1020 + *
1021 + * @readonly
1022 + * @type {String}
1023 + */
1024 +
1025 +var escapeFuncStr =
1026 + 'var _ENCODE_HTML_RULES = {\n'
1027 ++ ' "&": "&amp;"\n'
1028 ++ ' , "<": "&lt;"\n'
1029 ++ ' , ">": "&gt;"\n'
1030 ++ ' , \'"\': "&#34;"\n'
1031 ++ ' , "\'": "&#39;"\n'
1032 ++ ' }\n'
1033 ++ ' , _MATCH_HTML = /[&<>\'"]/g;\n'
1034 ++ 'function encode_char(c) {\n'
1035 ++ ' return _ENCODE_HTML_RULES[c] || c;\n'
1036 ++ '};\n';
1037 +
1038 +/**
1039 + * Escape characters reserved in XML.
1040 + *
1041 + * If `markup` is `undefined` or `null`, the empty string is returned.
1042 + *
1043 + * @implements {EscapeCallback}
1044 + * @param {String} markup Input string
1045 + * @return {String} Escaped string
1046 + * @static
1047 + * @private
1048 + */
1049 +
1050 +exports.escapeXML = function (markup) {
1051 + return markup == undefined
1052 + ? ''
1053 + : String(markup)
1054 + .replace(_MATCH_HTML, encode_char);
1055 +};
1056 +exports.escapeXML.toString = function () {
1057 + return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr;
1058 +};
1059 +
1060 +/**
1061 + * Naive copy of properties from one object to another.
1062 + * Does not recurse into non-scalar properties
1063 + * Does not check to see if the property has a value before copying
1064 + *
1065 + * @param {Object} to Destination object
1066 + * @param {Object} from Source object
1067 + * @return {Object} Destination object
1068 + * @static
1069 + * @private
1070 + */
1071 +exports.shallowCopy = function (to, from) {
1072 + from = from || {};
1073 + if ((to !== null) && (to !== undefined)) {
1074 + for (var p in from) {
1075 + if (!hasOwn(from, p)) {
1076 + continue;
1077 + }
1078 + if (p === '__proto__' || p === 'constructor') {
1079 + continue;
1080 + }
1081 + to[p] = from[p];
1082 + }
1083 + }
1084 + return to;
1085 +};
1086 +
1087 +/**
1088 + * Naive copy of a list of key names, from one object to another.
1089 + * Only copies property if it is actually defined
1090 + * Does not recurse into non-scalar properties
1091 + *
1092 + * @param {Object} to Destination object
1093 + * @param {Object} from Source object
1094 + * @param {Array} list List of properties to copy
1095 + * @return {Object} Destination object
1096 + * @static
1097 + * @private
1098 + */
1099 +exports.shallowCopyFromList = function (to, from, list) {
1100 + list = list || [];
1101 + from = from || {};
1102 + if ((to !== null) && (to !== undefined)) {
1103 + for (var i = 0; i < list.length; i++) {
1104 + var p = list[i];
1105 + if (typeof from[p] != 'undefined') {
1106 + if (!hasOwn(from, p)) {
1107 + continue;
1108 + }
1109 + if (p === '__proto__' || p === 'constructor') {
1110 + continue;
1111 + }
1112 + to[p] = from[p];
1113 + }
1114 + }
1115 + }
1116 + return to;
1117 +};
1118 +
1119 +/**
1120 + * Simple in-process cache implementation. Does not implement limits of any
1121 + * sort.
1122 + *
1123 + * @implements {Cache}
1124 + * @static
1125 + * @private
1126 + */
1127 +exports.cache = {
1128 + _data: {},
1129 + set: function (key, val) {
1130 + this._data[key] = val;
1131 + },
1132 + get: function (key) {
1133 + return this._data[key];
1134 + },
1135 + remove: function (key) {
1136 + delete this._data[key];
1137 + },
1138 + reset: function () {
1139 + this._data = {};
1140 + }
1141 +};
1142 +
1143 +/**
1144 + * Transforms hyphen case variable into camel case.
1145 + *
1146 + * @param {String} string Hyphen case string
1147 + * @return {String} Camel case string
1148 + * @static
1149 + * @private
1150 + */
1151 +exports.hyphenToCamel = function (str) {
1152 + return str.replace(/-[a-z]/g, function (match) { return match[1].toUpperCase(); });
1153 +};
1154 +
1155 +/**
1156 + * Returns a null-prototype object in runtimes that support it
1157 + *
1158 + * @return {Object} Object, prototype will be set to null where possible
1159 + * @static
1160 + * @private
1161 + */
1162 +exports.createNullProtoObjWherePossible = (function () {
1163 + if (typeof Object.create == 'function') {
1164 + return function () {
1165 + return Object.create(null);
1166 + };
1167 + }
1168 + if (!({__proto__: null} instanceof Object)) {
1169 + return function () {
1170 + return {__proto__: null};
1171 + };
1172 + }
1173 + // Not possible, just pass through
1174 + return function () {
1175 + return {};
1176 + };
1177 +})();
1178 +
1179 +
1180 +
1181 +},{}],3:[function(require,module,exports){
1182 +
1183 +},{}],4:[function(require,module,exports){
1184 +(function (process){
1185 +// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
1186 +// backported and transplited with Babel, with backwards-compat fixes
1187 +
1188 +// Copyright Joyent, Inc. and other Node contributors.
1189 +//
1190 +// Permission is hereby granted, free of charge, to any person obtaining a
1191 +// copy of this software and associated documentation files (the
1192 +// "Software"), to deal in the Software without restriction, including
1193 +// without limitation the rights to use, copy, modify, merge, publish,
1194 +// distribute, sublicense, and/or sell copies of the Software, and to permit
1195 +// persons to whom the Software is furnished to do so, subject to the
1196 +// following conditions:
1197 +//
1198 +// The above copyright notice and this permission notice shall be included
1199 +// in all copies or substantial portions of the Software.
1200 +//
1201 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
1202 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1203 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
1204 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
1205 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
1206 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
1207 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
1208 +
1209 +// resolves . and .. elements in a path array with directory names there
1210 +// must be no slashes, empty elements, or device names (c:\) in the array
1211 +// (so also no leading and trailing slashes - it does not distinguish
1212 +// relative and absolute paths)
1213 +function normalizeArray(parts, allowAboveRoot) {
1214 + // if the path tries to go above the root, `up` ends up > 0
1215 + var up = 0;
1216 + for (var i = parts.length - 1; i >= 0; i--) {
1217 + var last = parts[i];
1218 + if (last === '.') {
1219 + parts.splice(i, 1);
1220 + } else if (last === '..') {
1221 + parts.splice(i, 1);
1222 + up++;
1223 + } else if (up) {
1224 + parts.splice(i, 1);
1225 + up--;
1226 + }
1227 + }
1228 +
1229 + // if the path is allowed to go above the root, restore leading ..s
1230 + if (allowAboveRoot) {
1231 + for (; up--; up) {
1232 + parts.unshift('..');
1233 + }
1234 + }
1235 +
1236 + return parts;
1237 +}
1238 +
1239 +// path.resolve([from ...], to)
1240 +// posix version
1241 +exports.resolve = function() {
1242 + var resolvedPath = '',
1243 + resolvedAbsolute = false;
1244 +
1245 + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
1246 + var path = (i >= 0) ? arguments[i] : process.cwd();
1247 +
1248 + // Skip empty and invalid entries
1249 + if (typeof path !== 'string') {
1250 + throw new TypeError('Arguments to path.resolve must be strings');
1251 + } else if (!path) {
1252 + continue;
1253 + }
1254 +
1255 + resolvedPath = path + '/' + resolvedPath;
1256 + resolvedAbsolute = path.charAt(0) === '/';
1257 + }
1258 +
1259 + // At this point the path should be resolved to a full absolute path, but
1260 + // handle relative paths to be safe (might happen when process.cwd() fails)
1261 +
1262 + // Normalize the path
1263 + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
1264 + return !!p;
1265 + }), !resolvedAbsolute).join('/');
1266 +
1267 + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
1268 +};
1269 +
1270 +// path.normalize(path)
1271 +// posix version
1272 +exports.normalize = function(path) {
1273 + var isAbsolute = exports.isAbsolute(path),
1274 + trailingSlash = substr(path, -1) === '/';
1275 +
1276 + // Normalize the path
1277 + path = normalizeArray(filter(path.split('/'), function(p) {
1278 + return !!p;
1279 + }), !isAbsolute).join('/');
1280 +
1281 + if (!path && !isAbsolute) {
1282 + path = '.';
1283 + }
1284 + if (path && trailingSlash) {
1285 + path += '/';
1286 + }
1287 +
1288 + return (isAbsolute ? '/' : '') + path;
1289 +};
1290 +
1291 +// posix version
1292 +exports.isAbsolute = function(path) {
1293 + return path.charAt(0) === '/';
1294 +};
1295 +
1296 +// posix version
1297 +exports.join = function() {
1298 + var paths = Array.prototype.slice.call(arguments, 0);
1299 + return exports.normalize(filter(paths, function(p, index) {
1300 + if (typeof p !== 'string') {
1301 + throw new TypeError('Arguments to path.join must be strings');
1302 + }
1303 + return p;
1304 + }).join('/'));
1305 +};
1306 +
1307 +
1308 +// path.relative(from, to)
1309 +// posix version
1310 +exports.relative = function(from, to) {
1311 + from = exports.resolve(from).substr(1);
1312 + to = exports.resolve(to).substr(1);
1313 +
1314 + function trim(arr) {
1315 + var start = 0;
1316 + for (; start < arr.length; start++) {
1317 + if (arr[start] !== '') break;
1318 + }
1319 +
1320 + var end = arr.length - 1;
1321 + for (; end >= 0; end--) {
1322 + if (arr[end] !== '') break;
1323 + }
1324 +
1325 + if (start > end) return [];
1326 + return arr.slice(start, end - start + 1);
1327 + }
1328 +
1329 + var fromParts = trim(from.split('/'));
1330 + var toParts = trim(to.split('/'));
1331 +
1332 + var length = Math.min(fromParts.length, toParts.length);
1333 + var samePartsLength = length;
1334 + for (var i = 0; i < length; i++) {
1335 + if (fromParts[i] !== toParts[i]) {
1336 + samePartsLength = i;
1337 + break;
1338 + }
1339 + }
1340 +
1341 + var outputParts = [];
1342 + for (var i = samePartsLength; i < fromParts.length; i++) {
1343 + outputParts.push('..');
1344 + }
1345 +
1346 + outputParts = outputParts.concat(toParts.slice(samePartsLength));
1347 +
1348 + return outputParts.join('/');
1349 +};
1350 +
1351 +exports.sep = '/';
1352 +exports.delimiter = ':';
1353 +
1354 +exports.dirname = function (path) {
1355 + if (typeof path !== 'string') path = path + '';
1356 + if (path.length === 0) return '.';
1357 + var code = path.charCodeAt(0);
1358 + var hasRoot = code === 47 /*/*/;
1359 + var end = -1;
1360 + var matchedSlash = true;
1361 + for (var i = path.length - 1; i >= 1; --i) {
1362 + code = path.charCodeAt(i);
1363 + if (code === 47 /*/*/) {
1364 + if (!matchedSlash) {
1365 + end = i;
1366 + break;
1367 + }
1368 + } else {
1369 + // We saw the first non-path separator
1370 + matchedSlash = false;
1371 + }
1372 + }
1373 +
1374 + if (end === -1) return hasRoot ? '/' : '.';
1375 + if (hasRoot && end === 1) {
1376 + // return '//';
1377 + // Backwards-compat fix:
1378 + return '/';
1379 + }
1380 + return path.slice(0, end);
1381 +};
1382 +
1383 +function basename(path) {
1384 + if (typeof path !== 'string') path = path + '';
1385 +
1386 + var start = 0;
1387 + var end = -1;
1388 + var matchedSlash = true;
1389 + var i;
1390 +
1391 + for (i = path.length - 1; i >= 0; --i) {
1392 + if (path.charCodeAt(i) === 47 /*/*/) {
1393 + // If we reached a path separator that was not part of a set of path
1394 + // separators at the end of the string, stop now
1395 + if (!matchedSlash) {
1396 + start = i + 1;
1397 + break;
1398 + }
1399 + } else if (end === -1) {
1400 + // We saw the first non-path separator, mark this as the end of our
1401 + // path component
1402 + matchedSlash = false;
1403 + end = i + 1;
1404 + }
1405 + }
1406 +
1407 + if (end === -1) return '';
1408 + return path.slice(start, end);
1409 +}
1410 +
1411 +// Uses a mixed approach for backwards-compatibility, as ext behavior changed
1412 +// in new Node.js versions, so only basename() above is backported here
1413 +exports.basename = function (path, ext) {
1414 + var f = basename(path);
1415 + if (ext && f.substr(-1 * ext.length) === ext) {
1416 + f = f.substr(0, f.length - ext.length);
1417 + }
1418 + return f;
1419 +};
1420 +
1421 +exports.extname = function (path) {
1422 + if (typeof path !== 'string') path = path + '';
1423 + var startDot = -1;
1424 + var startPart = 0;
1425 + var end = -1;
1426 + var matchedSlash = true;
1427 + // Track the state of characters (if any) we see before our first dot and
1428 + // after any path separator we find
1429 + var preDotState = 0;
1430 + for (var i = path.length - 1; i >= 0; --i) {
1431 + var code = path.charCodeAt(i);
1432 + if (code === 47 /*/*/) {
1433 + // If we reached a path separator that was not part of a set of path
1434 + // separators at the end of the string, stop now
1435 + if (!matchedSlash) {
1436 + startPart = i + 1;
1437 + break;
1438 + }
1439 + continue;
1440 + }
1441 + if (end === -1) {
1442 + // We saw the first non-path separator, mark this as the end of our
1443 + // extension
1444 + matchedSlash = false;
1445 + end = i + 1;
1446 + }
1447 + if (code === 46 /*.*/) {
1448 + // If this is our first dot, mark it as the start of our extension
1449 + if (startDot === -1)
1450 + startDot = i;
1451 + else if (preDotState !== 1)
1452 + preDotState = 1;
1453 + } else if (startDot !== -1) {
1454 + // We saw a non-dot and non-path separator before our dot, so we should
1455 + // have a good chance at having a non-empty extension
1456 + preDotState = -1;
1457 + }
1458 + }
1459 +
1460 + if (startDot === -1 || end === -1 ||
1461 + // We saw a non-dot character immediately before the dot
1462 + preDotState === 0 ||
1463 + // The (right-most) trimmed path component is exactly '..'
1464 + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
1465 + return '';
1466 + }
1467 + return path.slice(startDot, end);
1468 +};
1469 +
1470 +function filter (xs, f) {
1471 + if (xs.filter) return xs.filter(f);
1472 + var res = [];
1473 + for (var i = 0; i < xs.length; i++) {
1474 + if (f(xs[i], i, xs)) res.push(xs[i]);
1475 + }
1476 + return res;
1477 +}
1478 +
1479 +// String.prototype.substr - negative index don't work in IE8
1480 +var substr = 'ab'.substr(-1) === 'b'
1481 + ? function (str, start, len) { return str.substr(start, len) }
1482 + : function (str, start, len) {
1483 + if (start < 0) start = str.length + start;
1484 + return str.substr(start, len);
1485 + }
1486 +;
1487 +
1488 +}).call(this,require('_process'))
1489 +},{"_process":5}],5:[function(require,module,exports){
1490 +// shim for using process in browser
1491 +var process = module.exports = {};
1492 +
1493 +// cached from whatever global is present so that test runners that stub it
1494 +// don't break things. But we need to wrap it in a try catch in case it is
1495 +// wrapped in strict mode code which doesn't define any globals. It's inside a
1496 +// function because try/catches deoptimize in certain engines.
1497 +
1498 +var cachedSetTimeout;
1499 +var cachedClearTimeout;
1500 +
1501 +function defaultSetTimout() {
1502 + throw new Error('setTimeout has not been defined');
1503 +}
1504 +function defaultClearTimeout () {
1505 + throw new Error('clearTimeout has not been defined');
1506 +}
1507 +(function () {
1508 + try {
1509 + if (typeof setTimeout === 'function') {
1510 + cachedSetTimeout = setTimeout;
1511 + } else {
1512 + cachedSetTimeout = defaultSetTimout;
1513 + }
1514 + } catch (e) {
1515 + cachedSetTimeout = defaultSetTimout;
1516 + }
1517 + try {
1518 + if (typeof clearTimeout === 'function') {
1519 + cachedClearTimeout = clearTimeout;
1520 + } else {
1521 + cachedClearTimeout = defaultClearTimeout;
1522 + }
1523 + } catch (e) {
1524 + cachedClearTimeout = defaultClearTimeout;
1525 + }
1526 +} ())
1527 +function runTimeout(fun) {
1528 + if (cachedSetTimeout === setTimeout) {
1529 + //normal enviroments in sane situations
1530 + return setTimeout(fun, 0);
1531 + }
1532 + // if setTimeout wasn't available but was latter defined
1533 + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
1534 + cachedSetTimeout = setTimeout;
1535 + return setTimeout(fun, 0);
1536 + }
1537 + try {
1538 + // when when somebody has screwed with setTimeout but no I.E. maddness
1539 + return cachedSetTimeout(fun, 0);
1540 + } catch(e){
1541 + try {
1542 + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1543 + return cachedSetTimeout.call(null, fun, 0);
1544 + } catch(e){
1545 + // 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
1546 + return cachedSetTimeout.call(this, fun, 0);
1547 + }
1548 + }
1549 +
1550 +
1551 +}
1552 +function runClearTimeout(marker) {
1553 + if (cachedClearTimeout === clearTimeout) {
1554 + //normal enviroments in sane situations
1555 + return clearTimeout(marker);
1556 + }
1557 + // if clearTimeout wasn't available but was latter defined
1558 + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
1559 + cachedClearTimeout = clearTimeout;
1560 + return clearTimeout(marker);
1561 + }
1562 + try {
1563 + // when when somebody has screwed with setTimeout but no I.E. maddness
1564 + return cachedClearTimeout(marker);
1565 + } catch (e){
1566 + try {
1567 + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1568 + return cachedClearTimeout.call(null, marker);
1569 + } catch (e){
1570 + // 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.
1571 + // Some versions of I.E. have different rules for clearTimeout vs setTimeout
1572 + return cachedClearTimeout.call(this, marker);
1573 + }
1574 + }
1575 +
1576 +
1577 +
1578 +}
1579 +var queue = [];
1580 +var draining = false;
1581 +var currentQueue;
1582 +var queueIndex = -1;
1583 +
1584 +function cleanUpNextTick() {
1585 + if (!draining || !currentQueue) {
1586 + return;
1587 + }
1588 + draining = false;
1589 + if (currentQueue.length) {
1590 + queue = currentQueue.concat(queue);
1591 + } else {
1592 + queueIndex = -1;
1593 + }
1594 + if (queue.length) {
1595 + drainQueue();
1596 + }
1597 +}
1598 +
1599 +function drainQueue() {
1600 + if (draining) {
1601 + return;
1602 + }
1603 + var timeout = runTimeout(cleanUpNextTick);
1604 + draining = true;
1605 +
1606 + var len = queue.length;
1607 + while(len) {
1608 + currentQueue = queue;
1609 + queue = [];
1610 + while (++queueIndex < len) {
1611 + if (currentQueue) {
1612 + currentQueue[queueIndex].run();
1613 + }
1614 + }
1615 + queueIndex = -1;
1616 + len = queue.length;
1617 + }
1618 + currentQueue = null;
1619 + draining = false;
1620 + runClearTimeout(timeout);
1621 +}
1622 +
1623 +process.nextTick = function (fun) {
1624 + var args = new Array(arguments.length - 1);
1625 + if (arguments.length > 1) {
1626 + for (var i = 1; i < arguments.length; i++) {
1627 + args[i - 1] = arguments[i];
1628 + }
1629 + }
1630 + queue.push(new Item(fun, args));
1631 + if (queue.length === 1 && !draining) {
1632 + runTimeout(drainQueue);
1633 + }
1634 +};
1635 +
1636 +// v8 likes predictible objects
1637 +function Item(fun, array) {
1638 + this.fun = fun;
1639 + this.array = array;
1640 +}
1641 +Item.prototype.run = function () {
1642 + this.fun.apply(null, this.array);
1643 +};
1644 +process.title = 'browser';
1645 +process.browser = true;
1646 +process.env = {};
1647 +process.argv = [];
1648 +process.version = ''; // empty string to avoid regexp issues
1649 +process.versions = {};
1650 +
1651 +function noop() {}
1652 +
1653 +process.on = noop;
1654 +process.addListener = noop;
1655 +process.once = noop;
1656 +process.off = noop;
1657 +process.removeListener = noop;
1658 +process.removeAllListeners = noop;
1659 +process.emit = noop;
1660 +process.prependListener = noop;
1661 +process.prependOnceListener = noop;
1662 +
1663 +process.listeners = function (name) { return [] }
1664 +
1665 +process.binding = function (name) {
1666 + throw new Error('process.binding is not supported');
1667 +};
1668 +
1669 +process.cwd = function () { return '/' };
1670 +process.chdir = function (dir) {
1671 + throw new Error('process.chdir is not supported');
1672 +};
1673 +process.umask = function() { return 0; };
1674 +
1675 +},{}],6:[function(require,module,exports){
1676 +module.exports={
1677 + "name": "ejs",
1678 + "description": "Embedded JavaScript templates",
1679 + "keywords": [
1680 + "template",
1681 + "engine",
1682 + "ejs"
1683 + ],
1684 + "version": "3.1.7",
1685 + "author": "Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",
1686 + "license": "Apache-2.0",
1687 + "bin": {
1688 + "ejs": "./bin/cli.js"
1689 + },
1690 + "main": "./lib/ejs.js",
1691 + "jsdelivr": "ejs.min.js",
1692 + "unpkg": "ejs.min.js",
1693 + "repository": {
1694 + "type": "git",
1695 + "url": "git://github.com/mde/ejs.git"
1696 + },
1697 + "bugs": "https://github.com/mde/ejs/issues",
1698 + "homepage": "https://github.com/mde/ejs",
1699 + "dependencies": {
1700 + "jake": "^10.8.5"
1701 + },
1702 + "devDependencies": {
1703 + "browserify": "^16.5.1",
1704 + "eslint": "^6.8.0",
1705 + "git-directory-deploy": "^1.5.1",
1706 + "jsdoc": "^3.6.7",
1707 + "lru-cache": "^4.0.1",
1708 + "mocha": "^7.1.1",
1709 + "uglify-js": "^3.3.16"
1710 + },
1711 + "engines": {
1712 + "node": ">=0.10.0"
1713 + },
1714 + "scripts": {
1715 + "test": "mocha"
1716 + }
1717 +}
1718 +
1719 +},{}]},{},[1])(1)
1720 +});
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;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){"use strict";var fs=require("fs");var path=require("path");var utils=require("./utils");var scopeOptionWarned=false;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"];var _OPTS_PASSABLE_WITH_DATA_EXPRESS=_OPTS_PASSABLE_WITH_DATA.concat("cache");var _BOM=/^\uFEFF/;var _JS_IDENTIFIER=/^[a-zA-Z_$][0-9a-zA-Z_$]*$/;exports.cache=utils.cache;exports.fileLoader=fs.readFileSync;exports.localsName=_DEFAULT_LOCALS_NAME;exports.promiseImpl=new Function("return this;")().Promise;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};function resolvePaths(name,paths){var filePath;if(paths.some(function(v){filePath=exports.resolveInclude(name,v,true);return fs.existsSync(filePath)})){return filePath}}function getIncludePath(path,options){var includePath;var filePath;var views=options.views;var match=/^[A-Za-z]+:\\|^\//.exec(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)}}else{if(options.filename){filePath=exports.resolveInclude(path,options.filename);if(fs.existsSync(filePath)){includePath=filePath}}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}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){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(utils.createNullProtoObjWherePossible(),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||utils.createNullProtoObjWherePossible();var opts=o||utils.createNullProtoObjWherePossible();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=utils.createNullProtoObjWherePossible()}return tryHandleCache(opts,data,cb)};exports.Template=Template;exports.clearCache=function(){exports.cache.reset()};function Template(text,opts){opts=opts||utils.createNullProtoObjWherePossible();var options=utils.createNullProtoObjWherePossible();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,open).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;var sanitizedFilename=opts.filename?JSON.stringify(opts.filename):"undefined";if(!this.source){this.generateSource();prepended+=' var __output = "";\n'+" function __append(s) { if (s !== undefined && s !== null) __output += s }\n";if(opts.outputFunctionName){if(!_JS_IDENTIFIER.test(opts.outputFunctionName)){throw new Error("outputFunctionName is not a valid JS identifier.")}prepended+=" var "+opts.outputFunctionName+" = __append;"+"\n"}if(opts.localsName&&!_JS_IDENTIFIER.test(opts.localsName)){throw new Error("localsName is not a valid JS identifier.")}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(!_JS_IDENTIFIER.test(name)){throw new Error("destructuredLocals["+i+"] is not a valid JS identifier.")}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 = "+sanitizedFilename+";"+"\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="+sanitizedFilename+"\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(utils.createNullProtoObjWherePossible(),data);if(includeData){d=utils.shallowCopy(d,includeData)}return includeFile(path,opts)(d)};return fn.apply(opts.context,[data||utils.createNullProtoObjWherePossible(),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;var hasOwnProperty=Object.prototype.hasOwnProperty;var hasOwn=function(obj,key){return hasOwnProperty.apply(obj,[key])};exports.escapeRegExpChars=function(string){if(!string){return""}return String(string).replace(regExpChars,"\\$&")};var _ENCODE_HTML_RULES={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&#34;","'":"&#39;"};var _MATCH_HTML=/[&<>'"]/g;function encode_char(c){return _ENCODE_HTML_RULES[c]||c}var escapeFuncStr="var _ENCODE_HTML_RULES = {\n"+' "&": "&amp;"\n'+' , "<": "&lt;"\n'+' , ">": "&gt;"\n'+' , \'"\': "&#34;"\n'+' , "\'": "&#39;"\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||{};if(to!==null&&to!==undefined){for(var p in from){if(!hasOwn(from,p)){continue}if(p==="__proto__"||p==="constructor"){continue}to[p]=from[p]}}return to};exports.shallowCopyFromList=function(to,from,list){list=list||[];from=from||{};if(to!==null&&to!==undefined){for(var i=0;i<list.length;i++){var p=list[i];if(typeof from[p]!="undefined"){if(!hasOwn(from,p)){continue}if(p==="__proto__"||p==="constructor"){continue}to[p]=from[p]}}}return to};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={}}};exports.hyphenToCamel=function(str){return str.replace(/-[a-z]/g,function(match){return match[1].toUpperCase()})};exports.createNullProtoObjWherePossible=function(){if(typeof Object.create=="function"){return function(){return Object.create(null)}}if(!({__proto__:null}instanceof Object)){return function(){return{__proto__:null}}}return function(){return{}}}()},{}],3:[function(require,module,exports){},{}],4:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){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(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<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{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;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}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){var process=module.exports={};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){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){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)}};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="";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.7",author:"Matthew Eernisse <mde@fleegix.org> (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.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^3.6.7","lru-cache":"^4.0.1",mocha:"^7.1.1","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"mocha"}}},{}]},{},[1])(1)});
1 +var fs = require('fs');
2 +var path = require('path');
3 +var execSync = require('child_process').execSync;
4 +var exec = function (cmd) {
5 + execSync(cmd, {stdio: 'inherit'});
6 +};
7 +
8 +/* global jake, task, desc, publishTask */
9 +
10 +task('build', ['lint', 'clean', 'browserify', 'minify'], function () {
11 + console.log('Build completed.');
12 +});
13 +
14 +desc('Cleans browerified/minified files and package files');
15 +task('clean', ['clobber'], function () {
16 + jake.rmRf('./ejs.js');
17 + jake.rmRf('./ejs.min.js');
18 + console.log('Cleaned up compiled files.');
19 +});
20 +
21 +desc('Lints the source code');
22 +task('lint', ['clean'], function () {
23 + var epath = path.join('./node_modules/.bin/eslint');
24 + exec(epath+' "**/*.js"');
25 + console.log('Linting completed.');
26 +});
27 +
28 +task('browserify', function () {
29 + var epath = path.join('./node_modules/browserify/bin/cmd.js');
30 + exec(epath+' --standalone ejs lib/ejs.js > ejs.js');
31 + console.log('Browserification completed.');
32 +});
33 +
34 +task('minify', function () {
35 + var epath = path.join('./node_modules/uglify-js/bin/uglifyjs');
36 + exec(epath+' ejs.js > ejs.min.js');
37 + console.log('Minification completed.');
38 +});
39 +
40 +desc('Generates the EJS API docs for the public API');
41 +task('doc', function () {
42 + jake.rmRf('out');
43 + var epath = path.join('./node_modules/.bin/jsdoc');
44 + exec(epath+' --verbose -c jsdoc.json lib/* docs/jsdoc/*');
45 + console.log('Documentation generated in ./out.');
46 +});
47 +
48 +desc('Generates the EJS API docs for the public and private API');
49 +task('devdoc', function () {
50 + jake.rmRf('out');
51 + var epath = path.join('./node_modules/.bin/jsdoc');
52 + exec(epath+' --verbose -p -c jsdoc.json lib/* docs/jsdoc/*');
53 + console.log('Documentation generated in ./out.');
54 +});
55 +
56 +desc('Publishes the EJS API docs');
57 +task('docPublish', ['doc'], function () {
58 + fs.writeFileSync('out/CNAME', 'api.ejs.co');
59 + console.log('Pushing docs to gh-pages...');
60 + var epath = path.join('./node_modules/.bin/git-directory-deploy');
61 + exec(epath+' --directory out/');
62 + console.log('Docs published to gh-pages.');
63 +});
64 +
65 +desc('Runs the EJS test suite');
66 +task('test', ['lint'], function () {
67 + exec(path.join('./node_modules/.bin/mocha'));
68 +});
69 +
70 +publishTask('ejs', ['build'], function () {
71 + this.packageFiles.include([
72 + 'jakefile.js',
73 + 'README.md',
74 + 'LICENSE',
75 + 'package.json',
76 + 'ejs.js',
77 + 'ejs.min.js',
78 + 'lib/**',
79 + 'bin/**',
80 + 'usage.txt'
81 + ]);
82 +});
83 +
84 +jake.Task.publish.on('complete', function () {
85 + console.log('Updating hosted docs...');
86 + console.log('If this fails, run jake docPublish to re-try.');
87 + jake.Task.docPublish.invoke();
88 +});
1 +/*
2 + * EJS Embedded JavaScript templates
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +'use strict';
20 +
21 +/**
22 + * @file Embedded JavaScript templating engine. {@link http://ejs.co}
23 + * @author Matthew Eernisse <mde@fleegix.org>
24 + * @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
25 + * @project EJS
26 + * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0}
27 + */
28 +
29 +/**
30 + * EJS internal functions.
31 + *
32 + * Technically this "module" lies in the same file as {@link module:ejs}, for
33 + * the sake of organization all the private functions re grouped into this
34 + * module.
35 + *
36 + * @module ejs-internal
37 + * @private
38 + */
39 +
40 +/**
41 + * Embedded JavaScript templating engine.
42 + *
43 + * @module ejs
44 + * @public
45 + */
46 +
47 +
48 +var fs = require('fs');
49 +var path = require('path');
50 +var utils = require('./utils');
51 +
52 +var scopeOptionWarned = false;
53 +/** @type {string} */
54 +var _VERSION_STRING = require('../package.json').version;
55 +var _DEFAULT_OPEN_DELIMITER = '<';
56 +var _DEFAULT_CLOSE_DELIMITER = '>';
57 +var _DEFAULT_DELIMITER = '%';
58 +var _DEFAULT_LOCALS_NAME = 'locals';
59 +var _NAME = 'ejs';
60 +var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)';
61 +var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug',
62 + 'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async'];
63 +// We don't allow 'cache' option to be passed in the data obj for
64 +// the normal `render` call, but this is where Express 2 & 3 put it
65 +// so we make an exception for `renderFile`
66 +var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache');
67 +var _BOM = /^\uFEFF/;
68 +var _JS_IDENTIFIER = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/;
69 +
70 +/**
71 + * EJS template function cache. This can be a LRU object from lru-cache NPM
72 + * module. By default, it is {@link module:utils.cache}, a simple in-process
73 + * cache that grows continuously.
74 + *
75 + * @type {Cache}
76 + */
77 +
78 +exports.cache = utils.cache;
79 +
80 +/**
81 + * Custom file loader. Useful for template preprocessing or restricting access
82 + * to a certain part of the filesystem.
83 + *
84 + * @type {fileLoader}
85 + */
86 +
87 +exports.fileLoader = fs.readFileSync;
88 +
89 +/**
90 + * Name of the object containing the locals.
91 + *
92 + * This variable is overridden by {@link Options}`.localsName` if it is not
93 + * `undefined`.
94 + *
95 + * @type {String}
96 + * @public
97 + */
98 +
99 +exports.localsName = _DEFAULT_LOCALS_NAME;
100 +
101 +/**
102 + * Promise implementation -- defaults to the native implementation if available
103 + * This is mostly just for testability
104 + *
105 + * @type {PromiseConstructorLike}
106 + * @public
107 + */
108 +
109 +exports.promiseImpl = (new Function('return this;'))().Promise;
110 +
111 +/**
112 + * Get the path to the included file from the parent file path and the
113 + * specified path.
114 + *
115 + * @param {String} name specified path
116 + * @param {String} filename parent file path
117 + * @param {Boolean} [isDir=false] whether the parent file path is a directory
118 + * @return {String}
119 + */
120 +exports.resolveInclude = function(name, filename, isDir) {
121 + var dirname = path.dirname;
122 + var extname = path.extname;
123 + var resolve = path.resolve;
124 + var includePath = resolve(isDir ? filename : dirname(filename), name);
125 + var ext = extname(name);
126 + if (!ext) {
127 + includePath += '.ejs';
128 + }
129 + return includePath;
130 +};
131 +
132 +/**
133 + * Try to resolve file path on multiple directories
134 + *
135 + * @param {String} name specified path
136 + * @param {Array<String>} paths list of possible parent directory paths
137 + * @return {String}
138 + */
139 +function resolvePaths(name, paths) {
140 + var filePath;
141 + if (paths.some(function (v) {
142 + filePath = exports.resolveInclude(name, v, true);
143 + return fs.existsSync(filePath);
144 + })) {
145 + return filePath;
146 + }
147 +}
148 +
149 +/**
150 + * Get the path to the included file by Options
151 + *
152 + * @param {String} path specified path
153 + * @param {Options} options compilation options
154 + * @return {String}
155 + */
156 +function getIncludePath(path, options) {
157 + var includePath;
158 + var filePath;
159 + var views = options.views;
160 + var match = /^[A-Za-z]+:\\|^\//.exec(path);
161 +
162 + // Abs path
163 + if (match && match.length) {
164 + path = path.replace(/^\/*/, '');
165 + if (Array.isArray(options.root)) {
166 + includePath = resolvePaths(path, options.root);
167 + } else {
168 + includePath = exports.resolveInclude(path, options.root || '/', true);
169 + }
170 + }
171 + // Relative paths
172 + else {
173 + // Look relative to a passed filename first
174 + if (options.filename) {
175 + filePath = exports.resolveInclude(path, options.filename);
176 + if (fs.existsSync(filePath)) {
177 + includePath = filePath;
178 + }
179 + }
180 + // Then look in any views directories
181 + if (!includePath && Array.isArray(views)) {
182 + includePath = resolvePaths(path, views);
183 + }
184 + if (!includePath && typeof options.includer !== 'function') {
185 + throw new Error('Could not find the include file "' +
186 + options.escapeFunction(path) + '"');
187 + }
188 + }
189 + return includePath;
190 +}
191 +
192 +/**
193 + * Get the template from a string or a file, either compiled on-the-fly or
194 + * read from cache (if enabled), and cache the template if needed.
195 + *
196 + * If `template` is not set, the file specified in `options.filename` will be
197 + * read.
198 + *
199 + * If `options.cache` is true, this function reads the file from
200 + * `options.filename` so it must be set prior to calling this function.
201 + *
202 + * @memberof module:ejs-internal
203 + * @param {Options} options compilation options
204 + * @param {String} [template] template source
205 + * @return {(TemplateFunction|ClientFunction)}
206 + * Depending on the value of `options.client`, either type might be returned.
207 + * @static
208 + */
209 +
210 +function handleCache(options, template) {
211 + var func;
212 + var filename = options.filename;
213 + var hasTemplate = arguments.length > 1;
214 +
215 + if (options.cache) {
216 + if (!filename) {
217 + throw new Error('cache option requires a filename');
218 + }
219 + func = exports.cache.get(filename);
220 + if (func) {
221 + return func;
222 + }
223 + if (!hasTemplate) {
224 + template = fileLoader(filename).toString().replace(_BOM, '');
225 + }
226 + }
227 + else if (!hasTemplate) {
228 + // istanbul ignore if: should not happen at all
229 + if (!filename) {
230 + throw new Error('Internal EJS error: no file name or template '
231 + + 'provided');
232 + }
233 + template = fileLoader(filename).toString().replace(_BOM, '');
234 + }
235 + func = exports.compile(template, options);
236 + if (options.cache) {
237 + exports.cache.set(filename, func);
238 + }
239 + return func;
240 +}
241 +
242 +/**
243 + * Try calling handleCache with the given options and data and call the
244 + * callback with the result. If an error occurs, call the callback with
245 + * the error. Used by renderFile().
246 + *
247 + * @memberof module:ejs-internal
248 + * @param {Options} options compilation options
249 + * @param {Object} data template data
250 + * @param {RenderFileCallback} cb callback
251 + * @static
252 + */
253 +
254 +function tryHandleCache(options, data, cb) {
255 + var result;
256 + if (!cb) {
257 + if (typeof exports.promiseImpl == 'function') {
258 + return new exports.promiseImpl(function (resolve, reject) {
259 + try {
260 + result = handleCache(options)(data);
261 + resolve(result);
262 + }
263 + catch (err) {
264 + reject(err);
265 + }
266 + });
267 + }
268 + else {
269 + throw new Error('Please provide a callback function');
270 + }
271 + }
272 + else {
273 + try {
274 + result = handleCache(options)(data);
275 + }
276 + catch (err) {
277 + return cb(err);
278 + }
279 +
280 + cb(null, result);
281 + }
282 +}
283 +
284 +/**
285 + * fileLoader is independent
286 + *
287 + * @param {String} filePath ejs file path.
288 + * @return {String} The contents of the specified file.
289 + * @static
290 + */
291 +
292 +function fileLoader(filePath){
293 + return exports.fileLoader(filePath);
294 +}
295 +
296 +/**
297 + * Get the template function.
298 + *
299 + * If `options.cache` is `true`, then the template is cached.
300 + *
301 + * @memberof module:ejs-internal
302 + * @param {String} path path for the specified file
303 + * @param {Options} options compilation options
304 + * @return {(TemplateFunction|ClientFunction)}
305 + * Depending on the value of `options.client`, either type might be returned
306 + * @static
307 + */
308 +
309 +function includeFile(path, options) {
310 + var opts = utils.shallowCopy(utils.createNullProtoObjWherePossible(), options);
311 + opts.filename = getIncludePath(path, opts);
312 + if (typeof options.includer === 'function') {
313 + var includerResult = options.includer(path, opts.filename);
314 + if (includerResult) {
315 + if (includerResult.filename) {
316 + opts.filename = includerResult.filename;
317 + }
318 + if (includerResult.template) {
319 + return handleCache(opts, includerResult.template);
320 + }
321 + }
322 + }
323 + return handleCache(opts);
324 +}
325 +
326 +/**
327 + * Re-throw the given `err` in context to the `str` of ejs, `filename`, and
328 + * `lineno`.
329 + *
330 + * @implements {RethrowCallback}
331 + * @memberof module:ejs-internal
332 + * @param {Error} err Error object
333 + * @param {String} str EJS source
334 + * @param {String} flnm file name of the EJS file
335 + * @param {Number} lineno line number of the error
336 + * @param {EscapeCallback} esc
337 + * @static
338 + */
339 +
340 +function rethrow(err, str, flnm, lineno, esc) {
341 + var lines = str.split('\n');
342 + var start = Math.max(lineno - 3, 0);
343 + var end = Math.min(lines.length, lineno + 3);
344 + var filename = esc(flnm);
345 + // Error context
346 + var context = lines.slice(start, end).map(function (line, i){
347 + var curr = i + start + 1;
348 + return (curr == lineno ? ' >> ' : ' ')
349 + + curr
350 + + '| '
351 + + line;
352 + }).join('\n');
353 +
354 + // Alter exception message
355 + err.path = filename;
356 + err.message = (filename || 'ejs') + ':'
357 + + lineno + '\n'
358 + + context + '\n\n'
359 + + err.message;
360 +
361 + throw err;
362 +}
363 +
364 +function stripSemi(str){
365 + return str.replace(/;(\s*$)/, '$1');
366 +}
367 +
368 +/**
369 + * Compile the given `str` of ejs into a template function.
370 + *
371 + * @param {String} template EJS template
372 + *
373 + * @param {Options} [opts] compilation options
374 + *
375 + * @return {(TemplateFunction|ClientFunction)}
376 + * Depending on the value of `opts.client`, either type might be returned.
377 + * Note that the return type of the function also depends on the value of `opts.async`.
378 + * @public
379 + */
380 +
381 +exports.compile = function compile(template, opts) {
382 + var templ;
383 +
384 + // v1 compat
385 + // 'scope' is 'context'
386 + // FIXME: Remove this in a future version
387 + if (opts && opts.scope) {
388 + if (!scopeOptionWarned){
389 + console.warn('`scope` option is deprecated and will be removed in EJS 3');
390 + scopeOptionWarned = true;
391 + }
392 + if (!opts.context) {
393 + opts.context = opts.scope;
394 + }
395 + delete opts.scope;
396 + }
397 + templ = new Template(template, opts);
398 + return templ.compile();
399 +};
400 +
401 +/**
402 + * Render the given `template` of ejs.
403 + *
404 + * If you would like to include options but not data, you need to explicitly
405 + * call this function with `data` being an empty object or `null`.
406 + *
407 + * @param {String} template EJS template
408 + * @param {Object} [data={}] template data
409 + * @param {Options} [opts={}] compilation and rendering options
410 + * @return {(String|Promise<String>)}
411 + * Return value type depends on `opts.async`.
412 + * @public
413 + */
414 +
415 +exports.render = function (template, d, o) {
416 + var data = d || utils.createNullProtoObjWherePossible();
417 + var opts = o || utils.createNullProtoObjWherePossible();
418 +
419 + // No options object -- if there are optiony names
420 + // in the data, copy them to options
421 + if (arguments.length == 2) {
422 + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
423 + }
424 +
425 + return handleCache(opts, template)(data);
426 +};
427 +
428 +/**
429 + * Render an EJS file at the given `path` and callback `cb(err, str)`.
430 + *
431 + * If you would like to include options but not data, you need to explicitly
432 + * call this function with `data` being an empty object or `null`.
433 + *
434 + * @param {String} path path to the EJS file
435 + * @param {Object} [data={}] template data
436 + * @param {Options} [opts={}] compilation and rendering options
437 + * @param {RenderFileCallback} cb callback
438 + * @public
439 + */
440 +
441 +exports.renderFile = function () {
442 + var args = Array.prototype.slice.call(arguments);
443 + var filename = args.shift();
444 + var cb;
445 + var opts = {filename: filename};
446 + var data;
447 + var viewOpts;
448 +
449 + // Do we have a callback?
450 + if (typeof arguments[arguments.length - 1] == 'function') {
451 + cb = args.pop();
452 + }
453 + // Do we have data/opts?
454 + if (args.length) {
455 + // Should always have data obj
456 + data = args.shift();
457 + // Normal passed opts (data obj + opts obj)
458 + if (args.length) {
459 + // Use shallowCopy so we don't pollute passed in opts obj with new vals
460 + utils.shallowCopy(opts, args.pop());
461 + }
462 + // Special casing for Express (settings + opts-in-data)
463 + else {
464 + // Express 3 and 4
465 + if (data.settings) {
466 + // Pull a few things from known locations
467 + if (data.settings.views) {
468 + opts.views = data.settings.views;
469 + }
470 + if (data.settings['view cache']) {
471 + opts.cache = true;
472 + }
473 + // Undocumented after Express 2, but still usable, esp. for
474 + // items that are unsafe to be passed along with data, like `root`
475 + viewOpts = data.settings['view options'];
476 + if (viewOpts) {
477 + utils.shallowCopy(opts, viewOpts);
478 + }
479 + }
480 + // Express 2 and lower, values set in app.locals, or people who just
481 + // want to pass options in their data. NOTE: These values will override
482 + // anything previously set in settings or settings['view options']
483 + utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
484 + }
485 + opts.filename = filename;
486 + }
487 + else {
488 + data = utils.createNullProtoObjWherePossible();
489 + }
490 +
491 + return tryHandleCache(opts, data, cb);
492 +};
493 +
494 +/**
495 + * Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
496 + * @public
497 + */
498 +
499 +/**
500 + * EJS template class
501 + * @public
502 + */
503 +exports.Template = Template;
504 +
505 +exports.clearCache = function () {
506 + exports.cache.reset();
507 +};
508 +
509 +function Template(text, opts) {
510 + opts = opts || utils.createNullProtoObjWherePossible();
511 + var options = utils.createNullProtoObjWherePossible();
512 + this.templateText = text;
513 + /** @type {string | null} */
514 + this.mode = null;
515 + this.truncate = false;
516 + this.currentLine = 1;
517 + this.source = '';
518 + options.client = opts.client || false;
519 + options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
520 + options.compileDebug = opts.compileDebug !== false;
521 + options.debug = !!opts.debug;
522 + options.filename = opts.filename;
523 + options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
524 + options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
525 + options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
526 + options.strict = opts.strict || false;
527 + options.context = opts.context;
528 + options.cache = opts.cache || false;
529 + options.rmWhitespace = opts.rmWhitespace;
530 + options.root = opts.root;
531 + options.includer = opts.includer;
532 + options.outputFunctionName = opts.outputFunctionName;
533 + options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
534 + options.views = opts.views;
535 + options.async = opts.async;
536 + options.destructuredLocals = opts.destructuredLocals;
537 + options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true;
538 +
539 + if (options.strict) {
540 + options._with = false;
541 + }
542 + else {
543 + options._with = typeof opts._with != 'undefined' ? opts._with : true;
544 + }
545 +
546 + this.opts = options;
547 +
548 + this.regex = this.createRegex();
549 +}
550 +
551 +Template.modes = {
552 + EVAL: 'eval',
553 + ESCAPED: 'escaped',
554 + RAW: 'raw',
555 + COMMENT: 'comment',
556 + LITERAL: 'literal'
557 +};
558 +
559 +Template.prototype = {
560 + createRegex: function () {
561 + var str = _REGEX_STRING;
562 + var delim = utils.escapeRegExpChars(this.opts.delimiter);
563 + var open = utils.escapeRegExpChars(this.opts.openDelimiter);
564 + var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
565 + str = str.replace(/%/g, delim)
566 + .replace(/</g, open)
567 + .replace(/>/g, close);
568 + return new RegExp(str);
569 + },
570 +
571 + compile: function () {
572 + /** @type {string} */
573 + var src;
574 + /** @type {ClientFunction} */
575 + var fn;
576 + var opts = this.opts;
577 + var prepended = '';
578 + var appended = '';
579 + /** @type {EscapeCallback} */
580 + var escapeFn = opts.escapeFunction;
581 + /** @type {FunctionConstructor} */
582 + var ctor;
583 + /** @type {string} */
584 + var sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : 'undefined';
585 +
586 + if (!this.source) {
587 + this.generateSource();
588 + prepended +=
589 + ' var __output = "";\n' +
590 + ' function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
591 + if (opts.outputFunctionName) {
592 + if (!_JS_IDENTIFIER.test(opts.outputFunctionName)) {
593 + throw new Error('outputFunctionName is not a valid JS identifier.');
594 + }
595 + prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
596 + }
597 + if (opts.localsName && !_JS_IDENTIFIER.test(opts.localsName)) {
598 + throw new Error('localsName is not a valid JS identifier.');
599 + }
600 + if (opts.destructuredLocals && opts.destructuredLocals.length) {
601 + var destructuring = ' var __locals = (' + opts.localsName + ' || {}),\n';
602 + for (var i = 0; i < opts.destructuredLocals.length; i++) {
603 + var name = opts.destructuredLocals[i];
604 + if (!_JS_IDENTIFIER.test(name)) {
605 + throw new Error('destructuredLocals[' + i + '] is not a valid JS identifier.');
606 + }
607 + if (i > 0) {
608 + destructuring += ',\n ';
609 + }
610 + destructuring += name + ' = __locals.' + name;
611 + }
612 + prepended += destructuring + ';\n';
613 + }
614 + if (opts._with !== false) {
615 + prepended += ' with (' + opts.localsName + ' || {}) {' + '\n';
616 + appended += ' }' + '\n';
617 + }
618 + appended += ' return __output;' + '\n';
619 + this.source = prepended + this.source + appended;
620 + }
621 +
622 + if (opts.compileDebug) {
623 + src = 'var __line = 1' + '\n'
624 + + ' , __lines = ' + JSON.stringify(this.templateText) + '\n'
625 + + ' , __filename = ' + sanitizedFilename + ';' + '\n'
626 + + 'try {' + '\n'
627 + + this.source
628 + + '} catch (e) {' + '\n'
629 + + ' rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
630 + + '}' + '\n';
631 + }
632 + else {
633 + src = this.source;
634 + }
635 +
636 + if (opts.client) {
637 + src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src;
638 + if (opts.compileDebug) {
639 + src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
640 + }
641 + }
642 +
643 + if (opts.strict) {
644 + src = '"use strict";\n' + src;
645 + }
646 + if (opts.debug) {
647 + console.log(src);
648 + }
649 + if (opts.compileDebug && opts.filename) {
650 + src = src + '\n'
651 + + '//# sourceURL=' + sanitizedFilename + '\n';
652 + }
653 +
654 + try {
655 + if (opts.async) {
656 + // Have to use generated function for this, since in envs without support,
657 + // it breaks in parsing
658 + try {
659 + ctor = (new Function('return (async function(){}).constructor;'))();
660 + }
661 + catch(e) {
662 + if (e instanceof SyntaxError) {
663 + throw new Error('This environment does not support async/await');
664 + }
665 + else {
666 + throw e;
667 + }
668 + }
669 + }
670 + else {
671 + ctor = Function;
672 + }
673 + fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src);
674 + }
675 + catch(e) {
676 + // istanbul ignore else
677 + if (e instanceof SyntaxError) {
678 + if (opts.filename) {
679 + e.message += ' in ' + opts.filename;
680 + }
681 + e.message += ' while compiling ejs\n\n';
682 + e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n';
683 + e.message += 'https://github.com/RyanZim/EJS-Lint';
684 + if (!opts.async) {
685 + e.message += '\n';
686 + e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.';
687 + }
688 + }
689 + throw e;
690 + }
691 +
692 + // Return a callable function which will execute the function
693 + // created by the source-code, with the passed data as locals
694 + // Adds a local `include` function which allows full recursive include
695 + var returnedFn = opts.client ? fn : function anonymous(data) {
696 + var include = function (path, includeData) {
697 + var d = utils.shallowCopy(utils.createNullProtoObjWherePossible(), data);
698 + if (includeData) {
699 + d = utils.shallowCopy(d, includeData);
700 + }
701 + return includeFile(path, opts)(d);
702 + };
703 + return fn.apply(opts.context,
704 + [data || utils.createNullProtoObjWherePossible(), escapeFn, include, rethrow]);
705 + };
706 + if (opts.filename && typeof Object.defineProperty === 'function') {
707 + var filename = opts.filename;
708 + var basename = path.basename(filename, path.extname(filename));
709 + try {
710 + Object.defineProperty(returnedFn, 'name', {
711 + value: basename,
712 + writable: false,
713 + enumerable: false,
714 + configurable: true
715 + });
716 + } catch (e) {/* ignore */}
717 + }
718 + return returnedFn;
719 + },
720 +
721 + generateSource: function () {
722 + var opts = this.opts;
723 +
724 + if (opts.rmWhitespace) {
725 + // Have to use two separate replace here as `^` and `$` operators don't
726 + // work well with `\r` and empty lines don't work well with the `m` flag.
727 + this.templateText =
728 + this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '');
729 + }
730 +
731 + // Slurp spaces and tabs before <%_ and after _%>
732 + this.templateText =
733 + this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>');
734 +
735 + var self = this;
736 + var matches = this.parseTemplateText();
737 + var d = this.opts.delimiter;
738 + var o = this.opts.openDelimiter;
739 + var c = this.opts.closeDelimiter;
740 +
741 + if (matches && matches.length) {
742 + matches.forEach(function (line, index) {
743 + var closing;
744 + // If this is an opening tag, check for closing tags
745 + // FIXME: May end up with some false positives here
746 + // Better to store modes as k/v with openDelimiter + delimiter as key
747 + // Then this can simply check against the map
748 + if ( line.indexOf(o + d) === 0 // If it is a tag
749 + && line.indexOf(o + d + d) !== 0) { // and is not escaped
750 + closing = matches[index + 2];
751 + if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) {
752 + throw new Error('Could not find matching close tag for "' + line + '".');
753 + }
754 + }
755 + self.scanLine(line);
756 + });
757 + }
758 +
759 + },
760 +
761 + parseTemplateText: function () {
762 + var str = this.templateText;
763 + var pat = this.regex;
764 + var result = pat.exec(str);
765 + var arr = [];
766 + var firstPos;
767 +
768 + while (result) {
769 + firstPos = result.index;
770 +
771 + if (firstPos !== 0) {
772 + arr.push(str.substring(0, firstPos));
773 + str = str.slice(firstPos);
774 + }
775 +
776 + arr.push(result[0]);
777 + str = str.slice(result[0].length);
778 + result = pat.exec(str);
779 + }
780 +
781 + if (str) {
782 + arr.push(str);
783 + }
784 +
785 + return arr;
786 + },
787 +
788 + _addOutput: function (line) {
789 + if (this.truncate) {
790 + // Only replace single leading linebreak in the line after
791 + // -%> tag -- this is the single, trailing linebreak
792 + // after the tag that the truncation mode replaces
793 + // Handle Win / Unix / old Mac linebreaks -- do the \r\n
794 + // combo first in the regex-or
795 + line = line.replace(/^(?:\r\n|\r|\n)/, '');
796 + this.truncate = false;
797 + }
798 + if (!line) {
799 + return line;
800 + }
801 +
802 + // Preserve literal slashes
803 + line = line.replace(/\\/g, '\\\\');
804 +
805 + // Convert linebreaks
806 + line = line.replace(/\n/g, '\\n');
807 + line = line.replace(/\r/g, '\\r');
808 +
809 + // Escape double-quotes
810 + // - this will be the delimiter during execution
811 + line = line.replace(/"/g, '\\"');
812 + this.source += ' ; __append("' + line + '")' + '\n';
813 + },
814 +
815 + scanLine: function (line) {
816 + var self = this;
817 + var d = this.opts.delimiter;
818 + var o = this.opts.openDelimiter;
819 + var c = this.opts.closeDelimiter;
820 + var newLineCount = 0;
821 +
822 + newLineCount = (line.split('\n').length - 1);
823 +
824 + switch (line) {
825 + case o + d:
826 + case o + d + '_':
827 + this.mode = Template.modes.EVAL;
828 + break;
829 + case o + d + '=':
830 + this.mode = Template.modes.ESCAPED;
831 + break;
832 + case o + d + '-':
833 + this.mode = Template.modes.RAW;
834 + break;
835 + case o + d + '#':
836 + this.mode = Template.modes.COMMENT;
837 + break;
838 + case o + d + d:
839 + this.mode = Template.modes.LITERAL;
840 + this.source += ' ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n';
841 + break;
842 + case d + d + c:
843 + this.mode = Template.modes.LITERAL;
844 + this.source += ' ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n';
845 + break;
846 + case d + c:
847 + case '-' + d + c:
848 + case '_' + d + c:
849 + if (this.mode == Template.modes.LITERAL) {
850 + this._addOutput(line);
851 + }
852 +
853 + this.mode = null;
854 + this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0;
855 + break;
856 + default:
857 + // In script mode, depends on type of tag
858 + if (this.mode) {
859 + // If '//' is found without a line break, add a line break.
860 + switch (this.mode) {
861 + case Template.modes.EVAL:
862 + case Template.modes.ESCAPED:
863 + case Template.modes.RAW:
864 + if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
865 + line += '\n';
866 + }
867 + }
868 + switch (this.mode) {
869 + // Just executing code
870 + case Template.modes.EVAL:
871 + this.source += ' ; ' + line + '\n';
872 + break;
873 + // Exec, esc, and output
874 + case Template.modes.ESCAPED:
875 + this.source += ' ; __append(escapeFn(' + stripSemi(line) + '))' + '\n';
876 + break;
877 + // Exec and output
878 + case Template.modes.RAW:
879 + this.source += ' ; __append(' + stripSemi(line) + ')' + '\n';
880 + break;
881 + case Template.modes.COMMENT:
882 + // Do nothing
883 + break;
884 + // Literal <%% mode, append as raw output
885 + case Template.modes.LITERAL:
886 + this._addOutput(line);
887 + break;
888 + }
889 + }
890 + // In string mode, just add the output
891 + else {
892 + this._addOutput(line);
893 + }
894 + }
895 +
896 + if (self.opts.compileDebug && newLineCount) {
897 + this.currentLine += newLineCount;
898 + this.source += ' ; __line = ' + this.currentLine + '\n';
899 + }
900 + }
901 +};
902 +
903 +/**
904 + * Escape characters reserved in XML.
905 + *
906 + * This is simply an export of {@link module:utils.escapeXML}.
907 + *
908 + * If `markup` is `undefined` or `null`, the empty string is returned.
909 + *
910 + * @param {String} markup Input string
911 + * @return {String} Escaped string
912 + * @public
913 + * @func
914 + * */
915 +exports.escapeXML = utils.escapeXML;
916 +
917 +/**
918 + * Express.js support.
919 + *
920 + * This is an alias for {@link module:ejs.renderFile}, in order to support
921 + * Express.js out-of-the-box.
922 + *
923 + * @func
924 + */
925 +
926 +exports.__express = exports.renderFile;
927 +
928 +/**
929 + * Version of EJS.
930 + *
931 + * @readonly
932 + * @type {String}
933 + * @public
934 + */
935 +
936 +exports.VERSION = _VERSION_STRING;
937 +
938 +/**
939 + * Name for detection of EJS.
940 + *
941 + * @readonly
942 + * @type {String}
943 + * @public
944 + */
945 +
946 +exports.name = _NAME;
947 +
948 +/* istanbul ignore if */
949 +if (typeof window != 'undefined') {
950 + window.ejs = exports;
951 +}
1 +/*
2 + * EJS Embedded JavaScript templates
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +/**
20 + * Private utility functions
21 + * @module utils
22 + * @private
23 + */
24 +
25 +'use strict';
26 +
27 +var regExpChars = /[|\\{}()[\]^$+*?.]/g;
28 +var hasOwnProperty = Object.prototype.hasOwnProperty;
29 +var hasOwn = function (obj, key) { return hasOwnProperty.apply(obj, [key]); };
30 +
31 +/**
32 + * Escape characters reserved in regular expressions.
33 + *
34 + * If `string` is `undefined` or `null`, the empty string is returned.
35 + *
36 + * @param {String} string Input string
37 + * @return {String} Escaped string
38 + * @static
39 + * @private
40 + */
41 +exports.escapeRegExpChars = function (string) {
42 + // istanbul ignore if
43 + if (!string) {
44 + return '';
45 + }
46 + return String(string).replace(regExpChars, '\\$&');
47 +};
48 +
49 +var _ENCODE_HTML_RULES = {
50 + '&': '&amp;',
51 + '<': '&lt;',
52 + '>': '&gt;',
53 + '"': '&#34;',
54 + "'": '&#39;'
55 +};
56 +var _MATCH_HTML = /[&<>'"]/g;
57 +
58 +function encode_char(c) {
59 + return _ENCODE_HTML_RULES[c] || c;
60 +}
61 +
62 +/**
63 + * Stringified version of constants used by {@link module:utils.escapeXML}.
64 + *
65 + * It is used in the process of generating {@link ClientFunction}s.
66 + *
67 + * @readonly
68 + * @type {String}
69 + */
70 +
71 +var escapeFuncStr =
72 + 'var _ENCODE_HTML_RULES = {\n'
73 ++ ' "&": "&amp;"\n'
74 ++ ' , "<": "&lt;"\n'
75 ++ ' , ">": "&gt;"\n'
76 ++ ' , \'"\': "&#34;"\n'
77 ++ ' , "\'": "&#39;"\n'
78 ++ ' }\n'
79 ++ ' , _MATCH_HTML = /[&<>\'"]/g;\n'
80 ++ 'function encode_char(c) {\n'
81 ++ ' return _ENCODE_HTML_RULES[c] || c;\n'
82 ++ '};\n';
83 +
84 +/**
85 + * Escape characters reserved in XML.
86 + *
87 + * If `markup` is `undefined` or `null`, the empty string is returned.
88 + *
89 + * @implements {EscapeCallback}
90 + * @param {String} markup Input string
91 + * @return {String} Escaped string
92 + * @static
93 + * @private
94 + */
95 +
96 +exports.escapeXML = function (markup) {
97 + return markup == undefined
98 + ? ''
99 + : String(markup)
100 + .replace(_MATCH_HTML, encode_char);
101 +};
102 +exports.escapeXML.toString = function () {
103 + return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr;
104 +};
105 +
106 +/**
107 + * Naive copy of properties from one object to another.
108 + * Does not recurse into non-scalar properties
109 + * Does not check to see if the property has a value before copying
110 + *
111 + * @param {Object} to Destination object
112 + * @param {Object} from Source object
113 + * @return {Object} Destination object
114 + * @static
115 + * @private
116 + */
117 +exports.shallowCopy = function (to, from) {
118 + from = from || {};
119 + if ((to !== null) && (to !== undefined)) {
120 + for (var p in from) {
121 + if (!hasOwn(from, p)) {
122 + continue;
123 + }
124 + if (p === '__proto__' || p === 'constructor') {
125 + continue;
126 + }
127 + to[p] = from[p];
128 + }
129 + }
130 + return to;
131 +};
132 +
133 +/**
134 + * Naive copy of a list of key names, from one object to another.
135 + * Only copies property if it is actually defined
136 + * Does not recurse into non-scalar properties
137 + *
138 + * @param {Object} to Destination object
139 + * @param {Object} from Source object
140 + * @param {Array} list List of properties to copy
141 + * @return {Object} Destination object
142 + * @static
143 + * @private
144 + */
145 +exports.shallowCopyFromList = function (to, from, list) {
146 + list = list || [];
147 + from = from || {};
148 + if ((to !== null) && (to !== undefined)) {
149 + for (var i = 0; i < list.length; i++) {
150 + var p = list[i];
151 + if (typeof from[p] != 'undefined') {
152 + if (!hasOwn(from, p)) {
153 + continue;
154 + }
155 + if (p === '__proto__' || p === 'constructor') {
156 + continue;
157 + }
158 + to[p] = from[p];
159 + }
160 + }
161 + }
162 + return to;
163 +};
164 +
165 +/**
166 + * Simple in-process cache implementation. Does not implement limits of any
167 + * sort.
168 + *
169 + * @implements {Cache}
170 + * @static
171 + * @private
172 + */
173 +exports.cache = {
174 + _data: {},
175 + set: function (key, val) {
176 + this._data[key] = val;
177 + },
178 + get: function (key) {
179 + return this._data[key];
180 + },
181 + remove: function (key) {
182 + delete this._data[key];
183 + },
184 + reset: function () {
185 + this._data = {};
186 + }
187 +};
188 +
189 +/**
190 + * Transforms hyphen case variable into camel case.
191 + *
192 + * @param {String} string Hyphen case string
193 + * @return {String} Camel case string
194 + * @static
195 + * @private
196 + */
197 +exports.hyphenToCamel = function (str) {
198 + return str.replace(/-[a-z]/g, function (match) { return match[1].toUpperCase(); });
199 +};
200 +
201 +/**
202 + * Returns a null-prototype object in runtimes that support it
203 + *
204 + * @return {Object} Object, prototype will be set to null where possible
205 + * @static
206 + * @private
207 + */
208 +exports.createNullProtoObjWherePossible = (function () {
209 + if (typeof Object.create == 'function') {
210 + return function () {
211 + return Object.create(null);
212 + };
213 + }
214 + if (!({__proto__: null} instanceof Object)) {
215 + return function () {
216 + return {__proto__: null};
217 + };
218 + }
219 + // Not possible, just pass through
220 + return function () {
221 + return {};
222 + };
223 +})();
224 +
225 +
1 +{
2 + "_from": "ejs",
3 + "_id": "ejs@3.1.8",
4 + "_inBundle": false,
5 + "_integrity": "sha512-/sXZeMlhS0ArkfX2Aw780gJzXSMPnKjtspYZv+f3NiKLlubezAHDU5+9xz6gd3/NhG3txQCo6xlglmTS+oTGEQ==",
6 + "_location": "/ejs",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "tag",
10 + "registry": true,
11 + "raw": "ejs",
12 + "name": "ejs",
13 + "escapedName": "ejs",
14 + "rawSpec": "",
15 + "saveSpec": null,
16 + "fetchSpec": "latest"
17 + },
18 + "_requiredBy": [
19 + "#USER",
20 + "/"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.8.tgz",
23 + "_shasum": "758d32910c78047585c7ef1f92f9ee041c1c190b",
24 + "_spec": "ejs",
25 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam",
26 + "author": {
27 + "name": "Matthew Eernisse",
28 + "email": "mde@fleegix.org",
29 + "url": "http://fleegix.org"
30 + },
31 + "bin": {
32 + "ejs": "bin/cli.js"
33 + },
34 + "bugs": {
35 + "url": "https://github.com/mde/ejs/issues"
36 + },
37 + "bundleDependencies": false,
38 + "dependencies": {
39 + "jake": "^10.8.5"
40 + },
41 + "deprecated": false,
42 + "description": "Embedded JavaScript templates",
43 + "devDependencies": {
44 + "browserify": "^16.5.1",
45 + "eslint": "^6.8.0",
46 + "git-directory-deploy": "^1.5.1",
47 + "jsdoc": "^3.6.7",
48 + "lru-cache": "^4.0.1",
49 + "mocha": "^7.1.1",
50 + "uglify-js": "^3.3.16"
51 + },
52 + "engines": {
53 + "node": ">=0.10.0"
54 + },
55 + "homepage": "https://github.com/mde/ejs",
56 + "jsdelivr": "ejs.min.js",
57 + "keywords": [
58 + "template",
59 + "engine",
60 + "ejs"
61 + ],
62 + "license": "Apache-2.0",
63 + "main": "./lib/ejs.js",
64 + "name": "ejs",
65 + "repository": {
66 + "type": "git",
67 + "url": "git://github.com/mde/ejs.git"
68 + },
69 + "scripts": {
70 + "test": "mocha"
71 + },
72 + "unpkg": "ejs.min.js",
73 + "version": "3.1.8"
74 +}
1 +EJS Embedded JavaScript templates
2 +{Usage}: ejs [options ...] template-file [data variables ...]
3 +
4 +{Options}:
5 + -o, --output-file FILE Write the rendered output to FILE rather than stdout.
6 + -f, --data-file FILE Must be JSON-formatted. Use parsed input from FILE as data for rendering.
7 + -i, --data-input STRING Must be JSON-formatted and URI-encoded. Use parsed input from STRING as data for rendering.
8 + -m, --delimiter CHARACTER Use CHARACTER with angle brackets for open/close (defaults to %).
9 + -p, --open-delimiter CHARACTER Use CHARACTER instead of left angle bracket to open.
10 + -c, --close-delimiter CHARACTER Use CHARACTER instead of right angle bracket to close.
11 + -s, --strict When set to `true`, generated function is in strict mode
12 + -n --no-with Use 'locals' object for vars rather than using `with` (implies --strict).
13 + -l --locals-name Name to use for the object storing local variables when not using `with`.
14 + -w --rm-whitespace Remove all safe-to-remove whitespace, including leading and trailing whitespace.
15 + -d --debug Outputs generated function body
16 + -h, --help Display this help message.
17 + -V/v, --version Display the EJS version.
18 +
19 +{Examples}:
20 + ejs -m $ ./test/fixtures/user.ejs -f ./user_data.json
21 + ejs -m $ ./test/fixtures/user.ejs name=Lerxst
22 + ejs -p [ -c ] ./template_file.ejs -o ./output.html
23 + ejs -n -l _ ./some_template.ejs -f ./data_file.json
24 + ejs -w ./template_with_whitspace.ejs -o ./output_file.html
1 +## FileList
2 +
3 +A FileList is a lazy-evaluated list of files. When given a list
4 +of glob patterns for possible files to be included in the file
5 +list, instead of searching the file structures to find the files,
6 +a FileList holds the pattern for latter use.
7 +
8 +This allows you to define a FileList to match any number of
9 +files, but only search out the actual files when then FileList
10 +itself is actually used. The key is that the first time an
11 +element of the FileList/Array is requested, the pending patterns
12 +are resolved into a real list of file names.
13 +
14 +### Usage
15 +
16 +Add files to the list with the `include` method. You can add glob
17 +patterns, individual files, or RegExp objects. When the Array
18 +methods are invoked on the FileList, these items are resolved to
19 +an actual list of files.
20 +
21 +```javascript
22 +var fl = new FileList();
23 +fl.include('test/*.js');
24 +fl.exclude('test/helpers.js');
25 +```
26 +
27 +Use the `exclude` method to override inclusions. You can use this
28 +when your inclusions are too broad.
29 +
30 +### Array methods
31 +
32 +FileList has lazy-evaluated versions of most of the array
33 +methods, including the following:
34 +
35 +* join
36 +* pop
37 +* push
38 +* concat
39 +* reverse
40 +* shift
41 +* unshift
42 +* slice
43 +* splice
44 +* sort
45 +* filter
46 +* forEach
47 +* some
48 +* every
49 +* map
50 +* indexOf
51 +* lastIndexOf
52 +* reduce
53 +* reduceRight
54 +
55 +When you call one of these methods, the items in the FileList
56 +will be resolved to the full list of files, and the method will
57 +be invoked on that result.
58 +
59 +### Special `length` method
60 +
61 +`length`: FileList includes a length *method* (instead of a
62 +property) which returns the number of actual files in the list
63 +once it's been resolved.
64 +
65 +### FileList-specific methods
66 +
67 +`include`: Add a filename/glob/regex to the list
68 +
69 +`exclude`: Override inclusions by excluding a filename/glob/regex
70 +
71 +`resolve`: Resolve the items in the FileList to the full list of
72 +files. This method is invoked automatically when one of the array
73 +methods is called.
74 +
75 +`toArray`: Immediately resolves the list of items, and returns an
76 +actual array of filepaths.
77 +
78 +`clearInclusions`: Clears any pending items -- must be used
79 +before resolving the list.
80 +
81 +`clearExclusions`: Clears the list of exclusions rules.
82 +
83 +
84 +
1 +// IncludeOptions definitions copied from minimatch (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/minimatch/index.d.ts)
2 +interface IncludeOptions {
3 + /**
4 + * Dump a ton of stuff to stderr.
5 + *
6 + * @default false
7 + */
8 + debug?: boolean;
9 +
10 + /**
11 + * Do not expand {a,b} and {1..3} brace sets.
12 + *
13 + * @default false
14 + */
15 + nobrace?: boolean;
16 +
17 + /**
18 + * Disable ** matching against multiple folder names.
19 + *
20 + * @default false
21 + */
22 + noglobstar?: boolean;
23 +
24 + /**
25 + * Allow patterns to match filenames starting with a period,
26 + * even if the pattern does not explicitly have a period in that spot.
27 + *
28 + * @default false
29 + */
30 + dot?: boolean;
31 +
32 + /**
33 + * Disable "extglob" style patterns like +(a|b).
34 + *
35 + * @default false
36 + */
37 + noext?: boolean;
38 +
39 + /**
40 + * Perform a case-insensitive match.
41 + *
42 + * @default false
43 + */
44 + nocase?: boolean;
45 +
46 + /**
47 + * When a match is not found by minimatch.match,
48 + * return a list containing the pattern itself if this option is set.
49 + * Otherwise, an empty list is returned if there are no matches.
50 + *
51 + * @default false
52 + */
53 + nonull?: boolean;
54 +
55 + /**
56 + * If set, then patterns without slashes will be matched against
57 + * the basename of the path if it contains slashes.
58 + *
59 + * @default false
60 + */
61 + matchBase?: boolean;
62 +
63 + /**
64 + * Suppress the behavior of treating #
65 + * at the start of a pattern as a comment.
66 + *
67 + * @default false
68 + */
69 + nocomment?: boolean;
70 +
71 + /**
72 + * Suppress the behavior of treating a leading ! character as negation.
73 + *
74 + * @default false
75 + */
76 + nonegate?: boolean;
77 +
78 + /**
79 + * Returns from negate expressions the same as if they were not negated.
80 + * (Ie, true on a hit, false on a miss.)
81 + *
82 + * @default false
83 + */
84 + flipNegate?: boolean;
85 +}
86 +
87 +export class FileList {
88 + static clone(): FileList
89 + static verbose: boolean
90 +}
91 +
92 +export interface FileList extends Omit<Array<string>, "length"> {
93 + pendingAdd: string[]
94 + pending: boolean
95 + excludes: {
96 + pats: RegExp[],
97 + funcs: Function[],
98 + regex: null | RegExp
99 + }
100 + items: string[]
101 + toArray(): string[]
102 + include(...items: string[]): this
103 + include(...items: (IncludeOptions | string)[]): this
104 + exclude(...items: string[]): this
105 + shouldExclude(item: string): boolean
106 + resolve(): this
107 + clearInclusions(): this
108 + clearExclusions(): this
109 + length(): number
110 +}
...\ No newline at end of file ...\ No newline at end of file
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +var fs = require('fs')
19 +, path = require('path')
20 +, minimatch = require('minimatch')
21 +, escapeRegExpChars
22 +, merge
23 +, basedir
24 +, _readDir
25 +, readdirR
26 +, globSync;
27 +var hasOwnProperty = Object.prototype.hasOwnProperty;
28 +var hasOwn = function (obj, key) { return hasOwnProperty.apply(obj, [key]); };
29 +
30 + /**
31 + @name escapeRegExpChars
32 + @function
33 + @return {String} A string of escaped characters
34 + @description Escapes regex control-characters in strings
35 + used to build regexes dynamically
36 + @param {String} string The string of chars to escape
37 + */
38 + escapeRegExpChars = (function () {
39 + var specials = [ '^', '$', '/', '.', '*', '+', '?', '|', '(', ')',
40 + '[', ']', '{', '}', '\\' ];
41 + var sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
42 + return function (string) {
43 + var str = string || '';
44 + str = String(str);
45 + return str.replace(sRE, '\\$1');
46 + };
47 + })();
48 +
49 + /**
50 + @name merge
51 + @function
52 + @return {Object} Returns the merged object
53 + @description Merge merges `otherObject` into `object` and takes care of deep
54 + merging of objects
55 + @param {Object} object Object to merge into
56 + @param {Object} otherObject Object to read from
57 + */
58 + merge = function (object, otherObject) {
59 + var obj = object || {}
60 + , otherObj = otherObject || {}
61 + , key, value;
62 +
63 + for (key in otherObj) {
64 +
65 + if (!hasOwn(otherObj, key)) {
66 + continue;
67 + }
68 + if (key === '__proto__' || key === 'constructor') {
69 + continue;
70 + }
71 +
72 + value = otherObj[key];
73 + // Check if a value is an Object, if so recursively add it's key/values
74 + if (typeof value === 'object' && !(value instanceof Array)) {
75 + // Update value of object to the one from otherObj
76 + obj[key] = merge(obj[key], value);
77 + }
78 + // Value is anything other than an Object, so just add it
79 + else {
80 + obj[key] = value;
81 + }
82 + }
83 +
84 + return obj;
85 + };
86 + /**
87 + Given a patern, return the base directory of it (ie. the folder
88 + that will contain all the files matching the path).
89 + eg. file.basedir('/test/**') => '/test/'
90 + Path ending by '/' are considerd as folder while other are considerd
91 + as files, eg.:
92 + file.basedir('/test/a/') => '/test/a'
93 + file.basedir('/test/a') => '/test'
94 + The returned path always end with a '/' so we have:
95 + file.basedir(file.basedir(x)) == file.basedir(x)
96 + */
97 + basedir = function (pathParam) {
98 + var bd = ''
99 + , parts
100 + , part
101 + , pos = 0
102 + , p = pathParam || '';
103 +
104 + // If the path has a leading asterisk, basedir is the current dir
105 + if (p.indexOf('*') == 0 || p.indexOf('**') == 0) {
106 + return '.';
107 + }
108 +
109 + // always consider .. at the end as a folder and not a filename
110 + if (/(?:^|\/|\\)\.\.$/.test(p.slice(-3))) {
111 + p += '/';
112 + }
113 +
114 + parts = p.split(/\\|\//);
115 + for (var i = 0, l = parts.length - 1; i < l; i++) {
116 + part = parts[i];
117 + if (part.indexOf('*') > -1 || part.indexOf('**') > -1) {
118 + break;
119 + }
120 + pos += part.length + 1;
121 + bd += part + p[pos - 1];
122 + }
123 + if (!bd) {
124 + bd = '.';
125 + }
126 + // Strip trailing slashes
127 + if (!(bd == '\\' || bd == '/')) {
128 + bd = bd.replace(/\\$|\/$/, '');
129 + }
130 + return bd;
131 +
132 + };
133 +
134 + // Return the contents of a given directory
135 + _readDir = function (dirPath) {
136 + var dir = path.normalize(dirPath)
137 + , paths = []
138 + , ret = [dir]
139 + , msg;
140 +
141 + try {
142 + paths = fs.readdirSync(dir);
143 + }
144 + catch (e) {
145 + msg = 'Could not read path ' + dir + '\n';
146 + if (e.stack) {
147 + msg += e.stack;
148 + }
149 + throw new Error(msg);
150 + }
151 +
152 + paths.forEach(function (p) {
153 + var curr = path.join(dir, p);
154 + var stat = fs.statSync(curr);
155 + if (stat.isDirectory()) {
156 + ret = ret.concat(_readDir(curr));
157 + }
158 + else {
159 + ret.push(curr);
160 + }
161 + });
162 +
163 + return ret;
164 + };
165 +
166 + /**
167 + @name file#readdirR
168 + @function
169 + @return {Array} Returns the contents as an Array, can be configured via opts.format
170 + @description Reads the given directory returning it's contents
171 + @param {String} dir The directory to read
172 + @param {Object} opts Options to use
173 + @param {String} [opts.format] Set the format to return(Default: Array)
174 + */
175 + readdirR = function (dir, opts) {
176 + var options = opts || {}
177 + , format = options.format || 'array'
178 + , ret;
179 + ret = _readDir(dir);
180 + return format == 'string' ? ret.join('\n') : ret;
181 + };
182 +
183 +
184 +globSync = function (pat, opts) {
185 + var dirname = basedir(pat)
186 + , files
187 + , matches;
188 +
189 + try {
190 + files = readdirR(dirname).map(function(file){
191 + return file.replace(/\\/g, '/');
192 + });
193 + }
194 + // Bail if path doesn't exist -- assume no files
195 + catch(e) {
196 + if (FileList.verbose) console.error(e.message);
197 + }
198 +
199 + if (files) {
200 + pat = path.normalize(pat);
201 + matches = minimatch.match(files, pat, opts || {});
202 + }
203 + return matches || [];
204 +};
205 +
206 +// Constants
207 +// ---------------
208 +// List of all the builtin Array methods we want to override
209 +var ARRAY_METHODS = Object.getOwnPropertyNames(Array.prototype)
210 +// Array methods that return a copy instead of affecting the original
211 + , SPECIAL_RETURN = {
212 + 'concat': true
213 + , 'slice': true
214 + , 'filter': true
215 + , 'map': true
216 + }
217 +// Default file-patterns we want to ignore
218 + , DEFAULT_IGNORE_PATTERNS = [
219 + /(^|[\/\\])CVS([\/\\]|$)/
220 + , /(^|[\/\\])\.svn([\/\\]|$)/
221 + , /(^|[\/\\])\.git([\/\\]|$)/
222 + , /\.bak$/
223 + , /~$/
224 + ]
225 +// Ignore core files
226 + , DEFAULT_IGNORE_FUNCS = [
227 + function (name) {
228 + var isDir = false
229 + , stats;
230 + try {
231 + stats = fs.statSync(name);
232 + isDir = stats.isDirectory();
233 + }
234 + catch(e) {}
235 + return (/(^|[\/\\])core$/).test(name) && !isDir;
236 + }
237 + ];
238 +
239 +var FileList = function () {
240 + var self = this
241 + , wrap;
242 +
243 + // List of glob-patterns or specific filenames
244 + this.pendingAdd = [];
245 + // Switched to false after lazy-eval of files
246 + this.pending = true;
247 + // Used to calculate exclusions from the list of files
248 + this.excludes = {
249 + pats: DEFAULT_IGNORE_PATTERNS.slice()
250 + , funcs: DEFAULT_IGNORE_FUNCS.slice()
251 + , regex: null
252 + };
253 + this.items = [];
254 +
255 + // Wrap the array methods with the delegates
256 + wrap = function (prop) {
257 + var arr;
258 + self[prop] = function () {
259 + if (self.pending) {
260 + self.resolve();
261 + }
262 + if (typeof self.items[prop] == 'function') {
263 + // Special method that return a copy
264 + if (SPECIAL_RETURN[prop]) {
265 + arr = self.items[prop].apply(self.items, arguments);
266 + return FileList.clone(self, arr);
267 + }
268 + else {
269 + return self.items[prop].apply(self.items, arguments);
270 + }
271 + }
272 + else {
273 + return self.items[prop];
274 + }
275 + };
276 + };
277 + for (var i = 0, ii = ARRAY_METHODS.length; i < ii; i++) {
278 + wrap(ARRAY_METHODS[i]);
279 + }
280 +
281 + // Include whatever files got passed to the constructor
282 + this.include.apply(this, arguments);
283 +
284 + // Fix constructor linkage
285 + this.constructor = FileList;
286 +};
287 +
288 +FileList.prototype = new (function () {
289 + var globPattern = /[*?\[\{]/;
290 +
291 + var _addMatching = function (item) {
292 + var matches = globSync(item.path, item.options);
293 + this.items = this.items.concat(matches);
294 + }
295 +
296 + , _resolveAdd = function (item) {
297 + if (globPattern.test(item.path)) {
298 + _addMatching.call(this, item);
299 + }
300 + else {
301 + this.push(item.path);
302 + }
303 + }
304 +
305 + , _calculateExcludeRe = function () {
306 + var pats = this.excludes.pats
307 + , pat
308 + , excl = []
309 + , matches = [];
310 +
311 + for (var i = 0, ii = pats.length; i < ii; i++) {
312 + pat = pats[i];
313 + if (typeof pat == 'string') {
314 + // Glob, look up files
315 + if (/[*?]/.test(pat)) {
316 + matches = globSync(pat);
317 + matches = matches.map(function (m) {
318 + return escapeRegExpChars(m);
319 + });
320 + excl = excl.concat(matches);
321 + }
322 + // String for regex
323 + else {
324 + excl.push(escapeRegExpChars(pat));
325 + }
326 + }
327 + // Regex, grab the string-representation
328 + else if (pat instanceof RegExp) {
329 + excl.push(pat.toString().replace(/^\/|\/$/g, ''));
330 + }
331 + }
332 + if (excl.length) {
333 + this.excludes.regex = new RegExp('(' + excl.join(')|(') + ')');
334 + }
335 + else {
336 + this.excludes.regex = /^$/;
337 + }
338 + }
339 +
340 + , _resolveExclude = function () {
341 + var self = this;
342 + _calculateExcludeRe.call(this);
343 + // No `reject` method, so use reverse-filter
344 + this.items = this.items.filter(function (name) {
345 + return !self.shouldExclude(name);
346 + });
347 + };
348 +
349 + /**
350 + * Includes file-patterns in the FileList. Should be called with one or more
351 + * pattern for finding file to include in the list. Arguments should be strings
352 + * for either a glob-pattern or a specific file-name, or an array of them
353 + */
354 + this.include = function () {
355 + var args = Array.prototype.slice.call(arguments)
356 + , arg
357 + , includes = { items: [], options: {} };
358 +
359 + for (var i = 0, ilen = args.length; i < ilen; i++) {
360 + arg = args[i];
361 +
362 + if (typeof arg === 'object' && !Array.isArray(arg)) {
363 + merge(includes.options, arg);
364 + } else {
365 + includes.items = includes.items.concat(arg).filter(function (item) {
366 + return !!item;
367 + });
368 + }
369 + }
370 +
371 + var items = includes.items.map(function(item) {
372 + return { path: item, options: includes.options };
373 + });
374 +
375 + this.pendingAdd = this.pendingAdd.concat(items);
376 +
377 + return this;
378 + };
379 +
380 + /**
381 + * Indicates whether a particular file would be filtered out by the current
382 + * exclusion rules for this FileList.
383 + * @param {String} name The filename to check
384 + * @return {Boolean} Whether or not the file should be excluded
385 + */
386 + this.shouldExclude = function (name) {
387 + if (!this.excludes.regex) {
388 + _calculateExcludeRe.call(this);
389 + }
390 + var excl = this.excludes;
391 + return excl.regex.test(name) || excl.funcs.some(function (f) {
392 + return !!f(name);
393 + });
394 + };
395 +
396 + /**
397 + * Excludes file-patterns from the FileList. Should be called with one or more
398 + * pattern for finding file to include in the list. Arguments can be:
399 + * 1. Strings for either a glob-pattern or a specific file-name
400 + * 2. Regular expression literals
401 + * 3. Functions to be run on the filename that return a true/false
402 + */
403 + this.exclude = function () {
404 + var args = Array.isArray(arguments[0]) ? arguments[0] : arguments
405 + , arg;
406 + for (var i = 0, ii = args.length; i < ii; i++) {
407 + arg = args[i];
408 + if (typeof arg == 'function' && !(arg instanceof RegExp)) {
409 + this.excludes.funcs.push(arg);
410 + }
411 + else {
412 + this.excludes.pats.push(arg);
413 + }
414 + }
415 + if (!this.pending) {
416 + _resolveExclude.call(this);
417 + }
418 + return this;
419 + };
420 +
421 + /**
422 + * Populates the FileList from the include/exclude rules with a list of
423 + * actual files
424 + */
425 + this.resolve = function () {
426 + var item
427 + , uniqueFunc = function (p, c) {
428 + if (p.indexOf(c) < 0) {
429 + p.push(c);
430 + }
431 + return p;
432 + };
433 + if (this.pending) {
434 + this.pending = false;
435 + while ((item = this.pendingAdd.shift())) {
436 + _resolveAdd.call(this, item);
437 + }
438 + // Reduce to a unique list
439 + this.items = this.items.reduce(uniqueFunc, []);
440 + // Remove exclusions
441 + _resolveExclude.call(this);
442 + }
443 + return this;
444 + };
445 +
446 + /**
447 + * Convert to a plain-jane array
448 + */
449 + this.toArray = function () {
450 + // Call slice to ensure lazy-resolution before slicing items
451 + var ret = this.slice().items.slice();
452 + return ret;
453 + };
454 +
455 + /**
456 + * Clear any pending items -- only useful before
457 + * calling `resolve`
458 + */
459 + this.clearInclusions = function () {
460 + this.pendingAdd = [];
461 + return this;
462 + };
463 +
464 + /**
465 + * Clear any current exclusion rules
466 + */
467 + this.clearExclusions = function () {
468 + this.excludes = {
469 + pats: []
470 + , funcs: []
471 + , regex: null
472 + };
473 + return this;
474 + };
475 +
476 +})();
477 +
478 +// Static method, used to create copy returned by special
479 +// array methods
480 +FileList.clone = function (list, items) {
481 + var clone = new FileList();
482 + if (items) {
483 + clone.items = items;
484 + }
485 + clone.pendingAdd = list.pendingAdd;
486 + clone.pending = list.pending;
487 + for (var p in list.excludes) {
488 + clone.excludes[p] = list.excludes[p];
489 + }
490 + return clone;
491 +};
492 +
493 +FileList.verbose = true
494 +
495 +exports.FileList = FileList;
1 +testTask('FileList', function () {
2 + this.testFiles.include('test/*.js');
3 +});
4 +
5 +publishTask('FileList', function () {
6 + this.packageFiles.include([
7 + 'jakefile.js',
8 + 'README.md',
9 + 'package.json',
10 + 'index.js',
11 + 'index.d.ts'
12 + ]);
13 +});
14 +
15 +
1 +The ISC License
2 +
3 +Copyright (c) 2011-2022 Isaac Z. Schlueter and Contributors
4 +
5 +Permission to use, copy, modify, and/or distribute this software for any
6 +purpose with or without fee is hereby granted, provided that the above
7 +copyright notice and this permission notice appear in all copies.
8 +
9 +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
15 +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1 +# minimatch
2 +
3 +A minimal matching utility.
4 +
5 +[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch)
6 +
7 +
8 +This is the matching library used internally by npm.
9 +
10 +It works by converting glob expressions into JavaScript `RegExp`
11 +objects.
12 +
13 +## Usage
14 +
15 +```javascript
16 +var minimatch = require("minimatch")
17 +
18 +minimatch("bar.foo", "*.foo") // true!
19 +minimatch("bar.foo", "*.bar") // false!
20 +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy!
21 +```
22 +
23 +## Features
24 +
25 +Supports these glob features:
26 +
27 +* Brace Expansion
28 +* Extended glob matching
29 +* "Globstar" `**` matching
30 +
31 +See:
32 +
33 +* `man sh`
34 +* `man bash`
35 +* `man 3 fnmatch`
36 +* `man 5 gitignore`
37 +
38 +## Windows
39 +
40 +**Please only use forward-slashes in glob expressions.**
41 +
42 +Though windows uses either `/` or `\` as its path separator, only `/`
43 +characters are used by this glob implementation. You must use
44 +forward-slashes **only** in glob expressions. Back-slashes in patterns
45 +will always be interpreted as escape characters, not path separators.
46 +
47 +Note that `\` or `/` _will_ be interpreted as path separators in paths on
48 +Windows, and will match against `/` in glob expressions.
49 +
50 +So just always use `/` in patterns.
51 +
52 +## Minimatch Class
53 +
54 +Create a minimatch object by instantiating the `minimatch.Minimatch` class.
55 +
56 +```javascript
57 +var Minimatch = require("minimatch").Minimatch
58 +var mm = new Minimatch(pattern, options)
59 +```
60 +
61 +### Properties
62 +
63 +* `pattern` The original pattern the minimatch object represents.
64 +* `options` The options supplied to the constructor.
65 +* `set` A 2-dimensional array of regexp or string expressions.
66 + Each row in the
67 + array corresponds to a brace-expanded pattern. Each item in the row
68 + corresponds to a single path-part. For example, the pattern
69 + `{a,b/c}/d` would expand to a set of patterns like:
70 +
71 + [ [ a, d ]
72 + , [ b, c, d ] ]
73 +
74 + If a portion of the pattern doesn't have any "magic" in it
75 + (that is, it's something like `"foo"` rather than `fo*o?`), then it
76 + will be left as a string rather than converted to a regular
77 + expression.
78 +
79 +* `regexp` Created by the `makeRe` method. A single regular expression
80 + expressing the entire pattern. This is useful in cases where you wish
81 + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
82 +* `negate` True if the pattern is negated.
83 +* `comment` True if the pattern is a comment.
84 +* `empty` True if the pattern is `""`.
85 +
86 +### Methods
87 +
88 +* `makeRe` Generate the `regexp` member if necessary, and return it.
89 + Will return `false` if the pattern is invalid.
90 +* `match(fname)` Return true if the filename matches the pattern, or
91 + false otherwise.
92 +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split
93 + filename, and match it against a single row in the `regExpSet`. This
94 + method is mainly for internal use, but is exposed so that it can be
95 + used by a glob-walker that needs to avoid excessive filesystem calls.
96 +
97 +All other methods are internal, and will be called as necessary.
98 +
99 +### minimatch(path, pattern, options)
100 +
101 +Main export. Tests a path against the pattern using the options.
102 +
103 +```javascript
104 +var isJS = minimatch(file, "*.js", { matchBase: true })
105 +```
106 +
107 +### minimatch.filter(pattern, options)
108 +
109 +Returns a function that tests its
110 +supplied argument, suitable for use with `Array.filter`. Example:
111 +
112 +```javascript
113 +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true}))
114 +```
115 +
116 +### minimatch.match(list, pattern, options)
117 +
118 +Match against the list of
119 +files, in the style of fnmatch or glob. If nothing is matched, and
120 +options.nonull is set, then return a list containing the pattern itself.
121 +
122 +```javascript
123 +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})
124 +```
125 +
126 +### minimatch.makeRe(pattern, options)
127 +
128 +Make a regular expression object from the pattern.
129 +
130 +## Options
131 +
132 +All options are `false` by default.
133 +
134 +### debug
135 +
136 +Dump a ton of stuff to stderr.
137 +
138 +### nobrace
139 +
140 +Do not expand `{a,b}` and `{1..3}` brace sets.
141 +
142 +### noglobstar
143 +
144 +Disable `**` matching against multiple folder names.
145 +
146 +### dot
147 +
148 +Allow patterns to match filenames starting with a period, even if
149 +the pattern does not explicitly have a period in that spot.
150 +
151 +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
152 +is set.
153 +
154 +### noext
155 +
156 +Disable "extglob" style patterns like `+(a|b)`.
157 +
158 +### nocase
159 +
160 +Perform a case-insensitive match.
161 +
162 +### nonull
163 +
164 +When a match is not found by `minimatch.match`, return a list containing
165 +the pattern itself if this option is set. When not set, an empty list
166 +is returned if there are no matches.
167 +
168 +### matchBase
169 +
170 +If set, then patterns without slashes will be matched
171 +against the basename of the path if it contains slashes. For example,
172 +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
173 +
174 +### nocomment
175 +
176 +Suppress the behavior of treating `#` at the start of a pattern as a
177 +comment.
178 +
179 +### nonegate
180 +
181 +Suppress the behavior of treating a leading `!` character as negation.
182 +
183 +### flipNegate
184 +
185 +Returns from negate expressions the same as if they were not negated.
186 +(Ie, true on a hit, false on a miss.)
187 +
188 +### partial
189 +
190 +Compare a partial path to a pattern. As long as the parts of the path that
191 +are present are not contradicted by the pattern, it will be treated as a
192 +match. This is useful in applications where you're walking through a
193 +folder structure, and don't yet have the full path, but want to ensure that
194 +you do not walk down paths that can never be a match.
195 +
196 +For example,
197 +
198 +```js
199 +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d
200 +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d
201 +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a
202 +```
203 +
204 +### windowsPathsNoEscape
205 +
206 +Use `\\` as a path separator _only_, and _never_ as an escape
207 +character. If set, all `\\` characters are replaced with `/` in
208 +the pattern. Note that this makes it **impossible** to match
209 +against paths containing literal glob pattern characters, but
210 +allows matching with patterns constructed using `path.join()` and
211 +`path.resolve()` on Windows platforms, mimicking the (buggy!)
212 +behavior of earlier versions on Windows. Please use with
213 +caution, and be mindful of [the caveat about Windows
214 +paths](#windows).
215 +
216 +For legacy reasons, this is also set if
217 +`options.allowWindowsEscape` is set to the exact value `false`.
218 +
219 +## Comparisons to other fnmatch/glob implementations
220 +
221 +While strict compliance with the existing standards is a worthwhile
222 +goal, some discrepancies exist between minimatch and other
223 +implementations, and are intentional.
224 +
225 +If the pattern starts with a `!` character, then it is negated. Set the
226 +`nonegate` flag to suppress this behavior, and treat leading `!`
227 +characters normally. This is perhaps relevant if you wish to start the
228 +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!`
229 +characters at the start of a pattern will negate the pattern multiple
230 +times.
231 +
232 +If a pattern starts with `#`, then it is treated as a comment, and
233 +will not match anything. Use `\#` to match a literal `#` at the
234 +start of a line, or set the `nocomment` flag to suppress this behavior.
235 +
236 +The double-star character `**` is supported by default, unless the
237 +`noglobstar` flag is set. This is supported in the manner of bsdglob
238 +and bash 4.1, where `**` only has special significance if it is the only
239 +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
240 +`a/**b` will not.
241 +
242 +If an escaped pattern has no matches, and the `nonull` flag is set,
243 +then minimatch.match returns the pattern as-provided, rather than
244 +interpreting the character escapes. For example,
245 +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
246 +`"*a?"`. This is akin to setting the `nullglob` option in bash, except
247 +that it does not resolve escaped pattern characters.
248 +
249 +If brace expansion is not disabled, then it is performed before any
250 +other interpretation of the glob pattern. Thus, a pattern like
251 +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
252 +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
253 +checked for validity. Since those two are valid, matching proceeds.
254 +
255 +Note that `fnmatch(3)` in libc is an extremely naive string comparison
256 +matcher, which does not do anything special for slashes. This library is
257 +designed to be used in glob searching and file walkers, and so it does do
258 +special things with `/`. Thus, `foo*` will not match `foo/bar` in this
259 +library, even though it would in `fnmatch(3)`.
1 +const isWindows = typeof process === 'object' &&
2 + process &&
3 + process.platform === 'win32'
4 +module.exports = isWindows ? { sep: '\\' } : { sep: '/' }
1 +const minimatch = module.exports = (p, pattern, options = {}) => {
2 + assertValidPattern(pattern)
3 +
4 + // shortcut: comments match nothing.
5 + if (!options.nocomment && pattern.charAt(0) === '#') {
6 + return false
7 + }
8 +
9 + return new Minimatch(pattern, options).match(p)
10 +}
11 +
12 +module.exports = minimatch
13 +
14 +const path = require('./lib/path.js')
15 +minimatch.sep = path.sep
16 +
17 +const GLOBSTAR = Symbol('globstar **')
18 +minimatch.GLOBSTAR = GLOBSTAR
19 +const expand = require('brace-expansion')
20 +
21 +const plTypes = {
22 + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
23 + '?': { open: '(?:', close: ')?' },
24 + '+': { open: '(?:', close: ')+' },
25 + '*': { open: '(?:', close: ')*' },
26 + '@': { open: '(?:', close: ')' }
27 +}
28 +
29 +// any single thing other than /
30 +// don't need to escape / when using new RegExp()
31 +const qmark = '[^/]'
32 +
33 +// * => any number of characters
34 +const star = qmark + '*?'
35 +
36 +// ** when dots are allowed. Anything goes, except .. and .
37 +// not (^ or / followed by one or two dots followed by $ or /),
38 +// followed by anything, any number of times.
39 +const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
40 +
41 +// not a ^ or / followed by a dot,
42 +// followed by anything, any number of times.
43 +const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
44 +
45 +// "abc" -> { a:true, b:true, c:true }
46 +const charSet = s => s.split('').reduce((set, c) => {
47 + set[c] = true
48 + return set
49 +}, {})
50 +
51 +// characters that need to be escaped in RegExp.
52 +const reSpecials = charSet('().*{}+?[]^$\\!')
53 +
54 +// characters that indicate we have to add the pattern start
55 +const addPatternStartSet = charSet('[.(')
56 +
57 +// normalizes slashes.
58 +const slashSplit = /\/+/
59 +
60 +minimatch.filter = (pattern, options = {}) =>
61 + (p, i, list) => minimatch(p, pattern, options)
62 +
63 +const ext = (a, b = {}) => {
64 + const t = {}
65 + Object.keys(a).forEach(k => t[k] = a[k])
66 + Object.keys(b).forEach(k => t[k] = b[k])
67 + return t
68 +}
69 +
70 +minimatch.defaults = def => {
71 + if (!def || typeof def !== 'object' || !Object.keys(def).length) {
72 + return minimatch
73 + }
74 +
75 + const orig = minimatch
76 +
77 + const m = (p, pattern, options) => orig(p, pattern, ext(def, options))
78 + m.Minimatch = class Minimatch extends orig.Minimatch {
79 + constructor (pattern, options) {
80 + super(pattern, ext(def, options))
81 + }
82 + }
83 + m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch
84 + m.filter = (pattern, options) => orig.filter(pattern, ext(def, options))
85 + m.defaults = options => orig.defaults(ext(def, options))
86 + m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options))
87 + m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options))
88 + m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options))
89 +
90 + return m
91 +}
92 +
93 +
94 +
95 +
96 +
97 +// Brace expansion:
98 +// a{b,c}d -> abd acd
99 +// a{b,}c -> abc ac
100 +// a{0..3}d -> a0d a1d a2d a3d
101 +// a{b,c{d,e}f}g -> abg acdfg acefg
102 +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
103 +//
104 +// Invalid sets are not expanded.
105 +// a{2..}b -> a{2..}b
106 +// a{b}c -> a{b}c
107 +minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options)
108 +
109 +const braceExpand = (pattern, options = {}) => {
110 + assertValidPattern(pattern)
111 +
112 + // Thanks to Yeting Li <https://github.com/yetingli> for
113 + // improving this regexp to avoid a ReDOS vulnerability.
114 + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
115 + // shortcut. no need to expand.
116 + return [pattern]
117 + }
118 +
119 + return expand(pattern)
120 +}
121 +
122 +const MAX_PATTERN_LENGTH = 1024 * 64
123 +const assertValidPattern = pattern => {
124 + if (typeof pattern !== 'string') {
125 + throw new TypeError('invalid pattern')
126 + }
127 +
128 + if (pattern.length > MAX_PATTERN_LENGTH) {
129 + throw new TypeError('pattern is too long')
130 + }
131 +}
132 +
133 +// parse a component of the expanded set.
134 +// At this point, no pattern may contain "/" in it
135 +// so we're going to return a 2d array, where each entry is the full
136 +// pattern, split on '/', and then turned into a regular expression.
137 +// A regexp is made at the end which joins each array with an
138 +// escaped /, and another full one which joins each regexp with |.
139 +//
140 +// Following the lead of Bash 4.1, note that "**" only has special meaning
141 +// when it is the *only* thing in a path portion. Otherwise, any series
142 +// of * is equivalent to a single *. Globstar behavior is enabled by
143 +// default, and can be disabled by setting options.noglobstar.
144 +const SUBPARSE = Symbol('subparse')
145 +
146 +minimatch.makeRe = (pattern, options) =>
147 + new Minimatch(pattern, options || {}).makeRe()
148 +
149 +minimatch.match = (list, pattern, options = {}) => {
150 + const mm = new Minimatch(pattern, options)
151 + list = list.filter(f => mm.match(f))
152 + if (mm.options.nonull && !list.length) {
153 + list.push(pattern)
154 + }
155 + return list
156 +}
157 +
158 +// replace stuff like \* with *
159 +const globUnescape = s => s.replace(/\\(.)/g, '$1')
160 +const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
161 +
162 +class Minimatch {
163 + constructor (pattern, options) {
164 + assertValidPattern(pattern)
165 +
166 + if (!options) options = {}
167 +
168 + this.options = options
169 + this.set = []
170 + this.pattern = pattern
171 + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||
172 + options.allowWindowsEscape === false
173 + if (this.windowsPathsNoEscape) {
174 + this.pattern = this.pattern.replace(/\\/g, '/')
175 + }
176 + this.regexp = null
177 + this.negate = false
178 + this.comment = false
179 + this.empty = false
180 + this.partial = !!options.partial
181 +
182 + // make the set of regexps etc.
183 + this.make()
184 + }
185 +
186 + debug () {}
187 +
188 + make () {
189 + const pattern = this.pattern
190 + const options = this.options
191 +
192 + // empty patterns and comments match nothing.
193 + if (!options.nocomment && pattern.charAt(0) === '#') {
194 + this.comment = true
195 + return
196 + }
197 + if (!pattern) {
198 + this.empty = true
199 + return
200 + }
201 +
202 + // step 1: figure out negation, etc.
203 + this.parseNegate()
204 +
205 + // step 2: expand braces
206 + let set = this.globSet = this.braceExpand()
207 +
208 + if (options.debug) this.debug = (...args) => console.error(...args)
209 +
210 + this.debug(this.pattern, set)
211 +
212 + // step 3: now we have a set, so turn each one into a series of path-portion
213 + // matching patterns.
214 + // These will be regexps, except in the case of "**", which is
215 + // set to the GLOBSTAR object for globstar behavior,
216 + // and will not contain any / characters
217 + set = this.globParts = set.map(s => s.split(slashSplit))
218 +
219 + this.debug(this.pattern, set)
220 +
221 + // glob --> regexps
222 + set = set.map((s, si, set) => s.map(this.parse, this))
223 +
224 + this.debug(this.pattern, set)
225 +
226 + // filter out everything that didn't compile properly.
227 + set = set.filter(s => s.indexOf(false) === -1)
228 +
229 + this.debug(this.pattern, set)
230 +
231 + this.set = set
232 + }
233 +
234 + parseNegate () {
235 + if (this.options.nonegate) return
236 +
237 + const pattern = this.pattern
238 + let negate = false
239 + let negateOffset = 0
240 +
241 + for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
242 + negate = !negate
243 + negateOffset++
244 + }
245 +
246 + if (negateOffset) this.pattern = pattern.substr(negateOffset)
247 + this.negate = negate
248 + }
249 +
250 + // set partial to true to test if, for example,
251 + // "/a/b" matches the start of "/*/b/*/d"
252 + // Partial means, if you run out of file before you run
253 + // out of pattern, then that's fine, as long as all
254 + // the parts match.
255 + matchOne (file, pattern, partial) {
256 + var options = this.options
257 +
258 + this.debug('matchOne',
259 + { 'this': this, file: file, pattern: pattern })
260 +
261 + this.debug('matchOne', file.length, pattern.length)
262 +
263 + for (var fi = 0,
264 + pi = 0,
265 + fl = file.length,
266 + pl = pattern.length
267 + ; (fi < fl) && (pi < pl)
268 + ; fi++, pi++) {
269 + this.debug('matchOne loop')
270 + var p = pattern[pi]
271 + var f = file[fi]
272 +
273 + this.debug(pattern, p, f)
274 +
275 + // should be impossible.
276 + // some invalid regexp stuff in the set.
277 + /* istanbul ignore if */
278 + if (p === false) return false
279 +
280 + if (p === GLOBSTAR) {
281 + this.debug('GLOBSTAR', [pattern, p, f])
282 +
283 + // "**"
284 + // a/**/b/**/c would match the following:
285 + // a/b/x/y/z/c
286 + // a/x/y/z/b/c
287 + // a/b/x/b/x/c
288 + // a/b/c
289 + // To do this, take the rest of the pattern after
290 + // the **, and see if it would match the file remainder.
291 + // If so, return success.
292 + // If not, the ** "swallows" a segment, and try again.
293 + // This is recursively awful.
294 + //
295 + // a/**/b/**/c matching a/b/x/y/z/c
296 + // - a matches a
297 + // - doublestar
298 + // - matchOne(b/x/y/z/c, b/**/c)
299 + // - b matches b
300 + // - doublestar
301 + // - matchOne(x/y/z/c, c) -> no
302 + // - matchOne(y/z/c, c) -> no
303 + // - matchOne(z/c, c) -> no
304 + // - matchOne(c, c) yes, hit
305 + var fr = fi
306 + var pr = pi + 1
307 + if (pr === pl) {
308 + this.debug('** at the end')
309 + // a ** at the end will just swallow the rest.
310 + // We have found a match.
311 + // however, it will not swallow /.x, unless
312 + // options.dot is set.
313 + // . and .. are *never* matched by **, for explosively
314 + // exponential reasons.
315 + for (; fi < fl; fi++) {
316 + if (file[fi] === '.' || file[fi] === '..' ||
317 + (!options.dot && file[fi].charAt(0) === '.')) return false
318 + }
319 + return true
320 + }
321 +
322 + // ok, let's see if we can swallow whatever we can.
323 + while (fr < fl) {
324 + var swallowee = file[fr]
325 +
326 + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
327 +
328 + // XXX remove this slice. Just pass the start index.
329 + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
330 + this.debug('globstar found match!', fr, fl, swallowee)
331 + // found a match.
332 + return true
333 + } else {
334 + // can't swallow "." or ".." ever.
335 + // can only swallow ".foo" when explicitly asked.
336 + if (swallowee === '.' || swallowee === '..' ||
337 + (!options.dot && swallowee.charAt(0) === '.')) {
338 + this.debug('dot detected!', file, fr, pattern, pr)
339 + break
340 + }
341 +
342 + // ** swallows a segment, and continue.
343 + this.debug('globstar swallow a segment, and continue')
344 + fr++
345 + }
346 + }
347 +
348 + // no match was found.
349 + // However, in partial mode, we can't say this is necessarily over.
350 + // If there's more *pattern* left, then
351 + /* istanbul ignore if */
352 + if (partial) {
353 + // ran out of file
354 + this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
355 + if (fr === fl) return true
356 + }
357 + return false
358 + }
359 +
360 + // something other than **
361 + // non-magic patterns just have to match exactly
362 + // patterns with magic have been turned into regexps.
363 + var hit
364 + if (typeof p === 'string') {
365 + hit = f === p
366 + this.debug('string match', p, f, hit)
367 + } else {
368 + hit = f.match(p)
369 + this.debug('pattern match', p, f, hit)
370 + }
371 +
372 + if (!hit) return false
373 + }
374 +
375 + // Note: ending in / means that we'll get a final ""
376 + // at the end of the pattern. This can only match a
377 + // corresponding "" at the end of the file.
378 + // If the file ends in /, then it can only match a
379 + // a pattern that ends in /, unless the pattern just
380 + // doesn't have any more for it. But, a/b/ should *not*
381 + // match "a/b/*", even though "" matches against the
382 + // [^/]*? pattern, except in partial mode, where it might
383 + // simply not be reached yet.
384 + // However, a/b/ should still satisfy a/*
385 +
386 + // now either we fell off the end of the pattern, or we're done.
387 + if (fi === fl && pi === pl) {
388 + // ran out of pattern and filename at the same time.
389 + // an exact hit!
390 + return true
391 + } else if (fi === fl) {
392 + // ran out of file, but still had pattern left.
393 + // this is ok if we're doing the match as part of
394 + // a glob fs traversal.
395 + return partial
396 + } else /* istanbul ignore else */ if (pi === pl) {
397 + // ran out of pattern, still have file left.
398 + // this is only acceptable if we're on the very last
399 + // empty segment of a file with a trailing slash.
400 + // a/* should match a/b/
401 + return (fi === fl - 1) && (file[fi] === '')
402 + }
403 +
404 + // should be unreachable.
405 + /* istanbul ignore next */
406 + throw new Error('wtf?')
407 + }
408 +
409 + braceExpand () {
410 + return braceExpand(this.pattern, this.options)
411 + }
412 +
413 + parse (pattern, isSub) {
414 + assertValidPattern(pattern)
415 +
416 + const options = this.options
417 +
418 + // shortcuts
419 + if (pattern === '**') {
420 + if (!options.noglobstar)
421 + return GLOBSTAR
422 + else
423 + pattern = '*'
424 + }
425 + if (pattern === '') return ''
426 +
427 + let re = ''
428 + let hasMagic = !!options.nocase
429 + let escaping = false
430 + // ? => one single character
431 + const patternListStack = []
432 + const negativeLists = []
433 + let stateChar
434 + let inClass = false
435 + let reClassStart = -1
436 + let classStart = -1
437 + let cs
438 + let pl
439 + let sp
440 + // . and .. never match anything that doesn't start with .,
441 + // even when options.dot is set.
442 + const patternStart = pattern.charAt(0) === '.' ? '' // anything
443 + // not (start or / followed by . or .. followed by / or end)
444 + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
445 + : '(?!\\.)'
446 +
447 + const clearStateChar = () => {
448 + if (stateChar) {
449 + // we had some state-tracking character
450 + // that wasn't consumed by this pass.
451 + switch (stateChar) {
452 + case '*':
453 + re += star
454 + hasMagic = true
455 + break
456 + case '?':
457 + re += qmark
458 + hasMagic = true
459 + break
460 + default:
461 + re += '\\' + stateChar
462 + break
463 + }
464 + this.debug('clearStateChar %j %j', stateChar, re)
465 + stateChar = false
466 + }
467 + }
468 +
469 + for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) {
470 + this.debug('%s\t%s %s %j', pattern, i, re, c)
471 +
472 + // skip over any that are escaped.
473 + if (escaping) {
474 + /* istanbul ignore next - completely not allowed, even escaped. */
475 + if (c === '/') {
476 + return false
477 + }
478 +
479 + if (reSpecials[c]) {
480 + re += '\\'
481 + }
482 + re += c
483 + escaping = false
484 + continue
485 + }
486 +
487 + switch (c) {
488 + /* istanbul ignore next */
489 + case '/': {
490 + // Should already be path-split by now.
491 + return false
492 + }
493 +
494 + case '\\':
495 + clearStateChar()
496 + escaping = true
497 + continue
498 +
499 + // the various stateChar values
500 + // for the "extglob" stuff.
501 + case '?':
502 + case '*':
503 + case '+':
504 + case '@':
505 + case '!':
506 + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
507 +
508 + // all of those are literals inside a class, except that
509 + // the glob [!a] means [^a] in regexp
510 + if (inClass) {
511 + this.debug(' in class')
512 + if (c === '!' && i === classStart + 1) c = '^'
513 + re += c
514 + continue
515 + }
516 +
517 + // if we already have a stateChar, then it means
518 + // that there was something like ** or +? in there.
519 + // Handle the stateChar, then proceed with this one.
520 + this.debug('call clearStateChar %j', stateChar)
521 + clearStateChar()
522 + stateChar = c
523 + // if extglob is disabled, then +(asdf|foo) isn't a thing.
524 + // just clear the statechar *now*, rather than even diving into
525 + // the patternList stuff.
526 + if (options.noext) clearStateChar()
527 + continue
528 +
529 + case '(':
530 + if (inClass) {
531 + re += '('
532 + continue
533 + }
534 +
535 + if (!stateChar) {
536 + re += '\\('
537 + continue
538 + }
539 +
540 + patternListStack.push({
541 + type: stateChar,
542 + start: i - 1,
543 + reStart: re.length,
544 + open: plTypes[stateChar].open,
545 + close: plTypes[stateChar].close
546 + })
547 + // negation is (?:(?!js)[^/]*)
548 + re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
549 + this.debug('plType %j %j', stateChar, re)
550 + stateChar = false
551 + continue
552 +
553 + case ')':
554 + if (inClass || !patternListStack.length) {
555 + re += '\\)'
556 + continue
557 + }
558 +
559 + clearStateChar()
560 + hasMagic = true
561 + pl = patternListStack.pop()
562 + // negation is (?:(?!js)[^/]*)
563 + // The others are (?:<pattern>)<type>
564 + re += pl.close
565 + if (pl.type === '!') {
566 + negativeLists.push(pl)
567 + }
568 + pl.reEnd = re.length
569 + continue
570 +
571 + case '|':
572 + if (inClass || !patternListStack.length) {
573 + re += '\\|'
574 + continue
575 + }
576 +
577 + clearStateChar()
578 + re += '|'
579 + continue
580 +
581 + // these are mostly the same in regexp and glob
582 + case '[':
583 + // swallow any state-tracking char before the [
584 + clearStateChar()
585 +
586 + if (inClass) {
587 + re += '\\' + c
588 + continue
589 + }
590 +
591 + inClass = true
592 + classStart = i
593 + reClassStart = re.length
594 + re += c
595 + continue
596 +
597 + case ']':
598 + // a right bracket shall lose its special
599 + // meaning and represent itself in
600 + // a bracket expression if it occurs
601 + // first in the list. -- POSIX.2 2.8.3.2
602 + if (i === classStart + 1 || !inClass) {
603 + re += '\\' + c
604 + continue
605 + }
606 +
607 + // handle the case where we left a class open.
608 + // "[z-a]" is valid, equivalent to "\[z-a\]"
609 + // split where the last [ was, make sure we don't have
610 + // an invalid re. if so, re-walk the contents of the
611 + // would-be class to re-translate any characters that
612 + // were passed through as-is
613 + // TODO: It would probably be faster to determine this
614 + // without a try/catch and a new RegExp, but it's tricky
615 + // to do safely. For now, this is safe and works.
616 + cs = pattern.substring(classStart + 1, i)
617 + try {
618 + RegExp('[' + cs + ']')
619 + } catch (er) {
620 + // not a valid class!
621 + sp = this.parse(cs, SUBPARSE)
622 + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
623 + hasMagic = hasMagic || sp[1]
624 + inClass = false
625 + continue
626 + }
627 +
628 + // finish up the class.
629 + hasMagic = true
630 + inClass = false
631 + re += c
632 + continue
633 +
634 + default:
635 + // swallow any state char that wasn't consumed
636 + clearStateChar()
637 +
638 + if (reSpecials[c] && !(c === '^' && inClass)) {
639 + re += '\\'
640 + }
641 +
642 + re += c
643 + break
644 +
645 + } // switch
646 + } // for
647 +
648 + // handle the case where we left a class open.
649 + // "[abc" is valid, equivalent to "\[abc"
650 + if (inClass) {
651 + // split where the last [ was, and escape it
652 + // this is a huge pita. We now have to re-walk
653 + // the contents of the would-be class to re-translate
654 + // any characters that were passed through as-is
655 + cs = pattern.substr(classStart + 1)
656 + sp = this.parse(cs, SUBPARSE)
657 + re = re.substr(0, reClassStart) + '\\[' + sp[0]
658 + hasMagic = hasMagic || sp[1]
659 + }
660 +
661 + // handle the case where we had a +( thing at the *end*
662 + // of the pattern.
663 + // each pattern list stack adds 3 chars, and we need to go through
664 + // and escape any | chars that were passed through as-is for the regexp.
665 + // Go through and escape them, taking care not to double-escape any
666 + // | chars that were already escaped.
667 + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
668 + let tail
669 + tail = re.slice(pl.reStart + pl.open.length)
670 + this.debug('setting tail', re, pl)
671 + // maybe some even number of \, then maybe 1 \, followed by a |
672 + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
673 + /* istanbul ignore else - should already be done */
674 + if (!$2) {
675 + // the | isn't already escaped, so escape it.
676 + $2 = '\\'
677 + }
678 +
679 + // need to escape all those slashes *again*, without escaping the
680 + // one that we need for escaping the | character. As it works out,
681 + // escaping an even number of slashes can be done by simply repeating
682 + // it exactly after itself. That's why this trick works.
683 + //
684 + // I am sorry that you have to see this.
685 + return $1 + $1 + $2 + '|'
686 + })
687 +
688 + this.debug('tail=%j\n %s', tail, tail, pl, re)
689 + const t = pl.type === '*' ? star
690 + : pl.type === '?' ? qmark
691 + : '\\' + pl.type
692 +
693 + hasMagic = true
694 + re = re.slice(0, pl.reStart) + t + '\\(' + tail
695 + }
696 +
697 + // handle trailing things that only matter at the very end.
698 + clearStateChar()
699 + if (escaping) {
700 + // trailing \\
701 + re += '\\\\'
702 + }
703 +
704 + // only need to apply the nodot start if the re starts with
705 + // something that could conceivably capture a dot
706 + const addPatternStart = addPatternStartSet[re.charAt(0)]
707 +
708 + // Hack to work around lack of negative lookbehind in JS
709 + // A pattern like: *.!(x).!(y|z) needs to ensure that a name
710 + // like 'a.xyz.yz' doesn't match. So, the first negative
711 + // lookahead, has to look ALL the way ahead, to the end of
712 + // the pattern.
713 + for (let n = negativeLists.length - 1; n > -1; n--) {
714 + const nl = negativeLists[n]
715 +
716 + const nlBefore = re.slice(0, nl.reStart)
717 + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
718 + let nlAfter = re.slice(nl.reEnd)
719 + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter
720 +
721 + // Handle nested stuff like *(*.js|!(*.json)), where open parens
722 + // mean that we should *not* include the ) in the bit that is considered
723 + // "after" the negated section.
724 + const openParensBefore = nlBefore.split('(').length - 1
725 + let cleanAfter = nlAfter
726 + for (let i = 0; i < openParensBefore; i++) {
727 + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
728 + }
729 + nlAfter = cleanAfter
730 +
731 + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : ''
732 + re = nlBefore + nlFirst + nlAfter + dollar + nlLast
733 + }
734 +
735 + // if the re is not "" at this point, then we need to make sure
736 + // it doesn't match against an empty path part.
737 + // Otherwise a/* will match a/, which it should not.
738 + if (re !== '' && hasMagic) {
739 + re = '(?=.)' + re
740 + }
741 +
742 + if (addPatternStart) {
743 + re = patternStart + re
744 + }
745 +
746 + // parsing just a piece of a larger pattern.
747 + if (isSub === SUBPARSE) {
748 + return [re, hasMagic]
749 + }
750 +
751 + // skip the regexp for non-magical patterns
752 + // unescape anything in it, though, so that it'll be
753 + // an exact match against a file etc.
754 + if (!hasMagic) {
755 + return globUnescape(pattern)
756 + }
757 +
758 + const flags = options.nocase ? 'i' : ''
759 + try {
760 + return Object.assign(new RegExp('^' + re + '$', flags), {
761 + _glob: pattern,
762 + _src: re,
763 + })
764 + } catch (er) /* istanbul ignore next - should be impossible */ {
765 + // If it was an invalid regular expression, then it can't match
766 + // anything. This trick looks for a character after the end of
767 + // the string, which is of course impossible, except in multi-line
768 + // mode, but it's not a /m regex.
769 + return new RegExp('$.')
770 + }
771 + }
772 +
773 + makeRe () {
774 + if (this.regexp || this.regexp === false) return this.regexp
775 +
776 + // at this point, this.set is a 2d array of partial
777 + // pattern strings, or "**".
778 + //
779 + // It's better to use .match(). This function shouldn't
780 + // be used, really, but it's pretty convenient sometimes,
781 + // when you just want to work with a regex.
782 + const set = this.set
783 +
784 + if (!set.length) {
785 + this.regexp = false
786 + return this.regexp
787 + }
788 + const options = this.options
789 +
790 + const twoStar = options.noglobstar ? star
791 + : options.dot ? twoStarDot
792 + : twoStarNoDot
793 + const flags = options.nocase ? 'i' : ''
794 +
795 + // coalesce globstars and regexpify non-globstar patterns
796 + // if it's the only item, then we just do one twoStar
797 + // if it's the first, and there are more, prepend (\/|twoStar\/)? to next
798 + // if it's the last, append (\/twoStar|) to previous
799 + // if it's in the middle, append (\/|\/twoStar\/) to previous
800 + // then filter out GLOBSTAR symbols
801 + let re = set.map(pattern => {
802 + pattern = pattern.map(p =>
803 + typeof p === 'string' ? regExpEscape(p)
804 + : p === GLOBSTAR ? GLOBSTAR
805 + : p._src
806 + ).reduce((set, p) => {
807 + if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) {
808 + set.push(p)
809 + }
810 + return set
811 + }, [])
812 + pattern.forEach((p, i) => {
813 + if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) {
814 + return
815 + }
816 + if (i === 0) {
817 + if (pattern.length > 1) {
818 + pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1]
819 + } else {
820 + pattern[i] = twoStar
821 + }
822 + } else if (i === pattern.length - 1) {
823 + pattern[i-1] += '(?:\\\/|' + twoStar + ')?'
824 + } else {
825 + pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1]
826 + pattern[i+1] = GLOBSTAR
827 + }
828 + })
829 + return pattern.filter(p => p !== GLOBSTAR).join('/')
830 + }).join('|')
831 +
832 + // must match entire pattern
833 + // ending in a * or ** will make it less strict.
834 + re = '^(?:' + re + ')$'
835 +
836 + // can match anything, as long as it's not this.
837 + if (this.negate) re = '^(?!' + re + ').*$'
838 +
839 + try {
840 + this.regexp = new RegExp(re, flags)
841 + } catch (ex) /* istanbul ignore next - should be impossible */ {
842 + this.regexp = false
843 + }
844 + return this.regexp
845 + }
846 +
847 + match (f, partial = this.partial) {
848 + this.debug('match', f, this.pattern)
849 + // short-circuit in the case of busted things.
850 + // comments, etc.
851 + if (this.comment) return false
852 + if (this.empty) return f === ''
853 +
854 + if (f === '/' && partial) return true
855 +
856 + const options = this.options
857 +
858 + // windows: need to use /, not \
859 + if (path.sep !== '/') {
860 + f = f.split(path.sep).join('/')
861 + }
862 +
863 + // treat the test path as a set of pathparts.
864 + f = f.split(slashSplit)
865 + this.debug(this.pattern, 'split', f)
866 +
867 + // just ONE of the pattern sets in this.set needs to match
868 + // in order for it to be valid. If negating, then just one
869 + // match means that we have failed.
870 + // Either way, return on the first hit.
871 +
872 + const set = this.set
873 + this.debug(this.pattern, 'set', set)
874 +
875 + // Find the basename of the path by looking for the last non-empty segment
876 + let filename
877 + for (let i = f.length - 1; i >= 0; i--) {
878 + filename = f[i]
879 + if (filename) break
880 + }
881 +
882 + for (let i = 0; i < set.length; i++) {
883 + const pattern = set[i]
884 + let file = f
885 + if (options.matchBase && pattern.length === 1) {
886 + file = [filename]
887 + }
888 + const hit = this.matchOne(file, pattern, partial)
889 + if (hit) {
890 + if (options.flipNegate) return true
891 + return !this.negate
892 + }
893 + }
894 +
895 + // didn't get any hits. this is success if it's a negative
896 + // pattern, failure otherwise.
897 + if (options.flipNegate) return false
898 + return this.negate
899 + }
900 +
901 + static defaults (def) {
902 + return minimatch.defaults(def).Minimatch
903 + }
904 +}
905 +
906 +minimatch.Minimatch = Minimatch
1 +{
2 + "_from": "minimatch@^5.0.1",
3 + "_id": "minimatch@5.1.0",
4 + "_inBundle": false,
5 + "_integrity": "sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==",
6 + "_location": "/filelist/minimatch",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "minimatch@^5.0.1",
12 + "name": "minimatch",
13 + "escapedName": "minimatch",
14 + "rawSpec": "^5.0.1",
15 + "saveSpec": null,
16 + "fetchSpec": "^5.0.1"
17 + },
18 + "_requiredBy": [
19 + "/filelist"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.0.tgz",
22 + "_shasum": "1717b464f4971b144f6aabe8f2d0b8e4511e09c7",
23 + "_spec": "minimatch@^5.0.1",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\filelist",
25 + "author": {
26 + "name": "Isaac Z. Schlueter",
27 + "email": "i@izs.me",
28 + "url": "http://blog.izs.me"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/isaacs/minimatch/issues"
32 + },
33 + "bundleDependencies": false,
34 + "dependencies": {
35 + "brace-expansion": "^2.0.1"
36 + },
37 + "deprecated": false,
38 + "description": "a glob matcher in javascript",
39 + "devDependencies": {
40 + "tap": "^15.1.6"
41 + },
42 + "engines": {
43 + "node": ">=10"
44 + },
45 + "files": [
46 + "minimatch.js",
47 + "lib"
48 + ],
49 + "homepage": "https://github.com/isaacs/minimatch#readme",
50 + "license": "ISC",
51 + "main": "minimatch.js",
52 + "name": "minimatch",
53 + "repository": {
54 + "type": "git",
55 + "url": "git://github.com/isaacs/minimatch.git"
56 + },
57 + "scripts": {
58 + "postversion": "npm publish",
59 + "prepublishOnly": "git push origin --follow-tags",
60 + "preversion": "npm test",
61 + "snap": "tap",
62 + "test": "tap"
63 + },
64 + "version": "5.1.0"
65 +}
1 +{
2 + "_from": "filelist@^1.0.1",
3 + "_id": "filelist@1.0.4",
4 + "_inBundle": false,
5 + "_integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==",
6 + "_location": "/filelist",
7 + "_phantomChildren": {
8 + "brace-expansion": "2.0.1"
9 + },
10 + "_requested": {
11 + "type": "range",
12 + "registry": true,
13 + "raw": "filelist@^1.0.1",
14 + "name": "filelist",
15 + "escapedName": "filelist",
16 + "rawSpec": "^1.0.1",
17 + "saveSpec": null,
18 + "fetchSpec": "^1.0.1"
19 + },
20 + "_requiredBy": [
21 + "/jake"
22 + ],
23 + "_resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz",
24 + "_shasum": "f78978a1e944775ff9e62e744424f215e58352b5",
25 + "_spec": "filelist@^1.0.1",
26 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\jake",
27 + "author": {
28 + "name": "Matthew Eernisse",
29 + "email": "mde@fleegix.org",
30 + "url": "http://fleegix.org"
31 + },
32 + "bugs": {
33 + "url": "https://github.com/mde/filelist/issues"
34 + },
35 + "bundleDependencies": false,
36 + "dependencies": {
37 + "minimatch": "^5.0.1"
38 + },
39 + "deprecated": false,
40 + "description": "Lazy-evaluating list of files, based on globs or regex patterns",
41 + "homepage": "https://github.com/mde/filelist",
42 + "keywords": [
43 + "file",
44 + "utility",
45 + "glob"
46 + ],
47 + "license": "Apache-2.0",
48 + "main": "index.js",
49 + "name": "filelist",
50 + "repository": {
51 + "type": "git",
52 + "url": "git://github.com/mde/filelist.git"
53 + },
54 + "scripts": {
55 + "test": "jake test"
56 + },
57 + "types": "index.d.ts",
58 + "version": "1.0.4"
59 +}
1 +/**
2 +Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag.
3 +
4 +@param flag - CLI flag to look for. The `--` prefix is optional.
5 +@param argv - CLI arguments. Default: `process.argv`.
6 +@returns Whether the flag exists.
7 +
8 +@example
9 +```
10 +// $ ts-node foo.ts -f --unicorn --foo=bar -- --rainbow
11 +
12 +// foo.ts
13 +import hasFlag = require('has-flag');
14 +
15 +hasFlag('unicorn');
16 +//=> true
17 +
18 +hasFlag('--unicorn');
19 +//=> true
20 +
21 +hasFlag('f');
22 +//=> true
23 +
24 +hasFlag('-f');
25 +//=> true
26 +
27 +hasFlag('foo=bar');
28 +//=> true
29 +
30 +hasFlag('foo');
31 +//=> false
32 +
33 +hasFlag('rainbow');
34 +//=> false
35 +```
36 +*/
37 +declare function hasFlag(flag: string, argv?: string[]): boolean;
38 +
39 +export = hasFlag;
1 +'use strict';
2 +
3 +module.exports = (flag, argv = process.argv) => {
4 + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
5 + const position = argv.indexOf(prefix + flag);
6 + const terminatorPosition = argv.indexOf('--');
7 + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
8 +};
1 +MIT License
2 +
3 +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
4 +
5 +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:
6 +
7 +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 +
9 +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.
1 +{
2 + "_from": "has-flag@^4.0.0",
3 + "_id": "has-flag@4.0.0",
4 + "_inBundle": false,
5 + "_integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
6 + "_location": "/has-flag",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "has-flag@^4.0.0",
12 + "name": "has-flag",
13 + "escapedName": "has-flag",
14 + "rawSpec": "^4.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "^4.0.0"
17 + },
18 + "_requiredBy": [
19 + "/supports-color"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
22 + "_shasum": "944771fd9c81c81265c4d6941860da06bb59479b",
23 + "_spec": "has-flag@^4.0.0",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\supports-color",
25 + "author": {
26 + "name": "Sindre Sorhus",
27 + "email": "sindresorhus@gmail.com",
28 + "url": "sindresorhus.com"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/sindresorhus/has-flag/issues"
32 + },
33 + "bundleDependencies": false,
34 + "deprecated": false,
35 + "description": "Check if argv has a specific flag",
36 + "devDependencies": {
37 + "ava": "^1.4.1",
38 + "tsd": "^0.7.2",
39 + "xo": "^0.24.0"
40 + },
41 + "engines": {
42 + "node": ">=8"
43 + },
44 + "files": [
45 + "index.js",
46 + "index.d.ts"
47 + ],
48 + "homepage": "https://github.com/sindresorhus/has-flag#readme",
49 + "keywords": [
50 + "has",
51 + "check",
52 + "detect",
53 + "contains",
54 + "find",
55 + "flag",
56 + "cli",
57 + "command-line",
58 + "argv",
59 + "process",
60 + "arg",
61 + "args",
62 + "argument",
63 + "arguments",
64 + "getopt",
65 + "minimist",
66 + "optimist"
67 + ],
68 + "license": "MIT",
69 + "name": "has-flag",
70 + "repository": {
71 + "type": "git",
72 + "url": "git+https://github.com/sindresorhus/has-flag.git"
73 + },
74 + "scripts": {
75 + "test": "xo && ava && tsd"
76 + },
77 + "version": "4.0.0"
78 +}
1 +# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag)
2 +
3 +> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag
4 +
5 +Correctly stops looking after an `--` argument terminator.
6 +
7 +---
8 +
9 +<div align="center">
10 + <b>
11 + <a href="https://tidelift.com/subscription/pkg/npm-has-flag?utm_source=npm-has-flag&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
12 + </b>
13 + <br>
14 + <sub>
15 + Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
16 + </sub>
17 +</div>
18 +
19 +---
20 +
21 +
22 +## Install
23 +
24 +```
25 +$ npm install has-flag
26 +```
27 +
28 +
29 +## Usage
30 +
31 +```js
32 +// foo.js
33 +const hasFlag = require('has-flag');
34 +
35 +hasFlag('unicorn');
36 +//=> true
37 +
38 +hasFlag('--unicorn');
39 +//=> true
40 +
41 +hasFlag('f');
42 +//=> true
43 +
44 +hasFlag('-f');
45 +//=> true
46 +
47 +hasFlag('foo=bar');
48 +//=> true
49 +
50 +hasFlag('foo');
51 +//=> false
52 +
53 +hasFlag('rainbow');
54 +//=> false
55 +```
56 +
57 +```
58 +$ node foo.js -f --unicorn --foo=bar -- --rainbow
59 +```
60 +
61 +
62 +## API
63 +
64 +### hasFlag(flag, [argv])
65 +
66 +Returns a boolean for whether the flag exists.
67 +
68 +#### flag
69 +
70 +Type: `string`
71 +
72 +CLI flag to look for. The `--` prefix is optional.
73 +
74 +#### argv
75 +
76 +Type: `string[]`<br>
77 +Default: `process.argv`
78 +
79 +CLI arguments.
80 +
81 +
82 +## Security
83 +
84 +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.
85 +
86 +
87 +## License
88 +
89 +MIT © [Sindre Sorhus](https://sindresorhus.com)
1 +#
2 +# Jake JavaScript build tool
3 +# Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 +#
5 +# Licensed under the Apache License, Version 2.0 (the "License");
6 +# you may not use this file except in compliance with the License.
7 +# You may obtain a copy of the License at
8 +#
9 +# http://www.apache.org/licenses/LICENSE-2.0
10 +#
11 +# Unless required by applicable law or agreed to in writing, software
12 +# distributed under the License is distributed on an "AS IS" BASIS,
13 +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 +# See the License for the specific language governing permissions and
15 +# limitations under the License.
16 +#
17 +
18 +.PHONY: all build install clean uninstall
19 +
20 +PREFIX=/usr/local
21 +DESTDIR=
22 +
23 +all: build
24 +
25 +build:
26 + @echo 'Jake built.'
27 +
28 +install:
29 + @mkdir -p $(DESTDIR)$(PREFIX)/bin && \
30 + mkdir -p $(DESTDIR)$(PREFIX)/lib/node_modules/jake && \
31 + mkdir -p ./node_modules && \
32 + npm install utilities minimatch && \
33 + cp -R ./* $(DESTDIR)$(PREFIX)/lib/node_modules/jake/ && \
34 + ln -snf ../lib/node_modules/jake/bin/cli.js $(DESTDIR)$(PREFIX)/bin/jake && \
35 + chmod 755 $(DESTDIR)$(PREFIX)/lib/node_modules/jake/bin/cli.js && \
36 + echo 'Jake installed.'
37 +
38 +clean:
39 + @true
40 +
41 +uninstall:
42 + @rm -f $(DESTDIR)$(PREFIX)/bin/jake && \
43 + rm -fr $(DESTDIR)$(PREFIX)/lib/node_modules/jake/ && \
44 + echo 'Jake uninstalled.'
1 +### Jake -- the JavaScript build tool for Node.js
2 +
3 +[![Build Status](https://travis-ci.org/jakejs/jake.svg?branch=master)](https://travis-ci.org/jakejs/jake)
4 +
5 +Documentation site at [http://jakejs.com](http://jakejs.com/)
6 +
7 +### Contributing
8 +1. [Install node](http://nodejs.org/#download).
9 +2. Clone this repository `$ git clone git@github.com:jakejs/jake.git`.
10 +3. Install dependencies `$ npm install`.
11 +4. Run tests with `$ npm test`.
12 +5. Start Hacking!
13 +
14 +### License
15 +
16 +Licensed under the Apache License, Version 2.0
17 +(<http://www.apache.org/licenses/LICENSE-2.0>)
1 +#!/bin/bash
2 +
3 +# http://stackoverflow.com/a/246128
4 +SOURCE="${BASH_SOURCE[0]}"
5 +while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
6 + DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
7 + SOURCE="$(readlink "$SOURCE")"
8 + [[ $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
9 +done
10 +JAKE_BIN_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
11 +
12 +# http://stackoverflow.com/a/12495480
13 +# http://stackoverflow.com/a/28647824
14 +_auto_jake()
15 +{
16 + local cur
17 + local -a COMPGEN=()
18 + _get_comp_words_by_ref -n : -c cur
19 +
20 + # run auto-completions in jake via our auto_complete.js wrapper
21 + local -a auto_complete_info=( $(export COMP_LINE="${COMP_LINE}" && ${JAKE_BIN_DIR}/auto_complete.js "$cur" "${3}") )
22 + # check reply flag
23 + local reply_flag="${auto_complete_info[0]}"
24 + if [[ "${reply_flag}" == "no-complete" ]]; then
25 + return 1
26 + fi
27 + local auto_completions=("${auto_complete_info[@]:1}")
28 + COMPGEN=( $(compgen -W "${auto_completions[*]}" -- "$cur") )
29 + COMPREPLY=( "${COMPGEN[@]}" )
30 +
31 + __ltrim_colon_completions "$cur"
32 +
33 + # do we need another space??
34 + if [[ "${reply_flag}" == "yes-space" ]]; then
35 + COMPREPLY=( "${COMPGEN[@]}" " " )
36 + fi
37 +
38 + return 0
39 +}
40 +
41 +complete -o default -F _auto_jake jake
1 +#!/usr/bin/env node
2 +/*
3 + * Jake JavaScript build tool
4 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
5 + *
6 + * Licensed under the Apache License, Version 2.0 (the "License");
7 + * you may not use this file except in compliance with the License.
8 + * You may obtain a copy of the License at
9 + *
10 + * http://www.apache.org/licenses/LICENSE-2.0
11 + *
12 + * Unless required by applicable law or agreed to in writing, software
13 + * distributed under the License is distributed on an "AS IS" BASIS,
14 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 + * See the License for the specific language governing permissions and
16 + * limitations under the License.
17 + *
18 +*/
19 +
20 +// Try to load a local jake
21 +try {
22 + require(`${ process.cwd() }/node_modules/jake`);
23 +}
24 +// If that fails, likely running globally
25 +catch(e) {
26 + require('../lib/jake');
27 +}
28 +
29 +var args = process.argv.slice(2);
30 +
31 +jake.run.apply(jake, args);
1 +let fs = require('fs')
2 +let path = require('path');
3 +let proc = require('child_process');
4 +
5 +const PROJECT_DIR = process.cwd();
6 +process.env.PROJECT_DIR = PROJECT_DIR;
7 +
8 +namespace('doc', function () {
9 + task('generate', ['doc:clobber'], function () {
10 + var cmd = '../node-jsdoc-toolkit/app/run.js -n -r=100 ' +
11 + '-t=../node-jsdoc-toolkit/templates/codeview -d=./doc/ ./lib';
12 + jake.logger.log('Generating docs ...');
13 + jake.exec([cmd], function () {
14 + jake.logger.log('Done.');
15 + complete();
16 + });
17 + }, {async: true});
18 +
19 + task('clobber', function () {
20 + var cmd = 'rm -fr ./doc/*';
21 + jake.exec([cmd], function () {
22 + jake.logger.log('Clobbered old docs.');
23 + complete();
24 + });
25 + }, {async: true});
26 +
27 +});
28 +
29 +desc('Generate docs for Jake');
30 +task('doc', ['doc:generate']);
31 +
32 +npmPublishTask('jake', function () {
33 + this.packageFiles.include([
34 + 'Makefile',
35 + 'jakefile.js',
36 + 'README.md',
37 + 'package.json',
38 + 'usage.txt',
39 + 'lib/**',
40 + 'bin/**',
41 + 'test/**'
42 + ]);
43 + this.packageFiles.exclude([
44 + 'test/tmp'
45 + ]);
46 +});
47 +
48 +jake.Task['publish:package'].directory = PROJECT_DIR;
49 +
50 +namespace('test', function () {
51 +
52 + let integrationTest = task('integration', async function () {
53 + let testArgs = [];
54 + if (process.env.filter) {
55 + testArgs.push(process.env.filter);
56 + }
57 + else {
58 + testArgs.push('*.js');
59 + }
60 + let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, {
61 + stdio: 'inherit'
62 + });
63 + return new Promise((resolve, reject) => {
64 + spawned.on('exit', () => {
65 + resolve();
66 + });
67 + });
68 +
69 + });
70 + integrationTest.directory = `${PROJECT_DIR}/test/integration`;
71 +
72 + let integrationClobber = task('integrationClobber', function () {
73 + proc.execSync('rm -rf package.json pkg tmp_publish');
74 + });
75 + integrationClobber.directory = `${PROJECT_DIR}/test/integration`;
76 +
77 + let unitTest = task('unit', async function () {
78 + let testArgs = [];
79 + if (process.env.filter) {
80 + testArgs.push(process.env.filter);
81 + }
82 + else {
83 + testArgs.push('*.js');
84 + }
85 + let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, {
86 + stdio: 'inherit'
87 + });
88 + });
89 + unitTest.directory = `${PROJECT_DIR}/test/unit`;
90 +
91 +});
92 +
93 +desc('Runs all tests');
94 +task('test', ['test:unit', 'test:integration', 'test:integrationClobber']);
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +let { uuid } = require('./utils');
19 +
20 +let api = new (function () {
21 + /**
22 + @name task
23 + @static
24 + @function
25 + @description Creates a Jake Task
26 + `
27 + @param {String} name The name of the Task
28 + @param {Array} [prereqs] Prerequisites to be run before this task
29 + @param {Function} [action] The action to perform for this task
30 + @param {Object} [opts]
31 + @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
32 + If you flag a task with this option, you must call the global
33 + `complete` method inside the task's action, for execution to proceed
34 + to the next task.
35 +
36 + @example
37 + desc('This is the default task.');
38 + task('default', function (params) {
39 + console.log('This is the default task.');
40 + });
41 +
42 + desc('This task has prerequisites.');
43 + task('hasPrereqs', ['foo', 'bar', 'baz'], function (params) {
44 + console.log('Ran some prereqs first.');
45 + });
46 +
47 + desc('This is an asynchronous task.');
48 + task('asyncTask', function () {
49 + setTimeout(complete, 1000);
50 + }, {async: true});
51 + */
52 + this.task = function (name, prereqs, action, opts) {
53 + let args = Array.prototype.slice.call(arguments);
54 + let createdTask;
55 + args.unshift('task');
56 + createdTask = jake.createTask.apply(global, args);
57 + jake.currentTaskDescription = null;
58 + return createdTask;
59 + };
60 +
61 + /**
62 + @name rule
63 + @static
64 + @function
65 + @description Creates a Jake Suffix Rule
66 + `
67 + @param {String} pattern The suffix name of the objective
68 + @param {String} source The suffix name of the objective
69 + @param {Array} [prereqs] Prerequisites to be run before this task
70 + @param {Function} [action] The action to perform for this task
71 + @param {Object} [opts]
72 + @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
73 + If you flag a task with this option, you must call the global
74 + `complete` method inside the task's action, for execution to proceed
75 + to the next task.
76 + @example
77 + desc('This is a rule, which does not support namespace or pattern.');
78 + rule('.o', '.c', {async: true}, function () {
79 + let cmd = util.format('gcc -o %s %s', this.name, this.source);
80 + jake.exec([cmd], function () {
81 + complete();
82 + }, {printStdout: true});
83 + });
84 +
85 + desc('This rule has prerequisites.');
86 + rule('.o', '.c', ['util.h'], {async: true}, function () {
87 + let cmd = util.format('gcc -o %s %s', this.name, this.source);
88 + jake.exec([cmd], function () {
89 + complete();
90 + }, {printStdout: true});
91 + });
92 +
93 + desc('This is a rule with patterns.');
94 + rule('%.o', '%.c', {async: true}, function () {
95 + let cmd = util.format('gcc -o %s %s', this.name, this.source);
96 + jake.exec([cmd], function () {
97 + complete();
98 + }, {printStdout: true});
99 + });
100 +
101 + desc('This is another rule with patterns.');
102 + rule('obj/%.o', 'src/%.c', {async: true}, function () {
103 + let cmd = util.format('gcc -o %s %s', this.name, this.source);
104 + jake.exec([cmd], function () {
105 + complete();
106 + }, {printStdout: true});
107 + });
108 +
109 + desc('This is an example with chain rules.');
110 + rule('%.pdf', '%.dvi', {async: true}, function () {
111 + let cmd = util.format('dvipdfm %s',this.source);
112 + jake.exec([cmd], function () {
113 + complete();
114 + }, {printStdout: true});
115 + });
116 +
117 + rule('%.dvi', '%.tex', {async: true}, function () {
118 + let cmd = util.format('latex %s',this.source);
119 + jake.exec([cmd], function () {
120 + complete();
121 + }, {printStdout: true});
122 + });
123 +
124 + desc('This rule has a namespace.');
125 + task('default', ['debug:obj/main.o]);
126 +
127 + namespace('debug', {async: true}, function() {
128 + rule('obj/%.o', 'src/%.c', function () {
129 + // ...
130 + });
131 + }
132 + */
133 + this.rule = function () {
134 + let args = Array.prototype.slice.call(arguments);
135 + let arg;
136 + let pattern = args.shift();
137 + let source = args.shift();
138 + let prereqs = [];
139 + let action = function () {};
140 + let opts = {};
141 + let key = pattern.toString(); // May be a RegExp
142 +
143 + while ((arg = args.shift())) {
144 + if (typeof arg == 'function') {
145 + action = arg;
146 + }
147 + else if (Array.isArray(arg)) {
148 + prereqs = arg;
149 + }
150 + else {
151 + opts = arg;
152 + }
153 + }
154 +
155 + jake.currentNamespace.rules[key] = new jake.Rule({
156 + pattern: pattern,
157 + source: source,
158 + prereqs: prereqs,
159 + action: action,
160 + opts: opts,
161 + desc: jake.currentTaskDescription,
162 + ns: jake.currentNamespace
163 + });
164 + jake.currentTaskDescription = null;
165 + };
166 +
167 + /**
168 + @name directory
169 + @static
170 + @function
171 + @description Creates a Jake DirectoryTask. Can be used as a prerequisite
172 + for FileTasks, or for simply ensuring a directory exists for use with a
173 + Task's action.
174 + `
175 + @param {String} name The name of the DiretoryTask
176 +
177 + @example
178 +
179 + // Creates the package directory for distribution
180 + directory('pkg');
181 + */
182 + this.directory = function (name) {
183 + let args = Array.prototype.slice.call(arguments);
184 + let createdTask;
185 + args.unshift('directory');
186 + createdTask = jake.createTask.apply(global, args);
187 + jake.currentTaskDescription = null;
188 + return createdTask;
189 + };
190 +
191 + /**
192 + @name file
193 + @static
194 + @function
195 + @description Creates a Jake FileTask.
196 + `
197 + @param {String} name The name of the FileTask
198 + @param {Array} [prereqs] Prerequisites to be run before this task
199 + @param {Function} [action] The action to create this file, if it doesn't
200 + exist already.
201 + @param {Object} [opts]
202 + @param {Array} [opts.asyc=false] Perform this task asynchronously.
203 + If you flag a task with this option, you must call the global
204 + `complete` method inside the task's action, for execution to proceed
205 + to the next task.
206 +
207 + */
208 + this.file = function (name, prereqs, action, opts) {
209 + let args = Array.prototype.slice.call(arguments);
210 + let createdTask;
211 + args.unshift('file');
212 + createdTask = jake.createTask.apply(global, args);
213 + jake.currentTaskDescription = null;
214 + return createdTask;
215 + };
216 +
217 + /**
218 + @name desc
219 + @static
220 + @function
221 + @description Creates a description for a Jake Task (or FileTask,
222 + DirectoryTask). When invoked, the description that iscreated will
223 + be associated with whatever Task is created next.
224 + `
225 + @param {String} description The description for the Task
226 + */
227 + this.desc = function (description) {
228 + jake.currentTaskDescription = description;
229 + };
230 +
231 + /**
232 + @name namespace
233 + @static
234 + @function
235 + @description Creates a namespace which allows logical grouping
236 + of tasks, and prevents name-collisions with task-names. Namespaces
237 + can be nested inside of other namespaces.
238 + `
239 + @param {String} name The name of the namespace
240 + @param {Function} scope The enclosing scope for the namespaced tasks
241 +
242 + @example
243 + namespace('doc', function () {
244 + task('generate', ['doc:clobber'], function () {
245 + // Generate some docs
246 + });
247 +
248 + task('clobber', function () {
249 + // Clobber the doc directory first
250 + });
251 + });
252 + */
253 + this.namespace = function (name, closure) {
254 + let curr = jake.currentNamespace;
255 + let ns = curr.childNamespaces[name] || new jake.Namespace(name, curr);
256 + let fn = closure || function () {};
257 + curr.childNamespaces[name] = ns;
258 + jake.currentNamespace = ns;
259 + fn();
260 + jake.currentNamespace = curr;
261 + jake.currentTaskDescription = null;
262 + return ns;
263 + };
264 +
265 + /**
266 + @name complete
267 + @static
268 + @function
269 + @description Completes an asynchronous task, allowing Jake's
270 + execution to proceed to the next task. Calling complete globally or without
271 + arguments completes the last task on the invocationChain. If you use parallel
272 + execution of prereqs this will probably complete a wrong task. You should call this
273 + function with this task as the first argument, before the optional return value.
274 + Alternatively you can call task.complete()
275 + `
276 + @example
277 + task('generate', ['doc:clobber'], function () {
278 + exec('./generate_docs.sh', function (err, stdout, stderr) {
279 + if (err || stderr) {
280 + fail(err || stderr);
281 + }
282 + else {
283 + console.log(stdout);
284 + complete();
285 + }
286 + });
287 + }, {async: true});
288 + */
289 + this.complete = function (task, val) {
290 + //this should detect if the first arg is a task, but I guess it should be more thorough
291 + if(task && task. _currentPrereqIndex >=0 ) {
292 + task.complete(val);
293 + }
294 + else {
295 + val = task;
296 + if(jake._invocationChain.length > 0) {
297 + jake._invocationChain[jake._invocationChain.length-1].complete(val);
298 + }
299 + }
300 + };
301 +
302 + /**
303 + @name fail
304 + @static
305 + @function
306 + @description Causes Jake execution to abort with an error.
307 + Allows passing an optional error code, which will be used to
308 + set the exit-code of exiting process.
309 + `
310 + @param {Error|String} err The error to thow when aborting execution.
311 + If this argument is an Error object, it will simply be thrown. If
312 + a String, it will be used as the error-message. (If it is a multi-line
313 + String, the first line will be used as the Error message, and the
314 + remaining lines will be used as the error-stack.)
315 +
316 + @example
317 + task('createTests, function () {
318 + if (!fs.existsSync('./tests')) {
319 + fail('Test directory does not exist.');
320 + }
321 + else {
322 + // Do some testing stuff ...
323 + }
324 + });
325 + */
326 + this.fail = function (err, code) {
327 + let msg;
328 + let errObj;
329 + if (code) {
330 + jake.errorCode = code;
331 + }
332 + if (err) {
333 + if (typeof err == 'string') {
334 + // Use the initial or only line of the error as the error-message
335 + // If there was a multi-line error, use the rest as the stack
336 + msg = err.split('\n');
337 + errObj = new Error(msg.shift());
338 + if (msg.length) {
339 + errObj.stack = msg.join('\n');
340 + }
341 + throw errObj;
342 + }
343 + else if (err instanceof Error) {
344 + throw err;
345 + }
346 + else {
347 + throw new Error(err.toString());
348 + }
349 + }
350 + else {
351 + throw new Error();
352 + }
353 + };
354 +
355 + this.packageTask = function (name, version, prereqs, definition) {
356 + return new jake.PackageTask(name, version, prereqs, definition);
357 + };
358 +
359 + this.publishTask = function (name, prereqs, opts, definition) {
360 + return new jake.PublishTask(name, prereqs, opts, definition);
361 + };
362 +
363 + // Backward-compat
364 + this.npmPublishTask = function (name, prereqs, opts, definition) {
365 + return new jake.PublishTask(name, prereqs, opts, definition);
366 + };
367 +
368 + this.testTask = function () {
369 + let ctor = function () {};
370 + let t;
371 + ctor.prototype = jake.TestTask.prototype;
372 + t = new ctor();
373 + jake.TestTask.apply(t, arguments);
374 + return t;
375 + };
376 +
377 + this.setTaskTimeout = function (t) {
378 + this._taskTimeout = t;
379 + };
380 +
381 + this.setSeriesAutoPrefix = function (prefix) {
382 + this._seriesAutoPrefix = prefix;
383 + };
384 +
385 + this.series = function (...args) {
386 + let prereqs = args.map((arg) => {
387 + let name = (this._seriesAutoPrefix || '') + arg.name;
388 + jake.task(name, arg);
389 + return name;
390 + });
391 + let seriesName = uuid();
392 + let seriesTask = jake.task(seriesName, prereqs);
393 + seriesTask._internal = true;
394 + let res = function () {
395 + return new Promise((resolve) => {
396 + seriesTask.invoke();
397 + seriesTask.on('complete', (val) => {
398 + resolve(val);
399 + });
400 + });
401 + };
402 + Object.defineProperty(res, 'name', {value: uuid(),
403 + writable: false});
404 + return res;
405 + };
406 +
407 +})();
408 +
409 +module.exports = api;
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +if (!global.jake) {
20 +
21 + let EventEmitter = require('events').EventEmitter;
22 + // And so it begins
23 + global.jake = new EventEmitter();
24 +
25 + let fs = require('fs');
26 + let chalk = require('chalk');
27 + let taskNs = require('./task');
28 + let Task = taskNs.Task;
29 + let FileTask = taskNs.FileTask;
30 + let DirectoryTask = taskNs.DirectoryTask;
31 + let Rule = require('./rule').Rule;
32 + let Namespace = require('./namespace').Namespace;
33 + let RootNamespace = require('./namespace').RootNamespace;
34 + let api = require('./api');
35 + let utils = require('./utils');
36 + let Program = require('./program').Program;
37 + let loader = require('./loader')();
38 + let pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString());
39 +
40 + const MAX_RULE_RECURSION_LEVEL = 16;
41 +
42 + // Globalize jake and top-level API methods (e.g., `task`, `desc`)
43 + Object.assign(global, api);
44 +
45 + // Copy utils onto base jake
46 + jake.logger = utils.logger;
47 + jake.exec = utils.exec;
48 +
49 + // File utils should be aliased directly on base jake as well
50 + Object.assign(jake, utils.file);
51 +
52 + // Also add top-level API methods to exported object for those who don't want to
53 + // use the globals (`file` here will overwrite the 'file' utils namespace)
54 + Object.assign(jake, api);
55 +
56 + Object.assign(jake, new (function () {
57 +
58 + this._invocationChain = [];
59 + this._taskTimeout = 30000;
60 +
61 + // Public properties
62 + // =================
63 + this.version = pkg.version;
64 + // Used when Jake exits with a specific error-code
65 + this.errorCode = null;
66 + // Loads Jakefiles/jakelibdirs
67 + this.loader = loader;
68 + // The root of all ... namespaces
69 + this.rootNamespace = new RootNamespace();
70 + // Non-namespaced tasks are placed into the default
71 + this.defaultNamespace = this.rootNamespace;
72 + // Start in the default
73 + this.currentNamespace = this.defaultNamespace;
74 + // Saves the description created by a 'desc' call that prefaces a
75 + // 'task' call that defines a task.
76 + this.currentTaskDescription = null;
77 + this.program = new Program();
78 + this.FileList = require('filelist').FileList;
79 + this.PackageTask = require('./package_task').PackageTask;
80 + this.PublishTask = require('./publish_task').PublishTask;
81 + this.TestTask = require('./test_task').TestTask;
82 + this.Task = Task;
83 + this.FileTask = FileTask;
84 + this.DirectoryTask = DirectoryTask;
85 + this.Namespace = Namespace;
86 + this.Rule = Rule;
87 +
88 + this.parseAllTasks = function () {
89 + let _parseNs = function (ns) {
90 + let nsTasks = ns.tasks;
91 + let nsNamespaces = ns.childNamespaces;
92 + for (let q in nsTasks) {
93 + let nsTask = nsTasks[q];
94 + jake.Task[nsTask.fullName] = nsTask;
95 + }
96 + for (let p in nsNamespaces) {
97 + let nsNamespace = nsNamespaces[p];
98 + _parseNs(nsNamespace);
99 + }
100 + };
101 + _parseNs(jake.defaultNamespace);
102 + };
103 +
104 + /**
105 + * Displays the list of descriptions available for tasks defined in
106 + * a Jakefile
107 + */
108 + this.showAllTaskDescriptions = function (f) {
109 + let p;
110 + let maxTaskNameLength = 0;
111 + let task;
112 + let padding;
113 + let name;
114 + let descr;
115 + let filter = typeof f == 'string' ? f : null;
116 + let taskParams;
117 + let len;
118 +
119 + for (p in jake.Task) {
120 + if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) {
121 + continue;
122 + }
123 + if (filter && p.indexOf(filter) == -1) {
124 + continue;
125 + }
126 + task = jake.Task[p];
127 + taskParams = task.params;
128 +
129 + // Record the length of the longest task name -- used for
130 + // pretty alignment of the task descriptions
131 + if (task.description) {
132 + len = p.length + taskParams.length;
133 + maxTaskNameLength = len > maxTaskNameLength ?
134 + len : maxTaskNameLength;
135 + }
136 + }
137 +
138 + // Print out each entry with descriptions neatly aligned
139 + for (p in jake.Task) {
140 + if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) {
141 + continue;
142 + }
143 + if (filter && p.indexOf(filter) == -1) {
144 + continue;
145 + }
146 + task = jake.Task[p];
147 +
148 + taskParams = "";
149 + if (task.params != "") {
150 + taskParams = "[" + task.params + "]";
151 + }
152 +
153 + //name = '\033[32m' + p + '\033[39m ';
154 + name = chalk.green(p);
155 +
156 + descr = task.description;
157 + if (descr) {
158 + descr = chalk.gray('# ' + descr);
159 +
160 + // Create padding-string with calculated length
161 + padding = (new Array(maxTaskNameLength - p.length - taskParams.length + 4)).join(' ');
162 +
163 + console.log('jake ' + name + taskParams + padding + descr);
164 + }
165 + }
166 + };
167 +
168 + this.createTask = function () {
169 + let args = Array.prototype.slice.call(arguments);
170 + let arg;
171 + let obj;
172 + let task;
173 + let type;
174 + let name;
175 + let action;
176 + let opts = {};
177 + let prereqs = [];
178 +
179 + type = args.shift();
180 +
181 + // name, [deps], [action]
182 + // Name (string) + deps (array) format
183 + if (typeof args[0] == 'string') {
184 + name = args.shift();
185 + if (Array.isArray(args[0])) {
186 + prereqs = args.shift();
187 + }
188 + }
189 + // name:deps, [action]
190 + // Legacy object-literal syntax, e.g.: {'name': ['depA', 'depB']}
191 + else {
192 + obj = args.shift();
193 + for (let p in obj) {
194 + prereqs = prereqs.concat(obj[p]);
195 + name = p;
196 + }
197 + }
198 +
199 + // Optional opts/callback or callback/opts
200 + while ((arg = args.shift())) {
201 + if (typeof arg == 'function') {
202 + action = arg;
203 + }
204 + else {
205 + opts = Object.assign(Object.create(null), arg);
206 + }
207 + }
208 +
209 + task = jake.currentNamespace.resolveTask(name);
210 + if (task && !action) {
211 + // Task already exists and no action, just update prereqs, and return it.
212 + task.prereqs = task.prereqs.concat(prereqs);
213 + return task;
214 + }
215 +
216 + switch (type) {
217 + case 'directory':
218 + action = function () {
219 + jake.mkdirP(name);
220 + };
221 + task = new DirectoryTask(name, prereqs, action, opts);
222 + break;
223 + case 'file':
224 + task = new FileTask(name, prereqs, action, opts);
225 + break;
226 + default:
227 + task = new Task(name, prereqs, action, opts);
228 + }
229 +
230 + jake.currentNamespace.addTask(task);
231 +
232 + if (jake.currentTaskDescription) {
233 + task.description = jake.currentTaskDescription;
234 + jake.currentTaskDescription = null;
235 + }
236 +
237 + // FIXME: Should only need to add a new entry for the current
238 + // task-definition, not reparse the entire structure
239 + jake.parseAllTasks();
240 +
241 + return task;
242 + };
243 +
244 + this.attemptRule = function (name, ns, level) {
245 + let prereqRule;
246 + let prereq;
247 + if (level > MAX_RULE_RECURSION_LEVEL) {
248 + return null;
249 + }
250 + // Check Rule
251 + prereqRule = ns.matchRule(name);
252 + if (prereqRule) {
253 + prereq = prereqRule.createTask(name, level);
254 + }
255 + return prereq || null;
256 + };
257 +
258 + this.createPlaceholderFileTask = function (name, namespace) {
259 + let parsed = name.split(':');
260 + let filePath = parsed.pop(); // Strip any namespace
261 + let task;
262 +
263 + task = namespace.resolveTask(name);
264 +
265 + // If there's not already an existing dummy FileTask for it,
266 + // create one
267 + if (!task) {
268 + // Create a dummy FileTask only if file actually exists
269 + if (fs.existsSync(filePath)) {
270 + task = new jake.FileTask(filePath);
271 + task.dummy = true;
272 + let ns;
273 + if (parsed.length) {
274 + ns = namespace.resolveNamespace(parsed.join(':'));
275 + }
276 + else {
277 + ns = namespace;
278 + }
279 + if (!namespace) {
280 + throw new Error('Invalid namespace, cannot add FileTask');
281 + }
282 + ns.addTask(task);
283 + // Put this dummy Task in the global Tasks list so
284 + // modTime will be eval'd correctly
285 + jake.Task[`${ns.path}:${filePath}`] = task;
286 + }
287 + }
288 +
289 + return task || null;
290 + };
291 +
292 +
293 + this.run = function () {
294 + let args = Array.prototype.slice.call(arguments);
295 + let program = this.program;
296 + let loader = this.loader;
297 + let preempt;
298 + let opts;
299 +
300 + program.parseArgs(args);
301 + program.init();
302 +
303 + preempt = program.firstPreemptiveOption();
304 + if (preempt) {
305 + preempt();
306 + }
307 + else {
308 + opts = program.opts;
309 + // jakefile flag set but no jakefile yet
310 + if (opts.autocomplete && opts.jakefile === true) {
311 + process.stdout.write('no-complete');
312 + return;
313 + }
314 + // Load Jakefile and jakelibdir files
315 + let jakefileLoaded = loader.loadFile(opts.jakefile);
316 + let jakelibdirLoaded = loader.loadDirectory(opts.jakelibdir);
317 +
318 + if(!jakefileLoaded && !jakelibdirLoaded && !opts.autocomplete) {
319 + fail('No Jakefile. Specify a valid path with -f/--jakefile, ' +
320 + 'or place one in the current directory.');
321 + }
322 +
323 + program.run();
324 + }
325 + };
326 +
327 + })());
328 +}
329 +
330 +module.exports = jake;
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +let path = require('path');
20 +let fs = require('fs');
21 +let existsSync = fs.existsSync;
22 +let utils = require('./utils');
23 +
24 +// Files like jakelib/foobar.jake.js
25 +const JAKELIB_FILE_PAT = /\.jake$|\.js$/;
26 +const SUPPORTED_EXTENSIONS = {
27 + 'js': null,
28 + 'coffee': function () {
29 + try {
30 + let cs = require('coffeescript');
31 + if (typeof cs.register == 'function') {
32 + cs.register();
33 + }
34 + }
35 + catch(e) {
36 + throw new Error('You have a CoffeeScript Jakefile, but have not installed CoffeeScript');
37 + }
38 + },
39 + 'ls': function () {
40 + try {
41 + require('livescript');
42 + }
43 + catch (e) {
44 + throw new Error('You have a LiveScript Jakefile, but have not installed LiveScript');
45 + }
46 + },
47 + 'ts': function () {
48 + try {
49 + require('ts-node/register/transpile-only');
50 + }
51 + catch (e) {
52 + throw new Error('You have a TypeScript Jakefile, but have not installed TypeScript and ts-node');
53 + }
54 + }
55 +};
56 +const IMPLICIT_JAKEFILE_NAMES = [
57 + 'Jakefile',
58 + 'Gulpfile'
59 +];
60 +
61 +let Loader = function () {
62 + // Load a Jakefile, running the code inside -- this may result in
63 + // tasks getting defined using the original Jake API, e.g.,
64 + // `task('foo' ['bar', 'baz']);`, or can also auto-create tasks
65 + // from any functions exported from the file
66 + function loadFile(filePath) {
67 + let exported = require(filePath);
68 + for (let [key, value] of Object.entries(exported)) {
69 + let t;
70 + if (typeof value == 'function') {
71 + t = jake.task(key, value);
72 + t.description = '(Exported function)';
73 + }
74 + }
75 + }
76 +
77 + function fileExists(name) {
78 + let nameWithExt = null;
79 + // Support no file extension as well
80 + let exts = Object.keys(SUPPORTED_EXTENSIONS).concat(['']);
81 + exts.some((ext) => {
82 + let fname = ext ? `${name}.${ext}` : name;
83 + if (existsSync(fname)) {
84 + nameWithExt = fname;
85 + return true;
86 + }
87 + });
88 + return nameWithExt;
89 + }
90 +
91 + // Recursive
92 + function findImplicitJakefile() {
93 + let cwd = process.cwd();
94 + let names = IMPLICIT_JAKEFILE_NAMES;
95 + let found = null;
96 + names.some((name) => {
97 + let n;
98 + // Prefer all-lowercase
99 + n = name.toLowerCase();
100 + if ((found = fileExists(n))) {
101 + return found;
102 + }
103 + // Check mixed-case as well
104 + n = name;
105 + if ((found = fileExists(n))) {
106 + return found;
107 + }
108 + });
109 + if (found) {
110 + return found;
111 + }
112 + else {
113 + process.chdir("..");
114 + // If we've walked all the way up the directory tree,
115 + // bail out with no result
116 + if (cwd === process.cwd()) {
117 + return null;
118 + }
119 + return findImplicitJakefile();
120 + }
121 + }
122 +
123 + this.loadFile = function (fileSpecified) {
124 + let jakefile;
125 + let origCwd = process.cwd();
126 +
127 + if (fileSpecified) {
128 + if (existsSync(fileSpecified)) {
129 + jakefile = fileSpecified;
130 + }
131 + }
132 + else {
133 + jakefile = findImplicitJakefile();
134 + }
135 +
136 + if (jakefile) {
137 + let ext = jakefile.split('.')[1];
138 + let loaderFunc = SUPPORTED_EXTENSIONS[ext];
139 + loaderFunc && loaderFunc();
140 +
141 + loadFile(utils.file.absolutize(jakefile));
142 + return true;
143 + }
144 + else {
145 + if (!fileSpecified) {
146 + // Restore the working directory on failure
147 + process.chdir(origCwd);
148 + }
149 + return false;
150 + }
151 + };
152 +
153 + this.loadDirectory = function (d) {
154 + let dirname = d || 'jakelib';
155 + let dirlist;
156 + dirname = utils.file.absolutize(dirname);
157 + if (existsSync(dirname)) {
158 + dirlist = fs.readdirSync(dirname);
159 + dirlist.forEach(function (filePath) {
160 + if (JAKELIB_FILE_PAT.test(filePath)) {
161 + loadFile(path.join(dirname, filePath));
162 + }
163 + });
164 + return true;
165 + }
166 + return false;
167 + };
168 +
169 +};
170 +
171 +module.exports = function () {
172 + return new Loader();
173 +};
1 +const ROOT_NAMESPACE_NAME = '__rootNamespace__';
2 +
3 +class Namespace {
4 + constructor(name, parentNamespace) {
5 + this.name = name;
6 + this.parentNamespace = parentNamespace;
7 + this.childNamespaces = {};
8 + this.tasks = {};
9 + this.rules = {};
10 + this.path = this.getPath();
11 + }
12 +
13 + get fullName() {
14 + return this._getFullName();
15 + }
16 +
17 + addTask(task) {
18 + this.tasks[task.name] = task;
19 + task.namespace = this;
20 + }
21 +
22 + resolveTask(name) {
23 + if (!name) {
24 + return;
25 + }
26 +
27 + let taskPath = name.split(':');
28 + let taskName = taskPath.pop();
29 + let task;
30 + let ns;
31 +
32 + // Namespaced, return either relative to current, or from root
33 + if (taskPath.length) {
34 + taskPath = taskPath.join(':');
35 + ns = this.resolveNamespace(taskPath) ||
36 + Namespace.ROOT_NAMESPACE.resolveNamespace(taskPath);
37 + task = (ns && ns.resolveTask(taskName));
38 + }
39 + // Bare task, return either local, or top-level
40 + else {
41 + task = this.tasks[name] || Namespace.ROOT_NAMESPACE.tasks[name];
42 + }
43 +
44 + return task || null;
45 + }
46 +
47 +
48 + resolveNamespace(relativeName) {
49 + if (!relativeName) {
50 + return this;
51 + }
52 +
53 + let parts = relativeName.split(':');
54 + let ns = this;
55 +
56 + for (let i = 0, ii = parts.length; (ns && i < ii); i++) {
57 + ns = ns.childNamespaces[parts[i]];
58 + }
59 +
60 + return ns || null;
61 + }
62 +
63 + matchRule(relativeName) {
64 + let parts = relativeName.split(':');
65 + parts.pop();
66 + let ns = this.resolveNamespace(parts.join(':'));
67 + let rules = ns ? ns.rules : [];
68 + let r;
69 + let match;
70 +
71 + for (let p in rules) {
72 + r = rules[p];
73 + if (r.match(relativeName)) {
74 + match = r;
75 + }
76 + }
77 +
78 + return (ns && match) ||
79 + (this.parentNamespace &&
80 + this.parentNamespace.matchRule(relativeName));
81 + }
82 +
83 + getPath() {
84 + let parts = [];
85 + let next = this.parentNamespace;
86 + while (next) {
87 + parts.push(next.name);
88 + next = next.parentNamespace;
89 + }
90 + parts.pop(); // Remove '__rootNamespace__'
91 + return parts.reverse().join(':');
92 + }
93 +
94 + _getFullName() {
95 + let path = this.path;
96 + path = (path && path.split(':')) || [];
97 + path.push(this.name);
98 + return path.join(':');
99 + }
100 +
101 + isRootNamespace() {
102 + return !this.parentNamespace;
103 + }
104 +}
105 +
106 +class RootNamespace extends Namespace {
107 + constructor() {
108 + super(ROOT_NAMESPACE_NAME, null);
109 + Namespace.ROOT_NAMESPACE = this;
110 + }
111 +}
112 +
113 +module.exports.Namespace = Namespace;
114 +module.exports.RootNamespace = RootNamespace;
115 +
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +let path = require('path');
20 +let fs = require('fs');
21 +let exec = require('child_process').exec;
22 +let FileList = require('filelist').FileList;
23 +
24 +/**
25 + @name jake
26 + @namespace jake
27 +*/
28 +/**
29 + @name jake.PackageTask
30 + @constructor
31 + @description Instantiating a PackageTask creates a number of Jake
32 + Tasks that make packaging and distributing your software easy.
33 +
34 + @param {String} name The name of the project
35 + @param {String} version The current project version (will be
36 + appended to the project-name in the package-archive
37 + @param {Function} definition Defines the contents of the package,
38 + and format of the package-archive. Will be executed on the instantiated
39 + PackageTask (i.e., 'this', will be the PackageTask instance),
40 + to set the various instance-propertiess.
41 +
42 + @example
43 + let t = new jake.PackageTask('rous', 'v' + version, function () {
44 + let files = [
45 + 'Capfile'
46 + , 'Jakefile'
47 + , 'README.md'
48 + , 'package.json'
49 + , 'app/*'
50 + , 'bin/*'
51 + , 'config/*'
52 + , 'lib/*'
53 + , 'node_modules/*'
54 + ];
55 + this.packageFiles.include(files);
56 + this.packageFiles.exclude('node_modules/foobar');
57 + this.needTarGz = true;
58 + });
59 +
60 + */
61 +let PackageTask = function () {
62 + let args = Array.prototype.slice.call(arguments);
63 + let name = args.shift();
64 + let version = args.shift();
65 + let definition = args.pop();
66 + let prereqs = args.pop() || []; // Optional
67 +
68 + prereqs = [].concat(prereqs); // Accept string or list
69 +
70 + /**
71 + @name jake.PackageTask#name
72 + @public
73 + @type {String}
74 + @description The name of the project
75 + */
76 + this.name = name;
77 + /**
78 + @name jake.PackageTask#version
79 + @public
80 + @type {String}
81 + @description The project version-string
82 + */
83 + this.version = version;
84 + /**
85 + @name jake.PackageTask#prereqs
86 + @public
87 + @type {Array}
88 + @description Tasks to run before packaging
89 + */
90 + this.prereqs = prereqs;
91 + /**
92 + @name jake.PackageTask#packageDir
93 + @public
94 + @type {String='pkg'}
95 + @description The directory-name to use for packaging the software
96 + */
97 + this.packageDir = 'pkg';
98 + /**
99 + @name jake.PackageTask#packageFiles
100 + @public
101 + @type {jake.FileList}
102 + @description The list of files and directories to include in the
103 + package-archive
104 + */
105 + this.packageFiles = new FileList();
106 + /**
107 + @name jake.PackageTask#needTar
108 + @public
109 + @type {Boolean=false}
110 + @description If set to true, uses the `tar` utility to create
111 + a gzip .tgz archive of the package
112 + */
113 + this.needTar = false;
114 + /**
115 + @name jake.PackageTask#needTarGz
116 + @public
117 + @type {Boolean=false}
118 + @description If set to true, uses the `tar` utility to create
119 + a gzip .tar.gz archive of the package
120 + */
121 + this.needTarGz = false;
122 + /**
123 + @name jake.PackageTask#needTarBz2
124 + @public
125 + @type {Boolean=false}
126 + @description If set to true, uses the `tar` utility to create
127 + a bzip2 .bz2 archive of the package
128 + */
129 + this.needTarBz2 = false;
130 + /**
131 + @name jake.PackageTask#needJar
132 + @public
133 + @type {Boolean=false}
134 + @description If set to true, uses the `jar` utility to create
135 + a .jar archive of the package
136 + */
137 + this.needJar = false;
138 + /**
139 + @name jake.PackageTask#needZip
140 + @public
141 + @type {Boolean=false}
142 + @description If set to true, uses the `zip` utility to create
143 + a .zip archive of the package
144 + */
145 + this.needZip = false;
146 + /**
147 + @name jake.PackageTask#manifestFile
148 + @public
149 + @type {String=null}
150 + @description Can be set to point the `jar` utility at a manifest
151 + file to use in a .jar archive. If unset, one will be automatically
152 + created by the `jar` utility. This path should be relative to the
153 + root of the package directory (this.packageDir above, likely 'pkg')
154 + */
155 + this.manifestFile = null;
156 + /**
157 + @name jake.PackageTask#tarCommand
158 + @public
159 + @type {String='tar'}
160 + @description The shell-command to use for creating tar archives.
161 + */
162 + this.tarCommand = 'tar';
163 + /**
164 + @name jake.PackageTask#jarCommand
165 + @public
166 + @type {String='jar'}
167 + @description The shell-command to use for creating jar archives.
168 + */
169 + this.jarCommand = 'jar';
170 + /**
171 + @name jake.PackageTask#zipCommand
172 + @public
173 + @type {String='zip'}
174 + @description The shell-command to use for creating zip archives.
175 + */
176 + this.zipCommand = 'zip';
177 + /**
178 + @name jake.PackageTask#archiveNoBaseDir
179 + @public
180 + @type {Boolean=false}
181 + @description Simple option for performing the archive on the
182 + contents of the directory instead of the directory itself
183 + */
184 + this.archiveNoBaseDir = false;
185 + /**
186 + @name jake.PackageTask#archiveChangeDir
187 + @public
188 + @type {String=null}
189 + @description Equivalent to the '-C' command for the `tar` and `jar`
190 + commands. ("Change to this directory before adding files.")
191 + */
192 + this.archiveChangeDir = null;
193 + /**
194 + @name jake.PackageTask#archiveContentDir
195 + @public
196 + @type {String=null}
197 + @description Specifies the files and directories to include in the
198 + package-archive. If unset, this will default to the main package
199 + directory -- i.e., name + version.
200 + */
201 + this.archiveContentDir = null;
202 +
203 + if (typeof definition == 'function') {
204 + definition.call(this);
205 + }
206 + this.define();
207 +};
208 +
209 +PackageTask.prototype = new (function () {
210 +
211 + let _compressOpts = {
212 + Tar: {
213 + ext: '.tgz',
214 + flags: 'czf',
215 + cmd: 'tar'
216 + },
217 + TarGz: {
218 + ext: '.tar.gz',
219 + flags: 'czf',
220 + cmd: 'tar'
221 + },
222 + TarBz2: {
223 + ext: '.tar.bz2',
224 + flags: 'cjf',
225 + cmd: 'tar'
226 + },
227 + Jar: {
228 + ext: '.jar',
229 + flags: 'cf',
230 + cmd: 'jar'
231 + },
232 + Zip: {
233 + ext: '.zip',
234 + flags: 'qr',
235 + cmd: 'zip'
236 + }
237 + };
238 +
239 + this.define = function () {
240 + let self = this;
241 + let packageDirPath = this.packageDirPath();
242 + let compressTaskArr = [];
243 +
244 + desc('Build the package for distribution');
245 + task('package', self.prereqs.concat(['clobberPackage', 'buildPackage']));
246 + // Backward-compat alias
247 + task('repackage', ['package']);
248 +
249 + task('clobberPackage', function () {
250 + jake.rmRf(self.packageDir, {silent: true});
251 + });
252 +
253 + desc('Remove the package');
254 + task('clobber', ['clobberPackage']);
255 +
256 + let doCommand = function (p) {
257 + let filename = path.resolve(self.packageDir + '/' + self.packageName() +
258 + _compressOpts[p].ext);
259 + if (process.platform == 'win32') {
260 + // Windows full path may have drive letter, which is going to cause
261 + // namespace problems, so strip it.
262 + if (filename.length > 2 && filename[1] == ':') {
263 + filename = filename.substr(2);
264 + }
265 + }
266 + compressTaskArr.push(filename);
267 +
268 + file(filename, [packageDirPath], function () {
269 + let cmd;
270 + let opts = _compressOpts[p];
271 + // Directory to move to when doing the compression-task
272 + // Changes in the case of zip for emulating -C option
273 + let chdir = self.packageDir;
274 + // Save the current dir so it's possible to pop back up
275 + // after compressing
276 + let currDir = process.cwd();
277 + let archiveChangeDir;
278 + let archiveContentDir;
279 +
280 + if (self.archiveNoBaseDir) {
281 + archiveChangeDir = self.packageName();
282 + archiveContentDir = '.';
283 + }
284 + else {
285 + archiveChangeDir = self.archiveChangeDir;
286 + archiveContentDir = self.archiveContentDir;
287 + }
288 +
289 + cmd = self[opts.cmd + 'Command'];
290 + cmd += ' -' + opts.flags;
291 + if (opts.cmd == 'jar' && self.manifestFile) {
292 + cmd += 'm';
293 + }
294 +
295 + // The name of the archive to create -- use full path
296 + // so compression can be performed from a different dir
297 + // if needed
298 + cmd += ' ' + filename;
299 +
300 + if (opts.cmd == 'jar' && self.manifestFile) {
301 + cmd += ' ' + self.manifestFile;
302 + }
303 +
304 + // Where to perform the compression -- -C option isn't
305 + // supported in zip, so actually do process.chdir for this
306 + if (archiveChangeDir) {
307 + if (opts.cmd == 'zip') {
308 + chdir = path.join(chdir, archiveChangeDir);
309 + }
310 + else {
311 + cmd += ' -C ' + archiveChangeDir;
312 + }
313 + }
314 +
315 + // Where to get the archive content
316 + if (archiveContentDir) {
317 + cmd += ' ' + archiveContentDir;
318 + }
319 + else {
320 + cmd += ' ' + self.packageName();
321 + }
322 +
323 + // Move into the desired dir (usually packageDir) to compress
324 + // Return back up to the current dir after the exec
325 + process.chdir(chdir);
326 +
327 + exec(cmd, function (err, stdout, stderr) {
328 + if (err) { throw err; }
329 +
330 + // Return back up to the starting directory (see above,
331 + // before exec)
332 + process.chdir(currDir);
333 +
334 + complete();
335 + });
336 + }, {async: true});
337 + };
338 +
339 + for (let p in _compressOpts) {
340 + if (this['need' + p]) {
341 + doCommand(p);
342 + }
343 + }
344 +
345 + task('buildPackage', compressTaskArr, function () {});
346 +
347 + directory(this.packageDir);
348 +
349 + file(packageDirPath, this.packageFiles, function () {
350 + jake.mkdirP(packageDirPath);
351 + let fileList = [];
352 + self.packageFiles.forEach(function (name) {
353 + let f = path.join(self.packageDirPath(), name);
354 + let fDir = path.dirname(f);
355 + jake.mkdirP(fDir, {silent: true});
356 +
357 + // Add both files and directories
358 + fileList.push({
359 + from: name,
360 + to: f
361 + });
362 + });
363 + let _copyFile = function () {
364 + let file = fileList.pop();
365 + let stat;
366 + if (file) {
367 + stat = fs.statSync(file.from);
368 + // Target is a directory, just create it
369 + if (stat.isDirectory()) {
370 + jake.mkdirP(file.to, {silent: true});
371 + _copyFile();
372 + }
373 + // Otherwise copy the file
374 + else {
375 + jake.cpR(file.from, file.to, {silent: true});
376 + _copyFile();
377 + }
378 + }
379 + else {
380 + complete();
381 + }
382 + };
383 + _copyFile();
384 + }, {async: true});
385 +
386 +
387 + };
388 +
389 + this.packageName = function () {
390 + if (this.version) {
391 + return this.name + '-' + this.version;
392 + }
393 + else {
394 + return this.name;
395 + }
396 + };
397 +
398 + this.packageDirPath = function () {
399 + return this.packageDir + '/' + this.packageName();
400 + };
401 +
402 +})();
403 +
404 +jake.PackageTask = PackageTask;
405 +exports.PackageTask = PackageTask;
406 +
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +let parseargs = {};
20 +let isOpt = function (arg) { return arg.indexOf('-') === 0 };
21 +let removeOptPrefix = function (opt) { return opt.replace(/^--/, '').replace(/^-/, '') };
22 +
23 +/**
24 + * @constructor
25 + * Parses a list of command-line args into a key/value object of
26 + * options and an array of positional commands.
27 + * @ param {Array} opts A list of options in the following format:
28 + * [{full: 'foo', abbr: 'f'}, {full: 'bar', abbr: 'b'}]]
29 + */
30 +parseargs.Parser = function (opts) {
31 + // A key/value object of matching options parsed out of the args
32 + this.opts = {};
33 + this.taskNames = null;
34 + this.envVars = null;
35 +
36 + // Data structures used for parsing
37 + this.reg = opts;
38 + this.shortOpts = {};
39 + this.longOpts = {};
40 +
41 + let self = this;
42 + [].forEach.call(opts, function (item) {
43 + self.shortOpts[item.abbr] = item;
44 + self.longOpts[item.full] = item;
45 + });
46 +};
47 +
48 +parseargs.Parser.prototype = new function () {
49 +
50 + let _trueOrNextVal = function (argParts, args) {
51 + if (argParts[1]) {
52 + return argParts[1];
53 + }
54 + else {
55 + return (!args[0] || isOpt(args[0])) ?
56 + true : args.shift();
57 + }
58 + };
59 +
60 + /**
61 + * Parses an array of arguments into options and positional commands
62 + * @param {Array} args The command-line args to parse
63 + */
64 + this.parse = function (args) {
65 + let cmds = [];
66 + let cmd;
67 + let envVars = {};
68 + let opts = {};
69 + let arg;
70 + let argItem;
71 + let argParts;
72 + let cmdItems;
73 + let taskNames = [];
74 + let preempt;
75 +
76 + while (args.length) {
77 + arg = args.shift();
78 +
79 + if (isOpt(arg)) {
80 + arg = removeOptPrefix(arg);
81 + argParts = arg.split('=');
82 + argItem = this.longOpts[argParts[0]] || this.shortOpts[argParts[0]];
83 + if (argItem) {
84 + // First-encountered preemptive opt takes precedence -- no further opts
85 + // or possibility of ambiguity, so just look for a value, or set to
86 + // true and then bail
87 + if (argItem.preempts) {
88 + opts[argItem.full] = _trueOrNextVal(argParts, args);
89 + preempt = true;
90 + break;
91 + }
92 + // If the opt requires a value, see if we can get a value from the
93 + // next arg, or infer true from no-arg -- if it's followed by another
94 + // opt, throw an error
95 + if (argItem.expectValue || argItem.allowValue) {
96 + opts[argItem.full] = _trueOrNextVal(argParts, args);
97 + if (argItem.expectValue && !opts[argItem.full]) {
98 + throw new Error(argItem.full + ' option expects a value.');
99 + }
100 + }
101 + else {
102 + opts[argItem.full] = true;
103 + }
104 + }
105 + }
106 + else {
107 + cmds.unshift(arg);
108 + }
109 + }
110 +
111 + if (!preempt) {
112 + // Parse out any env-vars and task-name
113 + while ((cmd = cmds.pop())) {
114 + cmdItems = cmd.split('=');
115 + if (cmdItems.length > 1) {
116 + envVars[cmdItems[0]] = cmdItems[1];
117 + }
118 + else {
119 + taskNames.push(cmd);
120 + }
121 + }
122 +
123 + }
124 +
125 + return {
126 + opts: opts,
127 + envVars: envVars,
128 + taskNames: taskNames
129 + };
130 + };
131 +
132 +};
133 +
134 +module.exports = parseargs;
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +let fs = require('fs');
20 +let parseargs = require('./parseargs');
21 +let utils = require('./utils');
22 +let Program;
23 +let usage = require('fs').readFileSync(`${__dirname}/../usage.txt`).toString();
24 +let { Task } = require('./task/task');
25 +
26 +function die(msg) {
27 + console.log(msg);
28 + process.stdout.write('', function () {
29 + process.stderr.write('', function () {
30 + process.exit();
31 + });
32 + });
33 +}
34 +
35 +let preempts = {
36 + version: function () {
37 + die(jake.version);
38 + },
39 + help: function () {
40 + die(usage);
41 + }
42 +};
43 +
44 +let AVAILABLE_OPTS = [
45 + { full: 'jakefile',
46 + abbr: 'f',
47 + expectValue: true
48 + },
49 + { full: 'quiet',
50 + abbr: 'q',
51 + expectValue: false
52 + },
53 + { full: 'directory',
54 + abbr: 'C',
55 + expectValue: true
56 + },
57 + { full: 'always-make',
58 + abbr: 'B',
59 + expectValue: false
60 + },
61 + { full: 'tasks',
62 + abbr: 'T',
63 + expectValue: false,
64 + allowValue: true
65 + },
66 + // Alias t
67 + { full: 'tasks',
68 + abbr: 't',
69 + expectValue: false,
70 + allowValue: true
71 + },
72 + // Alias ls
73 + { full: 'tasks',
74 + abbr: 'ls',
75 + expectValue: false,
76 + allowValue: true
77 + },
78 + { full: 'help',
79 + abbr: 'h',
80 + },
81 + { full: 'version',
82 + abbr: 'V',
83 + },
84 + // Alias lowercase v
85 + { full: 'version',
86 + abbr: 'v',
87 + },
88 + { full: 'jakelibdir',
89 + abbr: 'J',
90 + expectValue: true
91 + },
92 + { full: 'allow-rejection',
93 + abbr: 'ar',
94 + expectValue: false
95 + }
96 +];
97 +
98 +Program = function () {
99 + this.availableOpts = AVAILABLE_OPTS;
100 + this.opts = {};
101 + this.taskNames = null;
102 + this.taskArgs = null;
103 + this.envVars = null;
104 + this.die = die;
105 +};
106 +
107 +Program.prototype = new (function () {
108 +
109 + this.handleErr = function (err) {
110 + if (jake.listeners('error').length !== 0) {
111 + jake.emit('error', err);
112 + return;
113 + }
114 +
115 + if (jake.listeners('error').length) {
116 + jake.emit('error', err);
117 + return;
118 + }
119 +
120 + utils.logger.error('jake aborted.');
121 + if (err.stack) {
122 + utils.logger.error(err.stack);
123 + }
124 + else {
125 + utils.logger.error(err.message);
126 + }
127 +
128 + process.stdout.write('', function () {
129 + process.stderr.write('', function () {
130 + jake.errorCode = jake.errorCode || 1;
131 + process.exit(jake.errorCode);
132 + });
133 + });
134 + };
135 +
136 + this.parseArgs = function (args) {
137 + let result = (new parseargs.Parser(this.availableOpts)).parse(args);
138 + this.setOpts(result.opts);
139 + this.setTaskNames(result.taskNames);
140 + this.setEnvVars(result.envVars);
141 + };
142 +
143 + this.setOpts = function (options) {
144 + let opts = options || {};
145 + Object.assign(this.opts, opts);
146 + };
147 +
148 + this.internalOpts = function (options) {
149 + this.availableOpts = this.availableOpts.concat(options);
150 + };
151 +
152 + this.autocompletions = function (cur) {
153 + let p; let i; let task;
154 + let commonPrefix = '';
155 + let matches = [];
156 +
157 + for (p in jake.Task) {
158 + task = jake.Task[p];
159 + if (
160 + 'fullName' in task
161 + && (
162 + // if empty string, program converts to true
163 + cur === true ||
164 + task.fullName.indexOf(cur) === 0
165 + )
166 + ) {
167 + if (matches.length === 0) {
168 + commonPrefix = task.fullName;
169 + }
170 + else {
171 + for (i = commonPrefix.length; i > -1; --i) {
172 + commonPrefix = commonPrefix.substr(0, i);
173 + if (task.fullName.indexOf(commonPrefix) === 0) {
174 + break;
175 + }
176 + }
177 + }
178 + matches.push(task.fullName);
179 + }
180 + }
181 +
182 + if (matches.length > 1 && commonPrefix === cur) {
183 + matches.unshift('yes-space');
184 + }
185 + else {
186 + matches.unshift('no-space');
187 + }
188 +
189 + process.stdout.write(matches.join(' '));
190 + };
191 +
192 + this.setTaskNames = function (names) {
193 + if (names && !Array.isArray(names)) {
194 + throw new Error('Task names must be an array');
195 + }
196 + this.taskNames = (names && names.length) ? names : ['default'];
197 + };
198 +
199 + this.setEnvVars = function (vars) {
200 + this.envVars = vars || null;
201 + };
202 +
203 + this.firstPreemptiveOption = function () {
204 + let opts = this.opts;
205 + for (let p in opts) {
206 + if (preempts[p]) {
207 + return preempts[p];
208 + }
209 + }
210 + return false;
211 + };
212 +
213 + this.init = function (configuration) {
214 + let self = this;
215 + let config = configuration || {};
216 + if (config.options) {
217 + this.setOpts(config.options);
218 + }
219 + if (config.taskNames) {
220 + this.setTaskNames(config.taskNames);
221 + }
222 + if (config.envVars) {
223 + this.setEnvVars(config.envVars);
224 + }
225 + process.addListener('uncaughtException', function (err) {
226 + self.handleErr(err);
227 + });
228 + if (!this.opts['allow-rejection']) {
229 + process.addListener('unhandledRejection', (reason, promise) => {
230 + utils.logger.error('Unhandled rejection at:', promise, 'reason:', reason);
231 + self.handleErr(reason);
232 + });
233 + }
234 + if (this.envVars) {
235 + Object.assign(process.env, this.envVars);
236 + }
237 + };
238 +
239 + this.run = function () {
240 + let rootTask;
241 + let taskNames;
242 + let dirname;
243 + let opts = this.opts;
244 +
245 + if (opts.autocomplete) {
246 + return this.autocompletions(opts['autocomplete-cur'], opts['autocomplete-prev']);
247 + }
248 + // Run with `jake -T`, just show descriptions
249 + if (opts.tasks) {
250 + return jake.showAllTaskDescriptions(opts.tasks);
251 + }
252 +
253 + taskNames = this.taskNames;
254 + if (!(Array.isArray(taskNames) && taskNames.length)) {
255 + throw new Error('Please pass jake.runTasks an array of task-names');
256 + }
257 +
258 + // Set working dir
259 + dirname = opts.directory;
260 + if (dirname) {
261 + if (fs.existsSync(dirname) &&
262 + fs.statSync(dirname).isDirectory()) {
263 + process.chdir(dirname);
264 + }
265 + else {
266 + throw new Error(dirname + ' is not a valid directory path');
267 + }
268 + }
269 +
270 + rootTask = task(Task.ROOT_TASK_NAME, taskNames, function () {});
271 + rootTask._internal = true;
272 +
273 + rootTask.once('complete', function () {
274 + jake.emit('complete');
275 + });
276 + jake.emit('start');
277 + rootTask.invoke();
278 + };
279 +
280 +})();
281 +
282 +module.exports.Program = Program;
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +let fs = require('fs');
20 +let path = require('path');
21 +let exec = require('child_process').execSync;
22 +let FileList = require('filelist').FileList;
23 +
24 +let PublishTask = function () {
25 + let args = Array.prototype.slice.call(arguments).filter(function (item) {
26 + return typeof item != 'undefined';
27 + });
28 + let arg;
29 + let opts = {};
30 + let definition;
31 + let prereqs = [];
32 + let createDef = function (arg) {
33 + return function () {
34 + this.packageFiles.include(arg);
35 + };
36 + };
37 +
38 + this.name = args.shift();
39 +
40 + // Old API, just name + list of files
41 + if (args.length == 1 && (Array.isArray(args[0]) || typeof args[0] == 'string')) {
42 + definition = createDef(args.pop());
43 + }
44 + // Current API, name + [prereqs] + [opts] + definition
45 + else {
46 + while ((arg = args.pop())) {
47 + // Definition func
48 + if (typeof arg == 'function') {
49 + definition = arg;
50 + }
51 + // Prereqs
52 + else if (Array.isArray(arg) || typeof arg == 'string') {
53 + prereqs = arg;
54 + }
55 + // Opts
56 + else {
57 + opts = arg;
58 + }
59 + }
60 + }
61 +
62 + this.prereqs = prereqs;
63 + this.packageFiles = new FileList();
64 + this.publishCmd = opts.publishCmd || 'npm publish %filename';
65 + this.publishMessage = opts.publishMessage || 'BOOM! Published.';
66 + this.gitCmd = opts.gitCmd || 'git';
67 + this.versionFiles = opts.versionFiles || ['package.json'];
68 + this.scheduleDelay = 5000;
69 +
70 + // Override utility funcs for testing
71 + this._ensureRepoClean = function (stdout) {
72 + if (stdout.length) {
73 + fail(new Error('Git repository is not clean.'));
74 + }
75 + };
76 + this._getCurrentBranch = function (stdout) {
77 + return String(stdout).trim();
78 + };
79 +
80 + if (typeof definition == 'function') {
81 + definition.call(this);
82 + }
83 + this.define();
84 +};
85 +
86 +
87 +PublishTask.prototype = new (function () {
88 +
89 + let _currentBranch = null;
90 +
91 + let getPackage = function () {
92 + let pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(),
93 + '/package.json')).toString());
94 + return pkg;
95 + };
96 + let getPackageVersionNumber = function () {
97 + return getPackage().version;
98 + };
99 +
100 + this.define = function () {
101 + let self = this;
102 +
103 + namespace('publish', function () {
104 + task('fetchTags', function () {
105 + // Make sure local tags are up to date
106 + exec(self.gitCmd + ' fetch --tags');
107 + console.log('Fetched remote tags.');
108 + });
109 +
110 + task('getCurrentBranch', function () {
111 + // Figure out what branch to push to
112 + let stdout = exec(self.gitCmd + ' symbolic-ref --short HEAD').toString();
113 + if (!stdout) {
114 + throw new Error('No current Git branch found');
115 + }
116 + _currentBranch = self._getCurrentBranch(stdout);
117 + console.log('On branch ' + _currentBranch);
118 + });
119 +
120 + task('ensureClean', function () {
121 + // Only bump, push, and tag if the Git repo is clean
122 + let stdout = exec(self.gitCmd + ' status --porcelain --untracked-files=no').toString();
123 + // Throw if there's output
124 + self._ensureRepoClean(stdout);
125 + });
126 +
127 + task('updateVersionFiles', function () {
128 + let pkg;
129 + let version;
130 + let arr;
131 + let patch;
132 +
133 + // Grab the current version-string
134 + pkg = getPackage();
135 + version = pkg.version;
136 + // Increment the patch-number for the version
137 + arr = version.split('.');
138 + patch = parseInt(arr.pop(), 10) + 1;
139 + arr.push(patch);
140 + version = arr.join('.');
141 +
142 + // Update package.json or other files with the new version-info
143 + self.versionFiles.forEach(function (file) {
144 + let p = path.join(process.cwd(), file);
145 + let data = JSON.parse(fs.readFileSync(p).toString());
146 + data.version = version;
147 + fs.writeFileSync(p, JSON.stringify(data, true, 2) + '\n');
148 + });
149 + // Return the version string so that listeners for the 'complete' event
150 + // for this task can use it (e.g., to update other files before pushing
151 + // to Git)
152 + return version;
153 + });
154 +
155 + task('pushVersion', ['ensureClean', 'updateVersionFiles'], function () {
156 + let version = getPackageVersionNumber();
157 + let message = 'Version ' + version;
158 + let cmds = [
159 + self.gitCmd + ' commit -a -m "' + message + '"',
160 + self.gitCmd + ' push origin ' + _currentBranch,
161 + self.gitCmd + ' tag -a v' + version + ' -m "' + message + '"',
162 + self.gitCmd + ' push --tags'
163 + ];
164 + cmds.forEach((cmd) => {
165 + exec(cmd);
166 + });
167 + version = getPackageVersionNumber();
168 + console.log('Bumped version number to v' + version + '.');
169 + });
170 +
171 + let defineTask = task('definePackage', function () {
172 + let version = getPackageVersionNumber();
173 + new jake.PackageTask(self.name, 'v' + version, self.prereqs, function () {
174 + // Replace the PackageTask's FileList with the PublishTask's FileList
175 + this.packageFiles = self.packageFiles;
176 + this.needTarGz = true; // Default to tar.gz
177 + // If any of the need<CompressionFormat> or archive opts are set
178 + // proxy them to the PackageTask
179 + for (let p in this) {
180 + if (p.indexOf('need') === 0 || p.indexOf('archive') === 0) {
181 + if (typeof self[p] != 'undefined') {
182 + this[p] = self[p];
183 + }
184 + }
185 + }
186 + });
187 + });
188 + defineTask._internal = true;
189 +
190 + task('package', function () {
191 + let definePack = jake.Task['publish:definePackage'];
192 + let pack = jake.Task['package'];
193 + let version = getPackageVersionNumber();
194 +
195 + // May have already been run
196 + if (definePack.taskStatus == jake.Task.runStatuses.DONE) {
197 + definePack.reenable(true);
198 + }
199 + definePack.execute();
200 + definePack.on('complete', function () {
201 + pack.invoke();
202 + console.log('Created package for ' + self.name + ' v' + version);
203 + });
204 + });
205 +
206 + task('publish', function () {
207 + return new Promise((resolve) => {
208 + let version = getPackageVersionNumber();
209 + let filename;
210 + let cmd;
211 +
212 + console.log('Publishing ' + self.name + ' v' + version);
213 +
214 + if (typeof self.createPublishCommand == 'function') {
215 + cmd = self.createPublishCommand(version);
216 + }
217 + else {
218 + filename = './pkg/' + self.name + '-v' + version + '.tar.gz';
219 + cmd = self.publishCmd.replace(/%filename/gi, filename);
220 + }
221 +
222 + if (typeof cmd == 'function') {
223 + cmd(function (err) {
224 + if (err) {
225 + throw err;
226 + }
227 + console.log(self.publishMessage);
228 + resolve();
229 + });
230 + }
231 + else {
232 + // Hackity hack -- NPM publish sometimes returns errror like:
233 + // Error sending version data\nnpm ERR!
234 + // Error: forbidden 0.2.4 is modified, should match modified time
235 + setTimeout(function () {
236 + let stdout = exec(cmd).toString() || '';
237 + stdout = stdout.trim();
238 + if (stdout) {
239 + console.log(stdout);
240 + }
241 + console.log(self.publishMessage);
242 + resolve();
243 + }, self.scheduleDelay);
244 + }
245 + });
246 + });
247 +
248 + task('cleanup', function () {
249 + return new Promise((resolve) => {
250 + let clobber = jake.Task.clobber;
251 + clobber.reenable(true);
252 + clobber.on('complete', function () {
253 + console.log('Cleaned up package');
254 + resolve();
255 + });
256 + clobber.invoke();
257 + });
258 + });
259 +
260 + });
261 +
262 + let prefixNs = function (item) {
263 + return 'publish:' + item;
264 + };
265 +
266 + // Create aliases in the default namespace
267 + desc('Create a new version and release.');
268 + task('publish', self.prereqs.concat(['version', 'release']
269 + .map(prefixNs)));
270 +
271 + desc('Release the existing version.');
272 + task('publishExisting', self.prereqs.concat(['release']
273 + .map(prefixNs)));
274 +
275 + task('version', ['fetchTags', 'getCurrentBranch', 'pushVersion']
276 + .map(prefixNs));
277 +
278 + task('release', ['package', 'publish', 'cleanup']
279 + .map(prefixNs));
280 +
281 + // Invoke proactively so there will be a callable 'package' task
282 + // which can be used apart from 'publish'
283 + jake.Task['publish:definePackage'].invoke();
284 + };
285 +
286 +})();
287 +
288 +jake.PublishTask = PublishTask;
289 +exports.PublishTask = PublishTask;
290 +
1 +let path = require('path');
2 +let fs = require('fs');
3 +let Task = require('./task/task').Task;
4 +
5 +// Split a task to two parts, name space and task name.
6 +// For example, given 'foo:bin/a%.c', return an object with
7 +// - 'ns' : foo
8 +// - 'name' : bin/a%.c
9 +function splitNs(task) {
10 + let parts = task.split(':');
11 + let name = parts.pop();
12 + let ns = resolveNs(parts);
13 + return {
14 + 'name' : name,
15 + 'ns' : ns
16 + };
17 +}
18 +
19 +// Return the namespace based on an array of names.
20 +// For example, given ['foo', 'baz' ], return the namespace
21 +//
22 +// default -> foo -> baz
23 +//
24 +// where default is the global root namespace
25 +// and -> means child namespace.
26 +function resolveNs(parts) {
27 + let ns = jake.defaultNamespace;
28 + for(let i = 0, l = parts.length; ns && i < l; i++) {
29 + ns = ns.childNamespaces[parts[i]];
30 + }
31 + return ns;
32 +}
33 +
34 +// Given a pattern p, say 'foo:bin/a%.c'
35 +// Return an object with
36 +// - 'ns' : foo
37 +// - 'dir' : bin
38 +// - 'prefix' : a
39 +// - 'suffix' : .c
40 +function resolve(p) {
41 + let task = splitNs(p);
42 + let name = task.name;
43 + let ns = task.ns;
44 + let split = path.basename(name).split('%');
45 + return {
46 + ns: ns,
47 + dir: path.dirname(name),
48 + prefix: split[0],
49 + suffix: split[1]
50 + };
51 +}
52 +
53 +// Test whether string a is a suffix of string b
54 +function stringEndWith(a, b) {
55 + let l;
56 + return (l = b.lastIndexOf(a)) == -1 ? false : l + a.length == b.length;
57 +}
58 +
59 +// Replace the suffix a of the string s with b.
60 +// Note that, it is assumed a is a suffix of s.
61 +function stringReplaceSuffix(s, a, b) {
62 + return s.slice(0, s.lastIndexOf(a)) + b;
63 +}
64 +
65 +class Rule {
66 + constructor(opts) {
67 + this.pattern = opts.pattern;
68 + this.source = opts.source;
69 + this.prereqs = opts.prereqs;
70 + this.action = opts.action;
71 + this.opts = opts.opts;
72 + this.desc = opts.desc;
73 + this.ns = opts.ns;
74 + }
75 +
76 + // Create a file task based on this rule for the specified
77 + // task-name
78 + // ======
79 + // FIXME: Right now this just throws away any passed-in args
80 + // for the synthsized task (taskArgs param)
81 + // ======
82 + createTask(fullName, level) {
83 + let self = this;
84 + let pattern;
85 + let source;
86 + let action;
87 + let opts;
88 + let prereqs;
89 + let valid;
90 + let src;
91 + let tNs;
92 + let createdTask;
93 + let name = Task.getBaseTaskName(fullName);
94 + let nsPath = Task.getBaseNamespacePath(fullName);
95 + let ns = this.ns.resolveNamespace(nsPath);
96 +
97 + pattern = this.pattern;
98 + source = this.source;
99 +
100 + if (typeof source == 'string') {
101 + src = Rule.getSource(name, pattern, source);
102 + }
103 + else {
104 + src = source(name);
105 + }
106 +
107 + // TODO: Write a utility function that appends a
108 + // taskname to a namespace path
109 + src = nsPath.split(':').filter(function (item) {
110 + return !!item;
111 + }).concat(src).join(':');
112 +
113 + // Generate the prerequisite for the matching task.
114 + // It is the original prerequisites plus the prerequisite
115 + // representing source file, i.e.,
116 + //
117 + // rule( '%.o', '%.c', ['some.h'] ...
118 + //
119 + // If the objective is main.o, then new task should be
120 + //
121 + // file( 'main.o', ['main.c', 'some.h' ] ...
122 + prereqs = this.prereqs.slice(); // Get a copy to work with
123 + prereqs.unshift(src);
124 +
125 + // Prereq should be:
126 + // 1. an existing task
127 + // 2. an existing file on disk
128 + // 3. a valid rule (i.e., not at too deep a level)
129 + valid = prereqs.some(function (p) {
130 + let ns = self.ns;
131 + return ns.resolveTask(p) ||
132 + fs.existsSync(Task.getBaseTaskName(p)) ||
133 + jake.attemptRule(p, ns, level + 1);
134 + });
135 +
136 + // If any of the prereqs aren't valid, the rule isn't valid
137 + if (!valid) {
138 + return null;
139 + }
140 + // Otherwise, hunky-dory, finish creating the task for the rule
141 + else {
142 + // Create the action for the task
143 + action = function () {
144 + let task = this;
145 + self.action.apply(task);
146 + };
147 +
148 + opts = this.opts;
149 +
150 + // Insert the file task into Jake
151 + //
152 + // Since createTask function stores the task as a child task
153 + // of currentNamespace. Here we temporariliy switch the namespace.
154 + // FIXME: Should allow optional ns passed in instead of this hack
155 + tNs = jake.currentNamespace;
156 + jake.currentNamespace = ns;
157 + createdTask = jake.createTask('file', name, prereqs, action, opts);
158 + createdTask.source = src.split(':').pop();
159 + jake.currentNamespace = tNs;
160 +
161 + return createdTask;
162 + }
163 + }
164 +
165 + match(name) {
166 + return Rule.match(this.pattern, name);
167 + }
168 +
169 + // Test wether the a prerequisite matchs the pattern.
170 + // The arg 'pattern' does not have namespace as prefix.
171 + // For example, the following tests are true
172 + //
173 + // pattern | name
174 + // bin/%.o | bin/main.o
175 + // bin/%.o | foo:bin/main.o
176 + //
177 + // The following tests are false (trivally)
178 + //
179 + // pattern | name
180 + // bin/%.o | foobin/main.o
181 + // bin/%.o | bin/main.oo
182 + static match(pattern, name) {
183 + let p;
184 + let task;
185 + let obj;
186 + let filename;
187 +
188 + if (pattern instanceof RegExp) {
189 + return pattern.test(name);
190 + }
191 + else if (pattern.indexOf('%') == -1) {
192 + // No Pattern. No Folder. No Namespace.
193 + // A Simple Suffix Rule. Just test suffix
194 + return stringEndWith(pattern, name);
195 + }
196 + else {
197 + // Resolve the dir, prefix and suffix of pattern
198 + p = resolve(pattern);
199 +
200 + // Resolve the namespace and task-name
201 + task = splitNs(name);
202 + name = task.name;
203 +
204 + // Set the objective as the task-name
205 + obj = name;
206 +
207 + // Namespace is already matched.
208 +
209 + // Check dir
210 + if (path.dirname(obj) != p.dir) {
211 + return false;
212 + }
213 +
214 + filename = path.basename(obj);
215 +
216 + // Check file name length
217 + if ((p.prefix.length + p.suffix.length + 1) > filename.length) {
218 + // Length does not match.
219 + return false;
220 + }
221 +
222 + // Check prefix
223 + if (filename.indexOf(p.prefix) !== 0) {
224 + return false;
225 + }
226 +
227 + // Check suffix
228 + if (!stringEndWith(p.suffix, filename)) {
229 + return false;
230 + }
231 +
232 + // OK. Find a match.
233 + return true;
234 + }
235 + }
236 +
237 + // Generate the source based on
238 + // - name name for the synthesized task
239 + // - pattern pattern for the objective
240 + // - source pattern for the source
241 + //
242 + // Return the source with properties
243 + // - dep the prerequisite of source
244 + // (with the namespace)
245 + //
246 + // - file the file name of source
247 + // (without the namespace)
248 + //
249 + // For example, given
250 + //
251 + // - name foo:bin/main.o
252 + // - pattern bin/%.o
253 + // - source src/%.c
254 + //
255 + // return 'foo:src/main.c',
256 + //
257 + static getSource(name, pattern, source) {
258 + let dep;
259 + let pat;
260 + let match;
261 + let file;
262 + let src;
263 +
264 + // Regex pattern -- use to look up the extension
265 + if (pattern instanceof RegExp) {
266 + match = pattern.exec(name);
267 + if (match) {
268 + if (typeof source == 'function') {
269 + src = source(name);
270 + }
271 + else {
272 + src = stringReplaceSuffix(name, match[0], source);
273 + }
274 + }
275 + }
276 + // Assume string
277 + else {
278 + // Simple string suffix replacement
279 + if (pattern.indexOf('%') == -1) {
280 + if (typeof source == 'function') {
281 + src = source(name);
282 + }
283 + else {
284 + src = stringReplaceSuffix(name, pattern, source);
285 + }
286 + }
287 + // Percent-based substitution
288 + else {
289 + pat = pattern.replace('%', '(.*?)');
290 + pat = new RegExp(pat);
291 + match = pat.exec(name);
292 + if (match) {
293 + if (typeof source == 'function') {
294 + src = source(name);
295 + }
296 + else {
297 + file = match[1];
298 + file = source.replace('%', file);
299 + dep = match[0];
300 + src = name.replace(dep, file);
301 + }
302 + }
303 + }
304 + }
305 +
306 + return src;
307 + }
308 +}
309 +
310 +
311 +exports.Rule = Rule;
1 +let fs = require('fs');
2 +let FileTask = require('./file_task').FileTask;
3 +
4 +/**
5 + @name jake
6 + @namespace jake
7 +*/
8 +/**
9 + @name jake.DirectoryTask
10 + @constructor
11 + @augments EventEmitter
12 + @augments jake.Task
13 + @augments jake.FileTask
14 + @description A Jake DirectoryTask
15 +
16 + @param {String} name The name of the directory to create.
17 + */
18 +class DirectoryTask extends FileTask {
19 + constructor(...args) {
20 + super(...args);
21 + if (fs.existsSync(this.name)) {
22 + this.updateModTime();
23 + }
24 + else {
25 + this.modTime = null;
26 + }
27 + }
28 +}
29 +
30 +exports.DirectoryTask = DirectoryTask;
1 +let fs = require('fs');
2 +let Task = require('./task').Task;
3 +
4 +function isFileOrDirectory(t) {
5 + return (t instanceof FileTask ||
6 + t instanceof DirectoryTask);
7 +}
8 +
9 +function isFile(t) {
10 + return (t instanceof FileTask && !(t instanceof DirectoryTask));
11 +}
12 +
13 +/**
14 + @name jake
15 + @namespace jake
16 +*/
17 +/**
18 + @name jake.FileTask
19 + @class`
20 + @extentds Task
21 + @description A Jake FileTask
22 +
23 + @param {String} name The name of the Task
24 + @param {Array} [prereqs] Prerequisites to be run before this task
25 + @param {Function} [action] The action to perform to create this file
26 + @param {Object} [opts]
27 + @param {Array} [opts.asyc=false] Perform this task asynchronously.
28 + If you flag a task with this option, you must call the global
29 + `complete` method inside the task's action, for execution to proceed
30 + to the next task.
31 + */
32 +class FileTask extends Task {
33 + constructor(...args) {
34 + super(...args);
35 + this.dummy = false;
36 + if (fs.existsSync(this.name)) {
37 + this.updateModTime();
38 + }
39 + else {
40 + this.modTime = null;
41 + }
42 + }
43 +
44 + isNeeded() {
45 + let prereqs = this.prereqs;
46 + let prereqName;
47 + let prereqTask;
48 +
49 + // No repeatsies
50 + if (this.taskStatus == Task.runStatuses.DONE) {
51 + return false;
52 + }
53 + // The always-make override
54 + else if (jake.program.opts['always-make']) {
55 + return true;
56 + }
57 + // Default case
58 + else {
59 +
60 + // We need either an existing file, or an action to create one.
61 + // First try grabbing the actual mod-time of the file
62 + try {
63 + this.updateModTime();
64 + }
65 + // Then fall back to looking for an action
66 + catch(e) {
67 + if (typeof this.action == 'function') {
68 + return true;
69 + }
70 + else {
71 + throw new Error('File-task ' + this.fullName + ' has no ' +
72 + 'existing file, and no action to create one.');
73 + }
74 + }
75 +
76 + // Compare mod-time of all the prereqs with its mod-time
77 + // If any prereqs are newer, need to run the action to update
78 + if (prereqs && prereqs.length) {
79 + for (let i = 0, ii = prereqs.length; i < ii; i++) {
80 + prereqName = prereqs[i];
81 + prereqTask = this.namespace.resolveTask(prereqName) ||
82 + jake.createPlaceholderFileTask(prereqName, this.namespace);
83 + // Run the action if:
84 + // 1. The prereq is a normal task (not file/dir)
85 + // 2. The prereq is a file-task with a mod-date more recent than
86 + // the one for this file/dir
87 + if (prereqTask) {
88 + if (!isFileOrDirectory(prereqTask) ||
89 + (isFile(prereqTask) && prereqTask.modTime > this.modTime)) {
90 + return true;
91 + }
92 + }
93 + }
94 + }
95 + // File/dir has no prereqs, and exists -- no need to run
96 + else {
97 + // Effectively done
98 + this.taskStatus = Task.runStatuses.DONE;
99 + return false;
100 + }
101 + }
102 + }
103 +
104 + updateModTime() {
105 + let stats = fs.statSync(this.name);
106 + this.modTime = stats.mtime;
107 + }
108 +
109 + complete() {
110 + if (!this.dummy) {
111 + this.updateModTime();
112 + }
113 + // Hackity hack
114 + Task.prototype.complete.apply(this, arguments);
115 + }
116 +
117 +}
118 +
119 +exports.FileTask = FileTask;
120 +
121 +// DirectoryTask is a subclass of FileTask, depends on it
122 +// being defined
123 +let DirectoryTask = require('./directory_task').DirectoryTask;
124 +
1 +
2 +let Task = require('./task').Task;
3 +let FileTask = require('./file_task').FileTask;
4 +let DirectoryTask = require('./directory_task').DirectoryTask;
5 +
6 +exports.Task = Task;
7 +exports.FileTask = FileTask;
8 +exports.DirectoryTask = DirectoryTask;
9 +
1 +let EventEmitter = require('events').EventEmitter;
2 +let async = require('async');
3 +let chalk = require('chalk');
4 +// 'rule' module is required at the bottom because circular deps
5 +
6 +// Used for task value, so better not to use
7 +// null, since value should be unset/uninitialized
8 +let UNDEFINED_VALUE;
9 +
10 +const ROOT_TASK_NAME = '__rootTask__';
11 +const POLLING_INTERVAL = 100;
12 +
13 +// Parse any positional args attached to the task-name
14 +function parsePrereqName(name) {
15 + let taskArr = name.split('[');
16 + let taskName = taskArr[0];
17 + let taskArgs = [];
18 + if (taskArr[1]) {
19 + taskArgs = taskArr[1].replace(/\]$/, '');
20 + taskArgs = taskArgs.split(',');
21 + }
22 + return {
23 + name: taskName,
24 + args: taskArgs
25 + };
26 +}
27 +
28 +/**
29 + @name jake.Task
30 + @class
31 + @extends EventEmitter
32 + @description A Jake Task
33 +
34 + @param {String} name The name of the Task
35 + @param {Array} [prereqs] Prerequisites to be run before this task
36 + @param {Function} [action] The action to perform for this task
37 + @param {Object} [opts]
38 + @param {Array} [opts.asyc=false] Perform this task asynchronously.
39 + If you flag a task with this option, you must call the global
40 + `complete` method inside the task's action, for execution to proceed
41 + to the next task.
42 + */
43 +class Task extends EventEmitter {
44 +
45 + constructor(name, prereqs, action, options) {
46 + // EventEmitter ctor takes no args
47 + super();
48 +
49 + if (name.indexOf(':') > -1) {
50 + throw new Error('Task name cannot include a colon. It is used internally as namespace delimiter.');
51 + }
52 + let opts = options || {};
53 +
54 + this._currentPrereqIndex = 0;
55 + this._internal = false;
56 + this._skipped = false;
57 +
58 + this.name = name;
59 + this.prereqs = prereqs;
60 + this.action = action;
61 + this.async = false;
62 + this.taskStatus = Task.runStatuses.UNSTARTED;
63 + this.description = null;
64 + this.args = [];
65 + this.value = UNDEFINED_VALUE;
66 + this.concurrency = 1;
67 + this.startTime = null;
68 + this.endTime = null;
69 + this.directory = null;
70 + this.namespace = null;
71 +
72 + // Support legacy async-flag -- if not explicitly passed or falsy, will
73 + // be set to empty-object
74 + if (typeof opts == 'boolean' && opts === true) {
75 + this.async = true;
76 + }
77 + else {
78 + if (opts.async) {
79 + this.async = true;
80 + }
81 + if (opts.concurrency) {
82 + this.concurrency = opts.concurrency;
83 + }
84 + }
85 +
86 + //Do a test on self dependencies for this task
87 + if(Array.isArray(this.prereqs) && this.prereqs.indexOf(this.name) !== -1) {
88 + throw new Error("Cannot use prereq " + this.name + " as a dependency of itself");
89 + }
90 + }
91 +
92 + get fullName() {
93 + return this._getFullName();
94 + }
95 +
96 + get params() {
97 + return this._getParams();
98 + }
99 +
100 + _initInvocationChain() {
101 + // Legacy global invocation chain
102 + jake._invocationChain.push(this);
103 +
104 + // New root chain
105 + if (!this._invocationChain) {
106 + this._invocationChainRoot = true;
107 + this._invocationChain = [];
108 + if (jake.currentRunningTask) {
109 + jake.currentRunningTask._waitForChains = jake.currentRunningTask._waitForChains || [];
110 + jake.currentRunningTask._waitForChains.push(this._invocationChain);
111 + }
112 + }
113 + }
114 +
115 + /**
116 + @name jake.Task#invoke
117 + @function
118 + @description Runs prerequisites, then this task. If the task has already
119 + been run, will not run the task again.
120 + */
121 + invoke() {
122 + this._initInvocationChain();
123 +
124 + this.args = Array.prototype.slice.call(arguments);
125 + this.reenabled = false
126 + this.runPrereqs();
127 + }
128 +
129 + /**
130 + @name jake.Task#execute
131 + @function
132 + @description Run only this task, without prereqs. If the task has already
133 + been run, *will* run the task again.
134 + */
135 + execute() {
136 + this._initInvocationChain();
137 +
138 + this.args = Array.prototype.slice.call(arguments);
139 + this.reenable();
140 + this.reenabled = true
141 + this.run();
142 + }
143 +
144 + runPrereqs() {
145 + if (this.prereqs && this.prereqs.length) {
146 +
147 + if (this.concurrency > 1) {
148 + async.eachLimit(this.prereqs, this.concurrency,
149 +
150 + (name, cb) => {
151 + let parsed = parsePrereqName(name);
152 +
153 + let prereq = this.namespace.resolveTask(parsed.name) ||
154 + jake.attemptRule(name, this.namespace, 0) ||
155 + jake.createPlaceholderFileTask(name, this.namespace);
156 +
157 + if (!prereq) {
158 + throw new Error('Unknown task "' + name + '"');
159 + }
160 +
161 + //Test for circular invocation
162 + if(prereq === this) {
163 + setImmediate(function () {
164 + cb(new Error("Cannot use prereq " + prereq.name + " as a dependency of itself"));
165 + });
166 + }
167 +
168 + if (prereq.taskStatus == Task.runStatuses.DONE) {
169 + //prereq already done, return
170 + setImmediate(cb);
171 + }
172 + else {
173 + //wait for complete before calling cb
174 + prereq.once('_done', () => {
175 + prereq.removeAllListeners('_done');
176 + setImmediate(cb);
177 + });
178 + // Start the prereq if we are the first to encounter it
179 + if (prereq.taskStatus === Task.runStatuses.UNSTARTED) {
180 + prereq.taskStatus = Task.runStatuses.STARTED;
181 + prereq.invoke.apply(prereq, parsed.args);
182 + }
183 + }
184 + },
185 +
186 + (err) => {
187 + //async callback is called after all prereqs have run.
188 + if (err) {
189 + throw err;
190 + }
191 + else {
192 + setImmediate(this.run.bind(this));
193 + }
194 + }
195 + );
196 + }
197 + else {
198 + setImmediate(this.nextPrereq.bind(this));
199 + }
200 + }
201 + else {
202 + setImmediate(this.run.bind(this));
203 + }
204 + }
205 +
206 + nextPrereq() {
207 + let self = this;
208 + let index = this._currentPrereqIndex;
209 + let name = this.prereqs[index];
210 + let prereq;
211 + let parsed;
212 +
213 + if (name) {
214 +
215 + parsed = parsePrereqName(name);
216 +
217 + prereq = this.namespace.resolveTask(parsed.name) ||
218 + jake.attemptRule(name, this.namespace, 0) ||
219 + jake.createPlaceholderFileTask(name, this.namespace);
220 +
221 + if (!prereq) {
222 + throw new Error('Unknown task "' + name + '"');
223 + }
224 +
225 + // Do when done
226 + if (prereq.taskStatus == Task.runStatuses.DONE) {
227 + self.handlePrereqDone(prereq);
228 + }
229 + else {
230 + prereq.once('_done', () => {
231 + this.handlePrereqDone(prereq);
232 + prereq.removeAllListeners('_done');
233 + });
234 + if (prereq.taskStatus == Task.runStatuses.UNSTARTED) {
235 + prereq.taskStatus = Task.runStatuses.STARTED;
236 + prereq._invocationChain = this._invocationChain;
237 + prereq.invoke.apply(prereq, parsed.args);
238 + }
239 + }
240 + }
241 + }
242 +
243 + /**
244 + @name jake.Task#reenable
245 + @function
246 + @description Reenables a task so that it can be run again.
247 + */
248 + reenable(deep) {
249 + let prereqs;
250 + let prereq;
251 + this._skipped = false;
252 + this.taskStatus = Task.runStatuses.UNSTARTED;
253 + this.value = UNDEFINED_VALUE;
254 + if (deep && this.prereqs) {
255 + prereqs = this.prereqs;
256 + for (let i = 0, ii = prereqs.length; i < ii; i++) {
257 + prereq = jake.Task[prereqs[i]];
258 + if (prereq) {
259 + prereq.reenable(deep);
260 + }
261 + }
262 + }
263 + }
264 +
265 + handlePrereqDone(prereq) {
266 + this._currentPrereqIndex++;
267 + if (this._currentPrereqIndex < this.prereqs.length) {
268 + setImmediate(this.nextPrereq.bind(this));
269 + }
270 + else {
271 + setImmediate(this.run.bind(this));
272 + }
273 + }
274 +
275 + isNeeded() {
276 + let needed = true;
277 + if (this.taskStatus == Task.runStatuses.DONE) {
278 + needed = false;
279 + }
280 + return needed;
281 + }
282 +
283 + run() {
284 + let val, previous;
285 + let hasAction = typeof this.action == 'function';
286 +
287 + if (!this.isNeeded()) {
288 + this.emit('skip');
289 + this.emit('_done');
290 + }
291 + else {
292 + if (this._invocationChain.length) {
293 + previous = this._invocationChain[this._invocationChain.length - 1];
294 + // 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
295 + if (!(this.reenabled && previous == this)) {
296 + if (previous.taskStatus != Task.runStatuses.DONE) {
297 + let now = (new Date()).getTime();
298 + if (now - this.startTime > jake._taskTimeout) {
299 + return jake.fail(`Timed out waiting for task: ${previous.name} with status of ${previous.taskStatus}`);
300 + }
301 + setTimeout(this.run.bind(this), POLLING_INTERVAL);
302 + return;
303 + }
304 + }
305 + }
306 + if (!(this.reenabled && previous == this)) {
307 + this._invocationChain.push(this);
308 + }
309 +
310 + if (!(this._internal || jake.program.opts.quiet)) {
311 + console.log("Starting '" + chalk.green(this.fullName) + "'...");
312 + }
313 +
314 + this.startTime = (new Date()).getTime();
315 + this.emit('start');
316 +
317 + jake.currentRunningTask = this;
318 +
319 + if (hasAction) {
320 + try {
321 + if (this.directory) {
322 + process.chdir(this.directory);
323 + }
324 +
325 + val = this.action.apply(this, this.args);
326 +
327 + if (typeof val == 'object' && typeof val.then == 'function') {
328 + this.async = true;
329 +
330 + val.then(
331 + (result) => {
332 + setImmediate(() => {
333 + this.complete(result);
334 + });
335 + },
336 + (err) => {
337 + setImmediate(() => {
338 + this.errorOut(err);
339 + });
340 + });
341 + }
342 + }
343 + catch (err) {
344 + this.errorOut(err);
345 + return; // Bail out, not complete
346 + }
347 + }
348 +
349 + if (!(hasAction && this.async)) {
350 + setImmediate(() => {
351 + this.complete(val);
352 + });
353 + }
354 + }
355 + }
356 +
357 + errorOut(err) {
358 + this.taskStatus = Task.runStatuses.ERROR;
359 + this._invocationChain.chainStatus = Task.runStatuses.ERROR;
360 + this.emit('error', err);
361 + }
362 +
363 + complete(val) {
364 +
365 + if (Array.isArray(this._waitForChains)) {
366 + let stillWaiting = this._waitForChains.some((chain) => {
367 + return !(chain.chainStatus == Task.runStatuses.DONE ||
368 + chain.chainStatus == Task.runStatuses.ERROR);
369 + });
370 + if (stillWaiting) {
371 + let now = (new Date()).getTime();
372 + let elapsed = now - this.startTime;
373 + if (elapsed > jake._taskTimeout) {
374 + return jake.fail(`Timed out waiting for task: ${this.name} with status of ${this.taskStatus}. Elapsed: ${elapsed}`);
375 + }
376 + setTimeout(() => {
377 + this.complete(val);
378 + }, POLLING_INTERVAL);
379 + return;
380 + }
381 + }
382 +
383 + jake._invocationChain.splice(jake._invocationChain.indexOf(this), 1);
384 +
385 + if (this._invocationChainRoot) {
386 + this._invocationChain.chainStatus = Task.runStatuses.DONE;
387 + }
388 +
389 + this._currentPrereqIndex = 0;
390 +
391 + // If 'complete' getting called because task has been
392 + // run already, value will not be passed -- leave in place
393 + if (!this._skipped) {
394 + this.taskStatus = Task.runStatuses.DONE;
395 + this.value = val;
396 +
397 + this.emit('complete', this.value);
398 + this.emit('_done');
399 +
400 + this.endTime = (new Date()).getTime();
401 + let taskTime = this.endTime - this.startTime;
402 +
403 + if (!(this._internal || jake.program.opts.quiet)) {
404 + console.log("Finished '" + chalk.green(this.fullName) + "' after " + chalk.magenta(taskTime + ' ms'));
405 + }
406 +
407 + }
408 + }
409 +
410 + _getFullName() {
411 + let ns = this.namespace;
412 + let path = (ns && ns.path) || '';
413 + path = (path && path.split(':')) || [];
414 + if (this.namespace !== jake.defaultNamespace) {
415 + path.push(this.namespace.name);
416 + }
417 + path.push(this.name);
418 + return path.join(':');
419 + }
420 +
421 + _getParams() {
422 + if (!this.action) return "";
423 + let params = new RegExp('(?:'+this.action.name+'\\s*|^)\\s*\\((.*?)\\)').exec(this.action.toString().replace(/\n/g, ''))[1].replace(/\/\*.*?\*\//g, '').replace(/ /g, '');
424 + return params;
425 + }
426 +
427 + static getBaseNamespacePath(fullName) {
428 + return fullName.split(':').slice(0, -1).join(':');
429 + }
430 +
431 + static getBaseTaskName(fullName) {
432 + return fullName.split(':').pop();
433 + }
434 +}
435 +
436 +Task.runStatuses = {
437 + UNSTARTED: 'unstarted',
438 + DONE: 'done',
439 + STARTED: 'started',
440 + ERROR: 'error'
441 +};
442 +
443 +Task.ROOT_TASK_NAME = ROOT_TASK_NAME;
444 +
445 +exports.Task = Task;
446 +
447 +// Required here because circular deps
448 +require('../rule');
449 +
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +let path = require('path');
20 +let currDir = process.cwd();
21 +
22 +/**
23 + @name jake
24 + @namespace jake
25 +*/
26 +/**
27 + @name jake.TestTask
28 + @constructor
29 + @description Instantiating a TestTask creates a number of Jake
30 + Tasks that make running tests for your software easy.
31 +
32 + @param {String} name The name of the project
33 + @param {Function} definition Defines the list of files containing the tests,
34 + and the name of the namespace/task for running them. Will be executed on the
35 + instantiated TestTask (i.e., 'this', will be the TestTask instance), to set
36 + the various instance-propertiess.
37 +
38 + @example
39 + let t = new jake.TestTask('bij-js', function () {
40 + this.testName = 'testSpecial';
41 + this.testFiles.include('test/**');
42 + });
43 +
44 + */
45 +let TestTask = function () {
46 + let self = this;
47 + let args = Array.prototype.slice.call(arguments);
48 + let name = args.shift();
49 + let definition = args.pop();
50 + let prereqs = args.pop() || [];
51 +
52 + /**
53 + @name jake.TestTask#testNam
54 + @public
55 + @type {String}
56 + @description The name of the namespace to place the tests in, and
57 + the top-level task for running tests. Defaults to "test"
58 + */
59 + this.testName = 'test';
60 +
61 + /**
62 + @name jake.TestTask#testFiles
63 + @public
64 + @type {jake.FileList}
65 + @description The list of files containing tests to load
66 + */
67 + this.testFiles = new jake.FileList();
68 +
69 + /**
70 + @name jake.TestTask#showDescription
71 + @public
72 + @type {Boolean}
73 + @description Show the created task when doing Jake -T
74 + */
75 + this.showDescription = true;
76 +
77 + /*
78 + @name jake.TestTask#totalTests
79 + @public
80 + @type {Number}
81 + @description The total number of tests to run
82 + */
83 + this.totalTests = 0;
84 +
85 + /*
86 + @name jake.TestTask#executedTests
87 + @public
88 + @type {Number}
89 + @description The number of tests successfully run
90 + */
91 + this.executedTests = 0;
92 +
93 + if (typeof definition == 'function') {
94 + definition.call(this);
95 + }
96 +
97 + if (this.showDescription) {
98 + desc('Run the tests for ' + name);
99 + }
100 +
101 + task(this.testName, prereqs, {async: true}, function () {
102 + let t = jake.Task[this.fullName + ':run'];
103 + t.on('complete', function () {
104 + complete();
105 + });
106 + // Pass args to the namespaced test
107 + t.invoke.apply(t, arguments);
108 + });
109 +
110 + namespace(self.testName, function () {
111 +
112 + let runTask = task('run', {async: true}, function (pat) {
113 + let re;
114 + let testFiles;
115 +
116 + // Don't nest; make a top-level namespace. Don't want
117 + // re-calling from inside to nest infinitely
118 + jake.currentNamespace = jake.defaultNamespace;
119 +
120 + re = new RegExp(pat);
121 + // Get test files that match the passed-in pattern
122 + testFiles = self.testFiles.toArray()
123 + .filter(function (f) {
124 + return (re).test(f);
125 + }) // Don't load the same file multiple times -- should this be in FileList?
126 + .reduce(function (p, c) {
127 + if (p.indexOf(c) < 0) {
128 + p.push(c);
129 + }
130 + return p;
131 + }, []);
132 +
133 + // Create a namespace for all the testing tasks to live in
134 + namespace(self.testName + 'Exec', function () {
135 + // Each test will be a prereq for the dummy top-level task
136 + let prereqs = [];
137 + // Continuation to pass to the async tests, wrapping `continune`
138 + let next = function () {
139 + complete();
140 + };
141 + // Create the task for this test-function
142 + let createTask = function (name, action) {
143 + // If the test-function is defined with a continuation
144 + // param, flag the task as async
145 + let t;
146 + let isAsync = !!action.length;
147 +
148 + // Define the actual namespaced task with the name, the
149 + // wrapped action, and the correc async-flag
150 + t = task(name, createAction(name, action), {
151 + async: isAsync
152 + });
153 + t.once('complete', function () {
154 + self.executedTests++;
155 + });
156 + t._internal = true;
157 + return t;
158 + };
159 + // Used as the action for the defined task for each test.
160 + let createAction = function (n, a) {
161 + // A wrapped function that passes in the `next` function
162 + // for any tasks that run asynchronously
163 + return function () {
164 + let cb;
165 + if (a.length) {
166 + cb = next;
167 + }
168 + if (!(n == 'before' || n == 'after' ||
169 + /_beforeEach$/.test(n) || /_afterEach$/.test(n))) {
170 + jake.logger.log(n);
171 + }
172 + // 'this' will be the task when action is run
173 + return a.call(this, cb);
174 + };
175 + };
176 + // Dummy top-level task for everything to be prereqs for
177 + let topLevel;
178 +
179 + // Pull in each test-file, and iterate over any exported
180 + // test-functions. Register each test-function as a prereq task
181 + testFiles.forEach(function (file) {
182 + let exp = require(path.join(currDir, file));
183 +
184 + // Create a namespace for each filename, so test-name collisions
185 + // won't be a problem
186 + namespace(file, function () {
187 + let testPrefix = self.testName + 'Exec:' + file + ':';
188 + let testName;
189 + // Dummy task for displaying file banner
190 + testName = '*** Running ' + file + ' ***';
191 + prereqs.push(testPrefix + testName);
192 + createTask(testName, function () {});
193 +
194 + // 'before' setup
195 + if (typeof exp.before == 'function') {
196 + prereqs.push(testPrefix + 'before');
197 + // Create the task
198 + createTask('before', exp.before);
199 + }
200 +
201 + // Walk each exported function, and create a task for each
202 + for (let p in exp) {
203 + if (p == 'before' || p == 'after' ||
204 + p == 'beforeEach' || p == 'afterEach') {
205 + continue;
206 + }
207 +
208 + if (typeof exp.beforeEach == 'function') {
209 + prereqs.push(testPrefix + p + '_beforeEach');
210 + // Create the task
211 + createTask(p + '_beforeEach', exp.beforeEach);
212 + }
213 +
214 + // Add the namespace:name of this test to the list of prereqs
215 + // for the dummy top-level task
216 + prereqs.push(testPrefix + p);
217 + // Create the task
218 + createTask(p, exp[p]);
219 +
220 + if (typeof exp.afterEach == 'function') {
221 + prereqs.push(testPrefix + p + '_afterEach');
222 + // Create the task
223 + createTask(p + '_afterEach', exp.afterEach);
224 + }
225 + }
226 +
227 + // 'after' teardown
228 + if (typeof exp.after == 'function') {
229 + prereqs.push(testPrefix + 'after');
230 + // Create the task
231 + let afterTask = createTask('after', exp.after);
232 + afterTask._internal = true;
233 + }
234 +
235 + });
236 + });
237 +
238 + self.totalTests = prereqs.length;
239 + process.on('exit', function () {
240 + // Throw in the case where the process exits without
241 + // finishing tests, but no error was thrown
242 + if (!jake.errorCode && (self.totalTests > self.executedTests)) {
243 + throw new Error('Process exited without all tests completing.');
244 + }
245 + });
246 +
247 + // Create the dummy top-level task. When calling a task internally
248 + // with `invoke` that is async (or has async prereqs), have to listen
249 + // for the 'complete' event to know when it's done
250 + topLevel = task('__top__', prereqs);
251 + topLevel._internal = true;
252 + topLevel.addListener('complete', function () {
253 + jake.logger.log('All tests ran successfully');
254 + complete();
255 + });
256 +
257 + topLevel.invoke(); // Do the thing!
258 + });
259 +
260 + });
261 + runTask._internal = true;
262 +
263 + });
264 +
265 +
266 +};
267 +
268 +jake.TestTask = TestTask;
269 +exports.TestTask = TestTask;
270 +
1 +/*
2 + * Utilities: A classic collection of JavaScript utilities
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +let fs = require('fs');
20 +let path = require('path');
21 +
22 +/**
23 + @name file
24 + @namespace file
25 +*/
26 +
27 +let fileUtils = new (function () {
28 +
29 + // Recursively copy files and directories
30 + let _copyFile = function (fromPath, toPath, opts) {
31 + let from = path.normalize(fromPath)
32 + let to = path.normalize(toPath)
33 + let options = opts || {}
34 + let fromStat;
35 + let toStat;
36 + let destExists;
37 + let destDoesNotExistErr;
38 + let content;
39 + let filename;
40 + let dirContents;
41 + let targetDir;
42 +
43 + fromStat = fs.statSync(from);
44 +
45 + try {
46 + //console.dir(to + ' destExists');
47 + toStat = fs.statSync(to);
48 + destExists = true;
49 + }
50 + catch(e) {
51 + //console.dir(to + ' does not exist');
52 + destDoesNotExistErr = e;
53 + destExists = false;
54 + }
55 + // Destination dir or file exists, copy into (directory)
56 + // or overwrite (file)
57 + if (destExists) {
58 +
59 + // If there's a rename-via-copy file/dir name passed, use it.
60 + // Otherwise use the actual file/dir name
61 + filename = options.rename || path.basename(from);
62 +
63 + // Copying a directory
64 + if (fromStat.isDirectory()) {
65 + dirContents = fs.readdirSync(from);
66 + targetDir = path.join(to, filename);
67 + // We don't care if the target dir already exists
68 + try {
69 + fs.mkdirSync(targetDir, {mode: fromStat.mode & 0o777});
70 + }
71 + catch(e) {
72 + if (e.code !== 'EEXIST') {
73 + throw e;
74 + }
75 + }
76 + for (let i = 0, ii = dirContents.length; i < ii; i++) {
77 + _copyFile(path.join(from, dirContents[i]), targetDir, {preserveMode: options.preserveMode});
78 + }
79 + }
80 + // Copying a file
81 + else {
82 + content = fs.readFileSync(from);
83 + let mode = fromStat.mode & 0o777;
84 + let targetFile = to;
85 +
86 + if (toStat.isDirectory()) {
87 + targetFile = path.join(to, filename);
88 + }
89 +
90 + let fileExists = fs.existsSync(targetFile);
91 + fs.writeFileSync(targetFile, content);
92 +
93 + // If the file didn't already exist, use the original file mode.
94 + // Otherwise, only update the mode if preserverMode is true.
95 + if(!fileExists || options.preserveMode) {
96 + fs.chmodSync(targetFile, mode);
97 + }
98 + }
99 + }
100 + // Dest doesn't exist, can't create it
101 + else {
102 + throw destDoesNotExistErr;
103 + }
104 + };
105 +
106 + // Remove the given directory
107 + let _rmDir = function (dirPath) {
108 + let dir = path.normalize(dirPath);
109 + let paths = [];
110 + paths = fs.readdirSync(dir);
111 + paths.forEach(function (p) {
112 + let curr = path.join(dir, p);
113 + let stat = fs.lstatSync(curr);
114 + if (stat.isDirectory()) {
115 + _rmDir(curr);
116 + }
117 + else {
118 + try {
119 + fs.unlinkSync(curr);
120 + } catch(e) {
121 + if (e.code === 'EPERM') {
122 + fs.chmodSync(curr, parseInt(666, 8));
123 + fs.unlinkSync(curr);
124 + } else {
125 + throw e;
126 + }
127 + }
128 + }
129 + });
130 + fs.rmdirSync(dir);
131 + };
132 +
133 + /**
134 + @name file#cpR
135 + @public
136 + @function
137 + @description Copies a directory/file to a destination
138 + @param {String} fromPath The source path to copy from
139 + @param {String} toPath The destination path to copy to
140 + @param {Object} opts Options to use
141 + @param {Boolean} [opts.preserveMode] If target file already exists, this
142 + determines whether the original file's mode is copied over. The default of
143 + false mimics the behavior of the `cp` command line tool. (Default: false)
144 + */
145 + this.cpR = function (fromPath, toPath, options) {
146 + let from = path.normalize(fromPath);
147 + let to = path.normalize(toPath);
148 + let toStat;
149 + let doesNotExistErr;
150 + let filename;
151 + let opts = options || {};
152 +
153 + if (from == to) {
154 + throw new Error('Cannot copy ' + from + ' to itself.');
155 + }
156 +
157 + // Handle rename-via-copy
158 + try {
159 + toStat = fs.statSync(to);
160 + }
161 + catch(e) {
162 + doesNotExistErr = e;
163 +
164 + // Get abs path so it's possible to check parent dir
165 + if (!this.isAbsolute(to)) {
166 + to = path.join(process.cwd(), to);
167 + }
168 +
169 + // Save the file/dir name
170 + filename = path.basename(to);
171 + // See if a parent dir exists, so there's a place to put the
172 + /// renamed file/dir (resets the destination for the copy)
173 + to = path.dirname(to);
174 + try {
175 + toStat = fs.statSync(to);
176 + }
177 + catch(e) {}
178 + if (toStat && toStat.isDirectory()) {
179 + // Set the rename opt to pass to the copy func, will be used
180 + // as the new file/dir name
181 + opts.rename = filename;
182 + //console.log('filename ' + filename);
183 + }
184 + else {
185 + throw doesNotExistErr;
186 + }
187 + }
188 +
189 + _copyFile(from, to, opts);
190 + };
191 +
192 + /**
193 + @name file#mkdirP
194 + @public
195 + @function
196 + @description Create the given directory(ies) using the given mode permissions
197 + @param {String} dir The directory to create
198 + @param {Number} mode The mode to give the created directory(ies)(Default: 0755)
199 + */
200 + this.mkdirP = function (dir, mode) {
201 + let dirPath = path.normalize(dir);
202 + let paths = dirPath.split(/\/|\\/);
203 + let currPath = '';
204 + let next;
205 +
206 + if (paths[0] == '' || /^[A-Za-z]+:/.test(paths[0])) {
207 + currPath = paths.shift() || '/';
208 + currPath = path.join(currPath, paths.shift());
209 + //console.log('basedir');
210 + }
211 + while ((next = paths.shift())) {
212 + if (next == '..') {
213 + currPath = path.join(currPath, next);
214 + continue;
215 + }
216 + currPath = path.join(currPath, next);
217 + try {
218 + //console.log('making ' + currPath);
219 + fs.mkdirSync(currPath, mode || parseInt(755, 8));
220 + }
221 + catch(e) {
222 + if (e.code != 'EEXIST') {
223 + throw e;
224 + }
225 + }
226 + }
227 + };
228 +
229 + /**
230 + @name file#rmRf
231 + @public
232 + @function
233 + @description Deletes the given directory/file
234 + @param {String} p The path to delete, can be a directory or file
235 + */
236 + this.rmRf = function (p, options) {
237 + let stat;
238 + try {
239 + stat = fs.lstatSync(p);
240 + if (stat.isDirectory()) {
241 + _rmDir(p);
242 + }
243 + else {
244 + fs.unlinkSync(p);
245 + }
246 + }
247 + catch (e) {}
248 + };
249 +
250 + /**
251 + @name file#isAbsolute
252 + @public
253 + @function
254 + @return {Boolean/String} If it's absolute the first character is returned otherwise false
255 + @description Checks if a given path is absolute or relative
256 + @param {String} p Path to check
257 + */
258 + this.isAbsolute = function (p) {
259 + let match = /^[A-Za-z]+:\\|^\//.exec(p);
260 + if (match && match.length) {
261 + return match[0];
262 + }
263 + return false;
264 + };
265 +
266 + /**
267 + @name file#absolutize
268 + @public
269 + @function
270 + @return {String} Returns the absolute path for the given path
271 + @description Returns the absolute path for the given path
272 + @param {String} p The path to get the absolute path for
273 + */
274 + this.absolutize = function (p) {
275 + if (this.isAbsolute(p)) {
276 + return p;
277 + }
278 + else {
279 + return path.join(process.cwd(), p);
280 + }
281 + };
282 +
283 +})();
284 +
285 +module.exports = fileUtils;
286 +
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +
20 +let util = require('util'); // Native Node util module
21 +let spawn = require('child_process').spawn;
22 +let EventEmitter = require('events').EventEmitter;
23 +let logger = require('./logger');
24 +let file = require('./file');
25 +let Exec;
26 +
27 +const _UUID_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
28 +
29 +let parseArgs = function (argumentsObj) {
30 + let args;
31 + let arg;
32 + let cmds;
33 + let callback;
34 + let opts = {
35 + interactive: false,
36 + printStdout: false,
37 + printStderr: false,
38 + breakOnError: true
39 + };
40 +
41 + args = Array.prototype.slice.call(argumentsObj);
42 +
43 + cmds = args.shift();
44 + // Arrayize if passed a single string command
45 + if (typeof cmds == 'string') {
46 + cmds = [cmds];
47 + }
48 + // Make a copy if it's an actual list
49 + else {
50 + cmds = cmds.slice();
51 + }
52 +
53 + // Get optional callback or opts
54 + while((arg = args.shift())) {
55 + if (typeof arg == 'function') {
56 + callback = arg;
57 + }
58 + else if (typeof arg == 'object') {
59 + opts = Object.assign(opts, arg);
60 + }
61 + }
62 +
63 + // Backward-compat shim
64 + if (typeof opts.stdout != 'undefined') {
65 + opts.printStdout = opts.stdout;
66 + delete opts.stdout;
67 + }
68 + if (typeof opts.stderr != 'undefined') {
69 + opts.printStderr = opts.stderr;
70 + delete opts.stderr;
71 + }
72 +
73 + return {
74 + cmds: cmds,
75 + opts: opts,
76 + callback: callback
77 + };
78 +};
79 +
80 +/**
81 + @name jake
82 + @namespace jake
83 +*/
84 +let utils = new (function () {
85 + /**
86 + @name jake.exec
87 + @static
88 + @function
89 + @description Executes shell-commands asynchronously with an optional
90 + final callback.
91 + `
92 + @param {String[]} cmds The list of shell-commands to execute
93 + @param {Object} [opts]
94 + @param {Boolean} [opts.printStdout=false] Print stdout from each command
95 + @param {Boolean} [opts.printStderr=false] Print stderr from each command
96 + @param {Boolean} [opts.breakOnError=true] Stop further execution on
97 + the first error.
98 + @param {Boolean} [opts.windowsVerbatimArguments=false] Don't translate
99 + arguments on Windows.
100 + @param {Function} [callback] Callback to run after executing the
101 + commands
102 +
103 + @example
104 + let cmds = [
105 + 'echo "showing directories"'
106 + , 'ls -al | grep ^d'
107 + , 'echo "moving up a directory"'
108 + , 'cd ../'
109 + ]
110 + , callback = function () {
111 + console.log('Finished running commands.');
112 + }
113 + jake.exec(cmds, {stdout: true}, callback);
114 + */
115 + this.exec = function (a, b, c) {
116 + let parsed = parseArgs(arguments);
117 + let cmds = parsed.cmds;
118 + let opts = parsed.opts;
119 + let callback = parsed.callback;
120 +
121 + let ex = new Exec(cmds, opts, callback);
122 +
123 + ex.addListener('error', function (msg, code) {
124 + if (opts.breakOnError) {
125 + fail(msg, code);
126 + }
127 + });
128 + ex.run();
129 +
130 + return ex;
131 + };
132 +
133 + this.createExec = function (a, b, c) {
134 + return new Exec(a, b, c);
135 + };
136 +
137 + // From Math.uuid.js, https://github.com/broofa/node-uuid
138 + // Robert Kieffer (robert@broofa.com), MIT license
139 + this.uuid = function (length, radix) {
140 + var chars = _UUID_CHARS
141 + , uuid = []
142 + , r
143 + , i;
144 +
145 + radix = radix || chars.length;
146 +
147 + if (length) {
148 + // Compact form
149 + i = -1;
150 + while (++i < length) {
151 + uuid[i] = chars[0 | Math.random()*radix];
152 + }
153 + } else {
154 + // rfc4122, version 4 form
155 +
156 + // rfc4122 requires these characters
157 + uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
158 + uuid[14] = '4';
159 +
160 + // Fill in random data. At i==19 set the high bits of clock sequence as
161 + // per rfc4122, sec. 4.1.5
162 + i = -1;
163 + while (++i < 36) {
164 + if (!uuid[i]) {
165 + r = 0 | Math.random()*16;
166 + uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
167 + }
168 + }
169 + }
170 +
171 + return uuid.join('');
172 + };
173 +
174 +})();
175 +
176 +Exec = function () {
177 + let parsed = parseArgs(arguments);
178 + let cmds = parsed.cmds;
179 + let opts = parsed.opts;
180 + let callback = parsed.callback;
181 +
182 + this._cmds = cmds;
183 + this._callback = callback;
184 + this._config = opts;
185 +};
186 +
187 +util.inherits(Exec, EventEmitter);
188 +
189 +Object.assign(Exec.prototype, new (function () {
190 +
191 + let _run = function () {
192 + let self = this;
193 + let sh;
194 + let cmd;
195 + let args;
196 + let next = this._cmds.shift();
197 + let config = this._config;
198 + let errData = '';
199 + let shStdio;
200 + let handleStdoutData = function (data) {
201 + self.emit('stdout', data);
202 + };
203 + let handleStderrData = function (data) {
204 + let d = data.toString();
205 + self.emit('stderr', data);
206 + // Accumulate the error-data so we can use it as the
207 + // stack if the process exits with an error
208 + errData += d;
209 + };
210 +
211 + // Keep running as long as there are commands in the array
212 + if (next) {
213 + let spawnOpts = {};
214 + this.emit('cmdStart', next);
215 +
216 + // Ganking part of Node's child_process.exec to get cmdline args parsed
217 + if (process.platform == 'win32') {
218 + cmd = 'cmd';
219 + args = ['/c', next];
220 + if (config.windowsVerbatimArguments) {
221 + spawnOpts.windowsVerbatimArguments = true;
222 + }
223 + }
224 + else {
225 + cmd = '/bin/sh';
226 + args = ['-c', next];
227 + }
228 +
229 + if (config.interactive) {
230 + spawnOpts.stdio = 'inherit';
231 + sh = spawn(cmd, args, spawnOpts);
232 + }
233 + else {
234 + shStdio = [
235 + process.stdin
236 + ];
237 + if (config.printStdout) {
238 + shStdio.push(process.stdout);
239 + }
240 + else {
241 + shStdio.push('pipe');
242 + }
243 + if (config.printStderr) {
244 + shStdio.push(process.stderr);
245 + }
246 + else {
247 + shStdio.push('pipe');
248 + }
249 + spawnOpts.stdio = shStdio;
250 + sh = spawn(cmd, args, spawnOpts);
251 + if (!config.printStdout) {
252 + sh.stdout.addListener('data', handleStdoutData);
253 + }
254 + if (!config.printStderr) {
255 + sh.stderr.addListener('data', handleStderrData);
256 + }
257 + }
258 +
259 + // Exit, handle err or run next
260 + sh.on('exit', function (code) {
261 + let msg;
262 + if (code !== 0) {
263 + msg = errData || 'Process exited with error.';
264 + msg = msg.trim();
265 + self.emit('error', msg, code);
266 + }
267 + if (code === 0 || !config.breakOnError) {
268 + self.emit('cmdEnd', next);
269 + setTimeout(function () { _run.call(self); }, 0);
270 + }
271 + });
272 +
273 + }
274 + else {
275 + self.emit('end');
276 + if (typeof self._callback == 'function') {
277 + self._callback();
278 + }
279 + }
280 + };
281 +
282 + this.append = function (cmd) {
283 + this._cmds.push(cmd);
284 + };
285 +
286 + this.run = function () {
287 + _run.call(this);
288 + };
289 +
290 +})());
291 +
292 +utils.Exec = Exec;
293 +utils.file = file;
294 +utils.logger = logger;
295 +
296 +module.exports = utils;
297 +
1 +let util = require('util');
2 +
3 +let logger = new (function () {
4 + let _output = function (type, out) {
5 + let quiet = typeof jake != 'undefined' && jake.program &&
6 + jake.program.opts && jake.program.opts.quiet;
7 + let msg;
8 + if (!quiet) {
9 + msg = typeof out == 'string' ? out : util.inspect(out);
10 + console[type](msg);
11 + }
12 + };
13 +
14 + this.log = function (out) {
15 + _output('log', out);
16 + };
17 +
18 + this.error = function (out) {
19 + _output('error', out);
20 + };
21 +
22 +})();
23 +
24 +module.exports = logger;
1 +{
2 + "_from": "jake@^10.8.5",
3 + "_id": "jake@10.8.5",
4 + "_inBundle": false,
5 + "_integrity": "sha512-sVpxYeuAhWt0OTWITwT98oyV0GsXyMlXCF+3L1SuafBVUIr/uILGRB+NqwkzhgXKvoJpDIpQvqkUALgdmQsQxw==",
6 + "_location": "/jake",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "jake@^10.8.5",
12 + "name": "jake",
13 + "escapedName": "jake",
14 + "rawSpec": "^10.8.5",
15 + "saveSpec": null,
16 + "fetchSpec": "^10.8.5"
17 + },
18 + "_requiredBy": [
19 + "/ejs"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/jake/-/jake-10.8.5.tgz",
22 + "_shasum": "f2183d2c59382cb274226034543b9c03b8164c46",
23 + "_spec": "jake@^10.8.5",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\ejs",
25 + "author": {
26 + "name": "Matthew Eernisse",
27 + "email": "mde@fleegix.org",
28 + "url": "http://fleegix.org"
29 + },
30 + "bin": {
31 + "jake": "bin/cli.js"
32 + },
33 + "bugs": {
34 + "url": "https://github.com/jakejs/jake/issues"
35 + },
36 + "bundleDependencies": false,
37 + "dependencies": {
38 + "async": "^3.2.3",
39 + "chalk": "^4.0.2",
40 + "filelist": "^1.0.1",
41 + "minimatch": "^3.0.4"
42 + },
43 + "deprecated": false,
44 + "description": "JavaScript build tool, similar to Make or Rake",
45 + "devDependencies": {
46 + "eslint": "^6.8.0",
47 + "mocha": "^7.1.1",
48 + "q": "^1.5.1"
49 + },
50 + "engines": {
51 + "node": ">=10"
52 + },
53 + "homepage": "https://github.com/jakejs/jake#readme",
54 + "keywords": [
55 + "build",
56 + "cli",
57 + "make",
58 + "rake"
59 + ],
60 + "license": "Apache-2.0",
61 + "main": "./lib/jake.js",
62 + "name": "jake",
63 + "preferGlobal": true,
64 + "repository": {
65 + "type": "git",
66 + "url": "git://github.com/jakejs/jake.git"
67 + },
68 + "scripts": {
69 + "lint": "eslint --format codeframe \"lib/**/*.js\" \"test/**/*.js\"",
70 + "lint:fix": "eslint --fix \"lib/**/*.js\" \"test/**/*.js\"",
71 + "test": "./bin/cli.js test",
72 + "test:ci": "npm run lint && npm run test"
73 + },
74 + "version": "10.8.5"
75 +}
1 +let assert = require('assert');
2 +let exec = require('child_process').execSync;
3 +
4 +const PROJECT_DIR = process.env.PROJECT_DIR;
5 +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`;
6 +
7 +suite('concurrent', function () {
8 +
9 + this.timeout(7000);
10 +
11 + test(' simple concurrent prerequisites 1', function () {
12 + let out = exec(`${JAKE_CMD} -q concurrent:simple1`).toString().trim()
13 + assert.equal('Started A\nStarted B\nFinished B\nFinished A', out);
14 + });
15 +
16 + test(' simple concurrent prerequisites 2', function () {
17 + let out = exec(`${JAKE_CMD} -q concurrent:simple2`).toString().trim()
18 + assert.equal('Started C\nStarted D\nFinished C\nFinished D', out);
19 + });
20 +
21 + test(' sequential concurrent prerequisites', function () {
22 + let out = exec(`${JAKE_CMD} -q concurrent:seqconcurrent`).toString().trim()
23 + assert.equal('Started A\nStarted B\nFinished B\nFinished A\nStarted C\nStarted D\nFinished C\nFinished D', out);
24 + });
25 +
26 + test(' concurrent concurrent prerequisites', function () {
27 + let out = exec(`${JAKE_CMD} -q concurrent:concurrentconcurrent`).toString().trim()
28 + assert.equal('Started A\nStarted B\nStarted C\nStarted D\nFinished B\nFinished C\nFinished A\nFinished D', out);
29 + });
30 +
31 + test(' concurrent prerequisites with subdependency', function () {
32 + let out = exec(`${JAKE_CMD} -q concurrent:subdep`).toString().trim()
33 + assert.equal('Started A\nFinished A\nStarted Ba\nFinished Ba', out);
34 + });
35 +
36 + test(' failing in concurrent prerequisites', function () {
37 + try {
38 + exec(`${JAKE_CMD} -q concurrent:Cfail`);
39 + }
40 + catch(err) {
41 + assert(err.message.indexOf('Command failed') > -1);
42 + }
43 + });
44 +
45 +});
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +const PROJECT_DIR = process.env.PROJECT_DIR;
20 +
21 +let assert = require('assert');
22 +let fs = require('fs');
23 +let path = require('path');
24 +let file = require(`${PROJECT_DIR}/lib/utils/file`);
25 +let existsSync = fs.existsSync || path.existsSync;
26 +let exec = require('child_process').execSync;
27 +
28 +suite('fileUtils', function () {
29 +
30 + test('mkdirP', function () {
31 + let expected = [
32 + ['foo'],
33 + ['foo', 'bar'],
34 + ['foo', 'bar', 'baz'],
35 + ['foo', 'bar', 'baz', 'qux']
36 + ];
37 + file.mkdirP('foo/bar/baz/qux');
38 + let res = exec('find foo').toString().trim().split('\n');
39 + for (let i = 0, ii = res.length; i < ii; i++) {
40 + assert.equal(path.join.apply(path, expected[i]), res[i]);
41 + }
42 + file.rmRf('foo');
43 + });
44 +
45 + test('rmRf', function () {
46 + file.mkdirP('foo/bar/baz/qux');
47 + file.rmRf('foo/bar');
48 + let res = exec('find foo').toString().trim().split('\n');
49 + assert.equal(1, res.length);
50 + assert.equal('foo', res[0]);
51 + fs.rmdirSync('foo');
52 + });
53 +
54 + test('rmRf with symlink subdir', function () {
55 + file.mkdirP('foo');
56 + file.mkdirP('bar');
57 + fs.writeFileSync('foo/hello.txt', 'hello, it\'s me');
58 + fs.symlinkSync('../foo', 'bar/foo'); file.rmRf('bar');
59 +
60 + // Make sure the bar directory was successfully deleted
61 + let barDeleted = false;
62 + try {
63 + fs.statSync('bar');
64 + } catch(err) {
65 + if(err.code == 'ENOENT') {
66 + barDeleted = true;
67 + }
68 + }
69 + assert.equal(true, barDeleted);
70 +
71 + // Make sure that the file inside the linked folder wasn't deleted
72 + let res = fs.readdirSync('foo');
73 + assert.equal(1, res.length);
74 + assert.equal('hello.txt', res[0]);
75 +
76 + // Cleanup
77 + fs.unlinkSync('foo/hello.txt');
78 + fs.rmdirSync('foo');
79 + });
80 +
81 + test('rmRf with symlinked dir', function () {
82 + file.mkdirP('foo');
83 + fs.writeFileSync('foo/hello.txt', 'hello!');
84 + fs.symlinkSync('foo', 'bar');
85 + file.rmRf('bar');
86 +
87 + // Make sure the bar directory was successfully deleted
88 + let barDeleted = false;
89 + try {
90 + fs.statSync('bar');
91 + } catch(err) {
92 + if(err.code == 'ENOENT') {
93 + barDeleted = true;
94 + }
95 + }
96 + assert.equal(true, barDeleted);
97 +
98 + // Make sure that the file inside the linked folder wasn't deleted
99 + let res = fs.readdirSync('foo');
100 + assert.equal(1, res.length);
101 + assert.equal('hello.txt', res[0]);
102 +
103 + // Cleanup
104 + fs.unlinkSync('foo/hello.txt');
105 + fs.rmdirSync('foo');
106 + });
107 +
108 + test('cpR with same name and different directory', function () {
109 + file.mkdirP('foo');
110 + fs.writeFileSync('foo/bar.txt', 'w00t');
111 + file.cpR('foo', 'bar');
112 + assert.ok(existsSync('bar/bar.txt'));
113 + file.rmRf('foo');
114 + file.rmRf('bar');
115 + });
116 +
117 + test('cpR with same to and from will throw', function () {
118 + assert.throws(function () {
119 + file.cpR('foo.txt', 'foo.txt');
120 + });
121 + });
122 +
123 + test('cpR rename via copy in directory', function () {
124 + file.mkdirP('foo');
125 + fs.writeFileSync('foo/bar.txt', 'w00t');
126 + file.cpR('foo/bar.txt', 'foo/baz.txt');
127 + assert.ok(existsSync('foo/baz.txt'));
128 + file.rmRf('foo');
129 + });
130 +
131 + test('cpR rename via copy in base', function () {
132 + fs.writeFileSync('bar.txt', 'w00t');
133 + file.cpR('bar.txt', 'baz.txt');
134 + assert.ok(existsSync('baz.txt'));
135 + file.rmRf('bar.txt');
136 + file.rmRf('baz.txt');
137 + });
138 +
139 + test('cpR keeps file mode', function () {
140 + fs.writeFileSync('bar.txt', 'w00t', {mode: 0o750});
141 + fs.writeFileSync('bar1.txt', 'w00t!', {mode: 0o744});
142 + file.cpR('bar.txt', 'baz.txt');
143 + file.cpR('bar1.txt', 'baz1.txt');
144 +
145 + assert.ok(existsSync('baz.txt'));
146 + assert.ok(existsSync('baz1.txt'));
147 + let bazStat = fs.statSync('baz.txt');
148 + let bazStat1 = fs.statSync('baz1.txt');
149 + assert.equal(0o750, bazStat.mode & 0o7777);
150 + assert.equal(0o744, bazStat1.mode & 0o7777);
151 +
152 + file.rmRf('bar.txt');
153 + file.rmRf('baz.txt');
154 + file.rmRf('bar1.txt');
155 + file.rmRf('baz1.txt');
156 + });
157 +
158 + test('cpR keeps file mode when overwriting with preserveMode', function () {
159 + fs.writeFileSync('bar.txt', 'w00t', {mode: 0o755});
160 + fs.writeFileSync('baz.txt', 'w00t!', {mode: 0o744});
161 + file.cpR('bar.txt', 'baz.txt', {silent: true, preserveMode: true});
162 +
163 + assert.ok(existsSync('baz.txt'));
164 + let bazStat = fs.statSync('baz.txt');
165 + assert.equal(0o755, bazStat.mode & 0o777);
166 +
167 + file.rmRf('bar.txt');
168 + file.rmRf('baz.txt');
169 + });
170 +
171 + test('cpR does not keep file mode when overwriting', function () {
172 + fs.writeFileSync('bar.txt', 'w00t', {mode: 0o766});
173 + fs.writeFileSync('baz.txt', 'w00t!', {mode: 0o744});
174 + file.cpR('bar.txt', 'baz.txt');
175 +
176 + assert.ok(existsSync('baz.txt'));
177 + let bazStat = fs.statSync('baz.txt');
178 + assert.equal(0o744, bazStat.mode & 0o777);
179 +
180 + file.rmRf('bar.txt');
181 + file.rmRf('baz.txt');
182 + });
183 +
184 + test('cpR copies file mode recursively', function () {
185 + fs.mkdirSync('foo');
186 + fs.writeFileSync('foo/bar.txt', 'w00t', {mode: 0o740});
187 + file.cpR('foo', 'baz');
188 +
189 + assert.ok(existsSync('baz'));
190 + let barStat = fs.statSync('baz/bar.txt');
191 + assert.equal(0o740, barStat.mode & 0o777);
192 +
193 + file.rmRf('foo');
194 + file.rmRf('baz');
195 + });
196 +
197 + test('cpR keeps file mode recursively', function () {
198 + fs.mkdirSync('foo');
199 + fs.writeFileSync('foo/bar.txt', 'w00t', {mode: 0o740});
200 + fs.mkdirSync('baz');
201 + fs.mkdirSync('baz/foo');
202 + fs.writeFileSync('baz/foo/bar.txt', 'w00t!', {mode: 0o755});
203 + file.cpR('foo', 'baz', {silent: true, preserveMode: true});
204 +
205 + assert.ok(existsSync('baz'));
206 + let barStat = fs.statSync('baz/foo/bar.txt');
207 + assert.equal(0o740, barStat.mode & 0o777);
208 +
209 + file.rmRf('foo');
210 + file.rmRf('baz');
211 + });
212 +
213 + test('cpR copies directory mode recursively', function () {
214 + fs.mkdirSync('foo', 0o755);
215 + fs.mkdirSync('foo/bar', 0o700);
216 + file.cpR('foo', 'bar');
217 +
218 + assert.ok(existsSync('foo'));
219 + let fooBarStat = fs.statSync('bar/bar');
220 + assert.equal(0o700, fooBarStat.mode & 0o777);
221 +
222 + file.rmRf('foo');
223 + file.rmRf('bar');
224 + });
225 +
226 +});
227 +
228 +
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +const PROJECT_DIR = process.env.PROJECT_DIR;
20 +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`;
21 +
22 +let assert = require('assert');
23 +let fs = require('fs');
24 +let exec = require('child_process').execSync;
25 +let { rmRf } = require(`${PROJECT_DIR}/lib/jake`);
26 +
27 +let cleanUpAndNext = function (callback) {
28 + rmRf('./foo', {
29 + silent: true
30 + });
31 + callback && callback();
32 +};
33 +
34 +suite('fileTask', function () {
35 + this.timeout(7000);
36 +
37 + setup(function () {
38 + cleanUpAndNext();
39 + });
40 +
41 + test('where a file-task prereq does not change with --always-make', function () {
42 + let out;
43 + out = exec(`${JAKE_CMD} -q fileTest:foo/from-src1.txt`).toString().trim();
44 + assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task',
45 + out);
46 + out = exec(`${JAKE_CMD} -q -B fileTest:foo/from-src1.txt`).toString().trim();
47 + assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task',
48 + out);
49 + cleanUpAndNext();
50 + });
51 +
52 + test('concating two files', function () {
53 + let out;
54 + out = exec(`${JAKE_CMD} -q fileTest:foo/concat.txt`).toString().trim();
55 + assert.equal('fileTest:foo/src1.txt task\ndefault task\nfileTest:foo/src2.txt task\n' +
56 + 'fileTest:foo/concat.txt task', out);
57 + // Check to see the two files got concat'd
58 + let data = fs.readFileSync(process.cwd() + '/foo/concat.txt');
59 + assert.equal('src1src2', data.toString());
60 + cleanUpAndNext();
61 + });
62 +
63 + test('where a file-task prereq does not change', function () {
64 + let out;
65 + out = exec(`${JAKE_CMD} -q fileTest:foo/from-src1.txt`).toString().trim();
66 + assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task', out);
67 + out = exec(`${JAKE_CMD} -q fileTest:foo/from-src1.txt`).toString().trim();
68 + // Second time should be a no-op
69 + assert.equal('', out);
70 + cleanUpAndNext();
71 + });
72 +
73 + test('where a file-task prereq does change, then does not', function (next) {
74 + exec('mkdir -p ./foo');
75 + exec('touch ./foo/from-src1.txt');
76 + setTimeout(() => {
77 + fs.writeFileSync('./foo/src1.txt', '-SRC');
78 + // Task should run the first time
79 + let out;
80 + out = exec(`${JAKE_CMD} -q fileTest:foo/from-src1.txt`).toString().trim();
81 + assert.equal('fileTest:foo/from-src1.txt task', out);
82 + // Task should not run on subsequent invocation
83 + out = exec(`${JAKE_CMD} -q fileTest:foo/from-src1.txt`).toString().trim();
84 + assert.equal('', out);
85 + cleanUpAndNext(next);
86 + }, 1000);
87 + });
88 +
89 + test('a preexisting file', function () {
90 + let prereqData = 'howdy';
91 + exec('mkdir -p ./foo');
92 + fs.writeFileSync('foo/prereq.txt', prereqData);
93 + let out;
94 + out = exec(`${JAKE_CMD} -q fileTest:foo/from-prereq.txt`).toString().trim();
95 + assert.equal('fileTest:foo/from-prereq.txt task', out);
96 + let data = fs.readFileSync(process.cwd() + '/foo/from-prereq.txt');
97 + assert.equal(prereqData, data.toString());
98 + out = exec(`${JAKE_CMD} -q fileTest:foo/from-prereq.txt`).toString().trim();
99 + // Second time should be a no-op
100 + assert.equal('', out);
101 + cleanUpAndNext();
102 + });
103 +
104 + test('a preexisting file with --always-make flag', function () {
105 + let prereqData = 'howdy';
106 + exec('mkdir -p ./foo');
107 + fs.writeFileSync('foo/prereq.txt', prereqData);
108 + let out;
109 + out = exec(`${JAKE_CMD} -q fileTest:foo/from-prereq.txt`).toString().trim();
110 + assert.equal('fileTest:foo/from-prereq.txt task', out);
111 + let data = fs.readFileSync(process.cwd() + '/foo/from-prereq.txt');
112 + assert.equal(prereqData, data.toString());
113 + out = exec(`${JAKE_CMD} -q -B fileTest:foo/from-prereq.txt`).toString().trim();
114 + assert.equal('fileTest:foo/from-prereq.txt task', out);
115 + cleanUpAndNext();
116 + });
117 +
118 + test('nested directory-task', function () {
119 + exec(`${JAKE_CMD} -q fileTest:foo/bar/baz/bamf.txt`);
120 + let data = fs.readFileSync(process.cwd() + '/foo/bar/baz/bamf.txt');
121 + assert.equal('w00t', data);
122 + cleanUpAndNext();
123 + });
124 +
125 +});
126 +
1 +var exec = require('child_process').exec;
2 +
3 +var helpers = new (function () {
4 + var _tests;
5 + var _names = [];
6 + var _name;
7 + var _callback;
8 + var _runner = function () {
9 + if ((_name = _names.shift())) {
10 + console.log('Running ' + _name);
11 + _tests[_name]();
12 + }
13 + else {
14 + _callback();
15 + }
16 + };
17 +
18 + this.exec = function () {
19 + var args = Array.prototype.slice.call(arguments);
20 + var arg;
21 + var cmd = args.shift();
22 + var opts = {};
23 + var callback;
24 + // Optional opts/callback or callback/opts
25 + while ((arg = args.shift())) {
26 + if (typeof arg == 'function') {
27 + callback = arg;
28 + }
29 + else {
30 + opts = arg;
31 + }
32 + }
33 +
34 + cmd += ' --trace';
35 + var execOpts = opts.execOpts ? opts.execOpts : {};
36 + exec(cmd, execOpts, function (err, stdout, stderr) {
37 + var out = helpers.trim(stdout);
38 + if (err) {
39 + if (opts.breakOnError === false) {
40 + return callback(err);
41 + }
42 + else {
43 + throw err;
44 + }
45 + }
46 + if (stderr) {
47 + callback(stderr);
48 + }
49 + else {
50 + callback(out);
51 + }
52 + });
53 + };
54 +
55 + this.trim = function (s) {
56 + var str = s || '';
57 + return str.replace(/^\s*|\s*$/g, '');
58 + };
59 +
60 + this.parse = function (s) {
61 + var str = s || '';
62 + str = helpers.trim(str);
63 + str = str.replace(/'/g, '"');
64 + return JSON.parse(str);
65 + };
66 +
67 + this.run = function (tests, callback) {
68 + _tests = tests;
69 + _names = Object.keys(tests);
70 + _callback = callback;
71 + _runner();
72 + };
73 +
74 + this.next = function () {
75 + _runner();
76 + };
77 +
78 +})();
79 +
80 +module.exports = helpers;
1 +let fs = require('fs');
2 +let Q = require('q');
3 +
4 +desc('The default t.');
5 +task('default', function () {
6 + console.log('default task');
7 +});
8 +
9 +desc('No action.');
10 +task({'noAction': ['default']});
11 +
12 +desc('No action, no prereqs.');
13 +task('noActionNoPrereqs');
14 +
15 +desc('Top-level zerbofrangazoomy task');
16 +task('zerbofrangazoomy', function () {
17 + console.log('Whaaaaaaaa? Ran the zerbofrangazoomy task!')
18 +});
19 +
20 +desc('Task that throws');
21 +task('throwy', function () {
22 + let errorListener = function (err) {
23 + console.log('Emitted');
24 + console.log(err.toString());
25 +
26 + jake.removeListener('error', errorListener);
27 + };
28 +
29 + jake.on('error', errorListener);
30 +
31 + throw new Error('I am bad');
32 +});
33 +
34 +desc('Task that rejects a Promise');
35 +task('promiseRejecter', function () {
36 + const originalOption = jake.program.opts['allow-rejection'];
37 +
38 + const errorListener = function (err) {
39 + console.log(err.toString());
40 + jake.removeListener('error', errorListener);
41 + jake.program.opts['allow-rejection'] = originalOption; // Restore original 'allow-rejection' option
42 + };
43 + jake.on('error', errorListener);
44 +
45 + jake.program.opts['allow-rejection'] = false; // Do not allow rejection so the rejection is passed to error handlers
46 +
47 + Promise.reject('<promise rejected on purpose>');
48 +});
49 +
50 +desc('Accepts args and env vars.');
51 +task('argsEnvVars', function () {
52 + let res = {
53 + args: arguments
54 + , env: {
55 + foo: process.env.foo
56 + , baz: process.env.baz
57 + }
58 + };
59 + console.log(JSON.stringify(res));
60 +});
61 +
62 +namespace('foo', function () {
63 + desc('The foo:bar t.');
64 + task('bar', function () {
65 + if (arguments.length) {
66 + console.log('foo:bar[' +
67 + Array.prototype.join.call(arguments, ',') +
68 + '] task');
69 + }
70 + else {
71 + console.log('foo:bar task');
72 + }
73 + });
74 +
75 + desc('The foo:baz task, calls foo:bar as a prerequisite.');
76 + task('baz', ['foo:bar'], function () {
77 + console.log('foo:baz task');
78 + });
79 +
80 + desc('The foo:qux task, calls foo:bar with cmdline args as a prerequisite.');
81 + task('qux', ['foo:bar[asdf,qwer]'], function () {
82 + console.log('foo:qux task');
83 + });
84 +
85 + desc('The foo:frang task,`invokes` foo:bar with passed args as a prerequisite.');
86 + task('frang', function () {
87 + let t = jake.Task['foo:bar'];
88 + // Do args pass-through
89 + t.invoke.apply(t, arguments);
90 + t.on('complete', () => {
91 + console.log('foo:frang task');
92 + });
93 + });
94 +
95 + desc('The foo:zerb task, `executes` foo:bar with passed args as a prerequisite.');
96 + task('zerb', function () {
97 + let t = jake.Task['foo:bar'];
98 + // Do args pass-through
99 + t.execute.apply(t, arguments);
100 + t.on('complete', () => {
101 + console.log('foo:zerb task');
102 + });
103 + });
104 +
105 + desc('The foo:zoobie task, has no prerequisites.');
106 + task('zoobie', function () {
107 + console.log('foo:zoobie task');
108 + });
109 +
110 + desc('The foo:voom task, run the foo:zoobie task repeatedly.');
111 + task('voom', function () {
112 + let t = jake.Task['foo:bar'];
113 + t.on('complete', function () {
114 + console.log('complete');
115 + });
116 + t.execute.apply(t);
117 + t.execute.apply(t);
118 + });
119 +
120 + desc('The foo:asdf task, has the same prereq twice.');
121 + task('asdf', ['foo:bar', 'foo:baz'], function () {
122 + console.log('foo:asdf task');
123 + });
124 +
125 +});
126 +
127 +namespace('bar', function () {
128 + desc('The bar:foo task, has no prerequisites, is async, returns Promise which resolves.');
129 + task('foo', async function () {
130 + return new Promise((resolve, reject) => {
131 + console.log('bar:foo task');
132 + resolve();
133 + });
134 + });
135 +
136 + desc('The bar:promise task has no prerequisites, is async, returns Q-based promise.');
137 + task('promise', function () {
138 + return Q()
139 + .then(function () {
140 + console.log('bar:promise task');
141 + return 123654;
142 + });
143 + });
144 +
145 + desc('The bar:dependOnpromise task waits for a promise based async test');
146 + task('dependOnpromise', ['promise'], function () {
147 + console.log('bar:dependOnpromise task saw value', jake.Task["bar:promise"].value);
148 + });
149 +
150 + desc('The bar:brokenPromise task is a failing Q-promise based async task.');
151 + task('brokenPromise', function () {
152 + return Q()
153 + .then(function () {
154 + throw new Error("nom nom nom");
155 + });
156 + });
157 +
158 + desc('The bar:bar task, has the async bar:foo task as a prerequisite.');
159 + task('bar', ['bar:foo'], function () {
160 + console.log('bar:bar task');
161 + });
162 +
163 +});
164 +
165 +namespace('hoge', function () {
166 + desc('The hoge:hoge task, has no prerequisites.');
167 + task('hoge', function () {
168 + console.log('hoge:hoge task');
169 + });
170 +
171 + desc('The hoge:piyo task, has no prerequisites.');
172 + task('piyo', function () {
173 + console.log('hoge:piyo task');
174 + });
175 +
176 + desc('The hoge:fuga task, has hoge:hoge and hoge:piyo as prerequisites.');
177 + task('fuga', ['hoge:hoge', 'hoge:piyo'], function () {
178 + console.log('hoge:fuga task');
179 + });
180 +
181 + desc('The hoge:charan task, has hoge:fuga as a prerequisite.');
182 + task('charan', ['hoge:fuga'], function () {
183 + console.log('hoge:charan task');
184 + });
185 +
186 + desc('The hoge:gero task, has hoge:fuga as a prerequisite.');
187 + task('gero', ['hoge:fuga'], function () {
188 + console.log('hoge:gero task');
189 + });
190 +
191 + desc('The hoge:kira task, has hoge:charan and hoge:gero as prerequisites.');
192 + task('kira', ['hoge:charan', 'hoge:gero'], function () {
193 + console.log('hoge:kira task');
194 + });
195 +
196 +});
197 +
198 +namespace('fileTest', function () {
199 + directory('foo');
200 +
201 + desc('File task, concatenating two files together');
202 + file('foo/concat.txt', ['fileTest:foo', 'fileTest:foo/src1.txt', 'fileTest:foo/src2.txt'], function () {
203 + console.log('fileTest:foo/concat.txt task');
204 + let data1 = fs.readFileSync('foo/src1.txt');
205 + let data2 = fs.readFileSync('foo/src2.txt');
206 + fs.writeFileSync('foo/concat.txt', data1 + data2);
207 + });
208 +
209 + desc('File task, async creation with writeFile');
210 + file('foo/src1.txt', function () {
211 + return new Promise(function (resolve, reject) {
212 + fs.writeFile('foo/src1.txt', 'src1', function (err) {
213 + if (err) {
214 + reject(err);
215 + }
216 + else {
217 + console.log('fileTest:foo/src1.txt task');
218 + resolve();
219 + }
220 + });
221 + });
222 + });
223 +
224 + desc('File task, sync creation with writeFileSync');
225 + file('foo/src2.txt', ['default'], function () {
226 + fs.writeFileSync('foo/src2.txt', 'src2');
227 + console.log('fileTest:foo/src2.txt task');
228 + });
229 +
230 + desc('File task, do not run unless the prereq file changes');
231 + file('foo/from-src1.txt', ['fileTest:foo', 'fileTest:foo/src1.txt'], function () {
232 + let data = fs.readFileSync('foo/src1.txt').toString();
233 + fs.writeFileSync('foo/from-src1.txt', data);
234 + console.log('fileTest:foo/from-src1.txt task');
235 + });
236 +
237 + desc('File task, run if the prereq file changes');
238 + task('touch-prereq', function () {
239 + fs.writeFileSync('foo/prereq.txt', 'UPDATED');
240 + })
241 +
242 + desc('File task, has a preexisting file (with no associated task) as a prereq');
243 + file('foo/from-prereq.txt', ['fileTest:foo', 'foo/prereq.txt'], function () {
244 + let data = fs.readFileSync('foo/prereq.txt');
245 + fs.writeFileSync('foo/from-prereq.txt', data);
246 + console.log('fileTest:foo/from-prereq.txt task');
247 + });
248 +
249 + directory('foo/bar/baz');
250 +
251 + desc('Write a file in a nested subdirectory');
252 + file('foo/bar/baz/bamf.txt', ['foo/bar/baz'], function () {
253 + fs.writeFileSync('foo/bar/baz/bamf.txt', 'w00t');
254 + });
255 +
256 +});
257 +
258 +task('blammo');
259 +// Define task
260 +task('voom', ['blammo'], function () {
261 + console.log(this.prereqs.length);
262 +});
263 +
264 +// Modify, add a prereq
265 +task('voom', ['noActionNoPrereqs']);
266 +
267 +namespace('vronk', function () {
268 + task('groo', function () {
269 + let t = jake.Task['vronk:zong'];
270 + t.addListener('error', function (e) {
271 + console.log(e.message);
272 + });
273 + t.invoke();
274 + });
275 + task('zong', function () {
276 + throw new Error('OMFGZONG');
277 + });
278 +});
279 +
280 +// define namespace
281 +namespace('one', function () {
282 + task('one', function () {
283 + console.log('one:one');
284 + });
285 +});
286 +
287 +// modify namespace (add task)
288 +namespace('one', function () {
289 + task('two', ['one:one'], function () {
290 + console.log('one:two');
291 + });
292 +});
293 +
294 +task('selfdepconst', [], function () {
295 + task('selfdep', ['selfdep'], function () {
296 + console.log("I made a task that depends on itself");
297 + });
298 +});
299 +task('selfdepdyn', function () {
300 + task('selfdeppar', [], {concurrency: 2}, function () {
301 + console.log("I will depend on myself and will fail at runtime");
302 + });
303 + task('selfdeppar', ['selfdeppar']);
304 + jake.Task['selfdeppar'].invoke();
305 +});
306 +
307 +namespace("large", function () {
308 + task("leaf", function () {
309 + console.log("large:leaf");
310 + });
311 +
312 + const same = [];
313 + for (let i = 0; i < 2000; i++) {
314 + same.push("leaf");
315 + }
316 +
317 + desc("Task with a large number of same prereqs");
318 + task("same", same, { concurrency: 2 }, function () {
319 + console.log("large:same");
320 + });
321 +
322 + const different = [];
323 + for (let i = 0; i < 2000; i++) {
324 + const name = "leaf-" + i;
325 + task(name, function () {
326 + if (name === "leaf-12" || name === "leaf-123") {
327 + console.log(name);
328 + }
329 + });
330 + different.push(name);
331 + }
332 +
333 + desc("Task with a large number of different prereqs");
334 + task("different", different, { concurrency: 2 } , function () {
335 + console.log("large:different")
336 + })
337 +});
1 +
2 +namespace('concurrent', function () {
3 + task('A', function () {
4 + console.log('Started A');
5 + return new Promise((resolve, reject) => {
6 + setTimeout(() => {
7 + console.log('Finished A');
8 + resolve();
9 + }, 200);
10 + });
11 + });
12 +
13 + task('B', function () {
14 + console.log('Started B');
15 + return new Promise((resolve, reject) => {
16 + setTimeout(() => {
17 + console.log('Finished B');
18 + resolve();
19 + }, 50);
20 + });
21 + });
22 +
23 + task('C', function () {
24 + console.log('Started C');
25 + return new Promise((resolve, reject) => {
26 + setTimeout(() => {
27 + console.log('Finished C');
28 + resolve();
29 + }, 100);
30 + });
31 + });
32 +
33 + task('D', function () {
34 + console.log('Started D');
35 + return new Promise((resolve, reject) => {
36 + setTimeout(() => {
37 + console.log('Finished D');
38 + resolve();
39 + }, 300);
40 + });
41 + });
42 +
43 + task('Ba', ['A'], function () {
44 + console.log('Started Ba');
45 + return new Promise((resolve, reject) => {
46 + setTimeout(() => {
47 + console.log('Finished Ba');
48 + resolve();
49 + }, 50);
50 + });
51 + });
52 +
53 + task('Afail', function () {
54 + console.log('Started failing task');
55 + return new Promise((resolve, reject) => {
56 + setTimeout(() => {
57 + console.log('Failing B with error');
58 + throw new Error('I failed');
59 + }, 50);
60 + });
61 + });
62 +
63 + task('simple1', ['A','B'], {concurrency: 2}, function () {
64 + return new Promise((resolve, reject) => {
65 + setTimeout(() => {
66 + resolve();
67 + }, 50);
68 + });
69 + });
70 +
71 + task('simple2', ['C','D'], {concurrency: 2}, function () {
72 + return new Promise((resolve, reject) => {
73 + setTimeout(() => {
74 + resolve();
75 + }, 50);
76 + });
77 + });
78 +
79 + task('seqconcurrent', ['simple1','simple2'], function () {
80 + return new Promise((resolve, reject) => {
81 + setTimeout(() => {
82 + resolve();
83 + }, 50);
84 + });
85 + });
86 +
87 + task('concurrentconcurrent', ['simple1','simple2'], {concurrency: 2}, function () {
88 + return new Promise((resolve, reject) => {
89 + setTimeout(() => {
90 + resolve();
91 + }, 50);
92 + });
93 + });
94 +
95 + task('subdep', ['A','Ba'], {concurrency: 2}, function () {
96 + return new Promise((resolve, reject) => {
97 + setTimeout(() => {
98 + resolve();
99 + }, 50);
100 + });
101 + });
102 +
103 + task('fail', ['A', 'B', 'Afail'], {concurrency: 3}, function () {
104 + return new Promise((resolve, reject) => {
105 + setTimeout(() => {
106 + resolve();
107 + }, 50);
108 + });
109 + });
110 +
111 +});
112 +
113 +
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +const PROJECT_DIR = process.env.PROJECT_DIR;
20 +
21 +let fs = require('fs');
22 +let { publishTask, rmRf, mkdirP } = require(`${PROJECT_DIR}/lib/jake`);
23 +
24 +fs.writeFileSync('package.json', '{"version": "0.0.1"}');
25 +mkdirP('tmp_publish');
26 +fs.writeFileSync('tmp_publish/foo.txt', 'FOO');
27 +
28 +publishTask('zerb', function () {
29 + this.packageFiles.include([
30 + 'package.json'
31 + , 'tmp_publish/**'
32 + ]);
33 + this.publishCmd = 'node -p -e "\'%filename\'"';
34 + this.gitCmd = 'echo'
35 + this.scheduleDelay = 0;
36 +
37 + this._ensureRepoClean = function () {};
38 + this._getCurrentBranch = function () {
39 + return 'v0.0'
40 + };
41 +});
42 +
43 +jake.setTaskTimeout(5000);
44 +
45 +jake.Task['publish'].on('complete', function () {
46 + rmRf('tmp_publish', {silent: true});
47 + rmRf('package.json', {silent: true});
48 +});
49 +
1 +let { task, namespace } = require(`${process.env.PROJECT_DIR}/lib/jake`);
2 +
3 +namespace('usingRequire', function () {
4 + task('test', () => {
5 + console.log('howdy test');
6 + });
7 +});
8 +
9 +
10 +
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +const PROJECT_DIR = process.env.PROJECT_DIR;
20 +
21 +let exec = require('child_process').execSync;
22 +let fs = require('fs');
23 +let util = require('util');
24 +let { rule, rmRf } = require(`${PROJECT_DIR}/lib/jake`);
25 +
26 +directory('tmpsrc');
27 +directory('tmpbin');
28 +
29 +////////////////////////////////////////////////////////////
30 +// Simple Suffix Rule
31 +file('tmp', ['tmp_init', 'tmp_dep1.o', 'tmp_dep2.o'], function (params) {
32 + console.log('tmp task');
33 + let data1 = fs.readFileSync('tmp_dep1.o');
34 + let data2 = fs.readFileSync('tmp_dep2.o');
35 + fs.writeFileSync('tmp', data1 + data2);
36 +});
37 +
38 +rule('.o', '.c', function () {
39 + let cmd = util.format('cp %s %s', this.source, this.name);
40 + console.log(cmd + ' task');
41 + exec(cmd);
42 +});
43 +
44 +file('tmp_dep1.c', function () {
45 + fs.writeFileSync('tmp_dep1.c', 'src_1');
46 + console.log('tmp_dep1.c task');
47 +});
48 +
49 +// note that tmp_dep2.o depends on tmp_dep2.c, which is a
50 +// static file.
51 +task('tmp_init', function () {
52 + fs.writeFileSync('tmp_dep2.c', 'src_2');
53 + console.log('tmp_dep2.c task');
54 +});
55 +////////////////////////////////////////////////////////////
56 +
57 +////////////////////////////////////////////////////////////
58 +// Pattern Rule
59 +file('tmp_p', ['tmp_init', 'tmp_dep1.oo', 'tmp_dep2.oo'], function (params) {
60 + console.log('tmp pattern task');
61 + let data1 = fs.readFileSync('tmp_dep1.oo');
62 + let data2 = fs.readFileSync('tmp_dep2.oo');
63 + fs.writeFileSync('tmp_p', data1 + data2 + ' pattern');
64 +});
65 +
66 +rule('%.oo', '%.c', function () {
67 + let cmd = util.format('cp %s %s', this.source, this.name);
68 + console.log(cmd + ' task');
69 + exec(cmd);
70 +});
71 +////////////////////////////////////////////////////////////
72 +
73 +////////////////////////////////////////////////////////////
74 +// Pattern Rule with Folder
75 +// i.e. rule('tmpbin/%.oo', 'tmpsrc/%.c', ...
76 +file('tmp_pf', [
77 + 'tmp_src_init'
78 + , 'tmpbin'
79 + , 'tmpbin/tmp_dep1.oo'
80 + , 'tmpbin/tmp_dep2.oo' ], function (params) {
81 + console.log('tmp pattern folder task');
82 + let data1 = fs.readFileSync('tmpbin/tmp_dep1.oo');
83 + let data2 = fs.readFileSync('tmpbin/tmp_dep2.oo');
84 + fs.writeFileSync('tmp_pf', data1 + data2 + ' pattern folder');
85 +});
86 +
87 +rule('tmpbin/%.oo', 'tmpsrc/%.c', function () {
88 + let cmd = util.format('cp %s %s', this.source, this.name);
89 + console.log(cmd + ' task');
90 + exec(cmd);
91 +});
92 +
93 +file('tmpsrc/tmp_dep2.c',['tmpsrc'], function () {
94 + fs.writeFileSync('tmpsrc/tmp_dep2.c', 'src/src_2');
95 + console.log('tmpsrc/tmp_dep2.c task');
96 +});
97 +
98 +// Create static files in folder tmpsrc.
99 +task('tmp_src_init', ['tmpsrc'], function () {
100 + fs.writeFileSync('tmpsrc/tmp_dep1.c', 'src/src_1');
101 + console.log('tmpsrc/tmp_dep1.c task');
102 +});
103 +////////////////////////////////////////////////////////////
104 +
105 +
106 +////////////////////////////////////////////////////////////
107 +// Namespace Test. This is a Mixed Test.
108 +// Test for
109 +// - rules belonging to different namespace.
110 +// - rules with folder and pattern
111 +task('tmp_ns', [
112 + 'tmpbin'
113 + , 'rule:init'
114 + , 'tmpbin/tmp_dep2.oo' // *** This relies on a rule defined before.
115 + , 'rule:tmpbin/dep1.oo'
116 + , 'rule:tmpbin/file2.oo' ], function () {
117 + console.log('tmp pattern folder namespace task');
118 + let data1 = fs.readFileSync('tmpbin/dep1.oo');
119 + let data2 = fs.readFileSync('tmpbin/tmp_dep2.oo');
120 + let data3 = fs.readFileSync('tmpbin/file2.oo');
121 + fs.writeFileSync('tmp_ns', data1 + data2 + data3 + ' pattern folder namespace');
122 +});
123 +
124 +namespace('rule', function () {
125 + task('init', ['tmpsrc'], function () {
126 + fs.writeFileSync('tmpsrc/file2.c', 'src/src_3');
127 + console.log('tmpsrc/file2.c init task');
128 + });
129 +
130 + file('tmpsrc/dep1.c',['tmpsrc'], function () {
131 + fs.writeFileSync('tmpsrc/dep1.c', 'src/src_1');
132 + console.log('tmpsrc/dep1.c task');
133 + }, {async: true});
134 +
135 + rule('tmpbin/%.oo', 'tmpsrc/%.c', function () {
136 + let cmd = util.format('cp %s %s', this.source, this.name);
137 + console.log(cmd + ' ns task');
138 + exec(cmd);
139 + });
140 +});
141 +////////////////////////////////////////////////////////////
142 +
143 +////////////////////////////////////////////////////////////
144 +// Chain rule
145 +// rule('tmpbin/%.pdf', 'tmpbin/%.dvi', function() { ...
146 +// rule('tmpbin/%.dvi', 'tmpsrc/%.tex', ['tmpbin'], function() { ...
147 +task('tmp_cr', [
148 + 'chainrule:init'
149 + , 'chainrule:tmpbin/file1.pdf'
150 + , 'chainrule:tmpbin/file2.pdf' ], function () {
151 + console.log('tmp chainrule namespace task');
152 + let data1 = fs.readFileSync('tmpbin/file1.pdf');
153 + let data2 = fs.readFileSync('tmpbin/file2.pdf');
154 + fs.writeFileSync('tmp_cr', data1 + data2 + ' chainrule namespace');
155 +});
156 +
157 +namespace('chainrule', function () {
158 + task('init', ['tmpsrc', 'tmpbin'], function () {
159 + fs.writeFileSync('tmpsrc/file1.tex', 'tex1 ');
160 + fs.writeFileSync('tmpsrc/file2.tex', 'tex2 ');
161 + console.log('chainrule init task');
162 + });
163 +
164 + rule('tmpbin/%.pdf', 'tmpbin/%.dvi', function () {
165 + let cmd = util.format('cp %s %s', this.source, this.name);
166 + console.log(cmd + ' dvi->pdf task');
167 + exec(cmd);
168 + });
169 +
170 + rule('tmpbin/%.dvi', 'tmpsrc/%.tex', ['tmpbin'], function () {
171 + let cmd = util.format('cp %s %s', this.source, this.name);
172 + console.log(cmd + ' tex->dvi task');
173 + exec(cmd);
174 + });
175 +});
176 +////////////////////////////////////////////////////////////
177 +namespace('precedence', function () {
178 + task('test', ['foo.html'], function () {
179 + console.log('ran test');
180 + });
181 +
182 + rule('.html', '.txt', function () {
183 + console.log('created html');
184 + let data = fs.readFileSync(this.source);
185 + fs.writeFileSync(this.name, data.toString());
186 + });
187 +});
188 +
189 +namespace('regexPattern', function () {
190 + task('test', ['foo.html'], function () {
191 + console.log('ran test');
192 + });
193 +
194 + rule(/\.html$/, '.txt', function () {
195 + console.log('created html');
196 + let data = fs.readFileSync(this.source);
197 + fs.writeFileSync(this.name, data.toString());
198 + });
199 +});
200 +
201 +namespace('sourceFunction', function () {
202 +
203 + let srcFunc = function (taskName) {
204 + return taskName.replace(/\.[^.]+$/, '.txt');
205 + };
206 +
207 + task('test', ['foo.html'], function () {
208 + console.log('ran test');
209 + });
210 +
211 + rule('.html', srcFunc, function () {
212 + console.log('created html');
213 + let data = fs.readFileSync(this.source);
214 + fs.writeFileSync(this.name, data.toString());
215 + });
216 +});
217 +
218 +////////////////////////////////////////////////////////////
219 +task('clean', function () {
220 + rmRf('./foo');
221 + rmRf('./tmp');
222 +});
1 +let assert = require('assert');
2 +let exec = require('child_process').execSync;
3 +
4 +const PROJECT_DIR = process.env.PROJECT_DIR;
5 +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`;
6 +
7 +suite('publishTask', function () {
8 +
9 + this.timeout(7000);
10 +
11 + test('default task', function () {
12 + let out = exec(`${JAKE_CMD} -q publish`).toString().trim();
13 + let expected = [
14 + 'Fetched remote tags.'
15 + , 'On branch v0.0'
16 + , 'Bumped version number to v0.0.2.'
17 + , 'Created package for zerb v0.0.2'
18 + , 'Publishing zerb v0.0.2'
19 + , './pkg/zerb-v0.0.2.tar.gz'
20 + , 'BOOM! Published.'
21 + , 'Cleaned up package'
22 + ].join('\n');
23 + assert.equal(expected, out);
24 + });
25 +
26 +});
27 +
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +const PROJECT_DIR = process.env.PROJECT_DIR;
20 +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`;
21 +
22 +let assert = require('assert');
23 +let exec = require('child_process').execSync;
24 +let fs = require('fs');
25 +let { Rule } = require(`${PROJECT_DIR}/lib/rule`);
26 +let { rmRf } = require(`${PROJECT_DIR}/lib/jake`);
27 +
28 +let cleanUpAndNext = function (callback) {
29 + // Gotta add globbing to file utils rmRf
30 + let tmpFiles = [
31 + 'tmp'
32 + , 'tmp_ns'
33 + , 'tmp_cr'
34 + , 'tmp_p'
35 + , 'tmp_pf'
36 + , 'tmpbin'
37 + , 'tmpsrc'
38 + , 'tmp_dep1.c'
39 + , 'tmp_dep1.o'
40 + , 'tmp_dep1.oo'
41 + , 'tmp_dep2.c'
42 + , 'tmp_dep2.o'
43 + , 'tmp_dep2.oo'
44 + , 'foo'
45 + , 'foo.html'
46 + ];
47 + tmpFiles.forEach(function (f) {
48 + rmRf(f, {
49 + silent: true
50 + });
51 + });
52 + callback && callback();
53 +};
54 +
55 +suite('rule', function () {
56 +
57 + this.timeout(7000);
58 +
59 + setup(function (next) {
60 + cleanUpAndNext(next);
61 + });
62 +
63 +
64 + // - name foo:bin/main.o
65 + // - pattern bin/%.o
66 + // - source src/%.c
67 + //
68 + // return {
69 + // 'dep' : 'foo:src/main.c',
70 + // 'file': 'src/main.c'
71 + // };
72 + test('Rule.getSource', function () {
73 + let src = Rule.getSource('foo:bin/main.o', 'bin/%.o', 'src/%.c');
74 + assert.equal('foo:src/main.c', src);
75 + });
76 +
77 + test('rule w/o pattern', function () {
78 + let out = exec( `${JAKE_CMD} -q tmp`).toString().trim();
79 + let output = [
80 + "tmp_dep2.c task"
81 + , "tmp_dep1.c task"
82 + , "cp tmp_dep1.c tmp_dep1.o task"
83 + , "cp tmp_dep2.c tmp_dep2.o task"
84 + , "tmp task"];
85 + assert.equal( output.join('\n'), out);
86 + let data = fs.readFileSync(process.cwd() + '/tmp');
87 + assert.equal('src_1src_2', data.toString());
88 + cleanUpAndNext();
89 + });
90 +
91 + test('rule w pattern w/o folder w/o namespace', function () {
92 + let out = exec( `${JAKE_CMD} -q tmp_p`).toString().trim();
93 + let output = [
94 + "tmp_dep2.c task"
95 + , "tmp_dep1.c task"
96 + , "cp tmp_dep1.c tmp_dep1.oo task"
97 + , "cp tmp_dep2.c tmp_dep2.oo task"
98 + , "tmp pattern task"];
99 + let data;
100 + assert.equal( output.join('\n'), out);
101 + data = fs.readFileSync(process.cwd() + '/tmp_p');
102 + assert.equal('src_1src_2 pattern', data.toString());
103 + cleanUpAndNext();
104 + });
105 +
106 + test('rule w pattern w folder w/o namespace', function () {
107 + let out = exec( `${JAKE_CMD} -q tmp_pf`).toString().trim();
108 + let output = [
109 + "tmpsrc/tmp_dep1.c task"
110 + , "cp tmpsrc/tmp_dep1.c tmpbin/tmp_dep1.oo task"
111 + , "tmpsrc/tmp_dep2.c task"
112 + , "cp tmpsrc/tmp_dep2.c tmpbin/tmp_dep2.oo task"
113 + , "tmp pattern folder task"];
114 + let data;
115 + assert.equal( output.join('\n'), out);
116 + data = fs.readFileSync(process.cwd() + '/tmp_pf');
117 + assert.equal('src/src_1src/src_2 pattern folder', data.toString());
118 + cleanUpAndNext();
119 + });
120 +
121 + test.skip('rule w pattern w folder w namespace', function () {
122 + let out = exec( `${JAKE_CMD} -q tmp_ns`).toString().trim();
123 + let output = [
124 + "tmpsrc/file2.c init task" // yes
125 + , "tmpsrc/tmp_dep2.c task" // no
126 + , "cp tmpsrc/tmp_dep2.c tmpbin/tmp_dep2.oo task" // no
127 + , "tmpsrc/dep1.c task" // no
128 + , "cp tmpsrc/dep1.c tmpbin/dep1.oo ns task" // no
129 + , "cp tmpsrc/file2.c tmpbin/file2.oo ns task" // yes
130 + , "tmp pattern folder namespace task"]; // yes
131 + let data;
132 + assert.equal( output.join('\n'), out);
133 + data = fs.readFileSync(process.cwd() + '/tmp_ns');
134 + assert.equal('src/src_1src/src_2src/src_3 pattern folder namespace', data.toString());
135 + cleanUpAndNext();
136 + });
137 +
138 + test.skip('rule w chain w pattern w folder w namespace', function () {
139 + let out = exec( `${JAKE_CMD} -q tmp_cr`).toString().trim();
140 + let output = [
141 + "chainrule init task"
142 + , "cp tmpsrc/file1.tex tmpbin/file1.dvi tex->dvi task"
143 + , "cp tmpbin/file1.dvi tmpbin/file1.pdf dvi->pdf task"
144 + , "cp tmpsrc/file2.tex tmpbin/file2.dvi tex->dvi task"
145 + , "cp tmpbin/file2.dvi tmpbin/file2.pdf dvi->pdf task"
146 + , "tmp chainrule namespace task"];
147 + let data;
148 + assert.equal( output.join('\n'), out);
149 + data = fs.readFileSync(process.cwd() + '/tmp_cr');
150 + assert.equal('tex1 tex2 chainrule namespace', data.toString());
151 + cleanUpAndNext();
152 + });
153 +
154 +
155 + ['precedence', 'regexPattern', 'sourceFunction'].forEach(function (key) {
156 +
157 + test('rule with source file not created yet (' + key + ')', function () {
158 + let write = process.stderr.write;
159 + process.stderr.write = () => {};
160 + rmRf('foo.txt', {silent: true});
161 + rmRf('foo.html', {silent: true});
162 + try {
163 + exec(`${JAKE_CMD} ` + key + ':test');
164 + }
165 + catch(err) {
166 + // foo.txt prereq doesn't exist yet
167 + assert.ok(err.message.indexOf('Unknown task "foo.html"') > -1);
168 + }
169 + process.stderr.write = write;
170 + });
171 +
172 + test('rule with source file now created (' + key + ')', function () {
173 + fs.writeFileSync('foo.txt', '');
174 + let out = exec(`${JAKE_CMD} -q ` + key + ':test').toString().trim();
175 + // Should run prereq and test task
176 + let output = [
177 + 'created html'
178 + , 'ran test'
179 + ];
180 + assert.equal(output.join('\n'), out);
181 + });
182 +
183 + test('rule with source file modified (' + key + ')', function (next) {
184 + setTimeout(function () {
185 + fs.writeFileSync('foo.txt', '');
186 + let out = exec(`${JAKE_CMD} -q ` + key + ':test').toString().trim();
187 + // Should again run both prereq and test task
188 + let output = [
189 + 'created html'
190 + , 'ran test'
191 + ];
192 + assert.equal(output.join('\n'), out);
193 + //next();
194 + cleanUpAndNext(next);
195 + }, 1000); // Wait to do the touch to ensure mod-time is different
196 + });
197 +
198 + test('rule with existing objective file and no source ' +
199 + ' (should be normal file-task) (' + key + ')', function () {
200 + // Remove just the source file
201 + fs.writeFileSync('foo.html', '');
202 + rmRf('foo.txt', {silent: true});
203 + let out = exec(`${JAKE_CMD} -q ` + key + ':test').toString().trim();
204 + // Should treat existing objective file as plain file-task,
205 + // and just run test-task
206 + let output = [
207 + 'ran test'
208 + ];
209 + assert.equal(output.join('\n'), out);
210 + cleanUpAndNext();
211 + });
212 +
213 + });
214 +
215 +});
216 +
217 +
1 +let assert = require('assert');
2 +let exec = require('child_process').execSync;
3 +
4 +const PROJECT_DIR = process.env.PROJECT_DIR;
5 +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`;
6 +
7 +suite('selfDep', function () {
8 +
9 + this.timeout(7000);
10 +
11 + let origStderrWrite;
12 +
13 + setup(function () {
14 + origStderrWrite = process.stderr.write;
15 + process.stderr.write = function () {};
16 + });
17 +
18 + teardown(function () {
19 + process.stderr.write = origStderrWrite;
20 + });
21 +
22 + test('self dep const', function () {
23 + try {
24 + exec(`${JAKE_CMD} selfdepconst`);
25 + }
26 + catch(e) {
27 + assert(e.message.indexOf('dependency of itself') > -1)
28 + }
29 + });
30 +
31 + test('self dep dyn', function () {
32 + try {
33 + exec(`${JAKE_CMD} selfdepdyn`);
34 + }
35 + catch(e) {
36 + assert(e.message.indexOf('dependency of itself') > -1)
37 + }
38 + });
39 +
40 +});
41 +
42 +
1 +let assert = require('assert');
2 +let h = require('./helpers');
3 +let exec = require('child_process').execSync;
4 +
5 +const PROJECT_DIR = process.env.PROJECT_DIR;
6 +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`;
7 +
8 +suite('taskBase', function () {
9 +
10 + this.timeout(7000);
11 +
12 + test('default task', function () {
13 + let out;
14 + out = exec(`${JAKE_CMD} -q`).toString().trim();
15 + assert.equal(out, 'default task');
16 + out = exec(`${JAKE_CMD} -q default`).toString().trim();
17 + assert.equal(out, 'default task');
18 + });
19 +
20 + test('task with no action', function () {
21 + let out = exec(`${JAKE_CMD} -q noAction`).toString().trim();
22 + assert.equal(out, 'default task');
23 + });
24 +
25 + test('a task with no action and no prereqs', function () {
26 + exec(`${JAKE_CMD} noActionNoPrereqs`);
27 + });
28 +
29 + test('a task that exists at the top-level, and not in the specified namespace, should error', function () {
30 + let res = require('child_process').spawnSync(`${JAKE_CMD}`,
31 + ['asdfasdfasdf:zerbofrangazoomy']);
32 + let err = res.stderr.toString();
33 + assert.ok(err.indexOf('Unknown task' > -1));
34 + });
35 +
36 + test('passing args to a task', function () {
37 + let out = exec(`${JAKE_CMD} -q argsEnvVars[foo,bar]`).toString().trim();
38 + let parsed = h.parse(out);
39 + let args = parsed.args;
40 + assert.equal(args[0], 'foo');
41 + assert.equal(args[1], 'bar');
42 + });
43 +
44 + test('a task with environment vars', function () {
45 + let out = exec(`${JAKE_CMD} -q argsEnvVars foo=bar baz=qux`).toString().trim();
46 + let parsed = h.parse(out);
47 + let env = parsed.env;
48 + assert.equal(env.foo, 'bar');
49 + assert.equal(env.baz, 'qux');
50 + });
51 +
52 + test('passing args and using environment vars', function () {
53 + let out = exec(`${JAKE_CMD} -q argsEnvVars[foo,bar] foo=bar baz=qux`).toString().trim();
54 + let parsed = h.parse(out);
55 + let args = parsed.args;
56 + let env = parsed.env;
57 + assert.equal(args[0], 'foo');
58 + assert.equal(args[1], 'bar');
59 + assert.equal(env.foo, 'bar');
60 + assert.equal(env.baz, 'qux');
61 + });
62 +
63 + test('a simple prereq', function () {
64 + let out = exec(`${JAKE_CMD} -q foo:baz`).toString().trim();
65 + assert.equal(out, 'foo:bar task\nfoo:baz task');
66 + });
67 +
68 + test('a duplicate prereq only runs once', function () {
69 + let out = exec(`${JAKE_CMD} -q foo:asdf`).toString().trim();
70 + assert.equal(out, 'foo:bar task\nfoo:baz task\nfoo:asdf task');
71 + });
72 +
73 + test('a prereq with command-line args', function () {
74 + let out = exec(`${JAKE_CMD} -q foo:qux`).toString().trim();
75 + assert.equal(out, 'foo:bar[asdf,qwer] task\nfoo:qux task');
76 + });
77 +
78 + test('a prereq with args via invoke', function () {
79 + let out = exec(`${JAKE_CMD} -q foo:frang[zxcv,uiop]`).toString().trim();
80 + assert.equal(out, 'foo:bar[zxcv,uiop] task\nfoo:frang task');
81 + });
82 +
83 + test('a prereq with args via execute', function () {
84 + let out = exec(`${JAKE_CMD} -q foo:zerb[zxcv,uiop]`).toString().trim();
85 + assert.equal(out, 'foo:bar[zxcv,uiop] task\nfoo:zerb task');
86 + });
87 +
88 + test('repeating the task via execute', function () {
89 + let out = exec(`${JAKE_CMD} -q foo:voom`).toString().trim();
90 + assert.equal(out, 'foo:bar task\nfoo:bar task\ncomplete\ncomplete');
91 + });
92 +
93 + test('prereq execution-order', function () {
94 + let out = exec(`${JAKE_CMD} -q hoge:fuga`).toString().trim();
95 + assert.equal(out, 'hoge:hoge task\nhoge:piyo task\nhoge:fuga task');
96 + });
97 +
98 + test('basic async task', function () {
99 + let out = exec(`${JAKE_CMD} -q bar:bar`).toString().trim();
100 + assert.equal(out, 'bar:foo task\nbar:bar task');
101 + });
102 +
103 + test('promise async task', function () {
104 + let out = exec(`${JAKE_CMD} -q bar:dependOnpromise`).toString().trim();
105 + assert.equal(out, 'bar:promise task\nbar:dependOnpromise task saw value 123654');
106 + });
107 +
108 + test('failing promise async task', function () {
109 + try {
110 + exec(`${JAKE_CMD} -q bar:brokenPromise`);
111 + }
112 + catch(e) {
113 + assert(e.message.indexOf('Command failed') > -1);
114 + }
115 + });
116 +
117 + test('that current-prereq index gets reset', function () {
118 + let out = exec(`${JAKE_CMD} -q hoge:kira`).toString().trim();
119 + assert.equal(out, 'hoge:hoge task\nhoge:piyo task\nhoge:fuga task\n' +
120 + 'hoge:charan task\nhoge:gero task\nhoge:kira task');
121 + });
122 +
123 + test('modifying a task by adding prereq during execution', function () {
124 + let out = exec(`${JAKE_CMD} -q voom`).toString().trim();
125 + assert.equal(out, 2);
126 + });
127 +
128 + test('listening for task error-event', function () {
129 + try {
130 + exec(`${JAKE_CMD} -q vronk:groo`).toString().trim();
131 + }
132 + catch(e) {
133 + assert(e.message.indexOf('OMFGZONG') > -1);
134 + }
135 + });
136 +
137 + test('listening for jake error-event', function () {
138 + let out = exec(`${JAKE_CMD} -q throwy`).toString().trim();
139 + assert(out.indexOf('Emitted\nError: I am bad') > -1);
140 + });
141 +
142 + test('listening for jake unhandledRejection-event', function () {
143 + let out = exec(`${JAKE_CMD} -q promiseRejecter`).toString().trim();
144 + assert.equal(out, '<promise rejected on purpose>');
145 + });
146 +
147 + test('large number of same prereqs', function () {
148 + let out = exec(`${JAKE_CMD} -q large:same`).toString().trim();
149 + assert.equal(out, 'large:leaf\nlarge:same');
150 + });
151 +
152 + test('large number of different prereqs', function () {
153 + let out = exec(`${JAKE_CMD} -q large:different`).toString().trim();
154 + assert.equal(out, 'leaf-12\nleaf-123\nlarge:different');
155 + });
156 +
157 + test('large number of different prereqs', function () {
158 + let out = exec(`${JAKE_CMD} -q usingRequire:test`).toString().trim();
159 + assert.equal(out, 'howdy test');
160 + });
161 +
162 + test('modifying a namespace by adding a new task', function () {
163 + let out = exec(`${JAKE_CMD} -q one:two`).toString().trim();
164 + assert.equal('one:one\none:two', out);
165 + });
166 +
167 +});
1 +
2 +task('foo', function () {
3 + console.log('ran top-level foo');
4 +});
5 +
6 +task('bar', function () {
7 + console.log('ran top-level bar');
8 +});
9 +
10 +task('zerb', function () {
11 + console.log('ran zerb');
12 +});
13 +
14 +namespace('zooby', function () {
15 + task('zerp', function () {});
16 +
17 + task('derp', ['zerp'], function () {});
18 +
19 + namespace('frang', function () {
20 +
21 + namespace('w00t', function () {
22 + task('bar', function () {
23 + console.log('ran zooby:frang:w00t:bar');
24 + });
25 + });
26 +
27 + task('asdf', function () {});
28 + });
29 +
30 +});
31 +
32 +namespace('hurr', function () {
33 + namespace('durr');
34 +});
35 +
36 +
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +const PROJECT_DIR = process.env.PROJECT_DIR;
20 +
21 +// Load the jake global
22 +require(`${PROJECT_DIR}/lib/jake`);
23 +let { Namespace } = require(`${PROJECT_DIR}/lib/namespace`);
24 +
25 +require('./jakefile');
26 +
27 +let assert = require('assert');
28 +
29 +suite('namespace', function () {
30 +
31 + this.timeout(7000);
32 +
33 + test('resolve namespace by relative name', function () {
34 + let aaa, bbb, ccc;
35 + aaa = namespace('aaa', function () {
36 + bbb = namespace('bbb', function () {
37 + ccc = namespace('ccc', function () {
38 + });
39 + });
40 + });
41 +
42 + assert.ok(aaa, Namespace.ROOT_NAMESPACE.resolveNamespace('aaa'));
43 + assert.ok(bbb === aaa.resolveNamespace('bbb'));
44 + assert.ok(ccc === aaa.resolveNamespace('bbb:ccc'));
45 + });
46 +
47 + test('resolve task in sub-namespace by relative path', function () {
48 + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby');
49 + let task = curr.resolveTask('frang:w00t:bar');
50 + assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1);
51 + });
52 +
53 + test('prefer local to top-level', function () {
54 + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby:frang:w00t');
55 + let task = curr.resolveTask('bar');
56 + assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1);
57 + });
58 +
59 + test('does resolve top-level', function () {
60 + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby:frang:w00t');
61 + let task = curr.resolveTask('foo');
62 + assert.ok(task.action.toString().indexOf('top-level foo') > -1);
63 + });
64 +
65 + test('absolute lookup works from sub-namespaces', function () {
66 + let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('hurr:durr');
67 + let task = curr.resolveTask('zooby:frang:w00t:bar');
68 + assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1);
69 + });
70 +
71 + test('resolution miss with throw error', function () {
72 + let curr = Namespace.ROOT_NAMESPACE;
73 + let task = curr.resolveTask('asdf:qwer');
74 + assert.ok(!task);
75 + });
76 +
77 +});
1 +/*
2 + * Jake JavaScript build tool
3 + * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
4 + *
5 + * Licensed under the Apache License, Version 2.0 (the "License");
6 + * you may not use this file except in compliance with the License.
7 + * You may obtain a copy of the License at
8 + *
9 + * http://www.apache.org/licenses/LICENSE-2.0
10 + *
11 + * Unless required by applicable law or agreed to in writing, software
12 + * distributed under the License is distributed on an "AS IS" BASIS,
13 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 + * See the License for the specific language governing permissions and
15 + * limitations under the License.
16 + *
17 +*/
18 +
19 +const PROJECT_DIR = process.env.PROJECT_DIR;
20 +
21 +let parseargs = require(`${PROJECT_DIR}/lib/parseargs`);
22 +let assert = require('assert');
23 +let optsReg = [
24 + { full: 'directory',
25 + abbr: 'C',
26 + preempts: false,
27 + expectValue: true
28 + },
29 + { full: 'jakefile',
30 + abbr: 'f',
31 + preempts: false,
32 + expectValue: true
33 + },
34 + { full: 'tasks',
35 + abbr: 'T',
36 + preempts: true
37 + },
38 + { full: 'tasks',
39 + abbr: 'ls',
40 + preempts: true
41 + },
42 + { full: 'trace',
43 + abbr: 't',
44 + preempts: false,
45 + expectValue: false
46 + },
47 + { full: 'help',
48 + abbr: 'h',
49 + preempts: true
50 + },
51 + { full: 'version',
52 + abbr: 'V',
53 + preempts: true
54 + }
55 +];
56 +let p = new parseargs.Parser(optsReg);
57 +let z = function (s) { return s.split(' '); };
58 +let res;
59 +
60 +suite('parseargs', function () {
61 +
62 + test('long preemptive opt and val with equal-sign, ignore further opts', function () {
63 + res = p.parse(z('--tasks=foo --jakefile=asdf'));
64 + assert.equal('foo', res.opts.tasks);
65 + assert.equal(undefined, res.opts.jakefile);
66 + });
67 +
68 + test('long preemptive opt and val without equal-sign, ignore further opts', function () {
69 + res = p.parse(z('--tasks foo --jakefile=asdf'));
70 + assert.equal('foo', res.opts.tasks);
71 + assert.equal(undefined, res.opts.jakefile);
72 + });
73 +
74 + test('long preemptive opt and no val, ignore further opts', function () {
75 + res = p.parse(z('--tasks --jakefile=asdf'));
76 + assert.equal(true, res.opts.tasks);
77 + assert.equal(undefined, res.opts.jakefile);
78 + });
79 +
80 + test('preemptive opt with no val, should be true', function () {
81 + res = p.parse(z('-T'));
82 + assert.equal(true, res.opts.tasks);
83 + });
84 +
85 + test('preemptive opt with no val, should be true and ignore further opts', function () {
86 + res = p.parse(z('-T -f'));
87 + assert.equal(true, res.opts.tasks);
88 + assert.equal(undefined, res.opts.jakefile);
89 + });
90 +
91 + test('preemptive opt with val, should be val', function () {
92 + res = p.parse(z('-T zoobie -f foo/bar/baz'));
93 + assert.equal('zoobie', res.opts.tasks);
94 + assert.equal(undefined, res.opts.jakefile);
95 + });
96 +
97 + test('-f expects a value, -t does not (howdy is task-name)', function () {
98 + res = p.parse(z('-f zoobie -t howdy'));
99 + assert.equal('zoobie', res.opts.jakefile);
100 + assert.equal(true, res.opts.trace);
101 + assert.equal('howdy', res.taskNames[0]);
102 + });
103 +
104 + test('different order, -f expects a value, -t does not (howdy is task-name)', function () {
105 + res = p.parse(z('-f zoobie howdy -t'));
106 + assert.equal('zoobie', res.opts.jakefile);
107 + assert.equal(true, res.opts.trace);
108 + assert.equal('howdy', res.taskNames[0]);
109 + });
110 +
111 + test('-f expects a value, -t does not (foo=bar is env var)', function () {
112 + res = p.parse(z('-f zoobie -t foo=bar'));
113 + assert.equal('zoobie', res.opts.jakefile);
114 + assert.equal(true, res.opts.trace);
115 + assert.equal('bar', res.envVars.foo);
116 + assert.equal(undefined, res.taskNames[0]);
117 + });
118 +
119 + test('-f expects a value, -t does not (foo=bar is env-var, task-name follows)', function () {
120 + res = p.parse(z('-f zoobie -t howdy foo=bar'));
121 + assert.equal('zoobie', res.opts.jakefile);
122 + assert.equal(true, res.opts.trace);
123 + assert.equal('bar', res.envVars.foo);
124 + assert.equal('howdy', res.taskNames[0]);
125 + });
126 +
127 + test('-t does not expect a value, -f does (howdy is task-name)', function () {
128 + res = p.parse(z('-t howdy -f zoobie'));
129 + assert.equal(true, res.opts.trace);
130 + assert.equal('zoobie', res.opts.jakefile);
131 + assert.equal('howdy', res.taskNames[0]);
132 + });
133 +
134 + test('--trace does not expect a value, -f does (howdy is task-name)', function () {
135 + res = p.parse(z('--trace howdy --jakefile zoobie'));
136 + assert.equal(true, res.opts.trace);
137 + assert.equal('zoobie', res.opts.jakefile);
138 + assert.equal('howdy', res.taskNames[0]);
139 + });
140 +
141 + test('--trace does not expect a value (equal), -f does (throw howdy away)', function () {
142 + res = p.parse(z('--trace=howdy --jakefile=zoobie'));
143 + assert.equal(true, res.opts.trace);
144 + assert.equal('zoobie', res.opts.jakefile);
145 + assert.equal(undefined, res.taskNames[0]);
146 + });
147 +
148 + /*
149 +, test('task-name with positional args', function () {
150 + res = p.parse(z('foo:bar[asdf,qwer]'));
151 + assert.equal('asdf', p.taskArgs[0]);
152 + assert.equal('qwer', p.taskArgs[1]);
153 + }
154 +
155 +, test('opts, env vars, task-name with positional args', function () {
156 + res = p.parse(z('-f ./tests/Jakefile -t default[asdf,qwer] foo=bar'));
157 + assert.equal('./tests/Jakefile', res.opts.jakefile);
158 + assert.equal(true, res.opts.trace);
159 + assert.equal('bar', res.envVars.foo);
160 + assert.equal('default', res.taskName);
161 + assert.equal('asdf', p.taskArgs[0]);
162 + assert.equal('qwer', p.taskArgs[1]);
163 + }
164 +*/
165 +
166 +
167 +});
168 +
169 +
1 +Jake JavaScript build tool
2 +********************************************************************************
3 +If no flags are given, Jake looks for a Jakefile or Jakefile.js in the current directory.
4 +********************************************************************************
5 +{Usage}: jake [options ...] [env variables ...] target
6 +
7 +{Options}:
8 + -f, --jakefile FILE Use FILE as the Jakefile.
9 + -C, --directory DIRECTORY Change to DIRECTORY before running tasks.
10 + -B, --always-make Unconditionally make all targets.
11 + -T/-ls, --tasks Display the tasks (matching optional PATTERN) with descriptions, then exit.
12 + -J, --jakelibdir JAKELIBDIR Auto-import any .jake files in JAKELIBDIR. (default is \'jakelib\')
13 + -h, --help Display this help message.
14 + -V/-v, --version Display the Jake version.
15 + -ar, --allow-rejection Keep running even after unhandled promise rejection
16 +
1 +The ISC License
2 +
3 +Copyright (c) Isaac Z. Schlueter and Contributors
4 +
5 +Permission to use, copy, modify, and/or distribute this software for any
6 +purpose with or without fee is hereby granted, provided that the above
7 +copyright notice and this permission notice appear in all copies.
8 +
9 +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
15 +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1 +# minimatch
2 +
3 +A minimal matching utility.
4 +
5 +[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch)
6 +
7 +
8 +This is the matching library used internally by npm.
9 +
10 +It works by converting glob expressions into JavaScript `RegExp`
11 +objects.
12 +
13 +## Usage
14 +
15 +```javascript
16 +var minimatch = require("minimatch")
17 +
18 +minimatch("bar.foo", "*.foo") // true!
19 +minimatch("bar.foo", "*.bar") // false!
20 +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy!
21 +```
22 +
23 +## Features
24 +
25 +Supports these glob features:
26 +
27 +* Brace Expansion
28 +* Extended glob matching
29 +* "Globstar" `**` matching
30 +
31 +See:
32 +
33 +* `man sh`
34 +* `man bash`
35 +* `man 3 fnmatch`
36 +* `man 5 gitignore`
37 +
38 +## Minimatch Class
39 +
40 +Create a minimatch object by instantiating the `minimatch.Minimatch` class.
41 +
42 +```javascript
43 +var Minimatch = require("minimatch").Minimatch
44 +var mm = new Minimatch(pattern, options)
45 +```
46 +
47 +### Properties
48 +
49 +* `pattern` The original pattern the minimatch object represents.
50 +* `options` The options supplied to the constructor.
51 +* `set` A 2-dimensional array of regexp or string expressions.
52 + Each row in the
53 + array corresponds to a brace-expanded pattern. Each item in the row
54 + corresponds to a single path-part. For example, the pattern
55 + `{a,b/c}/d` would expand to a set of patterns like:
56 +
57 + [ [ a, d ]
58 + , [ b, c, d ] ]
59 +
60 + If a portion of the pattern doesn't have any "magic" in it
61 + (that is, it's something like `"foo"` rather than `fo*o?`), then it
62 + will be left as a string rather than converted to a regular
63 + expression.
64 +
65 +* `regexp` Created by the `makeRe` method. A single regular expression
66 + expressing the entire pattern. This is useful in cases where you wish
67 + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
68 +* `negate` True if the pattern is negated.
69 +* `comment` True if the pattern is a comment.
70 +* `empty` True if the pattern is `""`.
71 +
72 +### Methods
73 +
74 +* `makeRe` Generate the `regexp` member if necessary, and return it.
75 + Will return `false` if the pattern is invalid.
76 +* `match(fname)` Return true if the filename matches the pattern, or
77 + false otherwise.
78 +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split
79 + filename, and match it against a single row in the `regExpSet`. This
80 + method is mainly for internal use, but is exposed so that it can be
81 + used by a glob-walker that needs to avoid excessive filesystem calls.
82 +
83 +All other methods are internal, and will be called as necessary.
84 +
85 +### minimatch(path, pattern, options)
86 +
87 +Main export. Tests a path against the pattern using the options.
88 +
89 +```javascript
90 +var isJS = minimatch(file, "*.js", { matchBase: true })
91 +```
92 +
93 +### minimatch.filter(pattern, options)
94 +
95 +Returns a function that tests its
96 +supplied argument, suitable for use with `Array.filter`. Example:
97 +
98 +```javascript
99 +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true}))
100 +```
101 +
102 +### minimatch.match(list, pattern, options)
103 +
104 +Match against the list of
105 +files, in the style of fnmatch or glob. If nothing is matched, and
106 +options.nonull is set, then return a list containing the pattern itself.
107 +
108 +```javascript
109 +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true}))
110 +```
111 +
112 +### minimatch.makeRe(pattern, options)
113 +
114 +Make a regular expression object from the pattern.
115 +
116 +## Options
117 +
118 +All options are `false` by default.
119 +
120 +### debug
121 +
122 +Dump a ton of stuff to stderr.
123 +
124 +### nobrace
125 +
126 +Do not expand `{a,b}` and `{1..3}` brace sets.
127 +
128 +### noglobstar
129 +
130 +Disable `**` matching against multiple folder names.
131 +
132 +### dot
133 +
134 +Allow patterns to match filenames starting with a period, even if
135 +the pattern does not explicitly have a period in that spot.
136 +
137 +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
138 +is set.
139 +
140 +### noext
141 +
142 +Disable "extglob" style patterns like `+(a|b)`.
143 +
144 +### nocase
145 +
146 +Perform a case-insensitive match.
147 +
148 +### nonull
149 +
150 +When a match is not found by `minimatch.match`, return a list containing
151 +the pattern itself if this option is set. When not set, an empty list
152 +is returned if there are no matches.
153 +
154 +### matchBase
155 +
156 +If set, then patterns without slashes will be matched
157 +against the basename of the path if it contains slashes. For example,
158 +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
159 +
160 +### nocomment
161 +
162 +Suppress the behavior of treating `#` at the start of a pattern as a
163 +comment.
164 +
165 +### nonegate
166 +
167 +Suppress the behavior of treating a leading `!` character as negation.
168 +
169 +### flipNegate
170 +
171 +Returns from negate expressions the same as if they were not negated.
172 +(Ie, true on a hit, false on a miss.)
173 +
174 +### partial
175 +
176 +Compare a partial path to a pattern. As long as the parts of the path that
177 +are present are not contradicted by the pattern, it will be treated as a
178 +match. This is useful in applications where you're walking through a
179 +folder structure, and don't yet have the full path, but want to ensure that
180 +you do not walk down paths that can never be a match.
181 +
182 +For example,
183 +
184 +```js
185 +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d
186 +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d
187 +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a
188 +```
189 +
190 +### allowWindowsEscape
191 +
192 +Windows path separator `\` is by default converted to `/`, which
193 +prohibits the usage of `\` as a escape character. This flag skips that
194 +behavior and allows using the escape character.
195 +
196 +## Comparisons to other fnmatch/glob implementations
197 +
198 +While strict compliance with the existing standards is a worthwhile
199 +goal, some discrepancies exist between minimatch and other
200 +implementations, and are intentional.
201 +
202 +If the pattern starts with a `!` character, then it is negated. Set the
203 +`nonegate` flag to suppress this behavior, and treat leading `!`
204 +characters normally. This is perhaps relevant if you wish to start the
205 +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!`
206 +characters at the start of a pattern will negate the pattern multiple
207 +times.
208 +
209 +If a pattern starts with `#`, then it is treated as a comment, and
210 +will not match anything. Use `\#` to match a literal `#` at the
211 +start of a line, or set the `nocomment` flag to suppress this behavior.
212 +
213 +The double-star character `**` is supported by default, unless the
214 +`noglobstar` flag is set. This is supported in the manner of bsdglob
215 +and bash 4.1, where `**` only has special significance if it is the only
216 +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
217 +`a/**b` will not.
218 +
219 +If an escaped pattern has no matches, and the `nonull` flag is set,
220 +then minimatch.match returns the pattern as-provided, rather than
221 +interpreting the character escapes. For example,
222 +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
223 +`"*a?"`. This is akin to setting the `nullglob` option in bash, except
224 +that it does not resolve escaped pattern characters.
225 +
226 +If brace expansion is not disabled, then it is performed before any
227 +other interpretation of the glob pattern. Thus, a pattern like
228 +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
229 +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
230 +checked for validity. Since those two are valid, matching proceeds.
1 +module.exports = minimatch
2 +minimatch.Minimatch = Minimatch
3 +
4 +var path = (function () { try { return require('path') } catch (e) {}}()) || {
5 + sep: '/'
6 +}
7 +minimatch.sep = path.sep
8 +
9 +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
10 +var expand = require('brace-expansion')
11 +
12 +var plTypes = {
13 + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
14 + '?': { open: '(?:', close: ')?' },
15 + '+': { open: '(?:', close: ')+' },
16 + '*': { open: '(?:', close: ')*' },
17 + '@': { open: '(?:', close: ')' }
18 +}
19 +
20 +// any single thing other than /
21 +// don't need to escape / when using new RegExp()
22 +var qmark = '[^/]'
23 +
24 +// * => any number of characters
25 +var star = qmark + '*?'
26 +
27 +// ** when dots are allowed. Anything goes, except .. and .
28 +// not (^ or / followed by one or two dots followed by $ or /),
29 +// followed by anything, any number of times.
30 +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
31 +
32 +// not a ^ or / followed by a dot,
33 +// followed by anything, any number of times.
34 +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
35 +
36 +// characters that need to be escaped in RegExp.
37 +var reSpecials = charSet('().*{}+?[]^$\\!')
38 +
39 +// "abc" -> { a:true, b:true, c:true }
40 +function charSet (s) {
41 + return s.split('').reduce(function (set, c) {
42 + set[c] = true
43 + return set
44 + }, {})
45 +}
46 +
47 +// normalizes slashes.
48 +var slashSplit = /\/+/
49 +
50 +minimatch.filter = filter
51 +function filter (pattern, options) {
52 + options = options || {}
53 + return function (p, i, list) {
54 + return minimatch(p, pattern, options)
55 + }
56 +}
57 +
58 +function ext (a, b) {
59 + b = b || {}
60 + var t = {}
61 + Object.keys(a).forEach(function (k) {
62 + t[k] = a[k]
63 + })
64 + Object.keys(b).forEach(function (k) {
65 + t[k] = b[k]
66 + })
67 + return t
68 +}
69 +
70 +minimatch.defaults = function (def) {
71 + if (!def || typeof def !== 'object' || !Object.keys(def).length) {
72 + return minimatch
73 + }
74 +
75 + var orig = minimatch
76 +
77 + var m = function minimatch (p, pattern, options) {
78 + return orig(p, pattern, ext(def, options))
79 + }
80 +
81 + m.Minimatch = function Minimatch (pattern, options) {
82 + return new orig.Minimatch(pattern, ext(def, options))
83 + }
84 + m.Minimatch.defaults = function defaults (options) {
85 + return orig.defaults(ext(def, options)).Minimatch
86 + }
87 +
88 + m.filter = function filter (pattern, options) {
89 + return orig.filter(pattern, ext(def, options))
90 + }
91 +
92 + m.defaults = function defaults (options) {
93 + return orig.defaults(ext(def, options))
94 + }
95 +
96 + m.makeRe = function makeRe (pattern, options) {
97 + return orig.makeRe(pattern, ext(def, options))
98 + }
99 +
100 + m.braceExpand = function braceExpand (pattern, options) {
101 + return orig.braceExpand(pattern, ext(def, options))
102 + }
103 +
104 + m.match = function (list, pattern, options) {
105 + return orig.match(list, pattern, ext(def, options))
106 + }
107 +
108 + return m
109 +}
110 +
111 +Minimatch.defaults = function (def) {
112 + return minimatch.defaults(def).Minimatch
113 +}
114 +
115 +function minimatch (p, pattern, options) {
116 + assertValidPattern(pattern)
117 +
118 + if (!options) options = {}
119 +
120 + // shortcut: comments match nothing.
121 + if (!options.nocomment && pattern.charAt(0) === '#') {
122 + return false
123 + }
124 +
125 + return new Minimatch(pattern, options).match(p)
126 +}
127 +
128 +function Minimatch (pattern, options) {
129 + if (!(this instanceof Minimatch)) {
130 + return new Minimatch(pattern, options)
131 + }
132 +
133 + assertValidPattern(pattern)
134 +
135 + if (!options) options = {}
136 +
137 + pattern = pattern.trim()
138 +
139 + // windows support: need to use /, not \
140 + if (!options.allowWindowsEscape && path.sep !== '/') {
141 + pattern = pattern.split(path.sep).join('/')
142 + }
143 +
144 + this.options = options
145 + this.set = []
146 + this.pattern = pattern
147 + this.regexp = null
148 + this.negate = false
149 + this.comment = false
150 + this.empty = false
151 + this.partial = !!options.partial
152 +
153 + // make the set of regexps etc.
154 + this.make()
155 +}
156 +
157 +Minimatch.prototype.debug = function () {}
158 +
159 +Minimatch.prototype.make = make
160 +function make () {
161 + var pattern = this.pattern
162 + var options = this.options
163 +
164 + // empty patterns and comments match nothing.
165 + if (!options.nocomment && pattern.charAt(0) === '#') {
166 + this.comment = true
167 + return
168 + }
169 + if (!pattern) {
170 + this.empty = true
171 + return
172 + }
173 +
174 + // step 1: figure out negation, etc.
175 + this.parseNegate()
176 +
177 + // step 2: expand braces
178 + var set = this.globSet = this.braceExpand()
179 +
180 + if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
181 +
182 + this.debug(this.pattern, set)
183 +
184 + // step 3: now we have a set, so turn each one into a series of path-portion
185 + // matching patterns.
186 + // These will be regexps, except in the case of "**", which is
187 + // set to the GLOBSTAR object for globstar behavior,
188 + // and will not contain any / characters
189 + set = this.globParts = set.map(function (s) {
190 + return s.split(slashSplit)
191 + })
192 +
193 + this.debug(this.pattern, set)
194 +
195 + // glob --> regexps
196 + set = set.map(function (s, si, set) {
197 + return s.map(this.parse, this)
198 + }, this)
199 +
200 + this.debug(this.pattern, set)
201 +
202 + // filter out everything that didn't compile properly.
203 + set = set.filter(function (s) {
204 + return s.indexOf(false) === -1
205 + })
206 +
207 + this.debug(this.pattern, set)
208 +
209 + this.set = set
210 +}
211 +
212 +Minimatch.prototype.parseNegate = parseNegate
213 +function parseNegate () {
214 + var pattern = this.pattern
215 + var negate = false
216 + var options = this.options
217 + var negateOffset = 0
218 +
219 + if (options.nonegate) return
220 +
221 + for (var i = 0, l = pattern.length
222 + ; i < l && pattern.charAt(i) === '!'
223 + ; i++) {
224 + negate = !negate
225 + negateOffset++
226 + }
227 +
228 + if (negateOffset) this.pattern = pattern.substr(negateOffset)
229 + this.negate = negate
230 +}
231 +
232 +// Brace expansion:
233 +// a{b,c}d -> abd acd
234 +// a{b,}c -> abc ac
235 +// a{0..3}d -> a0d a1d a2d a3d
236 +// a{b,c{d,e}f}g -> abg acdfg acefg
237 +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
238 +//
239 +// Invalid sets are not expanded.
240 +// a{2..}b -> a{2..}b
241 +// a{b}c -> a{b}c
242 +minimatch.braceExpand = function (pattern, options) {
243 + return braceExpand(pattern, options)
244 +}
245 +
246 +Minimatch.prototype.braceExpand = braceExpand
247 +
248 +function braceExpand (pattern, options) {
249 + if (!options) {
250 + if (this instanceof Minimatch) {
251 + options = this.options
252 + } else {
253 + options = {}
254 + }
255 + }
256 +
257 + pattern = typeof pattern === 'undefined'
258 + ? this.pattern : pattern
259 +
260 + assertValidPattern(pattern)
261 +
262 + // Thanks to Yeting Li <https://github.com/yetingli> for
263 + // improving this regexp to avoid a ReDOS vulnerability.
264 + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
265 + // shortcut. no need to expand.
266 + return [pattern]
267 + }
268 +
269 + return expand(pattern)
270 +}
271 +
272 +var MAX_PATTERN_LENGTH = 1024 * 64
273 +var assertValidPattern = function (pattern) {
274 + if (typeof pattern !== 'string') {
275 + throw new TypeError('invalid pattern')
276 + }
277 +
278 + if (pattern.length > MAX_PATTERN_LENGTH) {
279 + throw new TypeError('pattern is too long')
280 + }
281 +}
282 +
283 +// parse a component of the expanded set.
284 +// At this point, no pattern may contain "/" in it
285 +// so we're going to return a 2d array, where each entry is the full
286 +// pattern, split on '/', and then turned into a regular expression.
287 +// A regexp is made at the end which joins each array with an
288 +// escaped /, and another full one which joins each regexp with |.
289 +//
290 +// Following the lead of Bash 4.1, note that "**" only has special meaning
291 +// when it is the *only* thing in a path portion. Otherwise, any series
292 +// of * is equivalent to a single *. Globstar behavior is enabled by
293 +// default, and can be disabled by setting options.noglobstar.
294 +Minimatch.prototype.parse = parse
295 +var SUBPARSE = {}
296 +function parse (pattern, isSub) {
297 + assertValidPattern(pattern)
298 +
299 + var options = this.options
300 +
301 + // shortcuts
302 + if (pattern === '**') {
303 + if (!options.noglobstar)
304 + return GLOBSTAR
305 + else
306 + pattern = '*'
307 + }
308 + if (pattern === '') return ''
309 +
310 + var re = ''
311 + var hasMagic = !!options.nocase
312 + var escaping = false
313 + // ? => one single character
314 + var patternListStack = []
315 + var negativeLists = []
316 + var stateChar
317 + var inClass = false
318 + var reClassStart = -1
319 + var classStart = -1
320 + // . and .. never match anything that doesn't start with .,
321 + // even when options.dot is set.
322 + var patternStart = pattern.charAt(0) === '.' ? '' // anything
323 + // not (start or / followed by . or .. followed by / or end)
324 + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
325 + : '(?!\\.)'
326 + var self = this
327 +
328 + function clearStateChar () {
329 + if (stateChar) {
330 + // we had some state-tracking character
331 + // that wasn't consumed by this pass.
332 + switch (stateChar) {
333 + case '*':
334 + re += star
335 + hasMagic = true
336 + break
337 + case '?':
338 + re += qmark
339 + hasMagic = true
340 + break
341 + default:
342 + re += '\\' + stateChar
343 + break
344 + }
345 + self.debug('clearStateChar %j %j', stateChar, re)
346 + stateChar = false
347 + }
348 + }
349 +
350 + for (var i = 0, len = pattern.length, c
351 + ; (i < len) && (c = pattern.charAt(i))
352 + ; i++) {
353 + this.debug('%s\t%s %s %j', pattern, i, re, c)
354 +
355 + // skip over any that are escaped.
356 + if (escaping && reSpecials[c]) {
357 + re += '\\' + c
358 + escaping = false
359 + continue
360 + }
361 +
362 + switch (c) {
363 + /* istanbul ignore next */
364 + case '/': {
365 + // completely not allowed, even escaped.
366 + // Should already be path-split by now.
367 + return false
368 + }
369 +
370 + case '\\':
371 + clearStateChar()
372 + escaping = true
373 + continue
374 +
375 + // the various stateChar values
376 + // for the "extglob" stuff.
377 + case '?':
378 + case '*':
379 + case '+':
380 + case '@':
381 + case '!':
382 + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
383 +
384 + // all of those are literals inside a class, except that
385 + // the glob [!a] means [^a] in regexp
386 + if (inClass) {
387 + this.debug(' in class')
388 + if (c === '!' && i === classStart + 1) c = '^'
389 + re += c
390 + continue
391 + }
392 +
393 + // if we already have a stateChar, then it means
394 + // that there was something like ** or +? in there.
395 + // Handle the stateChar, then proceed with this one.
396 + self.debug('call clearStateChar %j', stateChar)
397 + clearStateChar()
398 + stateChar = c
399 + // if extglob is disabled, then +(asdf|foo) isn't a thing.
400 + // just clear the statechar *now*, rather than even diving into
401 + // the patternList stuff.
402 + if (options.noext) clearStateChar()
403 + continue
404 +
405 + case '(':
406 + if (inClass) {
407 + re += '('
408 + continue
409 + }
410 +
411 + if (!stateChar) {
412 + re += '\\('
413 + continue
414 + }
415 +
416 + patternListStack.push({
417 + type: stateChar,
418 + start: i - 1,
419 + reStart: re.length,
420 + open: plTypes[stateChar].open,
421 + close: plTypes[stateChar].close
422 + })
423 + // negation is (?:(?!js)[^/]*)
424 + re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
425 + this.debug('plType %j %j', stateChar, re)
426 + stateChar = false
427 + continue
428 +
429 + case ')':
430 + if (inClass || !patternListStack.length) {
431 + re += '\\)'
432 + continue
433 + }
434 +
435 + clearStateChar()
436 + hasMagic = true
437 + var pl = patternListStack.pop()
438 + // negation is (?:(?!js)[^/]*)
439 + // The others are (?:<pattern>)<type>
440 + re += pl.close
441 + if (pl.type === '!') {
442 + negativeLists.push(pl)
443 + }
444 + pl.reEnd = re.length
445 + continue
446 +
447 + case '|':
448 + if (inClass || !patternListStack.length || escaping) {
449 + re += '\\|'
450 + escaping = false
451 + continue
452 + }
453 +
454 + clearStateChar()
455 + re += '|'
456 + continue
457 +
458 + // these are mostly the same in regexp and glob
459 + case '[':
460 + // swallow any state-tracking char before the [
461 + clearStateChar()
462 +
463 + if (inClass) {
464 + re += '\\' + c
465 + continue
466 + }
467 +
468 + inClass = true
469 + classStart = i
470 + reClassStart = re.length
471 + re += c
472 + continue
473 +
474 + case ']':
475 + // a right bracket shall lose its special
476 + // meaning and represent itself in
477 + // a bracket expression if it occurs
478 + // first in the list. -- POSIX.2 2.8.3.2
479 + if (i === classStart + 1 || !inClass) {
480 + re += '\\' + c
481 + escaping = false
482 + continue
483 + }
484 +
485 + // handle the case where we left a class open.
486 + // "[z-a]" is valid, equivalent to "\[z-a\]"
487 + // split where the last [ was, make sure we don't have
488 + // an invalid re. if so, re-walk the contents of the
489 + // would-be class to re-translate any characters that
490 + // were passed through as-is
491 + // TODO: It would probably be faster to determine this
492 + // without a try/catch and a new RegExp, but it's tricky
493 + // to do safely. For now, this is safe and works.
494 + var cs = pattern.substring(classStart + 1, i)
495 + try {
496 + RegExp('[' + cs + ']')
497 + } catch (er) {
498 + // not a valid class!
499 + var sp = this.parse(cs, SUBPARSE)
500 + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
501 + hasMagic = hasMagic || sp[1]
502 + inClass = false
503 + continue
504 + }
505 +
506 + // finish up the class.
507 + hasMagic = true
508 + inClass = false
509 + re += c
510 + continue
511 +
512 + default:
513 + // swallow any state char that wasn't consumed
514 + clearStateChar()
515 +
516 + if (escaping) {
517 + // no need
518 + escaping = false
519 + } else if (reSpecials[c]
520 + && !(c === '^' && inClass)) {
521 + re += '\\'
522 + }
523 +
524 + re += c
525 +
526 + } // switch
527 + } // for
528 +
529 + // handle the case where we left a class open.
530 + // "[abc" is valid, equivalent to "\[abc"
531 + if (inClass) {
532 + // split where the last [ was, and escape it
533 + // this is a huge pita. We now have to re-walk
534 + // the contents of the would-be class to re-translate
535 + // any characters that were passed through as-is
536 + cs = pattern.substr(classStart + 1)
537 + sp = this.parse(cs, SUBPARSE)
538 + re = re.substr(0, reClassStart) + '\\[' + sp[0]
539 + hasMagic = hasMagic || sp[1]
540 + }
541 +
542 + // handle the case where we had a +( thing at the *end*
543 + // of the pattern.
544 + // each pattern list stack adds 3 chars, and we need to go through
545 + // and escape any | chars that were passed through as-is for the regexp.
546 + // Go through and escape them, taking care not to double-escape any
547 + // | chars that were already escaped.
548 + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
549 + var tail = re.slice(pl.reStart + pl.open.length)
550 + this.debug('setting tail', re, pl)
551 + // maybe some even number of \, then maybe 1 \, followed by a |
552 + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
553 + if (!$2) {
554 + // the | isn't already escaped, so escape it.
555 + $2 = '\\'
556 + }
557 +
558 + // need to escape all those slashes *again*, without escaping the
559 + // one that we need for escaping the | character. As it works out,
560 + // escaping an even number of slashes can be done by simply repeating
561 + // it exactly after itself. That's why this trick works.
562 + //
563 + // I am sorry that you have to see this.
564 + return $1 + $1 + $2 + '|'
565 + })
566 +
567 + this.debug('tail=%j\n %s', tail, tail, pl, re)
568 + var t = pl.type === '*' ? star
569 + : pl.type === '?' ? qmark
570 + : '\\' + pl.type
571 +
572 + hasMagic = true
573 + re = re.slice(0, pl.reStart) + t + '\\(' + tail
574 + }
575 +
576 + // handle trailing things that only matter at the very end.
577 + clearStateChar()
578 + if (escaping) {
579 + // trailing \\
580 + re += '\\\\'
581 + }
582 +
583 + // only need to apply the nodot start if the re starts with
584 + // something that could conceivably capture a dot
585 + var addPatternStart = false
586 + switch (re.charAt(0)) {
587 + case '[': case '.': case '(': addPatternStart = true
588 + }
589 +
590 + // Hack to work around lack of negative lookbehind in JS
591 + // A pattern like: *.!(x).!(y|z) needs to ensure that a name
592 + // like 'a.xyz.yz' doesn't match. So, the first negative
593 + // lookahead, has to look ALL the way ahead, to the end of
594 + // the pattern.
595 + for (var n = negativeLists.length - 1; n > -1; n--) {
596 + var nl = negativeLists[n]
597 +
598 + var nlBefore = re.slice(0, nl.reStart)
599 + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
600 + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
601 + var nlAfter = re.slice(nl.reEnd)
602 +
603 + nlLast += nlAfter
604 +
605 + // Handle nested stuff like *(*.js|!(*.json)), where open parens
606 + // mean that we should *not* include the ) in the bit that is considered
607 + // "after" the negated section.
608 + var openParensBefore = nlBefore.split('(').length - 1
609 + var cleanAfter = nlAfter
610 + for (i = 0; i < openParensBefore; i++) {
611 + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
612 + }
613 + nlAfter = cleanAfter
614 +
615 + var dollar = ''
616 + if (nlAfter === '' && isSub !== SUBPARSE) {
617 + dollar = '$'
618 + }
619 + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
620 + re = newRe
621 + }
622 +
623 + // if the re is not "" at this point, then we need to make sure
624 + // it doesn't match against an empty path part.
625 + // Otherwise a/* will match a/, which it should not.
626 + if (re !== '' && hasMagic) {
627 + re = '(?=.)' + re
628 + }
629 +
630 + if (addPatternStart) {
631 + re = patternStart + re
632 + }
633 +
634 + // parsing just a piece of a larger pattern.
635 + if (isSub === SUBPARSE) {
636 + return [re, hasMagic]
637 + }
638 +
639 + // skip the regexp for non-magical patterns
640 + // unescape anything in it, though, so that it'll be
641 + // an exact match against a file etc.
642 + if (!hasMagic) {
643 + return globUnescape(pattern)
644 + }
645 +
646 + var flags = options.nocase ? 'i' : ''
647 + try {
648 + var regExp = new RegExp('^' + re + '$', flags)
649 + } catch (er) /* istanbul ignore next - should be impossible */ {
650 + // If it was an invalid regular expression, then it can't match
651 + // anything. This trick looks for a character after the end of
652 + // the string, which is of course impossible, except in multi-line
653 + // mode, but it's not a /m regex.
654 + return new RegExp('$.')
655 + }
656 +
657 + regExp._glob = pattern
658 + regExp._src = re
659 +
660 + return regExp
661 +}
662 +
663 +minimatch.makeRe = function (pattern, options) {
664 + return new Minimatch(pattern, options || {}).makeRe()
665 +}
666 +
667 +Minimatch.prototype.makeRe = makeRe
668 +function makeRe () {
669 + if (this.regexp || this.regexp === false) return this.regexp
670 +
671 + // at this point, this.set is a 2d array of partial
672 + // pattern strings, or "**".
673 + //
674 + // It's better to use .match(). This function shouldn't
675 + // be used, really, but it's pretty convenient sometimes,
676 + // when you just want to work with a regex.
677 + var set = this.set
678 +
679 + if (!set.length) {
680 + this.regexp = false
681 + return this.regexp
682 + }
683 + var options = this.options
684 +
685 + var twoStar = options.noglobstar ? star
686 + : options.dot ? twoStarDot
687 + : twoStarNoDot
688 + var flags = options.nocase ? 'i' : ''
689 +
690 + var re = set.map(function (pattern) {
691 + return pattern.map(function (p) {
692 + return (p === GLOBSTAR) ? twoStar
693 + : (typeof p === 'string') ? regExpEscape(p)
694 + : p._src
695 + }).join('\\\/')
696 + }).join('|')
697 +
698 + // must match entire pattern
699 + // ending in a * or ** will make it less strict.
700 + re = '^(?:' + re + ')$'
701 +
702 + // can match anything, as long as it's not this.
703 + if (this.negate) re = '^(?!' + re + ').*$'
704 +
705 + try {
706 + this.regexp = new RegExp(re, flags)
707 + } catch (ex) /* istanbul ignore next - should be impossible */ {
708 + this.regexp = false
709 + }
710 + return this.regexp
711 +}
712 +
713 +minimatch.match = function (list, pattern, options) {
714 + options = options || {}
715 + var mm = new Minimatch(pattern, options)
716 + list = list.filter(function (f) {
717 + return mm.match(f)
718 + })
719 + if (mm.options.nonull && !list.length) {
720 + list.push(pattern)
721 + }
722 + return list
723 +}
724 +
725 +Minimatch.prototype.match = function match (f, partial) {
726 + if (typeof partial === 'undefined') partial = this.partial
727 + this.debug('match', f, this.pattern)
728 + // short-circuit in the case of busted things.
729 + // comments, etc.
730 + if (this.comment) return false
731 + if (this.empty) return f === ''
732 +
733 + if (f === '/' && partial) return true
734 +
735 + var options = this.options
736 +
737 + // windows: need to use /, not \
738 + if (path.sep !== '/') {
739 + f = f.split(path.sep).join('/')
740 + }
741 +
742 + // treat the test path as a set of pathparts.
743 + f = f.split(slashSplit)
744 + this.debug(this.pattern, 'split', f)
745 +
746 + // just ONE of the pattern sets in this.set needs to match
747 + // in order for it to be valid. If negating, then just one
748 + // match means that we have failed.
749 + // Either way, return on the first hit.
750 +
751 + var set = this.set
752 + this.debug(this.pattern, 'set', set)
753 +
754 + // Find the basename of the path by looking for the last non-empty segment
755 + var filename
756 + var i
757 + for (i = f.length - 1; i >= 0; i--) {
758 + filename = f[i]
759 + if (filename) break
760 + }
761 +
762 + for (i = 0; i < set.length; i++) {
763 + var pattern = set[i]
764 + var file = f
765 + if (options.matchBase && pattern.length === 1) {
766 + file = [filename]
767 + }
768 + var hit = this.matchOne(file, pattern, partial)
769 + if (hit) {
770 + if (options.flipNegate) return true
771 + return !this.negate
772 + }
773 + }
774 +
775 + // didn't get any hits. this is success if it's a negative
776 + // pattern, failure otherwise.
777 + if (options.flipNegate) return false
778 + return this.negate
779 +}
780 +
781 +// set partial to true to test if, for example,
782 +// "/a/b" matches the start of "/*/b/*/d"
783 +// Partial means, if you run out of file before you run
784 +// out of pattern, then that's fine, as long as all
785 +// the parts match.
786 +Minimatch.prototype.matchOne = function (file, pattern, partial) {
787 + var options = this.options
788 +
789 + this.debug('matchOne',
790 + { 'this': this, file: file, pattern: pattern })
791 +
792 + this.debug('matchOne', file.length, pattern.length)
793 +
794 + for (var fi = 0,
795 + pi = 0,
796 + fl = file.length,
797 + pl = pattern.length
798 + ; (fi < fl) && (pi < pl)
799 + ; fi++, pi++) {
800 + this.debug('matchOne loop')
801 + var p = pattern[pi]
802 + var f = file[fi]
803 +
804 + this.debug(pattern, p, f)
805 +
806 + // should be impossible.
807 + // some invalid regexp stuff in the set.
808 + /* istanbul ignore if */
809 + if (p === false) return false
810 +
811 + if (p === GLOBSTAR) {
812 + this.debug('GLOBSTAR', [pattern, p, f])
813 +
814 + // "**"
815 + // a/**/b/**/c would match the following:
816 + // a/b/x/y/z/c
817 + // a/x/y/z/b/c
818 + // a/b/x/b/x/c
819 + // a/b/c
820 + // To do this, take the rest of the pattern after
821 + // the **, and see if it would match the file remainder.
822 + // If so, return success.
823 + // If not, the ** "swallows" a segment, and try again.
824 + // This is recursively awful.
825 + //
826 + // a/**/b/**/c matching a/b/x/y/z/c
827 + // - a matches a
828 + // - doublestar
829 + // - matchOne(b/x/y/z/c, b/**/c)
830 + // - b matches b
831 + // - doublestar
832 + // - matchOne(x/y/z/c, c) -> no
833 + // - matchOne(y/z/c, c) -> no
834 + // - matchOne(z/c, c) -> no
835 + // - matchOne(c, c) yes, hit
836 + var fr = fi
837 + var pr = pi + 1
838 + if (pr === pl) {
839 + this.debug('** at the end')
840 + // a ** at the end will just swallow the rest.
841 + // We have found a match.
842 + // however, it will not swallow /.x, unless
843 + // options.dot is set.
844 + // . and .. are *never* matched by **, for explosively
845 + // exponential reasons.
846 + for (; fi < fl; fi++) {
847 + if (file[fi] === '.' || file[fi] === '..' ||
848 + (!options.dot && file[fi].charAt(0) === '.')) return false
849 + }
850 + return true
851 + }
852 +
853 + // ok, let's see if we can swallow whatever we can.
854 + while (fr < fl) {
855 + var swallowee = file[fr]
856 +
857 + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
858 +
859 + // XXX remove this slice. Just pass the start index.
860 + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
861 + this.debug('globstar found match!', fr, fl, swallowee)
862 + // found a match.
863 + return true
864 + } else {
865 + // can't swallow "." or ".." ever.
866 + // can only swallow ".foo" when explicitly asked.
867 + if (swallowee === '.' || swallowee === '..' ||
868 + (!options.dot && swallowee.charAt(0) === '.')) {
869 + this.debug('dot detected!', file, fr, pattern, pr)
870 + break
871 + }
872 +
873 + // ** swallows a segment, and continue.
874 + this.debug('globstar swallow a segment, and continue')
875 + fr++
876 + }
877 + }
878 +
879 + // no match was found.
880 + // However, in partial mode, we can't say this is necessarily over.
881 + // If there's more *pattern* left, then
882 + /* istanbul ignore if */
883 + if (partial) {
884 + // ran out of file
885 + this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
886 + if (fr === fl) return true
887 + }
888 + return false
889 + }
890 +
891 + // something other than **
892 + // non-magic patterns just have to match exactly
893 + // patterns with magic have been turned into regexps.
894 + var hit
895 + if (typeof p === 'string') {
896 + hit = f === p
897 + this.debug('string match', p, f, hit)
898 + } else {
899 + hit = f.match(p)
900 + this.debug('pattern match', p, f, hit)
901 + }
902 +
903 + if (!hit) return false
904 + }
905 +
906 + // Note: ending in / means that we'll get a final ""
907 + // at the end of the pattern. This can only match a
908 + // corresponding "" at the end of the file.
909 + // If the file ends in /, then it can only match a
910 + // a pattern that ends in /, unless the pattern just
911 + // doesn't have any more for it. But, a/b/ should *not*
912 + // match "a/b/*", even though "" matches against the
913 + // [^/]*? pattern, except in partial mode, where it might
914 + // simply not be reached yet.
915 + // However, a/b/ should still satisfy a/*
916 +
917 + // now either we fell off the end of the pattern, or we're done.
918 + if (fi === fl && pi === pl) {
919 + // ran out of pattern and filename at the same time.
920 + // an exact hit!
921 + return true
922 + } else if (fi === fl) {
923 + // ran out of file, but still had pattern left.
924 + // this is ok if we're doing the match as part of
925 + // a glob fs traversal.
926 + return partial
927 + } else /* istanbul ignore else */ if (pi === pl) {
928 + // ran out of pattern, still have file left.
929 + // this is only acceptable if we're on the very last
930 + // empty segment of a file with a trailing slash.
931 + // a/* should match a/b/
932 + return (fi === fl - 1) && (file[fi] === '')
933 + }
934 +
935 + // should be unreachable.
936 + /* istanbul ignore next */
937 + throw new Error('wtf?')
938 +}
939 +
940 +// replace stuff like \* with *
941 +function globUnescape (s) {
942 + return s.replace(/\\(.)/g, '$1')
943 +}
944 +
945 +function regExpEscape (s) {
946 + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
947 +}
1 +MIT License
2 +
3 +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +SOFTWARE.
1 +# brace-expansion
2 +
3 +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
4 +as known from sh/bash, in JavaScript.
5 +
6 +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
7 +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
8 +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)
9 +
10 +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
11 +
12 +## Example
13 +
14 +```js
15 +var expand = require('brace-expansion');
16 +
17 +expand('file-{a,b,c}.jpg')
18 +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
19 +
20 +expand('-v{,,}')
21 +// => ['-v', '-v', '-v']
22 +
23 +expand('file{0..2}.jpg')
24 +// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
25 +
26 +expand('file-{a..c}.jpg')
27 +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
28 +
29 +expand('file{2..0}.jpg')
30 +// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
31 +
32 +expand('file{0..4..2}.jpg')
33 +// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
34 +
35 +expand('file-{a..e..2}.jpg')
36 +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
37 +
38 +expand('file{00..10..5}.jpg')
39 +// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
40 +
41 +expand('{{A..C},{a..c}}')
42 +// => ['A', 'B', 'C', 'a', 'b', 'c']
43 +
44 +expand('ppp{,config,oe{,conf}}')
45 +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
46 +```
47 +
48 +## API
49 +
50 +```js
51 +var expand = require('brace-expansion');
52 +```
53 +
54 +### var expanded = expand(str)
55 +
56 +Return an array of all possible and valid expansions of `str`. If none are
57 +found, `[str]` is returned.
58 +
59 +Valid expansions are:
60 +
61 +```js
62 +/^(.*,)+(.+)?$/
63 +// {a,b,...}
64 +```
65 +
66 +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
67 +
68 +```js
69 +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
70 +// {x..y[..incr]}
71 +```
72 +
73 +A numeric sequence from `x` to `y` inclusive, with optional increment.
74 +If `x` or `y` start with a leading `0`, all the numbers will be padded
75 +to have equal length. Negative numbers and backwards iteration work too.
76 +
77 +```js
78 +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
79 +// {x..y[..incr]}
80 +```
81 +
82 +An alphabetic sequence from `x` to `y` inclusive, with optional increment.
83 +`x` and `y` must be exactly one character, and if given, `incr` must be a
84 +number.
85 +
86 +For compatibility reasons, the string `${` is not eligible for brace expansion.
87 +
88 +## Installation
89 +
90 +With [npm](https://npmjs.org) do:
91 +
92 +```bash
93 +npm install brace-expansion
94 +```
95 +
96 +## Contributors
97 +
98 +- [Julian Gruber](https://github.com/juliangruber)
99 +- [Isaac Z. Schlueter](https://github.com/isaacs)
100 +
101 +## Sponsors
102 +
103 +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!
104 +
105 +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!
106 +
107 +## License
108 +
109 +(MIT)
110 +
111 +Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
112 +
113 +Permission is hereby granted, free of charge, to any person obtaining a copy of
114 +this software and associated documentation files (the "Software"), to deal in
115 +the Software without restriction, including without limitation the rights to
116 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
117 +of the Software, and to permit persons to whom the Software is furnished to do
118 +so, subject to the following conditions:
119 +
120 +The above copyright notice and this permission notice shall be included in all
121 +copies or substantial portions of the Software.
122 +
123 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
124 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
125 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
126 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
127 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
128 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
129 +SOFTWARE.
1 +var concatMap = require('concat-map');
2 +var balanced = require('balanced-match');
3 +
4 +module.exports = expandTop;
5 +
6 +var escSlash = '\0SLASH'+Math.random()+'\0';
7 +var escOpen = '\0OPEN'+Math.random()+'\0';
8 +var escClose = '\0CLOSE'+Math.random()+'\0';
9 +var escComma = '\0COMMA'+Math.random()+'\0';
10 +var escPeriod = '\0PERIOD'+Math.random()+'\0';
11 +
12 +function numeric(str) {
13 + return parseInt(str, 10) == str
14 + ? parseInt(str, 10)
15 + : str.charCodeAt(0);
16 +}
17 +
18 +function escapeBraces(str) {
19 + return str.split('\\\\').join(escSlash)
20 + .split('\\{').join(escOpen)
21 + .split('\\}').join(escClose)
22 + .split('\\,').join(escComma)
23 + .split('\\.').join(escPeriod);
24 +}
25 +
26 +function unescapeBraces(str) {
27 + return str.split(escSlash).join('\\')
28 + .split(escOpen).join('{')
29 + .split(escClose).join('}')
30 + .split(escComma).join(',')
31 + .split(escPeriod).join('.');
32 +}
33 +
34 +
35 +// Basically just str.split(","), but handling cases
36 +// where we have nested braced sections, which should be
37 +// treated as individual members, like {a,{b,c},d}
38 +function parseCommaParts(str) {
39 + if (!str)
40 + return [''];
41 +
42 + var parts = [];
43 + var m = balanced('{', '}', str);
44 +
45 + if (!m)
46 + return str.split(',');
47 +
48 + var pre = m.pre;
49 + var body = m.body;
50 + var post = m.post;
51 + var p = pre.split(',');
52 +
53 + p[p.length-1] += '{' + body + '}';
54 + var postParts = parseCommaParts(post);
55 + if (post.length) {
56 + p[p.length-1] += postParts.shift();
57 + p.push.apply(p, postParts);
58 + }
59 +
60 + parts.push.apply(parts, p);
61 +
62 + return parts;
63 +}
64 +
65 +function expandTop(str) {
66 + if (!str)
67 + return [];
68 +
69 + // I don't know why Bash 4.3 does this, but it does.
70 + // Anything starting with {} will have the first two bytes preserved
71 + // but *only* at the top level, so {},a}b will not expand to anything,
72 + // but a{},b}c will be expanded to [a}c,abc].
73 + // One could argue that this is a bug in Bash, but since the goal of
74 + // this module is to match Bash's rules, we escape a leading {}
75 + if (str.substr(0, 2) === '{}') {
76 + str = '\\{\\}' + str.substr(2);
77 + }
78 +
79 + return expand(escapeBraces(str), true).map(unescapeBraces);
80 +}
81 +
82 +function identity(e) {
83 + return e;
84 +}
85 +
86 +function embrace(str) {
87 + return '{' + str + '}';
88 +}
89 +function isPadded(el) {
90 + return /^-?0\d/.test(el);
91 +}
92 +
93 +function lte(i, y) {
94 + return i <= y;
95 +}
96 +function gte(i, y) {
97 + return i >= y;
98 +}
99 +
100 +function expand(str, isTop) {
101 + var expansions = [];
102 +
103 + var m = balanced('{', '}', str);
104 + if (!m || /\$$/.test(m.pre)) return [str];
105 +
106 + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
107 + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
108 + var isSequence = isNumericSequence || isAlphaSequence;
109 + var isOptions = m.body.indexOf(',') >= 0;
110 + if (!isSequence && !isOptions) {
111 + // {a},b}
112 + if (m.post.match(/,.*\}/)) {
113 + str = m.pre + '{' + m.body + escClose + m.post;
114 + return expand(str);
115 + }
116 + return [str];
117 + }
118 +
119 + var n;
120 + if (isSequence) {
121 + n = m.body.split(/\.\./);
122 + } else {
123 + n = parseCommaParts(m.body);
124 + if (n.length === 1) {
125 + // x{{a,b}}y ==> x{a}y x{b}y
126 + n = expand(n[0], false).map(embrace);
127 + if (n.length === 1) {
128 + var post = m.post.length
129 + ? expand(m.post, false)
130 + : [''];
131 + return post.map(function(p) {
132 + return m.pre + n[0] + p;
133 + });
134 + }
135 + }
136 + }
137 +
138 + // at this point, n is the parts, and we know it's not a comma set
139 + // with a single entry.
140 +
141 + // no need to expand pre, since it is guaranteed to be free of brace-sets
142 + var pre = m.pre;
143 + var post = m.post.length
144 + ? expand(m.post, false)
145 + : [''];
146 +
147 + var N;
148 +
149 + if (isSequence) {
150 + var x = numeric(n[0]);
151 + var y = numeric(n[1]);
152 + var width = Math.max(n[0].length, n[1].length)
153 + var incr = n.length == 3
154 + ? Math.abs(numeric(n[2]))
155 + : 1;
156 + var test = lte;
157 + var reverse = y < x;
158 + if (reverse) {
159 + incr *= -1;
160 + test = gte;
161 + }
162 + var pad = n.some(isPadded);
163 +
164 + N = [];
165 +
166 + for (var i = x; test(i, y); i += incr) {
167 + var c;
168 + if (isAlphaSequence) {
169 + c = String.fromCharCode(i);
170 + if (c === '\\')
171 + c = '';
172 + } else {
173 + c = String(i);
174 + if (pad) {
175 + var need = width - c.length;
176 + if (need > 0) {
177 + var z = new Array(need + 1).join('0');
178 + if (i < 0)
179 + c = '-' + z + c.slice(1);
180 + else
181 + c = z + c;
182 + }
183 + }
184 + }
185 + N.push(c);
186 + }
187 + } else {
188 + N = concatMap(n, function(el) { return expand(el, false) });
189 + }
190 +
191 + for (var j = 0; j < N.length; j++) {
192 + for (var k = 0; k < post.length; k++) {
193 + var expansion = pre + N[j] + post[k];
194 + if (!isTop || isSequence || expansion)
195 + expansions.push(expansion);
196 + }
197 + }
198 +
199 + return expansions;
200 +}
201 +
1 +{
2 + "_from": "brace-expansion@^1.1.7",
3 + "_id": "brace-expansion@1.1.11",
4 + "_inBundle": false,
5 + "_integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
6 + "_location": "/minimatch/brace-expansion",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "brace-expansion@^1.1.7",
12 + "name": "brace-expansion",
13 + "escapedName": "brace-expansion",
14 + "rawSpec": "^1.1.7",
15 + "saveSpec": null,
16 + "fetchSpec": "^1.1.7"
17 + },
18 + "_requiredBy": [
19 + "/minimatch"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
22 + "_shasum": "3c7fcbf529d87226f3d2f52b966ff5271eb441dd",
23 + "_spec": "brace-expansion@^1.1.7",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\minimatch",
25 + "author": {
26 + "name": "Julian Gruber",
27 + "email": "mail@juliangruber.com",
28 + "url": "http://juliangruber.com"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/juliangruber/brace-expansion/issues"
32 + },
33 + "bundleDependencies": false,
34 + "dependencies": {
35 + "balanced-match": "^1.0.0",
36 + "concat-map": "0.0.1"
37 + },
38 + "deprecated": false,
39 + "description": "Brace expansion as known from sh/bash",
40 + "devDependencies": {
41 + "matcha": "^0.7.0",
42 + "tape": "^4.6.0"
43 + },
44 + "homepage": "https://github.com/juliangruber/brace-expansion",
45 + "keywords": [],
46 + "license": "MIT",
47 + "main": "index.js",
48 + "name": "brace-expansion",
49 + "repository": {
50 + "type": "git",
51 + "url": "git://github.com/juliangruber/brace-expansion.git"
52 + },
53 + "scripts": {
54 + "bench": "matcha test/perf/bench.js",
55 + "gentest": "bash test/generate.sh",
56 + "test": "tape test/*.js"
57 + },
58 + "testling": {
59 + "files": "test/*.js",
60 + "browsers": [
61 + "ie/8..latest",
62 + "firefox/20..latest",
63 + "firefox/nightly",
64 + "chrome/25..latest",
65 + "chrome/canary",
66 + "opera/12..latest",
67 + "opera/next",
68 + "safari/5.1..latest",
69 + "ipad/6.0..latest",
70 + "iphone/6.0..latest",
71 + "android-browser/4.2..latest"
72 + ]
73 + },
74 + "version": "1.1.11"
75 +}
1 +{
2 + "_from": "minimatch@^3.0.4",
3 + "_id": "minimatch@3.1.2",
4 + "_inBundle": false,
5 + "_integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
6 + "_location": "/minimatch",
7 + "_phantomChildren": {
8 + "balanced-match": "1.0.2",
9 + "concat-map": "0.0.1"
10 + },
11 + "_requested": {
12 + "type": "range",
13 + "registry": true,
14 + "raw": "minimatch@^3.0.4",
15 + "name": "minimatch",
16 + "escapedName": "minimatch",
17 + "rawSpec": "^3.0.4",
18 + "saveSpec": null,
19 + "fetchSpec": "^3.0.4"
20 + },
21 + "_requiredBy": [
22 + "/jake"
23 + ],
24 + "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
25 + "_shasum": "19cd194bfd3e428f049a70817c038d89ab4be35b",
26 + "_spec": "minimatch@^3.0.4",
27 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\jake",
28 + "author": {
29 + "name": "Isaac Z. Schlueter",
30 + "email": "i@izs.me",
31 + "url": "http://blog.izs.me"
32 + },
33 + "bugs": {
34 + "url": "https://github.com/isaacs/minimatch/issues"
35 + },
36 + "bundleDependencies": false,
37 + "dependencies": {
38 + "brace-expansion": "^1.1.7"
39 + },
40 + "deprecated": false,
41 + "description": "a glob matcher in javascript",
42 + "devDependencies": {
43 + "tap": "^15.1.6"
44 + },
45 + "engines": {
46 + "node": "*"
47 + },
48 + "files": [
49 + "minimatch.js"
50 + ],
51 + "homepage": "https://github.com/isaacs/minimatch#readme",
52 + "license": "ISC",
53 + "main": "minimatch.js",
54 + "name": "minimatch",
55 + "publishConfig": {
56 + "tag": "v3-legacy"
57 + },
58 + "repository": {
59 + "type": "git",
60 + "url": "git://github.com/isaacs/minimatch.git"
61 + },
62 + "scripts": {
63 + "postpublish": "git push origin --all; git push origin --tags",
64 + "postversion": "npm publish",
65 + "preversion": "npm test",
66 + "test": "tap"
67 + },
68 + "version": "3.1.2"
69 +}
1 +'use strict';
2 +module.exports = {
3 + stdout: false,
4 + stderr: false
5 +};
1 +'use strict';
2 +const os = require('os');
3 +const tty = require('tty');
4 +const hasFlag = require('has-flag');
5 +
6 +const {env} = process;
7 +
8 +let forceColor;
9 +if (hasFlag('no-color') ||
10 + hasFlag('no-colors') ||
11 + hasFlag('color=false') ||
12 + hasFlag('color=never')) {
13 + forceColor = 0;
14 +} else if (hasFlag('color') ||
15 + hasFlag('colors') ||
16 + hasFlag('color=true') ||
17 + hasFlag('color=always')) {
18 + forceColor = 1;
19 +}
20 +
21 +if ('FORCE_COLOR' in env) {
22 + if (env.FORCE_COLOR === 'true') {
23 + forceColor = 1;
24 + } else if (env.FORCE_COLOR === 'false') {
25 + forceColor = 0;
26 + } else {
27 + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
28 + }
29 +}
30 +
31 +function translateLevel(level) {
32 + if (level === 0) {
33 + return false;
34 + }
35 +
36 + return {
37 + level,
38 + hasBasic: true,
39 + has256: level >= 2,
40 + has16m: level >= 3
41 + };
42 +}
43 +
44 +function supportsColor(haveStream, streamIsTTY) {
45 + if (forceColor === 0) {
46 + return 0;
47 + }
48 +
49 + if (hasFlag('color=16m') ||
50 + hasFlag('color=full') ||
51 + hasFlag('color=truecolor')) {
52 + return 3;
53 + }
54 +
55 + if (hasFlag('color=256')) {
56 + return 2;
57 + }
58 +
59 + if (haveStream && !streamIsTTY && forceColor === undefined) {
60 + return 0;
61 + }
62 +
63 + const min = forceColor || 0;
64 +
65 + if (env.TERM === 'dumb') {
66 + return min;
67 + }
68 +
69 + if (process.platform === 'win32') {
70 + // Windows 10 build 10586 is the first Windows release that supports 256 colors.
71 + // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
72 + const osRelease = os.release().split('.');
73 + if (
74 + Number(osRelease[0]) >= 10 &&
75 + Number(osRelease[2]) >= 10586
76 + ) {
77 + return Number(osRelease[2]) >= 14931 ? 3 : 2;
78 + }
79 +
80 + return 1;
81 + }
82 +
83 + if ('CI' in env) {
84 + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
85 + return 1;
86 + }
87 +
88 + return min;
89 + }
90 +
91 + if ('TEAMCITY_VERSION' in env) {
92 + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
93 + }
94 +
95 + if (env.COLORTERM === 'truecolor') {
96 + return 3;
97 + }
98 +
99 + if ('TERM_PROGRAM' in env) {
100 + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
101 +
102 + switch (env.TERM_PROGRAM) {
103 + case 'iTerm.app':
104 + return version >= 3 ? 3 : 2;
105 + case 'Apple_Terminal':
106 + return 2;
107 + // No default
108 + }
109 + }
110 +
111 + if (/-256(color)?$/i.test(env.TERM)) {
112 + return 2;
113 + }
114 +
115 + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
116 + return 1;
117 + }
118 +
119 + if ('COLORTERM' in env) {
120 + return 1;
121 + }
122 +
123 + return min;
124 +}
125 +
126 +function getSupportLevel(stream) {
127 + const level = supportsColor(stream, stream && stream.isTTY);
128 + return translateLevel(level);
129 +}
130 +
131 +module.exports = {
132 + supportsColor: getSupportLevel,
133 + stdout: translateLevel(supportsColor(true, tty.isatty(1))),
134 + stderr: translateLevel(supportsColor(true, tty.isatty(2)))
135 +};
1 +MIT License
2 +
3 +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
4 +
5 +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:
6 +
7 +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 +
9 +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.
1 +{
2 + "_from": "supports-color@^7.1.0",
3 + "_id": "supports-color@7.2.0",
4 + "_inBundle": false,
5 + "_integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
6 + "_location": "/supports-color",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "supports-color@^7.1.0",
12 + "name": "supports-color",
13 + "escapedName": "supports-color",
14 + "rawSpec": "^7.1.0",
15 + "saveSpec": null,
16 + "fetchSpec": "^7.1.0"
17 + },
18 + "_requiredBy": [
19 + "/chalk"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
22 + "_shasum": "1b7dcdcb32b8138801b3e478ba6a51caa89648da",
23 + "_spec": "supports-color@^7.1.0",
24 + "_where": "C:\\Users\\ds754\\Desktop\\healthcare-with-webcam\\node_modules\\chalk",
25 + "author": {
26 + "name": "Sindre Sorhus",
27 + "email": "sindresorhus@gmail.com",
28 + "url": "sindresorhus.com"
29 + },
30 + "browser": "browser.js",
31 + "bugs": {
32 + "url": "https://github.com/chalk/supports-color/issues"
33 + },
34 + "bundleDependencies": false,
35 + "dependencies": {
36 + "has-flag": "^4.0.0"
37 + },
38 + "deprecated": false,
39 + "description": "Detect whether a terminal supports color",
40 + "devDependencies": {
41 + "ava": "^1.4.1",
42 + "import-fresh": "^3.0.0",
43 + "xo": "^0.24.0"
44 + },
45 + "engines": {
46 + "node": ">=8"
47 + },
48 + "files": [
49 + "index.js",
50 + "browser.js"
51 + ],
52 + "homepage": "https://github.com/chalk/supports-color#readme",
53 + "keywords": [
54 + "color",
55 + "colour",
56 + "colors",
57 + "terminal",
58 + "console",
59 + "cli",
60 + "ansi",
61 + "styles",
62 + "tty",
63 + "rgb",
64 + "256",
65 + "shell",
66 + "xterm",
67 + "command-line",
68 + "support",
69 + "supports",
70 + "capability",
71 + "detect",
72 + "truecolor",
73 + "16m"
74 + ],
75 + "license": "MIT",
76 + "name": "supports-color",
77 + "repository": {
78 + "type": "git",
79 + "url": "git+https://github.com/chalk/supports-color.git"
80 + },
81 + "scripts": {
82 + "test": "xo && ava"
83 + },
84 + "version": "7.2.0"
85 +}
1 +# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color)
2 +
3 +> Detect whether a terminal supports color
4 +
5 +
6 +## Install
7 +
8 +```
9 +$ npm install supports-color
10 +```
11 +
12 +
13 +## Usage
14 +
15 +```js
16 +const supportsColor = require('supports-color');
17 +
18 +if (supportsColor.stdout) {
19 + console.log('Terminal stdout supports color');
20 +}
21 +
22 +if (supportsColor.stdout.has256) {
23 + console.log('Terminal stdout supports 256 colors');
24 +}
25 +
26 +if (supportsColor.stderr.has16m) {
27 + console.log('Terminal stderr supports 16 million colors (truecolor)');
28 +}
29 +```
30 +
31 +
32 +## API
33 +
34 +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.
35 +
36 +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag:
37 +
38 +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors)
39 +- `.level = 2` and `.has256 = true`: 256 color support
40 +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors)
41 +
42 +
43 +## Info
44 +
45 +It obeys the `--color` and `--no-color` CLI flags.
46 +
47 +For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
48 +
49 +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
50 +
51 +
52 +## Related
53 +
54 +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module
55 +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right
56 +
57 +
58 +## Maintainers
59 +
60 +- [Sindre Sorhus](https://github.com/sindresorhus)
61 +- [Josh Junon](https://github.com/qix-)
62 +
63 +
64 +---
65 +
66 +<div align="center">
67 + <b>
68 + <a href="https://tidelift.com/subscription/pkg/npm-supports-color?utm_source=npm-supports-color&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
69 + </b>
70 + <br>
71 + <sub>
72 + Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
73 + </sub>
74 +</div>
75 +
76 +---
...@@ -13,11 +13,29 @@ ...@@ -13,11 +13,29 @@
13 "negotiator": "0.6.3" 13 "negotiator": "0.6.3"
14 } 14 }
15 }, 15 },
16 + "ansi-styles": {
17 + "version": "4.3.0",
18 + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
19 + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
20 + "requires": {
21 + "color-convert": "^2.0.1"
22 + }
23 + },
16 "array-flatten": { 24 "array-flatten": {
17 "version": "1.1.1", 25 "version": "1.1.1",
18 "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", 26 "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
19 "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" 27 "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
20 }, 28 },
29 + "async": {
30 + "version": "3.2.3",
31 + "resolved": "https://registry.npmjs.org/async/-/async-3.2.3.tgz",
32 + "integrity": "sha512-spZRyzKL5l5BZQrr/6m/SqFdBN0q3OCI0f9rjfBzCMBIP4p75P620rR3gTmaksNOhmzgdxcaxdNfMy6anrbM0g=="
33 + },
34 + "balanced-match": {
35 + "version": "1.0.2",
36 + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
37 + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
38 + },
21 "body-parser": { 39 "body-parser": {
22 "version": "1.20.0", 40 "version": "1.20.0",
23 "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.0.tgz", 41 "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.0.tgz",
...@@ -37,6 +55,14 @@ ...@@ -37,6 +55,14 @@
37 "unpipe": "1.0.0" 55 "unpipe": "1.0.0"
38 } 56 }
39 }, 57 },
58 + "brace-expansion": {
59 + "version": "2.0.1",
60 + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
61 + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
62 + "requires": {
63 + "balanced-match": "^1.0.0"
64 + }
65 + },
40 "bytes": { 66 "bytes": {
41 "version": "3.1.2", 67 "version": "3.1.2",
42 "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", 68 "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
...@@ -51,6 +77,33 @@ ...@@ -51,6 +77,33 @@
51 "get-intrinsic": "^1.0.2" 77 "get-intrinsic": "^1.0.2"
52 } 78 }
53 }, 79 },
80 + "chalk": {
81 + "version": "4.1.2",
82 + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
83 + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
84 + "requires": {
85 + "ansi-styles": "^4.1.0",
86 + "supports-color": "^7.1.0"
87 + }
88 + },
89 + "color-convert": {
90 + "version": "2.0.1",
91 + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
92 + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
93 + "requires": {
94 + "color-name": "~1.1.4"
95 + }
96 + },
97 + "color-name": {
98 + "version": "1.1.4",
99 + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
100 + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
101 + },
102 + "concat-map": {
103 + "version": "0.0.1",
104 + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
105 + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s="
106 + },
54 "content-disposition": { 107 "content-disposition": {
55 "version": "0.5.4", 108 "version": "0.5.4",
56 "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", 109 "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
...@@ -97,6 +150,14 @@ ...@@ -97,6 +150,14 @@
97 "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", 150 "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
98 "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" 151 "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
99 }, 152 },
153 + "ejs": {
154 + "version": "3.1.8",
155 + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.8.tgz",
156 + "integrity": "sha512-/sXZeMlhS0ArkfX2Aw780gJzXSMPnKjtspYZv+f3NiKLlubezAHDU5+9xz6gd3/NhG3txQCo6xlglmTS+oTGEQ==",
157 + "requires": {
158 + "jake": "^10.8.5"
159 + }
160 + },
100 "encodeurl": { 161 "encodeurl": {
101 "version": "1.0.2", 162 "version": "1.0.2",
102 "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", 163 "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
...@@ -150,6 +211,24 @@ ...@@ -150,6 +211,24 @@
150 "vary": "~1.1.2" 211 "vary": "~1.1.2"
151 } 212 }
152 }, 213 },
214 + "filelist": {
215 + "version": "1.0.4",
216 + "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz",
217 + "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==",
218 + "requires": {
219 + "minimatch": "^5.0.1"
220 + },
221 + "dependencies": {
222 + "minimatch": {
223 + "version": "5.1.0",
224 + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.0.tgz",
225 + "integrity": "sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==",
226 + "requires": {
227 + "brace-expansion": "^2.0.1"
228 + }
229 + }
230 + }
231 + },
153 "finalhandler": { 232 "finalhandler": {
154 "version": "1.2.0", 233 "version": "1.2.0",
155 "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", 234 "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz",
...@@ -197,6 +276,11 @@ ...@@ -197,6 +276,11 @@
197 "function-bind": "^1.1.1" 276 "function-bind": "^1.1.1"
198 } 277 }
199 }, 278 },
279 + "has-flag": {
280 + "version": "4.0.0",
281 + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
282 + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="
283 + },
200 "has-symbols": { 284 "has-symbols": {
201 "version": "1.0.3", 285 "version": "1.0.3",
202 "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", 286 "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz",
...@@ -232,6 +316,17 @@ ...@@ -232,6 +316,17 @@
232 "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", 316 "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
233 "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==" 317 "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="
234 }, 318 },
319 + "jake": {
320 + "version": "10.8.5",
321 + "resolved": "https://registry.npmjs.org/jake/-/jake-10.8.5.tgz",
322 + "integrity": "sha512-sVpxYeuAhWt0OTWITwT98oyV0GsXyMlXCF+3L1SuafBVUIr/uILGRB+NqwkzhgXKvoJpDIpQvqkUALgdmQsQxw==",
323 + "requires": {
324 + "async": "^3.2.3",
325 + "chalk": "^4.0.2",
326 + "filelist": "^1.0.1",
327 + "minimatch": "^3.0.4"
328 + }
329 + },
235 "media-typer": { 330 "media-typer": {
236 "version": "0.3.0", 331 "version": "0.3.0",
237 "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", 332 "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
...@@ -265,6 +360,25 @@ ...@@ -265,6 +360,25 @@
265 "mime-db": "1.52.0" 360 "mime-db": "1.52.0"
266 } 361 }
267 }, 362 },
363 + "minimatch": {
364 + "version": "3.1.2",
365 + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
366 + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
367 + "requires": {
368 + "brace-expansion": "^1.1.7"
369 + },
370 + "dependencies": {
371 + "brace-expansion": {
372 + "version": "1.1.11",
373 + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
374 + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
375 + "requires": {
376 + "balanced-match": "^1.0.0",
377 + "concat-map": "0.0.1"
378 + }
379 + }
380 + }
381 + },
268 "ms": { 382 "ms": {
269 "version": "2.0.0", 383 "version": "2.0.0",
270 "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", 384 "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
...@@ -399,6 +513,14 @@ ...@@ -399,6 +513,14 @@
399 "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", 513 "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
400 "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==" 514 "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ=="
401 }, 515 },
516 + "supports-color": {
517 + "version": "7.2.0",
518 + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
519 + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
520 + "requires": {
521 + "has-flag": "^4.0.0"
522 + }
523 + },
402 "toidentifier": { 524 "toidentifier": {
403 "version": "1.0.1", 525 "version": "1.0.1",
404 "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", 526 "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
5 "main": "server.js", 5 "main": "server.js",
6 "scripts": { 6 "scripts": {
7 "test": "echo \"Error: no test specified\" && exit 1", 7 "test": "echo \"Error: no test specified\" && exit 1",
8 - "start" : "node server.js" 8 + "start": "node server.js"
9 }, 9 },
10 "repository": { 10 "repository": {
11 "type": "git", 11 "type": "git",
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
14 "author": "", 14 "author": "",
15 "license": "ISC", 15 "license": "ISC",
16 "dependencies": { 16 "dependencies": {
17 + "ejs": "^3.1.8",
17 "express": "^4.18.1" 18 "express": "^4.18.1"
18 } 19 }
19 } 20 }
......
1 const express = require('express'); 1 const express = require('express');
2 +const ejs = require('ejs')
3 +
2 const app = express(); 4 const app = express();
3 const port = 3000 5 const port = 3000
4 6
7 +
8 +app.set('port', port)
9 +app.set('view engine', 'ejs')
10 +app.engine('html',ejs.renderFile )
11 +
12 +
5 app.get('/', (req,res) => { 13 app.get('/', (req,res) => {
6 - res.send("Hello World") 14 + app.set('views', __dirname + '/views/mainPage')
15 + res.render('main.html')
16 +})
17 +
18 +app.get('/squart', (req,res) => {
19 + app.set('views', __dirname + '/views/squartPage')
20 + res.render('squart.html')
7 }) 21 })
8 22
9 app.listen(port, () => { 23 app.listen(port, () => {
......
1 +<!DOCTYPE html>
2 +<html lang="en">
3 +<head>
4 + <meta charset="UTF-8">
5 + <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 + <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 + <title>Main Page</title>
8 +</head>
9 +<body>
10 + Main Page
11 +</body>
12 +</html>
...\ No newline at end of file ...\ No newline at end of file
1 +<!DOCTYPE html>
2 +<html lang="en">
3 +<head>
4 + <meta charset="UTF-8">
5 + <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 + <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 + <title>Squart Page</title>
8 +</head>
9 +<body>
10 + Squart Page
11 +</body>
12 +</html>
...\ No newline at end of file ...\ No newline at end of file