Deployed the page to Github Pages.

This commit is contained in:
Batuhan Berk Başoğlu 2024-11-03 21:30:09 -05:00
parent 1d79754e93
commit 2c89899458
Signed by: batuhan-basoglu
SSH key fingerprint: SHA256:kEsnuHX+qbwhxSAXPUQ4ox535wFHu/hIRaa53FzxRpo
62797 changed files with 6551425 additions and 15279 deletions

19
node_modules/winston/LICENSE generated vendored Normal file
View file

@ -0,0 +1,19 @@
Copyright (c) 2010 Charlie Robbins
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.

1271
node_modules/winston/README.md generated vendored Normal file

File diff suppressed because it is too large Load diff

171
node_modules/winston/dist/winston.js generated vendored Normal file
View file

@ -0,0 +1,171 @@
/**
* winston.js: Top-level include defining Winston.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
var logform = require('logform');
var _require = require('./winston/common'),
warn = _require.warn;
/**
* Expose version. Use `require` method for `webpack` support.
* @type {string}
*/
exports.version = require('../package.json').version;
/**
* Include transports defined by default by winston
* @type {Array}
*/
exports.transports = require('./winston/transports');
/**
* Expose utility methods
* @type {Object}
*/
exports.config = require('./winston/config');
/**
* Hoist format-related functionality from logform.
* @type {Object}
*/
exports.addColors = logform.levels;
/**
* Hoist format-related functionality from logform.
* @type {Object}
*/
exports.format = logform.format;
/**
* Expose core Logging-related prototypes.
* @type {function}
*/
exports.createLogger = require('./winston/create-logger');
/**
* Expose core Logging-related prototypes.
* @type {function}
*/
exports.Logger = require('./winston/logger');
/**
* Expose core Logging-related prototypes.
* @type {Object}
*/
exports.ExceptionHandler = require('./winston/exception-handler');
/**
* Expose core Logging-related prototypes.
* @type {Object}
*/
exports.RejectionHandler = require('./winston/rejection-handler');
/**
* Expose core Logging-related prototypes.
* @type {Container}
*/
exports.Container = require('./winston/container');
/**
* Expose core Logging-related prototypes.
* @type {Object}
*/
exports.Transport = require('winston-transport');
/**
* We create and expose a default `Container` to `winston.loggers` so that the
* programmer may manage multiple `winston.Logger` instances without any
* additional overhead.
* @example
* // some-file1.js
* const logger = require('winston').loggers.get('something');
*
* // some-file2.js
* const logger = require('winston').loggers.get('something');
*/
exports.loggers = new exports.Container();
/**
* We create and expose a 'defaultLogger' so that the programmer may do the
* following without the need to create an instance of winston.Logger directly:
* @example
* const winston = require('winston');
* winston.log('info', 'some message');
* winston.error('some error');
*/
var defaultLogger = exports.createLogger();
// Pass through the target methods onto `winston.
Object.keys(exports.config.npm.levels).concat(['log', 'query', 'stream', 'add', 'remove', 'clear', 'profile', 'startTimer', 'handleExceptions', 'unhandleExceptions', 'handleRejections', 'unhandleRejections', 'configure', 'child']).forEach(function (method) {
return exports[method] = function () {
return defaultLogger[method].apply(defaultLogger, arguments);
};
});
/**
* Define getter / setter for the default logger level which need to be exposed
* by winston.
* @type {string}
*/
Object.defineProperty(exports, 'level', {
get: function get() {
return defaultLogger.level;
},
set: function set(val) {
defaultLogger.level = val;
}
});
/**
* Define getter for `exceptions` which replaces `handleExceptions` and
* `unhandleExceptions`.
* @type {Object}
*/
Object.defineProperty(exports, 'exceptions', {
get: function get() {
return defaultLogger.exceptions;
}
});
/**
* Define getter for `rejections` which replaces `handleRejections` and
* `unhandleRejections`.
* @type {Object}
*/
Object.defineProperty(exports, 'rejections', {
get: function get() {
return defaultLogger.rejections;
}
});
/**
* Define getters / setters for appropriate properties of the default logger
* which need to be exposed by winston.
* @type {Logger}
*/
['exitOnError'].forEach(function (prop) {
Object.defineProperty(exports, prop, {
get: function get() {
return defaultLogger[prop];
},
set: function set(val) {
defaultLogger[prop] = val;
}
});
});
/**
* The default transports and exceptionHandlers for the default winston logger.
* @type {Object}
*/
Object.defineProperty(exports, 'default', {
get: function get() {
return {
exceptionHandlers: defaultLogger.exceptionHandlers,
rejectionHandlers: defaultLogger.rejectionHandlers,
transports: defaultLogger.transports
};
}
});
// Have friendlier breakage notices for properties that were exposed by default
// on winston < 3.0.
warn.deprecated(exports, 'setLevels');
warn.forFunctions(exports, 'useFormat', ['cli']);
warn.forProperties(exports, 'useFormat', ['padLevels', 'stripColors']);
warn.forFunctions(exports, 'deprecated', ['addRewriter', 'addFilter', 'clone', 'extend']);
warn.forProperties(exports, 'deprecated', ['emitErrs', 'levelLength']);

44
node_modules/winston/dist/winston/common.js generated vendored Normal file
View file

@ -0,0 +1,44 @@
/**
* common.js: Internal helper and utility functions for winston.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
var _require = require('util'),
format = _require.format;
/**
* Set of simple deprecation notices and a way to expose them for a set of
* properties.
* @type {Object}
* @private
*/
exports.warn = {
deprecated: function deprecated(prop) {
return function () {
throw new Error(format('{ %s } was removed in winston@3.0.0.', prop));
};
},
useFormat: function useFormat(prop) {
return function () {
throw new Error([format('{ %s } was removed in winston@3.0.0.', prop), 'Use a custom winston.format = winston.format(function) instead.'].join('\n'));
};
},
forFunctions: function forFunctions(obj, type, props) {
props.forEach(function (prop) {
obj[prop] = exports.warn[type](prop);
});
},
forProperties: function forProperties(obj, type, props) {
props.forEach(function (prop) {
var notice = exports.warn[type](prop);
Object.defineProperty(obj, prop, {
get: notice,
set: notice
});
});
}
};

36
node_modules/winston/dist/winston/config/index.js generated vendored Normal file
View file

@ -0,0 +1,36 @@
/**
* index.js: Default settings for all levels that winston knows about.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
var logform = require('logform');
var _require = require('triple-beam'),
configs = _require.configs;
/**
* Export config set for the CLI.
* @type {Object}
*/
exports.cli = logform.levels(configs.cli);
/**
* Export config set for npm.
* @type {Object}
*/
exports.npm = logform.levels(configs.npm);
/**
* Export config set for the syslog.
* @type {Object}
*/
exports.syslog = logform.levels(configs.syslog);
/**
* Hoist addColors from logform where it was refactored into in winston@3.
* @type {Object}
*/
exports.addColors = logform.levels;

141
node_modules/winston/dist/winston/container.js generated vendored Normal file
View file

@ -0,0 +1,141 @@
/**
* container.js: Inversion of control container for winston logger instances.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var createLogger = require('./create-logger');
/**
* Inversion of control container for winston logger instances.
* @type {Container}
*/
module.exports = /*#__PURE__*/function () {
/**
* Constructor function for the Container object responsible for managing a
* set of `winston.Logger` instances based on string ids.
* @param {!Object} [options={}] - Default pass-thru options for Loggers.
*/
function Container() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Container);
this.loggers = new Map();
this.options = options;
}
/**
* Retrieves a `winston.Logger` instance for the specified `id`. If an
* instance does not exist, one is created.
* @param {!string} id - The id of the Logger to get.
* @param {?Object} [options] - Options for the Logger instance.
* @returns {Logger} - A configured Logger instance with a specified id.
*/
return _createClass(Container, [{
key: "add",
value: function add(id, options) {
var _this = this;
if (!this.loggers.has(id)) {
// Remark: Simple shallow clone for configuration options in case we pass
// in instantiated protoypal objects
options = Object.assign({}, options || this.options);
var existing = options.transports || this.options.transports;
// Remark: Make sure if we have an array of transports we slice it to
// make copies of those references.
if (existing) {
options.transports = Array.isArray(existing) ? existing.slice() : [existing];
} else {
options.transports = [];
}
var logger = createLogger(options);
logger.on('close', function () {
return _this._delete(id);
});
this.loggers.set(id, logger);
}
return this.loggers.get(id);
}
/**
* Retreives a `winston.Logger` instance for the specified `id`. If
* an instance does not exist, one is created.
* @param {!string} id - The id of the Logger to get.
* @param {?Object} [options] - Options for the Logger instance.
* @returns {Logger} - A configured Logger instance with a specified id.
*/
}, {
key: "get",
value: function get(id, options) {
return this.add(id, options);
}
/**
* Check if the container has a logger with the id.
* @param {?string} id - The id of the Logger instance to find.
* @returns {boolean} - Boolean value indicating if this instance has a
* logger with the specified `id`.
*/
}, {
key: "has",
value: function has(id) {
return !!this.loggers.has(id);
}
/**
* Closes a `Logger` instance with the specified `id` if it exists.
* If no `id` is supplied then all Loggers are closed.
* @param {?string} id - The id of the Logger instance to close.
* @returns {undefined}
*/
}, {
key: "close",
value: function close(id) {
var _this2 = this;
if (id) {
return this._removeLogger(id);
}
this.loggers.forEach(function (val, key) {
return _this2._removeLogger(key);
});
}
/**
* Remove a logger based on the id.
* @param {!string} id - The id of the logger to remove.
* @returns {undefined}
* @private
*/
}, {
key: "_removeLogger",
value: function _removeLogger(id) {
if (!this.loggers.has(id)) {
return;
}
var logger = this.loggers.get(id);
logger.close();
this._delete(id);
}
/**
* Deletes a `Logger` instance with the specified `id`.
* @param {!string} id - The id of the Logger instance to delete from
* container.
* @returns {undefined}
* @private
*/
}, {
key: "_delete",
value: function _delete(id) {
this.loggers["delete"](id);
}
}]);
}();

123
node_modules/winston/dist/winston/create-logger.js generated vendored Normal file
View file

@ -0,0 +1,123 @@
/**
* create-logger.js: Logger factory for winston logger instances.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var _require = require('triple-beam'),
LEVEL = _require.LEVEL;
var config = require('./config');
var Logger = require('./logger');
var debug = require('@dabh/diagnostics')('winston:create-logger');
function isLevelEnabledFunctionName(level) {
return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled';
}
/**
* Create a new instance of a winston Logger. Creates a new
* prototype for each instance.
* @param {!Object} opts - Options for the created logger.
* @returns {Logger} - A newly created logger instance.
*/
module.exports = function () {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
//
// Default levels: npm
//
opts.levels = opts.levels || config.npm.levels;
/**
* DerivedLogger to attach the logs level methods.
* @type {DerivedLogger}
* @extends {Logger}
*/
var DerivedLogger = /*#__PURE__*/function (_Logger) {
/**
* Create a new class derived logger for which the levels can be attached to
* the prototype of. This is a V8 optimization that is well know to increase
* performance of prototype functions.
* @param {!Object} options - Options for the created logger.
*/
function DerivedLogger(options) {
_classCallCheck(this, DerivedLogger);
return _callSuper(this, DerivedLogger, [options]);
}
_inherits(DerivedLogger, _Logger);
return _createClass(DerivedLogger);
}(Logger);
var logger = new DerivedLogger(opts);
//
// Create the log level methods for the derived logger.
//
Object.keys(opts.levels).forEach(function (level) {
debug('Define prototype method for "%s"', level);
if (level === 'log') {
// eslint-disable-next-line no-console
console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.');
return;
}
//
// Define prototype methods for each log level e.g.:
// logger.log('info', msg) implies these methods are defined:
// - logger.info(msg)
// - logger.isInfoEnabled()
//
// Remark: to support logger.child this **MUST** be a function
// so it'll always be called on the instance instead of a fixed
// place in the prototype chain.
//
DerivedLogger.prototype[level] = function () {
// Prefer any instance scope, but default to "root" logger
var self = this || logger;
// Optimize the hot-path which is the single object.
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.length === 1) {
var msg = args[0];
var info = msg && msg.message && msg || {
message: msg
};
info.level = info[LEVEL] = level;
self._addDefaultMeta(info);
self.write(info);
return this || logger;
}
// When provided nothing assume the empty string
if (args.length === 0) {
self.log(level, '');
return self;
}
// Otherwise build argument list which could potentially conform to
// either:
// . v3 API: log(obj)
// 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback])
return self.log.apply(self, [level].concat(args));
};
DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () {
return (this || logger).isLevelEnabled(level);
};
});
return logger;
};

265
node_modules/winston/dist/winston/exception-handler.js generated vendored Normal file
View file

@ -0,0 +1,265 @@
/**
* exception-handler.js: Object for handling uncaughtException events.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var os = require('os');
var asyncForEach = require('async/forEach');
var debug = require('@dabh/diagnostics')('winston:exception');
var once = require('one-time');
var stackTrace = require('stack-trace');
var ExceptionStream = require('./exception-stream');
/**
* Object for handling uncaughtException events.
* @type {ExceptionHandler}
*/
module.exports = /*#__PURE__*/function () {
/**
* TODO: add contructor description
* @param {!Logger} logger - TODO: add param description
*/
function ExceptionHandler(logger) {
_classCallCheck(this, ExceptionHandler);
if (!logger) {
throw new Error('Logger is required to handle exceptions');
}
this.logger = logger;
this.handlers = new Map();
}
/**
* Handles `uncaughtException` events for the current process by adding any
* handlers passed in.
* @returns {undefined}
*/
return _createClass(ExceptionHandler, [{
key: "handle",
value: function handle() {
var _this = this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
args.forEach(function (arg) {
if (Array.isArray(arg)) {
return arg.forEach(function (handler) {
return _this._addHandler(handler);
});
}
_this._addHandler(arg);
});
if (!this.catcher) {
this.catcher = this._uncaughtException.bind(this);
process.on('uncaughtException', this.catcher);
}
}
/**
* Removes any handlers to `uncaughtException` events for the current
* process. This does not modify the state of the `this.handlers` set.
* @returns {undefined}
*/
}, {
key: "unhandle",
value: function unhandle() {
var _this2 = this;
if (this.catcher) {
process.removeListener('uncaughtException', this.catcher);
this.catcher = false;
Array.from(this.handlers.values()).forEach(function (wrapper) {
return _this2.logger.unpipe(wrapper);
});
}
}
/**
* TODO: add method description
* @param {Error} err - Error to get information about.
* @returns {mixed} - TODO: add return description.
*/
}, {
key: "getAllInfo",
value: function getAllInfo(err) {
var message = null;
if (err) {
message = typeof err === 'string' ? err : err.message;
}
return {
error: err,
// TODO (indexzero): how do we configure this?
level: 'error',
message: ["uncaughtException: ".concat(message || '(no error message)'), err && err.stack || ' No stack trace'].join('\n'),
stack: err && err.stack,
exception: true,
date: new Date().toString(),
process: this.getProcessInfo(),
os: this.getOsInfo(),
trace: this.getTrace(err)
};
}
/**
* Gets all relevant process information for the currently running process.
* @returns {mixed} - TODO: add return description.
*/
}, {
key: "getProcessInfo",
value: function getProcessInfo() {
return {
pid: process.pid,
uid: process.getuid ? process.getuid() : null,
gid: process.getgid ? process.getgid() : null,
cwd: process.cwd(),
execPath: process.execPath,
version: process.version,
argv: process.argv,
memoryUsage: process.memoryUsage()
};
}
/**
* Gets all relevant OS information for the currently running process.
* @returns {mixed} - TODO: add return description.
*/
}, {
key: "getOsInfo",
value: function getOsInfo() {
return {
loadavg: os.loadavg(),
uptime: os.uptime()
};
}
/**
* Gets a stack trace for the specified error.
* @param {mixed} err - TODO: add param description.
* @returns {mixed} - TODO: add return description.
*/
}, {
key: "getTrace",
value: function getTrace(err) {
var trace = err ? stackTrace.parse(err) : stackTrace.get();
return trace.map(function (site) {
return {
column: site.getColumnNumber(),
file: site.getFileName(),
"function": site.getFunctionName(),
line: site.getLineNumber(),
method: site.getMethodName(),
"native": site.isNative()
};
});
}
/**
* Helper method to add a transport as an exception handler.
* @param {Transport} handler - The transport to add as an exception handler.
* @returns {void}
*/
}, {
key: "_addHandler",
value: function _addHandler(handler) {
if (!this.handlers.has(handler)) {
handler.handleExceptions = true;
var wrapper = new ExceptionStream(handler);
this.handlers.set(handler, wrapper);
this.logger.pipe(wrapper);
}
}
/**
* Logs all relevant information around the `err` and exits the current
* process.
* @param {Error} err - Error to handle
* @returns {mixed} - TODO: add return description.
* @private
*/
}, {
key: "_uncaughtException",
value: function _uncaughtException(err) {
var info = this.getAllInfo(err);
var handlers = this._getExceptionHandlers();
// Calculate if we should exit on this error
var doExit = typeof this.logger.exitOnError === 'function' ? this.logger.exitOnError(err) : this.logger.exitOnError;
var timeout;
if (!handlers.length && doExit) {
// eslint-disable-next-line no-console
console.warn('winston: exitOnError cannot be true with no exception handlers.');
// eslint-disable-next-line no-console
console.warn('winston: not exiting process.');
doExit = false;
}
function gracefulExit() {
debug('doExit', doExit);
debug('process._exiting', process._exiting);
if (doExit && !process._exiting) {
// Remark: Currently ignoring any exceptions from transports when
// catching uncaught exceptions.
if (timeout) {
clearTimeout(timeout);
}
// eslint-disable-next-line no-process-exit
process.exit(1);
}
}
if (!handlers || handlers.length === 0) {
return process.nextTick(gracefulExit);
}
// Log to all transports attempting to listen for when they are completed.
asyncForEach(handlers, function (handler, next) {
var done = once(next);
var transport = handler.transport || handler;
// Debug wrapping so that we can inspect what's going on under the covers.
function onDone(event) {
return function () {
debug(event);
done();
};
}
transport._ending = true;
transport.once('finish', onDone('finished'));
transport.once('error', onDone('error'));
}, function () {
return doExit && gracefulExit();
});
this.logger.log(info);
// If exitOnError is true, then only allow the logging of exceptions to
// take up to `3000ms`.
if (doExit) {
timeout = setTimeout(gracefulExit, 3000);
}
}
/**
* Returns the list of transports and exceptionHandlers for this instance.
* @returns {Array} - List of transports and exceptionHandlers for this
* instance.
* @private
*/
}, {
key: "_getExceptionHandlers",
value: function _getExceptionHandlers() {
// Remark (indexzero): since `logger.transports` returns all of the pipes
// from the _readableState of the stream we actually get the join of the
// explicit handlers and the implicit transports with
// `handleExceptions: true`
return this.logger.transports.filter(function (wrap) {
var transport = wrap.transport || wrap;
return transport.handleExceptions;
});
}
}]);
}();

75
node_modules/winston/dist/winston/exception-stream.js generated vendored Normal file
View file

@ -0,0 +1,75 @@
/**
* exception-stream.js: TODO: add file header handler.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var _require = require('readable-stream'),
Writable = _require.Writable;
/**
* TODO: add class description.
* @type {ExceptionStream}
* @extends {Writable}
*/
module.exports = /*#__PURE__*/function (_Writable) {
/**
* Constructor function for the ExceptionStream responsible for wrapping a
* TransportStream; only allowing writes of `info` objects with
* `info.exception` set to true.
* @param {!TransportStream} transport - Stream to filter to exceptions
*/
function ExceptionStream(transport) {
var _this;
_classCallCheck(this, ExceptionStream);
_this = _callSuper(this, ExceptionStream, [{
objectMode: true
}]);
if (!transport) {
throw new Error('ExceptionStream requires a TransportStream instance.');
}
// Remark (indexzero): we set `handleExceptions` here because it's the
// predicate checked in ExceptionHandler.prototype.__getExceptionHandlers
_this.handleExceptions = true;
_this.transport = transport;
return _this;
}
/**
* Writes the info object to our transport instance if (and only if) the
* `exception` property is set on the info.
* @param {mixed} info - TODO: add param description.
* @param {mixed} enc - TODO: add param description.
* @param {mixed} callback - TODO: add param description.
* @returns {mixed} - TODO: add return description.
* @private
*/
_inherits(ExceptionStream, _Writable);
return _createClass(ExceptionStream, [{
key: "_write",
value: function _write(info, enc, callback) {
if (info.exception) {
return this.transport.log(info, callback);
}
callback();
return true;
}
}]);
}(Writable);

672
node_modules/winston/dist/winston/logger.js generated vendored Normal file
View file

@ -0,0 +1,672 @@
/**
* logger.js: TODO: add file header description.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var _require = require('readable-stream'),
Stream = _require.Stream,
Transform = _require.Transform;
var asyncForEach = require('async/forEach');
var _require2 = require('triple-beam'),
LEVEL = _require2.LEVEL,
SPLAT = _require2.SPLAT;
var isStream = require('is-stream');
var ExceptionHandler = require('./exception-handler');
var RejectionHandler = require('./rejection-handler');
var LegacyTransportStream = require('winston-transport/legacy');
var Profiler = require('./profiler');
var _require3 = require('./common'),
warn = _require3.warn;
var config = require('./config');
/**
* Captures the number of format (i.e. %s strings) in a given string.
* Based on `util.format`, see Node.js source:
* https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230
* @type {RegExp}
*/
var formatRegExp = /%[scdjifoO%]/g;
/**
* TODO: add class description.
* @type {Logger}
* @extends {Transform}
*/
var Logger = /*#__PURE__*/function (_Transform) {
/**
* Constructor function for the Logger object responsible for persisting log
* messages and metadata to one or more transports.
* @param {!Object} options - foo
*/
function Logger(options) {
var _this;
_classCallCheck(this, Logger);
_this = _callSuper(this, Logger, [{
objectMode: true
}]);
_this.configure(options);
return _this;
}
_inherits(Logger, _Transform);
return _createClass(Logger, [{
key: "child",
value: function child(defaultRequestMetadata) {
var logger = this;
return Object.create(logger, {
write: {
value: function value(info) {
var infoClone = Object.assign({}, defaultRequestMetadata, info);
// Object.assign doesn't copy inherited Error
// properties so we have to do that explicitly
//
// Remark (indexzero): we should remove this
// since the errors format will handle this case.
//
if (info instanceof Error) {
infoClone.stack = info.stack;
infoClone.message = info.message;
}
logger.write(infoClone);
}
}
});
}
/**
* This will wholesale reconfigure this instance by:
* 1. Resetting all transports. Older transports will be removed implicitly.
* 2. Set all other options including levels, colors, rewriters, filters,
* exceptionHandlers, etc.
* @param {!Object} options - TODO: add param description.
* @returns {undefined}
*/
}, {
key: "configure",
value: function configure() {
var _this2 = this;
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
silent = _ref.silent,
format = _ref.format,
defaultMeta = _ref.defaultMeta,
levels = _ref.levels,
_ref$level = _ref.level,
level = _ref$level === void 0 ? 'info' : _ref$level,
_ref$exitOnError = _ref.exitOnError,
exitOnError = _ref$exitOnError === void 0 ? true : _ref$exitOnError,
transports = _ref.transports,
colors = _ref.colors,
emitErrs = _ref.emitErrs,
formatters = _ref.formatters,
padLevels = _ref.padLevels,
rewriters = _ref.rewriters,
stripColors = _ref.stripColors,
exceptionHandlers = _ref.exceptionHandlers,
rejectionHandlers = _ref.rejectionHandlers;
// Reset transports if we already have them
if (this.transports.length) {
this.clear();
}
this.silent = silent;
this.format = format || this.format || require('logform/json')();
this.defaultMeta = defaultMeta || null;
// Hoist other options onto this instance.
this.levels = levels || this.levels || config.npm.levels;
this.level = level;
if (this.exceptions) {
this.exceptions.unhandle();
}
if (this.rejections) {
this.rejections.unhandle();
}
this.exceptions = new ExceptionHandler(this);
this.rejections = new RejectionHandler(this);
this.profilers = {};
this.exitOnError = exitOnError;
// Add all transports we have been provided.
if (transports) {
transports = Array.isArray(transports) ? transports : [transports];
transports.forEach(function (transport) {
return _this2.add(transport);
});
}
if (colors || emitErrs || formatters || padLevels || rewriters || stripColors) {
throw new Error(['{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.', 'Use a custom winston.format(function) instead.', 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'].join('\n'));
}
if (exceptionHandlers) {
this.exceptions.handle(exceptionHandlers);
}
if (rejectionHandlers) {
this.rejections.handle(rejectionHandlers);
}
}
}, {
key: "isLevelEnabled",
value: function isLevelEnabled(level) {
var _this3 = this;
var givenLevelValue = getLevelValue(this.levels, level);
if (givenLevelValue === null) {
return false;
}
var configuredLevelValue = getLevelValue(this.levels, this.level);
if (configuredLevelValue === null) {
return false;
}
if (!this.transports || this.transports.length === 0) {
return configuredLevelValue >= givenLevelValue;
}
var index = this.transports.findIndex(function (transport) {
var transportLevelValue = getLevelValue(_this3.levels, transport.level);
if (transportLevelValue === null) {
transportLevelValue = configuredLevelValue;
}
return transportLevelValue >= givenLevelValue;
});
return index !== -1;
}
/* eslint-disable valid-jsdoc */
/**
* Ensure backwards compatibility with a `log` method
* @param {mixed} level - Level the log message is written at.
* @param {mixed} msg - TODO: add param description.
* @param {mixed} meta - TODO: add param description.
* @returns {Logger} - TODO: add return description.
*
* @example
* // Supports the existing API:
* logger.log('info', 'Hello world', { custom: true });
* logger.log('info', new Error('Yo, it\'s on fire'));
*
* // Requires winston.format.splat()
* logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true });
*
* // And the new API with a single JSON literal:
* logger.log({ level: 'info', message: 'Hello world', custom: true });
* logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') });
*
* // Also requires winston.format.splat()
* logger.log({
* level: 'info',
* message: '%s %d%%',
* [SPLAT]: ['A string', 50],
* meta: { thisIsMeta: true }
* });
*
*/
/* eslint-enable valid-jsdoc */
}, {
key: "log",
value: function log(level, msg) {
for (var _len = arguments.length, splat = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
splat[_key - 2] = arguments[_key];
}
// eslint-disable-line max-params
// Optimize for the hotpath of logging JSON literals
if (arguments.length === 1) {
// Yo dawg, I heard you like levels ... seriously ...
// In this context the LHS `level` here is actually the `info` so read
// this as: info[LEVEL] = info.level;
level[LEVEL] = level.level;
this._addDefaultMeta(level);
this.write(level);
return this;
}
// Slightly less hotpath, but worth optimizing for.
if (arguments.length === 2) {
if (msg && _typeof(msg) === 'object') {
msg[LEVEL] = msg.level = level;
this._addDefaultMeta(msg);
this.write(msg);
return this;
}
msg = _defineProperty(_defineProperty(_defineProperty({}, LEVEL, level), "level", level), "message", msg);
this._addDefaultMeta(msg);
this.write(msg);
return this;
}
var meta = splat[0];
if (_typeof(meta) === 'object' && meta !== null) {
// Extract tokens, if none available default to empty array to
// ensure consistancy in expected results
var tokens = msg && msg.match && msg.match(formatRegExp);
if (!tokens) {
var info = Object.assign({}, this.defaultMeta, meta, _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, LEVEL, level), SPLAT, splat), "level", level), "message", msg));
if (meta.message) info.message = "".concat(info.message, " ").concat(meta.message);
if (meta.stack) info.stack = meta.stack;
if (meta.cause) info.cause = meta.cause;
this.write(info);
return this;
}
}
this.write(Object.assign({}, this.defaultMeta, _defineProperty(_defineProperty(_defineProperty(_defineProperty({}, LEVEL, level), SPLAT, splat), "level", level), "message", msg)));
return this;
}
/**
* Pushes data so that it can be picked up by all of our pipe targets.
* @param {mixed} info - TODO: add param description.
* @param {mixed} enc - TODO: add param description.
* @param {mixed} callback - Continues stream processing.
* @returns {undefined}
* @private
*/
}, {
key: "_transform",
value: function _transform(info, enc, callback) {
if (this.silent) {
return callback();
}
// [LEVEL] is only soft guaranteed to be set here since we are a proper
// stream. It is likely that `info` came in through `.log(info)` or
// `.info(info)`. If it is not defined, however, define it.
// This LEVEL symbol is provided by `triple-beam` and also used in:
// - logform
// - winston-transport
// - abstract-winston-transport
if (!info[LEVEL]) {
info[LEVEL] = info.level;
}
// Remark: really not sure what to do here, but this has been reported as
// very confusing by pre winston@2.0.0 users as quite confusing when using
// custom levels.
if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) {
// eslint-disable-next-line no-console
console.error('[winston] Unknown logger level: %s', info[LEVEL]);
}
// Remark: not sure if we should simply error here.
if (!this._readableState.pipes) {
// eslint-disable-next-line no-console
console.error('[winston] Attempt to write logs with no transports, which can increase memory usage: %j', info);
}
// Here we write to the `format` pipe-chain, which on `readable` above will
// push the formatted `info` Object onto the buffer for this instance. We trap
// (and re-throw) any errors generated by the user-provided format, but also
// guarantee that the streams callback is invoked so that we can continue flowing.
try {
this.push(this.format.transform(info, this.format.options));
} finally {
this._writableState.sync = false;
// eslint-disable-next-line callback-return
callback();
}
}
/**
* Delays the 'finish' event until all transport pipe targets have
* also emitted 'finish' or are already finished.
* @param {mixed} callback - Continues stream processing.
*/
}, {
key: "_final",
value: function _final(callback) {
var transports = this.transports.slice();
asyncForEach(transports, function (transport, next) {
if (!transport || transport.finished) return setImmediate(next);
transport.once('finish', next);
transport.end();
}, callback);
}
/**
* Adds the transport to this logger instance by piping to it.
* @param {mixed} transport - TODO: add param description.
* @returns {Logger} - TODO: add return description.
*/
}, {
key: "add",
value: function add(transport) {
// Support backwards compatibility with all existing `winston < 3.x.x`
// transports which meet one of two criteria:
// 1. They inherit from winston.Transport in < 3.x.x which is NOT a stream.
// 2. They expose a log method which has a length greater than 2 (i.e. more then
// just `log(info, callback)`.
var target = !isStream(transport) || transport.log.length > 2 ? new LegacyTransportStream({
transport: transport
}) : transport;
if (!target._writableState || !target._writableState.objectMode) {
throw new Error('Transports must WritableStreams in objectMode. Set { objectMode: true }.');
}
// Listen for the `error` event and the `warn` event on the new Transport.
this._onEvent('error', target);
this._onEvent('warn', target);
this.pipe(target);
if (transport.handleExceptions) {
this.exceptions.handle();
}
if (transport.handleRejections) {
this.rejections.handle();
}
return this;
}
/**
* Removes the transport from this logger instance by unpiping from it.
* @param {mixed} transport - TODO: add param description.
* @returns {Logger} - TODO: add return description.
*/
}, {
key: "remove",
value: function remove(transport) {
if (!transport) return this;
var target = transport;
if (!isStream(transport) || transport.log.length > 2) {
target = this.transports.filter(function (match) {
return match.transport === transport;
})[0];
}
if (target) {
this.unpipe(target);
}
return this;
}
/**
* Removes all transports from this logger instance.
* @returns {Logger} - TODO: add return description.
*/
}, {
key: "clear",
value: function clear() {
this.unpipe();
return this;
}
/**
* Cleans up resources (streams, event listeners) for all transports
* associated with this instance (if necessary).
* @returns {Logger} - TODO: add return description.
*/
}, {
key: "close",
value: function close() {
this.exceptions.unhandle();
this.rejections.unhandle();
this.clear();
this.emit('close');
return this;
}
/**
* Sets the `target` levels specified on this instance.
* @param {Object} Target levels to use on this instance.
*/
}, {
key: "setLevels",
value: function setLevels() {
warn.deprecated('setLevels');
}
/**
* Queries the all transports for this instance with the specified `options`.
* This will aggregate each transport's results into one object containing
* a property per transport.
* @param {Object} options - Query options for this instance.
* @param {function} callback - Continuation to respond to when complete.
*/
}, {
key: "query",
value: function query(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
var results = {};
var queryObject = Object.assign({}, options.query || {});
// Helper function to query a single transport
function queryTransport(transport, next) {
if (options.query && typeof transport.formatQuery === 'function') {
options.query = transport.formatQuery(queryObject);
}
transport.query(options, function (err, res) {
if (err) {
return next(err);
}
if (typeof transport.formatResults === 'function') {
res = transport.formatResults(res, options.format);
}
next(null, res);
});
}
// Helper function to accumulate the results from `queryTransport` into
// the `results`.
function addResults(transport, next) {
queryTransport(transport, function (err, result) {
// queryTransport could potentially invoke the callback multiple times
// since Transport code can be unpredictable.
if (next) {
result = err || result;
if (result) {
results[transport.name] = result;
}
// eslint-disable-next-line callback-return
next();
}
next = null;
});
}
// Iterate over the transports in parallel setting the appropriate key in
// the `results`.
asyncForEach(this.transports.filter(function (transport) {
return !!transport.query;
}), addResults, function () {
return callback(null, results);
});
}
/**
* Returns a log stream for all transports. Options object is optional.
* @param{Object} options={} - Stream options for this instance.
* @returns {Stream} - TODO: add return description.
*/
}, {
key: "stream",
value: function stream() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var out = new Stream();
var streams = [];
out._streams = streams;
out.destroy = function () {
var i = streams.length;
while (i--) {
streams[i].destroy();
}
};
// Create a list of all transports for this instance.
this.transports.filter(function (transport) {
return !!transport.stream;
}).forEach(function (transport) {
var str = transport.stream(options);
if (!str) {
return;
}
streams.push(str);
str.on('log', function (log) {
log.transport = log.transport || [];
log.transport.push(transport.name);
out.emit('log', log);
});
str.on('error', function (err) {
err.transport = err.transport || [];
err.transport.push(transport.name);
out.emit('error', err);
});
});
return out;
}
/**
* Returns an object corresponding to a specific timing. When done is called
* the timer will finish and log the duration. e.g.:
* @returns {Profile} - TODO: add return description.
* @example
* const timer = winston.startTimer()
* setTimeout(() => {
* timer.done({
* message: 'Logging message'
* });
* }, 1000);
*/
}, {
key: "startTimer",
value: function startTimer() {
return new Profiler(this);
}
/**
* Tracks the time inbetween subsequent calls to this method with the same
* `id` parameter. The second call to this method will log the difference in
* milliseconds along with the message.
* @param {string} id Unique id of the profiler
* @returns {Logger} - TODO: add return description.
*/
}, {
key: "profile",
value: function profile(id) {
var time = Date.now();
if (this.profilers[id]) {
var timeEnd = this.profilers[id];
delete this.profilers[id];
// Attempt to be kind to users if they are still using older APIs.
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
if (typeof args[args.length - 2] === 'function') {
// eslint-disable-next-line no-console
console.warn('Callback function no longer supported as of winston@3.0.0');
args.pop();
}
// Set the duration property of the metadata
var info = _typeof(args[args.length - 1]) === 'object' ? args.pop() : {};
info.level = info.level || 'info';
info.durationMs = time - timeEnd;
info.message = info.message || id;
return this.write(info);
}
this.profilers[id] = time;
return this;
}
/**
* Backwards compatibility to `exceptions.handle` in winston < 3.0.0.
* @returns {undefined}
* @deprecated
*/
}, {
key: "handleExceptions",
value: function handleExceptions() {
var _this$exceptions;
// eslint-disable-next-line no-console
console.warn('Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()');
(_this$exceptions = this.exceptions).handle.apply(_this$exceptions, arguments);
}
/**
* Backwards compatibility to `exceptions.handle` in winston < 3.0.0.
* @returns {undefined}
* @deprecated
*/
}, {
key: "unhandleExceptions",
value: function unhandleExceptions() {
var _this$exceptions2;
// eslint-disable-next-line no-console
console.warn('Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()');
(_this$exceptions2 = this.exceptions).unhandle.apply(_this$exceptions2, arguments);
}
/**
* Throw a more meaningful deprecation notice
* @throws {Error} - TODO: add throws description.
*/
}, {
key: "cli",
value: function cli() {
throw new Error(['Logger.cli() was removed in winston@3.0.0', 'Use a custom winston.formats.cli() instead.', 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'].join('\n'));
}
/**
* Bubbles the `event` that occured on the specified `transport` up
* from this instance.
* @param {string} event - The event that occured
* @param {Object} transport - Transport on which the event occured
* @private
*/
}, {
key: "_onEvent",
value: function _onEvent(event, transport) {
function transportEvent(err) {
// https://github.com/winstonjs/winston/issues/1364
if (event === 'error' && !this.transports.includes(transport)) {
this.add(transport);
}
this.emit(event, err, transport);
}
if (!transport['__winston' + event]) {
transport['__winston' + event] = transportEvent.bind(this);
transport.on(event, transport['__winston' + event]);
}
}
}, {
key: "_addDefaultMeta",
value: function _addDefaultMeta(msg) {
if (this.defaultMeta) {
Object.assign(msg, this.defaultMeta);
}
}
}]);
}(Transform);
function getLevelValue(levels, level) {
var value = levels[level];
if (!value && value !== 0) {
return null;
}
return value;
}
/**
* Represents the current readableState pipe targets for this Logger instance.
* @type {Array|Object}
*/
Object.defineProperty(Logger.prototype, 'transports', {
configurable: false,
enumerable: true,
get: function get() {
var pipes = this._readableState.pipes;
return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes;
}
});
module.exports = Logger;

65
node_modules/winston/dist/winston/profiler.js generated vendored Normal file
View file

@ -0,0 +1,65 @@
/**
* profiler.js: TODO: add file header description.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
/**
* TODO: add class description.
* @type {Profiler}
* @private
*/
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var Profiler = /*#__PURE__*/function () {
/**
* Constructor function for the Profiler instance used by
* `Logger.prototype.startTimer`. When done is called the timer will finish
* and log the duration.
* @param {!Logger} logger - TODO: add param description.
* @private
*/
function Profiler(logger) {
_classCallCheck(this, Profiler);
var Logger = require('./logger');
if (_typeof(logger) !== 'object' || Array.isArray(logger) || !(logger instanceof Logger)) {
throw new Error('Logger is required for profiling');
} else {
this.logger = logger;
this.start = Date.now();
}
}
/**
* Ends the current timer (i.e. Profiler) instance and logs the `msg` along
* with the duration since creation.
* @returns {mixed} - TODO: add return description.
* @private
*/
return _createClass(Profiler, [{
key: "done",
value: function done() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (typeof args[args.length - 1] === 'function') {
// eslint-disable-next-line no-console
console.warn('Callback function no longer supported as of winston@3.0.0');
args.pop();
}
var info = _typeof(args[args.length - 1]) === 'object' ? args.pop() : {};
info.level = info.level || 'info';
info.durationMs = Date.now() - this.start;
return this.logger.write(info);
}
}]);
}();
;
module.exports = Profiler;

265
node_modules/winston/dist/winston/rejection-handler.js generated vendored Normal file
View file

@ -0,0 +1,265 @@
/**
* exception-handler.js: Object for handling uncaughtException events.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var os = require('os');
var asyncForEach = require('async/forEach');
var debug = require('@dabh/diagnostics')('winston:rejection');
var once = require('one-time');
var stackTrace = require('stack-trace');
var RejectionStream = require('./rejection-stream');
/**
* Object for handling unhandledRejection events.
* @type {RejectionHandler}
*/
module.exports = /*#__PURE__*/function () {
/**
* TODO: add contructor description
* @param {!Logger} logger - TODO: add param description
*/
function RejectionHandler(logger) {
_classCallCheck(this, RejectionHandler);
if (!logger) {
throw new Error('Logger is required to handle rejections');
}
this.logger = logger;
this.handlers = new Map();
}
/**
* Handles `unhandledRejection` events for the current process by adding any
* handlers passed in.
* @returns {undefined}
*/
return _createClass(RejectionHandler, [{
key: "handle",
value: function handle() {
var _this = this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
args.forEach(function (arg) {
if (Array.isArray(arg)) {
return arg.forEach(function (handler) {
return _this._addHandler(handler);
});
}
_this._addHandler(arg);
});
if (!this.catcher) {
this.catcher = this._unhandledRejection.bind(this);
process.on('unhandledRejection', this.catcher);
}
}
/**
* Removes any handlers to `unhandledRejection` events for the current
* process. This does not modify the state of the `this.handlers` set.
* @returns {undefined}
*/
}, {
key: "unhandle",
value: function unhandle() {
var _this2 = this;
if (this.catcher) {
process.removeListener('unhandledRejection', this.catcher);
this.catcher = false;
Array.from(this.handlers.values()).forEach(function (wrapper) {
return _this2.logger.unpipe(wrapper);
});
}
}
/**
* TODO: add method description
* @param {Error} err - Error to get information about.
* @returns {mixed} - TODO: add return description.
*/
}, {
key: "getAllInfo",
value: function getAllInfo(err) {
var message = null;
if (err) {
message = typeof err === 'string' ? err : err.message;
}
return {
error: err,
// TODO (indexzero): how do we configure this?
level: 'error',
message: ["unhandledRejection: ".concat(message || '(no error message)'), err && err.stack || ' No stack trace'].join('\n'),
stack: err && err.stack,
rejection: true,
date: new Date().toString(),
process: this.getProcessInfo(),
os: this.getOsInfo(),
trace: this.getTrace(err)
};
}
/**
* Gets all relevant process information for the currently running process.
* @returns {mixed} - TODO: add return description.
*/
}, {
key: "getProcessInfo",
value: function getProcessInfo() {
return {
pid: process.pid,
uid: process.getuid ? process.getuid() : null,
gid: process.getgid ? process.getgid() : null,
cwd: process.cwd(),
execPath: process.execPath,
version: process.version,
argv: process.argv,
memoryUsage: process.memoryUsage()
};
}
/**
* Gets all relevant OS information for the currently running process.
* @returns {mixed} - TODO: add return description.
*/
}, {
key: "getOsInfo",
value: function getOsInfo() {
return {
loadavg: os.loadavg(),
uptime: os.uptime()
};
}
/**
* Gets a stack trace for the specified error.
* @param {mixed} err - TODO: add param description.
* @returns {mixed} - TODO: add return description.
*/
}, {
key: "getTrace",
value: function getTrace(err) {
var trace = err ? stackTrace.parse(err) : stackTrace.get();
return trace.map(function (site) {
return {
column: site.getColumnNumber(),
file: site.getFileName(),
"function": site.getFunctionName(),
line: site.getLineNumber(),
method: site.getMethodName(),
"native": site.isNative()
};
});
}
/**
* Helper method to add a transport as an exception handler.
* @param {Transport} handler - The transport to add as an exception handler.
* @returns {void}
*/
}, {
key: "_addHandler",
value: function _addHandler(handler) {
if (!this.handlers.has(handler)) {
handler.handleRejections = true;
var wrapper = new RejectionStream(handler);
this.handlers.set(handler, wrapper);
this.logger.pipe(wrapper);
}
}
/**
* Logs all relevant information around the `err` and exits the current
* process.
* @param {Error} err - Error to handle
* @returns {mixed} - TODO: add return description.
* @private
*/
}, {
key: "_unhandledRejection",
value: function _unhandledRejection(err) {
var info = this.getAllInfo(err);
var handlers = this._getRejectionHandlers();
// Calculate if we should exit on this error
var doExit = typeof this.logger.exitOnError === 'function' ? this.logger.exitOnError(err) : this.logger.exitOnError;
var timeout;
if (!handlers.length && doExit) {
// eslint-disable-next-line no-console
console.warn('winston: exitOnError cannot be true with no rejection handlers.');
// eslint-disable-next-line no-console
console.warn('winston: not exiting process.');
doExit = false;
}
function gracefulExit() {
debug('doExit', doExit);
debug('process._exiting', process._exiting);
if (doExit && !process._exiting) {
// Remark: Currently ignoring any rejections from transports when
// catching unhandled rejections.
if (timeout) {
clearTimeout(timeout);
}
// eslint-disable-next-line no-process-exit
process.exit(1);
}
}
if (!handlers || handlers.length === 0) {
return process.nextTick(gracefulExit);
}
// Log to all transports attempting to listen for when they are completed.
asyncForEach(handlers, function (handler, next) {
var done = once(next);
var transport = handler.transport || handler;
// Debug wrapping so that we can inspect what's going on under the covers.
function onDone(event) {
return function () {
debug(event);
done();
};
}
transport._ending = true;
transport.once('finish', onDone('finished'));
transport.once('error', onDone('error'));
}, function () {
return doExit && gracefulExit();
});
this.logger.log(info);
// If exitOnError is true, then only allow the logging of exceptions to
// take up to `3000ms`.
if (doExit) {
timeout = setTimeout(gracefulExit, 3000);
}
}
/**
* Returns the list of transports and exceptionHandlers for this instance.
* @returns {Array} - List of transports and exceptionHandlers for this
* instance.
* @private
*/
}, {
key: "_getRejectionHandlers",
value: function _getRejectionHandlers() {
// Remark (indexzero): since `logger.transports` returns all of the pipes
// from the _readableState of the stream we actually get the join of the
// explicit handlers and the implicit transports with
// `handleRejections: true`
return this.logger.transports.filter(function (wrap) {
var transport = wrap.transport || wrap;
return transport.handleRejections;
});
}
}]);
}();

72
node_modules/winston/dist/winston/rejection-stream.js generated vendored Normal file
View file

@ -0,0 +1,72 @@
/**
* rejection-stream.js: TODO: add file header handler.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var _require = require('readable-stream'),
Writable = _require.Writable;
/**
* TODO: add class description.
* @type {RejectionStream}
* @extends {Writable}
*/
module.exports = /*#__PURE__*/function (_Writable) {
/**
* Constructor function for the RejectionStream responsible for wrapping a
* TransportStream; only allowing writes of `info` objects with
* `info.rejection` set to true.
* @param {!TransportStream} transport - Stream to filter to rejections
*/
function RejectionStream(transport) {
var _this;
_classCallCheck(this, RejectionStream);
_this = _callSuper(this, RejectionStream, [{
objectMode: true
}]);
if (!transport) {
throw new Error('RejectionStream requires a TransportStream instance.');
}
_this.handleRejections = true;
_this.transport = transport;
return _this;
}
/**
* Writes the info object to our transport instance if (and only if) the
* `rejection` property is set on the info.
* @param {mixed} info - TODO: add param description.
* @param {mixed} enc - TODO: add param description.
* @param {mixed} callback - TODO: add param description.
* @returns {mixed} - TODO: add return description.
* @private
*/
_inherits(RejectionStream, _Writable);
return _createClass(RejectionStream, [{
key: "_write",
value: function _write(info, enc, callback) {
if (info.rejection) {
return this.transport.log(info, callback);
}
callback();
return true;
}
}]);
}(Writable);

113
node_modules/winston/dist/winston/tail-file.js generated vendored Normal file
View file

@ -0,0 +1,113 @@
/**
* tail-file.js: TODO: add file header description.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
var fs = require('fs');
var _require = require('string_decoder'),
StringDecoder = _require.StringDecoder;
var _require2 = require('readable-stream'),
Stream = _require2.Stream;
/**
* Simple no-op function.
* @returns {undefined}
*/
function noop() {}
/**
* TODO: add function description.
* @param {Object} options - Options for tail.
* @param {function} iter - Iterator function to execute on every line.
* `tail -f` a file. Options must include file.
* @returns {mixed} - TODO: add return description.
*/
module.exports = function (options, iter) {
var buffer = Buffer.alloc(64 * 1024);
var decode = new StringDecoder('utf8');
var stream = new Stream();
var buff = '';
var pos = 0;
var row = 0;
if (options.start === -1) {
delete options.start;
}
stream.readable = true;
stream.destroy = function () {
stream.destroyed = true;
stream.emit('end');
stream.emit('close');
};
fs.open(options.file, 'a+', '0644', function (err, fd) {
if (err) {
if (!iter) {
stream.emit('error', err);
} else {
iter(err);
}
stream.destroy();
return;
}
(function read() {
if (stream.destroyed) {
fs.close(fd, noop);
return;
}
return fs.read(fd, buffer, 0, buffer.length, pos, function (error, bytes) {
if (error) {
if (!iter) {
stream.emit('error', error);
} else {
iter(error);
}
stream.destroy();
return;
}
if (!bytes) {
if (buff) {
// eslint-disable-next-line eqeqeq
if (options.start == null || row > options.start) {
if (!iter) {
stream.emit('line', buff);
} else {
iter(null, buff);
}
}
row++;
buff = '';
}
return setTimeout(read, 1000);
}
var data = decode.write(buffer.slice(0, bytes));
if (!iter) {
stream.emit('data', data);
}
data = (buff + data).split(/\n+/);
var l = data.length - 1;
var i = 0;
for (; i < l; i++) {
// eslint-disable-next-line eqeqeq
if (options.start == null || row > options.start) {
if (!iter) {
stream.emit('line', data[i]);
} else {
iter(null, data[i]);
}
}
row++;
}
buff = data[l];
pos += bytes;
return read();
});
})();
});
if (!iter) {
return stream;
}
return stream.destroy;
};

143
node_modules/winston/dist/winston/transports/console.js generated vendored Normal file
View file

@ -0,0 +1,143 @@
/* eslint-disable no-console */
/*
* console.js: Transport for outputting to the console.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var os = require('os');
var _require = require('triple-beam'),
LEVEL = _require.LEVEL,
MESSAGE = _require.MESSAGE;
var TransportStream = require('winston-transport');
/**
* Transport for outputting to the console.
* @type {Console}
* @extends {TransportStream}
*/
module.exports = /*#__PURE__*/function (_TransportStream) {
/**
* Constructor function for the Console transport object responsible for
* persisting log messages and metadata to a terminal or TTY.
* @param {!Object} [options={}] - Options for this instance.
*/
function Console() {
var _this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Console);
_this = _callSuper(this, Console, [options]);
// Expose the name of this Transport on the prototype
_this.name = options.name || 'console';
_this.stderrLevels = _this._stringArrayToSet(options.stderrLevels);
_this.consoleWarnLevels = _this._stringArrayToSet(options.consoleWarnLevels);
_this.eol = typeof options.eol === 'string' ? options.eol : os.EOL;
_this.forceConsole = options.forceConsole || false;
// Keep a reference to the log, warn, and error console methods
// in case they get redirected to this transport after the logger is
// instantiated. This prevents a circular reference issue.
_this._consoleLog = console.log.bind(console);
_this._consoleWarn = console.warn.bind(console);
_this._consoleError = console.error.bind(console);
_this.setMaxListeners(30);
return _this;
}
/**
* Core logging method exposed to Winston.
* @param {Object} info - TODO: add param description.
* @param {Function} callback - TODO: add param description.
* @returns {undefined}
*/
_inherits(Console, _TransportStream);
return _createClass(Console, [{
key: "log",
value: function log(info, callback) {
var _this2 = this;
setImmediate(function () {
return _this2.emit('logged', info);
});
// Remark: what if there is no raw...?
if (this.stderrLevels[info[LEVEL]]) {
if (console._stderr && !this.forceConsole) {
// Node.js maps `process.stderr` to `console._stderr`.
console._stderr.write("".concat(info[MESSAGE]).concat(this.eol));
} else {
// console.error adds a newline
this._consoleError(info[MESSAGE]);
}
if (callback) {
callback(); // eslint-disable-line callback-return
}
return;
} else if (this.consoleWarnLevels[info[LEVEL]]) {
if (console._stderr && !this.forceConsole) {
// Node.js maps `process.stderr` to `console._stderr`.
// in Node.js console.warn is an alias for console.error
console._stderr.write("".concat(info[MESSAGE]).concat(this.eol));
} else {
// console.warn adds a newline
this._consoleWarn(info[MESSAGE]);
}
if (callback) {
callback(); // eslint-disable-line callback-return
}
return;
}
if (console._stdout && !this.forceConsole) {
// Node.js maps `process.stdout` to `console._stdout`.
console._stdout.write("".concat(info[MESSAGE]).concat(this.eol));
} else {
// console.log adds a newline.
this._consoleLog(info[MESSAGE]);
}
if (callback) {
callback(); // eslint-disable-line callback-return
}
}
/**
* Returns a Set-like object with strArray's elements as keys (each with the
* value true).
* @param {Array} strArray - Array of Set-elements as strings.
* @param {?string} [errMsg] - Custom error message thrown on invalid input.
* @returns {Object} - TODO: add return description.
* @private
*/
}, {
key: "_stringArrayToSet",
value: function _stringArrayToSet(strArray, errMsg) {
if (!strArray) return {};
errMsg = errMsg || 'Cannot make set from type other than Array of string elements';
if (!Array.isArray(strArray)) {
throw new Error(errMsg);
}
return strArray.reduce(function (set, el) {
if (typeof el !== 'string') {
throw new Error(errMsg);
}
set[el] = true;
return set;
}, {});
}
}]);
}(TransportStream);

788
node_modules/winston/dist/winston/transports/file.js generated vendored Normal file
View file

@ -0,0 +1,788 @@
/* eslint-disable complexity,max-statements */
/**
* file.js: Transport for outputting to a local log file.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _readOnlyError(r) { throw new TypeError('"' + r + '" is read-only'); }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var fs = require('fs');
var path = require('path');
var asyncSeries = require('async/series');
var zlib = require('zlib');
var _require = require('triple-beam'),
MESSAGE = _require.MESSAGE;
var _require2 = require('readable-stream'),
Stream = _require2.Stream,
PassThrough = _require2.PassThrough;
var TransportStream = require('winston-transport');
var debug = require('@dabh/diagnostics')('winston:file');
var os = require('os');
var tailFile = require('../tail-file');
/**
* Transport for outputting to a local log file.
* @type {File}
* @extends {TransportStream}
*/
module.exports = /*#__PURE__*/function (_TransportStream) {
/**
* Constructor function for the File transport object responsible for
* persisting log messages and metadata to one or more files.
* @param {Object} options - Options for this instance.
*/
function File() {
var _this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, File);
_this = _callSuper(this, File, [options]);
// Expose the name of this Transport on the prototype.
_this.name = options.name || 'file';
// Helper function which throws an `Error` in the event that any of the
// rest of the arguments is present in `options`.
function throwIf(target) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
args.slice(1).forEach(function (name) {
if (options[name]) {
throw new Error("Cannot set ".concat(name, " and ").concat(target, " together"));
}
});
}
// Setup the base stream that always gets piped to to handle buffering.
_this._stream = new PassThrough();
_this._stream.setMaxListeners(30);
// Bind this context for listener methods.
_this._onError = _this._onError.bind(_this);
if (options.filename || options.dirname) {
throwIf('filename or dirname', 'stream');
_this._basename = _this.filename = options.filename ? path.basename(options.filename) : 'winston.log';
_this.dirname = options.dirname || path.dirname(options.filename);
_this.options = options.options || {
flags: 'a'
};
} else if (options.stream) {
// eslint-disable-next-line no-console
console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream');
throwIf('stream', 'filename', 'maxsize');
_this._dest = _this._stream.pipe(_this._setupStream(options.stream));
_this.dirname = path.dirname(_this._dest.path);
// We need to listen for drain events when write() returns false. This
// can make node mad at times.
} else {
throw new Error('Cannot log to file without filename or stream.');
}
_this.maxsize = options.maxsize || null;
_this.rotationFormat = options.rotationFormat || false;
_this.zippedArchive = options.zippedArchive || false;
_this.maxFiles = options.maxFiles || null;
_this.eol = typeof options.eol === 'string' ? options.eol : os.EOL;
_this.tailable = options.tailable || false;
_this.lazy = options.lazy || false;
// Internal state variables representing the number of files this instance
// has created and the current size (in bytes) of the current logfile.
_this._size = 0;
_this._pendingSize = 0;
_this._created = 0;
_this._drain = false;
_this._opening = false;
_this._ending = false;
_this._fileExist = false;
if (_this.dirname) _this._createLogDirIfNotExist(_this.dirname);
if (!_this.lazy) _this.open();
return _this;
}
_inherits(File, _TransportStream);
return _createClass(File, [{
key: "finishIfEnding",
value: function finishIfEnding() {
var _this2 = this;
if (this._ending) {
if (this._opening) {
this.once('open', function () {
_this2._stream.once('finish', function () {
return _this2.emit('finish');
});
setImmediate(function () {
return _this2._stream.end();
});
});
} else {
this._stream.once('finish', function () {
return _this2.emit('finish');
});
setImmediate(function () {
return _this2._stream.end();
});
}
}
}
/**
* Core logging method exposed to Winston. Metadata is optional.
* @param {Object} info - TODO: add param description.
* @param {Function} callback - TODO: add param description.
* @returns {undefined}
*/
}, {
key: "log",
value: function log(info) {
var _this3 = this;
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
// Remark: (jcrugzz) What is necessary about this callback(null, true) now
// when thinking about 3.x? Should silent be handled in the base
// TransportStream _write method?
if (this.silent) {
callback();
return true;
}
// Output stream buffer is full and has asked us to wait for the drain event
if (this._drain) {
this._stream.once('drain', function () {
_this3._drain = false;
_this3.log(info, callback);
});
return;
}
if (this._rotate) {
this._stream.once('rotate', function () {
_this3._rotate = false;
_this3.log(info, callback);
});
return;
}
if (this.lazy) {
if (!this._fileExist) {
if (!this._opening) {
this.open();
}
this.once('open', function () {
_this3._fileExist = true;
_this3.log(info, callback);
return;
});
return;
}
if (this._needsNewFile(this._pendingSize)) {
this._dest.once('close', function () {
if (!_this3._opening) {
_this3.open();
}
_this3.once('open', function () {
_this3.log(info, callback);
return;
});
return;
});
return;
}
}
// Grab the raw string and append the expected EOL.
var output = "".concat(info[MESSAGE]).concat(this.eol);
var bytes = Buffer.byteLength(output);
// After we have written to the PassThrough check to see if we need
// to rotate to the next file.
//
// Remark: This gets called too early and does not depict when data
// has been actually flushed to disk.
function logged() {
var _this4 = this;
this._size += bytes;
this._pendingSize -= bytes;
debug('logged %s %s', this._size, output);
this.emit('logged', info);
// Do not attempt to rotate files while rotating
if (this._rotate) {
return;
}
// Do not attempt to rotate files while opening
if (this._opening) {
return;
}
// Check to see if we need to end the stream and create a new one.
if (!this._needsNewFile()) {
return;
}
if (this.lazy) {
this._endStream(function () {
_this4.emit('fileclosed');
});
return;
}
// End the current stream, ensure it flushes and create a new one.
// This could potentially be optimized to not run a stat call but its
// the safest way since we are supporting `maxFiles`.
this._rotate = true;
this._endStream(function () {
return _this4._rotateFile();
});
}
// Keep track of the pending bytes being written while files are opening
// in order to properly rotate the PassThrough this._stream when the file
// eventually does open.
this._pendingSize += bytes;
if (this._opening && !this.rotatedWhileOpening && this._needsNewFile(this._size + this._pendingSize)) {
this.rotatedWhileOpening = true;
}
var written = this._stream.write(output, logged.bind(this));
if (!written) {
this._drain = true;
this._stream.once('drain', function () {
_this3._drain = false;
callback();
});
} else {
callback(); // eslint-disable-line callback-return
}
debug('written', written, this._drain);
this.finishIfEnding();
return written;
}
/**
* Query the transport. Options object is optional.
* @param {Object} options - Loggly-like query options for this instance.
* @param {function} callback - Continuation to respond to when complete.
* TODO: Refactor me.
*/
}, {
key: "query",
value: function query(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = normalizeQuery(options);
var file = path.join(this.dirname, this.filename);
var buff = '';
var results = [];
var row = 0;
var stream = fs.createReadStream(file, {
encoding: 'utf8'
});
stream.on('error', function (err) {
if (stream.readable) {
stream.destroy();
}
if (!callback) {
return;
}
return err.code !== 'ENOENT' ? callback(err) : callback(null, results);
});
stream.on('data', function (data) {
data = (buff + data).split(/\n+/);
var l = data.length - 1;
var i = 0;
for (; i < l; i++) {
if (!options.start || row >= options.start) {
add(data[i]);
}
row++;
}
buff = data[l];
});
stream.on('close', function () {
if (buff) {
add(buff, true);
}
if (options.order === 'desc') {
results = results.reverse();
}
// eslint-disable-next-line callback-return
if (callback) callback(null, results);
});
function add(buff, attempt) {
try {
var log = JSON.parse(buff);
if (check(log)) {
push(log);
}
} catch (e) {
if (!attempt) {
stream.emit('error', e);
}
}
}
function push(log) {
if (options.rows && results.length >= options.rows && options.order !== 'desc') {
if (stream.readable) {
stream.destroy();
}
return;
}
if (options.fields) {
log = options.fields.reduce(function (obj, key) {
obj[key] = log[key];
return obj;
}, {});
}
if (options.order === 'desc') {
if (results.length >= options.rows) {
results.shift();
}
}
results.push(log);
}
function check(log) {
if (!log) {
return;
}
if (_typeof(log) !== 'object') {
return;
}
var time = new Date(log.timestamp);
if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) {
return;
}
return true;
}
function normalizeQuery(options) {
options = options || {};
// limit
options.rows = options.rows || options.limit || 10;
// starting row offset
options.start = options.start || 0;
// now
options.until = options.until || new Date();
if (_typeof(options.until) !== 'object') {
options.until = new Date(options.until);
}
// now - 24
options.from = options.from || options.until - 24 * 60 * 60 * 1000;
if (_typeof(options.from) !== 'object') {
options.from = new Date(options.from);
}
// 'asc' or 'desc'
options.order = options.order || 'desc';
return options;
}
}
/**
* Returns a log stream for this transport. Options object is optional.
* @param {Object} options - Stream options for this instance.
* @returns {Stream} - TODO: add return description.
* TODO: Refactor me.
*/
}, {
key: "stream",
value: function stream() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var file = path.join(this.dirname, this.filename);
var stream = new Stream();
var tail = {
file: file,
start: options.start
};
stream.destroy = tailFile(tail, function (err, line) {
if (err) {
return stream.emit('error', err);
}
try {
stream.emit('data', line);
line = JSON.parse(line);
stream.emit('log', line);
} catch (e) {
stream.emit('error', e);
}
});
return stream;
}
/**
* Checks to see the filesize of.
* @returns {undefined}
*/
}, {
key: "open",
value: function open() {
var _this5 = this;
// If we do not have a filename then we were passed a stream and
// don't need to keep track of size.
if (!this.filename) return;
if (this._opening) return;
this._opening = true;
// Stat the target file to get the size and create the stream.
this.stat(function (err, size) {
if (err) {
return _this5.emit('error', err);
}
debug('stat done: %s { size: %s }', _this5.filename, size);
_this5._size = size;
_this5._dest = _this5._createStream(_this5._stream);
_this5._opening = false;
_this5.once('open', function () {
if (!_this5._stream.emit('rotate')) {
_this5._rotate = false;
}
});
});
}
/**
* Stat the file and assess information in order to create the proper stream.
* @param {function} callback - TODO: add param description.
* @returns {undefined}
*/
}, {
key: "stat",
value: function stat(callback) {
var _this6 = this;
var target = this._getFile();
var fullpath = path.join(this.dirname, target);
fs.stat(fullpath, function (err, stat) {
if (err && err.code === 'ENOENT') {
debug('ENOENT ok', fullpath);
// Update internally tracked filename with the new target name.
_this6.filename = target;
return callback(null, 0);
}
if (err) {
debug("err ".concat(err.code, " ").concat(fullpath));
return callback(err);
}
if (!stat || _this6._needsNewFile(stat.size)) {
// If `stats.size` is greater than the `maxsize` for this
// instance then try again.
return _this6._incFile(function () {
return _this6.stat(callback);
});
}
// Once we have figured out what the filename is, set it
// and return the size.
_this6.filename = target;
callback(null, stat.size);
});
}
/**
* Closes the stream associated with this instance.
* @param {function} cb - TODO: add param description.
* @returns {undefined}
*/
}, {
key: "close",
value: function close(cb) {
var _this7 = this;
if (!this._stream) {
return;
}
this._stream.end(function () {
if (cb) {
cb(); // eslint-disable-line callback-return
}
_this7.emit('flush');
_this7.emit('closed');
});
}
/**
* TODO: add method description.
* @param {number} size - TODO: add param description.
* @returns {undefined}
*/
}, {
key: "_needsNewFile",
value: function _needsNewFile(size) {
size = size || this._size;
return this.maxsize && size >= this.maxsize;
}
/**
* TODO: add method description.
* @param {Error} err - TODO: add param description.
* @returns {undefined}
*/
}, {
key: "_onError",
value: function _onError(err) {
this.emit('error', err);
}
/**
* TODO: add method description.
* @param {Stream} stream - TODO: add param description.
* @returns {mixed} - TODO: add return description.
*/
}, {
key: "_setupStream",
value: function _setupStream(stream) {
stream.on('error', this._onError);
return stream;
}
/**
* TODO: add method description.
* @param {Stream} stream - TODO: add param description.
* @returns {mixed} - TODO: add return description.
*/
}, {
key: "_cleanupStream",
value: function _cleanupStream(stream) {
stream.removeListener('error', this._onError);
stream.destroy();
return stream;
}
/**
* TODO: add method description.
*/
}, {
key: "_rotateFile",
value: function _rotateFile() {
var _this8 = this;
this._incFile(function () {
return _this8.open();
});
}
/**
* Unpipe from the stream that has been marked as full and end it so it
* flushes to disk.
*
* @param {function} callback - Callback for when the current file has closed.
* @private
*/
}, {
key: "_endStream",
value: function _endStream() {
var _this9 = this;
var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
if (this._dest) {
this._stream.unpipe(this._dest);
this._dest.end(function () {
_this9._cleanupStream(_this9._dest);
callback();
});
} else {
callback(); // eslint-disable-line callback-return
}
}
/**
* Returns the WritableStream for the active file on this instance. If we
* should gzip the file then a zlib stream is returned.
*
* @param {ReadableStream} source PassThrough to pipe to the file when open.
* @returns {WritableStream} Stream that writes to disk for the active file.
*/
}, {
key: "_createStream",
value: function _createStream(source) {
var _this10 = this;
var fullpath = path.join(this.dirname, this.filename);
debug('create stream start', fullpath, this.options);
var dest = fs.createWriteStream(fullpath, this.options)
// TODO: What should we do with errors here?
.on('error', function (err) {
return debug(err);
}).on('close', function () {
return debug('close', dest.path, dest.bytesWritten);
}).on('open', function () {
debug('file open ok', fullpath);
_this10.emit('open', fullpath);
source.pipe(dest);
// If rotation occured during the open operation then we immediately
// start writing to a new PassThrough, begin opening the next file
// and cleanup the previous source and dest once the source has drained.
if (_this10.rotatedWhileOpening) {
_this10._stream = new PassThrough();
_this10._stream.setMaxListeners(30);
_this10._rotateFile();
_this10.rotatedWhileOpening = false;
_this10._cleanupStream(dest);
source.end();
}
});
debug('create stream ok', fullpath);
return dest;
}
/**
* TODO: add method description.
* @param {function} callback - TODO: add param description.
* @returns {undefined}
*/
}, {
key: "_incFile",
value: function _incFile(callback) {
debug('_incFile', this.filename);
var ext = path.extname(this._basename);
var basename = path.basename(this._basename, ext);
var tasks = [];
if (this.zippedArchive) {
tasks.push(function (cb) {
var num = this._created > 0 && !this.tailable ? this._created : '';
this._compressFile(path.join(this.dirname, "".concat(basename).concat(num).concat(ext)), path.join(this.dirname, "".concat(basename).concat(num).concat(ext, ".gz")), cb);
}.bind(this));
}
tasks.push(function (cb) {
if (!this.tailable) {
this._created += 1;
this._checkMaxFilesIncrementing(ext, basename, cb);
} else {
this._checkMaxFilesTailable(ext, basename, cb);
}
}.bind(this));
asyncSeries(tasks, callback);
}
/**
* Gets the next filename to use for this instance in the case that log
* filesizes are being capped.
* @returns {string} - TODO: add return description.
* @private
*/
}, {
key: "_getFile",
value: function _getFile() {
var ext = path.extname(this._basename);
var basename = path.basename(this._basename, ext);
var isRotation = this.rotationFormat ? this.rotationFormat() : this._created;
// Caveat emptor (indexzero): rotationFormat() was broken by design When
// combined with max files because the set of files to unlink is never
// stored.
return !this.tailable && this._created ? "".concat(basename).concat(isRotation).concat(ext) : "".concat(basename).concat(ext);
}
/**
* Increment the number of files created or checked by this instance.
* @param {mixed} ext - TODO: add param description.
* @param {mixed} basename - TODO: add param description.
* @param {mixed} callback - TODO: add param description.
* @returns {undefined}
* @private
*/
}, {
key: "_checkMaxFilesIncrementing",
value: function _checkMaxFilesIncrementing(ext, basename, callback) {
// Check for maxFiles option and delete file.
if (!this.maxFiles || this._created < this.maxFiles) {
return setImmediate(callback);
}
var oldest = this._created - this.maxFiles;
var isOldest = oldest !== 0 ? oldest : '';
var isZipped = this.zippedArchive ? '.gz' : '';
var filePath = "".concat(basename).concat(isOldest).concat(ext).concat(isZipped);
var target = path.join(this.dirname, filePath);
fs.unlink(target, callback);
}
/**
* Roll files forward based on integer, up to maxFiles. e.g. if base if
* file.log and it becomes oversized, roll to file1.log, and allow file.log
* to be re-used. If file is oversized again, roll file1.log to file2.log,
* roll file.log to file1.log, and so on.
* @param {mixed} ext - TODO: add param description.
* @param {mixed} basename - TODO: add param description.
* @param {mixed} callback - TODO: add param description.
* @returns {undefined}
* @private
*/
}, {
key: "_checkMaxFilesTailable",
value: function _checkMaxFilesTailable(ext, basename, callback) {
var _this12 = this;
var tasks = [];
if (!this.maxFiles) {
return;
}
// const isZipped = this.zippedArchive ? '.gz' : '';
var isZipped = this.zippedArchive ? '.gz' : '';
for (var x = this.maxFiles - 1; x > 1; x--) {
tasks.push(function (i, cb) {
var _this11 = this;
var fileName = "".concat(basename).concat(i - 1).concat(ext).concat(isZipped);
var tmppath = path.join(this.dirname, fileName);
fs.exists(tmppath, function (exists) {
if (!exists) {
return cb(null);
}
fileName = "".concat(basename).concat(i).concat(ext).concat(isZipped);
fs.rename(tmppath, path.join(_this11.dirname, fileName), cb);
});
}.bind(this, x));
}
asyncSeries(tasks, function () {
fs.rename(path.join(_this12.dirname, "".concat(basename).concat(ext).concat(isZipped)), path.join(_this12.dirname, "".concat(basename, "1").concat(ext).concat(isZipped)), callback);
});
}
/**
* Compresses src to dest with gzip and unlinks src
* @param {string} src - path to source file.
* @param {string} dest - path to zipped destination file.
* @param {Function} callback - callback called after file has been compressed.
* @returns {undefined}
* @private
*/
}, {
key: "_compressFile",
value: function _compressFile(src, dest, callback) {
fs.access(src, fs.F_OK, function (err) {
if (err) {
return callback();
}
var gzip = zlib.createGzip();
var inp = fs.createReadStream(src);
var out = fs.createWriteStream(dest);
out.on('finish', function () {
fs.unlink(src, callback);
});
inp.pipe(gzip).pipe(out);
});
}
}, {
key: "_createLogDirIfNotExist",
value: function _createLogDirIfNotExist(dirPath) {
/* eslint-disable no-sync */
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, {
recursive: true
});
}
/* eslint-enable no-sync */
}
}]);
}(TransportStream);

288
node_modules/winston/dist/winston/transports/http.js generated vendored Normal file
View file

@ -0,0 +1,288 @@
/**
* http.js: Transport for outputting to a json-rpcserver.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _readOnlyError(r) { throw new TypeError('"' + r + '" is read-only'); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var http = require('http');
var https = require('https');
var _require = require('readable-stream'),
Stream = _require.Stream;
var TransportStream = require('winston-transport');
var _require2 = require('safe-stable-stringify'),
configure = _require2.configure;
/**
* Transport for outputting to a json-rpc server.
* @type {Stream}
* @extends {TransportStream}
*/
module.exports = /*#__PURE__*/function (_TransportStream) {
/**
* Constructor function for the Http transport object responsible for
* persisting log messages and metadata to a terminal or TTY.
* @param {!Object} [options={}] - Options for this instance.
*/
// eslint-disable-next-line max-statements
function Http() {
var _this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Http);
_this = _callSuper(this, Http, [options]);
_this.options = options;
_this.name = options.name || 'http';
_this.ssl = !!options.ssl;
_this.host = options.host || 'localhost';
_this.port = options.port;
_this.auth = options.auth;
_this.path = options.path || '';
_this.maximumDepth = options.maximumDepth;
_this.agent = options.agent;
_this.headers = options.headers || {};
_this.headers['content-type'] = 'application/json';
_this.batch = options.batch || false;
_this.batchInterval = options.batchInterval || 5000;
_this.batchCount = options.batchCount || 10;
_this.batchOptions = [];
_this.batchTimeoutID = -1;
_this.batchCallback = {};
if (!_this.port) {
_this.port = _this.ssl ? 443 : 80;
}
return _this;
}
/**
* Core logging method exposed to Winston.
* @param {Object} info - TODO: add param description.
* @param {function} callback - TODO: add param description.
* @returns {undefined}
*/
_inherits(Http, _TransportStream);
return _createClass(Http, [{
key: "log",
value: function log(info, callback) {
var _this2 = this;
this._request(info, null, null, function (err, res) {
if (res && res.statusCode !== 200) {
err = new Error("Invalid HTTP Status Code: ".concat(res.statusCode));
}
if (err) {
_this2.emit('warn', err);
} else {
_this2.emit('logged', info);
}
});
// Remark: (jcrugzz) Fire and forget here so requests dont cause buffering
// and block more requests from happening?
if (callback) {
setImmediate(callback);
}
}
/**
* Query the transport. Options object is optional.
* @param {Object} options - Loggly-like query options for this instance.
* @param {function} callback - Continuation to respond to when complete.
* @returns {undefined}
*/
}, {
key: "query",
value: function query(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = {
method: 'query',
params: this.normalizeQuery(options)
};
var auth = options.params.auth || null;
delete options.params.auth;
var path = options.params.path || null;
delete options.params.path;
this._request(options, auth, path, function (err, res, body) {
if (res && res.statusCode !== 200) {
err = new Error("Invalid HTTP Status Code: ".concat(res.statusCode));
}
if (err) {
return callback(err);
}
if (typeof body === 'string') {
try {
body = JSON.parse(body);
} catch (e) {
return callback(e);
}
}
callback(null, body);
});
}
/**
* Returns a log stream for this transport. Options object is optional.
* @param {Object} options - Stream options for this instance.
* @returns {Stream} - TODO: add return description
*/
}, {
key: "stream",
value: function stream() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var stream = new Stream();
options = {
method: 'stream',
params: options
};
var path = options.params.path || null;
delete options.params.path;
var auth = options.params.auth || null;
delete options.params.auth;
var buff = '';
var req = this._request(options, auth, path);
stream.destroy = function () {
return req.destroy();
};
req.on('data', function (data) {
data = (buff + data).split(/\n+/);
var l = data.length - 1;
var i = 0;
for (; i < l; i++) {
try {
stream.emit('log', JSON.parse(data[i]));
} catch (e) {
stream.emit('error', e);
}
}
buff = data[l];
});
req.on('error', function (err) {
return stream.emit('error', err);
});
return stream;
}
/**
* Make a request to a winstond server or any http server which can
* handle json-rpc.
* @param {function} options - Options to sent the request.
* @param {Object?} auth - authentication options
* @param {string} path - request path
* @param {function} callback - Continuation to respond to when complete.
*/
}, {
key: "_request",
value: function _request(options, auth, path, callback) {
options = options || {};
auth = auth || this.auth;
path = path || this.path || '';
if (this.batch) {
this._doBatch(options, callback, auth, path);
} else {
this._doRequest(options, callback, auth, path);
}
}
/**
* Send or memorize the options according to batch configuration
* @param {function} options - Options to sent the request.
* @param {function} callback - Continuation to respond to when complete.
* @param {Object?} auth - authentication options
* @param {string} path - request path
*/
}, {
key: "_doBatch",
value: function _doBatch(options, callback, auth, path) {
this.batchOptions.push(options);
if (this.batchOptions.length === 1) {
// First message stored, it's time to start the timeout!
var me = this;
this.batchCallback = callback;
this.batchTimeoutID = setTimeout(function () {
// timeout is reached, send all messages to endpoint
me.batchTimeoutID = -1;
me._doBatchRequest(me.batchCallback, auth, path);
}, this.batchInterval);
}
if (this.batchOptions.length === this.batchCount) {
// max batch count is reached, send all messages to endpoint
this._doBatchRequest(this.batchCallback, auth, path);
}
}
/**
* Initiate a request with the memorized batch options, stop the batch timeout
* @param {function} callback - Continuation to respond to when complete.
* @param {Object?} auth - authentication options
* @param {string} path - request path
*/
}, {
key: "_doBatchRequest",
value: function _doBatchRequest(callback, auth, path) {
if (this.batchTimeoutID > 0) {
clearTimeout(this.batchTimeoutID);
this.batchTimeoutID = -1;
}
var batchOptionsCopy = this.batchOptions.slice();
this.batchOptions = [];
this._doRequest(batchOptionsCopy, callback, auth, path);
}
/**
* Make a request to a winstond server or any http server which can
* handle json-rpc.
* @param {function} options - Options to sent the request.
* @param {function} callback - Continuation to respond to when complete.
* @param {Object?} auth - authentication options
* @param {string} path - request path
*/
}, {
key: "_doRequest",
value: function _doRequest(options, callback, auth, path) {
// Prepare options for outgoing HTTP request
var headers = Object.assign({}, this.headers);
if (auth && auth.bearer) {
headers.Authorization = "Bearer ".concat(auth.bearer);
}
var req = (this.ssl ? https : http).request(_objectSpread(_objectSpread({}, this.options), {}, {
method: 'POST',
host: this.host,
port: this.port,
path: "/".concat(path.replace(/^\//, '')),
headers: headers,
auth: auth && auth.username && auth.password ? "".concat(auth.username, ":").concat(auth.password) : '',
agent: this.agent
}));
req.on('error', callback);
req.on('response', function (res) {
return res.on('end', function () {
return callback(null, res);
}).resume();
});
var jsonStringify = configure(_objectSpread({}, this.maximumDepth && {
maximumDepth: this.maximumDepth
}));
req.end(Buffer.from(jsonStringify(options, this.options.replacer), 'utf8'));
}
}]);
}(TransportStream);

56
node_modules/winston/dist/winston/transports/index.js generated vendored Normal file
View file

@ -0,0 +1,56 @@
/**
* transports.js: Set of all transports Winston knows about.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
/**
* TODO: add property description.
* @type {Console}
*/
Object.defineProperty(exports, 'Console', {
configurable: true,
enumerable: true,
get: function get() {
return require('./console');
}
});
/**
* TODO: add property description.
* @type {File}
*/
Object.defineProperty(exports, 'File', {
configurable: true,
enumerable: true,
get: function get() {
return require('./file');
}
});
/**
* TODO: add property description.
* @type {Http}
*/
Object.defineProperty(exports, 'Http', {
configurable: true,
enumerable: true,
get: function get() {
return require('./http');
}
});
/**
* TODO: add property description.
* @type {Stream}
*/
Object.defineProperty(exports, 'Stream', {
configurable: true,
enumerable: true,
get: function get() {
return require('./stream');
}
});

86
node_modules/winston/dist/winston/transports/stream.js generated vendored Normal file
View file

@ -0,0 +1,86 @@
/**
* stream.js: Transport for outputting to any arbitrary stream.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var isStream = require('is-stream');
var _require = require('triple-beam'),
MESSAGE = _require.MESSAGE;
var os = require('os');
var TransportStream = require('winston-transport');
/**
* Transport for outputting to any arbitrary stream.
* @type {Stream}
* @extends {TransportStream}
*/
module.exports = /*#__PURE__*/function (_TransportStream) {
/**
* Constructor function for the Console transport object responsible for
* persisting log messages and metadata to a terminal or TTY.
* @param {!Object} [options={}] - Options for this instance.
*/
function Stream() {
var _this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, Stream);
_this = _callSuper(this, Stream, [options]);
if (!options.stream || !isStream(options.stream)) {
throw new Error('options.stream is required.');
}
// We need to listen for drain events when write() returns false. This can
// make node mad at times.
_this._stream = options.stream;
_this._stream.setMaxListeners(Infinity);
_this.isObjectMode = options.stream._writableState.objectMode;
_this.eol = typeof options.eol === 'string' ? options.eol : os.EOL;
return _this;
}
/**
* Core logging method exposed to Winston.
* @param {Object} info - TODO: add param description.
* @param {Function} callback - TODO: add param description.
* @returns {undefined}
*/
_inherits(Stream, _TransportStream);
return _createClass(Stream, [{
key: "log",
value: function log(info, callback) {
var _this2 = this;
setImmediate(function () {
return _this2.emit('logged', info);
});
if (this.isObjectMode) {
this._stream.write(info);
if (callback) {
callback(); // eslint-disable-line callback-return
}
return;
}
this._stream.write("".concat(info[MESSAGE]).concat(this.eol));
if (callback) {
callback(); // eslint-disable-line callback-return
}
return;
}
}]);
}(TransportStream);

208
node_modules/winston/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,208 @@
// Type definitions for winston 3.0
// Project: https://github.com/winstonjs/winston
/// <reference types="node" />
import * as NodeJSStream from 'stream';
import * as logform from 'logform';
import * as Transport from 'winston-transport';
import * as Config from './lib/winston/config/index';
import * as Transports from './lib/winston/transports/index';
declare namespace winston {
// Hoisted namespaces from other modules
export import format = logform.format;
export import Logform = logform;
export import config = Config;
export import transports = Transports;
export import transport = Transport;
class ExceptionHandler {
constructor(logger: Logger);
logger: Logger;
handlers: Map<any, any>;
catcher: Function | boolean;
handle(...transports: Transport[]): void;
unhandle(...transports: Transport[]): void;
getAllInfo(err: string | Error): object;
getProcessInfo(): object;
getOsInfo(): object;
getTrace(err: Error): object;
}
class RejectionHandler {
constructor(logger: Logger);
logger: Logger;
handlers: Map<any, any>;
catcher: Function | boolean;
handle(...transports: Transport[]): void;
unhandle(...transports: Transport[]): void;
getAllInfo(err: string | Error): object;
getProcessInfo(): object;
getOsInfo(): object;
getTrace(err: Error): object;
}
interface QueryOptions {
rows?: number;
limit?: number;
start?: number;
from?: Date;
until?: Date;
order?: 'asc' | 'desc';
fields: any;
}
class Profiler {
logger: Logger;
start: Number;
done(info?: any): boolean;
}
interface LogEntry {
level: string;
message: string;
[optionName: string]: any;
}
interface LogMethod {
(level: string, message: string, ...meta: any[]): Logger;
(entry: LogEntry): Logger;
(level: string, message: any): Logger;
}
interface LeveledLogMethod {
(message: string, ...meta: any[]): Logger;
(message: any): Logger;
(infoObject: object): Logger;
}
interface LoggerOptions {
levels?: Config.AbstractConfigSetLevels;
silent?: boolean;
format?: logform.Format;
level?: string;
exitOnError?: Function | boolean;
defaultMeta?: any;
transports?: Transport[] | Transport;
handleExceptions?: boolean;
handleRejections?: boolean;
exceptionHandlers?: any;
rejectionHandlers?: any;
}
class Logger extends NodeJSStream.Transform {
constructor(options?: LoggerOptions);
silent: boolean;
format: logform.Format;
levels: Config.AbstractConfigSetLevels;
level: string;
transports: Transport[];
exceptions: ExceptionHandler;
rejections: RejectionHandler;
profilers: object;
exitOnError: Function | boolean;
defaultMeta?: any;
log: LogMethod;
add(transport: Transport): this;
remove(transport: Transport): this;
clear(): this;
close(): this;
// for cli and npm levels
error: LeveledLogMethod;
warn: LeveledLogMethod;
help: LeveledLogMethod;
data: LeveledLogMethod;
info: LeveledLogMethod;
debug: LeveledLogMethod;
prompt: LeveledLogMethod;
http: LeveledLogMethod;
verbose: LeveledLogMethod;
input: LeveledLogMethod;
silly: LeveledLogMethod;
// for syslog levels only
emerg: LeveledLogMethod;
alert: LeveledLogMethod;
crit: LeveledLogMethod;
warning: LeveledLogMethod;
notice: LeveledLogMethod;
query(
options?: QueryOptions,
callback?: (err: Error, results: any) => void
): any;
stream(options?: any): NodeJS.ReadableStream;
startTimer(): Profiler;
profile(id: string | number, meta?: Record<string, any>): this;
configure(options: LoggerOptions): void;
child(options: Object): this;
isLevelEnabled(level: string): boolean;
isErrorEnabled(): boolean;
isWarnEnabled(): boolean;
isInfoEnabled(): boolean;
isVerboseEnabled(): boolean;
isDebugEnabled(): boolean;
isSillyEnabled(): boolean;
}
class Container {
loggers: Map<string, Logger>;
options: LoggerOptions;
add(id: string, options?: LoggerOptions): Logger;
get(id: string, options?: LoggerOptions): Logger;
has(id: string): boolean;
close(id?: string): void;
constructor(options?: LoggerOptions);
}
let version: string;
let loggers: Container;
let addColors: (target: Config.AbstractConfigSetColors) => any;
let createLogger: (options?: LoggerOptions) => Logger;
// Pass-through npm level methods routed to the default logger.
let error: LeveledLogMethod;
let warn: LeveledLogMethod;
let info: LeveledLogMethod;
let http: LeveledLogMethod;
let verbose: LeveledLogMethod;
let debug: LeveledLogMethod;
let silly: LeveledLogMethod;
// Other pass-through methods routed to the default logger.
let log: LogMethod;
let query: (
options?: QueryOptions,
callback?: (err: Error, results: any) => void
) => any;
let stream: (options?: any) => NodeJS.ReadableStream;
let add: (transport: Transport) => Logger;
let remove: (transport: Transport) => Logger;
let clear: () => Logger;
let startTimer: () => Profiler;
let profile: (id: string | number) => Logger;
let configure: (options: LoggerOptions) => void;
let child: (options: Object) => Logger;
let level: string;
let exceptions: ExceptionHandler;
let rejections: RejectionHandler;
let exitOnError: Function | boolean;
// let default: object;
}
export = winston;

191
node_modules/winston/lib/winston.js generated vendored Normal file
View file

@ -0,0 +1,191 @@
/**
* winston.js: Top-level include defining Winston.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const logform = require('logform');
const { warn } = require('./winston/common');
/**
* Expose version. Use `require` method for `webpack` support.
* @type {string}
*/
exports.version = require('../package.json').version;
/**
* Include transports defined by default by winston
* @type {Array}
*/
exports.transports = require('./winston/transports');
/**
* Expose utility methods
* @type {Object}
*/
exports.config = require('./winston/config');
/**
* Hoist format-related functionality from logform.
* @type {Object}
*/
exports.addColors = logform.levels;
/**
* Hoist format-related functionality from logform.
* @type {Object}
*/
exports.format = logform.format;
/**
* Expose core Logging-related prototypes.
* @type {function}
*/
exports.createLogger = require('./winston/create-logger');
/**
* Expose core Logging-related prototypes.
* @type {function}
*/
exports.Logger = require('./winston/logger');
/**
* Expose core Logging-related prototypes.
* @type {Object}
*/
exports.ExceptionHandler = require('./winston/exception-handler');
/**
* Expose core Logging-related prototypes.
* @type {Object}
*/
exports.RejectionHandler = require('./winston/rejection-handler');
/**
* Expose core Logging-related prototypes.
* @type {Container}
*/
exports.Container = require('./winston/container');
/**
* Expose core Logging-related prototypes.
* @type {Object}
*/
exports.Transport = require('winston-transport');
/**
* We create and expose a default `Container` to `winston.loggers` so that the
* programmer may manage multiple `winston.Logger` instances without any
* additional overhead.
* @example
* // some-file1.js
* const logger = require('winston').loggers.get('something');
*
* // some-file2.js
* const logger = require('winston').loggers.get('something');
*/
exports.loggers = new exports.Container();
/**
* We create and expose a 'defaultLogger' so that the programmer may do the
* following without the need to create an instance of winston.Logger directly:
* @example
* const winston = require('winston');
* winston.log('info', 'some message');
* winston.error('some error');
*/
const defaultLogger = exports.createLogger();
// Pass through the target methods onto `winston.
Object.keys(exports.config.npm.levels)
.concat([
'log',
'query',
'stream',
'add',
'remove',
'clear',
'profile',
'startTimer',
'handleExceptions',
'unhandleExceptions',
'handleRejections',
'unhandleRejections',
'configure',
'child'
])
.forEach(
method => (exports[method] = (...args) => defaultLogger[method](...args))
);
/**
* Define getter / setter for the default logger level which need to be exposed
* by winston.
* @type {string}
*/
Object.defineProperty(exports, 'level', {
get() {
return defaultLogger.level;
},
set(val) {
defaultLogger.level = val;
}
});
/**
* Define getter for `exceptions` which replaces `handleExceptions` and
* `unhandleExceptions`.
* @type {Object}
*/
Object.defineProperty(exports, 'exceptions', {
get() {
return defaultLogger.exceptions;
}
});
/**
* Define getter for `rejections` which replaces `handleRejections` and
* `unhandleRejections`.
* @type {Object}
*/
Object.defineProperty(exports, 'rejections', {
get() {
return defaultLogger.rejections;
}
});
/**
* Define getters / setters for appropriate properties of the default logger
* which need to be exposed by winston.
* @type {Logger}
*/
['exitOnError'].forEach(prop => {
Object.defineProperty(exports, prop, {
get() {
return defaultLogger[prop];
},
set(val) {
defaultLogger[prop] = val;
}
});
});
/**
* The default transports and exceptionHandlers for the default winston logger.
* @type {Object}
*/
Object.defineProperty(exports, 'default', {
get() {
return {
exceptionHandlers: defaultLogger.exceptionHandlers,
rejectionHandlers: defaultLogger.rejectionHandlers,
transports: defaultLogger.transports
};
}
});
// Have friendlier breakage notices for properties that were exposed by default
// on winston < 3.0.
warn.deprecated(exports, 'setLevels');
warn.forFunctions(exports, 'useFormat', ['cli']);
warn.forProperties(exports, 'useFormat', ['padLevels', 'stripColors']);
warn.forFunctions(exports, 'deprecated', [
'addRewriter',
'addFilter',
'clone',
'extend'
]);
warn.forProperties(exports, 'deprecated', ['emitErrs', 'levelLength']);

46
node_modules/winston/lib/winston/common.js generated vendored Normal file
View file

@ -0,0 +1,46 @@
/**
* common.js: Internal helper and utility functions for winston.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const { format } = require('util');
/**
* Set of simple deprecation notices and a way to expose them for a set of
* properties.
* @type {Object}
* @private
*/
exports.warn = {
deprecated(prop) {
return () => {
throw new Error(format('{ %s } was removed in winston@3.0.0.', prop));
};
},
useFormat(prop) {
return () => {
throw new Error([
format('{ %s } was removed in winston@3.0.0.', prop),
'Use a custom winston.format = winston.format(function) instead.'
].join('\n'));
};
},
forFunctions(obj, type, props) {
props.forEach(prop => {
obj[prop] = exports.warn[type](prop);
});
},
forProperties(obj, type, props) {
props.forEach(prop => {
const notice = exports.warn[type](prop);
Object.defineProperty(obj, prop, {
get: notice,
set: notice
});
});
}
};

99
node_modules/winston/lib/winston/config/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,99 @@
// Type definitions for winston 3.0
// Project: https://github.com/winstonjs/winston
/// <reference types="node" />
declare namespace winston {
interface AbstractConfigSetLevels {
[key: string]: number;
}
interface AbstractConfigSetColors {
[key: string]: string | string[];
}
interface AbstractConfigSet {
levels: AbstractConfigSetLevels;
colors: AbstractConfigSetColors;
}
interface CliConfigSetLevels extends AbstractConfigSetLevels {
error: number;
warn: number;
help: number;
data: number;
info: number;
debug: number;
prompt: number;
verbose: number;
input: number;
silly: number;
}
interface CliConfigSetColors extends AbstractConfigSetColors {
error: string | string[];
warn: string | string[];
help: string | string[];
data: string | string[];
info: string | string[];
debug: string | string[];
prompt: string | string[];
verbose: string | string[];
input: string | string[];
silly: string | string[];
}
interface NpmConfigSetLevels extends AbstractConfigSetLevels {
error: number;
warn: number;
info: number;
http: number;
verbose: number;
debug: number;
silly: number;
}
interface NpmConfigSetColors extends AbstractConfigSetColors {
error: string | string[];
warn: string | string[];
info: string | string[];
http: string | string[];
verbose: string | string[];
debug: string | string[];
silly: string | string[];
}
interface SyslogConfigSetLevels extends AbstractConfigSetLevels {
emerg: number;
alert: number;
crit: number;
error: number;
warning: number;
notice: number;
info: number;
debug: number;
}
interface SyslogConfigSetColors extends AbstractConfigSetColors {
emerg: string | string[];
alert: string | string[];
crit: string | string[];
error: string | string[];
warning: string | string[];
notice: string | string[];
info: string | string[];
debug: string | string[];
}
interface Config {
allColors: AbstractConfigSetColors;
cli: { levels: CliConfigSetLevels, colors: CliConfigSetColors };
npm: { levels: NpmConfigSetLevels, colors: NpmConfigSetColors };
syslog: { levels: SyslogConfigSetLevels, colors: SyslogConfigSetColors };
addColors(colors: AbstractConfigSetColors): void;
}
}
declare const winston: winston.Config;
export = winston;

35
node_modules/winston/lib/winston/config/index.js generated vendored Normal file
View file

@ -0,0 +1,35 @@
/**
* index.js: Default settings for all levels that winston knows about.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const logform = require('logform');
const { configs } = require('triple-beam');
/**
* Export config set for the CLI.
* @type {Object}
*/
exports.cli = logform.levels(configs.cli);
/**
* Export config set for npm.
* @type {Object}
*/
exports.npm = logform.levels(configs.npm);
/**
* Export config set for the syslog.
* @type {Object}
*/
exports.syslog = logform.levels(configs.syslog);
/**
* Hoist addColors from logform where it was refactored into in winston@3.
* @type {Object}
*/
exports.addColors = logform.levels;

118
node_modules/winston/lib/winston/container.js generated vendored Normal file
View file

@ -0,0 +1,118 @@
/**
* container.js: Inversion of control container for winston logger instances.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const createLogger = require('./create-logger');
/**
* Inversion of control container for winston logger instances.
* @type {Container}
*/
module.exports = class Container {
/**
* Constructor function for the Container object responsible for managing a
* set of `winston.Logger` instances based on string ids.
* @param {!Object} [options={}] - Default pass-thru options for Loggers.
*/
constructor(options = {}) {
this.loggers = new Map();
this.options = options;
}
/**
* Retrieves a `winston.Logger` instance for the specified `id`. If an
* instance does not exist, one is created.
* @param {!string} id - The id of the Logger to get.
* @param {?Object} [options] - Options for the Logger instance.
* @returns {Logger} - A configured Logger instance with a specified id.
*/
add(id, options) {
if (!this.loggers.has(id)) {
// Remark: Simple shallow clone for configuration options in case we pass
// in instantiated protoypal objects
options = Object.assign({}, options || this.options);
const existing = options.transports || this.options.transports;
// Remark: Make sure if we have an array of transports we slice it to
// make copies of those references.
if (existing) {
options.transports = Array.isArray(existing) ? existing.slice() : [existing];
} else {
options.transports = [];
}
const logger = createLogger(options);
logger.on('close', () => this._delete(id));
this.loggers.set(id, logger);
}
return this.loggers.get(id);
}
/**
* Retreives a `winston.Logger` instance for the specified `id`. If
* an instance does not exist, one is created.
* @param {!string} id - The id of the Logger to get.
* @param {?Object} [options] - Options for the Logger instance.
* @returns {Logger} - A configured Logger instance with a specified id.
*/
get(id, options) {
return this.add(id, options);
}
/**
* Check if the container has a logger with the id.
* @param {?string} id - The id of the Logger instance to find.
* @returns {boolean} - Boolean value indicating if this instance has a
* logger with the specified `id`.
*/
has(id) {
return !!this.loggers.has(id);
}
/**
* Closes a `Logger` instance with the specified `id` if it exists.
* If no `id` is supplied then all Loggers are closed.
* @param {?string} id - The id of the Logger instance to close.
* @returns {undefined}
*/
close(id) {
if (id) {
return this._removeLogger(id);
}
this.loggers.forEach((val, key) => this._removeLogger(key));
}
/**
* Remove a logger based on the id.
* @param {!string} id - The id of the logger to remove.
* @returns {undefined}
* @private
*/
_removeLogger(id) {
if (!this.loggers.has(id)) {
return;
}
const logger = this.loggers.get(id);
logger.close();
this._delete(id);
}
/**
* Deletes a `Logger` instance with the specified `id`.
* @param {!string} id - The id of the Logger instance to delete from
* container.
* @returns {undefined}
* @private
*/
_delete(id) {
this.loggers.delete(id);
}
};

104
node_modules/winston/lib/winston/create-logger.js generated vendored Normal file
View file

@ -0,0 +1,104 @@
/**
* create-logger.js: Logger factory for winston logger instances.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const { LEVEL } = require('triple-beam');
const config = require('./config');
const Logger = require('./logger');
const debug = require('@dabh/diagnostics')('winston:create-logger');
function isLevelEnabledFunctionName(level) {
return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled';
}
/**
* Create a new instance of a winston Logger. Creates a new
* prototype for each instance.
* @param {!Object} opts - Options for the created logger.
* @returns {Logger} - A newly created logger instance.
*/
module.exports = function (opts = {}) {
//
// Default levels: npm
//
opts.levels = opts.levels || config.npm.levels;
/**
* DerivedLogger to attach the logs level methods.
* @type {DerivedLogger}
* @extends {Logger}
*/
class DerivedLogger extends Logger {
/**
* Create a new class derived logger for which the levels can be attached to
* the prototype of. This is a V8 optimization that is well know to increase
* performance of prototype functions.
* @param {!Object} options - Options for the created logger.
*/
constructor(options) {
super(options);
}
}
const logger = new DerivedLogger(opts);
//
// Create the log level methods for the derived logger.
//
Object.keys(opts.levels).forEach(function (level) {
debug('Define prototype method for "%s"', level);
if (level === 'log') {
// eslint-disable-next-line no-console
console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.');
return;
}
//
// Define prototype methods for each log level e.g.:
// logger.log('info', msg) implies these methods are defined:
// - logger.info(msg)
// - logger.isInfoEnabled()
//
// Remark: to support logger.child this **MUST** be a function
// so it'll always be called on the instance instead of a fixed
// place in the prototype chain.
//
DerivedLogger.prototype[level] = function (...args) {
// Prefer any instance scope, but default to "root" logger
const self = this || logger;
// Optimize the hot-path which is the single object.
if (args.length === 1) {
const [msg] = args;
const info = msg && msg.message && msg || { message: msg };
info.level = info[LEVEL] = level;
self._addDefaultMeta(info);
self.write(info);
return (this || logger);
}
// When provided nothing assume the empty string
if (args.length === 0) {
self.log(level, '');
return self;
}
// Otherwise build argument list which could potentially conform to
// either:
// . v3 API: log(obj)
// 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback])
return self.log(level, ...args);
};
DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () {
return (this || logger).isLevelEnabled(level);
};
});
return logger;
};

245
node_modules/winston/lib/winston/exception-handler.js generated vendored Normal file
View file

@ -0,0 +1,245 @@
/**
* exception-handler.js: Object for handling uncaughtException events.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const os = require('os');
const asyncForEach = require('async/forEach');
const debug = require('@dabh/diagnostics')('winston:exception');
const once = require('one-time');
const stackTrace = require('stack-trace');
const ExceptionStream = require('./exception-stream');
/**
* Object for handling uncaughtException events.
* @type {ExceptionHandler}
*/
module.exports = class ExceptionHandler {
/**
* TODO: add contructor description
* @param {!Logger} logger - TODO: add param description
*/
constructor(logger) {
if (!logger) {
throw new Error('Logger is required to handle exceptions');
}
this.logger = logger;
this.handlers = new Map();
}
/**
* Handles `uncaughtException` events for the current process by adding any
* handlers passed in.
* @returns {undefined}
*/
handle(...args) {
args.forEach(arg => {
if (Array.isArray(arg)) {
return arg.forEach(handler => this._addHandler(handler));
}
this._addHandler(arg);
});
if (!this.catcher) {
this.catcher = this._uncaughtException.bind(this);
process.on('uncaughtException', this.catcher);
}
}
/**
* Removes any handlers to `uncaughtException` events for the current
* process. This does not modify the state of the `this.handlers` set.
* @returns {undefined}
*/
unhandle() {
if (this.catcher) {
process.removeListener('uncaughtException', this.catcher);
this.catcher = false;
Array.from(this.handlers.values())
.forEach(wrapper => this.logger.unpipe(wrapper));
}
}
/**
* TODO: add method description
* @param {Error} err - Error to get information about.
* @returns {mixed} - TODO: add return description.
*/
getAllInfo(err) {
let message = null;
if (err) {
message = typeof err === 'string' ? err : err.message;
}
return {
error: err,
// TODO (indexzero): how do we configure this?
level: 'error',
message: [
`uncaughtException: ${(message || '(no error message)')}`,
err && err.stack || ' No stack trace'
].join('\n'),
stack: err && err.stack,
exception: true,
date: new Date().toString(),
process: this.getProcessInfo(),
os: this.getOsInfo(),
trace: this.getTrace(err)
};
}
/**
* Gets all relevant process information for the currently running process.
* @returns {mixed} - TODO: add return description.
*/
getProcessInfo() {
return {
pid: process.pid,
uid: process.getuid ? process.getuid() : null,
gid: process.getgid ? process.getgid() : null,
cwd: process.cwd(),
execPath: process.execPath,
version: process.version,
argv: process.argv,
memoryUsage: process.memoryUsage()
};
}
/**
* Gets all relevant OS information for the currently running process.
* @returns {mixed} - TODO: add return description.
*/
getOsInfo() {
return {
loadavg: os.loadavg(),
uptime: os.uptime()
};
}
/**
* Gets a stack trace for the specified error.
* @param {mixed} err - TODO: add param description.
* @returns {mixed} - TODO: add return description.
*/
getTrace(err) {
const trace = err ? stackTrace.parse(err) : stackTrace.get();
return trace.map(site => {
return {
column: site.getColumnNumber(),
file: site.getFileName(),
function: site.getFunctionName(),
line: site.getLineNumber(),
method: site.getMethodName(),
native: site.isNative()
};
});
}
/**
* Helper method to add a transport as an exception handler.
* @param {Transport} handler - The transport to add as an exception handler.
* @returns {void}
*/
_addHandler(handler) {
if (!this.handlers.has(handler)) {
handler.handleExceptions = true;
const wrapper = new ExceptionStream(handler);
this.handlers.set(handler, wrapper);
this.logger.pipe(wrapper);
}
}
/**
* Logs all relevant information around the `err` and exits the current
* process.
* @param {Error} err - Error to handle
* @returns {mixed} - TODO: add return description.
* @private
*/
_uncaughtException(err) {
const info = this.getAllInfo(err);
const handlers = this._getExceptionHandlers();
// Calculate if we should exit on this error
let doExit = typeof this.logger.exitOnError === 'function'
? this.logger.exitOnError(err)
: this.logger.exitOnError;
let timeout;
if (!handlers.length && doExit) {
// eslint-disable-next-line no-console
console.warn('winston: exitOnError cannot be true with no exception handlers.');
// eslint-disable-next-line no-console
console.warn('winston: not exiting process.');
doExit = false;
}
function gracefulExit() {
debug('doExit', doExit);
debug('process._exiting', process._exiting);
if (doExit && !process._exiting) {
// Remark: Currently ignoring any exceptions from transports when
// catching uncaught exceptions.
if (timeout) {
clearTimeout(timeout);
}
// eslint-disable-next-line no-process-exit
process.exit(1);
}
}
if (!handlers || handlers.length === 0) {
return process.nextTick(gracefulExit);
}
// Log to all transports attempting to listen for when they are completed.
asyncForEach(handlers, (handler, next) => {
const done = once(next);
const transport = handler.transport || handler;
// Debug wrapping so that we can inspect what's going on under the covers.
function onDone(event) {
return () => {
debug(event);
done();
};
}
transport._ending = true;
transport.once('finish', onDone('finished'));
transport.once('error', onDone('error'));
}, () => doExit && gracefulExit());
this.logger.log(info);
// If exitOnError is true, then only allow the logging of exceptions to
// take up to `3000ms`.
if (doExit) {
timeout = setTimeout(gracefulExit, 3000);
}
}
/**
* Returns the list of transports and exceptionHandlers for this instance.
* @returns {Array} - List of transports and exceptionHandlers for this
* instance.
* @private
*/
_getExceptionHandlers() {
// Remark (indexzero): since `logger.transports` returns all of the pipes
// from the _readableState of the stream we actually get the join of the
// explicit handlers and the implicit transports with
// `handleExceptions: true`
return this.logger.transports.filter(wrap => {
const transport = wrap.transport || wrap;
return transport.handleExceptions;
});
}
};

54
node_modules/winston/lib/winston/exception-stream.js generated vendored Normal file
View file

@ -0,0 +1,54 @@
/**
* exception-stream.js: TODO: add file header handler.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const { Writable } = require('readable-stream');
/**
* TODO: add class description.
* @type {ExceptionStream}
* @extends {Writable}
*/
module.exports = class ExceptionStream extends Writable {
/**
* Constructor function for the ExceptionStream responsible for wrapping a
* TransportStream; only allowing writes of `info` objects with
* `info.exception` set to true.
* @param {!TransportStream} transport - Stream to filter to exceptions
*/
constructor(transport) {
super({ objectMode: true });
if (!transport) {
throw new Error('ExceptionStream requires a TransportStream instance.');
}
// Remark (indexzero): we set `handleExceptions` here because it's the
// predicate checked in ExceptionHandler.prototype.__getExceptionHandlers
this.handleExceptions = true;
this.transport = transport;
}
/**
* Writes the info object to our transport instance if (and only if) the
* `exception` property is set on the info.
* @param {mixed} info - TODO: add param description.
* @param {mixed} enc - TODO: add param description.
* @param {mixed} callback - TODO: add param description.
* @returns {mixed} - TODO: add return description.
* @private
*/
_write(info, enc, callback) {
if (info.exception) {
return this.transport.log(info, callback);
}
callback();
return true;
}
};

677
node_modules/winston/lib/winston/logger.js generated vendored Normal file
View file

@ -0,0 +1,677 @@
/**
* logger.js: TODO: add file header description.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const { Stream, Transform } = require('readable-stream');
const asyncForEach = require('async/forEach');
const { LEVEL, SPLAT } = require('triple-beam');
const isStream = require('is-stream');
const ExceptionHandler = require('./exception-handler');
const RejectionHandler = require('./rejection-handler');
const LegacyTransportStream = require('winston-transport/legacy');
const Profiler = require('./profiler');
const { warn } = require('./common');
const config = require('./config');
/**
* Captures the number of format (i.e. %s strings) in a given string.
* Based on `util.format`, see Node.js source:
* https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230
* @type {RegExp}
*/
const formatRegExp = /%[scdjifoO%]/g;
/**
* TODO: add class description.
* @type {Logger}
* @extends {Transform}
*/
class Logger extends Transform {
/**
* Constructor function for the Logger object responsible for persisting log
* messages and metadata to one or more transports.
* @param {!Object} options - foo
*/
constructor(options) {
super({ objectMode: true });
this.configure(options);
}
child(defaultRequestMetadata) {
const logger = this;
return Object.create(logger, {
write: {
value: function (info) {
const infoClone = Object.assign(
{},
defaultRequestMetadata,
info
);
// Object.assign doesn't copy inherited Error
// properties so we have to do that explicitly
//
// Remark (indexzero): we should remove this
// since the errors format will handle this case.
//
if (info instanceof Error) {
infoClone.stack = info.stack;
infoClone.message = info.message;
}
logger.write(infoClone);
}
}
});
}
/**
* This will wholesale reconfigure this instance by:
* 1. Resetting all transports. Older transports will be removed implicitly.
* 2. Set all other options including levels, colors, rewriters, filters,
* exceptionHandlers, etc.
* @param {!Object} options - TODO: add param description.
* @returns {undefined}
*/
configure({
silent,
format,
defaultMeta,
levels,
level = 'info',
exitOnError = true,
transports,
colors,
emitErrs,
formatters,
padLevels,
rewriters,
stripColors,
exceptionHandlers,
rejectionHandlers
} = {}) {
// Reset transports if we already have them
if (this.transports.length) {
this.clear();
}
this.silent = silent;
this.format = format || this.format || require('logform/json')();
this.defaultMeta = defaultMeta || null;
// Hoist other options onto this instance.
this.levels = levels || this.levels || config.npm.levels;
this.level = level;
if (this.exceptions) {
this.exceptions.unhandle();
}
if (this.rejections) {
this.rejections.unhandle();
}
this.exceptions = new ExceptionHandler(this);
this.rejections = new RejectionHandler(this);
this.profilers = {};
this.exitOnError = exitOnError;
// Add all transports we have been provided.
if (transports) {
transports = Array.isArray(transports) ? transports : [transports];
transports.forEach(transport => this.add(transport));
}
if (
colors ||
emitErrs ||
formatters ||
padLevels ||
rewriters ||
stripColors
) {
throw new Error(
[
'{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.',
'Use a custom winston.format(function) instead.',
'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'
].join('\n')
);
}
if (exceptionHandlers) {
this.exceptions.handle(exceptionHandlers);
}
if (rejectionHandlers) {
this.rejections.handle(rejectionHandlers);
}
}
isLevelEnabled(level) {
const givenLevelValue = getLevelValue(this.levels, level);
if (givenLevelValue === null) {
return false;
}
const configuredLevelValue = getLevelValue(this.levels, this.level);
if (configuredLevelValue === null) {
return false;
}
if (!this.transports || this.transports.length === 0) {
return configuredLevelValue >= givenLevelValue;
}
const index = this.transports.findIndex(transport => {
let transportLevelValue = getLevelValue(this.levels, transport.level);
if (transportLevelValue === null) {
transportLevelValue = configuredLevelValue;
}
return transportLevelValue >= givenLevelValue;
});
return index !== -1;
}
/* eslint-disable valid-jsdoc */
/**
* Ensure backwards compatibility with a `log` method
* @param {mixed} level - Level the log message is written at.
* @param {mixed} msg - TODO: add param description.
* @param {mixed} meta - TODO: add param description.
* @returns {Logger} - TODO: add return description.
*
* @example
* // Supports the existing API:
* logger.log('info', 'Hello world', { custom: true });
* logger.log('info', new Error('Yo, it\'s on fire'));
*
* // Requires winston.format.splat()
* logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true });
*
* // And the new API with a single JSON literal:
* logger.log({ level: 'info', message: 'Hello world', custom: true });
* logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') });
*
* // Also requires winston.format.splat()
* logger.log({
* level: 'info',
* message: '%s %d%%',
* [SPLAT]: ['A string', 50],
* meta: { thisIsMeta: true }
* });
*
*/
/* eslint-enable valid-jsdoc */
log(level, msg, ...splat) {
// eslint-disable-line max-params
// Optimize for the hotpath of logging JSON literals
if (arguments.length === 1) {
// Yo dawg, I heard you like levels ... seriously ...
// In this context the LHS `level` here is actually the `info` so read
// this as: info[LEVEL] = info.level;
level[LEVEL] = level.level;
this._addDefaultMeta(level);
this.write(level);
return this;
}
// Slightly less hotpath, but worth optimizing for.
if (arguments.length === 2) {
if (msg && typeof msg === 'object') {
msg[LEVEL] = msg.level = level;
this._addDefaultMeta(msg);
this.write(msg);
return this;
}
msg = { [LEVEL]: level, level, message: msg };
this._addDefaultMeta(msg);
this.write(msg);
return this;
}
const [meta] = splat;
if (typeof meta === 'object' && meta !== null) {
// Extract tokens, if none available default to empty array to
// ensure consistancy in expected results
const tokens = msg && msg.match && msg.match(formatRegExp);
if (!tokens) {
const info = Object.assign({}, this.defaultMeta, meta, {
[LEVEL]: level,
[SPLAT]: splat,
level,
message: msg
});
if (meta.message) info.message = `${info.message} ${meta.message}`;
if (meta.stack) info.stack = meta.stack;
if (meta.cause) info.cause = meta.cause;
this.write(info);
return this;
}
}
this.write(Object.assign({}, this.defaultMeta, {
[LEVEL]: level,
[SPLAT]: splat,
level,
message: msg
}));
return this;
}
/**
* Pushes data so that it can be picked up by all of our pipe targets.
* @param {mixed} info - TODO: add param description.
* @param {mixed} enc - TODO: add param description.
* @param {mixed} callback - Continues stream processing.
* @returns {undefined}
* @private
*/
_transform(info, enc, callback) {
if (this.silent) {
return callback();
}
// [LEVEL] is only soft guaranteed to be set here since we are a proper
// stream. It is likely that `info` came in through `.log(info)` or
// `.info(info)`. If it is not defined, however, define it.
// This LEVEL symbol is provided by `triple-beam` and also used in:
// - logform
// - winston-transport
// - abstract-winston-transport
if (!info[LEVEL]) {
info[LEVEL] = info.level;
}
// Remark: really not sure what to do here, but this has been reported as
// very confusing by pre winston@2.0.0 users as quite confusing when using
// custom levels.
if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) {
// eslint-disable-next-line no-console
console.error('[winston] Unknown logger level: %s', info[LEVEL]);
}
// Remark: not sure if we should simply error here.
if (!this._readableState.pipes) {
// eslint-disable-next-line no-console
console.error(
'[winston] Attempt to write logs with no transports, which can increase memory usage: %j',
info
);
}
// Here we write to the `format` pipe-chain, which on `readable` above will
// push the formatted `info` Object onto the buffer for this instance. We trap
// (and re-throw) any errors generated by the user-provided format, but also
// guarantee that the streams callback is invoked so that we can continue flowing.
try {
this.push(this.format.transform(info, this.format.options));
} finally {
this._writableState.sync = false;
// eslint-disable-next-line callback-return
callback();
}
}
/**
* Delays the 'finish' event until all transport pipe targets have
* also emitted 'finish' or are already finished.
* @param {mixed} callback - Continues stream processing.
*/
_final(callback) {
const transports = this.transports.slice();
asyncForEach(
transports,
(transport, next) => {
if (!transport || transport.finished) return setImmediate(next);
transport.once('finish', next);
transport.end();
},
callback
);
}
/**
* Adds the transport to this logger instance by piping to it.
* @param {mixed} transport - TODO: add param description.
* @returns {Logger} - TODO: add return description.
*/
add(transport) {
// Support backwards compatibility with all existing `winston < 3.x.x`
// transports which meet one of two criteria:
// 1. They inherit from winston.Transport in < 3.x.x which is NOT a stream.
// 2. They expose a log method which has a length greater than 2 (i.e. more then
// just `log(info, callback)`.
const target =
!isStream(transport) || transport.log.length > 2
? new LegacyTransportStream({ transport })
: transport;
if (!target._writableState || !target._writableState.objectMode) {
throw new Error(
'Transports must WritableStreams in objectMode. Set { objectMode: true }.'
);
}
// Listen for the `error` event and the `warn` event on the new Transport.
this._onEvent('error', target);
this._onEvent('warn', target);
this.pipe(target);
if (transport.handleExceptions) {
this.exceptions.handle();
}
if (transport.handleRejections) {
this.rejections.handle();
}
return this;
}
/**
* Removes the transport from this logger instance by unpiping from it.
* @param {mixed} transport - TODO: add param description.
* @returns {Logger} - TODO: add return description.
*/
remove(transport) {
if (!transport) return this;
let target = transport;
if (!isStream(transport) || transport.log.length > 2) {
target = this.transports.filter(
match => match.transport === transport
)[0];
}
if (target) {
this.unpipe(target);
}
return this;
}
/**
* Removes all transports from this logger instance.
* @returns {Logger} - TODO: add return description.
*/
clear() {
this.unpipe();
return this;
}
/**
* Cleans up resources (streams, event listeners) for all transports
* associated with this instance (if necessary).
* @returns {Logger} - TODO: add return description.
*/
close() {
this.exceptions.unhandle();
this.rejections.unhandle();
this.clear();
this.emit('close');
return this;
}
/**
* Sets the `target` levels specified on this instance.
* @param {Object} Target levels to use on this instance.
*/
setLevels() {
warn.deprecated('setLevels');
}
/**
* Queries the all transports for this instance with the specified `options`.
* This will aggregate each transport's results into one object containing
* a property per transport.
* @param {Object} options - Query options for this instance.
* @param {function} callback - Continuation to respond to when complete.
*/
query(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
const results = {};
const queryObject = Object.assign({}, options.query || {});
// Helper function to query a single transport
function queryTransport(transport, next) {
if (options.query && typeof transport.formatQuery === 'function') {
options.query = transport.formatQuery(queryObject);
}
transport.query(options, (err, res) => {
if (err) {
return next(err);
}
if (typeof transport.formatResults === 'function') {
res = transport.formatResults(res, options.format);
}
next(null, res);
});
}
// Helper function to accumulate the results from `queryTransport` into
// the `results`.
function addResults(transport, next) {
queryTransport(transport, (err, result) => {
// queryTransport could potentially invoke the callback multiple times
// since Transport code can be unpredictable.
if (next) {
result = err || result;
if (result) {
results[transport.name] = result;
}
// eslint-disable-next-line callback-return
next();
}
next = null;
});
}
// Iterate over the transports in parallel setting the appropriate key in
// the `results`.
asyncForEach(
this.transports.filter(transport => !!transport.query),
addResults,
() => callback(null, results)
);
}
/**
* Returns a log stream for all transports. Options object is optional.
* @param{Object} options={} - Stream options for this instance.
* @returns {Stream} - TODO: add return description.
*/
stream(options = {}) {
const out = new Stream();
const streams = [];
out._streams = streams;
out.destroy = () => {
let i = streams.length;
while (i--) {
streams[i].destroy();
}
};
// Create a list of all transports for this instance.
this.transports
.filter(transport => !!transport.stream)
.forEach(transport => {
const str = transport.stream(options);
if (!str) {
return;
}
streams.push(str);
str.on('log', log => {
log.transport = log.transport || [];
log.transport.push(transport.name);
out.emit('log', log);
});
str.on('error', err => {
err.transport = err.transport || [];
err.transport.push(transport.name);
out.emit('error', err);
});
});
return out;
}
/**
* Returns an object corresponding to a specific timing. When done is called
* the timer will finish and log the duration. e.g.:
* @returns {Profile} - TODO: add return description.
* @example
* const timer = winston.startTimer()
* setTimeout(() => {
* timer.done({
* message: 'Logging message'
* });
* }, 1000);
*/
startTimer() {
return new Profiler(this);
}
/**
* Tracks the time inbetween subsequent calls to this method with the same
* `id` parameter. The second call to this method will log the difference in
* milliseconds along with the message.
* @param {string} id Unique id of the profiler
* @returns {Logger} - TODO: add return description.
*/
profile(id, ...args) {
const time = Date.now();
if (this.profilers[id]) {
const timeEnd = this.profilers[id];
delete this.profilers[id];
// Attempt to be kind to users if they are still using older APIs.
if (typeof args[args.length - 2] === 'function') {
// eslint-disable-next-line no-console
console.warn(
'Callback function no longer supported as of winston@3.0.0'
);
args.pop();
}
// Set the duration property of the metadata
const info = typeof args[args.length - 1] === 'object' ? args.pop() : {};
info.level = info.level || 'info';
info.durationMs = time - timeEnd;
info.message = info.message || id;
return this.write(info);
}
this.profilers[id] = time;
return this;
}
/**
* Backwards compatibility to `exceptions.handle` in winston < 3.0.0.
* @returns {undefined}
* @deprecated
*/
handleExceptions(...args) {
// eslint-disable-next-line no-console
console.warn(
'Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()'
);
this.exceptions.handle(...args);
}
/**
* Backwards compatibility to `exceptions.handle` in winston < 3.0.0.
* @returns {undefined}
* @deprecated
*/
unhandleExceptions(...args) {
// eslint-disable-next-line no-console
console.warn(
'Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()'
);
this.exceptions.unhandle(...args);
}
/**
* Throw a more meaningful deprecation notice
* @throws {Error} - TODO: add throws description.
*/
cli() {
throw new Error(
[
'Logger.cli() was removed in winston@3.0.0',
'Use a custom winston.formats.cli() instead.',
'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'
].join('\n')
);
}
/**
* Bubbles the `event` that occured on the specified `transport` up
* from this instance.
* @param {string} event - The event that occured
* @param {Object} transport - Transport on which the event occured
* @private
*/
_onEvent(event, transport) {
function transportEvent(err) {
// https://github.com/winstonjs/winston/issues/1364
if (event === 'error' && !this.transports.includes(transport)) {
this.add(transport);
}
this.emit(event, err, transport);
}
if (!transport['__winston' + event]) {
transport['__winston' + event] = transportEvent.bind(this);
transport.on(event, transport['__winston' + event]);
}
}
_addDefaultMeta(msg) {
if (this.defaultMeta) {
Object.assign(msg, this.defaultMeta);
}
}
}
function getLevelValue(levels, level) {
const value = levels[level];
if (!value && value !== 0) {
return null;
}
return value;
}
/**
* Represents the current readableState pipe targets for this Logger instance.
* @type {Array|Object}
*/
Object.defineProperty(Logger.prototype, 'transports', {
configurable: false,
enumerable: true,
get() {
const { pipes } = this._readableState;
return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes;
}
});
module.exports = Logger;

53
node_modules/winston/lib/winston/profiler.js generated vendored Normal file
View file

@ -0,0 +1,53 @@
/**
* profiler.js: TODO: add file header description.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
/**
* TODO: add class description.
* @type {Profiler}
* @private
*/
class Profiler {
/**
* Constructor function for the Profiler instance used by
* `Logger.prototype.startTimer`. When done is called the timer will finish
* and log the duration.
* @param {!Logger} logger - TODO: add param description.
* @private
*/
constructor(logger) {
const Logger = require('./logger');
if (typeof logger !== 'object' || Array.isArray(logger) || !(logger instanceof Logger)) {
throw new Error('Logger is required for profiling');
} else {
this.logger = logger;
this.start = Date.now();
}
}
/**
* Ends the current timer (i.e. Profiler) instance and logs the `msg` along
* with the duration since creation.
* @returns {mixed} - TODO: add return description.
* @private
*/
done(...args) {
if (typeof args[args.length - 1] === 'function') {
// eslint-disable-next-line no-console
console.warn('Callback function no longer supported as of winston@3.0.0');
args.pop();
}
const info = typeof args[args.length - 1] === 'object' ? args.pop() : {};
info.level = info.level || 'info';
info.durationMs = (Date.now()) - this.start;
return this.logger.write(info);
}
};
module.exports = Profiler;

251
node_modules/winston/lib/winston/rejection-handler.js generated vendored Normal file
View file

@ -0,0 +1,251 @@
/**
* exception-handler.js: Object for handling uncaughtException events.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const os = require('os');
const asyncForEach = require('async/forEach');
const debug = require('@dabh/diagnostics')('winston:rejection');
const once = require('one-time');
const stackTrace = require('stack-trace');
const RejectionStream = require('./rejection-stream');
/**
* Object for handling unhandledRejection events.
* @type {RejectionHandler}
*/
module.exports = class RejectionHandler {
/**
* TODO: add contructor description
* @param {!Logger} logger - TODO: add param description
*/
constructor(logger) {
if (!logger) {
throw new Error('Logger is required to handle rejections');
}
this.logger = logger;
this.handlers = new Map();
}
/**
* Handles `unhandledRejection` events for the current process by adding any
* handlers passed in.
* @returns {undefined}
*/
handle(...args) {
args.forEach(arg => {
if (Array.isArray(arg)) {
return arg.forEach(handler => this._addHandler(handler));
}
this._addHandler(arg);
});
if (!this.catcher) {
this.catcher = this._unhandledRejection.bind(this);
process.on('unhandledRejection', this.catcher);
}
}
/**
* Removes any handlers to `unhandledRejection` events for the current
* process. This does not modify the state of the `this.handlers` set.
* @returns {undefined}
*/
unhandle() {
if (this.catcher) {
process.removeListener('unhandledRejection', this.catcher);
this.catcher = false;
Array.from(this.handlers.values()).forEach(wrapper =>
this.logger.unpipe(wrapper)
);
}
}
/**
* TODO: add method description
* @param {Error} err - Error to get information about.
* @returns {mixed} - TODO: add return description.
*/
getAllInfo(err) {
let message = null;
if (err) {
message = typeof err === 'string' ? err : err.message;
}
return {
error: err,
// TODO (indexzero): how do we configure this?
level: 'error',
message: [
`unhandledRejection: ${message || '(no error message)'}`,
err && err.stack || ' No stack trace'
].join('\n'),
stack: err && err.stack,
rejection: true,
date: new Date().toString(),
process: this.getProcessInfo(),
os: this.getOsInfo(),
trace: this.getTrace(err)
};
}
/**
* Gets all relevant process information for the currently running process.
* @returns {mixed} - TODO: add return description.
*/
getProcessInfo() {
return {
pid: process.pid,
uid: process.getuid ? process.getuid() : null,
gid: process.getgid ? process.getgid() : null,
cwd: process.cwd(),
execPath: process.execPath,
version: process.version,
argv: process.argv,
memoryUsage: process.memoryUsage()
};
}
/**
* Gets all relevant OS information for the currently running process.
* @returns {mixed} - TODO: add return description.
*/
getOsInfo() {
return {
loadavg: os.loadavg(),
uptime: os.uptime()
};
}
/**
* Gets a stack trace for the specified error.
* @param {mixed} err - TODO: add param description.
* @returns {mixed} - TODO: add return description.
*/
getTrace(err) {
const trace = err ? stackTrace.parse(err) : stackTrace.get();
return trace.map(site => {
return {
column: site.getColumnNumber(),
file: site.getFileName(),
function: site.getFunctionName(),
line: site.getLineNumber(),
method: site.getMethodName(),
native: site.isNative()
};
});
}
/**
* Helper method to add a transport as an exception handler.
* @param {Transport} handler - The transport to add as an exception handler.
* @returns {void}
*/
_addHandler(handler) {
if (!this.handlers.has(handler)) {
handler.handleRejections = true;
const wrapper = new RejectionStream(handler);
this.handlers.set(handler, wrapper);
this.logger.pipe(wrapper);
}
}
/**
* Logs all relevant information around the `err` and exits the current
* process.
* @param {Error} err - Error to handle
* @returns {mixed} - TODO: add return description.
* @private
*/
_unhandledRejection(err) {
const info = this.getAllInfo(err);
const handlers = this._getRejectionHandlers();
// Calculate if we should exit on this error
let doExit =
typeof this.logger.exitOnError === 'function'
? this.logger.exitOnError(err)
: this.logger.exitOnError;
let timeout;
if (!handlers.length && doExit) {
// eslint-disable-next-line no-console
console.warn('winston: exitOnError cannot be true with no rejection handlers.');
// eslint-disable-next-line no-console
console.warn('winston: not exiting process.');
doExit = false;
}
function gracefulExit() {
debug('doExit', doExit);
debug('process._exiting', process._exiting);
if (doExit && !process._exiting) {
// Remark: Currently ignoring any rejections from transports when
// catching unhandled rejections.
if (timeout) {
clearTimeout(timeout);
}
// eslint-disable-next-line no-process-exit
process.exit(1);
}
}
if (!handlers || handlers.length === 0) {
return process.nextTick(gracefulExit);
}
// Log to all transports attempting to listen for when they are completed.
asyncForEach(
handlers,
(handler, next) => {
const done = once(next);
const transport = handler.transport || handler;
// Debug wrapping so that we can inspect what's going on under the covers.
function onDone(event) {
return () => {
debug(event);
done();
};
}
transport._ending = true;
transport.once('finish', onDone('finished'));
transport.once('error', onDone('error'));
},
() => doExit && gracefulExit()
);
this.logger.log(info);
// If exitOnError is true, then only allow the logging of exceptions to
// take up to `3000ms`.
if (doExit) {
timeout = setTimeout(gracefulExit, 3000);
}
}
/**
* Returns the list of transports and exceptionHandlers for this instance.
* @returns {Array} - List of transports and exceptionHandlers for this
* instance.
* @private
*/
_getRejectionHandlers() {
// Remark (indexzero): since `logger.transports` returns all of the pipes
// from the _readableState of the stream we actually get the join of the
// explicit handlers and the implicit transports with
// `handleRejections: true`
return this.logger.transports.filter(wrap => {
const transport = wrap.transport || wrap;
return transport.handleRejections;
});
}
};

52
node_modules/winston/lib/winston/rejection-stream.js generated vendored Normal file
View file

@ -0,0 +1,52 @@
/**
* rejection-stream.js: TODO: add file header handler.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const { Writable } = require('readable-stream');
/**
* TODO: add class description.
* @type {RejectionStream}
* @extends {Writable}
*/
module.exports = class RejectionStream extends Writable {
/**
* Constructor function for the RejectionStream responsible for wrapping a
* TransportStream; only allowing writes of `info` objects with
* `info.rejection` set to true.
* @param {!TransportStream} transport - Stream to filter to rejections
*/
constructor(transport) {
super({ objectMode: true });
if (!transport) {
throw new Error('RejectionStream requires a TransportStream instance.');
}
this.handleRejections = true;
this.transport = transport;
}
/**
* Writes the info object to our transport instance if (and only if) the
* `rejection` property is set on the info.
* @param {mixed} info - TODO: add param description.
* @param {mixed} enc - TODO: add param description.
* @param {mixed} callback - TODO: add param description.
* @returns {mixed} - TODO: add return description.
* @private
*/
_write(info, enc, callback) {
if (info.rejection) {
return this.transport.log(info, callback);
}
callback();
return true;
}
};

124
node_modules/winston/lib/winston/tail-file.js generated vendored Normal file
View file

@ -0,0 +1,124 @@
/**
* tail-file.js: TODO: add file header description.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const fs = require('fs');
const { StringDecoder } = require('string_decoder');
const { Stream } = require('readable-stream');
/**
* Simple no-op function.
* @returns {undefined}
*/
function noop() {}
/**
* TODO: add function description.
* @param {Object} options - Options for tail.
* @param {function} iter - Iterator function to execute on every line.
* `tail -f` a file. Options must include file.
* @returns {mixed} - TODO: add return description.
*/
module.exports = (options, iter) => {
const buffer = Buffer.alloc(64 * 1024);
const decode = new StringDecoder('utf8');
const stream = new Stream();
let buff = '';
let pos = 0;
let row = 0;
if (options.start === -1) {
delete options.start;
}
stream.readable = true;
stream.destroy = () => {
stream.destroyed = true;
stream.emit('end');
stream.emit('close');
};
fs.open(options.file, 'a+', '0644', (err, fd) => {
if (err) {
if (!iter) {
stream.emit('error', err);
} else {
iter(err);
}
stream.destroy();
return;
}
(function read() {
if (stream.destroyed) {
fs.close(fd, noop);
return;
}
return fs.read(fd, buffer, 0, buffer.length, pos, (error, bytes) => {
if (error) {
if (!iter) {
stream.emit('error', error);
} else {
iter(error);
}
stream.destroy();
return;
}
if (!bytes) {
if (buff) {
// eslint-disable-next-line eqeqeq
if (options.start == null || row > options.start) {
if (!iter) {
stream.emit('line', buff);
} else {
iter(null, buff);
}
}
row++;
buff = '';
}
return setTimeout(read, 1000);
}
let data = decode.write(buffer.slice(0, bytes));
if (!iter) {
stream.emit('data', data);
}
data = (buff + data).split(/\n+/);
const l = data.length - 1;
let i = 0;
for (; i < l; i++) {
// eslint-disable-next-line eqeqeq
if (options.start == null || row > options.start) {
if (!iter) {
stream.emit('line', data[i]);
} else {
iter(null, data[i]);
}
}
row++;
}
buff = data[l];
pos += bytes;
return read();
});
}());
});
if (!iter) {
return stream;
}
return stream.destroy;
};

125
node_modules/winston/lib/winston/transports/console.js generated vendored Normal file
View file

@ -0,0 +1,125 @@
/* eslint-disable no-console */
/*
* console.js: Transport for outputting to the console.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const os = require('os');
const { LEVEL, MESSAGE } = require('triple-beam');
const TransportStream = require('winston-transport');
/**
* Transport for outputting to the console.
* @type {Console}
* @extends {TransportStream}
*/
module.exports = class Console extends TransportStream {
/**
* Constructor function for the Console transport object responsible for
* persisting log messages and metadata to a terminal or TTY.
* @param {!Object} [options={}] - Options for this instance.
*/
constructor(options = {}) {
super(options);
// Expose the name of this Transport on the prototype
this.name = options.name || 'console';
this.stderrLevels = this._stringArrayToSet(options.stderrLevels);
this.consoleWarnLevels = this._stringArrayToSet(options.consoleWarnLevels);
this.eol = typeof options.eol === 'string' ? options.eol : os.EOL;
this.forceConsole = options.forceConsole || false;
// Keep a reference to the log, warn, and error console methods
// in case they get redirected to this transport after the logger is
// instantiated. This prevents a circular reference issue.
this._consoleLog = console.log.bind(console);
this._consoleWarn = console.warn.bind(console);
this._consoleError = console.error.bind(console);
this.setMaxListeners(30);
}
/**
* Core logging method exposed to Winston.
* @param {Object} info - TODO: add param description.
* @param {Function} callback - TODO: add param description.
* @returns {undefined}
*/
log(info, callback) {
setImmediate(() => this.emit('logged', info));
// Remark: what if there is no raw...?
if (this.stderrLevels[info[LEVEL]]) {
if (console._stderr && !this.forceConsole) {
// Node.js maps `process.stderr` to `console._stderr`.
console._stderr.write(`${info[MESSAGE]}${this.eol}`);
} else {
// console.error adds a newline
this._consoleError(info[MESSAGE]);
}
if (callback) {
callback(); // eslint-disable-line callback-return
}
return;
} else if (this.consoleWarnLevels[info[LEVEL]]) {
if (console._stderr && !this.forceConsole) {
// Node.js maps `process.stderr` to `console._stderr`.
// in Node.js console.warn is an alias for console.error
console._stderr.write(`${info[MESSAGE]}${this.eol}`);
} else {
// console.warn adds a newline
this._consoleWarn(info[MESSAGE]);
}
if (callback) {
callback(); // eslint-disable-line callback-return
}
return;
}
if (console._stdout && !this.forceConsole) {
// Node.js maps `process.stdout` to `console._stdout`.
console._stdout.write(`${info[MESSAGE]}${this.eol}`);
} else {
// console.log adds a newline.
this._consoleLog(info[MESSAGE]);
}
if (callback) {
callback(); // eslint-disable-line callback-return
}
}
/**
* Returns a Set-like object with strArray's elements as keys (each with the
* value true).
* @param {Array} strArray - Array of Set-elements as strings.
* @param {?string} [errMsg] - Custom error message thrown on invalid input.
* @returns {Object} - TODO: add return description.
* @private
*/
_stringArrayToSet(strArray, errMsg) {
if (!strArray) return {};
errMsg =
errMsg || 'Cannot make set from type other than Array of string elements';
if (!Array.isArray(strArray)) {
throw new Error(errMsg);
}
return strArray.reduce((set, el) => {
if (typeof el !== 'string') {
throw new Error(errMsg);
}
set[el] = true;
return set;
}, {});
}
};

763
node_modules/winston/lib/winston/transports/file.js generated vendored Normal file
View file

@ -0,0 +1,763 @@
/* eslint-disable complexity,max-statements */
/**
* file.js: Transport for outputting to a local log file.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const fs = require('fs');
const path = require('path');
const asyncSeries = require('async/series');
const zlib = require('zlib');
const { MESSAGE } = require('triple-beam');
const { Stream, PassThrough } = require('readable-stream');
const TransportStream = require('winston-transport');
const debug = require('@dabh/diagnostics')('winston:file');
const os = require('os');
const tailFile = require('../tail-file');
/**
* Transport for outputting to a local log file.
* @type {File}
* @extends {TransportStream}
*/
module.exports = class File extends TransportStream {
/**
* Constructor function for the File transport object responsible for
* persisting log messages and metadata to one or more files.
* @param {Object} options - Options for this instance.
*/
constructor(options = {}) {
super(options);
// Expose the name of this Transport on the prototype.
this.name = options.name || 'file';
// Helper function which throws an `Error` in the event that any of the
// rest of the arguments is present in `options`.
function throwIf(target, ...args) {
args.slice(1).forEach(name => {
if (options[name]) {
throw new Error(`Cannot set ${name} and ${target} together`);
}
});
}
// Setup the base stream that always gets piped to to handle buffering.
this._stream = new PassThrough();
this._stream.setMaxListeners(30);
// Bind this context for listener methods.
this._onError = this._onError.bind(this);
if (options.filename || options.dirname) {
throwIf('filename or dirname', 'stream');
this._basename = this.filename = options.filename
? path.basename(options.filename)
: 'winston.log';
this.dirname = options.dirname || path.dirname(options.filename);
this.options = options.options || { flags: 'a' };
} else if (options.stream) {
// eslint-disable-next-line no-console
console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream');
throwIf('stream', 'filename', 'maxsize');
this._dest = this._stream.pipe(this._setupStream(options.stream));
this.dirname = path.dirname(this._dest.path);
// We need to listen for drain events when write() returns false. This
// can make node mad at times.
} else {
throw new Error('Cannot log to file without filename or stream.');
}
this.maxsize = options.maxsize || null;
this.rotationFormat = options.rotationFormat || false;
this.zippedArchive = options.zippedArchive || false;
this.maxFiles = options.maxFiles || null;
this.eol = (typeof options.eol === 'string') ? options.eol : os.EOL;
this.tailable = options.tailable || false;
this.lazy = options.lazy || false;
// Internal state variables representing the number of files this instance
// has created and the current size (in bytes) of the current logfile.
this._size = 0;
this._pendingSize = 0;
this._created = 0;
this._drain = false;
this._opening = false;
this._ending = false;
this._fileExist = false;
if (this.dirname) this._createLogDirIfNotExist(this.dirname);
if (!this.lazy) this.open();
}
finishIfEnding() {
if (this._ending) {
if (this._opening) {
this.once('open', () => {
this._stream.once('finish', () => this.emit('finish'));
setImmediate(() => this._stream.end());
});
} else {
this._stream.once('finish', () => this.emit('finish'));
setImmediate(() => this._stream.end());
}
}
}
/**
* Core logging method exposed to Winston. Metadata is optional.
* @param {Object} info - TODO: add param description.
* @param {Function} callback - TODO: add param description.
* @returns {undefined}
*/
log(info, callback = () => { }) {
// Remark: (jcrugzz) What is necessary about this callback(null, true) now
// when thinking about 3.x? Should silent be handled in the base
// TransportStream _write method?
if (this.silent) {
callback();
return true;
}
// Output stream buffer is full and has asked us to wait for the drain event
if (this._drain) {
this._stream.once('drain', () => {
this._drain = false;
this.log(info, callback);
});
return;
}
if (this._rotate) {
this._stream.once('rotate', () => {
this._rotate = false;
this.log(info, callback);
});
return;
}
if (this.lazy) {
if (!this._fileExist) {
if (!this._opening) {
this.open();
}
this.once('open', () => {
this._fileExist = true;
this.log(info, callback);
return;
});
return;
}
if (this._needsNewFile(this._pendingSize)) {
this._dest.once('close', () => {
if (!this._opening) {
this.open();
}
this.once('open', () => {
this.log(info, callback);
return;
});
return;
});
return;
}
}
// Grab the raw string and append the expected EOL.
const output = `${info[MESSAGE]}${this.eol}`;
const bytes = Buffer.byteLength(output);
// After we have written to the PassThrough check to see if we need
// to rotate to the next file.
//
// Remark: This gets called too early and does not depict when data
// has been actually flushed to disk.
function logged() {
this._size += bytes;
this._pendingSize -= bytes;
debug('logged %s %s', this._size, output);
this.emit('logged', info);
// Do not attempt to rotate files while rotating
if (this._rotate) {
return;
}
// Do not attempt to rotate files while opening
if (this._opening) {
return;
}
// Check to see if we need to end the stream and create a new one.
if (!this._needsNewFile()) {
return;
}
if (this.lazy) {
this._endStream(() => {this.emit('fileclosed');});
return;
}
// End the current stream, ensure it flushes and create a new one.
// This could potentially be optimized to not run a stat call but its
// the safest way since we are supporting `maxFiles`.
this._rotate = true;
this._endStream(() => this._rotateFile());
}
// Keep track of the pending bytes being written while files are opening
// in order to properly rotate the PassThrough this._stream when the file
// eventually does open.
this._pendingSize += bytes;
if (this._opening
&& !this.rotatedWhileOpening
&& this._needsNewFile(this._size + this._pendingSize)) {
this.rotatedWhileOpening = true;
}
const written = this._stream.write(output, logged.bind(this));
if (!written) {
this._drain = true;
this._stream.once('drain', () => {
this._drain = false;
callback();
});
} else {
callback(); // eslint-disable-line callback-return
}
debug('written', written, this._drain);
this.finishIfEnding();
return written;
}
/**
* Query the transport. Options object is optional.
* @param {Object} options - Loggly-like query options for this instance.
* @param {function} callback - Continuation to respond to when complete.
* TODO: Refactor me.
*/
query(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = normalizeQuery(options);
const file = path.join(this.dirname, this.filename);
let buff = '';
let results = [];
let row = 0;
const stream = fs.createReadStream(file, {
encoding: 'utf8'
});
stream.on('error', err => {
if (stream.readable) {
stream.destroy();
}
if (!callback) {
return;
}
return err.code !== 'ENOENT' ? callback(err) : callback(null, results);
});
stream.on('data', data => {
data = (buff + data).split(/\n+/);
const l = data.length - 1;
let i = 0;
for (; i < l; i++) {
if (!options.start || row >= options.start) {
add(data[i]);
}
row++;
}
buff = data[l];
});
stream.on('close', () => {
if (buff) {
add(buff, true);
}
if (options.order === 'desc') {
results = results.reverse();
}
// eslint-disable-next-line callback-return
if (callback) callback(null, results);
});
function add(buff, attempt) {
try {
const log = JSON.parse(buff);
if (check(log)) {
push(log);
}
} catch (e) {
if (!attempt) {
stream.emit('error', e);
}
}
}
function push(log) {
if (
options.rows &&
results.length >= options.rows &&
options.order !== 'desc'
) {
if (stream.readable) {
stream.destroy();
}
return;
}
if (options.fields) {
log = options.fields.reduce((obj, key) => {
obj[key] = log[key];
return obj;
}, {});
}
if (options.order === 'desc') {
if (results.length >= options.rows) {
results.shift();
}
}
results.push(log);
}
function check(log) {
if (!log) {
return;
}
if (typeof log !== 'object') {
return;
}
const time = new Date(log.timestamp);
if (
(options.from && time < options.from) ||
(options.until && time > options.until) ||
(options.level && options.level !== log.level)
) {
return;
}
return true;
}
function normalizeQuery(options) {
options = options || {};
// limit
options.rows = options.rows || options.limit || 10;
// starting row offset
options.start = options.start || 0;
// now
options.until = options.until || new Date();
if (typeof options.until !== 'object') {
options.until = new Date(options.until);
}
// now - 24
options.from = options.from || (options.until - (24 * 60 * 60 * 1000));
if (typeof options.from !== 'object') {
options.from = new Date(options.from);
}
// 'asc' or 'desc'
options.order = options.order || 'desc';
return options;
}
}
/**
* Returns a log stream for this transport. Options object is optional.
* @param {Object} options - Stream options for this instance.
* @returns {Stream} - TODO: add return description.
* TODO: Refactor me.
*/
stream(options = {}) {
const file = path.join(this.dirname, this.filename);
const stream = new Stream();
const tail = {
file,
start: options.start
};
stream.destroy = tailFile(tail, (err, line) => {
if (err) {
return stream.emit('error', err);
}
try {
stream.emit('data', line);
line = JSON.parse(line);
stream.emit('log', line);
} catch (e) {
stream.emit('error', e);
}
});
return stream;
}
/**
* Checks to see the filesize of.
* @returns {undefined}
*/
open() {
// If we do not have a filename then we were passed a stream and
// don't need to keep track of size.
if (!this.filename) return;
if (this._opening) return;
this._opening = true;
// Stat the target file to get the size and create the stream.
this.stat((err, size) => {
if (err) {
return this.emit('error', err);
}
debug('stat done: %s { size: %s }', this.filename, size);
this._size = size;
this._dest = this._createStream(this._stream);
this._opening = false;
this.once('open', () => {
if (!this._stream.emit('rotate')) {
this._rotate = false;
}
});
});
}
/**
* Stat the file and assess information in order to create the proper stream.
* @param {function} callback - TODO: add param description.
* @returns {undefined}
*/
stat(callback) {
const target = this._getFile();
const fullpath = path.join(this.dirname, target);
fs.stat(fullpath, (err, stat) => {
if (err && err.code === 'ENOENT') {
debug('ENOENT ok', fullpath);
// Update internally tracked filename with the new target name.
this.filename = target;
return callback(null, 0);
}
if (err) {
debug(`err ${err.code} ${fullpath}`);
return callback(err);
}
if (!stat || this._needsNewFile(stat.size)) {
// If `stats.size` is greater than the `maxsize` for this
// instance then try again.
return this._incFile(() => this.stat(callback));
}
// Once we have figured out what the filename is, set it
// and return the size.
this.filename = target;
callback(null, stat.size);
});
}
/**
* Closes the stream associated with this instance.
* @param {function} cb - TODO: add param description.
* @returns {undefined}
*/
close(cb) {
if (!this._stream) {
return;
}
this._stream.end(() => {
if (cb) {
cb(); // eslint-disable-line callback-return
}
this.emit('flush');
this.emit('closed');
});
}
/**
* TODO: add method description.
* @param {number} size - TODO: add param description.
* @returns {undefined}
*/
_needsNewFile(size) {
size = size || this._size;
return this.maxsize && size >= this.maxsize;
}
/**
* TODO: add method description.
* @param {Error} err - TODO: add param description.
* @returns {undefined}
*/
_onError(err) {
this.emit('error', err);
}
/**
* TODO: add method description.
* @param {Stream} stream - TODO: add param description.
* @returns {mixed} - TODO: add return description.
*/
_setupStream(stream) {
stream.on('error', this._onError);
return stream;
}
/**
* TODO: add method description.
* @param {Stream} stream - TODO: add param description.
* @returns {mixed} - TODO: add return description.
*/
_cleanupStream(stream) {
stream.removeListener('error', this._onError);
stream.destroy();
return stream;
}
/**
* TODO: add method description.
*/
_rotateFile() {
this._incFile(() => this.open());
}
/**
* Unpipe from the stream that has been marked as full and end it so it
* flushes to disk.
*
* @param {function} callback - Callback for when the current file has closed.
* @private
*/
_endStream(callback = () => { }) {
if (this._dest) {
this._stream.unpipe(this._dest);
this._dest.end(() => {
this._cleanupStream(this._dest);
callback();
});
} else {
callback(); // eslint-disable-line callback-return
}
}
/**
* Returns the WritableStream for the active file on this instance. If we
* should gzip the file then a zlib stream is returned.
*
* @param {ReadableStream} source PassThrough to pipe to the file when open.
* @returns {WritableStream} Stream that writes to disk for the active file.
*/
_createStream(source) {
const fullpath = path.join(this.dirname, this.filename);
debug('create stream start', fullpath, this.options);
const dest = fs.createWriteStream(fullpath, this.options)
// TODO: What should we do with errors here?
.on('error', err => debug(err))
.on('close', () => debug('close', dest.path, dest.bytesWritten))
.on('open', () => {
debug('file open ok', fullpath);
this.emit('open', fullpath);
source.pipe(dest);
// If rotation occured during the open operation then we immediately
// start writing to a new PassThrough, begin opening the next file
// and cleanup the previous source and dest once the source has drained.
if (this.rotatedWhileOpening) {
this._stream = new PassThrough();
this._stream.setMaxListeners(30);
this._rotateFile();
this.rotatedWhileOpening = false;
this._cleanupStream(dest);
source.end();
}
});
debug('create stream ok', fullpath);
return dest;
}
/**
* TODO: add method description.
* @param {function} callback - TODO: add param description.
* @returns {undefined}
*/
_incFile(callback) {
debug('_incFile', this.filename);
const ext = path.extname(this._basename);
const basename = path.basename(this._basename, ext);
const tasks = [];
if (this.zippedArchive) {
tasks.push(
function (cb) {
const num = this._created > 0 && !this.tailable ? this._created : '';
this._compressFile(
path.join(this.dirname, `${basename}${num}${ext}`),
path.join(this.dirname, `${basename}${num}${ext}.gz`),
cb
);
}.bind(this)
);
}
tasks.push(
function (cb) {
if (!this.tailable) {
this._created += 1;
this._checkMaxFilesIncrementing(ext, basename, cb);
} else {
this._checkMaxFilesTailable(ext, basename, cb);
}
}.bind(this)
);
asyncSeries(tasks, callback);
}
/**
* Gets the next filename to use for this instance in the case that log
* filesizes are being capped.
* @returns {string} - TODO: add return description.
* @private
*/
_getFile() {
const ext = path.extname(this._basename);
const basename = path.basename(this._basename, ext);
const isRotation = this.rotationFormat
? this.rotationFormat()
: this._created;
// Caveat emptor (indexzero): rotationFormat() was broken by design When
// combined with max files because the set of files to unlink is never
// stored.
return !this.tailable && this._created
? `${basename}${isRotation}${ext}`
: `${basename}${ext}`;
}
/**
* Increment the number of files created or checked by this instance.
* @param {mixed} ext - TODO: add param description.
* @param {mixed} basename - TODO: add param description.
* @param {mixed} callback - TODO: add param description.
* @returns {undefined}
* @private
*/
_checkMaxFilesIncrementing(ext, basename, callback) {
// Check for maxFiles option and delete file.
if (!this.maxFiles || this._created < this.maxFiles) {
return setImmediate(callback);
}
const oldest = this._created - this.maxFiles;
const isOldest = oldest !== 0 ? oldest : '';
const isZipped = this.zippedArchive ? '.gz' : '';
const filePath = `${basename}${isOldest}${ext}${isZipped}`;
const target = path.join(this.dirname, filePath);
fs.unlink(target, callback);
}
/**
* Roll files forward based on integer, up to maxFiles. e.g. if base if
* file.log and it becomes oversized, roll to file1.log, and allow file.log
* to be re-used. If file is oversized again, roll file1.log to file2.log,
* roll file.log to file1.log, and so on.
* @param {mixed} ext - TODO: add param description.
* @param {mixed} basename - TODO: add param description.
* @param {mixed} callback - TODO: add param description.
* @returns {undefined}
* @private
*/
_checkMaxFilesTailable(ext, basename, callback) {
const tasks = [];
if (!this.maxFiles) {
return;
}
// const isZipped = this.zippedArchive ? '.gz' : '';
const isZipped = this.zippedArchive ? '.gz' : '';
for (let x = this.maxFiles - 1; x > 1; x--) {
tasks.push(function (i, cb) {
let fileName = `${basename}${(i - 1)}${ext}${isZipped}`;
const tmppath = path.join(this.dirname, fileName);
fs.exists(tmppath, exists => {
if (!exists) {
return cb(null);
}
fileName = `${basename}${i}${ext}${isZipped}`;
fs.rename(tmppath, path.join(this.dirname, fileName), cb);
});
}.bind(this, x));
}
asyncSeries(tasks, () => {
fs.rename(
path.join(this.dirname, `${basename}${ext}${isZipped}`),
path.join(this.dirname, `${basename}1${ext}${isZipped}`),
callback
);
});
}
/**
* Compresses src to dest with gzip and unlinks src
* @param {string} src - path to source file.
* @param {string} dest - path to zipped destination file.
* @param {Function} callback - callback called after file has been compressed.
* @returns {undefined}
* @private
*/
_compressFile(src, dest, callback) {
fs.access(src, fs.F_OK, (err) => {
if (err) {
return callback();
}
var gzip = zlib.createGzip();
var inp = fs.createReadStream(src);
var out = fs.createWriteStream(dest);
out.on('finish', () => {
fs.unlink(src, callback);
});
inp.pipe(gzip).pipe(out);
});
}
_createLogDirIfNotExist(dirPath) {
/* eslint-disable no-sync */
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
/* eslint-enable no-sync */
}
};

262
node_modules/winston/lib/winston/transports/http.js generated vendored Normal file
View file

@ -0,0 +1,262 @@
/**
* http.js: Transport for outputting to a json-rpcserver.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const http = require('http');
const https = require('https');
const { Stream } = require('readable-stream');
const TransportStream = require('winston-transport');
const { configure } = require('safe-stable-stringify');
/**
* Transport for outputting to a json-rpc server.
* @type {Stream}
* @extends {TransportStream}
*/
module.exports = class Http extends TransportStream {
/**
* Constructor function for the Http transport object responsible for
* persisting log messages and metadata to a terminal or TTY.
* @param {!Object} [options={}] - Options for this instance.
*/
// eslint-disable-next-line max-statements
constructor(options = {}) {
super(options);
this.options = options;
this.name = options.name || 'http';
this.ssl = !!options.ssl;
this.host = options.host || 'localhost';
this.port = options.port;
this.auth = options.auth;
this.path = options.path || '';
this.maximumDepth = options.maximumDepth;
this.agent = options.agent;
this.headers = options.headers || {};
this.headers['content-type'] = 'application/json';
this.batch = options.batch || false;
this.batchInterval = options.batchInterval || 5000;
this.batchCount = options.batchCount || 10;
this.batchOptions = [];
this.batchTimeoutID = -1;
this.batchCallback = {};
if (!this.port) {
this.port = this.ssl ? 443 : 80;
}
}
/**
* Core logging method exposed to Winston.
* @param {Object} info - TODO: add param description.
* @param {function} callback - TODO: add param description.
* @returns {undefined}
*/
log(info, callback) {
this._request(info, null, null, (err, res) => {
if (res && res.statusCode !== 200) {
err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);
}
if (err) {
this.emit('warn', err);
} else {
this.emit('logged', info);
}
});
// Remark: (jcrugzz) Fire and forget here so requests dont cause buffering
// and block more requests from happening?
if (callback) {
setImmediate(callback);
}
}
/**
* Query the transport. Options object is optional.
* @param {Object} options - Loggly-like query options for this instance.
* @param {function} callback - Continuation to respond to when complete.
* @returns {undefined}
*/
query(options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = {
method: 'query',
params: this.normalizeQuery(options)
};
const auth = options.params.auth || null;
delete options.params.auth;
const path = options.params.path || null;
delete options.params.path;
this._request(options, auth, path, (err, res, body) => {
if (res && res.statusCode !== 200) {
err = new Error(`Invalid HTTP Status Code: ${res.statusCode}`);
}
if (err) {
return callback(err);
}
if (typeof body === 'string') {
try {
body = JSON.parse(body);
} catch (e) {
return callback(e);
}
}
callback(null, body);
});
}
/**
* Returns a log stream for this transport. Options object is optional.
* @param {Object} options - Stream options for this instance.
* @returns {Stream} - TODO: add return description
*/
stream(options = {}) {
const stream = new Stream();
options = {
method: 'stream',
params: options
};
const path = options.params.path || null;
delete options.params.path;
const auth = options.params.auth || null;
delete options.params.auth;
let buff = '';
const req = this._request(options, auth, path);
stream.destroy = () => req.destroy();
req.on('data', data => {
data = (buff + data).split(/\n+/);
const l = data.length - 1;
let i = 0;
for (; i < l; i++) {
try {
stream.emit('log', JSON.parse(data[i]));
} catch (e) {
stream.emit('error', e);
}
}
buff = data[l];
});
req.on('error', err => stream.emit('error', err));
return stream;
}
/**
* Make a request to a winstond server or any http server which can
* handle json-rpc.
* @param {function} options - Options to sent the request.
* @param {Object?} auth - authentication options
* @param {string} path - request path
* @param {function} callback - Continuation to respond to when complete.
*/
_request(options, auth, path, callback) {
options = options || {};
auth = auth || this.auth;
path = path || this.path || '';
if (this.batch) {
this._doBatch(options, callback, auth, path);
} else {
this._doRequest(options, callback, auth, path);
}
}
/**
* Send or memorize the options according to batch configuration
* @param {function} options - Options to sent the request.
* @param {function} callback - Continuation to respond to when complete.
* @param {Object?} auth - authentication options
* @param {string} path - request path
*/
_doBatch(options, callback, auth, path) {
this.batchOptions.push(options);
if (this.batchOptions.length === 1) {
// First message stored, it's time to start the timeout!
const me = this;
this.batchCallback = callback;
this.batchTimeoutID = setTimeout(function () {
// timeout is reached, send all messages to endpoint
me.batchTimeoutID = -1;
me._doBatchRequest(me.batchCallback, auth, path);
}, this.batchInterval);
}
if (this.batchOptions.length === this.batchCount) {
// max batch count is reached, send all messages to endpoint
this._doBatchRequest(this.batchCallback, auth, path);
}
}
/**
* Initiate a request with the memorized batch options, stop the batch timeout
* @param {function} callback - Continuation to respond to when complete.
* @param {Object?} auth - authentication options
* @param {string} path - request path
*/
_doBatchRequest(callback, auth, path) {
if (this.batchTimeoutID > 0) {
clearTimeout(this.batchTimeoutID);
this.batchTimeoutID = -1;
}
const batchOptionsCopy = this.batchOptions.slice();
this.batchOptions = [];
this._doRequest(batchOptionsCopy, callback, auth, path);
}
/**
* Make a request to a winstond server or any http server which can
* handle json-rpc.
* @param {function} options - Options to sent the request.
* @param {function} callback - Continuation to respond to when complete.
* @param {Object?} auth - authentication options
* @param {string} path - request path
*/
_doRequest(options, callback, auth, path) {
// Prepare options for outgoing HTTP request
const headers = Object.assign({}, this.headers);
if (auth && auth.bearer) {
headers.Authorization = `Bearer ${auth.bearer}`;
}
const req = (this.ssl ? https : http).request({
...this.options,
method: 'POST',
host: this.host,
port: this.port,
path: `/${path.replace(/^\//, '')}`,
headers: headers,
auth: (auth && auth.username && auth.password) ? (`${auth.username}:${auth.password}`) : '',
agent: this.agent
});
req.on('error', callback);
req.on('response', res => (
res.on('end', () => callback(null, res)).resume()
));
const jsonStringify = configure({
...(this.maximumDepth && { maximumDepth: this.maximumDepth })
});
req.end(Buffer.from(jsonStringify(options, this.options.replacer), 'utf8'));
}
};

117
node_modules/winston/lib/winston/transports/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,117 @@
// Type definitions for winston 3.0
// Project: https://github.com/winstonjs/winston
/// <reference types="node" />
import { Agent } from 'http';
import * as Transport from 'winston-transport';
declare namespace winston {
interface ConsoleTransportOptions extends Transport.TransportStreamOptions {
consoleWarnLevels?: string[];
stderrLevels?: string[];
debugStdout?: boolean;
eol?: string;
forceConsole?: boolean;
}
interface ConsoleTransportInstance extends Transport {
name: string;
stderrLevels: string[];
eol: string;
new (options?: ConsoleTransportOptions): ConsoleTransportInstance;
}
interface FileTransportOptions extends Transport.TransportStreamOptions {
filename?: string;
dirname?: string;
options?: object;
maxsize?: number;
stream?: NodeJS.WritableStream;
rotationFormat?: Function;
zippedArchive?: boolean;
maxFiles?: number;
eol?: string;
tailable?: boolean;
lazy?: boolean;
}
interface FileTransportInstance extends Transport {
name: string;
filename: string;
dirname: string;
options: object;
maxsize: number | null;
rotationFormat: Function | boolean;
zippedArchive: boolean;
maxFiles: number | null;
eol: string;
tailable: boolean;
lazy: boolean;
new (options?: FileTransportOptions): FileTransportInstance;
}
interface HttpTransportOptions extends Transport.TransportStreamOptions {
ssl?: any;
host?: string;
port?: number;
auth?: {
username?: string | undefined;
password?: string | undefined;
bearer?: string | undefined;
};
path?: string;
agent?: Agent;
headers?: object;
batch?: boolean;
batchInterval?: number;
batchCount?: number;
replacer?: (key: string, value: any) => any;
maximumDepth?: number;
}
interface HttpTransportInstance extends Transport {
name: string;
ssl: boolean;
host: string;
maximumDepth: number;
port: number;
auth?: {
username?: string | undefined;
password?: string | undefined;
bearer?: string | undefined;
};
path: string;
agent?: Agent | null;
new (options?: HttpTransportOptions): HttpTransportInstance;
}
interface StreamTransportOptions extends Transport.TransportStreamOptions {
stream: NodeJS.WritableStream;
eol?: string;
}
interface StreamTransportInstance extends Transport {
eol: string;
new (options?: StreamTransportOptions): StreamTransportInstance;
}
interface Transports {
FileTransportOptions: FileTransportOptions;
File: FileTransportInstance;
ConsoleTransportOptions: ConsoleTransportOptions;
Console: ConsoleTransportInstance;
HttpTransportOptions: HttpTransportOptions;
Http: HttpTransportInstance;
StreamTransportOptions: StreamTransportOptions;
Stream: StreamTransportInstance;
}
}
declare const winston: winston.Transports;
export = winston;

56
node_modules/winston/lib/winston/transports/index.js generated vendored Normal file
View file

@ -0,0 +1,56 @@
/**
* transports.js: Set of all transports Winston knows about.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
/**
* TODO: add property description.
* @type {Console}
*/
Object.defineProperty(exports, 'Console', {
configurable: true,
enumerable: true,
get() {
return require('./console');
}
});
/**
* TODO: add property description.
* @type {File}
*/
Object.defineProperty(exports, 'File', {
configurable: true,
enumerable: true,
get() {
return require('./file');
}
});
/**
* TODO: add property description.
* @type {Http}
*/
Object.defineProperty(exports, 'Http', {
configurable: true,
enumerable: true,
get() {
return require('./http');
}
});
/**
* TODO: add property description.
* @type {Stream}
*/
Object.defineProperty(exports, 'Stream', {
configurable: true,
enumerable: true,
get() {
return require('./stream');
}
});

63
node_modules/winston/lib/winston/transports/stream.js generated vendored Normal file
View file

@ -0,0 +1,63 @@
/**
* stream.js: Transport for outputting to any arbitrary stream.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const isStream = require('is-stream');
const { MESSAGE } = require('triple-beam');
const os = require('os');
const TransportStream = require('winston-transport');
/**
* Transport for outputting to any arbitrary stream.
* @type {Stream}
* @extends {TransportStream}
*/
module.exports = class Stream extends TransportStream {
/**
* Constructor function for the Console transport object responsible for
* persisting log messages and metadata to a terminal or TTY.
* @param {!Object} [options={}] - Options for this instance.
*/
constructor(options = {}) {
super(options);
if (!options.stream || !isStream(options.stream)) {
throw new Error('options.stream is required.');
}
// We need to listen for drain events when write() returns false. This can
// make node mad at times.
this._stream = options.stream;
this._stream.setMaxListeners(Infinity);
this.isObjectMode = options.stream._writableState.objectMode;
this.eol = (typeof options.eol === 'string') ? options.eol : os.EOL;
}
/**
* Core logging method exposed to Winston.
* @param {Object} info - TODO: add param description.
* @param {Function} callback - TODO: add param description.
* @returns {undefined}
*/
log(info, callback) {
setImmediate(() => this.emit('logged', info));
if (this.isObjectMode) {
this._stream.write(info);
if (callback) {
callback(); // eslint-disable-line callback-return
}
return;
}
this._stream.write(`${info[MESSAGE]}${this.eol}`);
if (callback) {
callback(); // eslint-disable-line callback-return
}
return;
}
};

View file

@ -0,0 +1,26 @@
MIT License
Original Library
- Copyright (c) Marak Squires
Additional Functionality
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
- Copyright (c) DABH (https://github.com/DABH)
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,219 @@
# @colors/colors ("colors.js")
[![Build Status](https://github.com/DABH/colors.js/actions/workflows/ci.yml/badge.svg)](https://github.com/DABH/colors.js/actions/workflows/ci.yml)
[![version](https://img.shields.io/npm/v/@colors/colors.svg)](https://www.npmjs.org/package/@colors/colors)
Please check out the [roadmap](ROADMAP.md) for upcoming features and releases. Please open Issues to provide feedback.
## get color and style in your node.js console
![Demo](https://raw.githubusercontent.com/DABH/colors.js/master/screenshots/colors.png)
## Installation
npm install @colors/colors
## colors and styles!
### text colors
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- white
- gray
- grey
### bright text colors
- brightRed
- brightGreen
- brightYellow
- brightBlue
- brightMagenta
- brightCyan
- brightWhite
### background colors
- bgBlack
- bgRed
- bgGreen
- bgYellow
- bgBlue
- bgMagenta
- bgCyan
- bgWhite
- bgGray
- bgGrey
### bright background colors
- bgBrightRed
- bgBrightGreen
- bgBrightYellow
- bgBrightBlue
- bgBrightMagenta
- bgBrightCyan
- bgBrightWhite
### styles
- reset
- bold
- dim
- italic
- underline
- inverse
- hidden
- strikethrough
### extras
- rainbow
- zebra
- america
- trap
- random
## Usage
By popular demand, `@colors/colors` now ships with two types of usages!
The super nifty way
```js
var colors = require('@colors/colors');
console.log('hello'.green); // outputs green text
console.log('i like cake and pies'.underline.red); // outputs red underlined text
console.log('inverse the color'.inverse); // inverses the color
console.log('OMG Rainbows!'.rainbow); // rainbow
console.log('Run the trap'.trap); // Drops the bass
```
or a slightly less nifty way which doesn't extend `String.prototype`
```js
var colors = require('@colors/colors/safe');
console.log(colors.green('hello')); // outputs green text
console.log(colors.red.underline('i like cake and pies')); // outputs red underlined text
console.log(colors.inverse('inverse the color')); // inverses the color
console.log(colors.rainbow('OMG Rainbows!')); // rainbow
console.log(colors.trap('Run the trap')); // Drops the bass
```
I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way.
If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object.
## Enabling/Disabling Colors
The package will auto-detect whether your terminal can use colors and enable/disable accordingly. When colors are disabled, the color functions do nothing. You can override this with a command-line flag:
```bash
node myapp.js --no-color
node myapp.js --color=false
node myapp.js --color
node myapp.js --color=true
node myapp.js --color=always
FORCE_COLOR=1 node myapp.js
```
Or in code:
```javascript
var colors = require('@colors/colors');
colors.enable();
colors.disable();
```
## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data)
```js
var name = 'Beowulf';
console.log(colors.green('Hello %s'), name);
// outputs -> 'Hello Beowulf'
```
## Custom themes
### Using standard API
```js
var colors = require('@colors/colors');
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
```
### Using string safe API
```js
var colors = require('@colors/colors/safe');
// set single property
var error = colors.red;
error('this is red');
// set theme
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log(colors.error("this is an error"));
// outputs yellow text
console.log(colors.warn("this is a warning"));
```
### Combining Colors
```javascript
var colors = require('@colors/colors');
colors.setTheme({
custom: ['red', 'underline']
});
console.log('test'.custom);
```
*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.*

View file

@ -0,0 +1,83 @@
var colors = require('../lib/index');
console.log('First some yellow text'.yellow);
console.log('Underline that text'.yellow.underline);
console.log('Make it bold and red'.red.bold);
console.log(('Double Raindows All Day Long').rainbow);
console.log('Drop the bass'.trap);
console.log('DROP THE RAINBOW BASS'.trap.rainbow);
// styles not widely supported
console.log('Chains are also cool.'.bold.italic.underline.red);
// styles not widely supported
console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse
+ ' styles! '.yellow.bold);
console.log('Zebras are so fun!'.zebra);
//
// Remark: .strikethrough may not work with Mac OS Terminal App
//
console.log('This is ' + 'not'.strikethrough + ' fun.');
console.log('Background color attack!'.black.bgWhite);
console.log('Use random styles on everything!'.random);
console.log('America, Heck Yeah!'.america);
// eslint-disable-next-line max-len
console.log('Blindingly '.brightCyan + 'bright? '.brightRed + 'Why '.brightYellow + 'not?!'.brightGreen);
console.log('Setting themes is useful');
//
// Custom themes
//
console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red',
});
// outputs red text
console.log('this is an error'.error);
// outputs yellow text
console.log('this is a warning'.warn);
// outputs grey text
console.log('this is an input'.input);
console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
try {
colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));
} catch (err) {
console.log(err);
}
// outputs red text
console.log('this is an error'.error);
// outputs yellow text
console.log('this is a warning'.warn);
// outputs grey text
console.log('this is an input'.input);
// console.log("Don't summon".zalgo)

View file

@ -0,0 +1,80 @@
var colors = require('../safe');
console.log(colors.yellow('First some yellow text'));
console.log(colors.yellow.underline('Underline that text'));
console.log(colors.red.bold('Make it bold and red'));
console.log(colors.rainbow('Double Raindows All Day Long'));
console.log(colors.trap('Drop the bass'));
console.log(colors.rainbow(colors.trap('DROP THE RAINBOW BASS')));
// styles not widely supported
console.log(colors.bold.italic.underline.red('Chains are also cool.'));
// styles not widely supported
console.log(colors.green('So ') + colors.underline('are') + ' '
+ colors.inverse('inverse') + colors.yellow.bold(' styles! '));
console.log(colors.zebra('Zebras are so fun!'));
console.log('This is ' + colors.strikethrough('not') + ' fun.');
console.log(colors.black.bgWhite('Background color attack!'));
console.log(colors.random('Use random styles on everything!'));
console.log(colors.america('America, Heck Yeah!'));
// eslint-disable-next-line max-len
console.log(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!'));
console.log('Setting themes is useful');
//
// Custom themes
//
// console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'blue',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red',
});
// outputs red text
console.log(colors.error('this is an error'));
// outputs yellow text
console.log(colors.warn('this is a warning'));
// outputs blue text
console.log(colors.input('this is an input'));
// console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));
// outputs red text
console.log(colors.error('this is an error'));
// outputs yellow text
console.log(colors.warn('this is a warning'));
// outputs grey text
console.log(colors.input('this is an input'));
// console.log(colors.zalgo("Don't summon him"))

View file

@ -0,0 +1,184 @@
// Type definitions for @colors/colors 1.4+
// Project: https://github.com/Marak/colors.js
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Staffan Eketorp <https://github.com/staeke>
// Definitions: https://github.com/DABH/colors.js
export interface Color {
(text: string): string;
strip: Color;
stripColors: Color;
black: Color;
red: Color;
green: Color;
yellow: Color;
blue: Color;
magenta: Color;
cyan: Color;
white: Color;
gray: Color;
grey: Color;
brightRed: Color;
brightGreen: Color;
brightYellow: Color;
brightBlue: Color;
brightMagenta: Color;
brightCyan: Color;
brightWhite: Color;
bgBlack: Color;
bgRed: Color;
bgGreen: Color;
bgYellow: Color;
bgBlue: Color;
bgMagenta: Color;
bgCyan: Color;
bgWhite: Color;
bgBrightRed: Color;
bgBrightGreen: Color;
bgBrightYellow: Color;
bgBrightBlue: Color;
bgBrightMagenta: Color;
bgBrightCyan: Color;
bgBrightWhite: Color;
reset: Color;
bold: Color;
dim: Color;
italic: Color;
underline: Color;
inverse: Color;
hidden: Color;
strikethrough: Color;
rainbow: Color;
zebra: Color;
america: Color;
trap: Color;
random: Color;
zalgo: Color;
}
export function enable(): void;
export function disable(): void;
export function setTheme(theme: any): void;
export let enabled: boolean;
export const strip: Color;
export const stripColors: Color;
export const black: Color;
export const red: Color;
export const green: Color;
export const yellow: Color;
export const blue: Color;
export const magenta: Color;
export const cyan: Color;
export const white: Color;
export const gray: Color;
export const grey: Color;
export const brightRed: Color;
export const brightGreen: Color;
export const brightYellow: Color;
export const brightBlue: Color;
export const brightMagenta: Color;
export const brightCyan: Color;
export const brightWhite: Color;
export const bgBlack: Color;
export const bgRed: Color;
export const bgGreen: Color;
export const bgYellow: Color;
export const bgBlue: Color;
export const bgMagenta: Color;
export const bgCyan: Color;
export const bgWhite: Color;
export const bgBrightRed: Color;
export const bgBrightGreen: Color;
export const bgBrightYellow: Color;
export const bgBrightBlue: Color;
export const bgBrightMagenta: Color;
export const bgBrightCyan: Color;
export const bgBrightWhite: Color;
export const reset: Color;
export const bold: Color;
export const dim: Color;
export const italic: Color;
export const underline: Color;
export const inverse: Color;
export const hidden: Color;
export const strikethrough: Color;
export const rainbow: Color;
export const zebra: Color;
export const america: Color;
export const trap: Color;
export const random: Color;
export const zalgo: Color;
declare global {
interface String {
strip: string;
stripColors: string;
black: string;
red: string;
green: string;
yellow: string;
blue: string;
magenta: string;
cyan: string;
white: string;
gray: string;
grey: string;
brightRed: string;
brightGreen: string;
brightYellow: string;
brightBlue: string;
brightMagenta: string;
brightCyan: string;
brightWhite: string;
bgBlack: string;
bgRed: string;
bgGreen: string;
bgYellow: string;
bgBlue: string;
bgMagenta: string;
bgCyan: string;
bgWhite: string;
bgBrightRed: string;
bgBrightGreen: string;
bgBrightYellow: string;
bgBrightBlue: string;
bgBrightMagenta: string;
bgBrightCyan: string;
bgBrightWhite: string;
reset: string;
// @ts-ignore
bold: string;
dim: string;
italic: string;
underline: string;
inverse: string;
hidden: string;
strikethrough: string;
rainbow: string;
zebra: string;
america: string;
trap: string;
random: string;
zalgo: string;
}
}

View file

@ -0,0 +1,211 @@
/*
The MIT License (MIT)
Original Library
- Copyright (c) Marak Squires
Additional functionality
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var colors = {};
module['exports'] = colors;
colors.themes = {};
var util = require('util');
var ansiStyles = colors.styles = require('./styles');
var defineProps = Object.defineProperties;
var newLineRegex = new RegExp(/[\r\n]+/g);
colors.supportsColor = require('./system/supports-colors').supportsColor;
if (typeof colors.enabled === 'undefined') {
colors.enabled = colors.supportsColor() !== false;
}
colors.enable = function() {
colors.enabled = true;
};
colors.disable = function() {
colors.enabled = false;
};
colors.stripColors = colors.strip = function(str) {
return ('' + str).replace(/\x1B\[\d+m/g, '');
};
// eslint-disable-next-line no-unused-vars
var stylize = colors.stylize = function stylize(str, style) {
if (!colors.enabled) {
return str+'';
}
var styleMap = ansiStyles[style];
// Stylize should work for non-ANSI styles, too
if (!styleMap && style in colors) {
// Style maps like trap operate as functions on strings;
// they don't have properties like open or close.
return colors[style](str);
}
return styleMap.open + str + styleMap.close;
};
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
var escapeStringRegexp = function(str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
};
function build(_styles) {
var builder = function builder() {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
// __proto__ is used because we must return a function, but there is
// no way to create a function with a different prototype.
builder.__proto__ = proto;
return builder;
}
var styles = (function() {
var ret = {};
ansiStyles.grey = ansiStyles.gray;
Object.keys(ansiStyles).forEach(function(key) {
ansiStyles[key].closeRe =
new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
ret[key] = {
get: function() {
return build(this._styles.concat(key));
},
};
});
return ret;
})();
var proto = defineProps(function colors() {}, styles);
function applyStyle() {
var args = Array.prototype.slice.call(arguments);
var str = args.map(function(arg) {
// Use weak equality check so we can colorize null/undefined in safe mode
if (arg != null && arg.constructor === String) {
return arg;
} else {
return util.inspect(arg);
}
}).join(' ');
if (!colors.enabled || !str) {
return str;
}
var newLinesPresent = str.indexOf('\n') != -1;
var nestedStyles = this._styles;
var i = nestedStyles.length;
while (i--) {
var code = ansiStyles[nestedStyles[i]];
str = code.open + str.replace(code.closeRe, code.open) + code.close;
if (newLinesPresent) {
str = str.replace(newLineRegex, function(match) {
return code.close + match + code.open;
});
}
}
return str;
}
colors.setTheme = function(theme) {
if (typeof theme === 'string') {
console.log('colors.setTheme now only accepts an object, not a string. ' +
'If you are trying to set a theme from a file, it is now your (the ' +
'caller\'s) responsibility to require the file. The old syntax ' +
'looked like colors.setTheme(__dirname + ' +
'\'/../themes/generic-logging.js\'); The new syntax looks like '+
'colors.setTheme(require(__dirname + ' +
'\'/../themes/generic-logging.js\'));');
return;
}
for (var style in theme) {
(function(style) {
colors[style] = function(str) {
if (typeof theme[style] === 'object') {
var out = str;
for (var i in theme[style]) {
out = colors[theme[style][i]](out);
}
return out;
}
return colors[theme[style]](str);
};
})(style);
}
};
function init() {
var ret = {};
Object.keys(styles).forEach(function(name) {
ret[name] = {
get: function() {
return build([name]);
},
};
});
return ret;
}
var sequencer = function sequencer(map, str) {
var exploded = str.split('');
exploded = exploded.map(map);
return exploded.join('');
};
// custom formatter methods
colors.trap = require('./custom/trap');
colors.zalgo = require('./custom/zalgo');
// maps
colors.maps = {};
colors.maps.america = require('./maps/america')(colors);
colors.maps.zebra = require('./maps/zebra')(colors);
colors.maps.rainbow = require('./maps/rainbow')(colors);
colors.maps.random = require('./maps/random')(colors);
for (var map in colors.maps) {
(function(map) {
colors[map] = function(str) {
return sequencer(colors.maps[map], str);
};
})(map);
}
defineProps(colors, init());

View file

@ -0,0 +1,46 @@
module['exports'] = function runTheTrap(text, options) {
var result = '';
text = text || 'Run the trap, drop the bass';
text = text.split('');
var trap = {
a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'],
b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'],
c: ['\u00a9', '\u023b', '\u03fe'],
d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'],
e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc',
'\u0a6c'],
f: ['\u04fa'],
g: ['\u0262'],
h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'],
i: ['\u0f0f'],
j: ['\u0134'],
k: ['\u0138', '\u04a0', '\u04c3', '\u051e'],
l: ['\u0139'],
m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'],
n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'],
o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd',
'\u06dd', '\u0e4f'],
p: ['\u01f7', '\u048e'],
q: ['\u09cd'],
r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'],
s: ['\u00a7', '\u03de', '\u03df', '\u03e8'],
t: ['\u0141', '\u0166', '\u0373'],
u: ['\u01b1', '\u054d'],
v: ['\u05d8'],
w: ['\u0428', '\u0460', '\u047c', '\u0d70'],
x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'],
y: ['\u00a5', '\u04b0', '\u04cb'],
z: ['\u01b5', '\u0240'],
};
text.forEach(function(c) {
c = c.toLowerCase();
var chars = trap[c] || [' '];
var rand = Math.floor(Math.random() * chars.length);
if (typeof trap[c] !== 'undefined') {
result += trap[c][rand];
} else {
result += c;
}
});
return result;
};

View file

@ -0,0 +1,110 @@
// please no
module['exports'] = function zalgo(text, options) {
text = text || ' he is here ';
var soul = {
'up': [
'̍', '̎', '̄', '̅',
'̿', '̑', '̆', '̐',
'͒', '͗', '͑', '̇',
'̈', '̊', '͂', '̓',
'̈', '͊', '͋', '͌',
'̃', '̂', '̌', '͐',
'̀', '́', '̋', '̏',
'̒', '̓', '̔', '̽',
'̉', 'ͣ', 'ͤ', 'ͥ',
'ͦ', 'ͧ', 'ͨ', 'ͩ',
'ͪ', 'ͫ', 'ͬ', 'ͭ',
'ͮ', 'ͯ', '̾', '͛',
'͆', '̚',
],
'down': [
'̖', '̗', '̘', '̙',
'̜', '̝', '̞', '̟',
'̠', '̤', '̥', '̦',
'̩', '̪', '̫', '̬',
'̭', '̮', '̯', '̰',
'̱', '̲', '̳', '̹',
'̺', '̻', '̼', 'ͅ',
'͇', '͈', '͉', '͍',
'͎', '͓', '͔', '͕',
'͖', '͙', '͚', '̣',
],
'mid': [
'̕', '̛', '̀', '́',
'͘', '̡', '̢', '̧',
'̨', '̴', '̵', '̶',
'͜', '͝', '͞',
'͟', '͠', '͢', '̸',
'̷', '͡', ' ҉',
],
};
var all = [].concat(soul.up, soul.down, soul.mid);
function randomNumber(range) {
var r = Math.floor(Math.random() * range);
return r;
}
function isChar(character) {
var bool = false;
all.filter(function(i) {
bool = (i === character);
});
return bool;
}
function heComes(text, options) {
var result = '';
var counts;
var l;
options = options || {};
options['up'] =
typeof options['up'] !== 'undefined' ? options['up'] : true;
options['mid'] =
typeof options['mid'] !== 'undefined' ? options['mid'] : true;
options['down'] =
typeof options['down'] !== 'undefined' ? options['down'] : true;
options['size'] =
typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';
text = text.split('');
for (l in text) {
if (isChar(l)) {
continue;
}
result = result + text[l];
counts = {'up': 0, 'down': 0, 'mid': 0};
switch (options.size) {
case 'mini':
counts.up = randomNumber(8);
counts.mid = randomNumber(2);
counts.down = randomNumber(8);
break;
case 'maxi':
counts.up = randomNumber(16) + 3;
counts.mid = randomNumber(4) + 1;
counts.down = randomNumber(64) + 3;
break;
default:
counts.up = randomNumber(8) + 1;
counts.mid = randomNumber(6) / 2;
counts.down = randomNumber(8) + 1;
break;
}
var arr = ['up', 'mid', 'down'];
for (var d in arr) {
var index = arr[d];
for (var i = 0; i <= counts[index]; i++) {
if (options[index]) {
result = result + soul[index][randomNumber(soul[index].length)];
}
}
}
}
return result;
}
// don't summon him
return heComes(text, options);
};

View file

@ -0,0 +1,110 @@
var colors = require('./colors');
module['exports'] = function() {
//
// Extends prototype of native string object to allow for "foo".red syntax
//
var addProperty = function(color, func) {
String.prototype.__defineGetter__(color, func);
};
addProperty('strip', function() {
return colors.strip(this);
});
addProperty('stripColors', function() {
return colors.strip(this);
});
addProperty('trap', function() {
return colors.trap(this);
});
addProperty('zalgo', function() {
return colors.zalgo(this);
});
addProperty('zebra', function() {
return colors.zebra(this);
});
addProperty('rainbow', function() {
return colors.rainbow(this);
});
addProperty('random', function() {
return colors.random(this);
});
addProperty('america', function() {
return colors.america(this);
});
//
// Iterate through all default styles and colors
//
var x = Object.keys(colors.styles);
x.forEach(function(style) {
addProperty(style, function() {
return colors.stylize(this, style);
});
});
function applyTheme(theme) {
//
// Remark: This is a list of methods that exist
// on String that you should not overwrite.
//
var stringPrototypeBlacklist = [
'__defineGetter__', '__defineSetter__', '__lookupGetter__',
'__lookupSetter__', 'charAt', 'constructor', 'hasOwnProperty',
'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString',
'valueOf', 'charCodeAt', 'indexOf', 'lastIndexOf', 'length',
'localeCompare', 'match', 'repeat', 'replace', 'search', 'slice',
'split', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase',
'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight',
];
Object.keys(theme).forEach(function(prop) {
if (stringPrototypeBlacklist.indexOf(prop) !== -1) {
console.log('warn: '.red + ('String.prototype' + prop).magenta +
' is probably something you don\'t want to override. ' +
'Ignoring style name');
} else {
if (typeof(theme[prop]) === 'string') {
colors[prop] = colors[theme[prop]];
addProperty(prop, function() {
return colors[prop](this);
});
} else {
var themePropApplicator = function(str) {
var ret = str || this;
for (var t = 0; t < theme[prop].length; t++) {
ret = colors[theme[prop][t]](ret);
}
return ret;
};
addProperty(prop, themePropApplicator);
colors[prop] = function(str) {
return themePropApplicator(str);
};
}
}
});
}
colors.setTheme = function(theme) {
if (typeof theme === 'string') {
console.log('colors.setTheme now only accepts an object, not a string. ' +
'If you are trying to set a theme from a file, it is now your (the ' +
'caller\'s) responsibility to require the file. The old syntax ' +
'looked like colors.setTheme(__dirname + ' +
'\'/../themes/generic-logging.js\'); The new syntax looks like '+
'colors.setTheme(require(__dirname + ' +
'\'/../themes/generic-logging.js\'));');
return;
} else {
applyTheme(theme);
}
};
};

View file

@ -0,0 +1,13 @@
var colors = require('./colors');
module['exports'] = colors;
// Remark: By default, colors will add style properties to String.prototype.
//
// If you don't wish to extend String.prototype, you can do this instead and
// native String will not be touched:
//
// var colors = require('@colors/colors/safe');
// colors.red("foo")
//
//
require('./extendStringPrototype')();

View file

@ -0,0 +1,10 @@
module['exports'] = function(colors) {
return function(letter, i, exploded) {
if (letter === ' ') return letter;
switch (i%3) {
case 0: return colors.red(letter);
case 1: return colors.white(letter);
case 2: return colors.blue(letter);
}
};
};

View file

@ -0,0 +1,12 @@
module['exports'] = function(colors) {
// RoY G BiV
var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];
return function(letter, i, exploded) {
if (letter === ' ') {
return letter;
} else {
return colors[rainbowColors[i++ % rainbowColors.length]](letter);
}
};
};

View file

@ -0,0 +1,11 @@
module['exports'] = function(colors) {
var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',
'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',
'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];
return function(letter, i, exploded) {
return letter === ' ' ? letter :
colors[
available[Math.round(Math.random() * (available.length - 2))]
](letter);
};
};

View file

@ -0,0 +1,5 @@
module['exports'] = function(colors) {
return function(letter, i, exploded) {
return i % 2 === 0 ? letter : colors.inverse(letter);
};
};

View file

@ -0,0 +1,95 @@
/*
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var styles = {};
module['exports'] = styles;
var codes = {
reset: [0, 0],
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
grey: [90, 39],
brightRed: [91, 39],
brightGreen: [92, 39],
brightYellow: [93, 39],
brightBlue: [94, 39],
brightMagenta: [95, 39],
brightCyan: [96, 39],
brightWhite: [97, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
bgGray: [100, 49],
bgGrey: [100, 49],
bgBrightRed: [101, 49],
bgBrightGreen: [102, 49],
bgBrightYellow: [103, 49],
bgBrightBlue: [104, 49],
bgBrightMagenta: [105, 49],
bgBrightCyan: [106, 49],
bgBrightWhite: [107, 49],
// legacy styles for colors pre v1.0.0
blackBG: [40, 49],
redBG: [41, 49],
greenBG: [42, 49],
yellowBG: [43, 49],
blueBG: [44, 49],
magentaBG: [45, 49],
cyanBG: [46, 49],
whiteBG: [47, 49],
};
Object.keys(codes).forEach(function(key) {
var val = codes[key];
var style = styles[key] = [];
style.open = '\u001b[' + val[0] + 'm';
style.close = '\u001b[' + val[1] + 'm';
});

View file

@ -0,0 +1,35 @@
/*
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
module.exports = function(flag, argv) {
argv = argv || process.argv || [];
var terminatorPos = argv.indexOf('--');
var prefix = /^-{1,2}/.test(flag) ? '' : '--';
var pos = argv.indexOf(prefix + flag);
return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
};

View file

@ -0,0 +1,151 @@
/*
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
'use strict';
var os = require('os');
var hasFlag = require('./has-flag.js');
var env = process.env;
var forceColor = void 0;
if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
forceColor = false;
} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')
|| hasFlag('color=always')) {
forceColor = true;
}
if ('FORCE_COLOR' in env) {
forceColor = env.FORCE_COLOR.length === 0
|| parseInt(env.FORCE_COLOR, 10) !== 0;
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level: level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3,
};
}
function supportsColor(stream) {
if (forceColor === false) {
return 0;
}
if (hasFlag('color=16m') || hasFlag('color=full')
|| hasFlag('color=truecolor')) {
return 3;
}
if (hasFlag('color=256')) {
return 2;
}
if (stream && !stream.isTTY && forceColor !== true) {
return 0;
}
var min = forceColor ? 1 : 0;
if (process.platform === 'win32') {
// Node.js 7.5.0 is the first version of Node.js to include a patch to
// libuv that enables 256 color output on Windows. Anything earlier and it
// won't work. However, here we target Node.js 8 at minimum as it is an LTS
// release, and Node.js 7 is not. Windows 10 build 10586 is the first
// Windows release that supports 256 colors. Windows 10 build 14931 is the
// first release that supports 16m/TrueColor.
var osRelease = os.release().split('.');
if (Number(process.versions.node.split('.')[0]) >= 8
&& Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ('CI' in env) {
if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {
return sign in env;
}) || env.CI_NAME === 'codeship') {
return 1;
}
return min;
}
if ('TEAMCITY_VERSION' in env) {
return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0
);
}
if ('TERM_PROGRAM' in env) {
var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
switch (env.TERM_PROGRAM) {
case 'iTerm.app':
return version >= 3 ? 3 : 2;
case 'Hyper':
return 3;
case 'Apple_Terminal':
return 2;
// No default
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ('COLORTERM' in env) {
return 1;
}
if (env.TERM === 'dumb') {
return min;
}
return min;
}
function getSupportLevel(stream) {
var level = supportsColor(stream);
return translateLevel(level);
}
module.exports = {
supportsColor: getSupportLevel,
stdout: getSupportLevel(process.stdout),
stderr: getSupportLevel(process.stderr),
};

View file

@ -0,0 +1,45 @@
{
"name": "@colors/colors",
"description": "get colors in your node.js console",
"version": "1.6.0",
"author": "DABH",
"contributors": [
{
"name": "DABH",
"url": "https://github.com/DABH"
}
],
"homepage": "https://github.com/DABH/colors.js",
"bugs": "https://github.com/DABH/colors.js/issues",
"keywords": [
"ansi",
"terminal",
"colors"
],
"repository": {
"type": "git",
"url": "http://github.com/DABH/colors.js.git"
},
"license": "MIT",
"scripts": {
"lint": "eslint . --fix",
"test": "export FORCE_COLOR=1 && node tests/basic-test.js && node tests/safe-test.js"
},
"engines": {
"node": ">=0.1.90"
},
"main": "lib/index.js",
"files": [
"examples",
"lib",
"LICENSE",
"safe.js",
"themes",
"index.d.ts",
"safe.d.ts"
],
"devDependencies": {
"eslint": "^8.9.0",
"eslint-config-google": "^0.14.0"
}
}

View file

@ -0,0 +1,64 @@
// Type definitions for Colors.js 1.2
// Project: https://github.com/Marak/colors.js
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>, Staffan Eketorp <https://github.com/staeke>
// Definitions: https://github.com/Marak/colors.js
export const enabled: boolean;
export function enable(): void;
export function disable(): void;
export function setTheme(theme: any): void;
export function strip(str: string): string;
export function stripColors(str: string): string;
export function black(str: string): string;
export function red(str: string): string;
export function green(str: string): string;
export function yellow(str: string): string;
export function blue(str: string): string;
export function magenta(str: string): string;
export function cyan(str: string): string;
export function white(str: string): string;
export function gray(str: string): string;
export function grey(str: string): string;
export function brightRed(str: string): string;
export function brightGreen(str: string): string;
export function brightYellow(str: string): string;
export function brightBlue(str: string): string;
export function brightMagenta(str: string): string;
export function brightCyan(str: string): string;
export function brightWhite(str: string): string;
export function bgBlack(str: string): string;
export function bgRed(str: string): string;
export function bgGreen(str: string): string;
export function bgYellow(str: string): string;
export function bgBlue(str: string): string;
export function bgMagenta(str: string): string;
export function bgCyan(str: string): string;
export function bgWhite(str: string): string;
export function bgBrightRed(str: string): string;
export function bgBrightGreen(str: string): string;
export function bgBrightYellow(str: string): string;
export function bgBrightBlue(str: string): string;
export function bgBrightMagenta(str: string): string;
export function bgBrightCyan(str: string): string;
export function bgBrightWhite(str: string): string;
export function reset(str: string): string;
export function bold(str: string): string;
export function dim(str: string): string;
export function italic(str: string): string;
export function underline(str: string): string;
export function inverse(str: string): string;
export function hidden(str: string): string;
export function strikethrough(str: string): string;
export function rainbow(str: string): string;
export function zebra(str: string): string;
export function america(str: string): string;
export function trap(str: string): string;
export function random(str: string): string;
export function zalgo(str: string): string;

View file

@ -0,0 +1,10 @@
//
// Remark: Requiring this file will use the "safe" colors API,
// which will not touch String.prototype.
//
// var colors = require('colors/safe');
// colors.red("foo")
//
//
var colors = require('./lib/colors');
module['exports'] = colors;

View file

@ -0,0 +1,12 @@
module['exports'] = {
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red',
};

View file

@ -0,0 +1,38 @@
# Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
* (a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
* (b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
* (c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
* (d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
## Moderation Policy
The [Node.js Moderation Policy] applies to this WG.
## Code of Conduct
The [Node.js Code of Conduct][] applies to this WG.
[Node.js Code of Conduct]:
https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md
[Node.js Moderation Policy]:
https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md

View file

@ -0,0 +1,136 @@
### Streams Working Group
The Node.js Streams is jointly governed by a Working Group
(WG)
that is responsible for high-level guidance of the project.
The WG has final authority over this project including:
* Technical direction
* Project governance and process (including this policy)
* Contribution policy
* GitHub repository hosting
* Conduct guidelines
* Maintaining the list of additional Collaborators
For the current list of WG members, see the project
[README.md](./README.md#current-project-team-members).
### Collaborators
The readable-stream GitHub repository is
maintained by the WG and additional Collaborators who are added by the
WG on an ongoing basis.
Individuals making significant and valuable contributions are made
Collaborators and given commit-access to the project. These
individuals are identified by the WG and their addition as
Collaborators is discussed during the WG meeting.
_Note:_ If you make a significant contribution and are not considered
for commit-access log an issue or contact a WG member directly and it
will be brought up in the next WG meeting.
Modifications of the contents of the readable-stream repository are
made on
a collaborative basis. Anybody with a GitHub account may propose a
modification via pull request and it will be considered by the project
Collaborators. All pull requests must be reviewed and accepted by a
Collaborator with sufficient expertise who is able to take full
responsibility for the change. In the case of pull requests proposed
by an existing Collaborator, an additional Collaborator is required
for sign-off. Consensus should be sought if additional Collaborators
participate and there is disagreement around a particular
modification. See _Consensus Seeking Process_ below for further detail
on the consensus model used for governance.
Collaborators may opt to elevate significant or controversial
modifications, or modifications that have not found consensus to the
WG for discussion by assigning the ***WG-agenda*** tag to a pull
request or issue. The WG should serve as the final arbiter where
required.
For the current list of Collaborators, see the project
[README.md](./README.md#members).
### WG Membership
WG seats are not time-limited. There is no fixed size of the WG.
However, the expected target is between 6 and 12, to ensure adequate
coverage of important areas of expertise, balanced with the ability to
make decisions efficiently.
There is no specific set of requirements or qualifications for WG
membership beyond these rules.
The WG may add additional members to the WG by unanimous consensus.
A WG member may be removed from the WG by voluntary resignation, or by
unanimous consensus of all other WG members.
Changes to WG membership should be posted in the agenda, and may be
suggested as any other agenda item (see "WG Meetings" below).
If an addition or removal is proposed during a meeting, and the full
WG is not in attendance to participate, then the addition or removal
is added to the agenda for the subsequent meeting. This is to ensure
that all members are given the opportunity to participate in all
membership decisions. If a WG member is unable to attend a meeting
where a planned membership decision is being made, then their consent
is assumed.
No more than 1/3 of the WG members may be affiliated with the same
employer. If removal or resignation of a WG member, or a change of
employment by a WG member, creates a situation where more than 1/3 of
the WG membership shares an employer, then the situation must be
immediately remedied by the resignation or removal of one or more WG
members affiliated with the over-represented employer(s).
### WG Meetings
The WG meets occasionally on a Google Hangout On Air. A designated moderator
approved by the WG runs the meeting. Each meeting should be
published to YouTube.
Items are added to the WG agenda that are considered contentious or
are modifications of governance, contribution policy, WG membership,
or release process.
The intention of the agenda is not to approve or review all patches;
that should happen continuously on GitHub and be handled by the larger
group of Collaborators.
Any community member or contributor can ask that something be added to
the next meeting's agenda by logging a GitHub Issue. Any Collaborator,
WG member or the moderator can add the item to the agenda by adding
the ***WG-agenda*** tag to the issue.
Prior to each WG meeting the moderator will share the Agenda with
members of the WG. WG members can add any items they like to the
agenda at the beginning of each meeting. The moderator and the WG
cannot veto or remove items.
The WG may invite persons or representatives from certain projects to
participate in a non-voting capacity.
The moderator is responsible for summarizing the discussion of each
agenda item and sends it as a pull request after the meeting.
### Consensus Seeking Process
The WG follows a
[Consensus
Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making)
decision-making model.
When an agenda item has appeared to reach a consensus the moderator
will ask "Does anyone object?" as a final call for dissent from the
consensus.
If an agenda item cannot reach a consensus a WG member can call for
either a closing vote or a vote to table the issue to the next
meeting. The call for a vote must be seconded by a majority of the WG
or else the discussion will continue. Simple majority wins.
Note that changes to WG membership require a majority consensus. See
"WG Membership" above.

View file

@ -0,0 +1,47 @@
Node.js is licensed for use as follows:
"""
Copyright Node.js contributors. All rights reserved.
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.
"""
This license applies to parts of Node.js originating from the
https://github.com/joyent/node repository:
"""
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
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,106 @@
# readable-stream
***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream)
[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)
[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/)
[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream)
```bash
npm install --save readable-stream
```
This package is a mirror of the streams implementations in Node.js.
Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html).
If you want to guarantee a stable streams base, regardless of what version of
Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).
As of version 2.0.0 **readable-stream** uses semantic versioning.
## Version 3.x.x
v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows:
1. Error codes: https://github.com/nodejs/node/pull/13310,
https://github.com/nodejs/node/pull/13291,
https://github.com/nodejs/node/pull/16589,
https://github.com/nodejs/node/pull/15042,
https://github.com/nodejs/node/pull/15665,
https://github.com/nodejs/readable-stream/pull/344
2. 'readable' have precedence over flowing
https://github.com/nodejs/node/pull/18994
3. make virtual methods errors consistent
https://github.com/nodejs/node/pull/18813
4. updated streams error handling
https://github.com/nodejs/node/pull/18438
5. writable.end should return this.
https://github.com/nodejs/node/pull/18780
6. readable continues to read when push('')
https://github.com/nodejs/node/pull/18211
7. add custom inspect to BufferList
https://github.com/nodejs/node/pull/17907
8. always defer 'readable' with nextTick
https://github.com/nodejs/node/pull/17979
## Version 2.x.x
v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11.
### Big Thanks
Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce]
# Usage
You can swap your `require('stream')` with `require('readable-stream')`
without any changes, if you are just using one of the main classes and
functions.
```js
const {
Readable,
Writable,
Transform,
Duplex,
pipeline,
finished
} = require('readable-stream')
````
Note that `require('stream')` will return `Stream`, while
`require('readable-stream')` will return `Readable`. We discourage using
whatever is exported directly, but rather use one of the properties as
shown in the example above.
# Streams Working Group
`readable-stream` is maintained by the Streams Working Group, which
oversees the development and maintenance of the Streams API within
Node.js. The responsibilities of the Streams Working Group include:
* Addressing stream issues on the Node.js issue tracker.
* Authoring and editing stream documentation within the Node.js project.
* Reviewing changes to stream subclasses within the Node.js project.
* Redirecting changes to streams from the Node.js project to this
project.
* Assisting in the implementation of stream providers within Node.js.
* Recommending versions of `readable-stream` to be included in Node.js.
* Messaging about the future of streams to give the community advance
notice of changes.
<a name="members"></a>
## Team Members
* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt;
- Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt;
* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt;
- Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E
* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt;
* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt;
[sauce]: https://saucelabs.com

View file

@ -0,0 +1,127 @@
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var codes = {};
function createErrorType(code, message, Base) {
if (!Base) {
Base = Error;
}
function getMessage(arg1, arg2, arg3) {
if (typeof message === 'string') {
return message;
} else {
return message(arg1, arg2, arg3);
}
}
var NodeError =
/*#__PURE__*/
function (_Base) {
_inheritsLoose(NodeError, _Base);
function NodeError(arg1, arg2, arg3) {
return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
}
return NodeError;
}(Base);
NodeError.prototype.name = Base.name;
NodeError.prototype.code = code;
codes[code] = NodeError;
} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
function oneOf(expected, thing) {
if (Array.isArray(expected)) {
var len = expected.length;
expected = expected.map(function (i) {
return String(i);
});
if (len > 2) {
return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
} else if (len === 2) {
return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
} else {
return "of ".concat(thing, " ").concat(expected[0]);
}
} else {
return "of ".concat(thing, " ").concat(String(expected));
}
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
function startsWith(str, search, pos) {
return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
function endsWith(str, search, this_len) {
if (this_len === undefined || this_len > str.length) {
this_len = str.length;
}
return str.substring(this_len - search.length, this_len) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
function includes(str, search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > str.length) {
return false;
} else {
return str.indexOf(search, start) !== -1;
}
}
createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
return 'The value "' + value + '" is invalid for option "' + name + '"';
}, TypeError);
createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
// determiner: 'must be' or 'must not be'
var determiner;
if (typeof expected === 'string' && startsWith(expected, 'not ')) {
determiner = 'must not be';
expected = expected.replace(/^not /, '');
} else {
determiner = 'must be';
}
var msg;
if (endsWith(name, ' argument')) {
// For cases like 'first argument'
msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
} else {
var type = includes(name, '.') ? 'property' : 'argument';
msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
}
msg += ". Received type ".concat(typeof actual);
return msg;
}, TypeError);
createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
return 'The ' + name + ' method is not implemented';
});
createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
createErrorType('ERR_STREAM_DESTROYED', function (name) {
return 'Cannot call ' + name + ' after a stream was destroyed';
});
createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
return 'Unknown encoding: ' + arg;
}, TypeError);
createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
module.exports.codes = codes;

View file

@ -0,0 +1,116 @@
'use strict';
const codes = {};
function createErrorType(code, message, Base) {
if (!Base) {
Base = Error
}
function getMessage (arg1, arg2, arg3) {
if (typeof message === 'string') {
return message
} else {
return message(arg1, arg2, arg3)
}
}
class NodeError extends Base {
constructor (arg1, arg2, arg3) {
super(getMessage(arg1, arg2, arg3));
}
}
NodeError.prototype.name = Base.name;
NodeError.prototype.code = code;
codes[code] = NodeError;
}
// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
function oneOf(expected, thing) {
if (Array.isArray(expected)) {
const len = expected.length;
expected = expected.map((i) => String(i));
if (len > 2) {
return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +
expected[len - 1];
} else if (len === 2) {
return `one of ${thing} ${expected[0]} or ${expected[1]}`;
} else {
return `of ${thing} ${expected[0]}`;
}
} else {
return `of ${thing} ${String(expected)}`;
}
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
function startsWith(str, search, pos) {
return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
function endsWith(str, search, this_len) {
if (this_len === undefined || this_len > str.length) {
this_len = str.length;
}
return str.substring(this_len - search.length, this_len) === search;
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
function includes(str, search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > str.length) {
return false;
} else {
return str.indexOf(search, start) !== -1;
}
}
createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
return 'The value "' + value + '" is invalid for option "' + name + '"'
}, TypeError);
createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
// determiner: 'must be' or 'must not be'
let determiner;
if (typeof expected === 'string' && startsWith(expected, 'not ')) {
determiner = 'must not be';
expected = expected.replace(/^not /, '');
} else {
determiner = 'must be';
}
let msg;
if (endsWith(name, ' argument')) {
// For cases like 'first argument'
msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;
} else {
const type = includes(name, '.') ? 'property' : 'argument';
msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`;
}
msg += `. Received type ${typeof actual}`;
return msg;
}, TypeError);
createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
return 'The ' + name + ' method is not implemented'
});
createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
createErrorType('ERR_STREAM_DESTROYED', function (name) {
return 'Cannot call ' + name + ' after a stream was destroyed';
});
createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
return 'Unknown encoding: ' + arg
}, TypeError);
createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
module.exports.codes = codes;

View file

@ -0,0 +1,17 @@
'use strict'
var experimentalWarnings = new Set();
function emitExperimentalWarning(feature) {
if (experimentalWarnings.has(feature)) return;
var msg = feature + ' is an experimental feature. This feature could ' +
'change at any time';
experimentalWarnings.add(feature);
process.emitWarning(msg, 'ExperimentalWarning');
}
function noop() {}
module.exports.emitExperimentalWarning = process.emitWarning
? emitExperimentalWarning
: noop;

View file

@ -0,0 +1,126 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
};
/*</replacement>*/
module.exports = Duplex;
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
require('inherits')(Duplex, Readable);
{
// Allow the keys array to be GC'ed.
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
this.allowHalfOpen = true;
if (options) {
if (options.readable === false) this.readable = false;
if (options.writable === false) this.writable = false;
if (options.allowHalfOpen === false) {
this.allowHalfOpen = false;
this.once('end', onend);
}
}
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.highWaterMark;
}
});
Object.defineProperty(Duplex.prototype, 'writableBuffer', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState && this._writableState.getBuffer();
}
});
Object.defineProperty(Duplex.prototype, 'writableLength', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.length;
}
});
// the no-half-open enforcer
function onend() {
// If the writable side ended, then we're ok.
if (this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
process.nextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});

View file

@ -0,0 +1,37 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
require('inherits')(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,190 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var _require$codes = require('../errors').codes,
ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
var Duplex = require('./_stream_duplex');
require('inherits')(Transform, Duplex);
function afterTransform(er, data) {
var ts = this._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (cb === null) {
return this.emit('error', new ERR_MULTIPLE_CALLBACK());
}
ts.writechunk = null;
ts.writecb = null;
if (data != null)
// single equals check for both `null` and `undefined`
this.push(data);
cb(er);
var rs = this._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = {
afterTransform: afterTransform.bind(this),
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: null
};
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.on('prefinish', prefinish);
}
function prefinish() {
var _this = this;
if (typeof this._flush === 'function' && !this._readableState.destroyed) {
this._flush(function (er, data) {
done(_this, er, data);
});
} else {
done(this, null, null);
}
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data != null)
// single equals check for both `null` and `undefined`
stream.push(data);
// TODO(BridgeAR): Write a test for these two error cases
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
return stream.push(null);
}

View file

@ -0,0 +1,641 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream = require('./internal/streams/stream');
/*</replacement>*/
var Buffer = require('buffer').Buffer;
var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
var destroyImpl = require('./internal/streams/destroy');
var _require = require('./internal/streams/state'),
getHighWaterMark = _require.getHighWaterMark;
var _require$codes = require('../errors').codes,
ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
var errorOrDestroy = destroyImpl.errorOrDestroy;
require('inherits')(Writable, Stream);
function nop() {}
function WritableState(options, stream, isDuplex) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream,
// e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// Should close be emitted on destroy. Defaults to true.
this.emitClose = options.emitClose !== false;
// Should .destroy() be called after 'finish' (and potentially 'end')
this.autoDestroy = !!options.autoDestroy;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function writableStateBufferGetter() {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function value(object) {
if (realHasInstance.call(this, object)) return true;
if (this !== Writable) return false;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function realHasInstance(object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
// Checking for a Stream.Duplex instance is faster here instead of inside
// the WritableState constructor, at least with V8 6.5
var isDuplex = this instanceof Duplex;
if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
this._writableState = new WritableState(options, this, isDuplex);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
};
function writeAfterEnd(stream, cb) {
var er = new ERR_STREAM_WRITE_AFTER_END();
// TODO: defer error events consistently everywhere, not just the cb
errorOrDestroy(stream, er);
process.nextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var er;
if (chunk === null) {
er = new ERR_STREAM_NULL_VALUES();
} else if (typeof chunk !== 'string' && !state.objectMode) {
er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
}
if (er) {
errorOrDestroy(stream, er);
process.nextTick(cb, er);
return false;
}
return true;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = !state.objectMode && _isUint8Array(chunk);
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
this._writableState.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
Object.defineProperty(Writable.prototype, 'writableBuffer', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState && this._writableState.getBuffer();
}
});
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.highWaterMark;
}
});
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
process.nextTick(cb, er);
// this can emit finish, and it will always happen
// after error
process.nextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
errorOrDestroy(stream, er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
errorOrDestroy(stream, er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state) || stream.destroyed;
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
process.nextTick(afterWrite, stream, state, finished, cb);
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
state.bufferedRequestCount = 0;
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
state.bufferedRequestCount--;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending) endWritable(this, state, cb);
return this;
};
Object.defineProperty(Writable.prototype, 'writableLength', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
return this._writableState.length;
}
});
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
errorOrDestroy(stream, err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function' && !state.destroyed) {
state.pendingcb++;
state.finalCalled = true;
process.nextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
if (state.autoDestroy) {
// In case of duplex streams we need a way to detect
// if the readable side is ready for autoDestroy as well
var rState = stream._readableState;
if (!rState || rState.autoDestroy && rState.endEmitted) {
stream.destroy();
}
}
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
// reuse the free corkReq.
state.corkedRequestsFree.next = corkReq;
}
Object.defineProperty(Writable.prototype, 'destroyed', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function get() {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function set(value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
cb(err);
};

View file

@ -0,0 +1,180 @@
'use strict';
var _Object$setPrototypeO;
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var finished = require('./end-of-stream');
var kLastResolve = Symbol('lastResolve');
var kLastReject = Symbol('lastReject');
var kError = Symbol('error');
var kEnded = Symbol('ended');
var kLastPromise = Symbol('lastPromise');
var kHandlePromise = Symbol('handlePromise');
var kStream = Symbol('stream');
function createIterResult(value, done) {
return {
value: value,
done: done
};
}
function readAndResolve(iter) {
var resolve = iter[kLastResolve];
if (resolve !== null) {
var data = iter[kStream].read();
// we defer if data is null
// we can be expecting either 'end' or
// 'error'
if (data !== null) {
iter[kLastPromise] = null;
iter[kLastResolve] = null;
iter[kLastReject] = null;
resolve(createIterResult(data, false));
}
}
}
function onReadable(iter) {
// we wait for the next tick, because it might
// emit an error with process.nextTick
process.nextTick(readAndResolve, iter);
}
function wrapForNext(lastPromise, iter) {
return function (resolve, reject) {
lastPromise.then(function () {
if (iter[kEnded]) {
resolve(createIterResult(undefined, true));
return;
}
iter[kHandlePromise](resolve, reject);
}, reject);
};
}
var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
get stream() {
return this[kStream];
},
next: function next() {
var _this = this;
// if we have detected an error in the meanwhile
// reject straight away
var error = this[kError];
if (error !== null) {
return Promise.reject(error);
}
if (this[kEnded]) {
return Promise.resolve(createIterResult(undefined, true));
}
if (this[kStream].destroyed) {
// We need to defer via nextTick because if .destroy(err) is
// called, the error will be emitted via nextTick, and
// we cannot guarantee that there is no error lingering around
// waiting to be emitted.
return new Promise(function (resolve, reject) {
process.nextTick(function () {
if (_this[kError]) {
reject(_this[kError]);
} else {
resolve(createIterResult(undefined, true));
}
});
});
}
// if we have multiple next() calls
// we will wait for the previous Promise to finish
// this logic is optimized to support for await loops,
// where next() is only called once at a time
var lastPromise = this[kLastPromise];
var promise;
if (lastPromise) {
promise = new Promise(wrapForNext(lastPromise, this));
} else {
// fast path needed to support multiple this.push()
// without triggering the next() queue
var data = this[kStream].read();
if (data !== null) {
return Promise.resolve(createIterResult(data, false));
}
promise = new Promise(this[kHandlePromise]);
}
this[kLastPromise] = promise;
return promise;
}
}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
return this;
}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
var _this2 = this;
// destroy(err, cb) is a private API
// we can guarantee we have that here, because we control the
// Readable class this is attached to
return new Promise(function (resolve, reject) {
_this2[kStream].destroy(null, function (err) {
if (err) {
reject(err);
return;
}
resolve(createIterResult(undefined, true));
});
});
}), _Object$setPrototypeO), AsyncIteratorPrototype);
var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
var _Object$create;
var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
value: stream,
writable: true
}), _defineProperty(_Object$create, kLastResolve, {
value: null,
writable: true
}), _defineProperty(_Object$create, kLastReject, {
value: null,
writable: true
}), _defineProperty(_Object$create, kError, {
value: null,
writable: true
}), _defineProperty(_Object$create, kEnded, {
value: stream._readableState.endEmitted,
writable: true
}), _defineProperty(_Object$create, kHandlePromise, {
value: function value(resolve, reject) {
var data = iterator[kStream].read();
if (data) {
iterator[kLastPromise] = null;
iterator[kLastResolve] = null;
iterator[kLastReject] = null;
resolve(createIterResult(data, false));
} else {
iterator[kLastResolve] = resolve;
iterator[kLastReject] = reject;
}
},
writable: true
}), _Object$create));
iterator[kLastPromise] = null;
finished(stream, function (err) {
if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
var reject = iterator[kLastReject];
// reject if we are waiting for data in the Promise
// returned by next() and store the error
if (reject !== null) {
iterator[kLastPromise] = null;
iterator[kLastResolve] = null;
iterator[kLastReject] = null;
reject(err);
}
iterator[kError] = err;
return;
}
var resolve = iterator[kLastResolve];
if (resolve !== null) {
iterator[kLastPromise] = null;
iterator[kLastResolve] = null;
iterator[kLastReject] = null;
resolve(createIterResult(undefined, true));
}
iterator[kEnded] = true;
});
stream.on('readable', onReadable.bind(null, iterator));
return iterator;
};
module.exports = createReadableStreamAsyncIterator;

View file

@ -0,0 +1,183 @@
'use strict';
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var _require = require('buffer'),
Buffer = _require.Buffer;
var _require2 = require('util'),
inspect = _require2.inspect;
var custom = inspect && inspect.custom || 'inspect';
function copyBuffer(src, target, offset) {
Buffer.prototype.copy.call(src, target, offset);
}
module.exports = /*#__PURE__*/function () {
function BufferList() {
_classCallCheck(this, BufferList);
this.head = null;
this.tail = null;
this.length = 0;
}
_createClass(BufferList, [{
key: "push",
value: function push(v) {
var entry = {
data: v,
next: null
};
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
}
}, {
key: "unshift",
value: function unshift(v) {
var entry = {
data: v,
next: this.head
};
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
}
}, {
key: "shift",
value: function shift() {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
}
}, {
key: "clear",
value: function clear() {
this.head = this.tail = null;
this.length = 0;
}
}, {
key: "join",
value: function join(s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) ret += s + p.data;
return ret;
}
}, {
key: "concat",
value: function concat(n) {
if (this.length === 0) return Buffer.alloc(0);
var ret = Buffer.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
copyBuffer(p.data, ret, i);
i += p.data.length;
p = p.next;
}
return ret;
}
// Consumes a specified amount of bytes or characters from the buffered data.
}, {
key: "consume",
value: function consume(n, hasStrings) {
var ret;
if (n < this.head.data.length) {
// `slice` is the same for buffers and strings.
ret = this.head.data.slice(0, n);
this.head.data = this.head.data.slice(n);
} else if (n === this.head.data.length) {
// First chunk is a perfect match.
ret = this.shift();
} else {
// Result spans more than one buffer.
ret = hasStrings ? this._getString(n) : this._getBuffer(n);
}
return ret;
}
}, {
key: "first",
value: function first() {
return this.head.data;
}
// Consumes a specified amount of characters from the buffered data.
}, {
key: "_getString",
value: function _getString(n) {
var p = this.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) this.head = p.next;else this.head = this.tail = null;
} else {
this.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
this.length -= c;
return ret;
}
// Consumes a specified amount of bytes from the buffered data.
}, {
key: "_getBuffer",
value: function _getBuffer(n) {
var ret = Buffer.allocUnsafe(n);
var p = this.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) this.head = p.next;else this.head = this.tail = null;
} else {
this.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
this.length -= c;
return ret;
}
// Make sure the linked list only shows the minimal necessary information.
}, {
key: custom,
value: function value(_, options) {
return inspect(this, _objectSpread(_objectSpread({}, options), {}, {
// Only inspect one level.
depth: 0,
// It should not recurse.
customInspect: false
}));
}
}]);
return BufferList;
}();

View file

@ -0,0 +1,96 @@
'use strict';
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err) {
if (!this._writableState) {
process.nextTick(emitErrorNT, this, err);
} else if (!this._writableState.errorEmitted) {
this._writableState.errorEmitted = true;
process.nextTick(emitErrorNT, this, err);
}
}
return this;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
if (!_this._writableState) {
process.nextTick(emitErrorAndCloseNT, _this, err);
} else if (!_this._writableState.errorEmitted) {
_this._writableState.errorEmitted = true;
process.nextTick(emitErrorAndCloseNT, _this, err);
} else {
process.nextTick(emitCloseNT, _this);
}
} else if (cb) {
process.nextTick(emitCloseNT, _this);
cb(err);
} else {
process.nextTick(emitCloseNT, _this);
}
});
return this;
}
function emitErrorAndCloseNT(self, err) {
emitErrorNT(self, err);
emitCloseNT(self);
}
function emitCloseNT(self) {
if (self._writableState && !self._writableState.emitClose) return;
if (self._readableState && !self._readableState.emitClose) return;
self.emit('close');
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finalCalled = false;
this._writableState.prefinished = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
function errorOrDestroy(stream, err) {
// We have tests that rely on errors being emitted
// in the same tick, so changing this is semver major.
// For now when you opt-in to autoDestroy we allow
// the error to be emitted nextTick. In a future
// semver major update we should change the default to this.
var rState = stream._readableState;
var wState = stream._writableState;
if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy,
errorOrDestroy: errorOrDestroy
};

View file

@ -0,0 +1,86 @@
// Ported from https://github.com/mafintosh/end-of-stream with
// permission from the author, Mathias Buus (@mafintosh).
'use strict';
var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
function once(callback) {
var called = false;
return function () {
if (called) return;
called = true;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
callback.apply(this, args);
};
}
function noop() {}
function isRequest(stream) {
return stream.setHeader && typeof stream.abort === 'function';
}
function eos(stream, opts, callback) {
if (typeof opts === 'function') return eos(stream, null, opts);
if (!opts) opts = {};
callback = once(callback || noop);
var readable = opts.readable || opts.readable !== false && stream.readable;
var writable = opts.writable || opts.writable !== false && stream.writable;
var onlegacyfinish = function onlegacyfinish() {
if (!stream.writable) onfinish();
};
var writableEnded = stream._writableState && stream._writableState.finished;
var onfinish = function onfinish() {
writable = false;
writableEnded = true;
if (!readable) callback.call(stream);
};
var readableEnded = stream._readableState && stream._readableState.endEmitted;
var onend = function onend() {
readable = false;
readableEnded = true;
if (!writable) callback.call(stream);
};
var onerror = function onerror(err) {
callback.call(stream, err);
};
var onclose = function onclose() {
var err;
if (readable && !readableEnded) {
if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
return callback.call(stream, err);
}
if (writable && !writableEnded) {
if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
return callback.call(stream, err);
}
};
var onrequest = function onrequest() {
stream.req.on('finish', onfinish);
};
if (isRequest(stream)) {
stream.on('complete', onfinish);
stream.on('abort', onclose);
if (stream.req) onrequest();else stream.on('request', onrequest);
} else if (writable && !stream._writableState) {
// legacy streams
stream.on('end', onlegacyfinish);
stream.on('close', onlegacyfinish);
}
stream.on('end', onend);
stream.on('finish', onfinish);
if (opts.error !== false) stream.on('error', onerror);
stream.on('close', onclose);
return function () {
stream.removeListener('complete', onfinish);
stream.removeListener('abort', onclose);
stream.removeListener('request', onrequest);
if (stream.req) stream.req.removeListener('finish', onfinish);
stream.removeListener('end', onlegacyfinish);
stream.removeListener('close', onlegacyfinish);
stream.removeListener('finish', onfinish);
stream.removeListener('end', onend);
stream.removeListener('error', onerror);
stream.removeListener('close', onclose);
};
}
module.exports = eos;

View file

@ -0,0 +1,3 @@
module.exports = function () {
throw new Error('Readable.from is not available in the browser')
};

View file

@ -0,0 +1,52 @@
'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;
function from(Readable, iterable, opts) {
var iterator;
if (iterable && typeof iterable.next === 'function') {
iterator = iterable;
} else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);
var readable = new Readable(_objectSpread({
objectMode: true
}, opts));
// Reading boolean to protect against _read
// being called before last iteration completion.
var reading = false;
readable._read = function () {
if (!reading) {
reading = true;
next();
}
};
function next() {
return _next2.apply(this, arguments);
}
function _next2() {
_next2 = _asyncToGenerator(function* () {
try {
var _yield$iterator$next = yield iterator.next(),
value = _yield$iterator$next.value,
done = _yield$iterator$next.done;
if (done) {
readable.push(null);
} else if (readable.push(yield value)) {
next();
} else {
reading = false;
}
} catch (err) {
readable.destroy(err);
}
});
return _next2.apply(this, arguments);
}
return readable;
}
module.exports = from;

View file

@ -0,0 +1,86 @@
// Ported from https://github.com/mafintosh/pump with
// permission from the author, Mathias Buus (@mafintosh).
'use strict';
var eos;
function once(callback) {
var called = false;
return function () {
if (called) return;
called = true;
callback.apply(void 0, arguments);
};
}
var _require$codes = require('../../../errors').codes,
ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
function noop(err) {
// Rethrow the error if it exists to avoid swallowing it
if (err) throw err;
}
function isRequest(stream) {
return stream.setHeader && typeof stream.abort === 'function';
}
function destroyer(stream, reading, writing, callback) {
callback = once(callback);
var closed = false;
stream.on('close', function () {
closed = true;
});
if (eos === undefined) eos = require('./end-of-stream');
eos(stream, {
readable: reading,
writable: writing
}, function (err) {
if (err) return callback(err);
closed = true;
callback();
});
var destroyed = false;
return function (err) {
if (closed) return;
if (destroyed) return;
destroyed = true;
// request.destroy just do .end - .abort is what we want
if (isRequest(stream)) return stream.abort();
if (typeof stream.destroy === 'function') return stream.destroy();
callback(err || new ERR_STREAM_DESTROYED('pipe'));
};
}
function call(fn) {
fn();
}
function pipe(from, to) {
return from.pipe(to);
}
function popCallback(streams) {
if (!streams.length) return noop;
if (typeof streams[streams.length - 1] !== 'function') return noop;
return streams.pop();
}
function pipeline() {
for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
streams[_key] = arguments[_key];
}
var callback = popCallback(streams);
if (Array.isArray(streams[0])) streams = streams[0];
if (streams.length < 2) {
throw new ERR_MISSING_ARGS('streams');
}
var error;
var destroys = streams.map(function (stream, i) {
var reading = i < streams.length - 1;
var writing = i > 0;
return destroyer(stream, reading, writing, function (err) {
if (!error) error = err;
if (err) destroys.forEach(call);
if (reading) return;
destroys.forEach(call);
callback(error);
});
});
return streams.reduce(pipe);
}
module.exports = pipeline;

View file

@ -0,0 +1,22 @@
'use strict';
var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
function highWaterMarkFrom(options, isDuplex, duplexKey) {
return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
}
function getHighWaterMark(state, options, duplexKey, isDuplex) {
var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
if (hwm != null) {
if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
var name = isDuplex ? duplexKey : 'highWaterMark';
throw new ERR_INVALID_OPT_VALUE(name, hwm);
}
return Math.floor(hwm);
}
// Default value
return state.objectMode ? 16 : 16 * 1024;
}
module.exports = {
getHighWaterMark: getHighWaterMark
};

View file

@ -0,0 +1 @@
module.exports = require('events').EventEmitter;

View file

@ -0,0 +1 @@
module.exports = require('stream');

View file

@ -0,0 +1,68 @@
{
"name": "readable-stream",
"version": "3.6.2",
"description": "Streams3, a user-land copy of the stream library from Node.js",
"main": "readable.js",
"engines": {
"node": ">= 6"
},
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"devDependencies": {
"@babel/cli": "^7.2.0",
"@babel/core": "^7.2.0",
"@babel/polyfill": "^7.0.0",
"@babel/preset-env": "^7.2.0",
"airtap": "0.0.9",
"assert": "^1.4.0",
"bl": "^2.0.0",
"deep-strict-equal": "^0.2.0",
"events.once": "^2.0.2",
"glob": "^7.1.2",
"gunzip-maybe": "^1.4.1",
"hyperquest": "^2.1.3",
"lolex": "^2.6.0",
"nyc": "^11.0.0",
"pump": "^3.0.0",
"rimraf": "^2.6.2",
"tap": "^12.0.0",
"tape": "^4.9.0",
"tar-fs": "^1.16.2",
"util-promisify": "^2.1.0"
},
"scripts": {
"test": "tap -J --no-esm test/parallel/*.js test/ours/*.js",
"ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap",
"test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js",
"test-browser-local": "airtap --open --local -- test/browser.js",
"cover": "nyc npm test",
"report": "nyc report --reporter=lcov",
"update-browser-errors": "babel -o errors-browser.js errors.js"
},
"repository": {
"type": "git",
"url": "git://github.com/nodejs/readable-stream"
},
"keywords": [
"readable",
"stream",
"pipe"
],
"browser": {
"util": false,
"worker_threads": false,
"./errors": "./errors-browser.js",
"./readable.js": "./readable-browser.js",
"./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js",
"./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js"
},
"nyc": {
"include": [
"lib/**.js"
]
},
"license": "MIT"
}

View file

@ -0,0 +1,9 @@
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
exports.finished = require('./lib/internal/streams/end-of-stream.js');
exports.pipeline = require('./lib/internal/streams/pipeline.js');

View file

@ -0,0 +1,16 @@
var Stream = require('stream');
if (process.env.READABLE_STREAM === 'disable' && Stream) {
module.exports = Stream.Readable;
Object.assign(module.exports, Stream);
module.exports.Stream = Stream;
} else {
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = Stream || exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
exports.finished = require('./lib/internal/streams/end-of-stream.js');
exports.pipeline = require('./lib/internal/streams/pipeline.js');
}

74
node_modules/winston/package.json generated vendored Normal file
View file

@ -0,0 +1,74 @@
{
"name": "winston",
"description": "A logger for just about everything.",
"version": "3.16.0",
"author": "Charlie Robbins <charlie.robbins@gmail.com>",
"maintainers": [
"David Hyde <dabh@alumni.stanford.edu>"
],
"repository": {
"type": "git",
"url": "https://github.com/winstonjs/winston.git"
},
"keywords": [
"winston",
"logger",
"logging",
"logs",
"sysadmin",
"bunyan",
"pino",
"loglevel",
"tools",
"json",
"stream"
],
"dependencies": {
"@dabh/diagnostics": "^2.0.2",
"@colors/colors": "^1.6.0",
"async": "^3.2.3",
"is-stream": "^2.0.0",
"logform": "^2.6.0",
"one-time": "^1.0.0",
"readable-stream": "^3.4.0",
"safe-stable-stringify": "^2.3.1",
"stack-trace": "0.0.x",
"triple-beam": "^1.3.0",
"winston-transport": "^4.7.0"
},
"devDependencies": {
"@babel/cli": "^7.23.9",
"@babel/core": "^7.24.0",
"@babel/preset-env": "^7.24.0",
"@dabh/eslint-config-populist": "^4.4.0",
"@types/node": "^20.11.24",
"abstract-winston-transport": "^0.5.1",
"assume": "^2.2.0",
"cross-spawn-async": "^2.2.5",
"eslint": "^8.57.0",
"hock": "^1.4.1",
"mocha": "^10.3.0",
"nyc": "^17.1.0",
"rimraf": "5.0.1",
"split2": "^4.1.0",
"std-mocks": "^2.0.0",
"through2": "^4.0.2",
"winston-compat": "^0.1.5"
},
"main": "./lib/winston.js",
"browser": "./dist/winston",
"types": "./index.d.ts",
"scripts": {
"lint": "eslint lib/*.js lib/winston/*.js lib/winston/**/*.js --resolve-plugins-relative-to ./node_modules/@dabh/eslint-config-populist",
"test": "rimraf test/fixtures/logs/* && mocha",
"test:coverage": "nyc npm run test:unit",
"test:unit": "mocha test/unit",
"test:integration": "mocha test/integration",
"build": "rimraf dist && babel lib -d dist",
"prepublishOnly": "npm run build"
},
"engines": {
"node": ">= 12.0.0"
},
"license": "MIT"
}