UNPKG

@maserde/ut-client

Version:

Universitas Terbuka API Client

2,243 lines (1,831 loc) 975 kB
#!/usr/bin/env node 'use strict'; var require$$0$3 = require('path'); var require$$0$4 = require('tty'); var require$$1$1 = require('util'); var require$$1$2 = require('fs'); var require$$4$1 = require('net'); var require$$0$5 = require('events'); var require$$1$3 = require('stream'); var require$$3$1 = require('zlib'); var require$$0$6 = require('buffer'); var require$$1$4 = require('string_decoder'); var require$$8 = require('querystring'); var require$$0$7 = require('url'); var require$$0$8 = require('http'); var require$$0$9 = require('crypto'); var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } var express$2 = {exports: {}}; var bodyParser = {exports: {}}; /*! * depd * Copyright(c) 2014-2018 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. */ var relative = require$$0$3.relative; /** * Module exports. */ var depd_1 = depd; /** * Get the path to base files on. */ var basePath = process.cwd(); /** * Determine if namespace is contained in the string. */ function containsNamespace (str, namespace) { var vals = str.split(/[ ,]+/); var ns = String(namespace).toLowerCase(); for (var i = 0; i < vals.length; i++) { var val = vals[i]; // namespace contained if (val && (val === '*' || val.toLowerCase() === ns)) { return true } } return false } /** * Convert a data descriptor to accessor descriptor. */ function convertDataDescriptorToAccessor (obj, prop, message) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop); var value = descriptor.value; descriptor.get = function getter () { return value }; if (descriptor.writable) { descriptor.set = function setter (val) { return (value = val) }; } delete descriptor.value; delete descriptor.writable; Object.defineProperty(obj, prop, descriptor); return descriptor } /** * Create arguments string to keep arity. */ function createArgumentsString (arity) { var str = ''; for (var i = 0; i < arity; i++) { str += ', arg' + i; } return str.substr(2) } /** * Create stack string from stack. */ function createStackString (stack) { var str = this.name + ': ' + this.namespace; if (this.message) { str += ' deprecated ' + this.message; } for (var i = 0; i < stack.length; i++) { str += '\n at ' + stack[i].toString(); } return str } /** * Create deprecate for namespace in caller. */ function depd (namespace) { if (!namespace) { throw new TypeError('argument namespace is required') } var stack = getStack(); var site = callSiteLocation(stack[1]); var file = site[0]; function deprecate (message) { // call to self as log log.call(deprecate, message); } deprecate._file = file; deprecate._ignored = isignored(namespace); deprecate._namespace = namespace; deprecate._traced = istraced(namespace); deprecate._warned = Object.create(null); deprecate.function = wrapfunction; deprecate.property = wrapproperty; return deprecate } /** * Determine if event emitter has listeners of a given type. * * The way to do this check is done three different ways in Node.js >= 0.8 * so this consolidates them into a minimal set using instance methods. * * @param {EventEmitter} emitter * @param {string} type * @returns {boolean} * @private */ function eehaslisteners (emitter, type) { var count = typeof emitter.listenerCount !== 'function' ? emitter.listeners(type).length : emitter.listenerCount(type); return count > 0 } /** * Determine if namespace is ignored. */ function isignored (namespace) { if (process.noDeprecation) { // --no-deprecation support return true } var str = process.env.NO_DEPRECATION || ''; // namespace ignored return containsNamespace(str, namespace) } /** * Determine if namespace is traced. */ function istraced (namespace) { if (process.traceDeprecation) { // --trace-deprecation support return true } var str = process.env.TRACE_DEPRECATION || ''; // namespace traced return containsNamespace(str, namespace) } /** * Display deprecation message. */ function log (message, site) { var haslisteners = eehaslisteners(process, 'deprecation'); // abort early if no destination if (!haslisteners && this._ignored) { return } var caller; var callFile; var callSite; var depSite; var i = 0; var seen = false; var stack = getStack(); var file = this._file; if (site) { // provided site depSite = site; callSite = callSiteLocation(stack[1]); callSite.name = depSite.name; file = callSite[0]; } else { // get call site i = 2; depSite = callSiteLocation(stack[i]); callSite = depSite; } // get caller of deprecated thing in relation to file for (; i < stack.length; i++) { caller = callSiteLocation(stack[i]); callFile = caller[0]; if (callFile === file) { seen = true; } else if (callFile === this._file) { file = this._file; } else if (seen) { break } } var key = caller ? depSite.join(':') + '__' + caller.join(':') : undefined; if (key !== undefined && key in this._warned) { // already warned return } this._warned[key] = true; // generate automatic message from call site var msg = message; if (!msg) { msg = callSite === depSite || !callSite.name ? defaultMessage(depSite) : defaultMessage(callSite); } // emit deprecation if listeners exist if (haslisteners) { var err = DeprecationError(this._namespace, msg, stack.slice(i)); process.emit('deprecation', err); return } // format and write message var format = process.stderr.isTTY ? formatColor : formatPlain; var output = format.call(this, msg, caller, stack.slice(i)); process.stderr.write(output + '\n', 'utf8'); } /** * Get call site location as array. */ function callSiteLocation (callSite) { var file = callSite.getFileName() || '<anonymous>'; var line = callSite.getLineNumber(); var colm = callSite.getColumnNumber(); if (callSite.isEval()) { file = callSite.getEvalOrigin() + ', ' + file; } var site = [file, line, colm]; site.callSite = callSite; site.name = callSite.getFunctionName(); return site } /** * Generate a default message from the site. */ function defaultMessage (site) { var callSite = site.callSite; var funcName = site.name; // make useful anonymous name if (!funcName) { funcName = '<anonymous@' + formatLocation(site) + '>'; } var context = callSite.getThis(); var typeName = context && callSite.getTypeName(); // ignore useless type name if (typeName === 'Object') { typeName = undefined; } // make useful type name if (typeName === 'Function') { typeName = context.name || typeName; } return typeName && callSite.getMethodName() ? typeName + '.' + funcName : funcName } /** * Format deprecation message without color. */ function formatPlain (msg, caller, stack) { var timestamp = new Date().toUTCString(); var formatted = timestamp + ' ' + this._namespace + ' deprecated ' + msg; // add stack trace if (this._traced) { for (var i = 0; i < stack.length; i++) { formatted += '\n at ' + stack[i].toString(); } return formatted } if (caller) { formatted += ' at ' + formatLocation(caller); } return formatted } /** * Format deprecation message with color. */ function formatColor (msg, caller, stack) { var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow ' \x1b[0m' + msg + '\x1b[39m'; // reset // add stack trace if (this._traced) { for (var i = 0; i < stack.length; i++) { formatted += '\n \x1b[36mat ' + stack[i].toString() + '\x1b[39m'; // cyan } return formatted } if (caller) { formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m'; // cyan } return formatted } /** * Format call site location. */ function formatLocation (callSite) { return relative(basePath, callSite[0]) + ':' + callSite[1] + ':' + callSite[2] } /** * Get the stack as array of call sites. */ function getStack () { var limit = Error.stackTraceLimit; var obj = {}; var prep = Error.prepareStackTrace; Error.prepareStackTrace = prepareObjectStackTrace; Error.stackTraceLimit = Math.max(10, limit); // capture the stack Error.captureStackTrace(obj); // slice this function off the top var stack = obj.stack.slice(1); Error.prepareStackTrace = prep; Error.stackTraceLimit = limit; return stack } /** * Capture call site stack from v8. */ function prepareObjectStackTrace (obj, stack) { return stack } /** * Return a wrapped function in a deprecation message. */ function wrapfunction (fn, message) { if (typeof fn !== 'function') { throw new TypeError('argument fn must be a function') } var args = createArgumentsString(fn.length); var stack = getStack(); var site = callSiteLocation(stack[1]); site.name = fn.name; // eslint-disable-next-line no-new-func var deprecatedfn = new Function('fn', 'log', 'deprecate', 'message', 'site', '"use strict"\n' + 'return function (' + args + ') {' + 'log.call(deprecate, message, site)\n' + 'return fn.apply(this, arguments)\n' + '}')(fn, log, this, message, site); return deprecatedfn } /** * Wrap property in a deprecation message. */ function wrapproperty (obj, prop, message) { if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { throw new TypeError('argument obj must be object') } var descriptor = Object.getOwnPropertyDescriptor(obj, prop); if (!descriptor) { throw new TypeError('must call property on owner object') } if (!descriptor.configurable) { throw new TypeError('property must be configurable') } var deprecate = this; var stack = getStack(); var site = callSiteLocation(stack[1]); // set site name site.name = prop; // convert data descriptor if ('value' in descriptor) { descriptor = convertDataDescriptorToAccessor(obj, prop); } var get = descriptor.get; var set = descriptor.set; // wrap getter if (typeof get === 'function') { descriptor.get = function getter () { log.call(deprecate, message, site); return get.apply(this, arguments) }; } // wrap setter if (typeof set === 'function') { descriptor.set = function setter () { log.call(deprecate, message, site); return set.apply(this, arguments) }; } Object.defineProperty(obj, prop, descriptor); } /** * Create DeprecationError for deprecation */ function DeprecationError (namespace, message, stack) { var error = new Error(); var stackString; Object.defineProperty(error, 'constructor', { value: DeprecationError }); Object.defineProperty(error, 'message', { configurable: true, enumerable: false, value: message, writable: true }); Object.defineProperty(error, 'name', { enumerable: false, configurable: true, value: 'DeprecationError', writable: true }); Object.defineProperty(error, 'namespace', { configurable: true, enumerable: false, value: namespace, writable: true }); Object.defineProperty(error, 'stack', { configurable: true, enumerable: false, get: function () { if (stackString !== undefined) { return stackString } // prepare stack trace return (stackString = createStackString.call(this, stack)) }, set: function setter (val) { stackString = val; } }); return error } var bytes = {exports: {}}; /*! * bytes * Copyright(c) 2012-2014 TJ Holowaychuk * Copyright(c) 2015 Jed Watson * MIT Licensed */ var hasRequiredBytes; function requireBytes () { if (hasRequiredBytes) return bytes.exports; hasRequiredBytes = 1; /** * Module exports. * @public */ bytes.exports = bytes$1; bytes.exports.format = format; bytes.exports.parse = parse; /** * Module variables. * @private */ var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; var map = { b: 1, kb: 1 << 10, mb: 1 << 20, gb: 1 << 30, tb: Math.pow(1024, 4), pb: Math.pow(1024, 5), }; var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; /** * Convert the given value in bytes into a string or parse to string to an integer in bytes. * * @param {string|number} value * @param {{ * case: [string], * decimalPlaces: [number] * fixedDecimals: [boolean] * thousandsSeparator: [string] * unitSeparator: [string] * }} [options] bytes options. * * @returns {string|number|null} */ function bytes$1(value, options) { if (typeof value === 'string') { return parse(value); } if (typeof value === 'number') { return format(value, options); } return null; } /** * Format the given value in bytes into a string. * * If the value is negative, it is kept as such. If it is a float, * it is rounded. * * @param {number} value * @param {object} [options] * @param {number} [options.decimalPlaces=2] * @param {number} [options.fixedDecimals=false] * @param {string} [options.thousandsSeparator=] * @param {string} [options.unit=] * @param {string} [options.unitSeparator=] * * @returns {string|null} * @public */ function format(value, options) { if (!Number.isFinite(value)) { return null; } var mag = Math.abs(value); var thousandsSeparator = (options && options.thousandsSeparator) || ''; var unitSeparator = (options && options.unitSeparator) || ''; var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; var fixedDecimals = Boolean(options && options.fixedDecimals); var unit = (options && options.unit) || ''; if (!unit || !map[unit.toLowerCase()]) { if (mag >= map.pb) { unit = 'PB'; } else if (mag >= map.tb) { unit = 'TB'; } else if (mag >= map.gb) { unit = 'GB'; } else if (mag >= map.mb) { unit = 'MB'; } else if (mag >= map.kb) { unit = 'KB'; } else { unit = 'B'; } } var val = value / map[unit.toLowerCase()]; var str = val.toFixed(decimalPlaces); if (!fixedDecimals) { str = str.replace(formatDecimalsRegExp, '$1'); } if (thousandsSeparator) { str = str.split('.').map(function (s, i) { return i === 0 ? s.replace(formatThousandsRegExp, thousandsSeparator) : s }).join('.'); } return str + unitSeparator + unit; } /** * Parse the string value into an integer in bytes. * * If no unit is given, it is assumed the value is in bytes. * * @param {number|string} val * * @returns {number|null} * @public */ function parse(val) { if (typeof val === 'number' && !isNaN(val)) { return val; } if (typeof val !== 'string') { return null; } // Test if the string passed is valid var results = parseRegExp.exec(val); var floatValue; var unit = 'b'; if (!results) { // Nothing could be extracted from the given string floatValue = parseInt(val, 10); unit = 'b'; } else { // Retrieve the value and the unit floatValue = parseFloat(results[1]); unit = results[4].toLowerCase(); } if (isNaN(floatValue)) { return null; } return Math.floor(map[unit] * floatValue); } return bytes.exports; } var contentType = {}; /*! * content-type * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ /** * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 * * parameter = token "=" ( token / quoted-string ) * token = 1*tchar * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" * / DIGIT / ALPHA * ; any VCHAR, except delimiters * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text * obs-text = %x80-FF * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) */ var PARAM_REGEXP$1 = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; // eslint-disable-line no-control-regex var TEXT_REGEXP$1 = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/; // eslint-disable-line no-control-regex var TOKEN_REGEXP$1 = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; /** * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 * * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) * obs-text = %x80-FF */ var QESC_REGEXP$1 = /\\([\u000b\u0020-\u00ff])/g; // eslint-disable-line no-control-regex /** * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 */ var QUOTE_REGEXP$1 = /([\\"])/g; /** * RegExp to match type in RFC 7231 sec 3.1.1.1 * * media-type = type "/" subtype * type = token * subtype = token */ var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; /** * Module exports. * @public */ contentType.format = format$2; contentType.parse = parse$9; /** * Format object to media type. * * @param {object} obj * @return {string} * @public */ function format$2 (obj) { if (!obj || typeof obj !== 'object') { throw new TypeError('argument obj is required') } var parameters = obj.parameters; var type = obj.type; if (!type || !TYPE_REGEXP.test(type)) { throw new TypeError('invalid type') } var string = type; // append parameters if (parameters && typeof parameters === 'object') { var param; var params = Object.keys(parameters).sort(); for (var i = 0; i < params.length; i++) { param = params[i]; if (!TOKEN_REGEXP$1.test(param)) { throw new TypeError('invalid parameter name') } string += '; ' + param + '=' + qstring$2(parameters[param]); } } return string } /** * Parse media type to object. * * @param {string|object} string * @return {Object} * @public */ function parse$9 (string) { if (!string) { throw new TypeError('argument string is required') } // support req/res-like objects as argument var header = typeof string === 'object' ? getcontenttype$1(string) : string; if (typeof header !== 'string') { throw new TypeError('argument string is required to be a string') } var index = header.indexOf(';'); var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); if (!TYPE_REGEXP.test(type)) { throw new TypeError('invalid media type') } var obj = new ContentType(type.toLowerCase()); // parse parameters if (index !== -1) { var key; var match; var value; PARAM_REGEXP$1.lastIndex = index; while ((match = PARAM_REGEXP$1.exec(header))) { if (match.index !== index) { throw new TypeError('invalid parameter format') } index += match[0].length; key = match[1].toLowerCase(); value = match[2]; if (value.charCodeAt(0) === 0x22 /* " */) { // remove quotes value = value.slice(1, -1); // remove escapes if (value.indexOf('\\') !== -1) { value = value.replace(QESC_REGEXP$1, '$1'); } } obj.parameters[key] = value; } if (index !== header.length) { throw new TypeError('invalid parameter format') } } return obj } /** * Get content-type from req/res objects. * * @param {object} * @return {Object} * @private */ function getcontenttype$1 (obj) { var header; if (typeof obj.getHeader === 'function') { // res-like header = obj.getHeader('content-type'); } else if (typeof obj.headers === 'object') { // req-like header = obj.headers && obj.headers['content-type']; } if (typeof header !== 'string') { throw new TypeError('content-type header is missing from object') } return header } /** * Quote a string if necessary. * * @param {string} val * @return {string} * @private */ function qstring$2 (val) { var str = String(val); // no need to quote tokens if (TOKEN_REGEXP$1.test(str)) { return str } if (str.length > 0 && !TEXT_REGEXP$1.test(str)) { throw new TypeError('invalid parameter value') } return '"' + str.replace(QUOTE_REGEXP$1, '\\$1') + '"' } /** * Class to represent a content type. * @private */ function ContentType (type) { this.parameters = Object.create(null); this.type = type; } var httpErrors = {exports: {}}; /* eslint no-proto: 0 */ var setprototypeof = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties); function setProtoOf (obj, proto) { obj.__proto__ = proto; return obj } function mixinProperties (obj, proto) { for (var prop in proto) { if (!Object.prototype.hasOwnProperty.call(obj, prop)) { obj[prop] = proto[prop]; } } return obj } var require$$0$2 = { "100": "Continue", "101": "Switching Protocols", "102": "Processing", "103": "Early Hints", "200": "OK", "201": "Created", "202": "Accepted", "203": "Non-Authoritative Information", "204": "No Content", "205": "Reset Content", "206": "Partial Content", "207": "Multi-Status", "208": "Already Reported", "226": "IM Used", "300": "Multiple Choices", "301": "Moved Permanently", "302": "Found", "303": "See Other", "304": "Not Modified", "305": "Use Proxy", "307": "Temporary Redirect", "308": "Permanent Redirect", "400": "Bad Request", "401": "Unauthorized", "402": "Payment Required", "403": "Forbidden", "404": "Not Found", "405": "Method Not Allowed", "406": "Not Acceptable", "407": "Proxy Authentication Required", "408": "Request Timeout", "409": "Conflict", "410": "Gone", "411": "Length Required", "412": "Precondition Failed", "413": "Payload Too Large", "414": "URI Too Long", "415": "Unsupported Media Type", "416": "Range Not Satisfiable", "417": "Expectation Failed", "418": "I'm a Teapot", "421": "Misdirected Request", "422": "Unprocessable Entity", "423": "Locked", "424": "Failed Dependency", "425": "Too Early", "426": "Upgrade Required", "428": "Precondition Required", "429": "Too Many Requests", "431": "Request Header Fields Too Large", "451": "Unavailable For Legal Reasons", "500": "Internal Server Error", "501": "Not Implemented", "502": "Bad Gateway", "503": "Service Unavailable", "504": "Gateway Timeout", "505": "HTTP Version Not Supported", "506": "Variant Also Negotiates", "507": "Insufficient Storage", "508": "Loop Detected", "509": "Bandwidth Limit Exceeded", "510": "Not Extended", "511": "Network Authentication Required" }; /*! * statuses * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2016 Douglas Christopher Wilson * MIT Licensed */ /** * Module dependencies. * @private */ var codes = require$$0$2; /** * Module exports. * @public */ var statuses$3 = status; // status code to message map status.message = codes; // status message (lower-case) to code map status.code = createMessageToStatusCodeMap(codes); // array of status codes status.codes = createStatusCodeList(codes); // status codes for redirects status.redirect = { 300: true, 301: true, 302: true, 303: true, 305: true, 307: true, 308: true }; // status codes for empty bodies status.empty = { 204: true, 205: true, 304: true }; // status codes for when you should retry the request status.retry = { 502: true, 503: true, 504: true }; /** * Create a map of message to status code. * @private */ function createMessageToStatusCodeMap (codes) { var map = {}; Object.keys(codes).forEach(function forEachCode (code) { var message = codes[code]; var status = Number(code); // populate map map[message.toLowerCase()] = status; }); return map } /** * Create a list of all status codes. * @private */ function createStatusCodeList (codes) { return Object.keys(codes).map(function mapCode (code) { return Number(code) }) } /** * Get the status code for given message. * @private */ function getStatusCode (message) { var msg = message.toLowerCase(); if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { throw new Error('invalid status message: "' + message + '"') } return status.code[msg] } /** * Get the status message for given code. * @private */ function getStatusMessage (code) { if (!Object.prototype.hasOwnProperty.call(status.message, code)) { throw new Error('invalid status code: ' + code) } return status.message[code] } /** * Get the status code. * * Given a number, this will throw if it is not a known status * code, otherwise the code will be returned. Given a string, * the string will be parsed for a number and return the code * if valid, otherwise will lookup the code assuming this is * the status message. * * @param {string|number} code * @returns {number} * @public */ function status (code) { if (typeof code === 'number') { return getStatusMessage(code) } if (typeof code !== 'string') { throw new TypeError('code must be a number or string') } // '403' var n = parseInt(code, 10); if (!isNaN(n)) { return getStatusMessage(n) } return getStatusCode(code) } var inherits = {exports: {}}; var inherits_browser = {exports: {}}; var hasRequiredInherits_browser; function requireInherits_browser () { if (hasRequiredInherits_browser) return inherits_browser.exports; hasRequiredInherits_browser = 1; if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module inherits_browser.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } }; } else { // old school shim for old browsers inherits_browser.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; var TempCtor = function () {}; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } }; } return inherits_browser.exports; } try { var util$1 = require('util'); /* istanbul ignore next */ if (typeof util$1.inherits !== 'function') throw ''; inherits.exports = util$1.inherits; } catch (e) { /* istanbul ignore next */ inherits.exports = requireInherits_browser(); } var inheritsExports = inherits.exports; /*! * toidentifier * Copyright(c) 2016 Douglas Christopher Wilson * MIT Licensed */ /** * Module exports. * @public */ var toidentifier = toIdentifier; /** * Trasform the given string into a JavaScript identifier * * @param {string} str * @returns {string} * @public */ function toIdentifier (str) { return str .split(' ') .map(function (token) { return token.slice(0, 1).toUpperCase() + token.slice(1) }) .join('') .replace(/[^ _0-9a-z]/gi, '') } /*! * http-errors * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2016 Douglas Christopher Wilson * MIT Licensed */ (function (module) { /** * Module dependencies. * @private */ var deprecate = depd_1('http-errors'); var setPrototypeOf = setprototypeof; var statuses = statuses$3; var inherits = inheritsExports; var toIdentifier = toidentifier; /** * Module exports. * @public */ module.exports = createError; module.exports.HttpError = createHttpErrorConstructor(); module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError); // Populate exports for all constructors populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError); /** * Get the code class of a status code. * @private */ function codeClass (status) { return Number(String(status).charAt(0) + '00') } /** * Create a new HTTP Error. * * @returns {Error} * @public */ function createError () { // so much arity going on ~_~ var err; var msg; var status = 500; var props = {}; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; var type = typeof arg; if (type === 'object' && arg instanceof Error) { err = arg; status = err.status || err.statusCode || status; } else if (type === 'number' && i === 0) { status = arg; } else if (type === 'string') { msg = arg; } else if (type === 'object') { props = arg; } else { throw new TypeError('argument #' + (i + 1) + ' unsupported type ' + type) } } if (typeof status === 'number' && (status < 400 || status >= 600)) { deprecate('non-error status code; use only 4xx or 5xx status codes'); } if (typeof status !== 'number' || (!statuses.message[status] && (status < 400 || status >= 600))) { status = 500; } // constructor var HttpError = createError[status] || createError[codeClass(status)]; if (!err) { // create error err = HttpError ? new HttpError(msg) : new Error(msg || statuses.message[status]); Error.captureStackTrace(err, createError); } if (!HttpError || !(err instanceof HttpError) || err.status !== status) { // add properties to generic error err.expose = status < 500; err.status = err.statusCode = status; } for (var key in props) { if (key !== 'status' && key !== 'statusCode') { err[key] = props[key]; } } return err } /** * Create HTTP error abstract base class. * @private */ function createHttpErrorConstructor () { function HttpError () { throw new TypeError('cannot construct abstract class') } inherits(HttpError, Error); return HttpError } /** * Create a constructor for a client error. * @private */ function createClientErrorConstructor (HttpError, name, code) { var className = toClassName(name); function ClientError (message) { // create the error object var msg = message != null ? message : statuses.message[code]; var err = new Error(msg); // capture a stack trace to the construction point Error.captureStackTrace(err, ClientError); // adjust the [[Prototype]] setPrototypeOf(err, ClientError.prototype); // redefine the error message Object.defineProperty(err, 'message', { enumerable: true, configurable: true, value: msg, writable: true }); // redefine the error name Object.defineProperty(err, 'name', { enumerable: false, configurable: true, value: className, writable: true }); return err } inherits(ClientError, HttpError); nameFunc(ClientError, className); ClientError.prototype.status = code; ClientError.prototype.statusCode = code; ClientError.prototype.expose = true; return ClientError } /** * Create function to test is a value is a HttpError. * @private */ function createIsHttpErrorFunction (HttpError) { return function isHttpError (val) { if (!val || typeof val !== 'object') { return false } if (val instanceof HttpError) { return true } return val instanceof Error && typeof val.expose === 'boolean' && typeof val.statusCode === 'number' && val.status === val.statusCode } } /** * Create a constructor for a server error. * @private */ function createServerErrorConstructor (HttpError, name, code) { var className = toClassName(name); function ServerError (message) { // create the error object var msg = message != null ? message : statuses.message[code]; var err = new Error(msg); // capture a stack trace to the construction point Error.captureStackTrace(err, ServerError); // adjust the [[Prototype]] setPrototypeOf(err, ServerError.prototype); // redefine the error message Object.defineProperty(err, 'message', { enumerable: true, configurable: true, value: msg, writable: true }); // redefine the error name Object.defineProperty(err, 'name', { enumerable: false, configurable: true, value: className, writable: true }); return err } inherits(ServerError, HttpError); nameFunc(ServerError, className); ServerError.prototype.status = code; ServerError.prototype.statusCode = code; ServerError.prototype.expose = false; return ServerError } /** * Set the name of a function, if possible. * @private */ function nameFunc (func, name) { var desc = Object.getOwnPropertyDescriptor(func, 'name'); if (desc && desc.configurable) { desc.value = name; Object.defineProperty(func, 'name', desc); } } /** * Populate the exports object with constructors for every error class. * @private */ function populateConstructorExports (exports, codes, HttpError) { codes.forEach(function forEachCode (code) { var CodeError; var name = toIdentifier(statuses.message[code]); switch (codeClass(code)) { case 400: CodeError = createClientErrorConstructor(HttpError, name, code); break case 500: CodeError = createServerErrorConstructor(HttpError, name, code); break } if (CodeError) { // export the constructor exports[code] = CodeError; exports[name] = CodeError; } }); } /** * Get a class name from a name identifier. * @private */ function toClassName (name) { return name.substr(-5) !== 'Error' ? name + 'Error' : name } } (httpErrors)); var httpErrorsExports = httpErrors.exports; var src = {exports: {}}; var browser = {exports: {}}; var debug$6 = {exports: {}}; /** * Helpers. */ var ms$2; var hasRequiredMs; function requireMs () { if (hasRequiredMs) return ms$2; hasRequiredMs = 1; var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} [options] * @throws {Error} throw an error if val is not a non-empty string or a number * @return {String|Number} * @api public */ ms$2 = function(val, options) { options = options || {}; var type = typeof val; if (type === 'string' && val.length > 0) { return parse(val); } else if (type === 'number' && isNaN(val) === false) { return options.long ? fmtLong(val) : fmtShort(val); } throw new Error( 'val is not a non-empty string or a valid number. val=' + JSON.stringify(val) ); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = String(str); if (str.length > 100) { return; } var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( str ); if (!match) { return; } var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; default: return undefined; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtShort(ms) { if (ms >= d) { return Math.round(ms / d) + 'd'; } if (ms >= h) { return Math.round(ms / h) + 'h'; } if (ms >= m) { return Math.round(ms / m) + 'm'; } if (ms >= s) { return Math.round(ms / s) + 's'; } return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function fmtLong(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) { return; } if (ms < n * 1.5) { return Math.floor(ms / n) + ' ' + name; } return Math.ceil(ms / n) + ' ' + name + 's'; } return ms$2; } var hasRequiredDebug; function requireDebug () { if (hasRequiredDebug) return debug$6.exports; hasRequiredDebug = 1; (function (module, exports) { /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = requireMs(); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". */ exports.formatters = {}; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * @param {String} namespace * @return {Number} * @api private */ function selectColor(namespace) { var hash = 0, i; for (i in namespace) { hash = ((hash << 5) - hash) + namespace.charCodeAt(i); hash |= 0; // Convert to 32bit integer } return exports.colors[Math.abs(hash) % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function createDebug(namespace) { function debug() { // disabled? if (!debug.enabled) return; var self = debug; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // turn the `arguments` into a proper Array var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %O args.unshift('%O'); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); // apply env-specific formatting (colors, etc.) exports.formatArgs.call(self, args); var logFn = debug.log || exports.log || console.log.bind(console); logFn.apply(self, args); } debug.namespace = namespace; debug.enabled = exports.enabled(namespace); debug.useColors = exports.useColors(); debug.color = selectColor(namespace); // env-specific initialization logic for debug instances if ('function' === typeof exports.init) { exports.init(debug); } return debug; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); exports.names = []; exports.skips = []; var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } } (debug$6, debug$6.exports)); return debug$6.exports; } /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ var hasRequiredBrowser; function requireBrowser () { if (hasRequiredBrowser) return browser.exports; hasRequiredBrowser = 1; (function (module, exports) { exports = module.exports = requireDebug(); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // NB: In an Electron preload script, document will be defined but not fully // initialized. Since we know we're in Chrome, we'll just detect this case // explicitly if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; } // is webkit? http://stackoverflow.com/a/16459606/376773 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || // is firebug? http://stackoverflow.com/a/398120/376773 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || // double check webkit in userAgent just in case we are in a worker (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { try { return JSON.stringify(v); } catch (err) { return '[UnexpectedJSONParseError]: ' + err.message; } }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs(args) { var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return; var c = 'color: ' + this.color; args.splice(1, 0, c, 'color: inherit'); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-zA-Z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} // If debug isn't set in LS, and we're in Electron, try to load $DEBUG if (!r && typeof process !== 'undefined' && 'env' in process) { r = process.env.DEBUG; } return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage() { try { return window.localStorage; } catch (e) {} } } (browser, browser.exports)); return browser.exports; } var node = {exports: {}}; /** * Module dependencies. */ var hasRequiredNode; function requireNode () { if (hasRequiredNode) return node.exports; hasRequiredNode = 1; (function (module, exports) { var tty = require$$0$4; var util = require$$1$1; /** * This is the Node.js implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = requireDebug(); exports.init = init; exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; /** * Colors. */ exports.colors = [6, 2, 3, 4, 5, 1]; /** * Build up the default `inspectOpts` object from the environment variables. * * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js */ exports.inspectOpts = Object.keys(process.env).filter(function (key) { return /^debug_/i.test(key); }).reduce(function (obj, key) { // camel-case var prop = key .substring(6) .toLowerCase() .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); // coerce string value into JS value var val = process.env[key]; if (/^(yes|on|true|enabled)$/i.test(val)) val = true; else if (/^(no|off|false|disabled)$/i.test(val)) val = false; else if (val === 'null') val = null; else val = Number(val); obj[prop] = val; return obj; }, {}); /** * The file descriptor to write the `debug()` calls to. * Set the `DEBUG_FD` env variable to override with another value. i.e.: * * $ DEBUG_FD=3 node script.js 3>debug.log */ var fd = parseInt(process.env.DEBUG_FD, 10) || 2; if (1 !== fd && 2 !== fd) { util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')(); } var stream = 1 === fd ? process.stdout : 2 === fd ? process.stderr : createWritableStdioStream(fd); /** * Is stdout a TTY? Colored output is enabled when `true`. */ function useColors() { return 'colors' in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(fd); } /** * Map %o to `util.inspect()`, all on a single line. */ exports.format