Commit b807a4c1 authored by Wolfgang Knopki's avatar Wolfgang Knopki
Browse files

Merge branch 'revert-jul13' into 'testing'

Revert "Merge branch 'MLAB-677' into 'testing'"

See merge request !168
parents 81e73777 08d3a3ba
Pipeline #6895 passed with stage
in 16 seconds
'use strict';
var util = require('util');
// Constants
var c = require('../const');
var $$ = require('../utils');
var HelpFormatter = require('./formatter.js');
/**
* new RawDescriptionHelpFormatter(options)
* new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...})
*
* Help message formatter which adds default values to argument help.
*
* Only the name of this class is considered a public API. All the methods
* provided by the class are considered an implementation detail.
**/
function ArgumentDefaultsHelpFormatter(options) {
HelpFormatter.call(this, options);
}
util.inherits(ArgumentDefaultsHelpFormatter, HelpFormatter);
ArgumentDefaultsHelpFormatter.prototype._getHelpString = function (action) {
var help = action.help;
if (action.help.indexOf('%(defaultValue)s') === -1) {
if (action.defaultValue !== c.SUPPRESS) {
var defaulting_nargs = [ c.OPTIONAL, c.ZERO_OR_MORE ];
if (action.isOptional() || (defaulting_nargs.indexOf(action.nargs) >= 0)) {
help += ' (default: %(defaultValue)s)';
}
}
}
return help;
};
module.exports.ArgumentDefaultsHelpFormatter = ArgumentDefaultsHelpFormatter;
/**
* new RawDescriptionHelpFormatter(options)
* new ArgumentParser({formatterClass: argparse.RawDescriptionHelpFormatter, ...})
*
* Help message formatter which retains any formatting in descriptions.
*
* Only the name of this class is considered a public API. All the methods
* provided by the class are considered an implementation detail.
**/
function RawDescriptionHelpFormatter(options) {
HelpFormatter.call(this, options);
}
util.inherits(RawDescriptionHelpFormatter, HelpFormatter);
RawDescriptionHelpFormatter.prototype._fillText = function (text, width, indent) {
var lines = text.split('\n');
lines = lines.map(function (line) {
return $$.trimEnd(indent + line);
});
return lines.join('\n');
};
module.exports.RawDescriptionHelpFormatter = RawDescriptionHelpFormatter;
/**
* new RawTextHelpFormatter(options)
* new ArgumentParser({formatterClass: argparse.RawTextHelpFormatter, ...})
*
* Help message formatter which retains formatting of all help text.
*
* Only the name of this class is considered a public API. All the methods
* provided by the class are considered an implementation detail.
**/
function RawTextHelpFormatter(options) {
RawDescriptionHelpFormatter.call(this, options);
}
util.inherits(RawTextHelpFormatter, RawDescriptionHelpFormatter);
RawTextHelpFormatter.prototype._splitLines = function (text) {
return text.split('\n');
};
module.exports.RawTextHelpFormatter = RawTextHelpFormatter;
/**
* class HelpFormatter
*
* Formatter for generating usage messages and argument help strings. Only the
* name of this class is considered a public API. All the methods provided by
* the class are considered an implementation detail.
*
* Do not call in your code, use this class only for inherits your own forvatter
*
* ToDo add [additonal formatters][1]
*
* [1]:http://docs.python.org/dev/library/argparse.html#formatter-class
**/
'use strict';
var sprintf = require('sprintf-js').sprintf;
// Constants
var c = require('../const');
var $$ = require('../utils');
/*:nodoc:* internal
* new Support(parent, heding)
* - parent (object): parent section
* - heading (string): header string
*
**/
function Section(parent, heading) {
this._parent = parent;
this._heading = heading;
this._items = [];
}
/*:nodoc:* internal
* Section#addItem(callback) -> Void
* - callback (array): tuple with function and args
*
* Add function for single element
**/
Section.prototype.addItem = function (callback) {
this._items.push(callback);
};
/*:nodoc:* internal
* Section#formatHelp(formatter) -> string
* - formatter (HelpFormatter): current formatter
*
* Form help section string
*
**/
Section.prototype.formatHelp = function (formatter) {
var itemHelp, heading;
// format the indented section
if (this._parent) {
formatter._indent();
}
itemHelp = this._items.map(function (item) {
var obj, func, args;
obj = formatter;
func = item[0];
args = item[1];
return func.apply(obj, args);
});
itemHelp = formatter._joinParts(itemHelp);
if (this._parent) {
formatter._dedent();
}
// return nothing if the section was empty
if (!itemHelp) {
return '';
}
// add the heading if the section was non-empty
heading = '';
if (this._heading && this._heading !== c.SUPPRESS) {
var currentIndent = formatter.currentIndent;
heading = $$.repeat(' ', currentIndent) + this._heading + ':' + c.EOL;
}
// join the section-initialize newline, the heading and the help
return formatter._joinParts([ c.EOL, heading, itemHelp, c.EOL ]);
};
/**
* new HelpFormatter(options)
*
* #### Options:
* - `prog`: program name
* - `indentIncriment`: indent step, default value 2
* - `maxHelpPosition`: max help position, default value = 24
* - `width`: line width
*
**/
var HelpFormatter = module.exports = function HelpFormatter(options) {
options = options || {};
this._prog = options.prog;
this._maxHelpPosition = options.maxHelpPosition || 24;
this._width = (options.width || ((process.env.COLUMNS || 80) - 2));
this._currentIndent = 0;
this._indentIncriment = options.indentIncriment || 2;
this._level = 0;
this._actionMaxLength = 0;
this._rootSection = new Section(null);
this._currentSection = this._rootSection;
this._whitespaceMatcher = new RegExp('\\s+', 'g');
this._longBreakMatcher = new RegExp(c.EOL + c.EOL + c.EOL + '+', 'g');
};
HelpFormatter.prototype._indent = function () {
this._currentIndent += this._indentIncriment;
this._level += 1;
};
HelpFormatter.prototype._dedent = function () {
this._currentIndent -= this._indentIncriment;
this._level -= 1;
if (this._currentIndent < 0) {
throw new Error('Indent decreased below 0.');
}
};
HelpFormatter.prototype._addItem = function (func, args) {
this._currentSection.addItem([ func, args ]);
};
//
// Message building methods
//
/**
* HelpFormatter#startSection(heading) -> Void
* - heading (string): header string
*
* Start new help section
*
* See alse [code example][1]
*
* ##### Example
*
* formatter.startSection(actionGroup.title);
* formatter.addText(actionGroup.description);
* formatter.addArguments(actionGroup._groupActions);
* formatter.endSection();
*
**/
HelpFormatter.prototype.startSection = function (heading) {
this._indent();
var section = new Section(this._currentSection, heading);
var func = section.formatHelp.bind(section);
this._addItem(func, [ this ]);
this._currentSection = section;
};
/**
* HelpFormatter#endSection -> Void
*
* End help section
*
* ##### Example
*
* formatter.startSection(actionGroup.title);
* formatter.addText(actionGroup.description);
* formatter.addArguments(actionGroup._groupActions);
* formatter.endSection();
**/
HelpFormatter.prototype.endSection = function () {
this._currentSection = this._currentSection._parent;
this._dedent();
};
/**
* HelpFormatter#addText(text) -> Void
* - text (string): plain text
*
* Add plain text into current section
*
* ##### Example
*
* formatter.startSection(actionGroup.title);
* formatter.addText(actionGroup.description);
* formatter.addArguments(actionGroup._groupActions);
* formatter.endSection();
*
**/
HelpFormatter.prototype.addText = function (text) {
if (text && text !== c.SUPPRESS) {
this._addItem(this._formatText, [ text ]);
}
};
/**
* HelpFormatter#addUsage(usage, actions, groups, prefix) -> Void
* - usage (string): usage text
* - actions (array): actions list
* - groups (array): groups list
* - prefix (string): usage prefix
*
* Add usage data into current section
*
* ##### Example
*
* formatter.addUsage(this.usage, this._actions, []);
* return formatter.formatHelp();
*
**/
HelpFormatter.prototype.addUsage = function (usage, actions, groups, prefix) {
if (usage !== c.SUPPRESS) {
this._addItem(this._formatUsage, [ usage, actions, groups, prefix ]);
}
};
/**
* HelpFormatter#addArgument(action) -> Void
* - action (object): action
*
* Add argument into current section
*
* Single variant of [[HelpFormatter#addArguments]]
**/
HelpFormatter.prototype.addArgument = function (action) {
if (action.help !== c.SUPPRESS) {
var self = this;
// find all invocations
var invocations = [ this._formatActionInvocation(action) ];
var invocationLength = invocations[0].length;
var actionLength;
if (action._getSubactions) {
this._indent();
action._getSubactions().forEach(function (subaction) {
var invocationNew = self._formatActionInvocation(subaction);
invocations.push(invocationNew);
invocationLength = Math.max(invocationLength, invocationNew.length);
});
this._dedent();
}
// update the maximum item length
actionLength = invocationLength + this._currentIndent;
this._actionMaxLength = Math.max(this._actionMaxLength, actionLength);
// add the item to the list
this._addItem(this._formatAction, [ action ]);
}
};
/**
* HelpFormatter#addArguments(actions) -> Void
* - actions (array): actions list
*
* Mass add arguments into current section
*
* ##### Example
*
* formatter.startSection(actionGroup.title);
* formatter.addText(actionGroup.description);
* formatter.addArguments(actionGroup._groupActions);
* formatter.endSection();
*
**/
HelpFormatter.prototype.addArguments = function (actions) {
var self = this;
actions.forEach(function (action) {
self.addArgument(action);
});
};
//
// Help-formatting methods
//
/**
* HelpFormatter#formatHelp -> string
*
* Format help
*
* ##### Example
*
* formatter.addText(this.epilog);
* return formatter.formatHelp();
*
**/
HelpFormatter.prototype.formatHelp = function () {
var help = this._rootSection.formatHelp(this);
if (help) {
help = help.replace(this._longBreakMatcher, c.EOL + c.EOL);
help = $$.trimChars(help, c.EOL) + c.EOL;
}
return help;
};
HelpFormatter.prototype._joinParts = function (partStrings) {
return partStrings.filter(function (part) {
return (part && part !== c.SUPPRESS);
}).join('');
};
HelpFormatter.prototype._formatUsage = function (usage, actions, groups, prefix) {
if (!prefix && typeof prefix !== 'string') {
prefix = 'usage: ';
}
actions = actions || [];
groups = groups || [];
// if usage is specified, use that
if (usage) {
usage = sprintf(usage, { prog: this._prog });
// if no optionals or positionals are available, usage is just prog
} else if (!usage && actions.length === 0) {
usage = this._prog;
// if optionals and positionals are available, calculate usage
} else if (!usage) {
var prog = this._prog;
var optionals = [];
var positionals = [];
var actionUsage;
var textWidth;
// split optionals from positionals
actions.forEach(function (action) {
if (action.isOptional()) {
optionals.push(action);
} else {
positionals.push(action);
}
});
// build full usage string
actionUsage = this._formatActionsUsage([].concat(optionals, positionals), groups);
usage = [ prog, actionUsage ].join(' ');
// wrap the usage parts if it's too long
textWidth = this._width - this._currentIndent;
if ((prefix.length + usage.length) > textWidth) {
// break usage into wrappable parts
var regexpPart = new RegExp('\\(.*?\\)+|\\[.*?\\]+|\\S+', 'g');
var optionalUsage = this._formatActionsUsage(optionals, groups);
var positionalUsage = this._formatActionsUsage(positionals, groups);
var optionalParts = optionalUsage.match(regexpPart);
var positionalParts = positionalUsage.match(regexpPart) || [];
if (optionalParts.join(' ') !== optionalUsage) {
throw new Error('assert "optionalParts.join(\' \') === optionalUsage"');
}
if (positionalParts.join(' ') !== positionalUsage) {
throw new Error('assert "positionalParts.join(\' \') === positionalUsage"');
}
// helper for wrapping lines
/*eslint-disable func-style*/ // node 0.10 compat
var _getLines = function (parts, indent, prefix) {
var lines = [];
var line = [];
var lineLength = prefix ? prefix.length - 1 : indent.length - 1;
parts.forEach(function (part) {
if (lineLength + 1 + part.length > textWidth) {
lines.push(indent + line.join(' '));
line = [];
lineLength = indent.length - 1;
}
line.push(part);
lineLength += part.length + 1;
});
if (line) {
lines.push(indent + line.join(' '));
}
if (prefix) {
lines[0] = lines[0].substr(indent.length);
}
return lines;
};
var lines, indent, parts;
// if prog is short, follow it with optionals or positionals
if (prefix.length + prog.length <= 0.75 * textWidth) {
indent = $$.repeat(' ', (prefix.length + prog.length + 1));
if (optionalParts) {
lines = [].concat(
_getLines([ prog ].concat(optionalParts), indent, prefix),
_getLines(positionalParts, indent)
);
} else if (positionalParts) {
lines = _getLines([ prog ].concat(positionalParts), indent, prefix);
} else {
lines = [ prog ];
}
// if prog is long, put it on its own line
} else {
indent = $$.repeat(' ', prefix.length);
parts = optionalParts.concat(positionalParts);
lines = _getLines(parts, indent);
if (lines.length > 1) {
lines = [].concat(
_getLines(optionalParts, indent),
_getLines(positionalParts, indent)
);
}
lines = [ prog ].concat(lines);
}
// join lines into usage
usage = lines.join(c.EOL);
}
}
// prefix with 'usage:'
return prefix + usage + c.EOL + c.EOL;
};
HelpFormatter.prototype._formatActionsUsage = function (actions, groups) {
// find group indices and identify actions in groups
var groupActions = [];
var inserts = [];
var self = this;
groups.forEach(function (group) {
var end;
var i;
var start = actions.indexOf(group._groupActions[0]);
if (start >= 0) {
end = start + group._groupActions.length;
//if (actions.slice(start, end) === group._groupActions) {
if ($$.arrayEqual(actions.slice(start, end), group._groupActions)) {
group._groupActions.forEach(function (action) {
groupActions.push(action);
});
if (!group.required) {
if (inserts[start]) {
inserts[start] += ' [';
} else {
inserts[start] = '[';
}
inserts[end] = ']';
} else {
if (inserts[start]) {
inserts[start] += ' (';
} else {
inserts[start] = '(';
}
inserts[end] = ')';
}
for (i = start + 1; i < end; i += 1) {
inserts[i] = '|';
}
}
}
});
// collect all actions format strings
var parts = [];
actions.forEach(function (action, actionIndex) {
var part;
var optionString;
var argsDefault;
var argsString;
// suppressed arguments are marked with None
// remove | separators for suppressed arguments
if (action.help === c.SUPPRESS) {
parts.push(null);
if (inserts[actionIndex] === '|') {
inserts.splice(actionIndex, actionIndex);
} else if (inserts[actionIndex + 1] === '|') {
inserts.splice(actionIndex + 1, actionIndex + 1);
}
// produce all arg strings
} else if (!action.isOptional()) {
part = self._formatArgs(action, action.dest);
// if it's in a group, strip the outer []
if (groupActions.indexOf(action) >= 0) {
if (part[0] === '[' && part[part.length - 1] === ']') {
part = part.slice(1, -1);
}
}
// add the action string to the list
parts.push(part);
// produce the first way to invoke the option in brackets
} else {
optionString = action.optionStrings[0];
// if the Optional doesn't take a value, format is: -s or --long
if (action.nargs === 0) {
part = '' + optionString;
// if the Optional takes a value, format is: -s ARGS or --long ARGS
} else {
argsDefault = action.dest.toUpperCase();
argsString = self._formatArgs(action, argsDefault);
part = optionString + ' ' + argsString;
}
// make it look optional if it's not required or in a group
if (!action.required && groupActions.indexOf(action) < 0) {
part = '[' + part + ']';
}
// add the action string to the list
parts.push(part);
}
});
// insert things at the necessary indices
for (var i = inserts.length - 1; i >= 0; --i) {
if (inserts[i] !== null) {
parts.splice(i, 0, inserts[i]);
}
}
// join all the action items with spaces
var text = parts.filter(function (part) {
return !!part;
}).join(' ');
// clean up separators for mutually exclusive groups
text = text.replace(/([\[(]) /g, '$1'); // remove spaces
text = text.replace(/ ([\])])/g, '$1');
text = text.replace(/\[ *\]/g, ''); // remove empty groups
text = text.replace(/\( *\)/g, '');
text = text.replace(/\(([^|]*)\)/g, '$1'); // remove () from single action groups
text = text.trim();
// return the text
return text;
};
HelpFormatter.prototype._formatText = function (text) {
text = sprintf(text, { prog: this._prog });
var textWidth = this._width - this._currentIndent;
var indentIncriment = $$.repeat(' ', this._currentIndent);
return this._fillText(text, textWidth, indentIncriment) + c.EOL + c.EOL;
};
HelpFormatter.prototype._formatAction = function (action) {
var self = this;
var helpText;
var helpLines;
var parts;
var indentFirst;
// determine the required width and the entry label
var helpPosition = Math.min(this._actionMaxLength + 2, this._maxHelpPosition);
var helpWidth = this._width - helpPosition;
var actionWidth = helpPosition - this._currentIndent - 2;
var actionHeader = this._formatActionInvocation(action);
// no help; start on same line and add a final newline
if (!action.help) {
actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL;
// short action name; start on the same line and pad two spaces
} else if (actionHeader.length <= actionWidth) {
actionHeader = $$.repeat(' ', this._currentIndent) +
actionHeader +
' ' +
$$.repeat(' ', actionWidth - actionHeader.length);
indentFirst = 0;
// long action name; start on the next line
} else {
actionHeader = $$.repeat(' ', this._currentIndent) + actionHeader + c.EOL;
indentFirst = helpPosition;
}
// collect the pieces of the action help
parts = [ actionHeader ];
// if there was help for the action, add lines of help text
if (action.help) {
helpText = this._expandHelp(action);
helpLines = this._splitLines(helpText, helpWidth);
parts.push($$.repeat(' ', indentFirst) + helpLines[0] + c.EOL);
helpLines.slice(1).forEach(function (line) {
parts.push($$.repeat(' ', helpPosition) + line + c.EOL);
});
// or add a newline if the description doesn't end with one
} else if (actionHeader.charAt(actionHeader.length - 1) !== c.EOL) {
parts.push(c.EOL);
}
// if there are any sub-actions, add their help as well
if (action._getSubactions) {
this._indent();
action._getSubactions().forEach(function (subaction) {
parts.push(self._formatAction(subaction));
});
this._dedent();
}
// return a single string
return this._joinParts(parts);
};
HelpFormatter.prototype._formatActionInvocation = function (action) {
if (!action.isOptional()) {
var format_func = this._metavarFormatter(action, action.dest);
var metavars = format_func(1);
return metavars[0];
}
var parts = [];
var argsDefault;
var argsString;
// if the Optional doesn't take a value, format is: -s, --long
if (action.nargs === 0) {
parts = parts.concat(action.optionStrings);
// if the Optional takes a value, format is: -s ARGS, --long ARGS
} else {
argsDefault = action.dest.toUpperCase();
argsString = this._formatArgs(action, argsDefault);
action.optionStrings.forEach(function (optionString) {
parts.push(optionString + ' ' + argsString);
});
}
return parts.join(', ');
};
HelpFormatter.prototype._metavarFormatter = function (action, metavarDefault) {
var result;
if (action.metavar || action.metavar === '') {
result = action.metavar;
} else if (action.choices) {
var choices = action.choices;
if (typeof choices === 'string') {
choices = choices.split('').join(', ');
} else if (Array.isArray(choices)) {
choices = choices.join(',');
} else {
choices = Object.keys(choices).join(',');
}
result = '{' + choices + '}';
} else {
result = metavarDefault;
}
return function (size) {
if (Array.isArray(result)) {
return result;
}
var metavars = [];
for (var i = 0; i < size; i += 1) {
metavars.push(result);
}
return metavars;
};
};
HelpFormatter.prototype._formatArgs = function (action, metavarDefault) {
var result;
var metavars;
var buildMetavar = this._metavarFormatter(action, metavarDefault);
switch (action.nargs) {
/*eslint-disable no-undefined*/
case undefined:
case null:
metavars = buildMetavar(1);
result = '' + metavars[0];
break;
case c.OPTIONAL:
metavars = buildMetavar(1);
result = '[' + metavars[0] + ']';
break;
case c.ZERO_OR_MORE:
metavars = buildMetavar(2);
result = '[' + metavars[0] + ' [' + metavars[1] + ' ...]]';
break;
case c.ONE_OR_MORE:
metavars = buildMetavar(2);
result = '' + metavars[0] + ' [' + metavars[1] + ' ...]';
break;
case c.REMAINDER:
result = '...';
break;
case c.PARSER:
metavars = buildMetavar(1);
result = metavars[0] + ' ...';
break;
default:
metavars = buildMetavar(action.nargs);
result = metavars.join(' ');
}
return result;
};
HelpFormatter.prototype._expandHelp = function (action) {
var params = { prog: this._prog };
Object.keys(action).forEach(function (actionProperty) {
var actionValue = action[actionProperty];
if (actionValue !== c.SUPPRESS) {
params[actionProperty] = actionValue;
}
});
if (params.choices) {
if (typeof params.choices === 'string') {
params.choices = params.choices.split('').join(', ');
} else if (Array.isArray(params.choices)) {
params.choices = params.choices.join(', ');
} else {
params.choices = Object.keys(params.choices).join(', ');
}
}
return sprintf(this._getHelpString(action), params);
};
HelpFormatter.prototype._splitLines = function (text, width) {
var lines = [];
var delimiters = [ ' ', '.', ',', '!', '?' ];
var re = new RegExp('[' + delimiters.join('') + '][^' + delimiters.join('') + ']*$');
text = text.replace(/[\n\|\t]/g, ' ');
text = text.trim();
text = text.replace(this._whitespaceMatcher, ' ');
// Wraps the single paragraph in text (a string) so every line
// is at most width characters long.
text.split(c.EOL).forEach(function (line) {
if (width >= line.length) {
lines.push(line);
return;
}
var wrapStart = 0;
var wrapEnd = width;
var delimiterIndex = 0;
while (wrapEnd <= line.length) {
if (wrapEnd !== line.length && delimiters.indexOf(line[wrapEnd] < -1)) {
delimiterIndex = (re.exec(line.substring(wrapStart, wrapEnd)) || {}).index;
wrapEnd = wrapStart + delimiterIndex + 1;
}
lines.push(line.substring(wrapStart, wrapEnd));
wrapStart = wrapEnd;
wrapEnd += width;
}
if (wrapStart < line.length) {
lines.push(line.substring(wrapStart, wrapEnd));
}
});
return lines;
};
HelpFormatter.prototype._fillText = function (text, width, indent) {
var lines = this._splitLines(text, width);
lines = lines.map(function (line) {
return indent + line;
});
return lines.join(c.EOL);
};
HelpFormatter.prototype._getHelpString = function (action) {
return action.help;
};
/**
* class Namespace
*
* Simple object for storing attributes. Implements equality by attribute names
* and values, and provides a simple string representation.
*
* See also [original guide][1]
*
* [1]:http://docs.python.org/dev/library/argparse.html#the-namespace-object
**/
'use strict';
var $$ = require('./utils');
/**
* new Namespace(options)
* - options(object): predefined propertis for result object
*
**/
var Namespace = module.exports = function Namespace(options) {
$$.extend(this, options);
};
/**
* Namespace#isset(key) -> Boolean
* - key (string|number): property name
*
* Tells whenever `namespace` contains given `key` or not.
**/
Namespace.prototype.isset = function (key) {
return $$.has(this, key);
};
/**
* Namespace#set(key, value) -> self
* -key (string|number|object): propery name
* -value (mixed): new property value
*
* Set the property named key with value.
* If key object then set all key properties to namespace object
**/
Namespace.prototype.set = function (key, value) {
if (typeof (key) === 'object') {
$$.extend(this, key);
} else {
this[key] = value;
}
return this;
};
/**
* Namespace#get(key, defaultValue) -> mixed
* - key (string|number): property name
* - defaultValue (mixed): default value
*
* Return the property key or defaulValue if not set
**/
Namespace.prototype.get = function (key, defaultValue) {
return !this[key] ? defaultValue : this[key];
};
/**
* Namespace#unset(key, defaultValue) -> mixed
* - key (string|number): property name
* - defaultValue (mixed): default value
*
* Return data[key](and delete it) or defaultValue
**/
Namespace.prototype.unset = function (key, defaultValue) {
var value = this[key];
if (value !== null) {
delete this[key];
return value;
}
return defaultValue;
};
'use strict';
exports.repeat = function (str, num) {
var result = '';
for (var i = 0; i < num; i++) { result += str; }
return result;
};
exports.arrayEqual = function (a, b) {
if (a.length !== b.length) { return false; }
for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) { return false; }
}
return true;
};
exports.trimChars = function (str, chars) {
var start = 0;
var end = str.length - 1;
while (chars.indexOf(str.charAt(start)) >= 0) { start++; }
while (chars.indexOf(str.charAt(end)) >= 0) { end--; }
return str.slice(start, end + 1);
};
exports.capitalize = function (str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
exports.arrayUnion = function () {
var result = [];
for (var i = 0, values = {}; i < arguments.length; i++) {
var arr = arguments[i];
for (var j = 0; j < arr.length; j++) {
if (!values[arr[j]]) {
values[arr[j]] = true;
result.push(arr[j]);
}
}
}
return result;
};
function has(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
exports.has = has;
exports.extend = function (dest, src) {
for (var i in src) {
if (has(src, i)) { dest[i] = src[i]; }
}
};
exports.trimEnd = function (str) {
return str.replace(/\s+$/g, '');
};
{
"name": "argparse",
"description": "Very powerful CLI arguments parser. Native port of argparse - python's options parsing library",
"version": "1.0.10",
"keywords": [
"cli",
"parser",
"argparse",
"option",
"args"
],
"contributors": [
"Eugene Shkuropat",
"Paul Jacobson"
],
"files": [
"index.js",
"lib/"
],
"license": "MIT",
"repository": "nodeca/argparse",
"scripts": {
"test": "make test"
},
"dependencies": {
"sprintf-js": "~1.0.2"
},
"devDependencies": {
"eslint": "^2.13.1",
"istanbul": "^0.4.5",
"mocha": "^3.1.0",
"ndoc": "^5.0.1"
}
}
declare namespace astralRegex {
interface Options {
/**
Only match an exact string. Useful with `RegExp#test()` to check if a string is a astral symbol. Default: `false` _(Matches any astral symbols in a string)_
*/
readonly exact?: boolean;
}
}
/**
Regular expression for matching [astral symbols](https://everything2.com/title/astral+plane).
@returns A `RegExp` for matching astral symbols.
@example
```
import astralRegex = require('astral-regex');
astralRegex({exact: true}).test('🦄');
//=> true
'foo 🦄 💩 bar'.match(astralRegex());
//=> ['🦄', '💩']
```
*/
declare function astralRegex(options?: astralRegex.Options): RegExp;
export = astralRegex;
'use strict';
const regex = '[\uD800-\uDBFF][\uDC00-\uDFFF]';
const astralRegex = options => options && options.exact ? new RegExp(`^${regex}$`) : new RegExp(regex, 'g');
module.exports = astralRegex;
MIT License
Copyright (c) Kevin Mårtensson <kevinmartensson@gmail.com> (github.com/kevva)
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.
{
"name": "astral-regex",
"version": "2.0.0",
"description": "Regular expression for matching astral symbols",
"license": "MIT",
"repository": "kevva/astral-regex",
"author": {
"name": "Kevin Mårtensson",
"email": "kevinmartensson@gmail.com",
"url": "github.com/kevva"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"astral",
"emoji",
"regex",
"surrogate"
],
"devDependencies": {
"ava": "^1.4.1",
"tsd": "^0.7.2",
"xo": "^0.24.0"
}
}
# astral-regex [![Build Status](https://travis-ci.org/kevva/astral-regex.svg?branch=master)](https://travis-ci.org/kevva/astral-regex)
> Regular expression for matching [astral symbols](https://everything2.com/title/astral+plane)
## Install
```
$ npm install astral-regex
```
## Usage
```js
const astralRegex = require('astral-regex');
astralRegex({exact: true}).test('🦄');
//=> true
'foo 🦄 💩 bar'.match(astralRegex());
//=> ['🦄', '💩']
```
## API
### astralRegex([options])
Returns a `RegExp` for matching astral symbols.
#### options
Type: `Object`
##### exact
Type: `boolean`<br>
Default: `false` *(Matches any astral symbols in a string)*
Only match an exact string. Useful with `RegExp#test()` to check if a string is a astral symbol.
## License
MIT © [Kevin Mårtensson](https://github.com/kevva)
1.20.0 / 2022-04-02
===================
* Fix error message for json parse whitespace in `strict`
* Fix internal error when inflated body exceeds limit
* Prevent loss of async hooks context
* Prevent hanging when request already read
* deps: depd@2.0.0
- Replace internal `eval` usage with `Function` constructor
- Use instance methods on `process` to check for listeners
* deps: http-errors@2.0.0
- deps: depd@2.0.0
- deps: statuses@2.0.1
* deps: on-finished@2.4.1
* deps: qs@6.10.3
* deps: raw-body@2.5.1
- deps: http-errors@2.0.0
1.19.2 / 2022-02-15
===================
* deps: bytes@3.1.2
* deps: qs@6.9.7
* Fix handling of `__proto__` keys
* deps: raw-body@2.4.3
- deps: bytes@3.1.2
1.19.1 / 2021-12-10
===================
* deps: bytes@3.1.1
* deps: http-errors@1.8.1
- deps: inherits@2.0.4
- deps: toidentifier@1.0.1
- deps: setprototypeof@1.2.0
* deps: qs@6.9.6
* deps: raw-body@2.4.2
- deps: bytes@3.1.1
- deps: http-errors@1.8.1
* deps: safe-buffer@5.2.1
* deps: type-is@~1.6.18
1.19.0 / 2019-04-25
===================
......
......@@ -2,7 +2,7 @@
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Build Status][travis-image]][travis-url]
[![Build Status][github-actions-ci-image]][github-actions-ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Node.js body parsing middleware.
......@@ -49,8 +49,6 @@ $ npm install body-parser
## API
<!-- eslint-disable no-unused-vars -->
```js
var bodyParser = require('body-parser')
```
......@@ -281,14 +279,15 @@ encoding of the request. The parsing can be aborted by throwing an error.
## Errors
The middlewares provided by this module create errors depending on the error
condition during parsing. The errors will typically have a `status`/`statusCode`
property that contains the suggested HTTP response code, an `expose` property
to determine if the `message` property should be displayed to the client, a
`type` property to determine the type of error without matching against the
`message`, and a `body` property containing the read body, if available.
The middlewares provided by this module create errors using the
[`http-errors` module](https://www.npmjs.com/package/http-errors). The errors
will typically have a `status`/`statusCode` property that contains the suggested
HTTP response code, an `expose` property to determine if the `message` property
should be displayed to the client, a `type` property to determine the type of
error without matching against the `message`, and a `body` property containing
the read body, if available.
The following are the common errors emitted, though any error can come through
The following are the common errors created, though any error can come through
for various reasons.
### content encoding unsupported
......@@ -299,6 +298,20 @@ contained an encoding but the "inflation" option was set to `false`. The
`'encoding.unsupported'`, and the `charset` property will be set to the
encoding that is unsupported.
### entity parse failed
This error will occur when the request contained an entity that could not be
parsed by the middleware. The `status` property is set to `400`, the `type`
property is set to `'entity.parse.failed'`, and the `body` property is set to
the entity value that failed parsing.
### entity verify failed
This error will occur when the request contained an entity that could not be
failed verification by the defined `verify` option. The `status` property is
set to `403`, the `type` property is set to `'entity.verify.failed'`, and the
`body` property is set to the entity value that failed verification.
### request aborted
This error will occur when the request is aborted by the client before reading
......@@ -329,6 +342,14 @@ to this middleware. This module operates directly on bytes only and you cannot
call `req.setEncoding` when using this module. The `status` property is set to
`500` and the `type` property is set to `'stream.encoding.set'`.
### stream is not readable
This error will occur when the request is no longer readable when this middleware
attempts to read it. This typically means something other than a middleware from
this module read the reqest body already and the middleware was also configured to
read the same request. The `status` property is set to `500` and the `type`
property is set to `'stream.not.readable'`.
### too many parameters
This error will occur when the content of the request exceeds the configured
......@@ -435,9 +456,9 @@ app.use(bodyParser.text({ type: 'text/html' }))
[npm-image]: https://img.shields.io/npm/v/body-parser.svg
[npm-url]: https://npmjs.org/package/body-parser
[travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg
[travis-url]: https://travis-ci.org/expressjs/body-parser
[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg
[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master
[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg
[downloads-url]: https://npmjs.org/package/body-parser
[github-actions-ci-image]: https://img.shields.io/github/workflow/status/expressjs/body-parser/ci/master?label=ci
[github-actions-ci-url]: https://github.com/expressjs/body-parser/actions/workflows/ci.yml
# Security Policies and Procedures
## Reporting a Bug
The Express team and community take all security bugs seriously. Thank you
for improving the security of Express. We appreciate your efforts and
responsible disclosure and will make every effort to acknowledge your
contributions.
Report security bugs by emailing the current owner(s) of `body-parser`. This
information can be found in the npm registry using the command
`npm owner ls body-parser`.
If unsure or unable to get the information from the above, open an issue
in the [project issue tracker](https://github.com/expressjs/body-parser/issues)
asking for the current contact information.
To ensure the timely response to your report, please ensure that the entirety
of the report is contained within the email body and not solely behind a web
link or an attachment.
At least one owner will acknowledge your email within 48 hours, and will send a
more detailed response within 48 hours indicating the next steps in handling
your report. After the initial reply to your report, the owners will
endeavor to keep you informed of the progress towards a fix and full
announcement, and may ask for additional information or guidance.
......@@ -12,9 +12,11 @@
*/
var createError = require('http-errors')
var destroy = require('destroy')
var getBody = require('raw-body')
var iconv = require('iconv-lite')
var onFinished = require('on-finished')
var unpipe = require('unpipe')
var zlib = require('zlib')
/**
......@@ -89,9 +91,14 @@ function read (req, res, next, parse, debug, options) {
_error = createError(400, error)
}
// unpipe from stream and destroy
if (stream !== req) {
unpipe(req)
destroy(stream, true)
}
// read off entire request
stream.resume()
onFinished(req, function onfinished () {
dump(req, function onfinished () {
next(createError(400, _error))
})
return
......@@ -179,3 +186,20 @@ function contentstream (req, debug, inflate) {
return stream
}
/**
* Dump the contents of a request.
*
* @param {object} req
* @param {function} callback
* @api private
*/
function dump (req, callback) {
if (onFinished.isFinished(req)) {
callback(null)
} else {
onFinished(req, callback)
req.resume()
}
}
......@@ -37,7 +37,7 @@ module.exports = json
* %x0D ) ; Carriage return
*/
var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex
var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*([^\x20\x09\x0a\x0d])/ // eslint-disable-line no-control-regex
/**
* Create a middleware to parse JSON bodies.
......@@ -122,7 +122,7 @@ function json (options) {
// assert charset per RFC 7159 sec 8.1
var charset = getCharset(req) || 'utf-8'
if (charset.substr(0, 4) !== 'utf-') {
if (charset.slice(0, 4) !== 'utf-') {
debug('invalid charset')
next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
charset: charset,
......@@ -152,7 +152,9 @@ function json (options) {
function createStrictSyntaxError (str, char) {
var index = str.indexOf(char)
var partial = str.substring(0, index) + '#'
var partial = index !== -1
? str.substring(0, index) + '#'
: ''
try {
JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation')
......@@ -173,7 +175,11 @@ function createStrictSyntaxError (str, char) {
*/
function firstchar (str) {
return FIRST_CHAR_REGEXP.exec(str)[1]
var match = FIRST_CHAR_REGEXP.exec(str)
return match
? match[1]
: undefined
}
/**
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment