Update ecstatic to 0.5 (resolve #800)

This commit is contained in:
Joshua Granick
2017-06-05 14:49:52 -07:00
parent fca12e66cf
commit dab605d892
14 changed files with 1162 additions and 125 deletions

1
templates/bin/node/http-server/node_modules/.bin/he generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../he/bin/he

1
templates/bin/node/http-server/node_modules/.bin/mime generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../mime/cli.js

View File

@@ -27,6 +27,7 @@ var ecstatic = module.exports = function (dir, options) {
handleError = opts.handleError;
opts.root = dir;
if (defaultExt && /^\./.test(defaultExt)) defaultExt = defaultExt.replace(/^\./, '');
return function middleware (req, res, next) {
@@ -37,8 +38,8 @@ var ecstatic = module.exports = function (dir, options) {
// Figure out the path for the file from the given url
var parsed = url.parse(req.url);
try {
decodeURI(req.url); // check validity of url
var pathname = decodeURI(parsed.pathname);
decodeURIComponent(req.url); // check validity of url
var pathname = decodePathname(parsed.pathname);
}
catch (err) {
return status[400](res, next, { error: err });
@@ -67,80 +68,136 @@ var ecstatic = module.exports = function (dir, options) {
return status[405](res, next);
}
function statFile() {
fs.stat(file, function (err, stat) {
if (err && err.code === 'ENOENT') {
if (req.statusCode == 404) {
// This means we're already trying ./404.html
status[404](res, next);
}
else if (defaultExt && !path.extname(parsed.pathname).length) {
//
// If no file extension is specified and there is a default extension
// try that before rendering 404.html.
//
middleware({
url: parsed.pathname + '.' + defaultExt + ((parsed.search)? parsed.search:'')
}, res, next);
}
else {
// Try for ./404.html
//
// In order to make tests pass, we have to punch the status code
// in both spots. It's stupid and mysterious, but at least we get
// the behavior we want.
//
// TODO: Figure out what the Hell is going on and clean this up.
res.statusCode = 404;
middleware({
url: (handleError ? ('/' + path.join(baseDir, '404.' + defaultExt)) : req.url),
statusCode: 404
}, res, next);
}
}
else if (err) {
status[500](res, next, { error: err });
}
else if (stat.isDirectory()) {
// 302 to / if necessary
if (!parsed.pathname.match(/\/$/)) {
res.statusCode = 302;
res.setHeader('location', parsed.pathname + '/' +
(parsed.query? ('?' + parsed.query):'')
);
return res.end();
}
if (autoIndex) {
return middleware({
url: path.join(encodeURIComponent(pathname), '/index.' + defaultExt)
}, res, function (err) {
if (err) {
return status[500](res, next, { error: err });
}
if (opts.showDir) {
return showDir(opts, stat)(req, res);
}
return status[403](res, next);
});
}
if (opts.showDir) {
return showDir(opts, stat)(req, res);
}
status[404](res, next);
}
else {
serve(stat);
}
});
}
// Look for a gzipped file if this is turned on
if (opts.gzip && shouldCompress(req)) {
fs.stat(gzipped, function (err, stat) {
if (!err && stat.isFile()) {
file = gzipped;
return serve(stat);
} else {
statFile();
}
});
} else {
statFile();
}
fs.stat(file, function (err, stat) {
if (err && err.code === 'ENOENT') {
if (req.statusCode == 404) {
// This means we're already trying ./404.html
status[404](res, next);
}
else if (defaultExt && !path.extname(parsed.pathname).length) {
//
// If no file extension is specified and there is a default extension
// try that before rendering 404.html.
//
middleware({
url: parsed.pathname + '.' + defaultExt + ((parsed.search)? parsed.search:'')
}, res, next);
}
else {
// Try for ./404.html
middleware({
url: (handleError ? ('/' + path.join(baseDir, '404.html')) : req.url),
statusCode: 404 // Override the response status code
}, res, next);
}
}
else if (err) {
status[500](res, next, { error: err });
}
else if (stat.isDirectory()) {
// 302 to / if necessary
if (!parsed.pathname.match(/\/$/)) {
res.statusCode = 302;
res.setHeader('location', parsed.pathname + '/' +
(parsed.query? ('?' + parsed.query):'')
);
return res.end();
}
if (autoIndex) {
return middleware({
url: path.join(pathname, '/index.html')
}, res, function (err) {
if (err) {
return status[500](res, next, { error: err });
}
if (opts.showDir) {
return showDir(opts, stat)(req, res);
}
return status[403](res, next);
});
}
if (opts.showDir) {
return showDir(opts, stat)(req, res);
}
status[404](res, next);
}
else {
serve(stat);
}
});
function serve(stat) {
// Do a MIME lookup, fall back to octet-stream and handle gzip
// special case.
var contentType = mime.lookup(file), charSet;
if (contentType) {
charSet = mime.charsets.lookup(contentType, 'utf-8');
if (charSet) {
contentType += '; charset=' + charSet;
}
}
if (path.extname(file) === '.gz') {
res.setHeader('Content-Encoding', 'gzip');
// strip gz ending and lookup mime type
contentType = mime.lookup(path.basename(file, ".gz"));
}
var range = (req.headers && req.headers['range']);
if (range) {
var total = stat.size;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = Math.min(total-1, partialend ? parseInt(partialend, 10) : total-1);
var chunksize = (end-start)+1;
if (start > end || isNaN(start) || isNaN(end)) {
return status['416'](res, next);
}
var fstream = fs.createReadStream(file, {start: start, end: end});
fstream.on('error', function (err) {
status['500'](res, next, { error: err });
});
res.writeHead(206, {
'Content-Range': 'bytes ' + start + '-' + end + '/' + total,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': contentType || 'application/octet-stream'
});
fstream.pipe(res);
return;
}
// TODO: Helper for this, with default headers.
res.setHeader('etag', etag(stat));
@@ -158,25 +215,6 @@ var ecstatic = module.exports = function (dir, options) {
}
res.setHeader('content-length', stat.size);
// Do a MIME lookup, fall back to octet-stream and handle gzip
// special case.
var contentType = mime.lookup(file), charSet;
if (contentType) {
charSet = mime.charsets.lookup(contentType);
if (charSet) {
contentType += '; charset=' + charSet;
}
}
if (path.extname(file) === '.gz') {
res.setHeader('Content-Encoding', 'gzip');
// strip gz ending and lookup mime type
contentType = mime.lookup(path.basename(file, ".gz"));
}
res.setHeader('content-type', contentType || 'application/octet-stream');
if (req.method === "HEAD") {
@@ -215,13 +253,28 @@ function shouldCompress(req) {
;
}
if(!module.parent) {
// See: https://github.com/jesusabdullah/node-ecstatic/issues/109
function decodePathname(pathname) {
var pieces = pathname.split('/');
return pieces.map(function (piece) {
piece = decodeURIComponent(piece);
if (process.platform === 'win32' && /\\/.test(piece)) {
throw new Error('Invalid forward slash character');
}
return piece;
}).join('/');
}
if (!module.parent) {
var http = require('http'),
opts = require('optimist').argv,
opts = require('minimist')(process.argv.slice(2)),
port = opts.port || opts.p || 8000,
dir = opts.root || opts._[0] || process.cwd();
if(opts.help || opts.h) {
if (opts.help || opts.h) {
var u = console.error;
u('usage: ecstatic [dir] {options} --port PORT');
u('see https://npm.im/ecstatic for more docs');
@@ -230,6 +283,6 @@ if(!module.parent) {
http.createServer(ecstatic(dir, opts))
.listen(port, function () {
console.log('ecstatic serving ' + dir + ' on port ' + port);
console.log('ecstatic serving ' + dir + ' at http://0.0.0.0:' + port);
});
}

View File

@@ -3,12 +3,12 @@
module.exports = function (opts) {
var autoIndex = true,
showDir = false,
showDir = true,
humanReadable = true,
si = false,
cache = 'max-age=3600',
gzip = false,
defaultExt,
defaultExt = '.html',
handleError = true;
if (opts) {
@@ -53,13 +53,8 @@ module.exports = function (opts) {
}
});
if (opts.defaultExt) {
if (opts.defaultExt === true) {
defaultExt = 'html';
}
else {
defaultExt = opts.defaultExt;
}
if (opts.defaultExt && typeof opts.defaultExt === 'string') {
defaultExt = opts.defaultExt;
}
if (typeof opts.cache !== 'undefined' && opts.cache !== null) {

View File

@@ -1,7 +1,7 @@
var ecstatic = require('../ecstatic'),
fs = require('fs'),
path = require('path'),
ent = require('ent'),
he = require('he'),
etag = require('./etag'),
url = require('url'),
status = require('./status-handlers');
@@ -18,7 +18,7 @@ module.exports = function (opts, stat) {
// Figure out the path for the file from the given url
var parsed = url.parse(req.url),
pathname = decodeURI(parsed.pathname),
pathname = decodeURIComponent(parsed.pathname),
dir = path.normalize(
path.join(root,
path.relative(
@@ -43,11 +43,14 @@ module.exports = function (opts, stat) {
res.setHeader('last-modified', (new Date(stat.mtime)).toUTCString());
res.setHeader('cache-control', cache);
sortByIsDirectory(files, function (errs, dirs, files) {
if (errs.length > 0) {
return status[500](res, next, { error: errs[0] });
}
sortByIsDirectory(files, function (lolwuts, dirs, files) {
// It's possible to get stat errors for all sorts of reasons here.
// Unfortunately, our two choices are to either bail completely,
// or just truck along as though everything's cool. In this case,
// I decided to just tack them on as "??!?" items along with dirs
// and files.
//
// Whatever.
// if it makes sense to, add a .. link
if (path.resolve(dir, '..').slice(0, root.length) == root) {
@@ -56,10 +59,10 @@ module.exports = function (opts, stat) {
return status[500](res, next, { error: err });
}
dirs.unshift([ '..', s ]);
render(dirs, files);
render(dirs, files, lolwuts);
});
}
render(dirs, files);
render(dirs, files, lolwuts);
});
function sortByIsDirectory(paths, cb) {
@@ -78,7 +81,7 @@ module.exports = function (opts, stat) {
paths.forEach(function (file) {
fs.stat(path.join(dir, file), function (err, s) {
if (err) {
errs.push(err);
errs.push([file, err]);
}
else if (s.isDirectory()) {
dirs.push([file, s]);
@@ -94,25 +97,27 @@ module.exports = function (opts, stat) {
});
}
function render(dirs, files) {
function render(dirs, files, lolwuts) {
// each entry in the array is a [name, stat] tuple
// TODO: use stylessheets?
var html = '<!doctype html>\
<html> \
<head> \
<meta charset="utf-8"> \
<title>Index of ' + pathname +'</title> \
</head> \
<body> \
<h1>Index of ' + pathname + '</h1>\n';
var html = [
'<!doctype html>',
'<html>',
' <head>',
' <meta charset="utf-8">',
' <title>Index of ' + pathname +'</title>',
' </head>',
' <body>',
'<h1>Index of ' + pathname + '</h1>'
].join('\n') + '\n';
html += '<table>';
var failed = false;
var writeRow = function (file, i) {
// render a row given a [name, stat] tuple
var isDir = file[1].isDirectory();
var isDir = file[1].isDirectory && file[1].isDirectory();
var href =
parsed.pathname.replace(/\/$/, '') +
'/' + encodeURIComponent(file[0]);
@@ -122,7 +127,7 @@ module.exports = function (opts, stat) {
href += '/' + ((parsed.search)? parsed.search:'');
}
var displayName = ent.encode(file[0]) + ((isDir)? '/':'');
var displayName = he.encode(file[0]) + ((isDir)? '/':'');
// TODO: use stylessheets?
html += '<tr>' +
@@ -132,15 +137,16 @@ module.exports = function (opts, stat) {
'</tr>\n';
};
dirs.sort(function (a, b) { return b[0] - a[0]; } ).forEach(writeRow);
dirs.sort(function (a, b) { return b[0] - a[0]; }).forEach(writeRow);
files.sort(function (a, b) { return b.toString().localeCompare(a.toString()); }).forEach(writeRow);
lolwuts.sort(function (a, b) { return b[0] - a[0] }).forEach(writeRow);
html += '</table>\n';
html += '<br><address>Node.js ' +
process.version +
'/ <a href="https://github.com/jesusabdullah/node-ecstatic">ecstatic</a> ' +
'server running @ ' +
ent.encode(req.headers.host || '') + '</address>\n' +
he.encode(req.headers.host || '') + '</address>\n' +
'</body></html>'
;
@@ -155,6 +161,11 @@ module.exports = function (opts, stat) {
};
function permsToString(stat) {
if (!stat.isDirectory || !stat.mode) {
return '???!!!???';
}
var dir = stat.isDirectory() ? 'd' : '-',
mode = stat.mode.toString(8);
@@ -177,7 +188,7 @@ function permsToString(stat) {
// si: (boolean) whether to use si (1k = 1000), otherwise 1k = 1024
// adopted from http://stackoverflow.com/a/14919494/665507
function sizeToString(stat, humanReadable, si) {
if (stat.isDirectory()) {
if (stat.isDirectory && stat.isDirectory()) {
return '';
}
@@ -185,15 +196,19 @@ function sizeToString(stat, humanReadable, si) {
var bytes = stat.size;
var threshold = si ? 1000 : 1024;
if(!humanReadable || bytes < threshold) {
if (!humanReadable || bytes < threshold) {
return bytes + 'B';
}
var units = ['k','M','G','T','P','E','Z','Y'];
var units = [ 'k','M','G','T','P','E','Z','Y' ];
var u = -1;
do {
bytes /= threshold;
++u;
} while (bytes >= threshold);
return bytes.toFixed(1)+units[u];
var b = bytes.toFixed(1);
if (isNaN(b)) b = '??';
return b + units[u];
}

View File

@@ -26,7 +26,7 @@ exports['405'] = function (res, next, opts) {
}
else {
res.setHeader('allow', (opts && opts.allow) || 'GET, HEAD');
res.end();
res.end();
}
};
@@ -44,6 +44,19 @@ exports['404'] = function (res, next) {
}
};
exports['416'] = function (res, next) {
res.statusCode = 416;
if (typeof next === "function") {
next();
}
else {
if (res.writable) {
res.setHeader('content-type', 'text/plain');
res.end('Requested range not satisfiable');
}
}
};
// flagrant error
exports['500'] = function (res, next, opts) {
res.statusCode = 500;

View File

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

143
templates/bin/node/http-server/node_modules/he/bin/he generated vendored Executable file
View File

@@ -0,0 +1,143 @@
#!/usr/bin/env node
(function() {
var fs = require('fs');
var he = require('../he.js');
var strings = process.argv.splice(2);
var stdin = process.stdin;
var data;
var timeout;
var action;
var options = {};
var log = console.log;
var main = function() {
var option = strings[0];
var count = 0;
if (/^(?:-h|--help|undefined)$/.test(option)) {
log(
'he v%s - http://mths.be/he',
he.version
);
log([
'\nUsage:\n',
'\the [--escape] string',
'\the [--encode] [--use-named-refs] [--everything] [--allow-unsafe] string',
'\the [--decode] [--attribute] [--strict] string',
'\the [-v | --version]',
'\the [-h | --help]',
'\nExamples:\n',
'\the --escape \\<img\\ src\\=\\\'x\\\'\\ onerror\\=\\"prompt\\(1\\)\\"\\>',
'\techo \'&copy; &#x1D306;\' | he --decode'
].join('\n'));
return process.exit(1);
}
if (/^(?:-v|--version)$/.test(option)) {
log('v%s', he.version);
return process.exit(1);
}
strings.forEach(function(string) {
// Process options
if (string == '--escape') {
action = 'escape';
return;
}
if (string == '--encode') {
action = 'encode';
return;
}
if (string == '--use-named-refs') {
action = 'encode';
options.useNamedReferences = true;
return;
}
if (string == '--everything') {
action = 'encode';
options.encodeEverything = true;
return;
}
if (string == '--allow-unsafe') {
action = 'encode';
options.allowUnsafeSymbols = true;
return;
}
if (string == '--decode') {
action = 'decode';
return;
}
if (string == '--attribute') {
action = 'decode';
options.isAttributeValue = true;
return;
}
if (string == '--strict') {
action = 'decode';
options.strict = true;
return;
}
// Process string(s)
var result;
if (!action) {
log('Error: he requires at least one option and a string argument.');
log('Try `he --help` for more information.');
return process.exit(1);
}
try {
result = he[action](string, options);
log(result);
count++;
} catch(error) {
log(error.message + '\n');
log('Error: failed to %s.', action);
log('If you think this is a bug in he, please report it:');
log('https://github.com/mathiasbynens/he/issues/new');
log(
'\nStack trace using he@%s:\n',
he.version
);
log(error.stack);
return process.exit(1);
}
});
if (!count) {
log('Error: he requires a string argument.');
log('Try `he --help` for more information.');
return process.exit(1);
}
// Return with exit status 0 outside of the `forEach` loop, in case
// multiple strings were passed in.
return process.exit(0);
};
if (stdin.isTTY) {
// handle shell arguments
main();
} else {
// Either the script is called from within a non-TTY context, or `stdin`
// content is being piped in.
if (!process.stdout.isTTY) {
// The script was called from a non-TTY context. This is a rather uncommon
// use case we dont actively support. However, we dont want the script
// to wait forever in such cases, so…
timeout = setTimeout(function() {
// …if no piped data arrived after a whole minute, handle shell
// arguments instead.
main();
}, 60000);
}
data = '';
stdin.on('data', function(chunk) {
clearTimeout(timeout);
data += chunk;
});
stdin.on('end', function() {
strings.push(data.trim());
main();
});
stdin.resume();
}
}());

329
templates/bin/node/http-server/node_modules/he/he.js generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,108 @@
{
"_args": [
[
"he@^0.5.0",
"/home/joshua/Development/Haxe/test/node_modules/ecstatic"
]
],
"_from": "he@>=0.5.0 <0.6.0",
"_id": "he@0.5.0",
"_inCache": true,
"_installable": true,
"_location": "/he",
"_npmUser": {
"email": "mathias@qiwi.be",
"name": "mathias"
},
"_npmVersion": "1.4.9",
"_phantomChildren": {},
"_requested": {
"name": "he",
"raw": "he@^0.5.0",
"rawSpec": "^0.5.0",
"scope": null,
"spec": ">=0.5.0 <0.6.0",
"type": "range"
},
"_requiredBy": [
"/ecstatic"
],
"_resolved": "https://registry.npmjs.org/he/-/he-0.5.0.tgz",
"_shasum": "2c05ffaef90b68e860f3fd2b54ef580989277ee2",
"_shrinkwrap": null,
"_spec": "he@^0.5.0",
"_where": "/home/joshua/Development/Haxe/test/node_modules/ecstatic",
"author": {
"name": "Mathias Bynens",
"url": "https://mathiasbynens.be/"
},
"bin": {
"he": "bin/he"
},
"bugs": {
"url": "https://github.com/mathiasbynens/he/issues"
},
"dependencies": {},
"description": "A robust HTML entities encoder/decoder with full Unicode support.",
"devDependencies": {
"coveralls": "^2.11.1",
"grunt": "^0.4.5",
"grunt-shell": "^1.0.1",
"grunt-template": "^0.2.3",
"istanbul": "^0.3.0",
"jsesc": "^0.5.0",
"lodash": "^2.4.1",
"qunit-extras": "^1.1.0",
"qunitjs": "~1.11.0",
"regenerate": "^0.6.2",
"requirejs": "^2.1.14",
"string.fromcodepoint": "^0.2.1"
},
"directories": {
"bin": "bin",
"man": "man",
"test": "tests"
},
"dist": {
"shasum": "2c05ffaef90b68e860f3fd2b54ef580989277ee2",
"tarball": "https://registry.npmjs.org/he/-/he-0.5.0.tgz"
},
"files": [
"LICENSE-MIT.txt",
"bin/",
"he.js",
"man/"
],
"homepage": "http://mths.be/he",
"keywords": [
"decode",
"encode",
"entities",
"entity",
"html",
"string",
"unicode"
],
"license": "MIT",
"main": "he.js",
"maintainers": [
{
"name": "mathias",
"email": "mathias@qiwi.be"
}
],
"man": [
"/Users/mathias/.npm/he/0.5.0/package/man/he.1"
],
"name": "he",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/mathiasbynens/he.git"
},
"scripts": {
"test": "node tests/tests.js"
},
"version": "0.5.0"
}

View File

@@ -0,0 +1,8 @@
language: node_js
node_js:
- "0.8"
- "0.10"
- "0.12"
- "iojs"
before_install:
- npm install -g npm@~1.4.6

View File

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

View File

@@ -0,0 +1,236 @@
module.exports = function (args, opts) {
if (!opts) opts = {};
var flags = { bools : {}, strings : {}, unknownFn: null };
if (typeof opts['unknown'] === 'function') {
flags.unknownFn = opts['unknown'];
}
if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
flags.allBools = true;
} else {
[].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
flags.bools[key] = true;
});
}
var aliases = {};
Object.keys(opts.alias || {}).forEach(function (key) {
aliases[key] = [].concat(opts.alias[key]);
aliases[key].forEach(function (x) {
aliases[x] = [key].concat(aliases[key].filter(function (y) {
return x !== y;
}));
});
});
[].concat(opts.string).filter(Boolean).forEach(function (key) {
flags.strings[key] = true;
if (aliases[key]) {
flags.strings[aliases[key]] = true;
}
});
var defaults = opts['default'] || {};
var argv = { _ : [] };
Object.keys(flags.bools).forEach(function (key) {
setArg(key, defaults[key] === undefined ? false : defaults[key]);
});
var notFlags = [];
if (args.indexOf('--') !== -1) {
notFlags = args.slice(args.indexOf('--')+1);
args = args.slice(0, args.indexOf('--'));
}
function argDefined(key, arg) {
return (flags.allBools && /^--[^=]+$/.test(arg)) ||
flags.strings[key] || flags.bools[key] || aliases[key];
}
function setArg (key, val, arg) {
if (arg && flags.unknownFn && !argDefined(key, arg)) {
if (flags.unknownFn(arg) === false) return;
}
var value = !flags.strings[key] && isNumber(val)
? Number(val) : val
;
setKey(argv, key.split('.'), value);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), value);
});
}
function setKey (obj, keys, value) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
if (o[key] === undefined) o[key] = {};
o = o[key];
});
var key = keys[keys.length - 1];
if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
o[key] = value;
}
else if (Array.isArray(o[key])) {
o[key].push(value);
}
else {
o[key] = [ o[key], value ];
}
}
function aliasIsBoolean(key) {
return aliases[key].some(function (x) {
return flags.bools[x];
});
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (/^--.+=/.test(arg)) {
// Using [\s\S] instead of . because js doesn't support the
// 'dotall' regex modifier. See:
// http://stackoverflow.com/a/1068308/13216
var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
var key = m[1];
var value = m[2];
if (flags.bools[key]) {
value = value !== 'false';
}
setArg(key, value, arg);
}
else if (/^--no-.+/.test(arg)) {
var key = arg.match(/^--no-(.+)/)[1];
setArg(key, false, arg);
}
else if (/^--.+/.test(arg)) {
var key = arg.match(/^--(.+)/)[1];
var next = args[i + 1];
if (next !== undefined && !/^-/.test(next)
&& !flags.bools[key]
&& !flags.allBools
&& (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, next, arg);
i++;
}
else if (/^(true|false)$/.test(next)) {
setArg(key, next === 'true', arg);
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true, arg);
}
}
else if (/^-[^-]+/.test(arg)) {
var letters = arg.slice(1,-1).split('');
var broken = false;
for (var j = 0; j < letters.length; j++) {
var next = arg.slice(j+2);
if (next === '-') {
setArg(letters[j], next, arg)
continue;
}
if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
setArg(letters[j], next.split('=')[1], arg);
broken = true;
break;
}
if (/[A-Za-z]/.test(letters[j])
&& /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j], next, arg);
broken = true;
break;
}
if (letters[j+1] && letters[j+1].match(/\W/)) {
setArg(letters[j], arg.slice(j+2), arg);
broken = true;
break;
}
else {
setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
}
}
var key = arg.slice(-1)[0];
if (!broken && key !== '-') {
if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
&& !flags.bools[key]
&& (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, args[i+1], arg);
i++;
}
else if (args[i+1] && /true|false/.test(args[i+1])) {
setArg(key, args[i+1] === 'true', arg);
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true, arg);
}
}
}
else {
if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
argv._.push(
flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
);
}
if (opts.stopEarly) {
argv._.push.apply(argv._, args.slice(i + 1));
break;
}
}
}
Object.keys(defaults).forEach(function (key) {
if (!hasKey(argv, key.split('.'))) {
setKey(argv, key.split('.'), defaults[key]);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), defaults[key]);
});
}
});
if (opts['--']) {
argv['--'] = new Array();
notFlags.forEach(function(key) {
argv['--'].push(key);
});
}
else {
notFlags.forEach(function(key) {
argv._.push(key);
});
}
return argv;
};
function hasKey (obj, keys) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
o = (o[key] || {});
});
var key = keys[keys.length - 1];
return key in o;
}
function isNumber (x) {
if (typeof x === 'number') return true;
if (/^0x[0-9a-f]+$/i.test(x)) return true;
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}

View File

@@ -0,0 +1,97 @@
{
"_args": [
[
"minimist@^1.1.0",
"/home/joshua/Development/Haxe/test/node_modules/ecstatic"
]
],
"_from": "minimist@>=1.1.0 <2.0.0",
"_id": "minimist@1.2.0",
"_inCache": true,
"_installable": true,
"_location": "/minimist",
"_nodeVersion": "2.4.0",
"_npmUser": {
"email": "substack@gmail.com",
"name": "substack"
},
"_npmVersion": "3.2.2",
"_phantomChildren": {},
"_requested": {
"name": "minimist",
"raw": "minimist@^1.1.0",
"rawSpec": "^1.1.0",
"scope": null,
"spec": ">=1.1.0 <2.0.0",
"type": "range"
},
"_requiredBy": [
"/ecstatic"
],
"_resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
"_shasum": "a35008b20f41383eec1fb914f4cd5df79a264284",
"_shrinkwrap": null,
"_spec": "minimist@^1.1.0",
"_where": "/home/joshua/Development/Haxe/test/node_modules/ecstatic",
"author": {
"email": "mail@substack.net",
"name": "James Halliday",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/minimist/issues"
},
"dependencies": {},
"description": "parse argument options",
"devDependencies": {
"covert": "^1.0.0",
"tap": "~0.4.0",
"tape": "^3.5.0"
},
"directories": {},
"dist": {
"shasum": "a35008b20f41383eec1fb914f4cd5df79a264284",
"tarball": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz"
},
"gitHead": "dc624482fcfec5bc669c68cdb861f00573ed4e64",
"homepage": "https://github.com/substack/minimist",
"keywords": [
"argv",
"getopt",
"optimist",
"parser"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "substack",
"email": "mail@substack.net"
}
],
"name": "minimist",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git://github.com/substack/minimist.git"
},
"scripts": {
"coverage": "covert test/*.js",
"test": "tap test/*.js"
},
"testling": {
"browsers": [
"chrome/10",
"chrome/latest",
"ff/5",
"firefox/latest",
"ie/6..latest",
"opera/12",
"safari/5.1",
"safari/latest"
],
"files": "test/*.js"
},
"version": "1.2.0"
}