= {\n source: src,\n data,\n };\n\n netEventLogger.silly(`netPromise > ${eventName} > RequestObj`);\n netEventLogger.silly(promiseRequest);\n\n const promiseResp: PromiseEventResp = (data: ServerPromiseResp
) => {\n const endTime = process.hrtime.bigint();\n const totalTime = Number(endTime - startTime) / 1e6;\n emitNet(respEventName, src, data);\n netEventLogger.silly(`Response Promise Event ${respEventName} (${totalTime}ms), Data >>`);\n netEventLogger.silly(data);\n };\n\n // In case the cb is a promise, we use Promise.resolve\n Promise.resolve(cb(promiseRequest, promiseResp)).catch((e) => {\n netEventLogger.error(\n `An error occured for a onNetPromise (${eventName}), Error: ${e.message}`,\n );\n\n promiseResp({ status: 'error', errorMsg: 'UNKNOWN_ERROR' });\n });\n });\n}\n","import { SessionStatus } from '@sentry/types';\nimport { dropUndefinedKeys, timestampInSeconds, uuid4 } from '@sentry/utils';\n/**\n * @inheritdoc\n */\nvar Session = /** @class */ (function () {\n function Session(context) {\n this.errors = 0;\n this.sid = uuid4();\n this.duration = 0;\n this.status = SessionStatus.Ok;\n this.init = true;\n this.ignoreDuration = false;\n // Both timestamp and started are in seconds since the UNIX epoch.\n var startingTime = timestampInSeconds();\n this.timestamp = startingTime;\n this.started = startingTime;\n if (context) {\n this.update(context);\n }\n }\n /** JSDoc */\n // eslint-disable-next-line complexity\n Session.prototype.update = function (context) {\n if (context === void 0) { context = {}; }\n if (context.user) {\n if (!this.ipAddress && context.user.ip_address) {\n this.ipAddress = context.user.ip_address;\n }\n if (!this.did && !context.did) {\n this.did = context.user.id || context.user.email || context.user.username;\n }\n }\n this.timestamp = context.timestamp || timestampInSeconds();\n if (context.ignoreDuration) {\n this.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n this.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n this.init = context.init;\n }\n if (!this.did && context.did) {\n this.did = \"\" + context.did;\n }\n if (typeof context.started === 'number') {\n this.started = context.started;\n }\n if (this.ignoreDuration) {\n this.duration = undefined;\n }\n else if (typeof context.duration === 'number') {\n this.duration = context.duration;\n }\n else {\n var duration = this.timestamp - this.started;\n this.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n this.release = context.release;\n }\n if (context.environment) {\n this.environment = context.environment;\n }\n if (!this.ipAddress && context.ipAddress) {\n this.ipAddress = context.ipAddress;\n }\n if (!this.userAgent && context.userAgent) {\n this.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n this.errors = context.errors;\n }\n if (context.status) {\n this.status = context.status;\n }\n };\n /** JSDoc */\n Session.prototype.close = function (status) {\n if (status) {\n this.update({ status: status });\n }\n else if (this.status === SessionStatus.Ok) {\n this.update({ status: SessionStatus.Exited });\n }\n else {\n this.update();\n }\n };\n /** JSDoc */\n Session.prototype.toJSON = function () {\n return dropUndefinedKeys({\n sid: \"\" + this.sid,\n init: this.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(this.started * 1000).toISOString(),\n timestamp: new Date(this.timestamp * 1000).toISOString(),\n status: this.status,\n errors: this.errors,\n did: typeof this.did === 'number' || typeof this.did === 'string' ? \"\" + this.did : undefined,\n duration: this.duration,\n attrs: dropUndefinedKeys({\n release: this.release,\n environment: this.environment,\n ip_address: this.ipAddress,\n user_agent: this.userAgent,\n }),\n });\n };\n return Session;\n}());\nexport { Session };\n//# sourceMappingURL=session.js.map","import { __assign, __read, __spread } from \"tslib\";\n/* eslint-disable max-lines */\nimport { SessionStatus, } from '@sentry/types';\nimport { consoleSandbox, dateTimestampInSeconds, getGlobalObject, isNodeEnv, logger, uuid4 } from '@sentry/utils';\nimport { Scope } from './scope';\nimport { Session } from './session';\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nexport var API_VERSION = 4;\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nvar DEFAULT_BREADCRUMBS = 100;\n/**\n * @inheritDoc\n */\nvar Hub = /** @class */ (function () {\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n function Hub(client, scope, _version) {\n if (scope === void 0) { scope = new Scope(); }\n if (_version === void 0) { _version = API_VERSION; }\n this._version = _version;\n /** Is a {@link Layer}[] containing the client and scope */\n this._stack = [{}];\n this.getStackTop().scope = scope;\n if (client) {\n this.bindClient(client);\n }\n }\n /**\n * @inheritDoc\n */\n Hub.prototype.isOlderThan = function (version) {\n return this._version < version;\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.bindClient = function (client) {\n var top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.pushScope = function () {\n // We want to clone the content of prev scope\n var scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope: scope,\n });\n return scope;\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.popScope = function () {\n if (this.getStack().length <= 1)\n return false;\n return !!this.getStack().pop();\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.withScope = function (callback) {\n var scope = this.pushScope();\n try {\n callback(scope);\n }\n finally {\n this.popScope();\n }\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.getClient = function () {\n return this.getStackTop().client;\n };\n /** Returns the scope of the top stack. */\n Hub.prototype.getScope = function () {\n return this.getStackTop().scope;\n };\n /** Returns the scope stack for domains or the process. */\n Hub.prototype.getStack = function () {\n return this._stack;\n };\n /** Returns the topmost scope layer in the order domain > local > process. */\n Hub.prototype.getStackTop = function () {\n return this._stack[this._stack.length - 1];\n };\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n Hub.prototype.captureException = function (exception, hint) {\n var eventId = (this._lastEventId = uuid4());\n var finalHint = hint;\n // If there's no explicit hint provided, mimic the same thing that would happen\n // in the minimal itself to create a consistent behavior.\n // We don't do this in the client, as it's the lowest level API, and doing this,\n // would prevent user from having full control over direct calls.\n if (!hint) {\n var syntheticException = void 0;\n try {\n throw new Error('Sentry syntheticException');\n }\n catch (exception) {\n syntheticException = exception;\n }\n finalHint = {\n originalException: exception,\n syntheticException: syntheticException,\n };\n }\n this._invokeClient('captureException', exception, __assign(__assign({}, finalHint), { event_id: eventId }));\n return eventId;\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.captureMessage = function (message, level, hint) {\n var eventId = (this._lastEventId = uuid4());\n var finalHint = hint;\n // If there's no explicit hint provided, mimic the same thing that would happen\n // in the minimal itself to create a consistent behavior.\n // We don't do this in the client, as it's the lowest level API, and doing this,\n // would prevent user from having full control over direct calls.\n if (!hint) {\n var syntheticException = void 0;\n try {\n throw new Error(message);\n }\n catch (exception) {\n syntheticException = exception;\n }\n finalHint = {\n originalException: message,\n syntheticException: syntheticException,\n };\n }\n this._invokeClient('captureMessage', message, level, __assign(__assign({}, finalHint), { event_id: eventId }));\n return eventId;\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.captureEvent = function (event, hint) {\n var eventId = uuid4();\n if (event.type !== 'transaction') {\n this._lastEventId = eventId;\n }\n this._invokeClient('captureEvent', event, __assign(__assign({}, hint), { event_id: eventId }));\n return eventId;\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.lastEventId = function () {\n return this._lastEventId;\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.addBreadcrumb = function (breadcrumb, hint) {\n var _a = this.getStackTop(), scope = _a.scope, client = _a.client;\n if (!scope || !client)\n return;\n // eslint-disable-next-line @typescript-eslint/unbound-method\n var _b = (client.getOptions && client.getOptions()) || {}, _c = _b.beforeBreadcrumb, beforeBreadcrumb = _c === void 0 ? null : _c, _d = _b.maxBreadcrumbs, maxBreadcrumbs = _d === void 0 ? DEFAULT_BREADCRUMBS : _d;\n if (maxBreadcrumbs <= 0)\n return;\n var timestamp = dateTimestampInSeconds();\n var mergedBreadcrumb = __assign({ timestamp: timestamp }, breadcrumb);\n var finalBreadcrumb = beforeBreadcrumb\n ? consoleSandbox(function () { return beforeBreadcrumb(mergedBreadcrumb, hint); })\n : mergedBreadcrumb;\n if (finalBreadcrumb === null)\n return;\n scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.setUser = function (user) {\n var scope = this.getScope();\n if (scope)\n scope.setUser(user);\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.setTags = function (tags) {\n var scope = this.getScope();\n if (scope)\n scope.setTags(tags);\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.setExtras = function (extras) {\n var scope = this.getScope();\n if (scope)\n scope.setExtras(extras);\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.setTag = function (key, value) {\n var scope = this.getScope();\n if (scope)\n scope.setTag(key, value);\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.setExtra = function (key, extra) {\n var scope = this.getScope();\n if (scope)\n scope.setExtra(key, extra);\n };\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Hub.prototype.setContext = function (name, context) {\n var scope = this.getScope();\n if (scope)\n scope.setContext(name, context);\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.configureScope = function (callback) {\n var _a = this.getStackTop(), scope = _a.scope, client = _a.client;\n if (scope && client) {\n callback(scope);\n }\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.run = function (callback) {\n var oldHub = makeMain(this);\n try {\n callback(this);\n }\n finally {\n makeMain(oldHub);\n }\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.getIntegration = function (integration) {\n var client = this.getClient();\n if (!client)\n return null;\n try {\n return client.getIntegration(integration);\n }\n catch (_oO) {\n logger.warn(\"Cannot retrieve integration \" + integration.id + \" from the current Hub\");\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.startSpan = function (context) {\n return this._callExtensionMethod('startSpan', context);\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.startTransaction = function (context, customSamplingContext) {\n return this._callExtensionMethod('startTransaction', context, customSamplingContext);\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.traceHeaders = function () {\n return this._callExtensionMethod('traceHeaders');\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.captureSession = function (endSession) {\n if (endSession === void 0) { endSession = false; }\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n // only send the update\n this._sendSessionUpdate();\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.endSession = function () {\n var _a, _b, _c, _d, _e;\n (_c = (_b = (_a = this.getStackTop()) === null || _a === void 0 ? void 0 : _a.scope) === null || _b === void 0 ? void 0 : _b.getSession()) === null || _c === void 0 ? void 0 : _c.close();\n this._sendSessionUpdate();\n // the session is over; take it off of the scope\n (_e = (_d = this.getStackTop()) === null || _d === void 0 ? void 0 : _d.scope) === null || _e === void 0 ? void 0 : _e.setSession();\n };\n /**\n * @inheritDoc\n */\n Hub.prototype.startSession = function (context) {\n var _a = this.getStackTop(), scope = _a.scope, client = _a.client;\n var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment;\n // Will fetch userAgent if called from browser sdk\n var global = getGlobalObject();\n var userAgent = (global.navigator || {}).userAgent;\n var session = new Session(__assign(__assign(__assign({ release: release,\n environment: environment }, (scope && { user: scope.getUser() })), (userAgent && { userAgent: userAgent })), context));\n if (scope) {\n // End existing session if there's one\n var currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === SessionStatus.Ok) {\n currentSession.update({ status: SessionStatus.Exited });\n }\n this.endSession();\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n }\n return session;\n };\n /**\n * Sends the current Session on the scope\n */\n Hub.prototype._sendSessionUpdate = function () {\n var _a = this.getStackTop(), scope = _a.scope, client = _a.client;\n if (!scope)\n return;\n var session = scope.getSession && scope.getSession();\n if (session) {\n if (client && client.captureSession) {\n client.captureSession(session);\n }\n }\n };\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Hub.prototype._invokeClient = function (method) {\n var _a;\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n var _b = this.getStackTop(), scope = _b.scope, client = _b.client;\n if (client && client[method]) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (_a = client)[method].apply(_a, __spread(args, [scope]));\n }\n };\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Hub.prototype._callExtensionMethod = function (method) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n var carrier = getMainCarrier();\n var sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n logger.warn(\"Extension method \" + method + \" couldn't be found, doing nothing.\");\n };\n return Hub;\n}());\nexport { Hub };\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nexport function getMainCarrier() {\n var carrier = getGlobalObject();\n carrier.__SENTRY__ = carrier.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return carrier;\n}\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nexport function makeMain(hub) {\n var registry = getMainCarrier();\n var oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nexport function getCurrentHub() {\n // Get main carrier (global for every environment)\n var registry = getMainCarrier();\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n // Prefer domains over global if they are there (applicable only to Node environment)\n if (isNodeEnv()) {\n return getHubFromActiveDomain(registry);\n }\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n/**\n * Returns the active domain, if one exists\n * @deprecated No longer used; remove in v7\n * @returns The domain, or undefined if there is no active domain\n */\n// eslint-disable-next-line deprecation/deprecation\nexport function getActiveDomain() {\n logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.');\n var sentry = getMainCarrier().__SENTRY__;\n return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active;\n}\n/**\n * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist\n * @returns discovered hub\n */\nfunction getHubFromActiveDomain(registry) {\n var _a, _b, _c;\n try {\n var activeDomain = (_c = (_b = (_a = getMainCarrier().__SENTRY__) === null || _a === void 0 ? void 0 : _a.extensions) === null || _b === void 0 ? void 0 : _b.domain) === null || _c === void 0 ? void 0 : _c.active;\n // If there's no active domain, just return global hub\n if (!activeDomain) {\n return getHubFromCarrier(registry);\n }\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(API_VERSION)) {\n var registryHubTopStack = getHubFromCarrier(registry).getStackTop();\n setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, Scope.clone(registryHubTopStack.scope)));\n }\n // Return hub that lives on a domain\n return getHubFromCarrier(activeDomain);\n }\n catch (_Oo) {\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n }\n}\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier) {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nexport function getHubFromCarrier(carrier) {\n if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub)\n return carrier.__SENTRY__.hub;\n carrier.__SENTRY__ = carrier.__SENTRY__ || {};\n carrier.__SENTRY__.hub = new Hub();\n return carrier.__SENTRY__.hub;\n}\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nexport function setHubOnCarrier(carrier, hub) {\n if (!carrier)\n return false;\n carrier.__SENTRY__ = carrier.__SENTRY__ || {};\n carrier.__SENTRY__.hub = hub;\n return true;\n}\n//# sourceMappingURL=hub.js.map","'use strict';\n\nconst core = require('./index.js');\nconst EventEmitter = require('events').EventEmitter;\n\nfunction makeDoneCb(resolve, reject, localErr) {\n return function (err, rows, fields) {\n if (err) {\n localErr.message = err.message;\n localErr.code = err.code;\n localErr.errno = err.errno;\n localErr.sql = err.sql;\n localErr.sqlState = err.sqlState;\n localErr.sqlMessage = err.sqlMessage;\n reject(localErr);\n } else {\n resolve([rows, fields]);\n }\n };\n}\n\nfunction inheritEvents(source, target, events) {\n const listeners = {};\n target\n .on('newListener', eventName => {\n if (events.indexOf(eventName) >= 0 && !target.listenerCount(eventName)) {\n source.on(\n eventName,\n (listeners[eventName] = function () {\n const args = [].slice.call(arguments);\n args.unshift(eventName);\n\n target.emit.apply(target, args);\n })\n );\n }\n })\n .on('removeListener', eventName => {\n if (events.indexOf(eventName) >= 0 && !target.listenerCount(eventName)) {\n source.removeListener(eventName, listeners[eventName]);\n delete listeners[eventName];\n }\n });\n}\n\nclass PromisePreparedStatementInfo {\n constructor(statement, promiseImpl) {\n this.statement = statement;\n this.Promise = promiseImpl;\n }\n\n execute(parameters) {\n const s = this.statement;\n const localErr = new Error();\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n if (parameters) {\n s.execute(parameters, done);\n } else {\n s.execute(done);\n }\n });\n }\n\n close() {\n return new this.Promise(resolve => {\n this.statement.close();\n resolve();\n });\n }\n}\n\nclass PromiseConnection extends EventEmitter {\n constructor(connection, promiseImpl) {\n super();\n this.connection = connection;\n this.Promise = promiseImpl || Promise;\n inheritEvents(connection, this, [\n 'error',\n 'drain',\n 'connect',\n 'end',\n 'enqueue'\n ]);\n }\n\n release() {\n this.connection.release();\n }\n\n query(query, params) {\n const c = this.connection;\n const localErr = new Error();\n if (typeof params === 'function') {\n throw new Error(\n 'Callback function is not available with promise clients.'\n );\n }\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n if (params !== undefined) {\n c.query(query, params, done);\n } else {\n c.query(query, done);\n }\n });\n }\n\n execute(query, params) {\n const c = this.connection;\n const localErr = new Error();\n if (typeof params === 'function') {\n throw new Error(\n 'Callback function is not available with promise clients.'\n );\n }\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n if (params !== undefined) {\n c.execute(query, params, done);\n } else {\n c.execute(query, done);\n }\n });\n }\n\n end() {\n return new this.Promise(resolve => {\n this.connection.end(resolve);\n });\n }\n\n beginTransaction() {\n const c = this.connection;\n const localErr = new Error();\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n c.beginTransaction(done);\n });\n }\n\n commit() {\n const c = this.connection;\n const localErr = new Error();\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n c.commit(done);\n });\n }\n\n rollback() {\n const c = this.connection;\n const localErr = new Error();\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n c.rollback(done);\n });\n }\n\n ping() {\n const c = this.connection;\n const localErr = new Error();\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n c.ping(done);\n });\n }\n\n connect() {\n const c = this.connection;\n const localErr = new Error();\n return new this.Promise((resolve, reject) => {\n c.connect((err, param) => {\n if (err) {\n localErr.message = err.message;\n localErr.code = err.code;\n localErr.errno = err.errno;\n localErr.sqlState = err.sqlState;\n localErr.sqlMessage = err.sqlMessage;\n reject(localErr);\n } else {\n resolve(param);\n }\n });\n });\n }\n\n prepare(options) {\n const c = this.connection;\n const promiseImpl = this.Promise;\n const localErr = new Error();\n return new this.Promise((resolve, reject) => {\n c.prepare(options, (err, statement) => {\n if (err) {\n localErr.message = err.message;\n localErr.code = err.code;\n localErr.errno = err.errno;\n localErr.sqlState = err.sqlState;\n localErr.sqlMessage = err.sqlMessage;\n reject(localErr);\n } else {\n const wrappedStatement = new PromisePreparedStatementInfo(\n statement,\n promiseImpl\n );\n resolve(wrappedStatement);\n }\n });\n });\n }\n\n changeUser(options) {\n const c = this.connection;\n const localErr = new Error();\n return new this.Promise((resolve, reject) => {\n c.changeUser(options, err => {\n if (err) {\n localErr.message = err.message;\n localErr.code = err.code;\n localErr.errno = err.errno;\n localErr.sqlState = err.sqlState;\n localErr.sqlMessage = err.sqlMessage;\n reject(localErr);\n } else {\n resolve();\n }\n });\n });\n }\n\n get config() {\n return this.connection.config;\n }\n\n get threadId() {\n return this.connection.threadId;\n }\n}\n\nfunction createConnection(opts) {\n const coreConnection = core.createConnection(opts);\n const createConnectionErr = new Error();\n const thePromise = opts.Promise || Promise;\n if (!thePromise) {\n throw new Error(\n 'no Promise implementation available.' +\n 'Use promise-enabled node version or pass userland Promise' +\n \" implementation as parameter, for example: { Promise: require('bluebird') }\"\n );\n }\n return new thePromise((resolve, reject) => {\n coreConnection.once('connect', () => {\n resolve(new PromiseConnection(coreConnection, thePromise));\n });\n coreConnection.once('error', err => {\n createConnectionErr.message = err.message;\n createConnectionErr.code = err.code;\n createConnectionErr.errno = err.errno;\n createConnectionErr.sqlState = err.sqlState;\n reject(createConnectionErr);\n });\n });\n}\n\n// note: the callback of \"changeUser\" is not called on success\n// hence there is no possibility to call \"resolve\"\n\n// patching PromiseConnection\n// create facade functions for prototype functions on \"Connection\" that are not yet\n// implemented with PromiseConnection\n\n// proxy synchronous functions only\n(function (functionsToWrap) {\n for (let i = 0; functionsToWrap && i < functionsToWrap.length; i++) {\n const func = functionsToWrap[i];\n\n if (\n typeof core.Connection.prototype[func] === 'function' &&\n PromiseConnection.prototype[func] === undefined\n ) {\n PromiseConnection.prototype[func] = (function factory(funcName) {\n return function () {\n return core.Connection.prototype[funcName].apply(\n this.connection,\n arguments\n );\n };\n })(func);\n }\n }\n})([\n // synchronous functions\n 'close',\n 'createBinlogStream',\n 'destroy',\n 'escape',\n 'escapeId',\n 'format',\n 'pause',\n 'pipe',\n 'resume',\n 'unprepare'\n]);\n\nclass PromisePoolConnection extends PromiseConnection {\n constructor(connection, promiseImpl) {\n super(connection, promiseImpl);\n }\n\n destroy() {\n return core.PoolConnection.prototype.destroy.apply(\n this.connection,\n arguments\n );\n }\n}\n\nclass PromisePool extends EventEmitter {\n constructor(pool, thePromise) {\n super();\n this.pool = pool;\n this.Promise = thePromise || Promise;\n inheritEvents(pool, this, ['acquire', 'connection', 'enqueue', 'release']);\n }\n\n getConnection() {\n const corePool = this.pool;\n return new this.Promise((resolve, reject) => {\n corePool.getConnection((err, coreConnection) => {\n if (err) {\n reject(err);\n } else {\n resolve(new PromisePoolConnection(coreConnection, this.Promise));\n }\n });\n });\n }\n\n query(sql, args) {\n const corePool = this.pool;\n const localErr = new Error();\n if (typeof args === 'function') {\n throw new Error(\n 'Callback function is not available with promise clients.'\n );\n }\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n if (args !== undefined) {\n corePool.query(sql, args, done);\n } else {\n corePool.query(sql, done);\n }\n });\n }\n\n execute(sql, args) {\n const corePool = this.pool;\n const localErr = new Error();\n if (typeof args === 'function') {\n throw new Error(\n 'Callback function is not available with promise clients.'\n );\n }\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n if (args) {\n corePool.execute(sql, args, done);\n } else {\n corePool.execute(sql, done);\n }\n });\n }\n\n end() {\n const corePool = this.pool;\n const localErr = new Error();\n return new this.Promise((resolve, reject) => {\n corePool.end(err => {\n if (err) {\n localErr.message = err.message;\n localErr.code = err.code;\n localErr.errno = err.errno;\n localErr.sqlState = err.sqlState;\n localErr.sqlMessage = err.sqlMessage;\n reject(localErr);\n } else {\n resolve();\n }\n });\n });\n }\n}\n\nfunction createPool(opts) {\n const corePool = core.createPool(opts);\n const thePromise = opts.Promise || Promise;\n if (!thePromise) {\n throw new Error(\n 'no Promise implementation available.' +\n 'Use promise-enabled node version or pass userland Promise' +\n \" implementation as parameter, for example: { Promise: require('bluebird') }\"\n );\n }\n\n return new PromisePool(corePool, thePromise);\n}\n\n(function (functionsToWrap) {\n for (let i = 0; functionsToWrap && i < functionsToWrap.length; i++) {\n const func = functionsToWrap[i];\n\n if (\n typeof core.Pool.prototype[func] === 'function' &&\n PromisePool.prototype[func] === undefined\n ) {\n PromisePool.prototype[func] = (function factory(funcName) {\n return function () {\n return core.Pool.prototype[funcName].apply(this.pool, arguments);\n };\n })(func);\n }\n }\n})([\n // synchronous functions\n 'escape',\n 'escapeId',\n 'format'\n]);\n\nclass PromisePoolCluster extends EventEmitter {\n constructor(poolCluster, thePromise) {\n super();\n this.poolCluster = poolCluster;\n this.Promise = thePromise || Promise;\n inheritEvents(poolCluster, this, ['acquire', 'connection', 'enqueue', 'release']);\n }\n\n getConnection() {\n const corePoolCluster = this.poolCluster;\n return new this.Promise((resolve, reject) => {\n corePoolCluster.getConnection((err, coreConnection) => {\n if (err) {\n reject(err);\n } else {\n resolve(new PromisePoolConnection(coreConnection, this.Promise));\n }\n });\n });\n }\n\n query(sql, args) {\n const corePoolCluster = this.poolCluster;\n const localErr = new Error();\n if (typeof args === 'function') {\n throw new Error(\n 'Callback function is not available with promise clients.'\n );\n }\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n corePoolCluster.query(sql, args, done);\n });\n }\n\n execute(sql, args) {\n const corePoolCluster = this.poolCluster;\n const localErr = new Error();\n if (typeof args === 'function') {\n throw new Error(\n 'Callback function is not available with promise clients.'\n );\n }\n return new this.Promise((resolve, reject) => {\n const done = makeDoneCb(resolve, reject, localErr);\n corePoolCluster.execute(sql, args, done);\n });\n }\n\n of(pattern, selector) {\n return new PromisePoolCluster(\n this.poolCluster.of(pattern, selector),\n this.Promise\n );\n }\n\n end() {\n const corePoolCluster = this.poolCluster;\n const localErr = new Error();\n return new this.Promise((resolve, reject) => {\n corePoolCluster.end(err => {\n if (err) {\n localErr.message = err.message;\n localErr.code = err.code;\n localErr.errno = err.errno;\n localErr.sqlState = err.sqlState;\n localErr.sqlMessage = err.sqlMessage;\n reject(localErr);\n } else {\n resolve();\n }\n });\n });\n }\n}\n\n/**\n * proxy poolCluster synchronous functions\n */\n(function (functionsToWrap) {\n for (let i = 0; functionsToWrap && i < functionsToWrap.length; i++) {\n const func = functionsToWrap[i];\n\n if (\n typeof core.PoolCluster.prototype[func] === 'function' &&\n PromisePoolCluster.prototype[func] === undefined\n ) {\n PromisePoolCluster.prototype[func] = (function factory(funcName) {\n return function () {\n return core.PoolCluster.prototype[funcName].apply(this.poolCluster, arguments);\n };\n })(func);\n }\n }\n})([\n 'add'\n]);\n\nfunction createPoolCluster(opts) {\n const corePoolCluster = core.createPoolCluster(opts);\n const thePromise = (opts && opts.Promise) || Promise;\n if (!thePromise) {\n throw new Error(\n 'no Promise implementation available.' +\n 'Use promise-enabled node version or pass userland Promise' +\n \" implementation as parameter, for example: { Promise: require('bluebird') }\"\n );\n }\n return new PromisePoolCluster(corePoolCluster, thePromise);\n}\n\nexports.createConnection = createConnection;\nexports.createPool = createPool;\nexports.createPoolCluster = createPoolCluster;\nexports.escape = core.escape;\nexports.escapeId = core.escapeId;\nexports.format = core.format;\nexports.raw = core.raw;\nexports.PromisePool = PromisePool;\nexports.PromiseConnection = PromiseConnection;\nexports.PromisePoolConnection = PromisePoolConnection;\n","module.exports = require(\"buffer\");","'use strict';\n\n// Manually extracted from mysql-5.5.23/include/mysql_com.h\nexports.LONG_PASSWORD = 0x00000001; /* new more secure passwords */\nexports.FOUND_ROWS = 0x00000002; /* found instead of affected rows */\nexports.LONG_FLAG = 0x00000004; /* get all column flags */\nexports.CONNECT_WITH_DB = 0x00000008; /* one can specify db on connect */\nexports.NO_SCHEMA = 0x00000010; /* don't allow database.table.column */\nexports.COMPRESS = 0x00000020; /* can use compression protocol */\nexports.ODBC = 0x00000040; /* odbc client */\nexports.LOCAL_FILES = 0x00000080; /* can use LOAD DATA LOCAL */\nexports.IGNORE_SPACE = 0x00000100; /* ignore spaces before '' */\nexports.PROTOCOL_41 = 0x00000200; /* new 4.1 protocol */\nexports.INTERACTIVE = 0x00000400; /* this is an interactive client */\nexports.SSL = 0x00000800; /* switch to ssl after handshake */\nexports.IGNORE_SIGPIPE = 0x00001000; /* IGNORE sigpipes */\nexports.TRANSACTIONS = 0x00002000; /* client knows about transactions */\nexports.RESERVED = 0x00004000; /* old flag for 4.1 protocol */\nexports.SECURE_CONNECTION = 0x00008000; /* new 4.1 authentication */\nexports.MULTI_STATEMENTS = 0x00010000; /* enable/disable multi-stmt support */\nexports.MULTI_RESULTS = 0x00020000; /* enable/disable multi-results */\nexports.PS_MULTI_RESULTS = 0x00040000; /* multi-results in ps-protocol */\nexports.PLUGIN_AUTH = 0x00080000; /* client supports plugin authentication */\nexports.CONNECT_ATTRS = 0x00100000; /* permits connection attributes */\nexports.PLUGIN_AUTH_LENENC_CLIENT_DATA = 0x00200000; /* Understands length-encoded integer for auth response data in Protocol::HandshakeResponse41. */\nexports.CAN_HANDLE_EXPIRED_PASSWORDS = 0x00400000; /* Announces support for expired password extension. */\nexports.SESSION_TRACK = 0x00800000; /* Can set SERVER_SESSION_STATE_CHANGED in the Status Flags and send session-state change data after a OK packet. */\nexports.DEPRECATE_EOF = 0x01000000; /* Can send OK after a Text Resultset. */\n\nexports.SSL_VERIFY_SERVER_CERT = 0x40000000;\nexports.REMEMBER_OPTIONS = 0x80000000;\n","'use strict';\n\nconst codes = {};\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n\n function getMessage (arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message\n } else {\n return message(arg1, arg2, arg3)\n }\n }\n\n class NodeError extends Base {\n constructor (arg1, arg2, arg3) {\n super(getMessage(arg1, arg2, arg3));\n }\n }\n\n NodeError.prototype.name = Base.name;\n NodeError.prototype.code = code;\n\n codes[code] = NodeError;\n}\n\n// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n const len = expected.length;\n expected = expected.map((i) => String(i));\n if (len > 2) {\n return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +\n expected[len - 1];\n } else if (len === 2) {\n return `one of ${thing} ${expected[0]} or ${expected[1]}`;\n } else {\n return `of ${thing} ${expected[0]}`;\n }\n } else {\n return `of ${thing} ${String(expected)}`;\n }\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\nfunction startsWith(str, search, pos) {\n\treturn str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\nfunction endsWith(str, search, this_len) {\n\tif (this_len === undefined || this_len > str.length) {\n\t\tthis_len = str.length;\n\t}\n\treturn str.substring(this_len - search.length, this_len) === search;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {\n return 'The value \"' + value + '\" is invalid for option \"' + name + '\"'\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n // determiner: 'must be' or 'must not be'\n let determiner;\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n let msg;\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;\n } else {\n const type = includes(name, '.') ? 'property' : 'argument';\n msg = `The \"${name}\" ${type} ${determiner} ${oneOf(expected, 'type')}`;\n }\n\n msg += `. Received type ${typeof actual}`;\n return msg;\n}, TypeError);\ncreateErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');\ncreateErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {\n return 'The ' + name + ' method is not implemented'\n});\ncreateErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');\ncreateErrorType('ERR_STREAM_DESTROYED', function (name) {\n return 'Cannot call ' + name + ' after a stream was destroyed';\n});\ncreateErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');\ncreateErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');\ncreateErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');\ncreateErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);\ncreateErrorType('ERR_UNKNOWN_ENCODING', function (arg) {\n return 'Unknown encoding: ' + arg\n}, TypeError);\ncreateErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');\n\nmodule.exports.codes = codes;\n","module.exports = require(\"http\");","module.exports = require(\"https\");","import { __assign, __read, __spread } from \"tslib\";\nimport { getMainCarrier } from '@sentry/hub';\nimport { TransactionSamplingMethod, } from '@sentry/types';\nimport { dynamicRequire, isNodeEnv, loadModule, logger } from '@sentry/utils';\nimport { registerErrorInstrumentation } from './errors';\nimport { IdleTransaction } from './idletransaction';\nimport { Transaction } from './transaction';\nimport { hasTracingEnabled } from './utils';\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders() {\n var scope = this.getScope();\n if (scope) {\n var span = scope.getSpan();\n if (span) {\n return {\n 'sentry-trace': span.toTraceparent(),\n };\n }\n }\n return {};\n}\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * @param hub: The hub off of which to read config options\n * @param transaction: The transaction needing a sampling decision\n * @param samplingContext: Default and user-provided data which may be used to help make the decision\n *\n * @returns The given transaction with its `sampled` value set\n */\nfunction sample(transaction, options, samplingContext) {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n transactionSampling: { method: TransactionSamplingMethod.Explicit },\n });\n return transaction;\n }\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should\n // work; prefer the hook if so\n var sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler(samplingContext);\n transaction.setMetadata({\n transactionSampling: {\n method: TransactionSamplingMethod.Sampler,\n // cast to number in case it's a boolean\n rate: Number(sampleRate),\n },\n });\n }\n else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n transaction.setMetadata({\n transactionSampling: { method: TransactionSamplingMethod.Inheritance },\n });\n }\n else {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n transactionSampling: {\n method: TransactionSamplingMethod.Rate,\n // cast to number in case it's a boolean\n rate: Number(sampleRate),\n },\n });\n }\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n logger.warn(\"[Tracing] Discarding transaction because of invalid sample rate.\");\n transaction.sampled = false;\n return transaction;\n }\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!sampleRate) {\n logger.log(\"[Tracing] Discarding transaction because \" + (typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'));\n transaction.sampled = false;\n return transaction;\n }\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < sampleRate;\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n logger.log(\"[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = \" + Number(sampleRate) + \")\");\n return transaction;\n }\n logger.log(\"[Tracing] starting \" + transaction.op + \" transaction - \" + transaction.name);\n return transaction;\n}\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate) {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n logger.warn(\"[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got \" + JSON.stringify(rate) + \" of type \" + JSON.stringify(typeof rate) + \".\");\n return false;\n }\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n logger.warn(\"[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got \" + rate + \".\");\n return false;\n }\n return true;\n}\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(transactionContext, customSamplingContext) {\n var _a, _b;\n var options = ((_a = this.getClient()) === null || _a === void 0 ? void 0 : _a.getOptions()) || {};\n var transaction = new Transaction(transactionContext, this);\n transaction = sample(transaction, options, __assign({ parentSampled: transactionContext.parentSampled, transactionContext: transactionContext }, customSamplingContext));\n if (transaction.sampled) {\n transaction.initSpanRecorder((_b = options._experiments) === null || _b === void 0 ? void 0 : _b.maxSpans);\n }\n return transaction;\n}\n/**\n * Create new idle transaction.\n */\nexport function startIdleTransaction(hub, transactionContext, idleTimeout, onScope, customSamplingContext) {\n var _a, _b;\n var options = ((_a = hub.getClient()) === null || _a === void 0 ? void 0 : _a.getOptions()) || {};\n var transaction = new IdleTransaction(transactionContext, hub, idleTimeout, onScope);\n transaction = sample(transaction, options, __assign({ parentSampled: transactionContext.parentSampled, transactionContext: transactionContext }, customSamplingContext));\n if (transaction.sampled) {\n transaction.initSpanRecorder((_b = options._experiments) === null || _b === void 0 ? void 0 : _b.maxSpans);\n }\n return transaction;\n}\n/**\n * @private\n */\nexport function _addTracingExtensions() {\n var carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n}\n/**\n * @private\n */\nfunction _autoloadDatabaseIntegrations() {\n var carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n var packageToIntegrationMapping = {\n mongodb: function () {\n var integration = dynamicRequire(module, './integrations/node/mongo');\n return new integration.Mongo();\n },\n mongoose: function () {\n var integration = dynamicRequire(module, './integrations/node/mongo');\n return new integration.Mongo({ mongoose: true });\n },\n mysql: function () {\n var integration = dynamicRequire(module, './integrations/node/mysql');\n return new integration.Mysql();\n },\n pg: function () {\n var integration = dynamicRequire(module, './integrations/node/postgres');\n return new integration.Postgres();\n },\n };\n var mappedPackages = Object.keys(packageToIntegrationMapping)\n .filter(function (moduleName) { return !!loadModule(moduleName); })\n .map(function (pkg) {\n try {\n return packageToIntegrationMapping[pkg]();\n }\n catch (e) {\n return undefined;\n }\n })\n .filter(function (p) { return p; });\n if (mappedPackages.length > 0) {\n carrier.__SENTRY__.integrations = __spread((carrier.__SENTRY__.integrations || []), mappedPackages);\n }\n}\n/**\n * This patches the global object and injects the Tracing extensions methods\n */\nexport function addExtensionMethods() {\n _addTracingExtensions();\n // Detect and automatically load specified integrations.\n if (isNodeEnv()) {\n _autoloadDatabaseIntegrations();\n }\n // If an error happens globally, we should make sure transaction status is set to error.\n registerErrorInstrumentation();\n}\n//# sourceMappingURL=hubextensions.js.map","import { __assign } from \"tslib\";\nimport { dropUndefinedKeys, timestampWithMs, uuid4 } from '@sentry/utils';\nimport { SpanStatus } from './spanstatus';\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nvar SpanRecorder = /** @class */ (function () {\n function SpanRecorder(maxlen) {\n if (maxlen === void 0) { maxlen = 1000; }\n this.spans = [];\n this._maxlen = maxlen;\n }\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n SpanRecorder.prototype.add = function (span) {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n }\n else {\n this.spans.push(span);\n }\n };\n return SpanRecorder;\n}());\nexport { SpanRecorder };\n/**\n * Span contains all data about a span\n */\nvar Span = /** @class */ (function () {\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n function Span(spanContext) {\n /**\n * @inheritDoc\n */\n this.traceId = uuid4();\n /**\n * @inheritDoc\n */\n this.spanId = uuid4().substring(16);\n /**\n * Timestamp in seconds when the span was created.\n */\n this.startTimestamp = timestampWithMs();\n /**\n * @inheritDoc\n */\n this.tags = {};\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.data = {};\n if (!spanContext) {\n return this;\n }\n if (spanContext.traceId) {\n this.traceId = spanContext.traceId;\n }\n if (spanContext.spanId) {\n this.spanId = spanContext.spanId;\n }\n if (spanContext.parentSpanId) {\n this.parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this.sampled = spanContext.sampled;\n }\n if (spanContext.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.data) {\n this.data = spanContext.data;\n }\n if (spanContext.tags) {\n this.tags = spanContext.tags;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.startTimestamp) {\n this.startTimestamp = spanContext.startTimestamp;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n }\n /**\n * @inheritDoc\n * @deprecated\n */\n Span.prototype.child = function (spanContext) {\n return this.startChild(spanContext);\n };\n /**\n * @inheritDoc\n */\n Span.prototype.startChild = function (spanContext) {\n var childSpan = new Span(__assign(__assign({}, spanContext), { parentSpanId: this.spanId, sampled: this.sampled, traceId: this.traceId }));\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n childSpan.transaction = this.transaction;\n return childSpan;\n };\n /**\n * @inheritDoc\n */\n Span.prototype.setTag = function (key, value) {\n var _a;\n this.tags = __assign(__assign({}, this.tags), (_a = {}, _a[key] = value, _a));\n return this;\n };\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n Span.prototype.setData = function (key, value) {\n var _a;\n this.data = __assign(__assign({}, this.data), (_a = {}, _a[key] = value, _a));\n return this;\n };\n /**\n * @inheritDoc\n */\n Span.prototype.setStatus = function (value) {\n this.status = value;\n return this;\n };\n /**\n * @inheritDoc\n */\n Span.prototype.setHttpStatus = function (httpStatus) {\n this.setTag('http.status_code', String(httpStatus));\n var spanStatus = SpanStatus.fromHttpCode(httpStatus);\n if (spanStatus !== SpanStatus.UnknownError) {\n this.setStatus(spanStatus);\n }\n return this;\n };\n /**\n * @inheritDoc\n */\n Span.prototype.isSuccess = function () {\n return this.status === SpanStatus.Ok;\n };\n /**\n * @inheritDoc\n */\n Span.prototype.finish = function (endTimestamp) {\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n };\n /**\n * @inheritDoc\n */\n Span.prototype.toTraceparent = function () {\n var sampledString = '';\n if (this.sampled !== undefined) {\n sampledString = this.sampled ? '-1' : '-0';\n }\n return this.traceId + \"-\" + this.spanId + sampledString;\n };\n /**\n * @inheritDoc\n */\n Span.prototype.toContext = function () {\n return dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n };\n /**\n * @inheritDoc\n */\n Span.prototype.updateWithContext = function (spanContext) {\n var _a, _b, _c, _d, _e;\n this.data = (_a = spanContext.data, (_a !== null && _a !== void 0 ? _a : {}));\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = (_b = spanContext.spanId, (_b !== null && _b !== void 0 ? _b : this.spanId));\n this.startTimestamp = (_c = spanContext.startTimestamp, (_c !== null && _c !== void 0 ? _c : this.startTimestamp));\n this.status = spanContext.status;\n this.tags = (_d = spanContext.tags, (_d !== null && _d !== void 0 ? _d : {}));\n this.traceId = (_e = spanContext.traceId, (_e !== null && _e !== void 0 ? _e : this.traceId));\n return this;\n };\n /**\n * @inheritDoc\n */\n Span.prototype.getTraceContext = function () {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n });\n };\n /**\n * @inheritDoc\n */\n Span.prototype.toJSON = function () {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n });\n };\n return Span;\n}());\nexport { Span };\n//# sourceMappingURL=span.js.map","import { isRegExp, isString } from './is';\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nexport function truncate(str, max) {\n if (max === void 0) { max = 0; }\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : str.substr(0, max) + \"...\";\n}\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nexport function snipLine(line, colno) {\n var newLine = line;\n var ll = newLine.length;\n if (ll <= 150) {\n return newLine;\n }\n if (colno > ll) {\n // eslint-disable-next-line no-param-reassign\n colno = ll;\n }\n var start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n var end = Math.min(start + 140, ll);\n if (end > ll - 5) {\n end = ll;\n }\n if (end === ll) {\n start = Math.max(end - 140, 0);\n }\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = \"'{snip} \" + newLine;\n }\n if (end < ll) {\n newLine += ' {snip}';\n }\n return newLine;\n}\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function safeJoin(input, delimiter) {\n if (!Array.isArray(input)) {\n return '';\n }\n var output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (var i = 0; i < input.length; i++) {\n var value = input[i];\n try {\n output.push(String(value));\n }\n catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n return output.join(delimiter);\n}\n/**\n * Checks if the value matches a regex or includes the string\n * @param value The string value to be checked against\n * @param pattern Either a regex or a string that must be contained in value\n */\nexport function isMatchingPattern(value, pattern) {\n if (!isString(value)) {\n return false;\n }\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (typeof pattern === 'string') {\n return value.indexOf(pattern) !== -1;\n }\n return false;\n}\n/**\n * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to\n * `new RegExp()`.\n *\n * Based on https://github.com/sindresorhus/escape-string-regexp. Vendored to a) reduce the size by skipping the runtime\n * type-checking, and b) ensure it gets down-compiled for old versions of Node (the published package only supports Node\n * 12+).\n *\n * @param regexString The string to escape\n * @returns An version of the string with all special regex characters escaped\n */\nexport function escapeStringForRegex(regexString) {\n // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems\n // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.\n return regexString.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&').replace(/-/g, '\\\\x2d');\n}\n//# sourceMappingURL=string.js.map","'use strict';\n\n/*\n4.1 authentication: (http://bazaar.launchpad.net/~mysql/mysql-server/5.5/view/head:/sql/password.c)\n\n SERVER: public_seed=create_random_string()\n send(public_seed)\n\n CLIENT: recv(public_seed)\n hash_stage1=sha1(\"password\")\n hash_stage2=sha1(hash_stage1)\n reply=xor(hash_stage1, sha1(public_seed,hash_stage2)\n\n // this three steps are done in scramble()\n\n send(reply)\n\n\n SERVER: recv(reply)\n hash_stage1=xor(reply, sha1(public_seed,hash_stage2))\n candidate_hash2=sha1(hash_stage1)\n check(candidate_hash2==hash_stage2)\n\nserver stores sha1(sha1(password)) ( hash_stag2)\n*/\n\nconst crypto = require('crypto');\n\nfunction sha1(msg, msg1, msg2) {\n const hash = crypto.createHash('sha1');\n hash.update(msg);\n if (msg1) {\n hash.update(msg1);\n }\n\n if (msg2) {\n hash.update(msg2);\n }\n\n return hash.digest();\n}\n\nfunction xor(a, b) {\n if (!Buffer.isBuffer(a)) {\n a = Buffer.from(a, 'binary');\n }\n\n if (!Buffer.isBuffer(b)) {\n b = Buffer.from(b, 'binary');\n }\n\n const result = Buffer.allocUnsafe(a.length);\n\n for (let i = 0; i < a.length; i++) {\n result[i] = a[i] ^ b[i];\n }\n return result;\n}\n\nexports.xor = xor;\n\nfunction token(password, scramble1, scramble2) {\n // TODO: use buffers (not sure why strings here)\n if (!password) {\n return Buffer.alloc(0);\n }\n const stage1 = sha1(password);\n return exports.calculateTokenFromPasswordSha(stage1, scramble1, scramble2);\n}\n\nexports.calculateTokenFromPasswordSha = function(\n passwordSha,\n scramble1,\n scramble2\n) {\n // we use AUTH 41 here, and we need only the bytes we just need.\n const authPluginData1 = scramble1.slice(0, 8);\n const authPluginData2 = scramble2.slice(0, 12);\n const stage2 = sha1(passwordSha);\n const stage3 = sha1(authPluginData1, authPluginData2, stage2);\n return xor(stage3, passwordSha);\n};\n\nexports.calculateToken = token;\n\nexports.verifyToken = function(publicSeed1, publicSeed2, token, doubleSha) {\n const hashStage1 = xor(token, sha1(publicSeed1, publicSeed2, doubleSha));\n const candidateHash2 = sha1(hashStage1);\n return candidateHash2.compare(doubleSha) === 0;\n};\n\nexports.doubleSha1 = function(password) {\n return sha1(sha1(password));\n};\n\nfunction xorRotating(a, seed) {\n if (!Buffer.isBuffer(a)) {\n a = Buffer.from(a, 'binary');\n }\n\n if (!Buffer.isBuffer(seed)) {\n seed = Buffer.from(seed, 'binary');\n }\n\n const result = Buffer.allocUnsafe(a.length);\n const seedLen = seed.length;\n\n for (let i = 0; i < a.length; i++) {\n result[i] = a[i] ^ seed[i % seedLen];\n }\n return result;\n}\nexports.xorRotating = xorRotating;\n","module.exports = stringify\nstringify.default = stringify\nstringify.stable = deterministicStringify\nstringify.stableStringify = deterministicStringify\n\nvar arr = []\nvar replacerStack = []\n\n// Regular stringify\nfunction stringify (obj, replacer, spacer) {\n decirc(obj, '', [], undefined)\n var res\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(obj, replacer, spacer)\n } else {\n res = JSON.stringify(obj, replaceGetterValues(replacer), spacer)\n }\n } catch (_) {\n return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')\n } finally {\n while (arr.length !== 0) {\n var part = arr.pop()\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3])\n } else {\n part[0][part[1]] = part[2]\n }\n }\n }\n return res\n}\nfunction decirc (val, k, stack, parent) {\n var i\n if (typeof val === 'object' && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)\n if (propertyDescriptor.get !== undefined) {\n if (propertyDescriptor.configurable) {\n Object.defineProperty(parent, k, { value: '[Circular]' })\n arr.push([parent, k, val, propertyDescriptor])\n } else {\n replacerStack.push([val, k])\n }\n } else {\n parent[k] = '[Circular]'\n arr.push([parent, k, val])\n }\n return\n }\n }\n stack.push(val)\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n decirc(val[i], i, stack, val)\n }\n } else {\n var keys = Object.keys(val)\n for (i = 0; i < keys.length; i++) {\n var key = keys[i]\n decirc(val[key], key, stack, val)\n }\n }\n stack.pop()\n }\n}\n\n// Stable-stringify\nfunction compareFunction (a, b) {\n if (a < b) {\n return -1\n }\n if (a > b) {\n return 1\n }\n return 0\n}\n\nfunction deterministicStringify (obj, replacer, spacer) {\n var tmp = deterministicDecirc(obj, '', [], undefined) || obj\n var res\n try {\n if (replacerStack.length === 0) {\n res = JSON.stringify(tmp, replacer, spacer)\n } else {\n res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)\n }\n } catch (_) {\n return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]')\n } finally {\n // Ensure that we restore the object as it was.\n while (arr.length !== 0) {\n var part = arr.pop()\n if (part.length === 4) {\n Object.defineProperty(part[0], part[1], part[3])\n } else {\n part[0][part[1]] = part[2]\n }\n }\n }\n return res\n}\n\nfunction deterministicDecirc (val, k, stack, parent) {\n var i\n if (typeof val === 'object' && val !== null) {\n for (i = 0; i < stack.length; i++) {\n if (stack[i] === val) {\n var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)\n if (propertyDescriptor.get !== undefined) {\n if (propertyDescriptor.configurable) {\n Object.defineProperty(parent, k, { value: '[Circular]' })\n arr.push([parent, k, val, propertyDescriptor])\n } else {\n replacerStack.push([val, k])\n }\n } else {\n parent[k] = '[Circular]'\n arr.push([parent, k, val])\n }\n return\n }\n }\n try {\n if (typeof val.toJSON === 'function') {\n return\n }\n } catch (_) {\n return\n }\n stack.push(val)\n // Optimize for Arrays. Big arrays could kill the performance otherwise!\n if (Array.isArray(val)) {\n for (i = 0; i < val.length; i++) {\n deterministicDecirc(val[i], i, stack, val)\n }\n } else {\n // Create a temporary object in the required way\n var tmp = {}\n var keys = Object.keys(val).sort(compareFunction)\n for (i = 0; i < keys.length; i++) {\n var key = keys[i]\n deterministicDecirc(val[key], key, stack, val)\n tmp[key] = val[key]\n }\n if (parent !== undefined) {\n arr.push([parent, k, val])\n parent[k] = tmp\n } else {\n return tmp\n }\n }\n stack.pop()\n }\n}\n\n// wraps replacer function to handle values we couldn't replace\n// and mark them as [Circular]\nfunction replaceGetterValues (replacer) {\n replacer = replacer !== undefined ? replacer : function (k, v) { return v }\n return function (key, val) {\n if (replacerStack.length > 0) {\n for (var i = 0; i < replacerStack.length; i++) {\n var part = replacerStack[i]\n if (part[1] === key && part[0] === val) {\n val = '[Circular]'\n replacerStack.splice(i, 1)\n break\n }\n }\n }\n return replacer.call(this, key, val)\n }\n}\n","'use strict';\n\nconst util = require('util');\nconst Writable = require('readable-stream/writable');\nconst { LEVEL } = require('triple-beam');\n\n/**\n * Constructor function for the TransportStream. This is the base prototype\n * that all `winston >= 3` transports should inherit from.\n * @param {Object} options - Options for this TransportStream instance\n * @param {String} options.level - Highest level according to RFC5424.\n * @param {Boolean} options.handleExceptions - If true, info with\n * { exception: true } will be written.\n * @param {Function} options.log - Custom log function for simple Transport\n * creation\n * @param {Function} options.close - Called on \"unpipe\" from parent.\n */\nconst TransportStream = module.exports = function TransportStream(options = {}) {\n Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });\n\n this.format = options.format;\n this.level = options.level;\n this.handleExceptions = options.handleExceptions;\n this.handleRejections = options.handleRejections;\n this.silent = options.silent;\n\n if (options.log) this.log = options.log;\n if (options.logv) this.logv = options.logv;\n if (options.close) this.close = options.close;\n\n // Get the levels from the source we are piped from.\n this.once('pipe', logger => {\n // Remark (indexzero): this bookkeeping can only support multiple\n // Logger parents with the same `levels`. This comes into play in\n // the `winston.Container` code in which `container.add` takes\n // a fully realized set of options with pre-constructed TransportStreams.\n this.levels = logger.levels;\n this.parent = logger;\n });\n\n // If and/or when the transport is removed from this instance\n this.once('unpipe', src => {\n // Remark (indexzero): this bookkeeping can only support multiple\n // Logger parents with the same `levels`. This comes into play in\n // the `winston.Container` code in which `container.add` takes\n // a fully realized set of options with pre-constructed TransportStreams.\n if (src === this.parent) {\n this.parent = null;\n if (this.close) {\n this.close();\n }\n }\n });\n};\n\n/*\n * Inherit from Writeable using Node.js built-ins\n */\nutil.inherits(TransportStream, Writable);\n\n/**\n * Writes the info object to our transport instance.\n * @param {mixed} info - TODO: add param description.\n * @param {mixed} enc - TODO: add param description.\n * @param {function} callback - TODO: add param description.\n * @returns {undefined}\n * @private\n */\nTransportStream.prototype._write = function _write(info, enc, callback) {\n if (this.silent || (info.exception === true && !this.handleExceptions)) {\n return callback(null);\n }\n\n // Remark: This has to be handled in the base transport now because we\n // cannot conditionally write to our pipe targets as stream. We always\n // prefer any explicit level set on the Transport itself falling back to\n // any level set on the parent.\n const level = this.level || (this.parent && this.parent.level);\n\n if (!level || this.levels[level] >= this.levels[info[LEVEL]]) {\n if (info && !this.format) {\n return this.log(info, callback);\n }\n\n let errState;\n let transformed;\n\n // We trap(and re-throw) any errors generated by the user-provided format, but also\n // guarantee that the streams callback is invoked so that we can continue flowing.\n try {\n transformed = this.format.transform(Object.assign({}, info), this.format.options);\n } catch (err) {\n errState = err;\n }\n\n if (errState || !transformed) {\n // eslint-disable-next-line callback-return\n callback();\n if (errState) throw errState;\n return;\n }\n\n return this.log(transformed, callback);\n }\n\n return callback(null);\n};\n\n/**\n * Writes the batch of info objects (i.e. \"object chunks\") to our transport\n * instance after performing any necessary filtering.\n * @param {mixed} chunks - TODO: add params description.\n * @param {function} callback - TODO: add params description.\n * @returns {mixed} - TODO: add returns description.\n * @private\n */\nTransportStream.prototype._writev = function _writev(chunks, callback) {\n if (this.logv) {\n const infos = chunks.filter(this._accept, this);\n if (!infos.length) {\n return callback(null);\n }\n\n // Remark (indexzero): from a performance perspective if Transport\n // implementers do choose to implement logv should we make it their\n // responsibility to invoke their format?\n return this.logv(infos, callback);\n }\n\n for (let i = 0; i < chunks.length; i++) {\n if (!this._accept(chunks[i])) continue;\n\n if (chunks[i].chunk && !this.format) {\n this.log(chunks[i].chunk, chunks[i].callback);\n continue;\n }\n\n let errState;\n let transformed;\n\n // We trap(and re-throw) any errors generated by the user-provided format, but also\n // guarantee that the streams callback is invoked so that we can continue flowing.\n try {\n transformed = this.format.transform(\n Object.assign({}, chunks[i].chunk),\n this.format.options\n );\n } catch (err) {\n errState = err;\n }\n\n if (errState || !transformed) {\n // eslint-disable-next-line callback-return\n chunks[i].callback();\n if (errState) {\n // eslint-disable-next-line callback-return\n callback(null);\n throw errState;\n }\n } else {\n this.log(transformed, chunks[i].callback);\n }\n }\n\n return callback(null);\n};\n\n/**\n * Predicate function that returns true if the specfied `info` on the\n * WriteReq, `write`, should be passed down into the derived\n * TransportStream's I/O via `.log(info, callback)`.\n * @param {WriteReq} write - winston@3 Node.js WriteReq for the `info` object\n * representing the log message.\n * @returns {Boolean} - Value indicating if the `write` should be accepted &\n * logged.\n */\nTransportStream.prototype._accept = function _accept(write) {\n const info = write.chunk;\n if (this.silent) {\n return false;\n }\n\n // We always prefer any explicit level set on the Transport itself\n // falling back to any level set on the parent.\n const level = this.level || (this.parent && this.parent.level);\n\n // Immediately check the average case: log level filtering.\n if (\n info.exception === true ||\n !level ||\n this.levels[level] >= this.levels[info[LEVEL]]\n ) {\n // Ensure the info object is valid based on `{ exception }`:\n // 1. { handleExceptions: true }: all `info` objects are valid\n // 2. { exception: false }: accepted by all transports.\n if (this.handleExceptions || info.exception !== true) {\n return true;\n }\n }\n\n return false;\n};\n\n/**\n * _nop is short for \"No operation\"\n * @returns {Boolean} Intentionally false.\n */\nTransportStream.prototype._nop = function _nop() {\n // eslint-disable-next-line no-undefined\n return void undefined;\n};\n\n\n// Expose legacy stream\nmodule.exports.LegacyTransportStream = require('./legacy');\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.isAsyncIterable = exports.isAsyncGenerator = exports.isAsync = undefined;\n\nvar _asyncify = require('../asyncify');\n\nvar _asyncify2 = _interopRequireDefault(_asyncify);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction isAsync(fn) {\n return fn[Symbol.toStringTag] === 'AsyncFunction';\n}\n\nfunction isAsyncGenerator(fn) {\n return fn[Symbol.toStringTag] === 'AsyncGenerator';\n}\n\nfunction isAsyncIterable(obj) {\n return typeof obj[Symbol.asyncIterator] === 'function';\n}\n\nfunction wrapAsync(asyncFn) {\n if (typeof asyncFn !== 'function') throw new Error('expected a function');\n return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn;\n}\n\nexports.default = wrapAsync;\nexports.isAsync = isAsync;\nexports.isAsyncGenerator = isAsyncGenerator;\nexports.isAsyncIterable = isAsyncIterable;","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n'use strict';\n/**/\n\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n\n for (var key in obj) {\n keys.push(key);\n }\n\n return keys;\n};\n/**/\n\n\nmodule.exports = Duplex;\n\nvar Readable = require('./_stream_readable');\n\nvar Writable = require('./_stream_writable');\n\nrequire('inherits')(Duplex, Readable);\n\n{\n // Allow the keys array to be GC'ed.\n var keys = objectKeys(Writable.prototype);\n\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n Readable.call(this, options);\n Writable.call(this, options);\n this.allowHalfOpen = true;\n\n if (options) {\n if (options.readable === false) this.readable = false;\n if (options.writable === false) this.writable = false;\n\n if (options.allowHalfOpen === false) {\n this.allowHalfOpen = false;\n this.once('end', onend);\n }\n }\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\nObject.defineProperty(Duplex.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n}); // the no-half-open enforcer\n\nfunction onend() {\n // If the writable side ended, then we're ok.\n if (this._writableState.ended) return; // no more data can be written.\n // But allow more writes to happen in this tick.\n\n process.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});","import { __extends, __values } from \"tslib\";\nimport { logger, timestampWithMs } from '@sentry/utils';\nimport { SpanRecorder } from './span';\nimport { SpanStatus } from './spanstatus';\nimport { Transaction } from './transaction';\nexport var DEFAULT_IDLE_TIMEOUT = 1000;\nexport var HEARTBEAT_INTERVAL = 5000;\n/**\n * @inheritDoc\n */\nvar IdleTransactionSpanRecorder = /** @class */ (function (_super) {\n __extends(IdleTransactionSpanRecorder, _super);\n function IdleTransactionSpanRecorder(_pushActivity, _popActivity, transactionSpanId, maxlen) {\n if (transactionSpanId === void 0) { transactionSpanId = ''; }\n var _this = _super.call(this, maxlen) || this;\n _this._pushActivity = _pushActivity;\n _this._popActivity = _popActivity;\n _this.transactionSpanId = transactionSpanId;\n return _this;\n }\n /**\n * @inheritDoc\n */\n IdleTransactionSpanRecorder.prototype.add = function (span) {\n var _this = this;\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = function (endTimestamp) {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs();\n _this._popActivity(span.spanId);\n };\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n _super.prototype.add.call(this, span);\n };\n return IdleTransactionSpanRecorder;\n}(SpanRecorder));\nexport { IdleTransactionSpanRecorder };\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nvar IdleTransaction = /** @class */ (function (_super) {\n __extends(IdleTransaction, _super);\n function IdleTransaction(transactionContext, _idleHub, \n /**\n * The time to wait in ms until the idle transaction will be finished.\n * @default 1000\n */\n _idleTimeout, \n // If an idle transaction should be put itself on and off the scope automatically.\n _onScope) {\n if (_idleTimeout === void 0) { _idleTimeout = DEFAULT_IDLE_TIMEOUT; }\n if (_onScope === void 0) { _onScope = false; }\n var _this = _super.call(this, transactionContext, _idleHub) || this;\n _this._idleHub = _idleHub;\n _this._idleTimeout = _idleTimeout;\n _this._onScope = _onScope;\n // Activities store a list of active spans\n _this.activities = {};\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n _this._heartbeatCounter = 0;\n // We should not use heartbeat if we finished a transaction\n _this._finished = false;\n _this._beforeFinishCallbacks = [];\n if (_idleHub && _onScope) {\n // There should only be one active transaction on the scope\n clearActiveTransaction(_idleHub);\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n logger.log(\"Setting idle transaction on scope. Span ID: \" + _this.spanId);\n _idleHub.configureScope(function (scope) { return scope.setSpan(_this); });\n }\n _this._initTimeout = setTimeout(function () {\n if (!_this._finished) {\n _this.finish();\n }\n }, _this._idleTimeout);\n return _this;\n }\n /** {@inheritDoc} */\n IdleTransaction.prototype.finish = function (endTimestamp) {\n var e_1, _a;\n var _this = this;\n if (endTimestamp === void 0) { endTimestamp = timestampWithMs(); }\n this._finished = true;\n this.activities = {};\n if (this.spanRecorder) {\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n try {\n for (var _b = __values(this._beforeFinishCallbacks), _c = _b.next(); !_c.done; _c = _b.next()) {\n var callback = _c.value;\n callback(this, endTimestamp);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n this.spanRecorder.spans = this.spanRecorder.spans.filter(function (span) {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === _this.spanId) {\n return true;\n }\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus(SpanStatus.Cancelled);\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n var keepSpan = span.startTimestamp < endTimestamp;\n if (!keepSpan) {\n logger.log('[Tracing] discarding Span since it happened after Transaction was finished', JSON.stringify(span, undefined, 2));\n }\n return keepSpan;\n });\n logger.log('[Tracing] flushing IdleTransaction');\n }\n else {\n logger.log('[Tracing] No active IdleTransaction');\n }\n // this._onScope is true if the transaction was previously on the scope.\n if (this._onScope) {\n clearActiveTransaction(this._idleHub);\n }\n return _super.prototype.finish.call(this, endTimestamp);\n };\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n IdleTransaction.prototype.registerBeforeFinishCallback = function (callback) {\n this._beforeFinishCallbacks.push(callback);\n };\n /**\n * @inheritDoc\n */\n IdleTransaction.prototype.initSpanRecorder = function (maxlen) {\n var _this = this;\n if (!this.spanRecorder) {\n var pushActivity = function (id) {\n if (_this._finished) {\n return;\n }\n _this._pushActivity(id);\n };\n var popActivity = function (id) {\n if (_this._finished) {\n return;\n }\n _this._popActivity(id);\n };\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n // Start heartbeat so that transactions do not run forever.\n logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n };\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n IdleTransaction.prototype._pushActivity = function (spanId) {\n if (this._initTimeout) {\n clearTimeout(this._initTimeout);\n this._initTimeout = undefined;\n }\n logger.log(\"[Tracing] pushActivity: \" + spanId);\n this.activities[spanId] = true;\n logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n };\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n IdleTransaction.prototype._popActivity = function (spanId) {\n var _this = this;\n if (this.activities[spanId]) {\n logger.log(\"[Tracing] popActivity \" + spanId);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n if (Object.keys(this.activities).length === 0) {\n var timeout = this._idleTimeout;\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampWithMs is in seconds, timeout is in ms\n var end_1 = timestampWithMs() + timeout / 1000;\n setTimeout(function () {\n if (!_this._finished) {\n _this.finish(end_1);\n }\n }, timeout);\n }\n };\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n IdleTransaction.prototype._beat = function () {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n var heartbeatString = Object.keys(this.activities).join('');\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter += 1;\n }\n else {\n this._heartbeatCounter = 1;\n }\n this._prevHeartbeatString = heartbeatString;\n if (this._heartbeatCounter >= 3) {\n logger.log(\"[Tracing] Transaction finished because of no change for 3 heart beats\");\n this.setStatus(SpanStatus.DeadlineExceeded);\n this.setTag('heartbeat', 'failed');\n this.finish();\n }\n else {\n this._pingHeartbeat();\n }\n };\n /**\n * Pings the heartbeat\n */\n IdleTransaction.prototype._pingHeartbeat = function () {\n var _this = this;\n logger.log(\"pinging Heartbeat -> current counter: \" + this._heartbeatCounter);\n setTimeout(function () {\n _this._beat();\n }, HEARTBEAT_INTERVAL);\n };\n return IdleTransaction;\n}(Transaction));\nexport { IdleTransaction };\n/**\n * Reset active transaction on scope\n */\nfunction clearActiveTransaction(hub) {\n if (hub) {\n var scope = hub.getScope();\n if (scope) {\n var transaction = scope.getTransaction();\n if (transaction) {\n scope.setSpan(undefined);\n }\n }\n }\n}\n//# sourceMappingURL=idletransaction.js.map","import { __assign, __extends } from \"tslib\";\nimport { getCurrentHub, Hub } from '@sentry/hub';\nimport { Outcome, } from '@sentry/types';\nimport { dropUndefinedKeys, isInstanceOf, logger } from '@sentry/utils';\nimport { Span as SpanClass, SpanRecorder } from './span';\n/** JSDoc */\nvar Transaction = /** @class */ (function (_super) {\n __extends(Transaction, _super);\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n function Transaction(transactionContext, hub) {\n var _this = _super.call(this, transactionContext) || this;\n _this._measurements = {};\n /**\n * The reference to the current hub.\n */\n _this._hub = getCurrentHub();\n if (isInstanceOf(hub, Hub)) {\n _this._hub = hub;\n }\n _this.name = transactionContext.name || '';\n _this.metadata = transactionContext.metadata || {};\n _this._trimEnd = transactionContext.trimEnd;\n // this is because transactions are also spans, and spans have a transaction pointer\n _this.transaction = _this;\n return _this;\n }\n /**\n * JSDoc\n */\n Transaction.prototype.setName = function (name) {\n this.name = name;\n };\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n Transaction.prototype.initSpanRecorder = function (maxlen) {\n if (maxlen === void 0) { maxlen = 1000; }\n if (!this.spanRecorder) {\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n };\n /**\n * Set observed measurements for this transaction.\n * @hidden\n */\n Transaction.prototype.setMeasurements = function (measurements) {\n this._measurements = __assign({}, measurements);\n };\n /**\n * Set metadata for this transaction.\n * @hidden\n */\n Transaction.prototype.setMetadata = function (newMetadata) {\n this.metadata = __assign(__assign({}, this.metadata), newMetadata);\n };\n /**\n * @inheritDoc\n */\n Transaction.prototype.finish = function (endTimestamp) {\n var _this = this;\n var _a, _b, _c, _d, _e;\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n if (!this.name) {\n logger.warn('Transaction has no name, falling back to ``.');\n this.name = '';\n }\n // just sets the end timestamp\n _super.prototype.finish.call(this, endTimestamp);\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n (_e = (_c = (_a = this._hub\n .getClient()) === null || _a === void 0 ? void 0 : (_b = _a).getTransport) === null || _c === void 0 ? void 0 : (_d = _c.call(_b)).recordLostEvent) === null || _e === void 0 ? void 0 : _e.call(_d, Outcome.SampleRate, 'transaction');\n return undefined;\n }\n var finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(function (s) { return s !== _this && s.endTimestamp; }) : [];\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce(function (prev, current) {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n var transaction = {\n contexts: {\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n debug_meta: this.metadata,\n };\n var hasMeasurements = Object.keys(this._measurements).length > 0;\n if (hasMeasurements) {\n logger.log('[Measurements] Adding measurements to transaction', JSON.stringify(this._measurements, undefined, 2));\n transaction.measurements = this._measurements;\n }\n logger.log(\"[Tracing] Finishing \" + this.op + \" transaction: \" + this.name + \".\");\n return this._hub.captureEvent(transaction);\n };\n /**\n * @inheritDoc\n */\n Transaction.prototype.toContext = function () {\n var spanContext = _super.prototype.toContext.call(this);\n return dropUndefinedKeys(__assign(__assign({}, spanContext), { name: this.name, trimEnd: this._trimEnd }));\n };\n /**\n * @inheritDoc\n */\n Transaction.prototype.updateWithContext = function (transactionContext) {\n var _a;\n _super.prototype.updateWithContext.call(this, transactionContext);\n this.name = (_a = transactionContext.name, (_a !== null && _a !== void 0 ? _a : ''));\n this._trimEnd = transactionContext.trimEnd;\n return this;\n };\n return Transaction;\n}(SpanClass));\nexport { Transaction };\n//# sourceMappingURL=transaction.js.map","module.exports = require(\"domain\");","import { getGlobalObject } from './global';\nimport { dynamicRequire, isNodeEnv } from './node';\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nvar dateTimestampSource = {\n nowSeconds: function () { return Date.now() / 1000; },\n};\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction getBrowserPerformance() {\n var performance = getGlobalObject().performance;\n if (!performance || !performance.now) {\n return undefined;\n }\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n var timeOrigin = Date.now() - performance.now();\n return {\n now: function () { return performance.now(); },\n timeOrigin: timeOrigin,\n };\n}\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance() {\n try {\n var perfHooks = dynamicRequire(module, 'perf_hooks');\n return perfHooks.performance;\n }\n catch (_) {\n return undefined;\n }\n}\n/**\n * The Performance API implementation for the current platform, if available.\n */\nvar platformPerformance = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\nvar timestampSource = platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: function () { return (platformPerformance.timeOrigin + platformPerformance.now()) / 1000; },\n };\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nexport var dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * See `usingPerformanceAPI` to test whether the Performance API is used.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nexport var timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource);\n// Re-exported with an old name for backwards-compatibility.\nexport var timestampWithMs = timestampInSeconds;\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nexport var usingPerformanceAPI = platformPerformance !== undefined;\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nexport var _browserPerformanceTimeOriginMode;\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nexport var browserPerformanceTimeOrigin = (function () {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n var performance = getGlobalObject().performance;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\n }\n var threshold = 3600 * 1000;\n var performanceNow = performance.now();\n var dateNow = Date.now();\n // if timeOrigin isn't available set delta to threshold so it isn't used\n var timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n var timeOriginIsReliable = timeOriginDelta < threshold;\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n var navigationStart = performance.timing && performance.timing.navigationStart;\n var hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n var navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n var navigationStartIsReliable = navigationStartDelta < threshold;\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n }\n else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n//# sourceMappingURL=time.js.map","'use strict';\n\n// Manually extracted from mysql-5.5.23/include/mysql_com.h\n// some more info here: http://dev.mysql.com/doc/refman/5.5/en/c-api-prepared-statement-type-codes.html\nexports.DECIMAL = 0x00; // aka DECIMAL (http://dev.mysql.com/doc/refman/5.0/en/precision-math-decimal-changes.html)\nexports.TINY = 0x01; // aka TINYINT, 1 byte\nexports.SHORT = 0x02; // aka SMALLINT, 2 bytes\nexports.LONG = 0x03; // aka INT, 4 bytes\nexports.FLOAT = 0x04; // aka FLOAT, 4-8 bytes\nexports.DOUBLE = 0x05; // aka DOUBLE, 8 bytes\nexports.NULL = 0x06; // NULL (used for prepared statements, I think)\nexports.TIMESTAMP = 0x07; // aka TIMESTAMP\nexports.LONGLONG = 0x08; // aka BIGINT, 8 bytes\nexports.INT24 = 0x09; // aka MEDIUMINT, 3 bytes\nexports.DATE = 0x0a; // aka DATE\nexports.TIME = 0x0b; // aka TIME\nexports.DATETIME = 0x0c; // aka DATETIME\nexports.YEAR = 0x0d; // aka YEAR, 1 byte (don't ask)\nexports.NEWDATE = 0x0e; // aka ?\nexports.VARCHAR = 0x0f; // aka VARCHAR (?)\nexports.BIT = 0x10; // aka BIT, 1-8 byte\nexports.JSON = 0xf5;\nexports.NEWDECIMAL = 0xf6; // aka DECIMAL\nexports.ENUM = 0xf7; // aka ENUM\nexports.SET = 0xf8; // aka SET\nexports.TINY_BLOB = 0xf9; // aka TINYBLOB, TINYTEXT\nexports.MEDIUM_BLOB = 0xfa; // aka MEDIUMBLOB, MEDIUMTEXT\nexports.LONG_BLOB = 0xfb; // aka LONGBLOG, LONGTEXT\nexports.BLOB = 0xfc; // aka BLOB, TEXT\nexports.VAR_STRING = 0xfd; // aka VARCHAR, VARBINARY\nexports.STRING = 0xfe; // aka CHAR, BINARY\nexports.GEOMETRY = 0xff; // aka GEOMETRY\n","'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar colors = require('colors/safe');\n\nvar _require = require('triple-beam'),\n LEVEL = _require.LEVEL,\n MESSAGE = _require.MESSAGE; //\n// Fix colors not appearing in non-tty environments\n//\n\n\ncolors.enabled = true;\n/**\n * @property {RegExp} hasSpace\n * Simple regex to check for presence of spaces.\n */\n\nvar hasSpace = /\\s+/;\n/*\n * Colorizer format. Wraps the `level` and/or `message` properties\n * of the `info` objects with ANSI color codes based on a few options.\n */\n\nvar Colorizer = /*#__PURE__*/function () {\n function Colorizer() {\n var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, Colorizer);\n\n if (opts.colors) {\n this.addColors(opts.colors);\n }\n\n this.options = opts;\n }\n /*\n * Adds the colors Object to the set of allColors\n * known by the Colorizer\n *\n * @param {Object} colors Set of color mappings to add.\n */\n\n\n _createClass(Colorizer, [{\n key: \"addColors\",\n\n /*\n * Adds the colors Object to the set of allColors\n * known by the Colorizer\n *\n * @param {Object} colors Set of color mappings to add.\n */\n value: function addColors(clrs) {\n return Colorizer.addColors(clrs);\n }\n /*\n * function colorize (lookup, level, message)\n * Performs multi-step colorization using colors/safe\n */\n\n }, {\n key: \"colorize\",\n value: function colorize(lookup, level, message) {\n if (typeof message === 'undefined') {\n message = level;\n } //\n // If the color for the level is just a string\n // then attempt to colorize the message with it.\n //\n\n\n if (!Array.isArray(Colorizer.allColors[lookup])) {\n return colors[Colorizer.allColors[lookup]](message);\n } //\n // If it is an Array then iterate over that Array, applying\n // the colors function for each item.\n //\n\n\n for (var i = 0, len = Colorizer.allColors[lookup].length; i < len; i++) {\n message = colors[Colorizer.allColors[lookup][i]](message);\n }\n\n return message;\n }\n /*\n * function transform (info, opts)\n * Attempts to colorize the { level, message } of the given\n * `logform` info object.\n */\n\n }, {\n key: \"transform\",\n value: function transform(info, opts) {\n if (opts.all && typeof info[MESSAGE] === 'string') {\n info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]);\n }\n\n if (opts.level || opts.all || !opts.message) {\n info.level = this.colorize(info[LEVEL], info.level);\n }\n\n if (opts.all || opts.message) {\n info.message = this.colorize(info[LEVEL], info.level, info.message);\n }\n\n return info;\n }\n }], [{\n key: \"addColors\",\n value: function addColors(clrs) {\n var nextColors = Object.keys(clrs).reduce(function (acc, level) {\n acc[level] = hasSpace.test(clrs[level]) ? clrs[level].split(hasSpace) : clrs[level];\n return acc;\n }, {});\n Colorizer.allColors = Object.assign({}, Colorizer.allColors || {}, nextColors);\n return Colorizer.allColors;\n }\n }]);\n\n return Colorizer;\n}();\n/*\n * function colorize (info)\n * Returns a new instance of the colorize Format that applies\n * level colors to `info` objects. This was previously exposed\n * as { colorize: true } to transports in `winston < 3.0.0`.\n */\n\n\nmodule.exports = function (opts) {\n return new Colorizer(opts);\n}; //\n// Attach the Colorizer for registration purposes\n//\n\n\nmodule.exports.Colorizer = module.exports.Format = Colorizer;","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = awaitify;\n// conditionally promisify a function.\n// only return a promise if a callback is omitted\nfunction awaitify(asyncFn, arity = asyncFn.length) {\n if (!arity) throw new Error('arity is undefined');\n function awaitable(...args) {\n if (typeof args[arity - 1] === 'function') {\n return asyncFn.apply(this, args);\n }\n\n return new Promise((resolve, reject) => {\n args[arity - 1] = (err, ...cbArgs) => {\n if (err) return reject(err);\n resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);\n };\n asyncFn.apply(this, args);\n });\n }\n\n return awaitable;\n}\nmodule.exports = exports['default'];","var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream.Readable;\n Object.assign(module.exports, Stream);\n module.exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n exports.finished = require('./lib/internal/streams/end-of-stream.js');\n exports.pipeline = require('./lib/internal/streams/pipeline.js');\n}\n","import { mainLogger } from '../sv_logger';\nimport PlayerService from './player.service';\n\nexport const playerLogger = mainLogger.child({\n module: 'player',\n});\n\nconst clean = (input: string) => (input ? input.replace(/[^0-9a-z]/gi, '') : input);\n\nexport async function getDefaultProfileNames(source: number): Promise {\n const defaultProfileNames: string[] = [];\n const player = PlayerService.getPlayer(source);\n\n if (player.getFirstName() && player.getLastName()) {\n defaultProfileNames.push(`${player.getFirstName()}_${player.getLastName()}`);\n } else if (player.getFirstName()) {\n defaultProfileNames.push(player.getFirstName());\n } else if (player.getLastName()) {\n defaultProfileNames.push(player.getLastName());\n }\n\n if (player.getPhoneNumber()) {\n defaultProfileNames.push(player.getPhoneNumber());\n }\n return defaultProfileNames;\n}\n","/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable @typescript-eslint/typedef */\n/* eslint-disable @typescript-eslint/explicit-module-boundary-types */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { isThenable } from './is';\n/** SyncPromise internal states */\nvar States;\n(function (States) {\n /** Pending */\n States[\"PENDING\"] = \"PENDING\";\n /** Resolved / OK */\n States[\"RESOLVED\"] = \"RESOLVED\";\n /** Rejected / Error */\n States[\"REJECTED\"] = \"REJECTED\";\n})(States || (States = {}));\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nvar SyncPromise = /** @class */ (function () {\n function SyncPromise(executor) {\n var _this = this;\n this._state = States.PENDING;\n this._handlers = [];\n /** JSDoc */\n this._resolve = function (value) {\n _this._setResult(States.RESOLVED, value);\n };\n /** JSDoc */\n this._reject = function (reason) {\n _this._setResult(States.REJECTED, reason);\n };\n /** JSDoc */\n this._setResult = function (state, value) {\n if (_this._state !== States.PENDING) {\n return;\n }\n if (isThenable(value)) {\n void value.then(_this._resolve, _this._reject);\n return;\n }\n _this._state = state;\n _this._value = value;\n _this._executeHandlers();\n };\n // TODO: FIXME\n /** JSDoc */\n this._attachHandler = function (handler) {\n _this._handlers = _this._handlers.concat(handler);\n _this._executeHandlers();\n };\n /** JSDoc */\n this._executeHandlers = function () {\n if (_this._state === States.PENDING) {\n return;\n }\n var cachedHandlers = _this._handlers.slice();\n _this._handlers = [];\n cachedHandlers.forEach(function (handler) {\n if (handler.done) {\n return;\n }\n if (_this._state === States.RESOLVED) {\n if (handler.onfulfilled) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n handler.onfulfilled(_this._value);\n }\n }\n if (_this._state === States.REJECTED) {\n if (handler.onrejected) {\n handler.onrejected(_this._value);\n }\n }\n handler.done = true;\n });\n };\n try {\n executor(this._resolve, this._reject);\n }\n catch (e) {\n this._reject(e);\n }\n }\n /** JSDoc */\n SyncPromise.resolve = function (value) {\n return new SyncPromise(function (resolve) {\n resolve(value);\n });\n };\n /** JSDoc */\n SyncPromise.reject = function (reason) {\n return new SyncPromise(function (_, reject) {\n reject(reason);\n });\n };\n /** JSDoc */\n SyncPromise.all = function (collection) {\n return new SyncPromise(function (resolve, reject) {\n if (!Array.isArray(collection)) {\n reject(new TypeError(\"Promise.all requires an array as input.\"));\n return;\n }\n if (collection.length === 0) {\n resolve([]);\n return;\n }\n var counter = collection.length;\n var resolvedCollection = [];\n collection.forEach(function (item, index) {\n void SyncPromise.resolve(item)\n .then(function (value) {\n resolvedCollection[index] = value;\n counter -= 1;\n if (counter !== 0) {\n return;\n }\n resolve(resolvedCollection);\n })\n .then(null, reject);\n });\n });\n };\n /** JSDoc */\n SyncPromise.prototype.then = function (onfulfilled, onrejected) {\n var _this = this;\n return new SyncPromise(function (resolve, reject) {\n _this._attachHandler({\n done: false,\n onfulfilled: function (result) {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result);\n return;\n }\n try {\n resolve(onfulfilled(result));\n return;\n }\n catch (e) {\n reject(e);\n return;\n }\n },\n onrejected: function (reason) {\n if (!onrejected) {\n reject(reason);\n return;\n }\n try {\n resolve(onrejected(reason));\n return;\n }\n catch (e) {\n reject(e);\n return;\n }\n },\n });\n });\n };\n /** JSDoc */\n SyncPromise.prototype.catch = function (onrejected) {\n return this.then(function (val) { return val; }, onrejected);\n };\n /** JSDoc */\n SyncPromise.prototype.finally = function (onfinally) {\n var _this = this;\n return new SyncPromise(function (resolve, reject) {\n var val;\n var isRejected;\n return _this.then(function (value) {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n }, function (reason) {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n }).then(function () {\n if (isRejected) {\n reject(val);\n return;\n }\n resolve(val);\n });\n });\n };\n /** JSDoc */\n SyncPromise.prototype.toString = function () {\n return '[object SyncPromise]';\n };\n return SyncPromise;\n}());\nexport { SyncPromise };\n//# sourceMappingURL=syncpromise.js.map","import mysql from 'mysql2/promise';\nimport { CONNECTION_STRING, parseSemiColonFormat } from './db_utils';\nimport { mainLogger } from '../sv_logger';\n\n// we require set mysql_connection_string to be set in the config\nconst mysqlConnectionString = GetConvar(CONNECTION_STRING, 'none');\nif (mysqlConnectionString === 'none') {\n const error = new Error(\n `No connection string provided. make sure \"${CONNECTION_STRING}\" is set in your config.`,\n );\n mainLogger.error(error.message);\n throw error;\n}\n\n/**\n * Most fivem servers utilize fivem-mysql-async (https://brouznouf.github.io/fivem-mysql-async/) and\n * define a environment variable \"mysql_connection_string\" in their configurations. We will try to\n * maintain backwards compatibility with this.\n *\n * fivem-mysql-async allows for two different connection string formats defined here:\n * https://brouznouf.github.io/fivem-mysql-async/config/ and we need to handle both of them.\n */\nexport function generateConnectionPool() {\n try {\n const config = mysqlConnectionString.includes('mysql://')\n ? { uri: mysqlConnectionString }\n : parseSemiColonFormat(mysqlConnectionString);\n\n return mysql.createPool({\n connectTimeout: 60000,\n ...config,\n });\n } catch (e) {\n mainLogger.error(`SQL Connection Pool Error: ${e.message}`, {\n connection: mysqlConnectionString,\n });\n }\n}\n\nexport const pool = generateConnectionPool();\n\nexport async function withTransaction(queries: Promise[]): Promise {\n const connection = await pool.getConnection();\n connection.beginTransaction();\n\n try {\n const results = await Promise.all(queries);\n await connection.commit();\n await connection.release();\n return results;\n } catch (err) {\n mainLogger.warn(`Error when submitting queries in transaction, ${err.message}`);\n await connection.rollback();\n await connection.release();\n return Promise.reject(err);\n }\n}\n","// This file was modified by Oracle on June 1, 2021.\n// The changes involve new logic to handle an additional ERR Packet sent by\n// the MySQL server when the connection is closed unexpectedly.\n// Modifications copyright (c) 2021, Oracle and/or its affiliates.\n\n// This file was modified by Oracle on June 17, 2021.\n// The changes involve logic to ensure the socket connection is closed when\n// there is a fatal error.\n// Modifications copyright (c) 2021, Oracle and/or its affiliates.\n\n'use strict';\n\nconst Net = require('net');\nconst Tls = require('tls');\nconst Timers = require('timers');\nconst EventEmitter = require('events').EventEmitter;\nconst Readable = require('stream').Readable;\nconst Queue = require('denque');\nconst SqlString = require('sqlstring');\nconst LRU = require('lru-cache');\n\nconst PacketParser = require('./packet_parser.js');\nconst Packets = require('./packets/index.js');\nconst Commands = require('./commands/index.js');\nconst ConnectionConfig = require('./connection_config.js');\nconst CharsetToEncoding = require('./constants/charset_encodings.js');\n\nlet _connectionId = 0;\n\nlet convertNamedPlaceholders = null;\n\nclass Connection extends EventEmitter {\n constructor(opts) {\n super();\n this.config = opts.config;\n // TODO: fill defaults\n // if no params, connect to /var/lib/mysql/mysql.sock ( /tmp/mysql.sock on OSX )\n // if host is given, connect to host:3306\n // TODO: use `/usr/local/mysql/bin/mysql_config --socket` output? as default socketPath\n // if there is no host/port and no socketPath parameters?\n if (!opts.config.stream) {\n if (opts.config.socketPath) {\n this.stream = Net.connect(opts.config.socketPath);\n } else {\n this.stream = Net.connect(\n opts.config.port,\n opts.config.host\n );\n\n // Enable keep-alive on the socket. It's disabled by default, but the\n // user can enable it and supply an initial delay.\n this.stream.setKeepAlive(true, this.config.keepAliveInitialDelay);\n }\n // if stream is a function, treat it as \"stream agent / factory\"\n } else if (typeof opts.config.stream === 'function') {\n this.stream = opts.config.stream(opts);\n } else {\n this.stream = opts.config.stream;\n }\n\n this._internalId = _connectionId++;\n this._commands = new Queue();\n this._command = null;\n this._paused = false;\n this._paused_packets = new Queue();\n this._statements = new LRU({\n max: this.config.maxPreparedStatements,\n dispose: function(key, statement) {\n statement.close();\n }\n });\n this.serverCapabilityFlags = 0;\n this.authorized = false;\n this.sequenceId = 0;\n this.compressedSequenceId = 0;\n this.threadId = null;\n this._handshakePacket = null;\n this._fatalError = null;\n this._protocolError = null;\n this._outOfOrderPackets = [];\n this.clientEncoding = CharsetToEncoding[this.config.charsetNumber];\n this.stream.on('error', this._handleNetworkError.bind(this));\n // see https://gist.github.com/khoomeister/4985691#use-that-instead-of-bind\n this.packetParser = new PacketParser(p => {\n this.handlePacket(p);\n });\n this.stream.on('data', data => {\n if (this.connectTimeout) {\n Timers.clearTimeout(this.connectTimeout);\n this.connectTimeout = null;\n }\n this.packetParser.execute(data);\n });\n this.stream.on('close', () => {\n // we need to set this flag everywhere where we want connection to close\n if (this._closing) {\n return;\n }\n if (!this._protocolError) {\n // no particular error message before disconnect\n this._protocolError = new Error(\n 'Connection lost: The server closed the connection.'\n );\n this._protocolError.fatal = true;\n this._protocolError.code = 'PROTOCOL_CONNECTION_LOST';\n }\n this._notifyError(this._protocolError);\n });\n let handshakeCommand;\n if (!this.config.isServer) {\n handshakeCommand = new Commands.ClientHandshake(this.config.clientFlags);\n handshakeCommand.on('end', () => {\n // this happens when handshake finishes early either because there was\n // some fatal error or the server sent an error packet instead of\n // an hello packet (for example, 'Too many connactions' error)\n if (!handshakeCommand.handshake || this._fatalError || this._protocolError) {\n return;\n }\n this._handshakePacket = handshakeCommand.handshake;\n this.threadId = handshakeCommand.handshake.connectionId;\n this.emit('connect', handshakeCommand.handshake);\n });\n handshakeCommand.on('error', err => {\n this._closing = true;\n this._notifyError(err);\n });\n this.addCommand(handshakeCommand);\n }\n // in case there was no initiall handshake but we need to read sting, assume it utf-8\n // most common example: \"Too many connections\" error ( packet is sent immediately on connection attempt, we don't know server encoding yet)\n // will be overwrittedn with actial encoding value as soon as server handshake packet is received\n this.serverEncoding = 'utf8';\n if (this.config.connectTimeout) {\n const timeoutHandler = this._handleTimeoutError.bind(this);\n this.connectTimeout = Timers.setTimeout(\n timeoutHandler,\n this.config.connectTimeout\n );\n }\n }\n\n promise(promiseImpl) {\n const PromiseConnection = require('../promise').PromiseConnection;\n return new PromiseConnection(this, promiseImpl);\n }\n\n _addCommandClosedState(cmd) {\n const err = new Error(\n \"Can't add new command when connection is in closed state\"\n );\n err.fatal = true;\n if (cmd.onResult) {\n cmd.onResult(err);\n } else {\n this.emit('error', err);\n }\n }\n\n _handleFatalError(err) {\n err.fatal = true;\n // stop receiving packets\n this.stream.removeAllListeners('data');\n this.addCommand = this._addCommandClosedState;\n this.write = () => {\n this.emit('error', new Error(\"Can't write in closed state\"));\n };\n this._notifyError(err);\n this._fatalError = err;\n }\n\n _handleNetworkError(err) {\n if (this.connectTimeout) {\n Timers.clearTimeout(this.connectTimeout);\n this.connectTimeout = null;\n }\n // Do not throw an error when a connection ends with a RST,ACK packet\n if (err.errno === 'ECONNRESET' && this._closing) {\n return;\n }\n this._handleFatalError(err);\n }\n\n _handleTimeoutError() {\n if (this.connectTimeout) {\n Timers.clearTimeout(this.connectTimeout);\n this.connectTimeout = null;\n }\n this.stream.destroy && this.stream.destroy();\n const err = new Error('connect ETIMEDOUT');\n err.errorno = 'ETIMEDOUT';\n err.code = 'ETIMEDOUT';\n err.syscall = 'connect';\n this._handleNetworkError(err);\n }\n\n // notify all commands in the queue and bubble error as connection \"error\"\n // called on stream error or unexpected termination\n _notifyError(err) {\n if (this.connectTimeout) {\n Timers.clearTimeout(this.connectTimeout);\n this.connectTimeout = null;\n }\n // prevent from emitting 'PROTOCOL_CONNECTION_LOST' after EPIPE or ECONNRESET\n if (this._fatalError) {\n return;\n }\n let command;\n // if there is no active command, notify connection\n // if there are commands and all of them have callbacks, pass error via callback\n let bubbleErrorToConnection = !this._command;\n if (this._command && this._command.onResult) {\n this._command.onResult(err);\n this._command = null;\n // connection handshake is special because we allow it to be implicit\n // if error happened during handshake, but there are others commands in queue\n // then bubble error to other commands and not to connection\n } else if (\n !(\n this._command &&\n this._command.constructor === Commands.ClientHandshake &&\n this._commands.length > 0\n )\n ) {\n bubbleErrorToConnection = true;\n }\n while ((command = this._commands.shift())) {\n if (command.onResult) {\n command.onResult(err);\n } else {\n bubbleErrorToConnection = true;\n }\n }\n // notify connection if some comands in the queue did not have callbacks\n // or if this is pool connection ( so it can be removed from pool )\n if (bubbleErrorToConnection || this._pool) {\n this.emit('error', err);\n }\n // close connection after emitting the event in case of a fatal error\n if (err.fatal) {\n this.close();\n }\n }\n\n write(buffer) {\n const result = this.stream.write(buffer, err => {\n if (err) {\n this._handleNetworkError(err);\n }\n });\n\n if (!result) {\n this.stream.emit('pause');\n }\n }\n\n // http://dev.mysql.com/doc/internals/en/sequence-id.html\n //\n // The sequence-id is incremented with each packet and may wrap around.\n // It starts at 0 and is reset to 0 when a new command\n // begins in the Command Phase.\n // http://dev.mysql.com/doc/internals/en/example-several-mysql-packets.html\n _resetSequenceId() {\n this.sequenceId = 0;\n this.compressedSequenceId = 0;\n }\n\n _bumpCompressedSequenceId(numPackets) {\n this.compressedSequenceId += numPackets;\n this.compressedSequenceId %= 256;\n }\n\n _bumpSequenceId(numPackets) {\n this.sequenceId += numPackets;\n this.sequenceId %= 256;\n }\n\n writePacket(packet) {\n const MAX_PACKET_LENGTH = 16777215;\n const length = packet.length();\n let chunk, offset, header;\n if (length < MAX_PACKET_LENGTH) {\n packet.writeHeader(this.sequenceId);\n if (this.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `${this._internalId} ${this.connectionId} <== ${this._command._commandName}#${this._command.stateName()}(${[this.sequenceId, packet._name, packet.length()].join(',')})`\n );\n // eslint-disable-next-line no-console\n console.log(\n `${this._internalId} ${this.connectionId} <== ${packet.buffer.toString('hex')}`\n );\n }\n this._bumpSequenceId(1);\n this.write(packet.buffer);\n } else {\n if (this.config.debug) {\n // eslint-disable-next-line no-console\n console.log(\n `${this._internalId} ${this.connectionId} <== Writing large packet, raw content not written:`\n );\n // eslint-disable-next-line no-console\n console.log(\n `${this._internalId} ${this.connectionId} <== ${this._command._commandName}#${this._command.stateName()}(${[this.sequenceId, packet._name, packet.length()].join(',')})`\n );\n }\n for (offset = 4; offset < 4 + length; offset += MAX_PACKET_LENGTH) {\n chunk = packet.buffer.slice(offset, offset + MAX_PACKET_LENGTH);\n if (chunk.length === MAX_PACKET_LENGTH) {\n header = Buffer.from([0xff, 0xff, 0xff, this.sequenceId]);\n } else {\n header = Buffer.from([\n chunk.length & 0xff,\n (chunk.length >> 8) & 0xff,\n (chunk.length >> 16) & 0xff,\n this.sequenceId\n ]);\n }\n this._bumpSequenceId(1);\n this.write(header);\n this.write(chunk);\n }\n }\n }\n\n // 0.11+ environment\n startTLS(onSecure) {\n if (this.config.debug) {\n // eslint-disable-next-line no-console\n console.log('Upgrading connection to TLS');\n }\n const secureContext = Tls.createSecureContext({\n ca: this.config.ssl.ca,\n cert: this.config.ssl.cert,\n ciphers: this.config.ssl.ciphers,\n key: this.config.ssl.key,\n passphrase: this.config.ssl.passphrase,\n minVersion: this.config.ssl.minVersion\n });\n const rejectUnauthorized = this.config.ssl.rejectUnauthorized;\n let secureEstablished = false;\n const secureSocket = new Tls.TLSSocket(this.stream, {\n rejectUnauthorized: rejectUnauthorized,\n requestCert: true,\n secureContext: secureContext,\n isServer: false\n });\n // error handler for secure socket\n secureSocket.on('_tlsError', err => {\n if (secureEstablished) {\n this._handleNetworkError(err);\n } else {\n onSecure(err);\n }\n });\n secureSocket.on('secure', () => {\n secureEstablished = true;\n onSecure(rejectUnauthorized ? secureSocket.ssl.verifyError() : null);\n });\n secureSocket.on('data', data => {\n this.packetParser.execute(data);\n });\n this.write = buffer => {\n secureSocket.write(buffer);\n };\n // start TLS communications\n secureSocket._start();\n }\n\n pipe() {\n if (this.stream instanceof Net.Stream) {\n this.stream.ondata = (data, start, end) => {\n this.packetParser.execute(data, start, end);\n };\n } else {\n this.stream.on('data', data => {\n this.packetParser.execute(\n data.parent,\n data.offset,\n data.offset + data.length\n );\n });\n }\n }\n\n protocolError(message, code) {\n // Starting with MySQL 8.0.24, if the client closes the connection\n // unexpectedly, the server will send a last ERR Packet, which we can\n // safely ignore.\n // https://dev.mysql.com/worklog/task/?id=12999\n if (this._closing) {\n return;\n }\n\n const err = new Error(message);\n err.fatal = true;\n err.code = code || 'PROTOCOL_ERROR';\n this.emit('error', err);\n }\n\n handlePacket(packet) {\n if (this._paused) {\n this._paused_packets.push(packet);\n return;\n }\n if (packet) {\n if (this.sequenceId !== packet.sequenceId) {\n const err = new Error(\n `Warning: got packets out of order. Expected ${this.sequenceId} but received ${packet.sequenceId}`\n );\n err.expected = this.sequenceId;\n err.received = packet.sequenceId;\n this.emit('warn', err); // REVIEW\n // eslint-disable-next-line no-console\n console.error(err.message);\n }\n this._bumpSequenceId(packet.numPackets);\n }\n if (this.config.debug) {\n if (packet) {\n // eslint-disable-next-line no-console\n console.log(\n ` raw: ${packet.buffer\n .slice(packet.offset, packet.offset + packet.length())\n .toString('hex')}`\n );\n // eslint-disable-next-line no-console\n console.trace();\n const commandName = this._command\n ? this._command._commandName\n : '(no command)';\n const stateName = this._command\n ? this._command.stateName()\n : '(no command)';\n // eslint-disable-next-line no-console\n console.log(\n `${this._internalId} ${this.connectionId} ==> ${commandName}#${stateName}(${[packet.sequenceId, packet.type(), packet.length()].join(',')})`\n );\n }\n }\n if (!this._command) {\n const marker = packet.peekByte();\n // If it's an Err Packet, we should use it.\n if (marker === 0xff) {\n const error = Packets.Error.fromPacket(packet);\n this.protocolError(error.message, error.code);\n } else {\n // Otherwise, it means it's some other unexpected packet.\n this.protocolError(\n 'Unexpected packet while no commands in the queue',\n 'PROTOCOL_UNEXPECTED_PACKET'\n );\n }\n this.close();\n return;\n }\n const done = this._command.execute(packet, this);\n if (done) {\n this._command = this._commands.shift();\n if (this._command) {\n this.sequenceId = 0;\n this.compressedSequenceId = 0;\n this.handlePacket();\n }\n }\n }\n\n addCommand(cmd) {\n // this.compressedSequenceId = 0;\n // this.sequenceId = 0;\n if (this.config.debug) {\n const commandName = cmd.constructor.name;\n // eslint-disable-next-line no-console\n console.log(`Add command: ${commandName}`);\n cmd._commandName = commandName;\n }\n if (!this._command) {\n this._command = cmd;\n this.handlePacket();\n } else {\n this._commands.push(cmd);\n }\n return cmd;\n }\n\n format(sql, values) {\n if (typeof this.config.queryFormat === 'function') {\n return this.config.queryFormat.call(\n this,\n sql,\n values,\n this.config.timezone\n );\n }\n const opts = {\n sql: sql,\n values: values\n };\n this._resolveNamedPlaceholders(opts);\n return SqlString.format(\n opts.sql,\n opts.values,\n this.config.stringifyObjects,\n this.config.timezone\n );\n }\n\n escape(value) {\n return SqlString.escape(value, false, this.config.timezone);\n }\n\n escapeId(value) {\n return SqlString.escapeId(value, false);\n }\n\n raw(sql) {\n return SqlString.raw(sql);\n }\n\n _resolveNamedPlaceholders(options) {\n let unnamed;\n if (this.config.namedPlaceholders || options.namedPlaceholders) {\n if (Array.isArray(options.values)) {\n // if an array is provided as the values, assume the conversion is not necessary.\n // this allows the usage of unnamed placeholders even if the namedPlaceholders flag is enabled.\n return\n }\n if (convertNamedPlaceholders === null) {\n convertNamedPlaceholders = require('named-placeholders')();\n }\n unnamed = convertNamedPlaceholders(options.sql, options.values);\n options.sql = unnamed[0];\n options.values = unnamed[1];\n }\n }\n\n query(sql, values, cb) {\n let cmdQuery;\n if (sql.constructor === Commands.Query) {\n cmdQuery = sql;\n } else {\n cmdQuery = Connection.createQuery(sql, values, cb, this.config);\n }\n this._resolveNamedPlaceholders(cmdQuery);\n const rawSql = this.format(cmdQuery.sql, cmdQuery.values !== undefined ? cmdQuery.values : []);\n cmdQuery.sql = rawSql;\n return this.addCommand(cmdQuery);\n }\n\n pause() {\n this._paused = true;\n this.stream.pause();\n }\n\n resume() {\n let packet;\n this._paused = false;\n while ((packet = this._paused_packets.shift())) {\n this.handlePacket(packet);\n // don't resume if packet hander paused connection\n if (this._paused) {\n return;\n }\n }\n this.stream.resume();\n }\n\n // TODO: named placeholders support\n prepare(options, cb) {\n if (typeof options === 'string') {\n options = { sql: options };\n }\n return this.addCommand(new Commands.Prepare(options, cb));\n }\n\n unprepare(sql) {\n let options = {};\n if (typeof sql === 'object') {\n options = sql;\n } else {\n options.sql = sql;\n }\n const key = Connection.statementKey(options);\n const stmt = this._statements.get(key);\n if (stmt) {\n this._statements.del(key);\n stmt.close();\n }\n return stmt;\n }\n\n execute(sql, values, cb) {\n let options = {};\n if (typeof sql === 'object') {\n // execute(options, cb)\n options = sql;\n if (typeof values === 'function') {\n cb = values;\n } else {\n options.values = options.values || values;\n }\n } else if (typeof values === 'function') {\n // execute(sql, cb)\n cb = values;\n options.sql = sql;\n options.values = undefined;\n } else {\n // execute(sql, values, cb)\n options.sql = sql;\n options.values = values;\n }\n this._resolveNamedPlaceholders(options);\n // check for values containing undefined\n if (options.values) {\n //If namedPlaceholder is not enabled and object is passed as bind parameters\n if (!Array.isArray(options.values)) {\n throw new TypeError(\n 'Bind parameters must be array if namedPlaceholders parameter is not enabled'\n );\n }\n options.values.forEach(val => {\n //If namedPlaceholder is not enabled and object is passed as bind parameters\n if (!Array.isArray(options.values)) {\n throw new TypeError(\n 'Bind parameters must be array if namedPlaceholders parameter is not enabled'\n );\n }\n if (val === undefined) {\n throw new TypeError(\n 'Bind parameters must not contain undefined. To pass SQL NULL specify JS null'\n );\n }\n if (typeof val === 'function') {\n throw new TypeError(\n 'Bind parameters must not contain function(s). To pass the body of a function as a string call .toString() first'\n );\n }\n });\n }\n const executeCommand = new Commands.Execute(options, cb);\n const prepareCommand = new Commands.Prepare(options, (err, stmt) => {\n if (err) {\n // skip execute command if prepare failed, we have main\n // combined callback here\n executeCommand.start = function() {\n return null;\n };\n if (cb) {\n cb(err);\n } else {\n executeCommand.emit('error', err);\n }\n executeCommand.emit('end');\n return;\n }\n executeCommand.statement = stmt;\n });\n this.addCommand(prepareCommand);\n this.addCommand(executeCommand);\n return executeCommand;\n }\n\n changeUser(options, callback) {\n if (!callback && typeof options === 'function') {\n callback = options;\n options = {};\n }\n const charsetNumber = options.charset\n ? ConnectionConfig.getCharsetNumber(options.charset)\n : this.config.charsetNumber;\n return this.addCommand(\n new Commands.ChangeUser(\n {\n user: options.user || this.config.user,\n password: options.password || this.config.password,\n passwordSha1: options.passwordSha1 || this.config.passwordSha1,\n database: options.database || this.config.database,\n timeout: options.timeout,\n charsetNumber: charsetNumber,\n currentConfig: this.config\n },\n err => {\n if (err) {\n err.fatal = true;\n }\n if (callback) {\n callback(err);\n }\n }\n )\n );\n }\n\n // transaction helpers\n beginTransaction(cb) {\n return this.query('START TRANSACTION', cb);\n }\n\n commit(cb) {\n return this.query('COMMIT', cb);\n }\n\n rollback(cb) {\n return this.query('ROLLBACK', cb);\n }\n\n ping(cb) {\n return this.addCommand(new Commands.Ping(cb));\n }\n\n _registerSlave(opts, cb) {\n return this.addCommand(new Commands.RegisterSlave(opts, cb));\n }\n\n _binlogDump(opts, cb) {\n return this.addCommand(new Commands.BinlogDump(opts, cb));\n }\n\n // currently just alias to close\n destroy() {\n this.close();\n }\n\n close() {\n if (this.connectTimeout) {\n Timers.clearTimeout(this.connectTimeout);\n this.connectTimeout = null;\n }\n this._closing = true;\n this.stream.end();\n this.addCommand = this._addCommandClosedState;\n }\n\n createBinlogStream(opts) {\n // TODO: create proper stream class\n // TODO: use through2\n let test = 1;\n const stream = new Readable({ objectMode: true });\n stream._read = function() {\n return {\n data: test++\n };\n };\n this._registerSlave(opts, () => {\n const dumpCmd = this._binlogDump(opts);\n dumpCmd.on('event', ev => {\n stream.push(ev);\n });\n dumpCmd.on('eof', () => {\n stream.push(null);\n // if non-blocking, then close stream to prevent errors\n if (opts.flags && opts.flags & 0x01) {\n this.close();\n }\n });\n // TODO: pipe errors as well\n });\n return stream;\n }\n\n connect(cb) {\n if (!cb) {\n return;\n }\n if (this._fatalError || this._protocolError) {\n return cb(this._fatalError || this._protocolError);\n }\n if (this._handshakePacket) {\n return cb(null, this);\n }\n let connectCalled = 0;\n function callbackOnce(isErrorHandler) {\n return function(param) {\n if (!connectCalled) {\n if (isErrorHandler) {\n cb(param);\n } else {\n cb(null, param);\n }\n }\n connectCalled = 1;\n };\n }\n this.once('error', callbackOnce(true));\n this.once('connect', callbackOnce(false));\n }\n\n // ===================================\n // outgoing server connection methods\n // ===================================\n writeColumns(columns) {\n this.writePacket(Packets.ResultSetHeader.toPacket(columns.length));\n columns.forEach(column => {\n this.writePacket(\n Packets.ColumnDefinition.toPacket(column, this.serverConfig.encoding)\n );\n });\n this.writeEof();\n }\n\n // row is array of columns, not hash\n writeTextRow(column) {\n this.writePacket(\n Packets.TextRow.toPacket(column, this.serverConfig.encoding)\n );\n }\n\n writeTextResult(rows, columns) {\n this.writeColumns(columns);\n rows.forEach(row => {\n const arrayRow = new Array(columns.length);\n columns.forEach(column => {\n arrayRow.push(row[column.name]);\n });\n this.writeTextRow(arrayRow);\n });\n this.writeEof();\n }\n\n writeEof(warnings, statusFlags) {\n this.writePacket(Packets.EOF.toPacket(warnings, statusFlags));\n }\n\n writeOk(args) {\n if (!args) {\n args = { affectedRows: 0 };\n }\n this.writePacket(Packets.OK.toPacket(args, this.serverConfig.encoding));\n }\n\n writeError(args) {\n // if we want to send error before initial hello was sent, use default encoding\n const encoding = this.serverConfig ? this.serverConfig.encoding : 'cesu8';\n this.writePacket(Packets.Error.toPacket(args, encoding));\n }\n\n serverHandshake(args) {\n this.serverConfig = args;\n this.serverConfig.encoding =\n CharsetToEncoding[this.serverConfig.characterSet];\n return this.addCommand(new Commands.ServerHandshake(args));\n }\n\n // ===============================================================\n end(callback) {\n if (this.config.isServer) {\n this._closing = true;\n const quitCmd = new EventEmitter();\n setImmediate(() => {\n this.stream.end();\n quitCmd.emit('end');\n });\n return quitCmd;\n }\n // trigger error if more commands enqueued after end command\n const quitCmd = this.addCommand(new Commands.Quit(callback));\n this.addCommand = this._addCommandClosedState;\n return quitCmd;\n }\n\n static createQuery(sql, values, cb, config) {\n let options = {\n rowsAsArray: config.rowsAsArray\n };\n if (typeof sql === 'object') {\n // query(options, cb)\n options = sql;\n if (typeof values === 'function') {\n cb = values;\n } else if (values !== undefined) {\n options.values = values;\n }\n } else if (typeof values === 'function') {\n // query(sql, cb)\n cb = values;\n options.sql = sql;\n options.values = undefined;\n } else {\n // query(sql, values, cb)\n options.sql = sql;\n options.values = values;\n }\n return new Commands.Query(options, cb);\n }\n\n static statementKey(options) {\n return (\n `${typeof options.nestTables}/${options.nestTables}/${options.rowsAsArray}${options.sql}`\n );\n }\n}\n\nif (Tls.TLSSocket) {\n // not supported\n} else {\n Connection.prototype.startTLS = function _startTLS(onSecure) {\n if (this.config.debug) {\n // eslint-disable-next-line no-console\n console.log('Upgrading connection to TLS');\n }\n const crypto = require('crypto');\n const config = this.config;\n const stream = this.stream;\n const rejectUnauthorized = this.config.ssl.rejectUnauthorized;\n const credentials = crypto.createCredentials({\n key: config.ssl.key,\n cert: config.ssl.cert,\n passphrase: config.ssl.passphrase,\n ca: config.ssl.ca,\n ciphers: config.ssl.ciphers\n });\n const securePair = Tls.createSecurePair(\n credentials,\n false,\n true,\n rejectUnauthorized\n );\n\n if (stream.ondata) {\n stream.ondata = null;\n }\n stream.removeAllListeners('data');\n stream.pipe(securePair.encrypted);\n securePair.encrypted.pipe(stream);\n securePair.cleartext.on('data', data => {\n this.packetParser.execute(data);\n });\n this.write = function(buffer) {\n securePair.cleartext.write(buffer);\n };\n securePair.on('secure', () => {\n onSecure(rejectUnauthorized ? securePair.ssl.verifyError() : null);\n });\n };\n}\n\nmodule.exports = Connection;\n","'use strict';\n\nconst Iconv = require('iconv-lite');\n\nexports.decode = function(buffer, encoding, start, end, options) {\n if (Buffer.isEncoding(encoding)) {\n return buffer.toString(encoding, start, end);\n }\n\n const decoder = Iconv.getDecoder(encoding, options || {});\n\n const res = decoder.write(buffer.slice(start, end));\n const trail = decoder.end();\n\n return trail ? res + trail : res;\n};\n\nexports.encode = function(string, encoding, options) {\n if (Buffer.isEncoding(encoding)) {\n return Buffer.from(string, encoding);\n }\n\n const encoder = Iconv.getEncoder(encoding, options || {});\n\n const res = encoder.write(string);\n const trail = encoder.end();\n\n return trail && trail.length > 0 ? Buffer.concat([res, trail]) : res;\n};\n","module.exports = require(\"process\");","'use strict';\n\nexports.BIG5_CHINESE_CI = 1;\nexports.LATIN2_CZECH_CS = 2;\nexports.DEC8_SWEDISH_CI = 3;\nexports.CP850_GENERAL_CI = 4;\nexports.LATIN1_GERMAN1_CI = 5;\nexports.HP8_ENGLISH_CI = 6;\nexports.KOI8R_GENERAL_CI = 7;\nexports.LATIN1_SWEDISH_CI = 8;\nexports.LATIN2_GENERAL_CI = 9;\nexports.SWE7_SWEDISH_CI = 10;\nexports.ASCII_GENERAL_CI = 11;\nexports.UJIS_JAPANESE_CI = 12;\nexports.SJIS_JAPANESE_CI = 13;\nexports.CP1251_BULGARIAN_CI = 14;\nexports.LATIN1_DANISH_CI = 15;\nexports.HEBREW_GENERAL_CI = 16;\nexports.TIS620_THAI_CI = 18;\nexports.EUCKR_KOREAN_CI = 19;\nexports.LATIN7_ESTONIAN_CS = 20;\nexports.LATIN2_HUNGARIAN_CI = 21;\nexports.KOI8U_GENERAL_CI = 22;\nexports.CP1251_UKRAINIAN_CI = 23;\nexports.GB2312_CHINESE_CI = 24;\nexports.GREEK_GENERAL_CI = 25;\nexports.CP1250_GENERAL_CI = 26;\nexports.LATIN2_CROATIAN_CI = 27;\nexports.GBK_CHINESE_CI = 28;\nexports.CP1257_LITHUANIAN_CI = 29;\nexports.LATIN5_TURKISH_CI = 30;\nexports.LATIN1_GERMAN2_CI = 31;\nexports.ARMSCII8_GENERAL_CI = 32;\nexports.UTF8_GENERAL_CI = 33;\nexports.CP1250_CZECH_CS = 34;\nexports.UCS2_GENERAL_CI = 35;\nexports.CP866_GENERAL_CI = 36;\nexports.KEYBCS2_GENERAL_CI = 37;\nexports.MACCE_GENERAL_CI = 38;\nexports.MACROMAN_GENERAL_CI = 39;\nexports.CP852_GENERAL_CI = 40;\nexports.LATIN7_GENERAL_CI = 41;\nexports.LATIN7_GENERAL_CS = 42;\nexports.MACCE_BIN = 43;\nexports.CP1250_CROATIAN_CI = 44;\nexports.UTF8MB4_GENERAL_CI = 45;\nexports.UTF8MB4_BIN = 46;\nexports.LATIN1_BIN = 47;\nexports.LATIN1_GENERAL_CI = 48;\nexports.LATIN1_GENERAL_CS = 49;\nexports.CP1251_BIN = 50;\nexports.CP1251_GENERAL_CI = 51;\nexports.CP1251_GENERAL_CS = 52;\nexports.MACROMAN_BIN = 53;\nexports.UTF16_GENERAL_CI = 54;\nexports.UTF16_BIN = 55;\nexports.UTF16LE_GENERAL_CI = 56;\nexports.CP1256_GENERAL_CI = 57;\nexports.CP1257_BIN = 58;\nexports.CP1257_GENERAL_CI = 59;\nexports.UTF32_GENERAL_CI = 60;\nexports.UTF32_BIN = 61;\nexports.UTF16LE_BIN = 62;\nexports.BINARY = 63;\nexports.ARMSCII8_BIN = 64;\nexports.ASCII_BIN = 65;\nexports.CP1250_BIN = 66;\nexports.CP1256_BIN = 67;\nexports.CP866_BIN = 68;\nexports.DEC8_BIN = 69;\nexports.GREEK_BIN = 70;\nexports.HEBREW_BIN = 71;\nexports.HP8_BIN = 72;\nexports.KEYBCS2_BIN = 73;\nexports.KOI8R_BIN = 74;\nexports.KOI8U_BIN = 75;\nexports.UTF8_TOLOWER_CI = 76;\nexports.LATIN2_BIN = 77;\nexports.LATIN5_BIN = 78;\nexports.LATIN7_BIN = 79;\nexports.CP850_BIN = 80;\nexports.CP852_BIN = 81;\nexports.SWE7_BIN = 82;\nexports.UTF8_BIN = 83;\nexports.BIG5_BIN = 84;\nexports.EUCKR_BIN = 85;\nexports.GB2312_BIN = 86;\nexports.GBK_BIN = 87;\nexports.SJIS_BIN = 88;\nexports.TIS620_BIN = 89;\nexports.UCS2_BIN = 90;\nexports.UJIS_BIN = 91;\nexports.GEOSTD8_GENERAL_CI = 92;\nexports.GEOSTD8_BIN = 93;\nexports.LATIN1_SPANISH_CI = 94;\nexports.CP932_JAPANESE_CI = 95;\nexports.CP932_BIN = 96;\nexports.EUCJPMS_JAPANESE_CI = 97;\nexports.EUCJPMS_BIN = 98;\nexports.CP1250_POLISH_CI = 99;\nexports.UTF16_UNICODE_CI = 101;\nexports.UTF16_ICELANDIC_CI = 102;\nexports.UTF16_LATVIAN_CI = 103;\nexports.UTF16_ROMANIAN_CI = 104;\nexports.UTF16_SLOVENIAN_CI = 105;\nexports.UTF16_POLISH_CI = 106;\nexports.UTF16_ESTONIAN_CI = 107;\nexports.UTF16_SPANISH_CI = 108;\nexports.UTF16_SWEDISH_CI = 109;\nexports.UTF16_TURKISH_CI = 110;\nexports.UTF16_CZECH_CI = 111;\nexports.UTF16_DANISH_CI = 112;\nexports.UTF16_LITHUANIAN_CI = 113;\nexports.UTF16_SLOVAK_CI = 114;\nexports.UTF16_SPANISH2_CI = 115;\nexports.UTF16_ROMAN_CI = 116;\nexports.UTF16_PERSIAN_CI = 117;\nexports.UTF16_ESPERANTO_CI = 118;\nexports.UTF16_HUNGARIAN_CI = 119;\nexports.UTF16_SINHALA_CI = 120;\nexports.UTF16_GERMAN2_CI = 121;\nexports.UTF16_CROATIAN_CI = 122;\nexports.UTF16_UNICODE_520_CI = 123;\nexports.UTF16_VIETNAMESE_CI = 124;\nexports.UCS2_UNICODE_CI = 128;\nexports.UCS2_ICELANDIC_CI = 129;\nexports.UCS2_LATVIAN_CI = 130;\nexports.UCS2_ROMANIAN_CI = 131;\nexports.UCS2_SLOVENIAN_CI = 132;\nexports.UCS2_POLISH_CI = 133;\nexports.UCS2_ESTONIAN_CI = 134;\nexports.UCS2_SPANISH_CI = 135;\nexports.UCS2_SWEDISH_CI = 136;\nexports.UCS2_TURKISH_CI = 137;\nexports.UCS2_CZECH_CI = 138;\nexports.UCS2_DANISH_CI = 139;\nexports.UCS2_LITHUANIAN_CI = 140;\nexports.UCS2_SLOVAK_CI = 141;\nexports.UCS2_SPANISH2_CI = 142;\nexports.UCS2_ROMAN_CI = 143;\nexports.UCS2_PERSIAN_CI = 144;\nexports.UCS2_ESPERANTO_CI = 145;\nexports.UCS2_HUNGARIAN_CI = 146;\nexports.UCS2_SINHALA_CI = 147;\nexports.UCS2_GERMAN2_CI = 148;\nexports.UCS2_CROATIAN_CI = 149;\nexports.UCS2_UNICODE_520_CI = 150;\nexports.UCS2_VIETNAMESE_CI = 151;\nexports.UCS2_GENERAL_MYSQL500_CI = 159;\nexports.UTF32_UNICODE_CI = 160;\nexports.UTF32_ICELANDIC_CI = 161;\nexports.UTF32_LATVIAN_CI = 162;\nexports.UTF32_ROMANIAN_CI = 163;\nexports.UTF32_SLOVENIAN_CI = 164;\nexports.UTF32_POLISH_CI = 165;\nexports.UTF32_ESTONIAN_CI = 166;\nexports.UTF32_SPANISH_CI = 167;\nexports.UTF32_SWEDISH_CI = 168;\nexports.UTF32_TURKISH_CI = 169;\nexports.UTF32_CZECH_CI = 170;\nexports.UTF32_DANISH_CI = 171;\nexports.UTF32_LITHUANIAN_CI = 172;\nexports.UTF32_SLOVAK_CI = 173;\nexports.UTF32_SPANISH2_CI = 174;\nexports.UTF32_ROMAN_CI = 175;\nexports.UTF32_PERSIAN_CI = 176;\nexports.UTF32_ESPERANTO_CI = 177;\nexports.UTF32_HUNGARIAN_CI = 178;\nexports.UTF32_SINHALA_CI = 179;\nexports.UTF32_GERMAN2_CI = 180;\nexports.UTF32_CROATIAN_CI = 181;\nexports.UTF32_UNICODE_520_CI = 182;\nexports.UTF32_VIETNAMESE_CI = 183;\nexports.UTF8_UNICODE_CI = 192;\nexports.UTF8_ICELANDIC_CI = 193;\nexports.UTF8_LATVIAN_CI = 194;\nexports.UTF8_ROMANIAN_CI = 195;\nexports.UTF8_SLOVENIAN_CI = 196;\nexports.UTF8_POLISH_CI = 197;\nexports.UTF8_ESTONIAN_CI = 198;\nexports.UTF8_SPANISH_CI = 199;\nexports.UTF8_SWEDISH_CI = 200;\nexports.UTF8_TURKISH_CI = 201;\nexports.UTF8_CZECH_CI = 202;\nexports.UTF8_DANISH_CI = 203;\nexports.UTF8_LITHUANIAN_CI = 204;\nexports.UTF8_SLOVAK_CI = 205;\nexports.UTF8_SPANISH2_CI = 206;\nexports.UTF8_ROMAN_CI = 207;\nexports.UTF8_PERSIAN_CI = 208;\nexports.UTF8_ESPERANTO_CI = 209;\nexports.UTF8_HUNGARIAN_CI = 210;\nexports.UTF8_SINHALA_CI = 211;\nexports.UTF8_GERMAN2_CI = 212;\nexports.UTF8_CROATIAN_CI = 213;\nexports.UTF8_UNICODE_520_CI = 214;\nexports.UTF8_VIETNAMESE_CI = 215;\nexports.UTF8_GENERAL_MYSQL500_CI = 223;\nexports.UTF8MB4_UNICODE_CI = 224;\nexports.UTF8MB4_ICELANDIC_CI = 225;\nexports.UTF8MB4_LATVIAN_CI = 226;\nexports.UTF8MB4_ROMANIAN_CI = 227;\nexports.UTF8MB4_SLOVENIAN_CI = 228;\nexports.UTF8MB4_POLISH_CI = 229;\nexports.UTF8MB4_ESTONIAN_CI = 230;\nexports.UTF8MB4_SPANISH_CI = 231;\nexports.UTF8MB4_SWEDISH_CI = 232;\nexports.UTF8MB4_TURKISH_CI = 233;\nexports.UTF8MB4_CZECH_CI = 234;\nexports.UTF8MB4_DANISH_CI = 235;\nexports.UTF8MB4_LITHUANIAN_CI = 236;\nexports.UTF8MB4_SLOVAK_CI = 237;\nexports.UTF8MB4_SPANISH2_CI = 238;\nexports.UTF8MB4_ROMAN_CI = 239;\nexports.UTF8MB4_PERSIAN_CI = 240;\nexports.UTF8MB4_ESPERANTO_CI = 241;\nexports.UTF8MB4_HUNGARIAN_CI = 242;\nexports.UTF8MB4_SINHALA_CI = 243;\nexports.UTF8MB4_GERMAN2_CI = 244;\nexports.UTF8MB4_CROATIAN_CI = 245;\nexports.UTF8MB4_UNICODE_520_CI = 246;\nexports.UTF8MB4_VIETNAMESE_CI = 247;\nexports.GB18030_CHINESE_CI = 248;\nexports.GB18030_BIN = 249;\nexports.GB18030_UNICODE_520_CI = 250;\nexports.UTF8_GENERAL50_CI = 253;\nexports.UTF8MB4_0900_AI_CI = 255;\nexports.UTF8MB4_CS_0900_AI_CI = 266;\nexports.UTF8MB4_DA_0900_AI_CI = 267;\nexports.UTF8MB4_DE_PB_0900_AI_CI = 256;\nexports.UTF8MB4_EO_0900_AI_CI = 273;\nexports.UTF8MB4_ES_0900_AI_CI = 263;\nexports.UTF8MB4_ES_TRAD_0900_AI_CI = 270;\nexports.UTF8MB4_ET_0900_AI_CI = 262;\nexports.UTF8MB4_HR_0900_AI_CI = 275;\nexports.UTF8MB4_HU_0900_AI_CI = 274;\nexports.UTF8MB4_IS_0900_AI_CI = 257;\nexports.UTF8MB4_LA_0900_AI_CI = 271;\nexports.UTF8MB4_LT_0900_AI_CI = 268;\nexports.UTF8MB4_LV_0900_AI_CI = 258;\nexports.UTF8MB4_PL_0900_AI_CI = 261;\nexports.UTF8MB4_RO_0900_AI_CI = 259;\nexports.UTF8MB4_SK_0900_AI_CI = 269;\nexports.UTF8MB4_SL_0900_AI_CI = 260;\nexports.UTF8MB4_SV_0900_AI_CI = 264;\nexports.UTF8MB4_TR_0900_AI_CI = 265;\nexports.UTF8MB4_VI_0900_AI_CI = 277;\n\n// short aliases\nexports.BIG5 = exports.BIG5_CHINESE_CI;\nexports.DEC8 = exports.DEC8_SWEDISH_CI;\nexports.CP850 = exports.CP850_GENERAL_CI;\nexports.HP8 = exports.HP8_ENGLISH_CI;\nexports.KOI8R = exports.KOI8R_GENERAL_CI;\nexports.LATIN1 = exports.LATIN1_SWEDISH_CI;\nexports.LATIN2 = exports.LATIN2_GENERAL_CI;\nexports.SWE7 = exports.SWE7_SWEDISH_CI;\nexports.ASCII = exports.ASCII_GENERAL_CI;\nexports.UJIS = exports.UJIS_JAPANESE_CI;\nexports.SJIS = exports.SJIS_JAPANESE_CI;\nexports.HEBREW = exports.HEBREW_GENERAL_CI;\nexports.TIS620 = exports.TIS620_THAI_CI;\nexports.EUCKR = exports.EUCKR_KOREAN_CI;\nexports.KOI8U = exports.KOI8U_GENERAL_CI;\nexports.GB2312 = exports.GB2312_CHINESE_CI;\nexports.GREEK = exports.GREEK_GENERAL_CI;\nexports.CP1250 = exports.CP1250_GENERAL_CI;\nexports.GBK = exports.GBK_CHINESE_CI;\nexports.LATIN5 = exports.LATIN5_TURKISH_CI;\nexports.ARMSCII8 = exports.ARMSCII8_GENERAL_CI;\nexports.UTF8 = exports.UTF8_GENERAL_CI;\nexports.UCS2 = exports.UCS2_GENERAL_CI;\nexports.CP866 = exports.CP866_GENERAL_CI;\nexports.KEYBCS2 = exports.KEYBCS2_GENERAL_CI;\nexports.MACCE = exports.MACCE_GENERAL_CI;\nexports.MACROMAN = exports.MACROMAN_GENERAL_CI;\nexports.CP852 = exports.CP852_GENERAL_CI;\nexports.LATIN7 = exports.LATIN7_GENERAL_CI;\nexports.UTF8MB4 = exports.UTF8MB4_GENERAL_CI;\nexports.CP1251 = exports.CP1251_GENERAL_CI;\nexports.UTF16 = exports.UTF16_GENERAL_CI;\nexports.UTF16LE = exports.UTF16LE_GENERAL_CI;\nexports.CP1256 = exports.CP1256_GENERAL_CI;\nexports.CP1257 = exports.CP1257_GENERAL_CI;\nexports.UTF32 = exports.UTF32_GENERAL_CI;\nexports.CP932 = exports.CP932_JAPANESE_CI;\nexports.EUCJPMS = exports.EUCJPMS_JAPANESE_CI;\nexports.GB18030 = exports.GB18030_CHINESE_CI;\nexports.GEOSTD8 = exports.GEOSTD8_GENERAL_CI;\n","'use strict';\n\nconst { URL } = require('url');\nconst ClientConstants = require('./constants/client');\nconst Charsets = require('./constants/charsets');\nlet SSLProfiles = null;\n\nconst validOptions = {\n authPlugins: 1,\n authSwitchHandler: 1,\n bigNumberStrings: 1,\n charset: 1,\n charsetNumber: 1,\n compress: 1,\n connectAttributes: 1,\n connectTimeout: 1,\n database: 1,\n dateStrings: 1,\n debug: 1,\n decimalNumbers: 1,\n enableKeepAlive: 1,\n flags: 1,\n host: 1,\n insecureAuth: 1,\n isServer: 1,\n keepAliveInitialDelay: 1,\n localAddress: 1,\n maxPreparedStatements: 1,\n multipleStatements: 1,\n namedPlaceholders: 1,\n nestTables: 1,\n password: 1,\n passwordSha1: 1,\n pool: 1,\n port: 1,\n queryFormat: 1,\n rowsAsArray: 1,\n socketPath: 1,\n ssl: 1,\n stream: 1,\n stringifyObjects: 1,\n supportBigNumbers: 1,\n timezone: 1,\n trace: 1,\n typeCast: 1,\n uri: 1,\n user: 1,\n // These options are used for Pool\n connectionLimit: 1,\n Promise: 1,\n queueLimit: 1,\n waitForConnections: 1\n};\n\nclass ConnectionConfig {\n constructor(options) {\n if (typeof options === 'string') {\n options = ConnectionConfig.parseUrl(options);\n } else if (options && options.uri) {\n const uriOptions = ConnectionConfig.parseUrl(options.uri);\n for (const key in uriOptions) {\n if (!Object.prototype.hasOwnProperty.call(uriOptions, key)) continue;\n if (options[key]) continue;\n options[key] = uriOptions[key];\n }\n }\n for (const key in options) {\n if (!Object.prototype.hasOwnProperty.call(options, key)) continue;\n if (validOptions[key] !== 1) {\n // REVIEW: Should this be emitted somehow?\n // eslint-disable-next-line no-console\n console.error(\n `Ignoring invalid configuration option passed to Connection: ${key}. This is currently a warning, but in future versions of MySQL2, an error will be thrown if you pass an invalid configuration option to a Connection`\n );\n }\n }\n this.isServer = options.isServer;\n this.stream = options.stream;\n this.host = options.host || 'localhost';\n this.port = options.port || 3306;\n this.localAddress = options.localAddress;\n this.socketPath = options.socketPath;\n this.user = options.user || undefined;\n this.password = options.password || undefined;\n this.passwordSha1 = options.passwordSha1 || undefined;\n this.database = options.database;\n this.connectTimeout = isNaN(options.connectTimeout)\n ? 10 * 1000\n : options.connectTimeout;\n this.insecureAuth = options.insecureAuth || false;\n this.supportBigNumbers = options.supportBigNumbers || false;\n this.bigNumberStrings = options.bigNumberStrings || false;\n this.decimalNumbers = options.decimalNumbers || false;\n this.dateStrings = options.dateStrings || false;\n this.debug = options.debug;\n this.trace = options.trace !== false;\n this.stringifyObjects = options.stringifyObjects || false;\n this.enableKeepAlive = !!options.enableKeepAlive;\n this.keepAliveInitialDelay = options.keepAliveInitialDelay || 0;\n if (\n options.timezone &&\n !/^(?:local|Z|[ +-]\\d\\d:\\d\\d)$/.test(options.timezone)\n ) {\n // strictly supports timezones specified by mysqljs/mysql:\n // https://github.com/mysqljs/mysql#user-content-connection-options\n // eslint-disable-next-line no-console\n console.error(\n `Ignoring invalid timezone passed to Connection: ${options.timezone}. This is currently a warning, but in future versions of MySQL2, an error will be thrown if you pass an invalid configuration option to a Connection`\n );\n // SqlStrings falls back to UTC on invalid timezone\n this.timezone = 'Z';\n } else {\n this.timezone = options.timezone || 'local';\n }\n this.queryFormat = options.queryFormat;\n this.pool = options.pool || undefined;\n this.ssl =\n typeof options.ssl === 'string'\n ? ConnectionConfig.getSSLProfile(options.ssl)\n : options.ssl || false;\n this.multipleStatements = options.multipleStatements || false;\n this.rowsAsArray = options.rowsAsArray || false;\n this.namedPlaceholders = options.namedPlaceholders || false;\n this.nestTables =\n options.nestTables === undefined ? undefined : options.nestTables;\n this.typeCast = options.typeCast === undefined ? true : options.typeCast;\n if (this.timezone[0] === ' ') {\n // \"+\" is a url encoded char for space so it\n // gets translated to space when giving a\n // connection string..\n this.timezone = `+${this.timezone.substr(1)}`;\n }\n if (this.ssl) {\n if (typeof this.ssl !== 'object') {\n throw new TypeError(\n `SSL profile must be an object, instead it's a ${typeof this.ssl}`\n );\n }\n // Default rejectUnauthorized to true\n this.ssl.rejectUnauthorized = this.ssl.rejectUnauthorized !== false;\n }\n this.maxPacketSize = 0;\n this.charsetNumber = options.charset\n ? ConnectionConfig.getCharsetNumber(options.charset)\n : options.charsetNumber || Charsets.UTF8MB4_UNICODE_CI;\n this.compress = options.compress || false;\n this.authPlugins = options.authPlugins;\n this.authSwitchHandler = options.authSwitchHandler;\n this.clientFlags = ConnectionConfig.mergeFlags(\n ConnectionConfig.getDefaultFlags(options),\n options.flags || ''\n );\n this.connectAttributes = options.connectAttributes;\n this.maxPreparedStatements = options.maxPreparedStatements || 16000;\n }\n\n static mergeFlags(default_flags, user_flags) {\n let flags = 0x0,\n i;\n if (!Array.isArray(user_flags)) {\n user_flags = String(user_flags || '')\n .toUpperCase()\n .split(/\\s*,+\\s*/);\n }\n // add default flags unless \"blacklisted\"\n for (i in default_flags) {\n if (user_flags.indexOf(`-${default_flags[i]}`) >= 0) {\n continue;\n }\n flags |= ClientConstants[default_flags[i]] || 0x0;\n }\n // add user flags unless already already added\n for (i in user_flags) {\n if (user_flags[i][0] === '-') {\n continue;\n }\n if (default_flags.indexOf(user_flags[i]) >= 0) {\n continue;\n }\n flags |= ClientConstants[user_flags[i]] || 0x0;\n }\n return flags;\n }\n\n static getDefaultFlags(options) {\n const defaultFlags = [\n 'LONG_PASSWORD',\n 'FOUND_ROWS',\n 'LONG_FLAG',\n 'CONNECT_WITH_DB',\n 'ODBC',\n 'LOCAL_FILES',\n 'IGNORE_SPACE',\n 'PROTOCOL_41',\n 'IGNORE_SIGPIPE',\n 'TRANSACTIONS',\n 'RESERVED',\n 'SECURE_CONNECTION',\n 'MULTI_RESULTS',\n 'TRANSACTIONS',\n 'SESSION_TRACK'\n ];\n if (options && options.multipleStatements) {\n defaultFlags.push('MULTI_STATEMENTS');\n }\n defaultFlags.push('PLUGIN_AUTH');\n defaultFlags.push('PLUGIN_AUTH_LENENC_CLIENT_DATA');\n\n if (options && options.connectAttributes) {\n defaultFlags.push('CONNECT_ATTRS');\n }\n return defaultFlags;\n }\n\n static getCharsetNumber(charset) {\n const num = Charsets[charset.toUpperCase()];\n if (num === undefined) {\n throw new TypeError(`Unknown charset '${charset}'`);\n }\n return num;\n }\n\n static getSSLProfile(name) {\n if (!SSLProfiles) {\n SSLProfiles = require('./constants/ssl_profiles.js');\n }\n const ssl = SSLProfiles[name];\n if (ssl === undefined) {\n throw new TypeError(`Unknown SSL profile '${name}'`);\n }\n return ssl;\n }\n\n static parseUrl(url) {\n const parsedUrl = new URL(url);\n const options = {\n host: parsedUrl.hostname,\n port: parsedUrl.port,\n database: parsedUrl.pathname.substr(1),\n user: parsedUrl.username,\n password: parsedUrl.password\n };\n parsedUrl.searchParams.forEach((value, key) => {\n try {\n // Try to parse this as a JSON expression first\n options[key] = JSON.parse(value);\n } catch (err) {\n // Otherwise assume it is a plain string\n options[key] = value;\n }\n });\n return options;\n }\n}\n\nmodule.exports = ConnectionConfig;\n","'use strict';\n\nconst colors = require('colors/safe');\nconst { LEVEL, MESSAGE } = require('triple-beam');\n\n//\n// Fix colors not appearing in non-tty environments\n//\ncolors.enabled = true;\n\n/**\n * @property {RegExp} hasSpace\n * Simple regex to check for presence of spaces.\n */\nconst hasSpace = /\\s+/;\n\n/*\n * Colorizer format. Wraps the `level` and/or `message` properties\n * of the `info` objects with ANSI color codes based on a few options.\n */\nclass Colorizer {\n constructor(opts = {}) {\n if (opts.colors) {\n this.addColors(opts.colors);\n }\n\n this.options = opts;\n }\n\n /*\n * Adds the colors Object to the set of allColors\n * known by the Colorizer\n *\n * @param {Object} colors Set of color mappings to add.\n */\n static addColors(clrs) {\n const nextColors = Object.keys(clrs).reduce((acc, level) => {\n acc[level] = hasSpace.test(clrs[level])\n ? clrs[level].split(hasSpace)\n : clrs[level];\n\n return acc;\n }, {});\n\n Colorizer.allColors = Object.assign({}, Colorizer.allColors || {}, nextColors);\n return Colorizer.allColors;\n }\n\n /*\n * Adds the colors Object to the set of allColors\n * known by the Colorizer\n *\n * @param {Object} colors Set of color mappings to add.\n */\n addColors(clrs) {\n return Colorizer.addColors(clrs);\n }\n\n /*\n * function colorize (lookup, level, message)\n * Performs multi-step colorization using colors/safe\n */\n colorize(lookup, level, message) {\n if (typeof message === 'undefined') {\n message = level;\n }\n\n //\n // If the color for the level is just a string\n // then attempt to colorize the message with it.\n //\n if (!Array.isArray(Colorizer.allColors[lookup])) {\n return colors[Colorizer.allColors[lookup]](message);\n }\n\n //\n // If it is an Array then iterate over that Array, applying\n // the colors function for each item.\n //\n for (let i = 0, len = Colorizer.allColors[lookup].length; i < len; i++) {\n message = colors[Colorizer.allColors[lookup][i]](message);\n }\n\n return message;\n }\n\n /*\n * function transform (info, opts)\n * Attempts to colorize the { level, message } of the given\n * `logform` info object.\n */\n transform(info, opts) {\n if (opts.all && typeof info[MESSAGE] === 'string') {\n info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]);\n }\n\n if (opts.level || opts.all || !opts.message) {\n info.level = this.colorize(info[LEVEL], info.level);\n }\n\n if (opts.all || opts.message) {\n info.message = this.colorize(info[LEVEL], info.level, info.message);\n }\n\n return info;\n }\n}\n\n/*\n * function colorize (info)\n * Returns a new instance of the colorize Format that applies\n * level colors to `info` objects. This was previously exposed\n * as { colorize: true } to transports in `winston < 3.0.0`.\n */\nmodule.exports = opts => new Colorizer(opts);\n\n//\n// Attach the Colorizer for registration purposes\n//\nmodule.exports.Colorizer\n = module.exports.Format\n = Colorizer;\n","//\n// Remark: Requiring this file will use the \"safe\" colors API,\n// which will not touch String.prototype.\n//\n// var colors = require('colors/safe');\n// colors.red(\"foo\")\n//\n//\nvar colors = require('./lib/colors');\nmodule['exports'] = colors;\n","'use strict';\n\nvar _require = require('./colorize'),\n Colorizer = _require.Colorizer;\n/*\n * Simple method to register colors with a simpler require\n * path within the module.\n */\n\n\nmodule.exports = function (config) {\n Colorizer.addColors(config.colors || config);\n return config;\n};","/* eslint no-unused-vars: 0 */\n'use strict';\n\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('triple-beam'),\n configs = _require.configs,\n LEVEL = _require.LEVEL,\n MESSAGE = _require.MESSAGE;\n\nvar Padder = /*#__PURE__*/function () {\n function Padder() {\n var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {\n levels: configs.npm.levels\n };\n\n _classCallCheck(this, Padder);\n\n this.paddings = Padder.paddingForLevels(opts.levels, opts.filler);\n this.options = opts;\n }\n /**\n * Returns the maximum length of keys in the specified `levels` Object.\n * @param {Object} levels Set of all levels to calculate longest level against.\n * @returns {Number} Maximum length of the longest level string.\n */\n\n\n _createClass(Padder, [{\n key: \"transform\",\n\n /**\n * Prepends the padding onto the `message` based on the `LEVEL` of\n * the `info`. This is based on the behavior of `winston@2` which also\n * prepended the level onto the message.\n *\n * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201\n *\n * @param {Info} info Logform info object\n * @param {Object} opts Options passed along to this instance.\n * @returns {Info} Modified logform info object.\n */\n value: function transform(info, opts) {\n info.message = \"\".concat(this.paddings[info[LEVEL]]).concat(info.message);\n\n if (info[MESSAGE]) {\n info[MESSAGE] = \"\".concat(this.paddings[info[LEVEL]]).concat(info[MESSAGE]);\n }\n\n return info;\n }\n }], [{\n key: \"getLongestLevel\",\n value: function getLongestLevel(levels) {\n var lvls = Object.keys(levels).map(function (level) {\n return level.length;\n });\n return Math.max.apply(Math, _toConsumableArray(lvls));\n }\n /**\n * Returns the padding for the specified `level` assuming that the\n * maximum length of all levels it's associated with is `maxLength`.\n * @param {String} level Level to calculate padding for.\n * @param {String} filler Repeatable text to use for padding.\n * @param {Number} maxLength Length of the longest level\n * @returns {String} Padding string for the `level`\n */\n\n }, {\n key: \"paddingForLevel\",\n value: function paddingForLevel(level, filler, maxLength) {\n var targetLen = maxLength + 1 - level.length;\n var rep = Math.floor(targetLen / filler.length);\n var padding = \"\".concat(filler).concat(filler.repeat(rep));\n return padding.slice(0, targetLen);\n }\n /**\n * Returns an object with the string paddings for the given `levels`\n * using the specified `filler`.\n * @param {Object} levels Set of all levels to calculate padding for.\n * @param {String} filler Repeatable text to use for padding.\n * @returns {Object} Mapping of level to desired padding.\n */\n\n }, {\n key: \"paddingForLevels\",\n value: function paddingForLevels(levels) {\n var filler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' ';\n var maxLength = Padder.getLongestLevel(levels);\n return Object.keys(levels).reduce(function (acc, level) {\n acc[level] = Padder.paddingForLevel(level, filler, maxLength);\n return acc;\n }, {});\n }\n }]);\n\n return Padder;\n}();\n/*\n * function padLevels (info)\n * Returns a new instance of the padLevels Format which pads\n * levels to be the same length. This was previously exposed as\n * { padLevels: true } to transports in `winston < 3.0.0`.\n */\n\n\nmodule.exports = function (opts) {\n return new Padder(opts);\n};\n\nmodule.exports.Padder = module.exports.Format = Padder;","'use strict';\n\nif (typeof process === 'undefined' ||\n !process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/**/\n\nmodule.exports = Duplex;\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};","//\n// Select the correct build version depending on the environment.\n//\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./production.js');\n} else {\n module.exports = require('./development.js');\n}\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n","var defaultFunctionName = '';\n/**\n * Safely extract function name from itself\n */\nexport function getFunctionName(fn) {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n }\n catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n//# sourceMappingURL=stacktrace.js.map","import { __assign, __read, __spread } from \"tslib\";\nimport { dateTimestampInSeconds, getGlobalObject, isPlainObject, isThenable, SyncPromise } from '@sentry/utils';\n/**\n * Absolute maximum number of breadcrumbs added to an event.\n * The `maxBreadcrumbs` option cannot be higher than this value.\n */\nvar MAX_BREADCRUMBS = 100;\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\n */\nvar Scope = /** @class */ (function () {\n function Scope() {\n /** Flag if notifying is happening. */\n this._notifyingListeners = false;\n /** Callback for client to receive scope changes. */\n this._scopeListeners = [];\n /** Callback list that will be called after {@link applyToEvent}. */\n this._eventProcessors = [];\n /** Array of breadcrumbs. */\n this._breadcrumbs = [];\n /** User */\n this._user = {};\n /** Tags */\n this._tags = {};\n /** Extra */\n this._extra = {};\n /** Contexts */\n this._contexts = {};\n }\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n Scope.clone = function (scope) {\n var newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = __spread(scope._breadcrumbs);\n newScope._tags = __assign({}, scope._tags);\n newScope._extra = __assign({}, scope._extra);\n newScope._contexts = __assign({}, scope._contexts);\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = __spread(scope._eventProcessors);\n newScope._requestSession = scope._requestSession;\n }\n return newScope;\n };\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n Scope.prototype.addScopeListener = function (callback) {\n this._scopeListeners.push(callback);\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.addEventProcessor = function (callback) {\n this._eventProcessors.push(callback);\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setUser = function (user) {\n this._user = user || {};\n if (this._session) {\n this._session.update({ user: user });\n }\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.getUser = function () {\n return this._user;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.getRequestSession = function () {\n return this._requestSession;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setRequestSession = function (requestSession) {\n this._requestSession = requestSession;\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setTags = function (tags) {\n this._tags = __assign(__assign({}, this._tags), tags);\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setTag = function (key, value) {\n var _a;\n this._tags = __assign(__assign({}, this._tags), (_a = {}, _a[key] = value, _a));\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setExtras = function (extras) {\n this._extra = __assign(__assign({}, this._extra), extras);\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setExtra = function (key, extra) {\n var _a;\n this._extra = __assign(__assign({}, this._extra), (_a = {}, _a[key] = extra, _a));\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setFingerprint = function (fingerprint) {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setLevel = function (level) {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setTransactionName = function (name) {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n };\n /**\n * Can be removed in major version.\n * @deprecated in favor of {@link this.setTransactionName}\n */\n Scope.prototype.setTransaction = function (name) {\n return this.setTransactionName(name);\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setContext = function (key, context) {\n var _a;\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n }\n else {\n this._contexts = __assign(__assign({}, this._contexts), (_a = {}, _a[key] = context, _a));\n }\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setSpan = function (span) {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.getSpan = function () {\n return this._span;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.getTransaction = function () {\n var _a, _b, _c, _d;\n // often, this span will be a transaction, but it's not guaranteed to be\n var span = this.getSpan();\n // try it the new way first\n if ((_a = span) === null || _a === void 0 ? void 0 : _a.transaction) {\n return (_b = span) === null || _b === void 0 ? void 0 : _b.transaction;\n }\n // fallback to the old way (known bug: this only finds transactions with sampled = true)\n if ((_d = (_c = span) === null || _c === void 0 ? void 0 : _c.spanRecorder) === null || _d === void 0 ? void 0 : _d.spans[0]) {\n return span.spanRecorder.spans[0];\n }\n // neither way found a transaction\n return undefined;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.setSession = function (session) {\n if (!session) {\n delete this._session;\n }\n else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.getSession = function () {\n return this._session;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.update = function (captureContext) {\n if (!captureContext) {\n return this;\n }\n if (typeof captureContext === 'function') {\n var updatedScope = captureContext(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n if (captureContext instanceof Scope) {\n this._tags = __assign(__assign({}, this._tags), captureContext._tags);\n this._extra = __assign(__assign({}, this._extra), captureContext._extra);\n this._contexts = __assign(__assign({}, this._contexts), captureContext._contexts);\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n }\n else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext;\n this._tags = __assign(__assign({}, this._tags), captureContext.tags);\n this._extra = __assign(__assign({}, this._extra), captureContext.extra);\n this._contexts = __assign(__assign({}, this._contexts), captureContext.contexts);\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n }\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.clear = function () {\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) {\n var maxCrumbs = typeof maxBreadcrumbs === 'number' ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS;\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n var mergedBreadcrumb = __assign({ timestamp: dateTimestampInSeconds() }, breadcrumb);\n this._breadcrumbs = __spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxCrumbs);\n this._notifyScopeListeners();\n return this;\n };\n /**\n * @inheritDoc\n */\n Scope.prototype.clearBreadcrumbs = function () {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n };\n /**\n * Applies the current context and fingerprint to the event.\n * Note that breadcrumbs will be added by the client.\n * Also if the event has already breadcrumbs on it, we do not merge them.\n * @param event Event\n * @param hint May contain additional information about the original exception.\n * @hidden\n */\n Scope.prototype.applyToEvent = function (event, hint) {\n var _a;\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = __assign(__assign({}, this._extra), event.extra);\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = __assign(__assign({}, this._tags), event.tags);\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = __assign(__assign({}, this._user), event.user);\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = __assign(__assign({}, this._contexts), event.contexts);\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (this._span) {\n event.contexts = __assign({ trace: this._span.getTraceContext() }, event.contexts);\n var transactionName = (_a = this._span.transaction) === null || _a === void 0 ? void 0 : _a.name;\n if (transactionName) {\n event.tags = __assign({ transaction: transactionName }, event.tags);\n }\n }\n this._applyFingerprint(event);\n event.breadcrumbs = __spread((event.breadcrumbs || []), this._breadcrumbs);\n event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined;\n return this._notifyEventProcessors(__spread(getGlobalEventProcessors(), this._eventProcessors), event, hint);\n };\n /**\n * This will be called after {@link applyToEvent} is finished.\n */\n Scope.prototype._notifyEventProcessors = function (processors, event, hint, index) {\n var _this = this;\n if (index === void 0) { index = 0; }\n return new SyncPromise(function (resolve, reject) {\n var processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n }\n else {\n var result = processor(__assign({}, event), hint);\n if (isThenable(result)) {\n void result\n .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); })\n .then(null, reject);\n }\n else {\n void _this._notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n };\n /**\n * This will be called on every set call.\n */\n Scope.prototype._notifyScopeListeners = function () {\n var _this = this;\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(function (callback) {\n callback(_this);\n });\n this._notifyingListeners = false;\n }\n };\n /**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\n Scope.prototype._applyFingerprint = function (event) {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint\n ? Array.isArray(event.fingerprint)\n ? event.fingerprint\n : [event.fingerprint]\n : [];\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n };\n return Scope;\n}());\nexport { Scope };\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors() {\n /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */\n var global = getGlobalObject();\n global.__SENTRY__ = global.__SENTRY__ || {};\n global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || [];\n return global.__SENTRY__.globalEventProcessors;\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */\n}\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nexport function addGlobalEventProcessor(callback) {\n getGlobalEventProcessors().push(callback);\n}\n//# sourceMappingURL=scope.js.map","export var TransactionSamplingMethod;\n(function (TransactionSamplingMethod) {\n TransactionSamplingMethod[\"Explicit\"] = \"explicitly_set\";\n TransactionSamplingMethod[\"Sampler\"] = \"client_sampler\";\n TransactionSamplingMethod[\"Rate\"] = \"client_rate\";\n TransactionSamplingMethod[\"Inheritance\"] = \"inheritance\";\n})(TransactionSamplingMethod || (TransactionSamplingMethod = {}));\n//# sourceMappingURL=transaction.js.map","module.exports = function(originalModule) {\n\tif (!originalModule.webpackPolyfill) {\n\t\tvar module = Object.create(originalModule);\n\t\t// module.parent = undefined by default\n\t\tif (!module.children) module.children = [];\n\t\tObject.defineProperty(module, \"loaded\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.l;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"id\", {\n\t\t\tenumerable: true,\n\t\t\tget: function() {\n\t\t\t\treturn module.i;\n\t\t\t}\n\t\t});\n\t\tObject.defineProperty(module, \"exports\", {\n\t\t\tenumerable: true\n\t\t});\n\t\tmodule.webpackPolyfill = 1;\n\t}\n\treturn module;\n};\n","'use strict';\n\nconst SqlString = require('sqlstring');\n\nconst Connection = require('./lib/connection.js');\nconst ConnectionConfig = require('./lib/connection_config.js');\nconst parserCache = require('./lib/parsers/parser_cache');\n\nexports.createConnection = function(opts) {\n return new Connection({ config: new ConnectionConfig(opts) });\n};\n\nexports.connect = exports.createConnection;\nexports.Connection = Connection;\n\nconst Pool = require('./lib/pool.js');\nconst PoolCluster = require('./lib/pool_cluster.js');\n\nexports.createPool = function(config) {\n const PoolConfig = require('./lib/pool_config.js');\n return new Pool({ config: new PoolConfig(config) });\n};\n\nexports.createPoolCluster = function(config) {\n const PoolCluster = require('./lib/pool_cluster.js');\n return new PoolCluster(config);\n};\n\nexports.createQuery = Connection.createQuery;\n\nexports.Pool = Pool;\n\nexports.PoolCluster = PoolCluster;\n\nexports.createServer = function(handler) {\n const Server = require('./lib/server.js');\n const s = new Server();\n if (handler) {\n s.on('connection', handler);\n }\n return s;\n};\n\nexports.PoolConnection = require('./lib/pool_connection');\nexports.escape = SqlString.escape;\nexports.escapeId = SqlString.escapeId;\nexports.format = SqlString.format;\nexports.raw = SqlString.raw;\n\nexports.__defineGetter__(\n 'createConnectionPromise',\n () => require('./promise.js').createConnection\n);\n\nexports.__defineGetter__(\n 'createPoolPromise',\n () => require('./promise.js').createPool\n);\n\nexports.__defineGetter__(\n 'createPoolClusterPromise',\n () => require('./promise.js').createPoolCluster\n);\n\nexports.__defineGetter__('Types', () => require('./lib/constants/types.js'));\n\nexports.__defineGetter__('Charsets', () =>\n require('./lib/constants/charsets.js')\n);\n\nexports.__defineGetter__('CharsetToEncoding', () =>\n require('./lib/constants/charset_encodings.js')\n);\n\nexports.setMaxParserCache = function(max) {\n parserCache.setMaxCache(max);\n};\n\nexports.clearParserCache = function() {\n parserCache.clearCache();\n};\n","module.exports = require(\"net\");","module.exports = require(\"timers\");","module.exports = require(\"zlib\");","'use strict';\n\nconst LRU = require('lru-cache');\n\nconst parserCache = new LRU({\n max: 15000\n});\n\nfunction keyFromFields(type, fields, options, config) {\n let res =\n `${type}` +\n `/${typeof options.nestTables}` +\n `/${options.nestTables}` +\n `/${options.rowsAsArray}` +\n `/${options.supportBigNumbers || config.supportBigNumbers}` +\n `/${options.bigNumberStrings || config.bigNumberStrings}` +\n `/${typeof options.typeCast}` +\n `/${options.timezone || config.timezone}` +\n `/${options.decimalNumbers}` +\n `/${options.dateStrings}`;\n for (let i = 0; i < fields.length; ++i) {\n const field = fields[i];\n res += `/${field.name}:${field.columnType}:${field.length}:${field.schema}:${field.table}:${field.flags}:${field.characterSet}`;\n }\n return res;\n}\n\nfunction getParser(type, fields, options, config, compiler) {\n const key = keyFromFields(type, fields, options, config);\n let parser = parserCache.get(key);\n\n if (parser) {\n return parser;\n }\n\n parser = compiler(fields, options, config);\n parserCache.set(key, parser);\n return parser;\n}\n\nfunction setMaxCache(max) {\n parserCache.max = max;\n}\n\nfunction clearCache() {\n parserCache.reset();\n}\n\nmodule.exports = {\n getParser: getParser,\n setMaxCache: setMaxCache,\n clearCache: clearCache\n};\n","'use strict';\n\nconst { Colorizer } = require('./colorize');\n\n/*\n * Simple method to register colors with a simpler require\n * path within the module.\n */\nmodule.exports = config => {\n Colorizer.addColors(config.colors || config);\n return config;\n};\n","/* eslint no-unused-vars: 0 */\n'use strict';\n\nconst { configs, LEVEL, MESSAGE } = require('triple-beam');\n\nclass Padder {\n constructor(opts = { levels: configs.npm.levels }) {\n this.paddings = Padder.paddingForLevels(opts.levels, opts.filler);\n this.options = opts;\n }\n\n /**\n * Returns the maximum length of keys in the specified `levels` Object.\n * @param {Object} levels Set of all levels to calculate longest level against.\n * @returns {Number} Maximum length of the longest level string.\n */\n static getLongestLevel(levels) {\n const lvls = Object.keys(levels).map(level => level.length);\n return Math.max(...lvls);\n }\n\n /**\n * Returns the padding for the specified `level` assuming that the\n * maximum length of all levels it's associated with is `maxLength`.\n * @param {String} level Level to calculate padding for.\n * @param {String} filler Repeatable text to use for padding.\n * @param {Number} maxLength Length of the longest level\n * @returns {String} Padding string for the `level`\n */\n static paddingForLevel(level, filler, maxLength) {\n const targetLen = maxLength + 1 - level.length;\n const rep = Math.floor(targetLen / filler.length);\n const padding = `${filler}${filler.repeat(rep)}`;\n return padding.slice(0, targetLen);\n }\n\n /**\n * Returns an object with the string paddings for the given `levels`\n * using the specified `filler`.\n * @param {Object} levels Set of all levels to calculate padding for.\n * @param {String} filler Repeatable text to use for padding.\n * @returns {Object} Mapping of level to desired padding.\n */\n static paddingForLevels(levels, filler = ' ') {\n const maxLength = Padder.getLongestLevel(levels);\n return Object.keys(levels).reduce((acc, level) => {\n acc[level] = Padder.paddingForLevel(level, filler, maxLength);\n return acc;\n }, {});\n }\n\n /**\n * Prepends the padding onto the `message` based on the `LEVEL` of\n * the `info`. This is based on the behavior of `winston@2` which also\n * prepended the level onto the message.\n *\n * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201\n *\n * @param {Info} info Logform info object\n * @param {Object} opts Options passed along to this instance.\n * @returns {Info} Modified logform info object.\n */\n transform(info, opts) {\n info.message = `${this.paddings[info[LEVEL]]}${info.message}`;\n if (info[MESSAGE]) {\n info[MESSAGE] = `${this.paddings[info[LEVEL]]}${info[MESSAGE]}`;\n }\n\n return info;\n }\n}\n\n/*\n * function padLevels (info)\n * Returns a new instance of the padLevels Format which pads\n * levels to be the same length. This was previously exposed as\n * { padLevels: true } to transports in `winston < 3.0.0`.\n */\nmodule.exports = opts => new Padder(opts);\n\nmodule.exports.Padder\n = module.exports.Format\n = Padder;\n","'use strict';\n\nconst format = require('./format');\nconst { MESSAGE } = require('triple-beam');\nconst jsonStringify = require('fast-safe-stringify');\n\n/*\n * function replacer (key, value)\n * Handles proper stringification of Buffer and bigint output.\n */\nfunction replacer(key, value) {\n if (value instanceof Buffer)\n return value.toString('base64');\n // eslint-disable-next-line valid-typeof\n if (typeof value === 'bigint')\n return value.toString();\n return value;\n}\n\n/*\n * function json (info)\n * Returns a new instance of the JSON format that turns a log `info`\n * object into pure JSON. This was previously exposed as { json: true }\n * to transports in `winston < 3.0.0`.\n */\nmodule.exports = format((info, opts = {}) => {\n info[MESSAGE] = (opts.stable ? jsonStringify.stableStringify\n : jsonStringify)(info, opts.replacer || replacer, opts.space);\n return info;\n});\n","'use strict';\n\nvar format = require('./format');\n/*\n * function align (info)\n * Returns a new instance of the align Format which adds a `\\t`\n * delimiter before the message to properly align it in the same place.\n * It was previously { align: true } in winston < 3.0.0\n */\n\n\nmodule.exports = format(function (info) {\n info.message = \"\\t\".concat(info.message);\n return info;\n});","'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('./colorize'),\n Colorizer = _require.Colorizer;\n\nvar _require2 = require('./pad-levels'),\n Padder = _require2.Padder;\n\nvar _require3 = require('triple-beam'),\n configs = _require3.configs,\n MESSAGE = _require3.MESSAGE;\n/**\n * Cli format class that handles initial state for a a separate\n * Colorizer and Padder instance.\n */\n\n\nvar CliFormat = /*#__PURE__*/function () {\n function CliFormat() {\n var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n _classCallCheck(this, CliFormat);\n\n if (!opts.levels) {\n opts.levels = configs.npm.levels;\n }\n\n this.colorizer = new Colorizer(opts);\n this.padder = new Padder(opts);\n this.options = opts;\n }\n /*\n * function transform (info, opts)\n * Attempts to both:\n * 1. Pad the { level }\n * 2. Colorize the { level, message }\n * of the given `logform` info object depending on the `opts`.\n */\n\n\n _createClass(CliFormat, [{\n key: \"transform\",\n value: function transform(info, opts) {\n this.colorizer.transform(this.padder.transform(info, opts), opts);\n info[MESSAGE] = \"\".concat(info.level, \":\").concat(info.message);\n return info;\n }\n }]);\n\n return CliFormat;\n}();\n/*\n * function cli (opts)\n * Returns a new instance of the CLI format that turns a log\n * `info` object into the same format previously available\n * in `winston.cli()` in `winston < 3.0.0`.\n */\n\n\nmodule.exports = function (opts) {\n return new CliFormat(opts);\n}; //\n// Attach the CliFormat for registration purposes\n//\n\n\nmodule.exports.Format = CliFormat;","'use strict';\n\nvar format = require('./format');\n/*\n * function cascade(formats)\n * Returns a function that invokes the `._format` function in-order\n * for the specified set of `formats`. In this manner we say that Formats\n * are \"pipe-like\", but not a pure pumpify implementation. Since there is no back\n * pressure we can remove all of the \"readable\" plumbing in Node streams.\n */\n\n\nfunction cascade(formats) {\n if (!formats.every(isValidFormat)) {\n return;\n }\n\n return function (info) {\n var obj = info;\n\n for (var i = 0; i < formats.length; i++) {\n obj = formats[i].transform(obj, formats[i].options);\n\n if (!obj) {\n return false;\n }\n }\n\n return obj;\n };\n}\n/*\n * function isValidFormat(format)\n * If the format does not define a `transform` function throw an error\n * with more detailed usage.\n */\n\n\nfunction isValidFormat(fmt) {\n if (typeof fmt.transform !== 'function') {\n throw new Error(['No transform function found on format. Did you create a format instance?', 'const myFormat = format(formatFn);', 'const instance = myFormat();'].join('\\n'));\n }\n\n return true;\n}\n/*\n * function combine (info)\n * Returns a new instance of the combine Format which combines the specified\n * formats into a new format. This is similar to a pipe-chain in transform streams.\n * We choose to combine the prototypes this way because there is no back pressure in\n * an in-memory transform chain.\n */\n\n\nmodule.exports = function () {\n for (var _len = arguments.length, formats = new Array(_len), _key = 0; _key < _len; _key++) {\n formats[_key] = arguments[_key];\n }\n\n var combinedFormat = format(cascade(formats));\n var instance = combinedFormat();\n instance.Format = combinedFormat.Format;\n return instance;\n}; //\n// Export the cascade method for use in cli and other\n// combined formats that should not be assumed to be\n// singletons.\n//\n\n\nmodule.exports.cascade = cascade;","'use strict';\n\nvar format = require('./format');\n\nvar _require = require('triple-beam'),\n MESSAGE = _require.MESSAGE;\n\nvar jsonStringify = require('fast-safe-stringify');\n/*\n * function replacer (key, value)\n * Handles proper stringification of Buffer and bigint output.\n */\n\n\nfunction replacer(key, value) {\n if (value instanceof Buffer) return value.toString('base64'); // eslint-disable-next-line valid-typeof\n\n if (typeof value === 'bigint') return value.toString();\n return value;\n}\n/*\n * function json (info)\n * Returns a new instance of the JSON format that turns a log `info`\n * object into pure JSON. This was previously exposed as { json: true }\n * to transports in `winston < 3.0.0`.\n */\n\n\nmodule.exports = format(function (info) {\n var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n info[MESSAGE] = (opts.stable ? jsonStringify.stableStringify : jsonStringify)(info, opts.replacer || replacer, opts.space);\n return info;\n});","'use strict';\n\nvar format = require('./format');\n/*\n * function label (info)\n * Returns a new instance of the label Format which adds the specified\n * `opts.label` before the message. This was previously exposed as\n * { label: 'my label' } to transports in `winston < 3.0.0`.\n */\n\n\nmodule.exports = format(function (info, opts) {\n if (opts.message) {\n info.message = \"[\".concat(opts.label, \"] \").concat(info.message);\n return info;\n }\n\n info.label = opts.label;\n return info;\n});","'use strict';\n\nvar format = require('./format');\n\nvar _require = require('triple-beam'),\n MESSAGE = _require.MESSAGE;\n\nvar jsonStringify = require('fast-safe-stringify');\n/*\n * function logstash (info)\n * Returns a new instance of the LogStash Format that turns a\n * log `info` object into pure JSON with the appropriate logstash\n * options. This was previously exposed as { logstash: true }\n * to transports in `winston < 3.0.0`.\n */\n\n\nmodule.exports = format(function (info) {\n var logstash = {};\n\n if (info.message) {\n logstash['@message'] = info.message;\n delete info.message;\n }\n\n if (info.timestamp) {\n logstash['@timestamp'] = info.timestamp;\n delete info.timestamp;\n }\n\n logstash['@fields'] = info;\n info[MESSAGE] = jsonStringify(logstash);\n return info;\n});","'use strict';\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar format = require('./format');\n\nfunction fillExcept(info, fillExceptKeys, metadataKey) {\n var savedKeys = fillExceptKeys.reduce(function (acc, key) {\n acc[key] = info[key];\n delete info[key];\n return acc;\n }, {});\n var metadata = Object.keys(info).reduce(function (acc, key) {\n acc[key] = info[key];\n delete info[key];\n return acc;\n }, {});\n Object.assign(info, savedKeys, _defineProperty({}, metadataKey, metadata));\n return info;\n}\n\nfunction fillWith(info, fillWithKeys, metadataKey) {\n info[metadataKey] = fillWithKeys.reduce(function (acc, key) {\n acc[key] = info[key];\n delete info[key];\n return acc;\n }, {});\n return info;\n}\n/**\n * Adds in a \"metadata\" object to collect extraneous data, similar to the metadata\n * object in winston 2.x.\n */\n\n\nmodule.exports = format(function (info) {\n var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var metadataKey = 'metadata';\n\n if (opts.key) {\n metadataKey = opts.key;\n }\n\n var fillExceptKeys = [];\n\n if (!opts.fillExcept && !opts.fillWith) {\n fillExceptKeys.push('level');\n fillExceptKeys.push('message');\n }\n\n if (opts.fillExcept) {\n fillExceptKeys = opts.fillExcept;\n }\n\n if (fillExceptKeys.length > 0) {\n return fillExcept(info, fillExceptKeys, metadataKey);\n }\n\n if (opts.fillWith) {\n return fillWith(info, opts.fillWith, metadataKey);\n }\n\n return info;\n});","'use strict';\n\nvar inspect = require('util').inspect;\n\nvar format = require('./format');\n\nvar _require = require('triple-beam'),\n LEVEL = _require.LEVEL,\n MESSAGE = _require.MESSAGE,\n SPLAT = _require.SPLAT;\n/*\n * function prettyPrint (info)\n * Returns a new instance of the prettyPrint Format that \"prettyPrint\"\n * serializes `info` objects. This was previously exposed as\n * { prettyPrint: true } to transports in `winston < 3.0.0`.\n */\n\n\nmodule.exports = format(function (info) {\n var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n //\n // info[{LEVEL, MESSAGE, SPLAT}] are enumerable here. Since they\n // are internal, we remove them before util.inspect so they\n // are not printed.\n //\n var stripped = Object.assign({}, info); // Remark (indexzero): update this technique in April 2019\n // when node@6 is EOL\n\n delete stripped[LEVEL];\n delete stripped[MESSAGE];\n delete stripped[SPLAT];\n info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize);\n return info;\n});","'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar _require = require('triple-beam'),\n MESSAGE = _require.MESSAGE;\n\nvar Printf = /*#__PURE__*/function () {\n function Printf(templateFn) {\n _classCallCheck(this, Printf);\n\n this.template = templateFn;\n }\n\n _createClass(Printf, [{\n key: \"transform\",\n value: function transform(info) {\n info[MESSAGE] = this.template(info);\n return info;\n }\n }]);\n\n return Printf;\n}();\n/*\n * function printf (templateFn)\n * Returns a new instance of the printf Format that creates an\n * intermediate prototype to store the template string-based formatter\n * function.\n */\n\n\nmodule.exports = function (opts) {\n return new Printf(opts);\n};\n\nmodule.exports.Printf = module.exports.Format = Printf;","/* eslint no-undefined: 0 */\n'use strict';\n\nvar format = require('./format');\n\nvar _require = require('triple-beam'),\n MESSAGE = _require.MESSAGE;\n\nvar jsonStringify = require('fast-safe-stringify');\n/*\n * function simple (info)\n * Returns a new instance of the simple format TransformStream\n * which writes a simple representation of logs.\n *\n * const { level, message, splat, ...rest } = info;\n *\n * ${level}: ${message} if rest is empty\n * ${level}: ${message} ${JSON.stringify(rest)} otherwise\n */\n\n\nmodule.exports = format(function (info) {\n var stringifiedRest = jsonStringify(Object.assign({}, info, {\n level: undefined,\n message: undefined,\n splat: undefined\n }));\n var padding = info.padding && info.padding[info.level] || '';\n\n if (stringifiedRest !== '{}') {\n info[MESSAGE] = \"\".concat(info.level, \":\").concat(padding, \" \").concat(info.message, \" \").concat(stringifiedRest);\n } else {\n info[MESSAGE] = \"\".concat(info.level, \":\").concat(padding, \" \").concat(info.message);\n }\n\n return info;\n});","'use strict';\n\nfunction _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _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, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nvar util = require('util');\n\nvar _require = require('triple-beam'),\n SPLAT = _require.SPLAT;\n/**\n * Captures the number of format (i.e. %s strings) in a given string.\n * Based on `util.format`, see Node.js source:\n * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230\n * @type {RegExp}\n */\n\n\nvar formatRegExp = /%[scdjifoO%]/g;\n/**\n * Captures the number of escaped % signs in a format string (i.e. %s strings).\n * @type {RegExp}\n */\n\nvar escapedPercent = /%%/g;\n\nvar Splatter = /*#__PURE__*/function () {\n function Splatter(opts) {\n _classCallCheck(this, Splatter);\n\n this.options = opts;\n }\n /**\n * Check to see if tokens <= splat.length, assign { splat, meta } into the\n * `info` accordingly, and write to this instance.\n *\n * @param {Info} info Logform info message.\n * @param {String[]} tokens Set of string interpolation tokens.\n * @returns {Info} Modified info message\n * @private\n */\n\n\n _createClass(Splatter, [{\n key: \"_splat\",\n value: function _splat(info, tokens) {\n var msg = info.message;\n var splat = info[SPLAT] || info.splat || [];\n var percents = msg.match(escapedPercent);\n var escapes = percents && percents.length || 0; // The expected splat is the number of tokens minus the number of escapes\n // e.g.\n // - { expectedSplat: 3 } '%d %s %j'\n // - { expectedSplat: 5 } '[%s] %d%% %d%% %s %j'\n //\n // Any \"meta\" will be arugments in addition to the expected splat size\n // regardless of type. e.g.\n //\n // logger.log('info', '%d%% %s %j', 100, 'wow', { such: 'js' }, { thisIsMeta: true });\n // would result in splat of four (4), but only three (3) are expected. Therefore:\n //\n // extraSplat = 3 - 4 = -1\n // metas = [100, 'wow', { such: 'js' }, { thisIsMeta: true }].splice(-1, -1 * -1);\n // splat = [100, 'wow', { such: 'js' }]\n\n var expectedSplat = tokens.length - escapes;\n var extraSplat = expectedSplat - splat.length;\n var metas = extraSplat < 0 ? splat.splice(extraSplat, -1 * extraSplat) : []; // Now that { splat } has been separated from any potential { meta }. we\n // can assign this to the `info` object and write it to our format stream.\n // If the additional metas are **NOT** objects or **LACK** enumerable properties\n // you are going to have a bad time.\n\n var metalen = metas.length;\n\n if (metalen) {\n for (var i = 0; i < metalen; i++) {\n Object.assign(info, metas[i]);\n }\n }\n\n info.message = util.format.apply(util, [msg].concat(_toConsumableArray(splat)));\n return info;\n }\n /**\n * Transforms the `info` message by using `util.format` to complete\n * any `info.message` provided it has string interpolation tokens.\n * If no tokens exist then `info` is immutable.\n *\n * @param {Info} info Logform info message.\n * @param {Object} opts Options for this instance.\n * @returns {Info} Modified info message\n */\n\n }, {\n key: \"transform\",\n value: function transform(info) {\n var msg = info.message;\n var splat = info[SPLAT] || info.splat; // No need to process anything if splat is undefined\n\n if (!splat || !splat.length) {\n return info;\n } // Extract tokens, if none available default to empty array to\n // ensure consistancy in expected results\n\n\n var tokens = msg && msg.match && msg.match(formatRegExp); // This condition will take care of inputs with info[SPLAT]\n // but no tokens present\n\n if (!tokens && (splat || splat.length)) {\n var metas = splat.length > 1 ? splat.splice(0) : splat; // Now that { splat } has been separated from any potential { meta }. we\n // can assign this to the `info` object and write it to our format stream.\n // If the additional metas are **NOT** objects or **LACK** enumerable properties\n // you are going to have a bad time.\n\n var metalen = metas.length;\n\n if (metalen) {\n for (var i = 0; i < metalen; i++) {\n Object.assign(info, metas[i]);\n }\n }\n\n return info;\n }\n\n if (tokens) {\n return this._splat(info, tokens);\n }\n\n return info;\n }\n }]);\n\n return Splatter;\n}();\n/*\n * function splat (info)\n * Returns a new instance of the splat format TransformStream\n * which performs string interpolation from `info` objects. This was\n * previously exposed implicitly in `winston < 3.0.0`.\n */\n\n\nmodule.exports = function (opts) {\n return new Splatter(opts);\n};","'use strict';\n\nvar fecha = require('fecha');\n\nvar format = require('./format');\n/*\n * function timestamp (info)\n * Returns a new instance of the timestamp Format which adds a timestamp\n * to the info. It was previously available in winston < 3.0.0 as:\n *\n * - { timestamp: true } // `new Date.toISOString()`\n * - { timestamp: function:String } // Value returned by `timestamp()`\n */\n\n\nmodule.exports = format(function (info) {\n var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (opts.format) {\n info.timestamp = typeof opts.format === 'function' ? opts.format() : fecha.format(new Date(), opts.format);\n }\n\n if (!info.timestamp) {\n info.timestamp = new Date().toISOString();\n }\n\n if (opts.alias) {\n info[opts.alias] = info.timestamp;\n }\n\n return info;\n});","'use strict';\n\nvar colors = require('colors/safe');\n\nvar format = require('./format');\n\nvar _require = require('triple-beam'),\n MESSAGE = _require.MESSAGE;\n/*\n * function uncolorize (info)\n * Returns a new instance of the uncolorize Format that strips colors\n * from `info` objects. This was previously exposed as { stripColors: true }\n * to transports in `winston < 3.0.0`.\n */\n\n\nmodule.exports = format(function (info, opts) {\n if (opts.level !== false) {\n info.level = colors.strip(info.level);\n }\n\n if (opts.message !== false) {\n info.message = colors.strip(info.message);\n }\n\n if (opts.raw !== false && info[MESSAGE]) {\n info[MESSAGE] = colors.strip(info[MESSAGE]);\n }\n\n return info;\n});","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = isArrayLike;\nfunction isArrayLike(value) {\n return value && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0;\n}\nmodule.exports = exports['default'];","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n// A temporary value used to identify if the loop should be broken.\n// See #1064, #1293\nconst breakLoop = {};\nexports.default = breakLoop;\nmodule.exports = exports[\"default\"];","// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n'use strict';\n\nvar ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;\n\nfunction once(callback) {\n var called = false;\n return function () {\n if (called) return;\n called = true;\n\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n callback.apply(this, args);\n };\n}\n\nfunction noop() {}\n\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function';\n}\n\nfunction eos(stream, opts, callback) {\n if (typeof opts === 'function') return eos(stream, null, opts);\n if (!opts) opts = {};\n callback = once(callback || noop);\n var readable = opts.readable || opts.readable !== false && stream.readable;\n var writable = opts.writable || opts.writable !== false && stream.writable;\n\n var onlegacyfinish = function onlegacyfinish() {\n if (!stream.writable) onfinish();\n };\n\n var writableEnded = stream._writableState && stream._writableState.finished;\n\n var onfinish = function onfinish() {\n writable = false;\n writableEnded = true;\n if (!readable) callback.call(stream);\n };\n\n var readableEnded = stream._readableState && stream._readableState.endEmitted;\n\n var onend = function onend() {\n readable = false;\n readableEnded = true;\n if (!writable) callback.call(stream);\n };\n\n var onerror = function onerror(err) {\n callback.call(stream, err);\n };\n\n var onclose = function onclose() {\n var err;\n\n if (readable && !readableEnded) {\n if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n\n if (writable && !writableEnded) {\n if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();\n return callback.call(stream, err);\n }\n };\n\n var onrequest = function onrequest() {\n stream.req.on('finish', onfinish);\n };\n\n if (isRequest(stream)) {\n stream.on('complete', onfinish);\n stream.on('abort', onclose);\n if (stream.req) onrequest();else stream.on('request', onrequest);\n } else if (writable && !stream._writableState) {\n // legacy streams\n stream.on('end', onlegacyfinish);\n stream.on('close', onlegacyfinish);\n }\n\n stream.on('end', onend);\n stream.on('finish', onfinish);\n if (opts.error !== false) stream.on('error', onerror);\n stream.on('close', onclose);\n return function () {\n stream.removeListener('complete', onfinish);\n stream.removeListener('abort', onclose);\n stream.removeListener('request', onrequest);\n if (stream.req) stream.req.removeListener('finish', onfinish);\n stream.removeListener('end', onlegacyfinish);\n stream.removeListener('close', onlegacyfinish);\n stream.removeListener('finish', onfinish);\n stream.removeListener('end', onend);\n stream.removeListener('error', onerror);\n stream.removeListener('close', onclose);\n };\n}\n\nmodule.exports = eos;","/**\n * index.js: Default settings for all levels that winston knows about.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst logform = require('logform');\nconst { configs } = require('triple-beam');\n\n/**\n * Export config set for the CLI.\n * @type {Object}\n */\nexports.cli = logform.levels(configs.cli);\n\n/**\n * Export config set for npm.\n * @type {Object}\n */\nexports.npm = logform.levels(configs.npm);\n\n/**\n * Export config set for the syslog.\n * @type {Object}\n */\nexports.syslog = logform.levels(configs.syslog);\n\n/**\n * Hoist addColors from logform where it was refactored into in winston@3.\n * @type {Object}\n */\nexports.addColors = logform.levels;\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _eachOf = require('./eachOf');\n\nvar _eachOf2 = _interopRequireDefault(_eachOf);\n\nvar _withoutIndex = require('./internal/withoutIndex');\n\nvar _withoutIndex2 = _interopRequireDefault(_withoutIndex);\n\nvar _wrapAsync = require('./internal/wrapAsync');\n\nvar _wrapAsync2 = _interopRequireDefault(_wrapAsync);\n\nvar _awaitify = require('./internal/awaitify');\n\nvar _awaitify2 = _interopRequireDefault(_awaitify);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Applies the function `iteratee` to each item in `coll`, in parallel.\n * The `iteratee` is called with an item from the list, and a callback for when\n * it has finished. If the `iteratee` passes an error to its `callback`, the\n * main `callback` (for the `each` function) is immediately called with the\n * error.\n *\n * Note, that since this function applies `iteratee` to each item in parallel,\n * there is no guarantee that the iteratee functions will complete in order.\n *\n * @name each\n * @static\n * @memberOf module:Collections\n * @method\n * @alias forEach\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to\n * each item in `coll`. Invoked with (item, callback).\n * The array index is not passed to the iteratee.\n * If you need the index, use `eachOf`.\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n * @example\n *\n * // assuming openFiles is an array of file names and saveFile is a function\n * // to save the modified contents of that file:\n *\n * async.each(openFiles, saveFile, function(err){\n * // if any of the saves produced an error, err would equal that error\n * });\n *\n * // assuming openFiles is an array of file names\n * async.each(openFiles, function(file, callback) {\n *\n * // Perform operation on file here.\n * console.log('Processing file ' + file);\n *\n * if( file.length > 32 ) {\n * console.log('This file name is too long');\n * callback('File name too long');\n * } else {\n * // Do work to process file here\n * console.log('File processed');\n * callback();\n * }\n * }, function(err) {\n * // if any of the file processing produced an error, err would equal that error\n * if( err ) {\n * // One of the iterations produced an error.\n * // All processing will now stop.\n * console.log('A file failed to process');\n * } else {\n * console.log('All files have been processed successfully');\n * }\n * });\n */\nfunction eachLimit(coll, iteratee, callback) {\n return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);\n}\n\nexports.default = (0, _awaitify2.default)(eachLimit, 3);\nmodule.exports = exports['default'];","export const PHONE_NUMBER_REGEX = /^([0-9]{3}-[0-9]{4})|([0-9]{7})$/;\nexport interface ScriptMessage {\n method: string;\n app: string;\n data: T;\n}\n\nexport enum PhoneEvents {\n OPEN_APP = 'npwd:openApp',\n OPEN_PHONE = 'npwd:open',\n CLOSE_PHONE = 'npwd:close',\n UNLOAD_CHARACTER = 'npwd:unloadCharacter',\n SET_VISIBILITY = 'npwd:setVisibility',\n ADD_SNACKBAR_ALERT = 'npwd:setSnackarAlert',\n SET_NUMBER = 'npwd:setNumber',\n SET_PHONE_READY = 'npwd:phoneReady',\n SET_CONFIG = 'npwd:setPhoneConfig',\n SET_TIME = 'npwd:setGameTime',\n SEND_CREDENTIALS = 'npwd:sendCredentials',\n FETCH_CREDENTIALS = 'npwd:getCredentials',\n TOGGLE_KEYS = 'npwd:toggleAllControls',\n SET_PLAYER_LOADED = 'npwd:setPlayerLoaded',\n}\n\n// Used to standardize the server response\nexport enum ErrorStringKeys {\n SERVER_ERROR = 'GENERAL_SERVER_ERROR',\n DELETE_FAILED = 'DELETE_FAILED',\n ADD_FAILED = 'ADD_FAILED',\n UPDATE_FAILED = 'UPDATED_FAILED',\n FETCH_FAILED = 'FETCH_FAILED',\n}\n\nexport interface FxServerRespError {\n errorCode: ErrorStringKeys;\n message: string;\n}\n\nexport interface FxServerResponse {\n data?: unknown;\n action: string;\n status: 'success' | 'failure';\n app: string;\n error?: FxServerRespError;\n}\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar normalizeHeaderName = require('./helpers/normalizeHeaderName');\nvar enhanceError = require('./core/enhanceError');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('./adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('./adapters/http');\n }\n return adapter;\n}\n\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nvar defaults = {\n\n transitional: {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n },\n\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {\n setContentTypeIfUnset(headers, 'application/json');\n return stringifySafely(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n var transitional = this.transitional;\n var silentJSONParsing = transitional && transitional.silentJSONParsing;\n var forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';\n\n if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw enhanceError(e, this, 'E_JSON_PARSE');\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n }\n};\n\ndefaults.headers = {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","'use strict';\n\n/**\n * Update an Error with the specified config, error code, and response.\n *\n * @param {Error} error The error to update.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The error.\n */\nmodule.exports = function enhanceError(error, config, code, request, response) {\n error.config = config;\n if (code) {\n error.code = code;\n }\n\n error.request = request;\n error.response = response;\n error.isAxiosError = true;\n\n error.toJSON = function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code\n };\n };\n return error;\n};\n","'use strict';\n\nvar enhanceError = require('./enhanceError');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nmodule.exports = function createError(message, config, code, request, response) {\n var error = new Error(message);\n return enhanceError(error, config, code, request, response);\n};\n","import { mainLogger } from '../sv_logger';\n\nexport const twitterLogger = mainLogger.child({ module: 'twitter' });\n","import { mainLogger } from '../sv_logger';\nimport { FormattedMatch, FormattedProfile, Match, Profile } from '../../../typings/match';\nimport dayjs from 'dayjs';\n\nexport const matchLogger = mainLogger.child({ module: 'match' });\n\nexport function formatProfile(profile: Profile): FormattedProfile | null {\n return {\n ...profile,\n tagList: profile.tags.split(',').filter((t) => t), // remove any empty tags\n lastActiveFormatted: dayjs.unix(profile.lastActive).toString(),\n viewed: false,\n };\n}\n\nexport function formatMatches(match: Match): FormattedMatch | null {\n return {\n ...match,\n tagList: match.tags.split(',').filter((t) => t), // remove any empty tags\n lastActiveFormatted: dayjs.unix(match.lastActive).toString(),\n matchedAtFormatted: dayjs.unix(match.matchedAt).toString(),\n };\n}\n","import { getGlobalObject } from './global';\nimport { isString } from './is';\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nexport function htmlTreeAsString(elem, keyAttrs) {\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n var currentElem = elem;\n var MAX_TRAVERSE_HEIGHT = 5;\n var MAX_OUTPUT_LEN = 80;\n var out = [];\n var height = 0;\n var len = 0;\n var separator = ' > ';\n var sepLength = separator.length;\n var nextStr = void 0;\n // eslint-disable-next-line no-plusplus\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds MAX_OUTPUT_LEN\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) {\n break;\n }\n out.push(nextStr);\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n return out.reverse().join(separator);\n }\n catch (_oO) {\n return '';\n }\n}\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el, keyAttrs) {\n var _a, _b;\n var elem = el;\n var out = [];\n var className;\n var classes;\n var key;\n var attr;\n var i;\n if (!elem || !elem.tagName) {\n return '';\n }\n out.push(elem.tagName.toLowerCase());\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n var keyAttrPairs = ((_a = keyAttrs) === null || _a === void 0 ? void 0 : _a.length) ? keyAttrs.filter(function (keyAttr) { return elem.getAttribute(keyAttr); }).map(function (keyAttr) { return [keyAttr, elem.getAttribute(keyAttr)]; })\n : null;\n if ((_b = keyAttrPairs) === null || _b === void 0 ? void 0 : _b.length) {\n keyAttrPairs.forEach(function (keyAttrPair) {\n out.push(\"[\" + keyAttrPair[0] + \"=\\\"\" + keyAttrPair[1] + \"\\\"]\");\n });\n }\n else {\n if (elem.id) {\n out.push(\"#\" + elem.id);\n }\n // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(\".\" + classes[i]);\n }\n }\n }\n var allowedAttrs = ['type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(\"[\" + key + \"=\\\"\" + attr + \"\\\"]\");\n }\n }\n return out.join('');\n}\n/**\n * A safe form of location.href\n */\nexport function getLocationHref() {\n var global = getGlobalObject();\n try {\n return global.document.location.href;\n }\n catch (oO) {\n return '';\n }\n}\n//# sourceMappingURL=browser.js.map","import { __assign } from \"tslib\";\nimport { getGlobalObject } from './global';\nimport { snipLine } from './string';\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nexport function uuid4() {\n var global = getGlobalObject();\n var crypto = global.crypto || global.msCrypto;\n if (!(crypto === void 0) && crypto.getRandomValues) {\n // Use window.crypto API if available\n var arr = new Uint16Array(8);\n crypto.getRandomValues(arr);\n // set 4 in byte 7\n // eslint-disable-next-line no-bitwise\n arr[3] = (arr[3] & 0xfff) | 0x4000;\n // set 2 most significant bits of byte 9 to '10'\n // eslint-disable-next-line no-bitwise\n arr[4] = (arr[4] & 0x3fff) | 0x8000;\n var pad = function (num) {\n var v = num.toString(16);\n while (v.length < 4) {\n v = \"0\" + v;\n }\n return v;\n };\n return (pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7]));\n }\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n // eslint-disable-next-line no-bitwise\n var r = (Math.random() * 16) | 0;\n // eslint-disable-next-line no-bitwise\n var v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nexport function parseUrl(url) {\n if (!url) {\n return {};\n }\n var match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n if (!match) {\n return {};\n }\n // coerce to undefined values to empty string so we don't get 'undefined'\n var query = match[6] || '';\n var fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n relative: match[5] + query + fragment,\n };\n}\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nexport function getEventDescription(event) {\n if (event.message) {\n return event.message;\n }\n if (event.exception && event.exception.values && event.exception.values[0]) {\n var exception = event.exception.values[0];\n if (exception.type && exception.value) {\n return exception.type + \": \" + exception.value;\n }\n return exception.type || exception.value || event.event_id || '';\n }\n return event.event_id || '';\n}\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nexport function addExceptionTypeValue(event, value, type) {\n event.exception = event.exception || {};\n event.exception.values = event.exception.values || [];\n event.exception.values[0] = event.exception.values[0] || {};\n event.exception.values[0].value = event.exception.values[0].value || value || '';\n event.exception.values[0].type = event.exception.values[0].type || type || 'Error';\n}\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nexport function addExceptionMechanism(event, newMechanism) {\n var _a;\n if (!event.exception || !event.exception.values) {\n return;\n }\n var exceptionValue0 = event.exception.values[0];\n var defaultMechanism = { type: 'generic', handled: true };\n var currentMechanism = exceptionValue0.mechanism;\n exceptionValue0.mechanism = __assign(__assign(__assign({}, defaultMechanism), currentMechanism), newMechanism);\n if (newMechanism && 'data' in newMechanism) {\n var mergedData = __assign(__assign({}, (_a = currentMechanism) === null || _a === void 0 ? void 0 : _a.data), newMechanism.data);\n exceptionValue0.mechanism.data = mergedData;\n }\n}\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nvar SEMVER_REGEXP = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nexport function parseSemver(input) {\n var match = input.match(SEMVER_REGEXP) || [];\n var major = parseInt(match[1], 10);\n var minor = parseInt(match[2], 10);\n var patch = parseInt(match[3], 10);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\nvar defaultRetryAfter = 60 * 1000; // 60 seconds\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param now current unix timestamp\n * @param header string representation of 'Retry-After' header\n */\nexport function parseRetryAfterHeader(now, header) {\n if (!header) {\n return defaultRetryAfter;\n }\n var headerDelay = parseInt(\"\" + header, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n var headerDate = Date.parse(\"\" + header);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n return defaultRetryAfter;\n}\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nexport function addContextToFrame(lines, frame, linesOfContext) {\n if (linesOfContext === void 0) { linesOfContext = 5; }\n var lineno = frame.lineno || 0;\n var maxLines = lines.length;\n var sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0);\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map(function (line) { return snipLine(line, 0); });\n frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map(function (line) { return snipLine(line, 0); });\n}\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nexport function stripUrlQueryAndFragment(urlPath) {\n // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nexport function checkOrSetAlreadyCaught(exception) {\n var _a;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if ((_a = exception) === null || _a === void 0 ? void 0 : _a.__sentry_captured__) {\n return true;\n }\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n Object.defineProperty(exception, '__sentry_captured__', {\n value: true,\n });\n }\n catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n return false;\n}\n//# sourceMappingURL=misc.js.map","import { getGlobalObject } from './global';\nimport { logger } from './logger';\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsErrorEvent() {\n try {\n new ErrorEvent('');\n return true;\n }\n catch (e) {\n return false;\n }\n}\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMError() {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-ignore It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n }\n catch (e) {\n return false;\n }\n}\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsDOMException() {\n try {\n new DOMException('');\n return true;\n }\n catch (e) {\n return false;\n }\n}\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsFetch() {\n if (!('fetch' in getGlobalObject())) {\n return false;\n }\n try {\n new Headers();\n new Request('');\n new Response();\n return true;\n }\n catch (e) {\n return false;\n }\n}\n/**\n * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function isNativeFetch(func) {\n return func && /^function fetch\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nexport function supportsNativeFetch() {\n if (!supportsFetch()) {\n return false;\n }\n var global = getGlobalObject();\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFetch(global.fetch)) {\n return true;\n }\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n var result = false;\n var doc = global.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof doc.createElement === \"function\") {\n try {\n var sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n }\n catch (err) {\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n return result;\n}\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReportingObserver() {\n return 'ReportingObserver' in getGlobalObject();\n}\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsReferrerPolicy() {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default\n // https://caniuse.com/#feat=referrer-policy\n // It doesn't. And it throw exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n if (!supportsFetch()) {\n return false;\n }\n try {\n new Request('_', {\n referrerPolicy: 'origin',\n });\n return true;\n }\n catch (e) {\n return false;\n }\n}\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nexport function supportsHistory() {\n // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n var global = getGlobalObject();\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n var chrome = global.chrome;\n var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n var hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState;\n return !isChromePackagedApp && hasHistoryApi;\n}\n//# sourceMappingURL=supports.js.map","module.exports = require('./lib/SqlString');\n","module.exports = require(\"tls\");","'use strict';\n\n/**\n * Custom implementation of a double ended queue.\n */\nfunction Denque(array, options) {\n var options = options || {};\n\n this._head = 0;\n this._tail = 0;\n this._capacity = options.capacity;\n this._capacityMask = 0x3;\n this._list = new Array(4);\n if (Array.isArray(array)) {\n this._fromArray(array);\n }\n}\n\n/**\n * --------------\n * PUBLIC API\n * -------------\n */\n\n/**\n * Returns the item at the specified index from the list.\n * 0 is the first element, 1 is the second, and so on...\n * Elements at negative values are that many from the end: -1 is one before the end\n * (the last element), -2 is two before the end (one before last), etc.\n * @param index\n * @returns {*}\n */\nDenque.prototype.peekAt = function peekAt(index) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n var len = this.size();\n if (i >= len || i < -len) return undefined;\n if (i < 0) i += len;\n i = (this._head + i) & this._capacityMask;\n return this._list[i];\n};\n\n/**\n * Alias for peekAt()\n * @param i\n * @returns {*}\n */\nDenque.prototype.get = function get(i) {\n return this.peekAt(i);\n};\n\n/**\n * Returns the first item in the list without removing it.\n * @returns {*}\n */\nDenque.prototype.peek = function peek() {\n if (this._head === this._tail) return undefined;\n return this._list[this._head];\n};\n\n/**\n * Alias for peek()\n * @returns {*}\n */\nDenque.prototype.peekFront = function peekFront() {\n return this.peek();\n};\n\n/**\n * Returns the item that is at the back of the queue without removing it.\n * Uses peekAt(-1)\n */\nDenque.prototype.peekBack = function peekBack() {\n return this.peekAt(-1);\n};\n\n/**\n * Returns the current length of the queue\n * @return {Number}\n */\nObject.defineProperty(Denque.prototype, 'length', {\n get: function length() {\n return this.size();\n }\n});\n\n/**\n * Return the number of items on the list, or 0 if empty.\n * @returns {number}\n */\nDenque.prototype.size = function size() {\n if (this._head === this._tail) return 0;\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Add an item at the beginning of the list.\n * @param item\n */\nDenque.prototype.unshift = function unshift(item) {\n if (arguments.length === 0) return this.size();\n var len = this._list.length;\n this._head = (this._head - 1 + len) & this._capacityMask;\n this._list[this._head] = item;\n if (this._tail === this._head) this._growArray();\n if (this._capacity && this.size() > this._capacity) this.pop();\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the first item on the list,\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.shift = function shift() {\n var head = this._head;\n if (head === this._tail) return undefined;\n var item = this._list[head];\n this._list[head] = undefined;\n this._head = (head + 1) & this._capacityMask;\n if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray();\n return item;\n};\n\n/**\n * Add an item to the bottom of the list.\n * @param item\n */\nDenque.prototype.push = function push(item) {\n if (arguments.length === 0) return this.size();\n var tail = this._tail;\n this._list[tail] = item;\n this._tail = (tail + 1) & this._capacityMask;\n if (this._tail === this._head) {\n this._growArray();\n }\n if (this._capacity && this.size() > this._capacity) {\n this.shift();\n }\n if (this._head < this._tail) return this._tail - this._head;\n else return this._capacityMask + 1 - (this._head - this._tail);\n};\n\n/**\n * Remove and return the last item on the list.\n * Returns undefined if the list is empty.\n * @returns {*}\n */\nDenque.prototype.pop = function pop() {\n var tail = this._tail;\n if (tail === this._head) return undefined;\n var len = this._list.length;\n this._tail = (tail - 1 + len) & this._capacityMask;\n var item = this._list[this._tail];\n this._list[this._tail] = undefined;\n if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray();\n return item;\n};\n\n/**\n * Remove and return the item at the specified index from the list.\n * Returns undefined if the list is empty.\n * @param index\n * @returns {*}\n */\nDenque.prototype.removeOne = function removeOne(index) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n if (this._head === this._tail) return void 0;\n var size = this.size();\n var len = this._list.length;\n if (i >= size || i < -size) return void 0;\n if (i < 0) i += size;\n i = (this._head + i) & this._capacityMask;\n var item = this._list[i];\n var k;\n if (index < size / 2) {\n for (k = index; k > 0; k--) {\n this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask];\n }\n this._list[i] = void 0;\n this._head = (this._head + 1 + len) & this._capacityMask;\n } else {\n for (k = size - 1 - index; k > 0; k--) {\n this._list[i] = this._list[i = (i + 1 + len) & this._capacityMask];\n }\n this._list[i] = void 0;\n this._tail = (this._tail - 1 + len) & this._capacityMask;\n }\n return item;\n};\n\n/**\n * Remove number of items from the specified index from the list.\n * Returns array of removed items.\n * Returns undefined if the list is empty.\n * @param index\n * @param count\n * @returns {array}\n */\nDenque.prototype.remove = function remove(index, count) {\n var i = index;\n var removed;\n var del_count = count;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n if (this._head === this._tail) return void 0;\n var size = this.size();\n var len = this._list.length;\n if (i >= size || i < -size || count < 1) return void 0;\n if (i < 0) i += size;\n if (count === 1 || !count) {\n removed = new Array(1);\n removed[0] = this.removeOne(i);\n return removed;\n }\n if (i === 0 && i + count >= size) {\n removed = this.toArray();\n this.clear();\n return removed;\n }\n if (i + count > size) count = size - i;\n var k;\n removed = new Array(count);\n for (k = 0; k < count; k++) {\n removed[k] = this._list[(this._head + i + k) & this._capacityMask];\n }\n i = (this._head + i) & this._capacityMask;\n if (index + count === size) {\n this._tail = (this._tail - count + len) & this._capacityMask;\n for (k = count; k > 0; k--) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n }\n return removed;\n }\n if (index === 0) {\n this._head = (this._head + count + len) & this._capacityMask;\n for (k = count - 1; k > 0; k--) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n }\n return removed;\n }\n if (i < size / 2) {\n this._head = (this._head + index + count + len) & this._capacityMask;\n for (k = index; k > 0; k--) {\n this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]);\n }\n i = (this._head - 1 + len) & this._capacityMask;\n while (del_count > 0) {\n this._list[i = (i - 1 + len) & this._capacityMask] = void 0;\n del_count--;\n }\n if (index < 0) this._tail = i;\n } else {\n this._tail = i;\n i = (i + count + len) & this._capacityMask;\n for (k = size - (count + index); k > 0; k--) {\n this.push(this._list[i++]);\n }\n i = this._tail;\n while (del_count > 0) {\n this._list[i = (i + 1 + len) & this._capacityMask] = void 0;\n del_count--;\n }\n }\n if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray();\n return removed;\n};\n\n/**\n * Native splice implementation.\n * Remove number of items from the specified index from the list and/or add new elements.\n * Returns array of removed items or empty array if count == 0.\n * Returns undefined if the list is empty.\n *\n * @param index\n * @param count\n * @param {...*} [elements]\n * @returns {array}\n */\nDenque.prototype.splice = function splice(index, count) {\n var i = index;\n // expect a number or return undefined\n if ((i !== (i | 0))) {\n return void 0;\n }\n var size = this.size();\n if (i < 0) i += size;\n if (i > size) return void 0;\n if (arguments.length > 2) {\n var k;\n var temp;\n var removed;\n var arg_len = arguments.length;\n var len = this._list.length;\n var arguments_index = 2;\n if (!size || i < size / 2) {\n temp = new Array(i);\n for (k = 0; k < i; k++) {\n temp[k] = this._list[(this._head + k) & this._capacityMask];\n }\n if (count === 0) {\n removed = [];\n if (i > 0) {\n this._head = (this._head + i + len) & this._capacityMask;\n }\n } else {\n removed = this.remove(i, count);\n this._head = (this._head + i + len) & this._capacityMask;\n }\n while (arg_len > arguments_index) {\n this.unshift(arguments[--arg_len]);\n }\n for (k = i; k > 0; k--) {\n this.unshift(temp[k - 1]);\n }\n } else {\n temp = new Array(size - (i + count));\n var leng = temp.length;\n for (k = 0; k < leng; k++) {\n temp[k] = this._list[(this._head + i + count + k) & this._capacityMask];\n }\n if (count === 0) {\n removed = [];\n if (i != size) {\n this._tail = (this._head + i + len) & this._capacityMask;\n }\n } else {\n removed = this.remove(i, count);\n this._tail = (this._tail - leng + len) & this._capacityMask;\n }\n while (arguments_index < arg_len) {\n this.push(arguments[arguments_index++]);\n }\n for (k = 0; k < leng; k++) {\n this.push(temp[k]);\n }\n }\n return removed;\n } else {\n return this.remove(i, count);\n }\n};\n\n/**\n * Soft clear - does not reset capacity.\n */\nDenque.prototype.clear = function clear() {\n this._head = 0;\n this._tail = 0;\n};\n\n/**\n * Returns true or false whether the list is empty.\n * @returns {boolean}\n */\nDenque.prototype.isEmpty = function isEmpty() {\n return this._head === this._tail;\n};\n\n/**\n * Returns an array of all queue items.\n * @returns {Array}\n */\nDenque.prototype.toArray = function toArray() {\n return this._copyArray(false);\n};\n\n/**\n * -------------\n * INTERNALS\n * -------------\n */\n\n/**\n * Fills the queue with items from an array\n * For use in the constructor\n * @param array\n * @private\n */\nDenque.prototype._fromArray = function _fromArray(array) {\n for (var i = 0; i < array.length; i++) this.push(array[i]);\n};\n\n/**\n *\n * @param fullCopy\n * @returns {Array}\n * @private\n */\nDenque.prototype._copyArray = function _copyArray(fullCopy) {\n var newArray = [];\n var list = this._list;\n var len = list.length;\n var i;\n if (fullCopy || this._head > this._tail) {\n for (i = this._head; i < len; i++) newArray.push(list[i]);\n for (i = 0; i < this._tail; i++) newArray.push(list[i]);\n } else {\n for (i = this._head; i < this._tail; i++) newArray.push(list[i]);\n }\n return newArray;\n};\n\n/**\n * Grows the internal list array.\n * @private\n */\nDenque.prototype._growArray = function _growArray() {\n if (this._head) {\n // copy existing data, head to end, then beginning to tail.\n this._list = this._copyArray(true);\n this._head = 0;\n }\n\n // head is at 0 and array is now full, safe to extend\n this._tail = this._list.length;\n\n this._list.length <<= 1;\n this._capacityMask = (this._capacityMask << 1) | 1;\n};\n\n/**\n * Shrinks the internal list array.\n * @private\n */\nDenque.prototype._shrinkArray = function _shrinkArray() {\n this._list.length >>>= 1;\n this._capacityMask >>>= 1;\n};\n\n\nmodule.exports = Denque;\n","'use strict'\n\n// A linked list to keep track of recently-used-ness\nconst Yallist = require('yallist')\n\nconst MAX = Symbol('max')\nconst LENGTH = Symbol('length')\nconst LENGTH_CALCULATOR = Symbol('lengthCalculator')\nconst ALLOW_STALE = Symbol('allowStale')\nconst MAX_AGE = Symbol('maxAge')\nconst DISPOSE = Symbol('dispose')\nconst NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')\nconst LRU_LIST = Symbol('lruList')\nconst CACHE = Symbol('cache')\nconst UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')\n\nconst naiveLength = () => 1\n\n// lruList is a yallist where the head is the youngest\n// item, and the tail is the oldest. the list contains the Hit\n// objects as the entries.\n// Each Hit object has a reference to its Yallist.Node. This\n// never changes.\n//\n// cache is a Map (or PseudoMap) that matches the keys to\n// the Yallist.Node object.\nclass LRUCache {\n constructor (options) {\n if (typeof options === 'number')\n options = { max: options }\n\n if (!options)\n options = {}\n\n if (options.max && (typeof options.max !== 'number' || options.max < 0))\n throw new TypeError('max must be a non-negative number')\n // Kind of weird to have a default max of Infinity, but oh well.\n const max = this[MAX] = options.max || Infinity\n\n const lc = options.length || naiveLength\n this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc\n this[ALLOW_STALE] = options.stale || false\n if (options.maxAge && typeof options.maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n this[MAX_AGE] = options.maxAge || 0\n this[DISPOSE] = options.dispose\n this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false\n this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false\n this.reset()\n }\n\n // resize the cache when the max changes.\n set max (mL) {\n if (typeof mL !== 'number' || mL < 0)\n throw new TypeError('max must be a non-negative number')\n\n this[MAX] = mL || Infinity\n trim(this)\n }\n get max () {\n return this[MAX]\n }\n\n set allowStale (allowStale) {\n this[ALLOW_STALE] = !!allowStale\n }\n get allowStale () {\n return this[ALLOW_STALE]\n }\n\n set maxAge (mA) {\n if (typeof mA !== 'number')\n throw new TypeError('maxAge must be a non-negative number')\n\n this[MAX_AGE] = mA\n trim(this)\n }\n get maxAge () {\n return this[MAX_AGE]\n }\n\n // resize the cache when the lengthCalculator changes.\n set lengthCalculator (lC) {\n if (typeof lC !== 'function')\n lC = naiveLength\n\n if (lC !== this[LENGTH_CALCULATOR]) {\n this[LENGTH_CALCULATOR] = lC\n this[LENGTH] = 0\n this[LRU_LIST].forEach(hit => {\n hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)\n this[LENGTH] += hit.length\n })\n }\n trim(this)\n }\n get lengthCalculator () { return this[LENGTH_CALCULATOR] }\n\n get length () { return this[LENGTH] }\n get itemCount () { return this[LRU_LIST].length }\n\n rforEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].tail; walker !== null;) {\n const prev = walker.prev\n forEachStep(this, fn, walker, thisp)\n walker = prev\n }\n }\n\n forEach (fn, thisp) {\n thisp = thisp || this\n for (let walker = this[LRU_LIST].head; walker !== null;) {\n const next = walker.next\n forEachStep(this, fn, walker, thisp)\n walker = next\n }\n }\n\n keys () {\n return this[LRU_LIST].toArray().map(k => k.key)\n }\n\n values () {\n return this[LRU_LIST].toArray().map(k => k.value)\n }\n\n reset () {\n if (this[DISPOSE] &&\n this[LRU_LIST] &&\n this[LRU_LIST].length) {\n this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))\n }\n\n this[CACHE] = new Map() // hash of items by key\n this[LRU_LIST] = new Yallist() // list of items in order of use recency\n this[LENGTH] = 0 // length of items in the list\n }\n\n dump () {\n return this[LRU_LIST].map(hit =>\n isStale(this, hit) ? false : {\n k: hit.key,\n v: hit.value,\n e: hit.now + (hit.maxAge || 0)\n }).toArray().filter(h => h)\n }\n\n dumpLru () {\n return this[LRU_LIST]\n }\n\n set (key, value, maxAge) {\n maxAge = maxAge || this[MAX_AGE]\n\n if (maxAge && typeof maxAge !== 'number')\n throw new TypeError('maxAge must be a number')\n\n const now = maxAge ? Date.now() : 0\n const len = this[LENGTH_CALCULATOR](value, key)\n\n if (this[CACHE].has(key)) {\n if (len > this[MAX]) {\n del(this, this[CACHE].get(key))\n return false\n }\n\n const node = this[CACHE].get(key)\n const item = node.value\n\n // dispose of the old one before overwriting\n // split out into 2 ifs for better coverage tracking\n if (this[DISPOSE]) {\n if (!this[NO_DISPOSE_ON_SET])\n this[DISPOSE](key, item.value)\n }\n\n item.now = now\n item.maxAge = maxAge\n item.value = value\n this[LENGTH] += len - item.length\n item.length = len\n this.get(key)\n trim(this)\n return true\n }\n\n const hit = new Entry(key, value, len, now, maxAge)\n\n // oversized objects fall out of cache automatically.\n if (hit.length > this[MAX]) {\n if (this[DISPOSE])\n this[DISPOSE](key, value)\n\n return false\n }\n\n this[LENGTH] += hit.length\n this[LRU_LIST].unshift(hit)\n this[CACHE].set(key, this[LRU_LIST].head)\n trim(this)\n return true\n }\n\n has (key) {\n if (!this[CACHE].has(key)) return false\n const hit = this[CACHE].get(key).value\n return !isStale(this, hit)\n }\n\n get (key) {\n return get(this, key, true)\n }\n\n peek (key) {\n return get(this, key, false)\n }\n\n pop () {\n const node = this[LRU_LIST].tail\n if (!node)\n return null\n\n del(this, node)\n return node.value\n }\n\n del (key) {\n del(this, this[CACHE].get(key))\n }\n\n load (arr) {\n // reset the cache\n this.reset()\n\n const now = Date.now()\n // A previous serialized cache has the most recent items first\n for (let l = arr.length - 1; l >= 0; l--) {\n const hit = arr[l]\n const expiresAt = hit.e || 0\n if (expiresAt === 0)\n // the item was created without expiration in a non aged cache\n this.set(hit.k, hit.v)\n else {\n const maxAge = expiresAt - now\n // dont add already expired items\n if (maxAge > 0) {\n this.set(hit.k, hit.v, maxAge)\n }\n }\n }\n }\n\n prune () {\n this[CACHE].forEach((value, key) => get(this, key, false))\n }\n}\n\nconst get = (self, key, doUse) => {\n const node = self[CACHE].get(key)\n if (node) {\n const hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n return undefined\n } else {\n if (doUse) {\n if (self[UPDATE_AGE_ON_GET])\n node.value.now = Date.now()\n self[LRU_LIST].unshiftNode(node)\n }\n }\n return hit.value\n }\n}\n\nconst isStale = (self, hit) => {\n if (!hit || (!hit.maxAge && !self[MAX_AGE]))\n return false\n\n const diff = Date.now() - hit.now\n return hit.maxAge ? diff > hit.maxAge\n : self[MAX_AGE] && (diff > self[MAX_AGE])\n}\n\nconst trim = self => {\n if (self[LENGTH] > self[MAX]) {\n for (let walker = self[LRU_LIST].tail;\n self[LENGTH] > self[MAX] && walker !== null;) {\n // We know that we're about to delete this one, and also\n // what the next least recently used key will be, so just\n // go ahead and set it now.\n const prev = walker.prev\n del(self, walker)\n walker = prev\n }\n }\n}\n\nconst del = (self, node) => {\n if (node) {\n const hit = node.value\n if (self[DISPOSE])\n self[DISPOSE](hit.key, hit.value)\n\n self[LENGTH] -= hit.length\n self[CACHE].delete(hit.key)\n self[LRU_LIST].removeNode(node)\n }\n}\n\nclass Entry {\n constructor (key, value, length, now, maxAge) {\n this.key = key\n this.value = value\n this.length = length\n this.now = now\n this.maxAge = maxAge || 0\n }\n}\n\nconst forEachStep = (self, fn, node, thisp) => {\n let hit = node.value\n if (isStale(self, hit)) {\n del(self, node)\n if (!self[ALLOW_STALE])\n hit = undefined\n }\n if (hit)\n fn.call(thisp, hit.value, hit.key, self)\n}\n\nmodule.exports = LRUCache\n","'use strict';\n\nconst Packet = require('./packets/packet.js');\n\nconst MAX_PACKET_LENGTH = 16777215;\n\nfunction readPacketLength(b, off) {\n const b0 = b[off];\n const b1 = b[off + 1];\n const b2 = b[off + 2];\n if (b1 + b2 === 0) {\n return b0;\n }\n return b0 + (b1 << 8) + (b2 << 16);\n}\n\nclass PacketParser {\n constructor(onPacket, packetHeaderLength) {\n // 4 for normal packets, 7 for comprssed protocol packets\n if (typeof packetHeaderLength === 'undefined') {\n packetHeaderLength = 4;\n }\n // array of last payload chunks\n // only used when current payload is not complete\n this.buffer = [];\n // total length of chunks on buffer\n this.bufferLength = 0;\n this.packetHeaderLength = packetHeaderLength;\n // incomplete header state: number of header bytes received\n this.headerLen = 0;\n // expected payload length\n this.length = 0;\n this.largePacketParts = [];\n this.firstPacketSequenceId = 0;\n this.onPacket = onPacket;\n this.execute = PacketParser.prototype.executeStart;\n this._flushLargePacket =\n packetHeaderLength === 7\n ? this._flushLargePacket7\n : this._flushLargePacket4;\n }\n\n _flushLargePacket4() {\n const numPackets = this.largePacketParts.length;\n this.largePacketParts.unshift(Buffer.from([0, 0, 0, 0])); // insert header\n const body = Buffer.concat(this.largePacketParts);\n const packet = new Packet(this.firstPacketSequenceId, body, 0, body.length);\n this.largePacketParts.length = 0;\n packet.numPackets = numPackets;\n this.onPacket(packet);\n }\n\n _flushLargePacket7() {\n const numPackets = this.largePacketParts.length;\n this.largePacketParts.unshift(Buffer.from([0, 0, 0, 0, 0, 0, 0])); // insert header\n const body = Buffer.concat(this.largePacketParts);\n this.largePacketParts.length = 0;\n const packet = new Packet(this.firstPacketSequenceId, body, 0, body.length);\n packet.numPackets = numPackets;\n this.onPacket(packet);\n }\n\n executeStart(chunk) {\n let start = 0;\n const end = chunk.length;\n while (end - start >= 3) {\n this.length = readPacketLength(chunk, start);\n if (end - start >= this.length + this.packetHeaderLength) {\n // at least one full packet\n const sequenceId = chunk[start + 3];\n if (\n this.length < MAX_PACKET_LENGTH &&\n this.largePacketParts.length === 0\n ) {\n this.onPacket(\n new Packet(\n sequenceId,\n chunk,\n start,\n start + this.packetHeaderLength + this.length\n )\n );\n } else {\n // first large packet - remember it's id\n if (this.largePacketParts.length === 0) {\n this.firstPacketSequenceId = sequenceId;\n }\n this.largePacketParts.push(\n chunk.slice(\n start + this.packetHeaderLength,\n start + this.packetHeaderLength + this.length\n )\n );\n if (this.length < MAX_PACKET_LENGTH) {\n this._flushLargePacket();\n }\n }\n start += this.packetHeaderLength + this.length;\n } else {\n // payload is incomplete\n this.buffer = [chunk.slice(start + 3, end)];\n this.bufferLength = end - start - 3;\n this.execute = PacketParser.prototype.executePayload;\n return;\n }\n }\n if (end - start > 0) {\n // there is start of length header, but it's not full 3 bytes\n this.headerLen = end - start; // 1 or 2 bytes\n this.length = chunk[start];\n if (this.headerLen === 2) {\n this.length = chunk[start] + (chunk[start + 1] << 8);\n this.execute = PacketParser.prototype.executeHeader3;\n } else {\n this.execute = PacketParser.prototype.executeHeader2;\n }\n }\n }\n\n executePayload(chunk) {\n let start = 0;\n const end = chunk.length;\n const remainingPayload =\n this.length - this.bufferLength + this.packetHeaderLength - 3;\n if (end - start >= remainingPayload) {\n // last chunk for payload\n const payload = Buffer.allocUnsafe(this.length + this.packetHeaderLength);\n let offset = 3;\n for (let i = 0; i < this.buffer.length; ++i) {\n this.buffer[i].copy(payload, offset);\n offset += this.buffer[i].length;\n }\n chunk.copy(payload, offset, start, start + remainingPayload);\n const sequenceId = payload[3];\n if (\n this.length < MAX_PACKET_LENGTH &&\n this.largePacketParts.length === 0\n ) {\n this.onPacket(\n new Packet(\n sequenceId,\n payload,\n 0,\n this.length + this.packetHeaderLength\n )\n );\n } else {\n // first large packet - remember it's id\n if (this.largePacketParts.length === 0) {\n this.firstPacketSequenceId = sequenceId;\n }\n this.largePacketParts.push(\n payload.slice(\n this.packetHeaderLength,\n this.packetHeaderLength + this.length\n )\n );\n if (this.length < MAX_PACKET_LENGTH) {\n this._flushLargePacket();\n }\n }\n this.buffer = [];\n this.bufferLength = 0;\n this.execute = PacketParser.prototype.executeStart;\n start += remainingPayload;\n if (end - start > 0) {\n return this.execute(chunk.slice(start, end));\n }\n } else {\n this.buffer.push(chunk);\n this.bufferLength += chunk.length;\n }\n return null;\n }\n\n executeHeader2(chunk) {\n this.length += chunk[0] << 8;\n if (chunk.length > 1) {\n this.length += chunk[1] << 16;\n this.execute = PacketParser.prototype.executePayload;\n return this.executePayload(chunk.slice(2));\n } \n this.execute = PacketParser.prototype.executeHeader3;\n \n return null;\n }\n\n executeHeader3(chunk) {\n this.length += chunk[0] << 16;\n this.execute = PacketParser.prototype.executePayload;\n return this.executePayload(chunk.slice(1));\n }\n}\n\nmodule.exports = PacketParser;\n","// This file was modified by Oracle on June 1, 2021.\n// An entry was created for a new error reported by the MySQL server due to\n// client inactivity.\n// Modifications copyright (c) 2021, Oracle and/or its affiliates.\n\n'use strict';\n\n// copy from https://raw.githubusercontent.com/mysqljs/mysql/7770ee5bb13260c56a160b91fe480d9165dbeeba/lib/protocol/constants/errors.js\n// (c) node-mysql authors\n\n/**\n * MySQL error constants\n *\n * !! Generated by generate-error-constants.js, do not modify by hand !!\n */\n\nexports.EE_CANTCREATEFILE = 1;\nexports.EE_READ = 2;\nexports.EE_WRITE = 3;\nexports.EE_BADCLOSE = 4;\nexports.EE_OUTOFMEMORY = 5;\nexports.EE_DELETE = 6;\nexports.EE_LINK = 7;\nexports.EE_EOFERR = 9;\nexports.EE_CANTLOCK = 10;\nexports.EE_CANTUNLOCK = 11;\nexports.EE_DIR = 12;\nexports.EE_STAT = 13;\nexports.EE_CANT_CHSIZE = 14;\nexports.EE_CANT_OPEN_STREAM = 15;\nexports.EE_GETWD = 16;\nexports.EE_SETWD = 17;\nexports.EE_LINK_WARNING = 18;\nexports.EE_OPEN_WARNING = 19;\nexports.EE_DISK_FULL = 20;\nexports.EE_CANT_MKDIR = 21;\nexports.EE_UNKNOWN_CHARSET = 22;\nexports.EE_OUT_OF_FILERESOURCES = 23;\nexports.EE_CANT_READLINK = 24;\nexports.EE_CANT_SYMLINK = 25;\nexports.EE_REALPATH = 26;\nexports.EE_SYNC = 27;\nexports.EE_UNKNOWN_COLLATION = 28;\nexports.EE_FILENOTFOUND = 29;\nexports.EE_FILE_NOT_CLOSED = 30;\nexports.EE_CHANGE_OWNERSHIP = 31;\nexports.EE_CHANGE_PERMISSIONS = 32;\nexports.EE_CANT_SEEK = 33;\nexports.HA_ERR_KEY_NOT_FOUND = 120;\nexports.HA_ERR_FOUND_DUPP_KEY = 121;\nexports.HA_ERR_INTERNAL_ERROR = 122;\nexports.HA_ERR_RECORD_CHANGED = 123;\nexports.HA_ERR_WRONG_INDEX = 124;\nexports.HA_ERR_CRASHED = 126;\nexports.HA_ERR_WRONG_IN_RECORD = 127;\nexports.HA_ERR_OUT_OF_MEM = 128;\nexports.HA_ERR_NOT_A_TABLE = 130;\nexports.HA_ERR_WRONG_COMMAND = 131;\nexports.HA_ERR_OLD_FILE = 132;\nexports.HA_ERR_NO_ACTIVE_RECORD = 133;\nexports.HA_ERR_RECORD_DELETED = 134;\nexports.HA_ERR_RECORD_FILE_FULL = 135;\nexports.HA_ERR_INDEX_FILE_FULL = 136;\nexports.HA_ERR_END_OF_FILE = 137;\nexports.HA_ERR_UNSUPPORTED = 138;\nexports.HA_ERR_TO_BIG_ROW = 139;\nexports.HA_WRONG_CREATE_OPTION = 140;\nexports.HA_ERR_FOUND_DUPP_UNIQUE = 141;\nexports.HA_ERR_UNKNOWN_CHARSET = 142;\nexports.HA_ERR_WRONG_MRG_TABLE_DEF = 143;\nexports.HA_ERR_CRASHED_ON_REPAIR = 144;\nexports.HA_ERR_CRASHED_ON_USAGE = 145;\nexports.HA_ERR_LOCK_WAIT_TIMEOUT = 146;\nexports.HA_ERR_LOCK_TABLE_FULL = 147;\nexports.HA_ERR_READ_ONLY_TRANSACTION = 148;\nexports.HA_ERR_LOCK_DEADLOCK = 149;\nexports.HA_ERR_CANNOT_ADD_FOREIGN = 150;\nexports.HA_ERR_NO_REFERENCED_ROW = 151;\nexports.HA_ERR_ROW_IS_REFERENCED = 152;\nexports.HA_ERR_NO_SAVEPOINT = 153;\nexports.HA_ERR_NON_UNIQUE_BLOCK_SIZE = 154;\nexports.HA_ERR_NO_SUCH_TABLE = 155;\nexports.HA_ERR_TABLE_EXIST = 156;\nexports.HA_ERR_NO_CONNECTION = 157;\nexports.HA_ERR_NULL_IN_SPATIAL = 158;\nexports.HA_ERR_TABLE_DEF_CHANGED = 159;\nexports.HA_ERR_NO_PARTITION_FOUND = 160;\nexports.HA_ERR_RBR_LOGGING_FAILED = 161;\nexports.HA_ERR_DROP_INDEX_FK = 162;\nexports.HA_ERR_FOREIGN_DUPLICATE_KEY = 163;\nexports.HA_ERR_TABLE_NEEDS_UPGRADE = 164;\nexports.HA_ERR_TABLE_READONLY = 165;\nexports.HA_ERR_AUTOINC_READ_FAILED = 166;\nexports.HA_ERR_AUTOINC_ERANGE = 167;\nexports.HA_ERR_GENERIC = 168;\nexports.HA_ERR_RECORD_IS_THE_SAME = 169;\nexports.HA_ERR_LOGGING_IMPOSSIBLE = 170;\nexports.HA_ERR_CORRUPT_EVENT = 171;\nexports.HA_ERR_NEW_FILE = 172;\nexports.HA_ERR_ROWS_EVENT_APPLY = 173;\nexports.HA_ERR_INITIALIZATION = 174;\nexports.HA_ERR_FILE_TOO_SHORT = 175;\nexports.HA_ERR_WRONG_CRC = 176;\nexports.HA_ERR_TOO_MANY_CONCURRENT_TRXS = 177;\nexports.HA_ERR_NOT_IN_LOCK_PARTITIONS = 178;\nexports.HA_ERR_INDEX_COL_TOO_LONG = 179;\nexports.HA_ERR_INDEX_CORRUPT = 180;\nexports.HA_ERR_UNDO_REC_TOO_BIG = 181;\nexports.HA_FTS_INVALID_DOCID = 182;\nexports.HA_ERR_TABLE_IN_FK_CHECK = 183;\nexports.HA_ERR_TABLESPACE_EXISTS = 184;\nexports.HA_ERR_TOO_MANY_FIELDS = 185;\nexports.HA_ERR_ROW_IN_WRONG_PARTITION = 186;\nexports.HA_ERR_INNODB_READ_ONLY = 187;\nexports.HA_ERR_FTS_EXCEED_RESULT_CACHE_LIMIT = 188;\nexports.HA_ERR_TEMP_FILE_WRITE_FAILURE = 189;\nexports.HA_ERR_INNODB_FORCED_RECOVERY = 190;\nexports.HA_ERR_FTS_TOO_MANY_WORDS_IN_PHRASE = 191;\nexports.ER_HASHCHK = 1000;\nexports.ER_NISAMCHK = 1001;\nexports.ER_NO = 1002;\nexports.ER_YES = 1003;\nexports.ER_CANT_CREATE_FILE = 1004;\nexports.ER_CANT_CREATE_TABLE = 1005;\nexports.ER_CANT_CREATE_DB = 1006;\nexports.ER_DB_CREATE_EXISTS = 1007;\nexports.ER_DB_DROP_EXISTS = 1008;\nexports.ER_DB_DROP_DELETE = 1009;\nexports.ER_DB_DROP_RMDIR = 1010;\nexports.ER_CANT_DELETE_FILE = 1011;\nexports.ER_CANT_FIND_SYSTEM_REC = 1012;\nexports.ER_CANT_GET_STAT = 1013;\nexports.ER_CANT_GET_WD = 1014;\nexports.ER_CANT_LOCK = 1015;\nexports.ER_CANT_OPEN_FILE = 1016;\nexports.ER_FILE_NOT_FOUND = 1017;\nexports.ER_CANT_READ_DIR = 1018;\nexports.ER_CANT_SET_WD = 1019;\nexports.ER_CHECKREAD = 1020;\nexports.ER_DISK_FULL = 1021;\nexports.ER_DUP_KEY = 1022;\nexports.ER_ERROR_ON_CLOSE = 1023;\nexports.ER_ERROR_ON_READ = 1024;\nexports.ER_ERROR_ON_RENAME = 1025;\nexports.ER_ERROR_ON_WRITE = 1026;\nexports.ER_FILE_USED = 1027;\nexports.ER_FILSORT_ABORT = 1028;\nexports.ER_FORM_NOT_FOUND = 1029;\nexports.ER_GET_ERRNO = 1030;\nexports.ER_ILLEGAL_HA = 1031;\nexports.ER_KEY_NOT_FOUND = 1032;\nexports.ER_NOT_FORM_FILE = 1033;\nexports.ER_NOT_KEYFILE = 1034;\nexports.ER_OLD_KEYFILE = 1035;\nexports.ER_OPEN_AS_READONLY = 1036;\nexports.ER_OUTOFMEMORY = 1037;\nexports.ER_OUT_OF_SORTMEMORY = 1038;\nexports.ER_UNEXPECTED_EOF = 1039;\nexports.ER_CON_COUNT_ERROR = 1040;\nexports.ER_OUT_OF_RESOURCES = 1041;\nexports.ER_BAD_HOST_ERROR = 1042;\nexports.ER_HANDSHAKE_ERROR = 1043;\nexports.ER_DBACCESS_DENIED_ERROR = 1044;\nexports.ER_ACCESS_DENIED_ERROR = 1045;\nexports.ER_NO_DB_ERROR = 1046;\nexports.ER_UNKNOWN_COM_ERROR = 1047;\nexports.ER_BAD_NULL_ERROR = 1048;\nexports.ER_BAD_DB_ERROR = 1049;\nexports.ER_TABLE_EXISTS_ERROR = 1050;\nexports.ER_BAD_TABLE_ERROR = 1051;\nexports.ER_NON_UNIQ_ERROR = 1052;\nexports.ER_SERVER_SHUTDOWN = 1053;\nexports.ER_BAD_FIELD_ERROR = 1054;\nexports.ER_WRONG_FIELD_WITH_GROUP = 1055;\nexports.ER_WRONG_GROUP_FIELD = 1056;\nexports.ER_WRONG_SUM_SELECT = 1057;\nexports.ER_WRONG_VALUE_COUNT = 1058;\nexports.ER_TOO_LONG_IDENT = 1059;\nexports.ER_DUP_FIELDNAME = 1060;\nexports.ER_DUP_KEYNAME = 1061;\nexports.ER_DUP_ENTRY = 1062;\nexports.ER_WRONG_FIELD_SPEC = 1063;\nexports.ER_PARSE_ERROR = 1064;\nexports.ER_EMPTY_QUERY = 1065;\nexports.ER_NONUNIQ_TABLE = 1066;\nexports.ER_INVALID_DEFAULT = 1067;\nexports.ER_MULTIPLE_PRI_KEY = 1068;\nexports.ER_TOO_MANY_KEYS = 1069;\nexports.ER_TOO_MANY_KEY_PARTS = 1070;\nexports.ER_TOO_LONG_KEY = 1071;\nexports.ER_KEY_COLUMN_DOES_NOT_EXITS = 1072;\nexports.ER_BLOB_USED_AS_KEY = 1073;\nexports.ER_TOO_BIG_FIELDLENGTH = 1074;\nexports.ER_WRONG_AUTO_KEY = 1075;\nexports.ER_READY = 1076;\nexports.ER_NORMAL_SHUTDOWN = 1077;\nexports.ER_GOT_SIGNAL = 1078;\nexports.ER_SHUTDOWN_COMPLETE = 1079;\nexports.ER_FORCING_CLOSE = 1080;\nexports.ER_IPSOCK_ERROR = 1081;\nexports.ER_NO_SUCH_INDEX = 1082;\nexports.ER_WRONG_FIELD_TERMINATORS = 1083;\nexports.ER_BLOBS_AND_NO_TERMINATED = 1084;\nexports.ER_TEXTFILE_NOT_READABLE = 1085;\nexports.ER_FILE_EXISTS_ERROR = 1086;\nexports.ER_LOAD_INFO = 1087;\nexports.ER_ALTER_INFO = 1088;\nexports.ER_WRONG_SUB_KEY = 1089;\nexports.ER_CANT_REMOVE_ALL_FIELDS = 1090;\nexports.ER_CANT_DROP_FIELD_OR_KEY = 1091;\nexports.ER_INSERT_INFO = 1092;\nexports.ER_UPDATE_TABLE_USED = 1093;\nexports.ER_NO_SUCH_THREAD = 1094;\nexports.ER_KILL_DENIED_ERROR = 1095;\nexports.ER_NO_TABLES_USED = 1096;\nexports.ER_TOO_BIG_SET = 1097;\nexports.ER_NO_UNIQUE_LOGFILE = 1098;\nexports.ER_TABLE_NOT_LOCKED_FOR_WRITE = 1099;\nexports.ER_TABLE_NOT_LOCKED = 1100;\nexports.ER_BLOB_CANT_HAVE_DEFAULT = 1101;\nexports.ER_WRONG_DB_NAME = 1102;\nexports.ER_WRONG_TABLE_NAME = 1103;\nexports.ER_TOO_BIG_SELECT = 1104;\nexports.ER_UNKNOWN_ERROR = 1105;\nexports.ER_UNKNOWN_PROCEDURE = 1106;\nexports.ER_WRONG_PARAMCOUNT_TO_PROCEDURE = 1107;\nexports.ER_WRONG_PARAMETERS_TO_PROCEDURE = 1108;\nexports.ER_UNKNOWN_TABLE = 1109;\nexports.ER_FIELD_SPECIFIED_TWICE = 1110;\nexports.ER_INVALID_GROUP_FUNC_USE = 1111;\nexports.ER_UNSUPPORTED_EXTENSION = 1112;\nexports.ER_TABLE_MUST_HAVE_COLUMNS = 1113;\nexports.ER_RECORD_FILE_FULL = 1114;\nexports.ER_UNKNOWN_CHARACTER_SET = 1115;\nexports.ER_TOO_MANY_TABLES = 1116;\nexports.ER_TOO_MANY_FIELDS = 1117;\nexports.ER_TOO_BIG_ROWSIZE = 1118;\nexports.ER_STACK_OVERRUN = 1119;\nexports.ER_WRONG_OUTER_JOIN = 1120;\nexports.ER_NULL_COLUMN_IN_INDEX = 1121;\nexports.ER_CANT_FIND_UDF = 1122;\nexports.ER_CANT_INITIALIZE_UDF = 1123;\nexports.ER_UDF_NO_PATHS = 1124;\nexports.ER_UDF_EXISTS = 1125;\nexports.ER_CANT_OPEN_LIBRARY = 1126;\nexports.ER_CANT_FIND_DL_ENTRY = 1127;\nexports.ER_FUNCTION_NOT_DEFINED = 1128;\nexports.ER_HOST_IS_BLOCKED = 1129;\nexports.ER_HOST_NOT_PRIVILEGED = 1130;\nexports.ER_PASSWORD_ANONYMOUS_USER = 1131;\nexports.ER_PASSWORD_NOT_ALLOWED = 1132;\nexports.ER_PASSWORD_NO_MATCH = 1133;\nexports.ER_UPDATE_INFO = 1134;\nexports.ER_CANT_CREATE_THREAD = 1135;\nexports.ER_WRONG_VALUE_COUNT_ON_ROW = 1136;\nexports.ER_CANT_REOPEN_TABLE = 1137;\nexports.ER_INVALID_USE_OF_NULL = 1138;\nexports.ER_REGEXP_ERROR = 1139;\nexports.ER_MIX_OF_GROUP_FUNC_AND_FIELDS = 1140;\nexports.ER_NONEXISTING_GRANT = 1141;\nexports.ER_TABLEACCESS_DENIED_ERROR = 1142;\nexports.ER_COLUMNACCESS_DENIED_ERROR = 1143;\nexports.ER_ILLEGAL_GRANT_FOR_TABLE = 1144;\nexports.ER_GRANT_WRONG_HOST_OR_USER = 1145;\nexports.ER_NO_SUCH_TABLE = 1146;\nexports.ER_NONEXISTING_TABLE_GRANT = 1147;\nexports.ER_NOT_ALLOWED_COMMAND = 1148;\nexports.ER_SYNTAX_ERROR = 1149;\nexports.ER_DELAYED_CANT_CHANGE_LOCK = 1150;\nexports.ER_TOO_MANY_DELAYED_THREADS = 1151;\nexports.ER_ABORTING_CONNECTION = 1152;\nexports.ER_NET_PACKET_TOO_LARGE = 1153;\nexports.ER_NET_READ_ERROR_FROM_PIPE = 1154;\nexports.ER_NET_FCNTL_ERROR = 1155;\nexports.ER_NET_PACKETS_OUT_OF_ORDER = 1156;\nexports.ER_NET_UNCOMPRESS_ERROR = 1157;\nexports.ER_NET_READ_ERROR = 1158;\nexports.ER_NET_READ_INTERRUPTED = 1159;\nexports.ER_NET_ERROR_ON_WRITE = 1160;\nexports.ER_NET_WRITE_INTERRUPTED = 1161;\nexports.ER_TOO_LONG_STRING = 1162;\nexports.ER_TABLE_CANT_HANDLE_BLOB = 1163;\nexports.ER_TABLE_CANT_HANDLE_AUTO_INCREMENT = 1164;\nexports.ER_DELAYED_INSERT_TABLE_LOCKED = 1165;\nexports.ER_WRONG_COLUMN_NAME = 1166;\nexports.ER_WRONG_KEY_COLUMN = 1167;\nexports.ER_WRONG_MRG_TABLE = 1168;\nexports.ER_DUP_UNIQUE = 1169;\nexports.ER_BLOB_KEY_WITHOUT_LENGTH = 1170;\nexports.ER_PRIMARY_CANT_HAVE_NULL = 1171;\nexports.ER_TOO_MANY_ROWS = 1172;\nexports.ER_REQUIRES_PRIMARY_KEY = 1173;\nexports.ER_NO_RAID_COMPILED = 1174;\nexports.ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE = 1175;\nexports.ER_KEY_DOES_NOT_EXITS = 1176;\nexports.ER_CHECK_NO_SUCH_TABLE = 1177;\nexports.ER_CHECK_NOT_IMPLEMENTED = 1178;\nexports.ER_CANT_DO_THIS_DURING_AN_TRANSACTION = 1179;\nexports.ER_ERROR_DURING_COMMIT = 1180;\nexports.ER_ERROR_DURING_ROLLBACK = 1181;\nexports.ER_ERROR_DURING_FLUSH_LOGS = 1182;\nexports.ER_ERROR_DURING_CHECKPOINT = 1183;\nexports.ER_NEW_ABORTING_CONNECTION = 1184;\nexports.ER_DUMP_NOT_IMPLEMENTED = 1185;\nexports.ER_FLUSH_MASTER_BINLOG_CLOSED = 1186; // deprecated\nexports.ER_FLUSH_SOURCE_BINLOG_CLOSED = 1186;\nexports.ER_INDEX_REBUILD = 1187;\nexports.ER_MASTER = 1188; // deprecated\nexports.ER_SOURCE = 1188;\nexports.ER_MASTER_NET_READ = 1189; // deprecated\nexports.ER_SOURCE_NET_READ = 1189;\nexports.ER_MASTER_NET_WRITE = 1190; // deprecated\nexports.ER_SOURCE_NET_WRITE = 1190;\nexports.ER_FT_MATCHING_KEY_NOT_FOUND = 1191;\nexports.ER_LOCK_OR_ACTIVE_TRANSACTION = 1192;\nexports.ER_UNKNOWN_SYSTEM_VARIABLE = 1193;\nexports.ER_CRASHED_ON_USAGE = 1194;\nexports.ER_CRASHED_ON_REPAIR = 1195;\nexports.ER_WARNING_NOT_COMPLETE_ROLLBACK = 1196;\nexports.ER_TRANS_CACHE_FULL = 1197;\nexports.ER_SLAVE_MUST_STOP = 1198; // deprecated\nexports.ER_REPLICA_MUST_STOP = 1198;\nexports.ER_SLAVE_NOT_RUNNING = 1199; // deprecated\nexports.ER_REPLICA_NOT_RUNNING = 1199;\nexports.ER_BAD_SLAVE = 1200; // deprecated\nexports.ER_BAD_REPLICA = 1200;\nexports.ER_MASTER_INFO = 1201; // deprecated\nexports.ER_SOURCE_INFO = 1201;\nexports.ER_SLAVE_THREAD = 1202; // deprecated\nexports.ER_REPLICA_THREAD = 1202;\nexports.ER_TOO_MANY_USER_CONNECTIONS = 1203;\nexports.ER_SET_CONSTANTS_ONLY = 1204;\nexports.ER_LOCK_WAIT_TIMEOUT = 1205;\nexports.ER_LOCK_TABLE_FULL = 1206;\nexports.ER_READ_ONLY_TRANSACTION = 1207;\nexports.ER_DROP_DB_WITH_READ_LOCK = 1208;\nexports.ER_CREATE_DB_WITH_READ_LOCK = 1209;\nexports.ER_WRONG_ARGUMENTS = 1210;\nexports.ER_NO_PERMISSION_TO_CREATE_USER = 1211;\nexports.ER_UNION_TABLES_IN_DIFFERENT_DIR = 1212;\nexports.ER_LOCK_DEADLOCK = 1213;\nexports.ER_TABLE_CANT_HANDLE_FT = 1214;\nexports.ER_CANNOT_ADD_FOREIGN = 1215;\nexports.ER_NO_REFERENCED_ROW = 1216;\nexports.ER_ROW_IS_REFERENCED = 1217;\nexports.ER_CONNECT_TO_MASTER = 1218; // deprecated\nexports.ER_CONNECT_TO_SOURCE = 1218;\nexports.ER_QUERY_ON_MASTER = 1219; // deprecated\nexports.ER_QUERY_ON_SOURCE = 1219;\nexports.ER_ERROR_WHEN_EXECUTING_COMMAND = 1220;\nexports.ER_WRONG_USAGE = 1221;\nexports.ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT = 1222;\nexports.ER_CANT_UPDATE_WITH_READLOCK = 1223;\nexports.ER_MIXING_NOT_ALLOWED = 1224;\nexports.ER_DUP_ARGUMENT = 1225;\nexports.ER_USER_LIMIT_REACHED = 1226;\nexports.ER_SPECIFIC_ACCESS_DENIED_ERROR = 1227;\nexports.ER_LOCAL_VARIABLE = 1228;\nexports.ER_GLOBAL_VARIABLE = 1229;\nexports.ER_NO_DEFAULT = 1230;\nexports.ER_WRONG_VALUE_FOR_VAR = 1231;\nexports.ER_WRONG_TYPE_FOR_VAR = 1232;\nexports.ER_VAR_CANT_BE_READ = 1233;\nexports.ER_CANT_USE_OPTION_HERE = 1234;\nexports.ER_NOT_SUPPORTED_YET = 1235;\nexports.ER_MASTER_FATAL_ERROR_READING_BINLOG = 1236; // deprecated\nexports.ER_SOURCE_FATAL_ERROR_READING_BINLOG = 1236;\nexports.ER_SLAVE_IGNORED_TABLE = 1237; // deprecated\nexports.ER_REPLICA_IGNORED_TABLE = 1237;\nexports.ER_INCORRECT_GLOBAL_LOCAL_VAR = 1238;\nexports.ER_WRONG_FK_DEF = 1239;\nexports.ER_KEY_REF_DO_NOT_MATCH_TABLE_REF = 1240;\nexports.ER_OPERAND_COLUMNS = 1241;\nexports.ER_SUBQUERY_NO_1_ROW = 1242;\nexports.ER_UNKNOWN_STMT_HANDLER = 1243;\nexports.ER_CORRUPT_HELP_DB = 1244;\nexports.ER_CYCLIC_REFERENCE = 1245;\nexports.ER_AUTO_CONVERT = 1246;\nexports.ER_ILLEGAL_REFERENCE = 1247;\nexports.ER_DERIVED_MUST_HAVE_ALIAS = 1248;\nexports.ER_SELECT_REDUCED = 1249;\nexports.ER_TABLENAME_NOT_ALLOWED_HERE = 1250;\nexports.ER_NOT_SUPPORTED_AUTH_MODE = 1251;\nexports.ER_SPATIAL_CANT_HAVE_NULL = 1252;\nexports.ER_COLLATION_CHARSET_MISMATCH = 1253;\nexports.ER_SLAVE_WAS_RUNNING = 1254; // deprecated\nexports.ER_REPLICA_WAS_RUNNING = 1254;\nexports.ER_SLAVE_WAS_NOT_RUNNING = 1255; // deprecated\nexports.ER_REPLICA_WAS_NOT_RUNNING = 1255;\nexports.ER_TOO_BIG_FOR_UNCOMPRESS = 1256;\nexports.ER_ZLIB_Z_MEM_ERROR = 1257;\nexports.ER_ZLIB_Z_BUF_ERROR = 1258;\nexports.ER_ZLIB_Z_DATA_ERROR = 1259;\nexports.ER_CUT_VALUE_GROUP_CONCAT = 1260;\nexports.ER_WARN_TOO_FEW_RECORDS = 1261;\nexports.ER_WARN_TOO_MANY_RECORDS = 1262;\nexports.ER_WARN_NULL_TO_NOTNULL = 1263;\nexports.ER_WARN_DATA_OUT_OF_RANGE = 1264;\nexports.ER_WARN_DATA_TRUNCATED = 1265;\nexports.ER_WARN_USING_OTHER_HANDLER = 1266;\nexports.ER_CANT_AGGREGATE_2COLLATIONS = 1267;\nexports.ER_DROP_USER = 1268;\nexports.ER_REVOKE_GRANTS = 1269;\nexports.ER_CANT_AGGREGATE_3COLLATIONS = 1270;\nexports.ER_CANT_AGGREGATE_NCOLLATIONS = 1271;\nexports.ER_VARIABLE_IS_NOT_STRUCT = 1272;\nexports.ER_UNKNOWN_COLLATION = 1273;\nexports.ER_SLAVE_IGNORED_SSL_PARAMS = 1274; // deprecated\nexports.ER_REPLICA_IGNORED_SSL_PARAMS = 1274;\nexports.ER_SERVER_IS_IN_SECURE_AUTH_MODE = 1275;\nexports.ER_WARN_FIELD_RESOLVED = 1276;\nexports.ER_BAD_SLAVE_UNTIL_COND = 1277; // deprecated\nexports.ER_BAD_REPLICA_UNTIL_COND = 1277;\nexports.ER_MISSING_SKIP_SLAVE = 1278; // deprecated\nexports.ER_MISSING_SKIP_REPLICA = 1278;\nexports.ER_UNTIL_COND_IGNORED = 1279;\nexports.ER_WRONG_NAME_FOR_INDEX = 1280;\nexports.ER_WRONG_NAME_FOR_CATALOG = 1281;\nexports.ER_WARN_QC_RESIZE = 1282;\nexports.ER_BAD_FT_COLUMN = 1283;\nexports.ER_UNKNOWN_KEY_CACHE = 1284;\nexports.ER_WARN_HOSTNAME_WONT_WORK = 1285;\nexports.ER_UNKNOWN_STORAGE_ENGINE = 1286;\nexports.ER_WARN_DEPRECATED_SYNTAX = 1287;\nexports.ER_NON_UPDATABLE_TABLE = 1288;\nexports.ER_FEATURE_DISABLED = 1289;\nexports.ER_OPTION_PREVENTS_STATEMENT = 1290;\nexports.ER_DUPLICATED_VALUE_IN_TYPE = 1291;\nexports.ER_TRUNCATED_WRONG_VALUE = 1292;\nexports.ER_TOO_MUCH_AUTO_TIMESTAMP_COLS = 1293;\nexports.ER_INVALID_ON_UPDATE = 1294;\nexports.ER_UNSUPPORTED_PS = 1295;\nexports.ER_GET_ERRMSG = 1296;\nexports.ER_GET_TEMPORARY_ERRMSG = 1297;\nexports.ER_UNKNOWN_TIME_ZONE = 1298;\nexports.ER_WARN_INVALID_TIMESTAMP = 1299;\nexports.ER_INVALID_CHARACTER_STRING = 1300;\nexports.ER_WARN_ALLOWED_PACKET_OVERFLOWED = 1301;\nexports.ER_CONFLICTING_DECLARATIONS = 1302;\nexports.ER_SP_NO_RECURSIVE_CREATE = 1303;\nexports.ER_SP_ALREADY_EXISTS = 1304;\nexports.ER_SP_DOES_NOT_EXIST = 1305;\nexports.ER_SP_DROP_FAILED = 1306;\nexports.ER_SP_STORE_FAILED = 1307;\nexports.ER_SP_LILABEL_MISMATCH = 1308;\nexports.ER_SP_LABEL_REDEFINE = 1309;\nexports.ER_SP_LABEL_MISMATCH = 1310;\nexports.ER_SP_UNINIT_VAR = 1311;\nexports.ER_SP_BADSELECT = 1312;\nexports.ER_SP_BADRETURN = 1313;\nexports.ER_SP_BADSTATEMENT = 1314;\nexports.ER_UPDATE_LOG_DEPRECATED_IGNORED = 1315;\nexports.ER_UPDATE_LOG_DEPRECATED_TRANSLATED = 1316;\nexports.ER_QUERY_INTERRUPTED = 1317;\nexports.ER_SP_WRONG_NO_OF_ARGS = 1318;\nexports.ER_SP_COND_MISMATCH = 1319;\nexports.ER_SP_NORETURN = 1320;\nexports.ER_SP_NORETURNEND = 1321;\nexports.ER_SP_BAD_CURSOR_QUERY = 1322;\nexports.ER_SP_BAD_CURSOR_SELECT = 1323;\nexports.ER_SP_CURSOR_MISMATCH = 1324;\nexports.ER_SP_CURSOR_ALREADY_OPEN = 1325;\nexports.ER_SP_CURSOR_NOT_OPEN = 1326;\nexports.ER_SP_UNDECLARED_VAR = 1327;\nexports.ER_SP_WRONG_NO_OF_FETCH_ARGS = 1328;\nexports.ER_SP_FETCH_NO_DATA = 1329;\nexports.ER_SP_DUP_PARAM = 1330;\nexports.ER_SP_DUP_VAR = 1331;\nexports.ER_SP_DUP_COND = 1332;\nexports.ER_SP_DUP_CURS = 1333;\nexports.ER_SP_CANT_ALTER = 1334;\nexports.ER_SP_SUBSELECT_NYI = 1335;\nexports.ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG = 1336;\nexports.ER_SP_VARCOND_AFTER_CURSHNDLR = 1337;\nexports.ER_SP_CURSOR_AFTER_HANDLER = 1338;\nexports.ER_SP_CASE_NOT_FOUND = 1339;\nexports.ER_FPARSER_TOO_BIG_FILE = 1340;\nexports.ER_FPARSER_BAD_HEADER = 1341;\nexports.ER_FPARSER_EOF_IN_COMMENT = 1342;\nexports.ER_FPARSER_ERROR_IN_PARAMETER = 1343;\nexports.ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER = 1344;\nexports.ER_VIEW_NO_EXPLAIN = 1345;\nexports.ER_FRM_UNKNOWN_TYPE = 1346;\nexports.ER_WRONG_OBJECT = 1347;\nexports.ER_NONUPDATEABLE_COLUMN = 1348;\nexports.ER_VIEW_SELECT_DERIVED = 1349;\nexports.ER_VIEW_SELECT_CLAUSE = 1350;\nexports.ER_VIEW_SELECT_VARIABLE = 1351;\nexports.ER_VIEW_SELECT_TMPTABLE = 1352;\nexports.ER_VIEW_WRONG_LIST = 1353;\nexports.ER_WARN_VIEW_MERGE = 1354;\nexports.ER_WARN_VIEW_WITHOUT_KEY = 1355;\nexports.ER_VIEW_INVALID = 1356;\nexports.ER_SP_NO_DROP_SP = 1357;\nexports.ER_SP_GOTO_IN_HNDLR = 1358;\nexports.ER_TRG_ALREADY_EXISTS = 1359;\nexports.ER_TRG_DOES_NOT_EXIST = 1360;\nexports.ER_TRG_ON_VIEW_OR_TEMP_TABLE = 1361;\nexports.ER_TRG_CANT_CHANGE_ROW = 1362;\nexports.ER_TRG_NO_SUCH_ROW_IN_TRG = 1363;\nexports.ER_NO_DEFAULT_FOR_FIELD = 1364;\nexports.ER_DIVISION_BY_ZERO = 1365;\nexports.ER_TRUNCATED_WRONG_VALUE_FOR_FIELD = 1366;\nexports.ER_ILLEGAL_VALUE_FOR_TYPE = 1367;\nexports.ER_VIEW_NONUPD_CHECK = 1368;\nexports.ER_VIEW_CHECK_FAILED = 1369;\nexports.ER_PROCACCESS_DENIED_ERROR = 1370;\nexports.ER_RELAY_LOG_FAIL = 1371;\nexports.ER_PASSWD_LENGTH = 1372;\nexports.ER_UNKNOWN_TARGET_BINLOG = 1373;\nexports.ER_IO_ERR_LOG_INDEX_READ = 1374;\nexports.ER_BINLOG_PURGE_PROHIBITED = 1375;\nexports.ER_FSEEK_FAIL = 1376;\nexports.ER_BINLOG_PURGE_FATAL_ERR = 1377;\nexports.ER_LOG_IN_USE = 1378;\nexports.ER_LOG_PURGE_UNKNOWN_ERR = 1379;\nexports.ER_RELAY_LOG_INIT = 1380;\nexports.ER_NO_BINARY_LOGGING = 1381;\nexports.ER_RESERVED_SYNTAX = 1382;\nexports.ER_WSAS_FAILED = 1383;\nexports.ER_DIFF_GROUPS_PROC = 1384;\nexports.ER_NO_GROUP_FOR_PROC = 1385;\nexports.ER_ORDER_WITH_PROC = 1386;\nexports.ER_LOGGING_PROHIBIT_CHANGING_OF = 1387;\nexports.ER_NO_FILE_MAPPING = 1388;\nexports.ER_WRONG_MAGIC = 1389;\nexports.ER_PS_MANY_PARAM = 1390;\nexports.ER_KEY_PART_0 = 1391;\nexports.ER_VIEW_CHECKSUM = 1392;\nexports.ER_VIEW_MULTIUPDATE = 1393;\nexports.ER_VIEW_NO_INSERT_FIELD_LIST = 1394;\nexports.ER_VIEW_DELETE_MERGE_VIEW = 1395;\nexports.ER_CANNOT_USER = 1396;\nexports.ER_XAER_NOTA = 1397;\nexports.ER_XAER_INVAL = 1398;\nexports.ER_XAER_RMFAIL = 1399;\nexports.ER_XAER_OUTSIDE = 1400;\nexports.ER_XAER_RMERR = 1401;\nexports.ER_XA_RBROLLBACK = 1402;\nexports.ER_NONEXISTING_PROC_GRANT = 1403;\nexports.ER_PROC_AUTO_GRANT_FAIL = 1404;\nexports.ER_PROC_AUTO_REVOKE_FAIL = 1405;\nexports.ER_DATA_TOO_LONG = 1406;\nexports.ER_SP_BAD_SQLSTATE = 1407;\nexports.ER_STARTUP = 1408;\nexports.ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR = 1409;\nexports.ER_CANT_CREATE_USER_WITH_GRANT = 1410;\nexports.ER_WRONG_VALUE_FOR_TYPE = 1411;\nexports.ER_TABLE_DEF_CHANGED = 1412;\nexports.ER_SP_DUP_HANDLER = 1413;\nexports.ER_SP_NOT_VAR_ARG = 1414;\nexports.ER_SP_NO_RETSET = 1415;\nexports.ER_CANT_CREATE_GEOMETRY_OBJECT = 1416;\nexports.ER_FAILED_ROUTINE_BREAK_BINLOG = 1417;\nexports.ER_BINLOG_UNSAFE_ROUTINE = 1418;\nexports.ER_BINLOG_CREATE_ROUTINE_NEED_SUPER = 1419;\nexports.ER_EXEC_STMT_WITH_OPEN_CURSOR = 1420;\nexports.ER_STMT_HAS_NO_OPEN_CURSOR = 1421;\nexports.ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG = 1422;\nexports.ER_NO_DEFAULT_FOR_VIEW_FIELD = 1423;\nexports.ER_SP_NO_RECURSION = 1424;\nexports.ER_TOO_BIG_SCALE = 1425;\nexports.ER_TOO_BIG_PRECISION = 1426;\nexports.ER_M_BIGGER_THAN_D = 1427;\nexports.ER_WRONG_LOCK_OF_SYSTEM_TABLE = 1428;\nexports.ER_CONNECT_TO_FOREIGN_DATA_SOURCE = 1429;\nexports.ER_QUERY_ON_FOREIGN_DATA_SOURCE = 1430;\nexports.ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST = 1431;\nexports.ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE = 1432;\nexports.ER_FOREIGN_DATA_STRING_INVALID = 1433;\nexports.ER_CANT_CREATE_FEDERATED_TABLE = 1434;\nexports.ER_TRG_IN_WRONG_SCHEMA = 1435;\nexports.ER_STACK_OVERRUN_NEED_MORE = 1436;\nexports.ER_TOO_LONG_BODY = 1437;\nexports.ER_WARN_CANT_DROP_DEFAULT_KEYCACHE = 1438;\nexports.ER_TOO_BIG_DISPLAYWIDTH = 1439;\nexports.ER_XAER_DUPID = 1440;\nexports.ER_DATETIME_FUNCTION_OVERFLOW = 1441;\nexports.ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG = 1442;\nexports.ER_VIEW_PREVENT_UPDATE = 1443;\nexports.ER_PS_NO_RECURSION = 1444;\nexports.ER_SP_CANT_SET_AUTOCOMMIT = 1445;\nexports.ER_MALFORMED_DEFINER = 1446;\nexports.ER_VIEW_FRM_NO_USER = 1447;\nexports.ER_VIEW_OTHER_USER = 1448;\nexports.ER_NO_SUCH_USER = 1449;\nexports.ER_FORBID_SCHEMA_CHANGE = 1450;\nexports.ER_ROW_IS_REFERENCED_2 = 1451;\nexports.ER_NO_REFERENCED_ROW_2 = 1452;\nexports.ER_SP_BAD_VAR_SHADOW = 1453;\nexports.ER_TRG_NO_DEFINER = 1454;\nexports.ER_OLD_FILE_FORMAT = 1455;\nexports.ER_SP_RECURSION_LIMIT = 1456;\nexports.ER_SP_PROC_TABLE_CORRUPT = 1457;\nexports.ER_SP_WRONG_NAME = 1458;\nexports.ER_TABLE_NEEDS_UPGRADE = 1459;\nexports.ER_SP_NO_AGGREGATE = 1460;\nexports.ER_MAX_PREPARED_STMT_COUNT_REACHED = 1461;\nexports.ER_VIEW_RECURSIVE = 1462;\nexports.ER_NON_GROUPING_FIELD_USED = 1463;\nexports.ER_TABLE_CANT_HANDLE_SPKEYS = 1464;\nexports.ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA = 1465;\nexports.ER_REMOVED_SPACES = 1466;\nexports.ER_AUTOINC_READ_FAILED = 1467;\nexports.ER_USERNAME = 1468;\nexports.ER_HOSTNAME = 1469;\nexports.ER_WRONG_STRING_LENGTH = 1470;\nexports.ER_NON_INSERTABLE_TABLE = 1471;\nexports.ER_ADMIN_WRONG_MRG_TABLE = 1472;\nexports.ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT = 1473;\nexports.ER_NAME_BECOMES_EMPTY = 1474;\nexports.ER_AMBIGUOUS_FIELD_TERM = 1475;\nexports.ER_FOREIGN_SERVER_EXISTS = 1476;\nexports.ER_FOREIGN_SERVER_DOESNT_EXIST = 1477;\nexports.ER_ILLEGAL_HA_CREATE_OPTION = 1478;\nexports.ER_PARTITION_REQUIRES_VALUES_ERROR = 1479;\nexports.ER_PARTITION_WRONG_VALUES_ERROR = 1480;\nexports.ER_PARTITION_MAXVALUE_ERROR = 1481;\nexports.ER_PARTITION_SUBPARTITION_ERROR = 1482;\nexports.ER_PARTITION_SUBPART_MIX_ERROR = 1483;\nexports.ER_PARTITION_WRONG_NO_PART_ERROR = 1484;\nexports.ER_PARTITION_WRONG_NO_SUBPART_ERROR = 1485;\nexports.ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR = 1486;\nexports.ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR = 1487;\nexports.ER_FIELD_NOT_FOUND_PART_ERROR = 1488;\nexports.ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR = 1489;\nexports.ER_INCONSISTENT_PARTITION_INFO_ERROR = 1490;\nexports.ER_PARTITION_FUNC_NOT_ALLOWED_ERROR = 1491;\nexports.ER_PARTITIONS_MUST_BE_DEFINED_ERROR = 1492;\nexports.ER_RANGE_NOT_INCREASING_ERROR = 1493;\nexports.ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR = 1494;\nexports.ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR = 1495;\nexports.ER_PARTITION_ENTRY_ERROR = 1496;\nexports.ER_MIX_HANDLER_ERROR = 1497;\nexports.ER_PARTITION_NOT_DEFINED_ERROR = 1498;\nexports.ER_TOO_MANY_PARTITIONS_ERROR = 1499;\nexports.ER_SUBPARTITION_ERROR = 1500;\nexports.ER_CANT_CREATE_HANDLER_FILE = 1501;\nexports.ER_BLOB_FIELD_IN_PART_FUNC_ERROR = 1502;\nexports.ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF = 1503;\nexports.ER_NO_PARTS_ERROR = 1504;\nexports.ER_PARTITION_MGMT_ON_NONPARTITIONED = 1505;\nexports.ER_FOREIGN_KEY_ON_PARTITIONED = 1506;\nexports.ER_DROP_PARTITION_NON_EXISTENT = 1507;\nexports.ER_DROP_LAST_PARTITION = 1508;\nexports.ER_COALESCE_ONLY_ON_HASH_PARTITION = 1509;\nexports.ER_REORG_HASH_ONLY_ON_SAME_NO = 1510;\nexports.ER_REORG_NO_PARAM_ERROR = 1511;\nexports.ER_ONLY_ON_RANGE_LIST_PARTITION = 1512;\nexports.ER_ADD_PARTITION_SUBPART_ERROR = 1513;\nexports.ER_ADD_PARTITION_NO_NEW_PARTITION = 1514;\nexports.ER_COALESCE_PARTITION_NO_PARTITION = 1515;\nexports.ER_REORG_PARTITION_NOT_EXIST = 1516;\nexports.ER_SAME_NAME_PARTITION = 1517;\nexports.ER_NO_BINLOG_ERROR = 1518;\nexports.ER_CONSECUTIVE_REORG_PARTITIONS = 1519;\nexports.ER_REORG_OUTSIDE_RANGE = 1520;\nexports.ER_PARTITION_FUNCTION_FAILURE = 1521;\nexports.ER_PART_STATE_ERROR = 1522;\nexports.ER_LIMITED_PART_RANGE = 1523;\nexports.ER_PLUGIN_IS_NOT_LOADED = 1524;\nexports.ER_WRONG_VALUE = 1525;\nexports.ER_NO_PARTITION_FOR_GIVEN_VALUE = 1526;\nexports.ER_FILEGROUP_OPTION_ONLY_ONCE = 1527;\nexports.ER_CREATE_FILEGROUP_FAILED = 1528;\nexports.ER_DROP_FILEGROUP_FAILED = 1529;\nexports.ER_TABLESPACE_AUTO_EXTEND_ERROR = 1530;\nexports.ER_WRONG_SIZE_NUMBER = 1531;\nexports.ER_SIZE_OVERFLOW_ERROR = 1532;\nexports.ER_ALTER_FILEGROUP_FAILED = 1533;\nexports.ER_BINLOG_ROW_LOGGING_FAILED = 1534;\nexports.ER_BINLOG_ROW_WRONG_TABLE_DEF = 1535;\nexports.ER_BINLOG_ROW_RBR_TO_SBR = 1536;\nexports.ER_EVENT_ALREADY_EXISTS = 1537;\nexports.ER_EVENT_STORE_FAILED = 1538;\nexports.ER_EVENT_DOES_NOT_EXIST = 1539;\nexports.ER_EVENT_CANT_ALTER = 1540;\nexports.ER_EVENT_DROP_FAILED = 1541;\nexports.ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG = 1542;\nexports.ER_EVENT_ENDS_BEFORE_STARTS = 1543;\nexports.ER_EVENT_EXEC_TIME_IN_THE_PAST = 1544;\nexports.ER_EVENT_OPEN_TABLE_FAILED = 1545;\nexports.ER_EVENT_NEITHER_M_EXPR_NOR_M_AT = 1546;\nexports.ER_COL_COUNT_DOESNT_MATCH_CORRUPTED = 1547;\nexports.ER_CANNOT_LOAD_FROM_TABLE = 1548;\nexports.ER_EVENT_CANNOT_DELETE = 1549;\nexports.ER_EVENT_COMPILE_ERROR = 1550;\nexports.ER_EVENT_SAME_NAME = 1551;\nexports.ER_EVENT_DATA_TOO_LONG = 1552;\nexports.ER_DROP_INDEX_FK = 1553;\nexports.ER_WARN_DEPRECATED_SYNTAX_WITH_VER = 1554;\nexports.ER_CANT_WRITE_LOCK_LOG_TABLE = 1555;\nexports.ER_CANT_LOCK_LOG_TABLE = 1556;\nexports.ER_FOREIGN_DUPLICATE_KEY = 1557;\nexports.ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE = 1558;\nexports.ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR = 1559;\nexports.ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT = 1560;\nexports.ER_NDB_CANT_SWITCH_BINLOG_FORMAT = 1561;\nexports.ER_PARTITION_NO_TEMPORARY = 1562;\nexports.ER_PARTITION_CONST_DOMAIN_ERROR = 1563;\nexports.ER_PARTITION_FUNCTION_IS_NOT_ALLOWED = 1564;\nexports.ER_DDL_LOG_ERROR = 1565;\nexports.ER_NULL_IN_VALUES_LESS_THAN = 1566;\nexports.ER_WRONG_PARTITION_NAME = 1567;\nexports.ER_CANT_CHANGE_TX_ISOLATION = 1568;\nexports.ER_DUP_ENTRY_AUTOINCREMENT_CASE = 1569;\nexports.ER_EVENT_MODIFY_QUEUE_ERROR = 1570;\nexports.ER_EVENT_SET_VAR_ERROR = 1571;\nexports.ER_PARTITION_MERGE_ERROR = 1572;\nexports.ER_CANT_ACTIVATE_LOG = 1573;\nexports.ER_RBR_NOT_AVAILABLE = 1574;\nexports.ER_BASE64_DECODE_ERROR = 1575;\nexports.ER_EVENT_RECURSION_FORBIDDEN = 1576;\nexports.ER_EVENTS_DB_ERROR = 1577;\nexports.ER_ONLY_INTEGERS_ALLOWED = 1578;\nexports.ER_UNSUPORTED_LOG_ENGINE = 1579;\nexports.ER_BAD_LOG_STATEMENT = 1580;\nexports.ER_CANT_RENAME_LOG_TABLE = 1581;\nexports.ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT = 1582;\nexports.ER_WRONG_PARAMETERS_TO_NATIVE_FCT = 1583;\nexports.ER_WRONG_PARAMETERS_TO_STORED_FCT = 1584;\nexports.ER_NATIVE_FCT_NAME_COLLISION = 1585;\nexports.ER_DUP_ENTRY_WITH_KEY_NAME = 1586;\nexports.ER_BINLOG_PURGE_EMFILE = 1587;\nexports.ER_EVENT_CANNOT_CREATE_IN_THE_PAST = 1588;\nexports.ER_EVENT_CANNOT_ALTER_IN_THE_PAST = 1589;\nexports.ER_SLAVE_INCIDENT = 1590; // deprecated\nexports.ER_REPLICA_INCIDENT = 1590;\nexports.ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT = 1591;\nexports.ER_BINLOG_UNSAFE_STATEMENT = 1592;\nexports.ER_SLAVE_FATAL_ERROR = 1593; // deprecated\nexports.ER_REPLICA_FATAL_ERROR = 1593;\nexports.ER_SLAVE_RELAY_LOG_READ_FAILURE = 1594; //deprecated\nexports.ER_REPLICA_RELAY_LOG_READ_FAILURE = 1594;\nexports.ER_SLAVE_RELAY_LOG_WRITE_FAILURE = 1595; // deprecated\nexports.ER_REPLICA_RELAY_LOG_WRITE_FAILURE = 1595;\nexports.ER_SLAVE_CREATE_EVENT_FAILURE = 1596; // deprecated\nexports.ER_REPLICA_CREATE_EVENT_FAILURE = 1596;\nexports.ER_SLAVE_MASTER_COM_FAILURE = 1597; // deprecated\nexports.ER_REPLICA_SOURCE_COM_FAILURE = 1597;\nexports.ER_BINLOG_LOGGING_IMPOSSIBLE = 1598;\nexports.ER_VIEW_NO_CREATION_CTX = 1599;\nexports.ER_VIEW_INVALID_CREATION_CTX = 1600;\nexports.ER_SR_INVALID_CREATION_CTX = 1601;\nexports.ER_TRG_CORRUPTED_FILE = 1602;\nexports.ER_TRG_NO_CREATION_CTX = 1603;\nexports.ER_TRG_INVALID_CREATION_CTX = 1604;\nexports.ER_EVENT_INVALID_CREATION_CTX = 1605;\nexports.ER_TRG_CANT_OPEN_TABLE = 1606;\nexports.ER_CANT_CREATE_SROUTINE = 1607;\nexports.ER_NEVER_USED = 1608;\nexports.ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT = 1609;\nexports.ER_SLAVE_CORRUPT_EVENT = 1610; // deprecated\nexports.ER_REPLICA_CORRUPT_EVENT = 1610;\nexports.ER_LOAD_DATA_INVALID_COLUMN = 1611;\nexports.ER_LOG_PURGE_NO_FILE = 1612;\nexports.ER_XA_RBTIMEOUT = 1613;\nexports.ER_XA_RBDEADLOCK = 1614;\nexports.ER_NEED_REPREPARE = 1615;\nexports.ER_DELAYED_NOT_SUPPORTED = 1616;\nexports.WARN_NO_MASTER_INFO = 1617; // deprecated\nexports.WARN_NO_SOURCE_INFO = 1617;\nexports.WARN_OPTION_IGNORED = 1618;\nexports.WARN_PLUGIN_DELETE_BUILTIN = 1619;\nexports.WARN_PLUGIN_BUSY = 1620;\nexports.ER_VARIABLE_IS_READONLY = 1621;\nexports.ER_WARN_ENGINE_TRANSACTION_ROLLBACK = 1622;\nexports.ER_SLAVE_HEARTBEAT_FAILURE = 1623; // deprecated\nexports.ER_REPLICA_HEARTBEAT_FAILURE = 1623;\nexports.ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE = 1624; // deprecated\nexports.ER_REPLICA_HEARTBEAT_VALUE_OUT_OF_RANGE = 1624;\nexports.ER_NDB_REPLICATION_SCHEMA_ERROR = 1625;\nexports.ER_CONFLICT_FN_PARSE_ERROR = 1626;\nexports.ER_EXCEPTIONS_WRITE_ERROR = 1627;\nexports.ER_TOO_LONG_TABLE_COMMENT = 1628;\nexports.ER_TOO_LONG_FIELD_COMMENT = 1629;\nexports.ER_FUNC_INEXISTENT_NAME_COLLISION = 1630;\nexports.ER_DATABASE_NAME = 1631;\nexports.ER_TABLE_NAME = 1632;\nexports.ER_PARTITION_NAME = 1633;\nexports.ER_SUBPARTITION_NAME = 1634;\nexports.ER_TEMPORARY_NAME = 1635;\nexports.ER_RENAMED_NAME = 1636;\nexports.ER_TOO_MANY_CONCURRENT_TRXS = 1637;\nexports.WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED = 1638;\nexports.ER_DEBUG_SYNC_TIMEOUT = 1639;\nexports.ER_DEBUG_SYNC_HIT_LIMIT = 1640;\nexports.ER_DUP_SIGNAL_SET = 1641;\nexports.ER_SIGNAL_WARN = 1642;\nexports.ER_SIGNAL_NOT_FOUND = 1643;\nexports.ER_SIGNAL_EXCEPTION = 1644;\nexports.ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER = 1645;\nexports.ER_SIGNAL_BAD_CONDITION_TYPE = 1646;\nexports.WARN_COND_ITEM_TRUNCATED = 1647;\nexports.ER_COND_ITEM_TOO_LONG = 1648;\nexports.ER_UNKNOWN_LOCALE = 1649;\nexports.ER_SLAVE_IGNORE_SERVER_IDS = 1650; // deprecated\nexports.ER_REPLICA_IGNORE_SERVER_IDS = 1650;\nexports.ER_QUERY_CACHE_DISABLED = 1651;\nexports.ER_SAME_NAME_PARTITION_FIELD = 1652;\nexports.ER_PARTITION_COLUMN_LIST_ERROR = 1653;\nexports.ER_WRONG_TYPE_COLUMN_VALUE_ERROR = 1654;\nexports.ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR = 1655;\nexports.ER_MAXVALUE_IN_VALUES_IN = 1656;\nexports.ER_TOO_MANY_VALUES_ERROR = 1657;\nexports.ER_ROW_SINGLE_PARTITION_FIELD_ERROR = 1658;\nexports.ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD = 1659;\nexports.ER_PARTITION_FIELDS_TOO_LONG = 1660;\nexports.ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE = 1661;\nexports.ER_BINLOG_ROW_MODE_AND_STMT_ENGINE = 1662;\nexports.ER_BINLOG_UNSAFE_AND_STMT_ENGINE = 1663;\nexports.ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE = 1664;\nexports.ER_BINLOG_STMT_MODE_AND_ROW_ENGINE = 1665;\nexports.ER_BINLOG_ROW_INJECTION_AND_STMT_MODE = 1666;\nexports.ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE = 1667;\nexports.ER_BINLOG_UNSAFE_LIMIT = 1668;\nexports.ER_BINLOG_UNSAFE_INSERT_DELAYED = 1669;\nexports.ER_BINLOG_UNSAFE_SYSTEM_TABLE = 1670;\nexports.ER_BINLOG_UNSAFE_AUTOINC_COLUMNS = 1671;\nexports.ER_BINLOG_UNSAFE_UDF = 1672;\nexports.ER_BINLOG_UNSAFE_SYSTEM_VARIABLE = 1673;\nexports.ER_BINLOG_UNSAFE_SYSTEM_FUNCTION = 1674;\nexports.ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS = 1675;\nexports.ER_MESSAGE_AND_STATEMENT = 1676;\nexports.ER_SLAVE_CONVERSION_FAILED = 1677; // deprecated\nexports.ER_REPLICA_CONVERSION_FAILED = 1677;\nexports.ER_SLAVE_CANT_CREATE_CONVERSION = 1678; // deprecated\nexports.ER_REPLICA_CANT_CREATE_CONVERSION = 1678;\nexports.ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT = 1679;\nexports.ER_PATH_LENGTH = 1680;\nexports.ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT = 1681;\nexports.ER_WRONG_NATIVE_TABLE_STRUCTURE = 1682;\nexports.ER_WRONG_PERFSCHEMA_USAGE = 1683;\nexports.ER_WARN_I_S_SKIPPED_TABLE = 1684;\nexports.ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT = 1685;\nexports.ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT = 1686;\nexports.ER_SPATIAL_MUST_HAVE_GEOM_COL = 1687;\nexports.ER_TOO_LONG_INDEX_COMMENT = 1688;\nexports.ER_LOCK_ABORTED = 1689;\nexports.ER_DATA_OUT_OF_RANGE = 1690;\nexports.ER_WRONG_SPVAR_TYPE_IN_LIMIT = 1691;\nexports.ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE = 1692;\nexports.ER_BINLOG_UNSAFE_MIXED_STATEMENT = 1693;\nexports.ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN = 1694;\nexports.ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN = 1695;\nexports.ER_FAILED_READ_FROM_PAR_FILE = 1696;\nexports.ER_VALUES_IS_NOT_INT_TYPE_ERROR = 1697;\nexports.ER_ACCESS_DENIED_NO_PASSWORD_ERROR = 1698;\nexports.ER_SET_PASSWORD_AUTH_PLUGIN = 1699;\nexports.ER_GRANT_PLUGIN_USER_EXISTS = 1700;\nexports.ER_TRUNCATE_ILLEGAL_FK = 1701;\nexports.ER_PLUGIN_IS_PERMANENT = 1702;\nexports.ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN = 1703; // deprecated\nexports.ER_REPLICA_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN = 1703;\nexports.ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX = 1704; // deprecated\nexports.ER_REPLICA_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX = 1704;\nexports.ER_STMT_CACHE_FULL = 1705;\nexports.ER_MULTI_UPDATE_KEY_CONFLICT = 1706;\nexports.ER_TABLE_NEEDS_REBUILD = 1707;\nexports.WARN_OPTION_BELOW_LIMIT = 1708;\nexports.ER_INDEX_COLUMN_TOO_LONG = 1709;\nexports.ER_ERROR_IN_TRIGGER_BODY = 1710;\nexports.ER_ERROR_IN_UNKNOWN_TRIGGER_BODY = 1711;\nexports.ER_INDEX_CORRUPT = 1712;\nexports.ER_UNDO_RECORD_TOO_BIG = 1713;\nexports.ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT = 1714;\nexports.ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE = 1715;\nexports.ER_BINLOG_UNSAFE_REPLACE_SELECT = 1716;\nexports.ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT = 1717;\nexports.ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT = 1718;\nexports.ER_BINLOG_UNSAFE_UPDATE_IGNORE = 1719;\nexports.ER_PLUGIN_NO_UNINSTALL = 1720;\nexports.ER_PLUGIN_NO_INSTALL = 1721;\nexports.ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT = 1722;\nexports.ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC = 1723;\nexports.ER_BINLOG_UNSAFE_INSERT_TWO_KEYS = 1724;\nexports.ER_TABLE_IN_FK_CHECK = 1725;\nexports.ER_UNSUPPORTED_ENGINE = 1726;\nexports.ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST = 1727;\nexports.ER_CANNOT_LOAD_FROM_TABLE_V2 = 1728;\nexports.ER_MASTER_DELAY_VALUE_OUT_OF_RANGE = 1729; // deprecated\nexports.ER_SOURCE_DELAY_VALUE_OUT_OF_RANGE = 1729;\nexports.ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT = 1730;\nexports.ER_PARTITION_EXCHANGE_DIFFERENT_OPTION = 1731;\nexports.ER_PARTITION_EXCHANGE_PART_TABLE = 1732;\nexports.ER_PARTITION_EXCHANGE_TEMP_TABLE = 1733;\nexports.ER_PARTITION_INSTEAD_OF_SUBPARTITION = 1734;\nexports.ER_UNKNOWN_PARTITION = 1735;\nexports.ER_TABLES_DIFFERENT_METADATA = 1736;\nexports.ER_ROW_DOES_NOT_MATCH_PARTITION = 1737;\nexports.ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX = 1738;\nexports.ER_WARN_INDEX_NOT_APPLICABLE = 1739;\nexports.ER_PARTITION_EXCHANGE_FOREIGN_KEY = 1740;\nexports.ER_NO_SUCH_KEY_VALUE = 1741;\nexports.ER_RPL_INFO_DATA_TOO_LONG = 1742;\nexports.ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE = 1743;\nexports.ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE = 1744;\nexports.ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX = 1745;\nexports.ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT = 1746;\nexports.ER_PARTITION_CLAUSE_ON_NONPARTITIONED = 1747;\nexports.ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET = 1748;\nexports.ER_NO_SUCH_PARTITION = 1749;\nexports.ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE = 1750;\nexports.ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE = 1751;\nexports.ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE = 1752;\nexports.ER_MTS_FEATURE_IS_NOT_SUPPORTED = 1753;\nexports.ER_MTS_UPDATED_DBS_GREATER_MAX = 1754;\nexports.ER_MTS_CANT_PARALLEL = 1755;\nexports.ER_MTS_INCONSISTENT_DATA = 1756;\nexports.ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING = 1757;\nexports.ER_DA_INVALID_CONDITION_NUMBER = 1758;\nexports.ER_INSECURE_PLAIN_TEXT = 1759;\nexports.ER_INSECURE_CHANGE_MASTER = 1760; // deprecated\nexports.ER_INSECURE_CHANGE_SOURCE = 1760;\nexports.ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO = 1761;\nexports.ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO = 1762;\nexports.ER_SQLTHREAD_WITH_SECURE_SLAVE = 1763; // deprecated\nexports.ER_SQLTHREAD_WITH_SECURE_REPLICA = 1763;\nexports.ER_TABLE_HAS_NO_FT = 1764;\nexports.ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER = 1765;\nexports.ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION = 1766;\nexports.ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST = 1767;\nexports.ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION_WHEN_GTID_NEXT_LIST_IS_NULL = 1768;\nexports.ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION = 1769;\nexports.ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL = 1770;\nexports.ER_SKIPPING_LOGGED_TRANSACTION = 1771;\nexports.ER_MALFORMED_GTID_SET_SPECIFICATION = 1772;\nexports.ER_MALFORMED_GTID_SET_ENCODING = 1773;\nexports.ER_MALFORMED_GTID_SPECIFICATION = 1774;\nexports.ER_GNO_EXHAUSTED = 1775;\nexports.ER_BAD_SLAVE_AUTO_POSITION = 1776; // deprecated\nexports.ER_BAD_REPLICA_AUTO_POSITION = 1776;\nexports.ER_AUTO_POSITION_REQUIRES_GTID_MODE_ON = 1777;\nexports.ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET = 1778;\nexports.ER_GTID_MODE_2_OR_3_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON = 1779;\nexports.ER_GTID_MODE_REQUIRES_BINLOG = 1780;\nexports.ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF = 1781;\nexports.ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON = 1782;\nexports.ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF = 1783;\nexports.ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF = 1784;\nexports.ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE = 1785;\nexports.ER_GTID_UNSAFE_CREATE_SELECT = 1786;\nexports.ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION = 1787;\nexports.ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME = 1788;\nexports.ER_MASTER_HAS_PURGED_REQUIRED_GTIDS = 1789; // deprecated\nexports.ER_SOURCE_HAS_PURGED_REQUIRED_GTIDS = 1789;\nexports.ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID = 1790;\nexports.ER_UNKNOWN_EXPLAIN_FORMAT = 1791;\nexports.ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION = 1792;\nexports.ER_TOO_LONG_TABLE_PARTITION_COMMENT = 1793;\nexports.ER_SLAVE_CONFIGURATION = 1794; // deprecated\nexports.ER_REPLICA_CONFIGURATION = 1794;\nexports.ER_INNODB_FT_LIMIT = 1795;\nexports.ER_INNODB_NO_FT_TEMP_TABLE = 1796;\nexports.ER_INNODB_FT_WRONG_DOCID_COLUMN = 1797;\nexports.ER_INNODB_FT_WRONG_DOCID_INDEX = 1798;\nexports.ER_INNODB_ONLINE_LOG_TOO_BIG = 1799;\nexports.ER_UNKNOWN_ALTER_ALGORITHM = 1800;\nexports.ER_UNKNOWN_ALTER_LOCK = 1801;\nexports.ER_MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS = 1802; // deprecated\nexports.ER_MTS_CHANGE_SOURCE_CANT_RUN_WITH_GAPS = 1802;\nexports.ER_MTS_RECOVERY_FAILURE = 1803;\nexports.ER_MTS_RESET_WORKERS = 1804;\nexports.ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2 = 1805;\nexports.ER_SLAVE_SILENT_RETRY_TRANSACTION = 1806; // deprecated\nexports.ER_REPLICA_SILENT_RETRY_TRANSACTION = 1806;\nexports.ER_DISCARD_FK_CHECKS_RUNNING = 1807;\nexports.ER_TABLE_SCHEMA_MISMATCH = 1808;\nexports.ER_TABLE_IN_SYSTEM_TABLESPACE = 1809;\nexports.ER_IO_READ_ERROR = 1810;\nexports.ER_IO_WRITE_ERROR = 1811;\nexports.ER_TABLESPACE_MISSING = 1812;\nexports.ER_TABLESPACE_EXISTS = 1813;\nexports.ER_TABLESPACE_DISCARDED = 1814;\nexports.ER_INTERNAL_ERROR = 1815;\nexports.ER_INNODB_IMPORT_ERROR = 1816;\nexports.ER_INNODB_INDEX_CORRUPT = 1817;\nexports.ER_INVALID_YEAR_COLUMN_LENGTH = 1818;\nexports.ER_NOT_VALID_PASSWORD = 1819;\nexports.ER_MUST_CHANGE_PASSWORD = 1820;\nexports.ER_FK_NO_INDEX_CHILD = 1821;\nexports.ER_FK_NO_INDEX_PARENT = 1822;\nexports.ER_FK_FAIL_ADD_SYSTEM = 1823;\nexports.ER_FK_CANNOT_OPEN_PARENT = 1824;\nexports.ER_FK_INCORRECT_OPTION = 1825;\nexports.ER_FK_DUP_NAME = 1826;\nexports.ER_PASSWORD_FORMAT = 1827;\nexports.ER_FK_COLUMN_CANNOT_DROP = 1828;\nexports.ER_FK_COLUMN_CANNOT_DROP_CHILD = 1829;\nexports.ER_FK_COLUMN_NOT_NULL = 1830;\nexports.ER_DUP_INDEX = 1831;\nexports.ER_FK_COLUMN_CANNOT_CHANGE = 1832;\nexports.ER_FK_COLUMN_CANNOT_CHANGE_CHILD = 1833;\nexports.ER_FK_CANNOT_DELETE_PARENT = 1834;\nexports.ER_MALFORMED_PACKET = 1835;\nexports.ER_READ_ONLY_MODE = 1836;\nexports.ER_GTID_NEXT_TYPE_UNDEFINED_GROUP = 1837;\nexports.ER_VARIABLE_NOT_SETTABLE_IN_SP = 1838;\nexports.ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF = 1839;\nexports.ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY = 1840;\nexports.ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY = 1841;\nexports.ER_GTID_PURGED_WAS_CHANGED = 1842;\nexports.ER_GTID_EXECUTED_WAS_CHANGED = 1843;\nexports.ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES = 1844;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED = 1845;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON = 1846;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY = 1847;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION = 1848;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME = 1849;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE = 1850;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK = 1851;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE = 1852;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK = 1853;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC = 1854;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS = 1855;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS = 1856;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS = 1857;\nexports.ER_SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE = 1858; // deprecated\nexports.ER_SQL_REPLICA_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE = 1858;\nexports.ER_DUP_UNKNOWN_IN_INDEX = 1859;\nexports.ER_IDENT_CAUSES_TOO_LONG_PATH = 1860;\nexports.ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL = 1861;\nexports.ER_MUST_CHANGE_PASSWORD_LOGIN = 1862;\nexports.ER_ROW_IN_WRONG_PARTITION = 1863;\nexports.ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX = 1864;\nexports.ER_INNODB_NO_FT_USES_PARSER = 1865;\nexports.ER_BINLOG_LOGICAL_CORRUPTION = 1866;\nexports.ER_WARN_PURGE_LOG_IN_USE = 1867;\nexports.ER_WARN_PURGE_LOG_IS_ACTIVE = 1868;\nexports.ER_AUTO_INCREMENT_CONFLICT = 1869;\nexports.WARN_ON_BLOCKHOLE_IN_RBR = 1870;\nexports.ER_SLAVE_MI_INIT_REPOSITORY = 1871; // deprecated\nexports.ER_REPLICA_MI_INIT_REPOSITORY = 1871;\nexports.ER_SLAVE_RLI_INIT_REPOSITORY = 1872; // deprecated\nexports.ER_REPLICA_RLI_INIT_REPOSITORY = 1872;\nexports.ER_ACCESS_DENIED_CHANGE_USER_ERROR = 1873;\nexports.ER_INNODB_READ_ONLY = 1874;\nexports.ER_STOP_SLAVE_SQL_THREAD_TIMEOUT = 1875; // deprecated\nexports.ER_STOP_REPLICA_SQL_THREAD_TIMEOUT = 1875;\nexports.ER_STOP_SLAVE_IO_THREAD_TIMEOUT = 1876; // deprecated\nexports.ER_STOP_REPLICA_IO_THREAD_TIMEOUT = 1876;\nexports.ER_TABLE_CORRUPT = 1877;\nexports.ER_TEMP_FILE_WRITE_FAILURE = 1878;\nexports.ER_INNODB_FT_AUX_NOT_HEX_ID = 1879;\nexports.ER_OLD_TEMPORALS_UPGRADED = 1880;\nexports.ER_INNODB_FORCED_RECOVERY = 1881;\nexports.ER_AES_INVALID_IV = 1882;\nexports.ER_FILE_CORRUPT = 1883;\nexports.ER_ERROR_ON_SOURCE = 1884;\nexports.ER_INCONSISTENT_ERROR = 1885;\nexports.ER_STORAGE_ENGINE_NOT_LOADED = 1886;\nexports.ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER = 1887;\nexports.ER_WARN_LEGACY_SYNTAX_CONVERTED = 1888;\nexports.ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN = 1889;\nexports.ER_CANNOT_DISCARD_TEMPORARY_TABLE = 1890;\nexports.ER_FK_DEPTH_EXCEEDED = 1891;\nexports.ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2 = 1892;\nexports.ER_WARN_TRIGGER_DOESNT_HAVE_CREATED = 1893;\nexports.ER_REFERENCED_TRG_DOES_NOT_EXIST = 1894;\nexports.ER_EXPLAIN_NOT_SUPPORTED = 1895;\nexports.ER_INVALID_FIELD_SIZE = 1896;\nexports.ER_MISSING_HA_CREATE_OPTION = 1897;\nexports.ER_ENGINE_OUT_OF_MEMORY = 1898;\nexports.ER_PASSWORD_EXPIRE_ANONYMOUS_USER = 1899;\nexports.ER_REPLICA_SQL_THREAD_MUST_STOP = 1900;\nexports.ER_NO_FT_MATERIALIZED_SUBQUERY = 1901;\nexports.ER_INNODB_UNDO_LOG_FULL = 1902;\nexports.ER_INVALID_ARGUMENT_FOR_LOGARITHM = 1903;\nexports.ER_REPLICA_IO_THREAD_MUST_STOP = 1904;\nexports.ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO = 1905;\nexports.ER_WARN_ONLY_SOURCE_LOG_FILE_NO_POS = 1906;\nexports.ER_QUERY_TIMEOUT = 1907;\nexports.ER_NON_RO_SELECT_DISABLE_TIMER = 1908;\nexports.ER_DUP_LIST_ENTRY = 1909;\nexports.ER_SQL_MODE_NO_EFFECT = 1910;\nexports.ER_SESSION_WAS_KILLED = 3169;\nexports.ER_CLIENT_INTERACTION_TIMEOUT = 4031;\n\n// Lookup-by-number table\nexports[1] = 'EE_CANTCREATEFILE';\nexports[2] = 'EE_READ';\nexports[3] = 'EE_WRITE';\nexports[4] = 'EE_BADCLOSE';\nexports[5] = 'EE_OUTOFMEMORY';\nexports[6] = 'EE_DELETE';\nexports[7] = 'EE_LINK';\nexports[9] = 'EE_EOFERR';\nexports[10] = 'EE_CANTLOCK';\nexports[11] = 'EE_CANTUNLOCK';\nexports[12] = 'EE_DIR';\nexports[13] = 'EE_STAT';\nexports[14] = 'EE_CANT_CHSIZE';\nexports[15] = 'EE_CANT_OPEN_STREAM';\nexports[16] = 'EE_GETWD';\nexports[17] = 'EE_SETWD';\nexports[18] = 'EE_LINK_WARNING';\nexports[19] = 'EE_OPEN_WARNING';\nexports[20] = 'EE_DISK_FULL';\nexports[21] = 'EE_CANT_MKDIR';\nexports[22] = 'EE_UNKNOWN_CHARSET';\nexports[23] = 'EE_OUT_OF_FILERESOURCES';\nexports[24] = 'EE_CANT_READLINK';\nexports[25] = 'EE_CANT_SYMLINK';\nexports[26] = 'EE_REALPATH';\nexports[27] = 'EE_SYNC';\nexports[28] = 'EE_UNKNOWN_COLLATION';\nexports[29] = 'EE_FILENOTFOUND';\nexports[30] = 'EE_FILE_NOT_CLOSED';\nexports[31] = 'EE_CHANGE_OWNERSHIP';\nexports[32] = 'EE_CHANGE_PERMISSIONS';\nexports[33] = 'EE_CANT_SEEK';\nexports[120] = 'HA_ERR_KEY_NOT_FOUND';\nexports[121] = 'HA_ERR_FOUND_DUPP_KEY';\nexports[122] = 'HA_ERR_INTERNAL_ERROR';\nexports[123] = 'HA_ERR_RECORD_CHANGED';\nexports[124] = 'HA_ERR_WRONG_INDEX';\nexports[126] = 'HA_ERR_CRASHED';\nexports[127] = 'HA_ERR_WRONG_IN_RECORD';\nexports[128] = 'HA_ERR_OUT_OF_MEM';\nexports[130] = 'HA_ERR_NOT_A_TABLE';\nexports[131] = 'HA_ERR_WRONG_COMMAND';\nexports[132] = 'HA_ERR_OLD_FILE';\nexports[133] = 'HA_ERR_NO_ACTIVE_RECORD';\nexports[134] = 'HA_ERR_RECORD_DELETED';\nexports[135] = 'HA_ERR_RECORD_FILE_FULL';\nexports[136] = 'HA_ERR_INDEX_FILE_FULL';\nexports[137] = 'HA_ERR_END_OF_FILE';\nexports[138] = 'HA_ERR_UNSUPPORTED';\nexports[139] = 'HA_ERR_TO_BIG_ROW';\nexports[140] = 'HA_WRONG_CREATE_OPTION';\nexports[141] = 'HA_ERR_FOUND_DUPP_UNIQUE';\nexports[142] = 'HA_ERR_UNKNOWN_CHARSET';\nexports[143] = 'HA_ERR_WRONG_MRG_TABLE_DEF';\nexports[144] = 'HA_ERR_CRASHED_ON_REPAIR';\nexports[145] = 'HA_ERR_CRASHED_ON_USAGE';\nexports[146] = 'HA_ERR_LOCK_WAIT_TIMEOUT';\nexports[147] = 'HA_ERR_LOCK_TABLE_FULL';\nexports[148] = 'HA_ERR_READ_ONLY_TRANSACTION';\nexports[149] = 'HA_ERR_LOCK_DEADLOCK';\nexports[150] = 'HA_ERR_CANNOT_ADD_FOREIGN';\nexports[151] = 'HA_ERR_NO_REFERENCED_ROW';\nexports[152] = 'HA_ERR_ROW_IS_REFERENCED';\nexports[153] = 'HA_ERR_NO_SAVEPOINT';\nexports[154] = 'HA_ERR_NON_UNIQUE_BLOCK_SIZE';\nexports[155] = 'HA_ERR_NO_SUCH_TABLE';\nexports[156] = 'HA_ERR_TABLE_EXIST';\nexports[157] = 'HA_ERR_NO_CONNECTION';\nexports[158] = 'HA_ERR_NULL_IN_SPATIAL';\nexports[159] = 'HA_ERR_TABLE_DEF_CHANGED';\nexports[160] = 'HA_ERR_NO_PARTITION_FOUND';\nexports[161] = 'HA_ERR_RBR_LOGGING_FAILED';\nexports[162] = 'HA_ERR_DROP_INDEX_FK';\nexports[163] = 'HA_ERR_FOREIGN_DUPLICATE_KEY';\nexports[164] = 'HA_ERR_TABLE_NEEDS_UPGRADE';\nexports[165] = 'HA_ERR_TABLE_READONLY';\nexports[166] = 'HA_ERR_AUTOINC_READ_FAILED';\nexports[167] = 'HA_ERR_AUTOINC_ERANGE';\nexports[168] = 'HA_ERR_GENERIC';\nexports[169] = 'HA_ERR_RECORD_IS_THE_SAME';\nexports[170] = 'HA_ERR_LOGGING_IMPOSSIBLE';\nexports[171] = 'HA_ERR_CORRUPT_EVENT';\nexports[172] = 'HA_ERR_NEW_FILE';\nexports[173] = 'HA_ERR_ROWS_EVENT_APPLY';\nexports[174] = 'HA_ERR_INITIALIZATION';\nexports[175] = 'HA_ERR_FILE_TOO_SHORT';\nexports[176] = 'HA_ERR_WRONG_CRC';\nexports[177] = 'HA_ERR_TOO_MANY_CONCURRENT_TRXS';\nexports[178] = 'HA_ERR_NOT_IN_LOCK_PARTITIONS';\nexports[179] = 'HA_ERR_INDEX_COL_TOO_LONG';\nexports[180] = 'HA_ERR_INDEX_CORRUPT';\nexports[181] = 'HA_ERR_UNDO_REC_TOO_BIG';\nexports[182] = 'HA_FTS_INVALID_DOCID';\nexports[183] = 'HA_ERR_TABLE_IN_FK_CHECK';\nexports[184] = 'HA_ERR_TABLESPACE_EXISTS';\nexports[185] = 'HA_ERR_TOO_MANY_FIELDS';\nexports[186] = 'HA_ERR_ROW_IN_WRONG_PARTITION';\nexports[187] = 'HA_ERR_INNODB_READ_ONLY';\nexports[188] = 'HA_ERR_FTS_EXCEED_RESULT_CACHE_LIMIT';\nexports[189] = 'HA_ERR_TEMP_FILE_WRITE_FAILURE';\nexports[190] = 'HA_ERR_INNODB_FORCED_RECOVERY';\nexports[191] = 'HA_ERR_FTS_TOO_MANY_WORDS_IN_PHRASE';\nexports[1000] = 'ER_HASHCHK';\nexports[1001] = 'ER_NISAMCHK';\nexports[1002] = 'ER_NO';\nexports[1003] = 'ER_YES';\nexports[1004] = 'ER_CANT_CREATE_FILE';\nexports[1005] = 'ER_CANT_CREATE_TABLE';\nexports[1006] = 'ER_CANT_CREATE_DB';\nexports[1007] = 'ER_DB_CREATE_EXISTS';\nexports[1008] = 'ER_DB_DROP_EXISTS';\nexports[1009] = 'ER_DB_DROP_DELETE';\nexports[1010] = 'ER_DB_DROP_RMDIR';\nexports[1011] = 'ER_CANT_DELETE_FILE';\nexports[1012] = 'ER_CANT_FIND_SYSTEM_REC';\nexports[1013] = 'ER_CANT_GET_STAT';\nexports[1014] = 'ER_CANT_GET_WD';\nexports[1015] = 'ER_CANT_LOCK';\nexports[1016] = 'ER_CANT_OPEN_FILE';\nexports[1017] = 'ER_FILE_NOT_FOUND';\nexports[1018] = 'ER_CANT_READ_DIR';\nexports[1019] = 'ER_CANT_SET_WD';\nexports[1020] = 'ER_CHECKREAD';\nexports[1021] = 'ER_DISK_FULL';\nexports[1022] = 'ER_DUP_KEY';\nexports[1023] = 'ER_ERROR_ON_CLOSE';\nexports[1024] = 'ER_ERROR_ON_READ';\nexports[1025] = 'ER_ERROR_ON_RENAME';\nexports[1026] = 'ER_ERROR_ON_WRITE';\nexports[1027] = 'ER_FILE_USED';\nexports[1028] = 'ER_FILSORT_ABORT';\nexports[1029] = 'ER_FORM_NOT_FOUND';\nexports[1030] = 'ER_GET_ERRNO';\nexports[1031] = 'ER_ILLEGAL_HA';\nexports[1032] = 'ER_KEY_NOT_FOUND';\nexports[1033] = 'ER_NOT_FORM_FILE';\nexports[1034] = 'ER_NOT_KEYFILE';\nexports[1035] = 'ER_OLD_KEYFILE';\nexports[1036] = 'ER_OPEN_AS_READONLY';\nexports[1037] = 'ER_OUTOFMEMORY';\nexports[1038] = 'ER_OUT_OF_SORTMEMORY';\nexports[1039] = 'ER_UNEXPECTED_EOF';\nexports[1040] = 'ER_CON_COUNT_ERROR';\nexports[1041] = 'ER_OUT_OF_RESOURCES';\nexports[1042] = 'ER_BAD_HOST_ERROR';\nexports[1043] = 'ER_HANDSHAKE_ERROR';\nexports[1044] = 'ER_DBACCESS_DENIED_ERROR';\nexports[1045] = 'ER_ACCESS_DENIED_ERROR';\nexports[1046] = 'ER_NO_DB_ERROR';\nexports[1047] = 'ER_UNKNOWN_COM_ERROR';\nexports[1048] = 'ER_BAD_NULL_ERROR';\nexports[1049] = 'ER_BAD_DB_ERROR';\nexports[1050] = 'ER_TABLE_EXISTS_ERROR';\nexports[1051] = 'ER_BAD_TABLE_ERROR';\nexports[1052] = 'ER_NON_UNIQ_ERROR';\nexports[1053] = 'ER_SERVER_SHUTDOWN';\nexports[1054] = 'ER_BAD_FIELD_ERROR';\nexports[1055] = 'ER_WRONG_FIELD_WITH_GROUP';\nexports[1056] = 'ER_WRONG_GROUP_FIELD';\nexports[1057] = 'ER_WRONG_SUM_SELECT';\nexports[1058] = 'ER_WRONG_VALUE_COUNT';\nexports[1059] = 'ER_TOO_LONG_IDENT';\nexports[1060] = 'ER_DUP_FIELDNAME';\nexports[1061] = 'ER_DUP_KEYNAME';\nexports[1062] = 'ER_DUP_ENTRY';\nexports[1063] = 'ER_WRONG_FIELD_SPEC';\nexports[1064] = 'ER_PARSE_ERROR';\nexports[1065] = 'ER_EMPTY_QUERY';\nexports[1066] = 'ER_NONUNIQ_TABLE';\nexports[1067] = 'ER_INVALID_DEFAULT';\nexports[1068] = 'ER_MULTIPLE_PRI_KEY';\nexports[1069] = 'ER_TOO_MANY_KEYS';\nexports[1070] = 'ER_TOO_MANY_KEY_PARTS';\nexports[1071] = 'ER_TOO_LONG_KEY';\nexports[1072] = 'ER_KEY_COLUMN_DOES_NOT_EXITS';\nexports[1073] = 'ER_BLOB_USED_AS_KEY';\nexports[1074] = 'ER_TOO_BIG_FIELDLENGTH';\nexports[1075] = 'ER_WRONG_AUTO_KEY';\nexports[1076] = 'ER_READY';\nexports[1077] = 'ER_NORMAL_SHUTDOWN';\nexports[1078] = 'ER_GOT_SIGNAL';\nexports[1079] = 'ER_SHUTDOWN_COMPLETE';\nexports[1080] = 'ER_FORCING_CLOSE';\nexports[1081] = 'ER_IPSOCK_ERROR';\nexports[1082] = 'ER_NO_SUCH_INDEX';\nexports[1083] = 'ER_WRONG_FIELD_TERMINATORS';\nexports[1084] = 'ER_BLOBS_AND_NO_TERMINATED';\nexports[1085] = 'ER_TEXTFILE_NOT_READABLE';\nexports[1086] = 'ER_FILE_EXISTS_ERROR';\nexports[1087] = 'ER_LOAD_INFO';\nexports[1088] = 'ER_ALTER_INFO';\nexports[1089] = 'ER_WRONG_SUB_KEY';\nexports[1090] = 'ER_CANT_REMOVE_ALL_FIELDS';\nexports[1091] = 'ER_CANT_DROP_FIELD_OR_KEY';\nexports[1092] = 'ER_INSERT_INFO';\nexports[1093] = 'ER_UPDATE_TABLE_USED';\nexports[1094] = 'ER_NO_SUCH_THREAD';\nexports[1095] = 'ER_KILL_DENIED_ERROR';\nexports[1096] = 'ER_NO_TABLES_USED';\nexports[1097] = 'ER_TOO_BIG_SET';\nexports[1098] = 'ER_NO_UNIQUE_LOGFILE';\nexports[1099] = 'ER_TABLE_NOT_LOCKED_FOR_WRITE';\nexports[1100] = 'ER_TABLE_NOT_LOCKED';\nexports[1101] = 'ER_BLOB_CANT_HAVE_DEFAULT';\nexports[1102] = 'ER_WRONG_DB_NAME';\nexports[1103] = 'ER_WRONG_TABLE_NAME';\nexports[1104] = 'ER_TOO_BIG_SELECT';\nexports[1105] = 'ER_UNKNOWN_ERROR';\nexports[1106] = 'ER_UNKNOWN_PROCEDURE';\nexports[1107] = 'ER_WRONG_PARAMCOUNT_TO_PROCEDURE';\nexports[1108] = 'ER_WRONG_PARAMETERS_TO_PROCEDURE';\nexports[1109] = 'ER_UNKNOWN_TABLE';\nexports[1110] = 'ER_FIELD_SPECIFIED_TWICE';\nexports[1111] = 'ER_INVALID_GROUP_FUNC_USE';\nexports[1112] = 'ER_UNSUPPORTED_EXTENSION';\nexports[1113] = 'ER_TABLE_MUST_HAVE_COLUMNS';\nexports[1114] = 'ER_RECORD_FILE_FULL';\nexports[1115] = 'ER_UNKNOWN_CHARACTER_SET';\nexports[1116] = 'ER_TOO_MANY_TABLES';\nexports[1117] = 'ER_TOO_MANY_FIELDS';\nexports[1118] = 'ER_TOO_BIG_ROWSIZE';\nexports[1119] = 'ER_STACK_OVERRUN';\nexports[1120] = 'ER_WRONG_OUTER_JOIN';\nexports[1121] = 'ER_NULL_COLUMN_IN_INDEX';\nexports[1122] = 'ER_CANT_FIND_UDF';\nexports[1123] = 'ER_CANT_INITIALIZE_UDF';\nexports[1124] = 'ER_UDF_NO_PATHS';\nexports[1125] = 'ER_UDF_EXISTS';\nexports[1126] = 'ER_CANT_OPEN_LIBRARY';\nexports[1127] = 'ER_CANT_FIND_DL_ENTRY';\nexports[1128] = 'ER_FUNCTION_NOT_DEFINED';\nexports[1129] = 'ER_HOST_IS_BLOCKED';\nexports[1130] = 'ER_HOST_NOT_PRIVILEGED';\nexports[1131] = 'ER_PASSWORD_ANONYMOUS_USER';\nexports[1132] = 'ER_PASSWORD_NOT_ALLOWED';\nexports[1133] = 'ER_PASSWORD_NO_MATCH';\nexports[1134] = 'ER_UPDATE_INFO';\nexports[1135] = 'ER_CANT_CREATE_THREAD';\nexports[1136] = 'ER_WRONG_VALUE_COUNT_ON_ROW';\nexports[1137] = 'ER_CANT_REOPEN_TABLE';\nexports[1138] = 'ER_INVALID_USE_OF_NULL';\nexports[1139] = 'ER_REGEXP_ERROR';\nexports[1140] = 'ER_MIX_OF_GROUP_FUNC_AND_FIELDS';\nexports[1141] = 'ER_NONEXISTING_GRANT';\nexports[1142] = 'ER_TABLEACCESS_DENIED_ERROR';\nexports[1143] = 'ER_COLUMNACCESS_DENIED_ERROR';\nexports[1144] = 'ER_ILLEGAL_GRANT_FOR_TABLE';\nexports[1145] = 'ER_GRANT_WRONG_HOST_OR_USER';\nexports[1146] = 'ER_NO_SUCH_TABLE';\nexports[1147] = 'ER_NONEXISTING_TABLE_GRANT';\nexports[1148] = 'ER_NOT_ALLOWED_COMMAND';\nexports[1149] = 'ER_SYNTAX_ERROR';\nexports[1150] = 'ER_DELAYED_CANT_CHANGE_LOCK';\nexports[1151] = 'ER_TOO_MANY_DELAYED_THREADS';\nexports[1152] = 'ER_ABORTING_CONNECTION';\nexports[1153] = 'ER_NET_PACKET_TOO_LARGE';\nexports[1154] = 'ER_NET_READ_ERROR_FROM_PIPE';\nexports[1155] = 'ER_NET_FCNTL_ERROR';\nexports[1156] = 'ER_NET_PACKETS_OUT_OF_ORDER';\nexports[1157] = 'ER_NET_UNCOMPRESS_ERROR';\nexports[1158] = 'ER_NET_READ_ERROR';\nexports[1159] = 'ER_NET_READ_INTERRUPTED';\nexports[1160] = 'ER_NET_ERROR_ON_WRITE';\nexports[1161] = 'ER_NET_WRITE_INTERRUPTED';\nexports[1162] = 'ER_TOO_LONG_STRING';\nexports[1163] = 'ER_TABLE_CANT_HANDLE_BLOB';\nexports[1164] = 'ER_TABLE_CANT_HANDLE_AUTO_INCREMENT';\nexports[1165] = 'ER_DELAYED_INSERT_TABLE_LOCKED';\nexports[1166] = 'ER_WRONG_COLUMN_NAME';\nexports[1167] = 'ER_WRONG_KEY_COLUMN';\nexports[1168] = 'ER_WRONG_MRG_TABLE';\nexports[1169] = 'ER_DUP_UNIQUE';\nexports[1170] = 'ER_BLOB_KEY_WITHOUT_LENGTH';\nexports[1171] = 'ER_PRIMARY_CANT_HAVE_NULL';\nexports[1172] = 'ER_TOO_MANY_ROWS';\nexports[1173] = 'ER_REQUIRES_PRIMARY_KEY';\nexports[1174] = 'ER_NO_RAID_COMPILED';\nexports[1175] = 'ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE';\nexports[1176] = 'ER_KEY_DOES_NOT_EXITS';\nexports[1177] = 'ER_CHECK_NO_SUCH_TABLE';\nexports[1178] = 'ER_CHECK_NOT_IMPLEMENTED';\nexports[1179] = 'ER_CANT_DO_THIS_DURING_AN_TRANSACTION';\nexports[1180] = 'ER_ERROR_DURING_COMMIT';\nexports[1181] = 'ER_ERROR_DURING_ROLLBACK';\nexports[1182] = 'ER_ERROR_DURING_FLUSH_LOGS';\nexports[1183] = 'ER_ERROR_DURING_CHECKPOINT';\nexports[1184] = 'ER_NEW_ABORTING_CONNECTION';\nexports[1185] = 'ER_DUMP_NOT_IMPLEMENTED';\nexports[1186] = 'ER_FLUSH_SOURCE_BINLOG_CLOSED';\nexports[1187] = 'ER_INDEX_REBUILD';\nexports[1188] = 'ER_SOURCE';\nexports[1189] = 'ER_SOURCE_NET_READ';\nexports[1190] = 'ER_SOURCE_NET_WRITE';\nexports[1191] = 'ER_FT_MATCHING_KEY_NOT_FOUND';\nexports[1192] = 'ER_LOCK_OR_ACTIVE_TRANSACTION';\nexports[1193] = 'ER_UNKNOWN_SYSTEM_VARIABLE';\nexports[1194] = 'ER_CRASHED_ON_USAGE';\nexports[1195] = 'ER_CRASHED_ON_REPAIR';\nexports[1196] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK';\nexports[1197] = 'ER_TRANS_CACHE_FULL';\nexports[1198] = 'ER_REPLICA_MUST_STOP';\nexports[1199] = 'ER_REPLICA_NOT_RUNNING';\nexports[1200] = 'ER_BAD_REPLICA';\nexports[1201] = 'ER_SOURCE_INFO';\nexports[1202] = 'ER_REPLICA_THREAD';\nexports[1203] = 'ER_TOO_MANY_USER_CONNECTIONS';\nexports[1204] = 'ER_SET_CONSTANTS_ONLY';\nexports[1205] = 'ER_LOCK_WAIT_TIMEOUT';\nexports[1206] = 'ER_LOCK_TABLE_FULL';\nexports[1207] = 'ER_READ_ONLY_TRANSACTION';\nexports[1208] = 'ER_DROP_DB_WITH_READ_LOCK';\nexports[1209] = 'ER_CREATE_DB_WITH_READ_LOCK';\nexports[1210] = 'ER_WRONG_ARGUMENTS';\nexports[1211] = 'ER_NO_PERMISSION_TO_CREATE_USER';\nexports[1212] = 'ER_UNION_TABLES_IN_DIFFERENT_DIR';\nexports[1213] = 'ER_LOCK_DEADLOCK';\nexports[1214] = 'ER_TABLE_CANT_HANDLE_FT';\nexports[1215] = 'ER_CANNOT_ADD_FOREIGN';\nexports[1216] = 'ER_NO_REFERENCED_ROW';\nexports[1217] = 'ER_ROW_IS_REFERENCED';\nexports[1218] = 'ER_CONNECT_TO_SOURCE';\nexports[1219] = 'ER_QUERY_ON_SOURCE';\nexports[1220] = 'ER_ERROR_WHEN_EXECUTING_COMMAND';\nexports[1221] = 'ER_WRONG_USAGE';\nexports[1222] = 'ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT';\nexports[1223] = 'ER_CANT_UPDATE_WITH_READLOCK';\nexports[1224] = 'ER_MIXING_NOT_ALLOWED';\nexports[1225] = 'ER_DUP_ARGUMENT';\nexports[1226] = 'ER_USER_LIMIT_REACHED';\nexports[1227] = 'ER_SPECIFIC_ACCESS_DENIED_ERROR';\nexports[1228] = 'ER_LOCAL_VARIABLE';\nexports[1229] = 'ER_GLOBAL_VARIABLE';\nexports[1230] = 'ER_NO_DEFAULT';\nexports[1231] = 'ER_WRONG_VALUE_FOR_VAR';\nexports[1232] = 'ER_WRONG_TYPE_FOR_VAR';\nexports[1233] = 'ER_VAR_CANT_BE_READ';\nexports[1234] = 'ER_CANT_USE_OPTION_HERE';\nexports[1235] = 'ER_NOT_SUPPORTED_YET';\nexports[1236] = 'ER_SOURCE_FATAL_ERROR_READING_BINLOG';\nexports[1237] = 'ER_REPLICA_IGNORED_TABLE';\nexports[1238] = 'ER_INCORRECT_GLOBAL_LOCAL_VAR';\nexports[1239] = 'ER_WRONG_FK_DEF';\nexports[1240] = 'ER_KEY_REF_DO_NOT_MATCH_TABLE_REF';\nexports[1241] = 'ER_OPERAND_COLUMNS';\nexports[1242] = 'ER_SUBQUERY_NO_1_ROW';\nexports[1243] = 'ER_UNKNOWN_STMT_HANDLER';\nexports[1244] = 'ER_CORRUPT_HELP_DB';\nexports[1245] = 'ER_CYCLIC_REFERENCE';\nexports[1246] = 'ER_AUTO_CONVERT';\nexports[1247] = 'ER_ILLEGAL_REFERENCE';\nexports[1248] = 'ER_DERIVED_MUST_HAVE_ALIAS';\nexports[1249] = 'ER_SELECT_REDUCED';\nexports[1250] = 'ER_TABLENAME_NOT_ALLOWED_HERE';\nexports[1251] = 'ER_NOT_SUPPORTED_AUTH_MODE';\nexports[1252] = 'ER_SPATIAL_CANT_HAVE_NULL';\nexports[1253] = 'ER_COLLATION_CHARSET_MISMATCH';\nexports[1254] = 'ER_REPLICA_WAS_RUNNING';\nexports[1255] = 'ER_REPLICA_WAS_NOT_RUNNING';\nexports[1256] = 'ER_TOO_BIG_FOR_UNCOMPRESS';\nexports[1257] = 'ER_ZLIB_Z_MEM_ERROR';\nexports[1258] = 'ER_ZLIB_Z_BUF_ERROR';\nexports[1259] = 'ER_ZLIB_Z_DATA_ERROR';\nexports[1260] = 'ER_CUT_VALUE_GROUP_CONCAT';\nexports[1261] = 'ER_WARN_TOO_FEW_RECORDS';\nexports[1262] = 'ER_WARN_TOO_MANY_RECORDS';\nexports[1263] = 'ER_WARN_NULL_TO_NOTNULL';\nexports[1264] = 'ER_WARN_DATA_OUT_OF_RANGE';\nexports[1265] = 'ER_WARN_DATA_TRUNCATED';\nexports[1266] = 'ER_WARN_USING_OTHER_HANDLER';\nexports[1267] = 'ER_CANT_AGGREGATE_2COLLATIONS';\nexports[1268] = 'ER_DROP_USER';\nexports[1269] = 'ER_REVOKE_GRANTS';\nexports[1270] = 'ER_CANT_AGGREGATE_3COLLATIONS';\nexports[1271] = 'ER_CANT_AGGREGATE_NCOLLATIONS';\nexports[1272] = 'ER_VARIABLE_IS_NOT_STRUCT';\nexports[1273] = 'ER_UNKNOWN_COLLATION';\nexports[1274] = 'ER_REPLICA_IGNORED_SSL_PARAMS';\nexports[1275] = 'ER_SERVER_IS_IN_SECURE_AUTH_MODE';\nexports[1276] = 'ER_WARN_FIELD_RESOLVED';\nexports[1277] = 'ER_BAD_REPLICA_UNTIL_COND';\nexports[1278] = 'ER_MISSING_SKIP_REPLICA';\nexports[1279] = 'ER_UNTIL_COND_IGNORED';\nexports[1280] = 'ER_WRONG_NAME_FOR_INDEX';\nexports[1281] = 'ER_WRONG_NAME_FOR_CATALOG';\nexports[1282] = 'ER_WARN_QC_RESIZE';\nexports[1283] = 'ER_BAD_FT_COLUMN';\nexports[1284] = 'ER_UNKNOWN_KEY_CACHE';\nexports[1285] = 'ER_WARN_HOSTNAME_WONT_WORK';\nexports[1286] = 'ER_UNKNOWN_STORAGE_ENGINE';\nexports[1287] = 'ER_WARN_DEPRECATED_SYNTAX';\nexports[1288] = 'ER_NON_UPDATABLE_TABLE';\nexports[1289] = 'ER_FEATURE_DISABLED';\nexports[1290] = 'ER_OPTION_PREVENTS_STATEMENT';\nexports[1291] = 'ER_DUPLICATED_VALUE_IN_TYPE';\nexports[1292] = 'ER_TRUNCATED_WRONG_VALUE';\nexports[1293] = 'ER_TOO_MUCH_AUTO_TIMESTAMP_COLS';\nexports[1294] = 'ER_INVALID_ON_UPDATE';\nexports[1295] = 'ER_UNSUPPORTED_PS';\nexports[1296] = 'ER_GET_ERRMSG';\nexports[1297] = 'ER_GET_TEMPORARY_ERRMSG';\nexports[1298] = 'ER_UNKNOWN_TIME_ZONE';\nexports[1299] = 'ER_WARN_INVALID_TIMESTAMP';\nexports[1300] = 'ER_INVALID_CHARACTER_STRING';\nexports[1301] = 'ER_WARN_ALLOWED_PACKET_OVERFLOWED';\nexports[1302] = 'ER_CONFLICTING_DECLARATIONS';\nexports[1303] = 'ER_SP_NO_RECURSIVE_CREATE';\nexports[1304] = 'ER_SP_ALREADY_EXISTS';\nexports[1305] = 'ER_SP_DOES_NOT_EXIST';\nexports[1306] = 'ER_SP_DROP_FAILED';\nexports[1307] = 'ER_SP_STORE_FAILED';\nexports[1308] = 'ER_SP_LILABEL_MISMATCH';\nexports[1309] = 'ER_SP_LABEL_REDEFINE';\nexports[1310] = 'ER_SP_LABEL_MISMATCH';\nexports[1311] = 'ER_SP_UNINIT_VAR';\nexports[1312] = 'ER_SP_BADSELECT';\nexports[1313] = 'ER_SP_BADRETURN';\nexports[1314] = 'ER_SP_BADSTATEMENT';\nexports[1315] = 'ER_UPDATE_LOG_DEPRECATED_IGNORED';\nexports[1316] = 'ER_UPDATE_LOG_DEPRECATED_TRANSLATED';\nexports[1317] = 'ER_QUERY_INTERRUPTED';\nexports[1318] = 'ER_SP_WRONG_NO_OF_ARGS';\nexports[1319] = 'ER_SP_COND_MISMATCH';\nexports[1320] = 'ER_SP_NORETURN';\nexports[1321] = 'ER_SP_NORETURNEND';\nexports[1322] = 'ER_SP_BAD_CURSOR_QUERY';\nexports[1323] = 'ER_SP_BAD_CURSOR_SELECT';\nexports[1324] = 'ER_SP_CURSOR_MISMATCH';\nexports[1325] = 'ER_SP_CURSOR_ALREADY_OPEN';\nexports[1326] = 'ER_SP_CURSOR_NOT_OPEN';\nexports[1327] = 'ER_SP_UNDECLARED_VAR';\nexports[1328] = 'ER_SP_WRONG_NO_OF_FETCH_ARGS';\nexports[1329] = 'ER_SP_FETCH_NO_DATA';\nexports[1330] = 'ER_SP_DUP_PARAM';\nexports[1331] = 'ER_SP_DUP_VAR';\nexports[1332] = 'ER_SP_DUP_COND';\nexports[1333] = 'ER_SP_DUP_CURS';\nexports[1334] = 'ER_SP_CANT_ALTER';\nexports[1335] = 'ER_SP_SUBSELECT_NYI';\nexports[1336] = 'ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG';\nexports[1337] = 'ER_SP_VARCOND_AFTER_CURSHNDLR';\nexports[1338] = 'ER_SP_CURSOR_AFTER_HANDLER';\nexports[1339] = 'ER_SP_CASE_NOT_FOUND';\nexports[1340] = 'ER_FPARSER_TOO_BIG_FILE';\nexports[1341] = 'ER_FPARSER_BAD_HEADER';\nexports[1342] = 'ER_FPARSER_EOF_IN_COMMENT';\nexports[1343] = 'ER_FPARSER_ERROR_IN_PARAMETER';\nexports[1344] = 'ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER';\nexports[1345] = 'ER_VIEW_NO_EXPLAIN';\nexports[1346] = 'ER_FRM_UNKNOWN_TYPE';\nexports[1347] = 'ER_WRONG_OBJECT';\nexports[1348] = 'ER_NONUPDATEABLE_COLUMN';\nexports[1349] = 'ER_VIEW_SELECT_DERIVED';\nexports[1350] = 'ER_VIEW_SELECT_CLAUSE';\nexports[1351] = 'ER_VIEW_SELECT_VARIABLE';\nexports[1352] = 'ER_VIEW_SELECT_TMPTABLE';\nexports[1353] = 'ER_VIEW_WRONG_LIST';\nexports[1354] = 'ER_WARN_VIEW_MERGE';\nexports[1355] = 'ER_WARN_VIEW_WITHOUT_KEY';\nexports[1356] = 'ER_VIEW_INVALID';\nexports[1357] = 'ER_SP_NO_DROP_SP';\nexports[1358] = 'ER_SP_GOTO_IN_HNDLR';\nexports[1359] = 'ER_TRG_ALREADY_EXISTS';\nexports[1360] = 'ER_TRG_DOES_NOT_EXIST';\nexports[1361] = 'ER_TRG_ON_VIEW_OR_TEMP_TABLE';\nexports[1362] = 'ER_TRG_CANT_CHANGE_ROW';\nexports[1363] = 'ER_TRG_NO_SUCH_ROW_IN_TRG';\nexports[1364] = 'ER_NO_DEFAULT_FOR_FIELD';\nexports[1365] = 'ER_DIVISION_BY_ZERO';\nexports[1366] = 'ER_TRUNCATED_WRONG_VALUE_FOR_FIELD';\nexports[1367] = 'ER_ILLEGAL_VALUE_FOR_TYPE';\nexports[1368] = 'ER_VIEW_NONUPD_CHECK';\nexports[1369] = 'ER_VIEW_CHECK_FAILED';\nexports[1370] = 'ER_PROCACCESS_DENIED_ERROR';\nexports[1371] = 'ER_RELAY_LOG_FAIL';\nexports[1372] = 'ER_PASSWD_LENGTH';\nexports[1373] = 'ER_UNKNOWN_TARGET_BINLOG';\nexports[1374] = 'ER_IO_ERR_LOG_INDEX_READ';\nexports[1375] = 'ER_BINLOG_PURGE_PROHIBITED';\nexports[1376] = 'ER_FSEEK_FAIL';\nexports[1377] = 'ER_BINLOG_PURGE_FATAL_ERR';\nexports[1378] = 'ER_LOG_IN_USE';\nexports[1379] = 'ER_LOG_PURGE_UNKNOWN_ERR';\nexports[1380] = 'ER_RELAY_LOG_INIT';\nexports[1381] = 'ER_NO_BINARY_LOGGING';\nexports[1382] = 'ER_RESERVED_SYNTAX';\nexports[1383] = 'ER_WSAS_FAILED';\nexports[1384] = 'ER_DIFF_GROUPS_PROC';\nexports[1385] = 'ER_NO_GROUP_FOR_PROC';\nexports[1386] = 'ER_ORDER_WITH_PROC';\nexports[1387] = 'ER_LOGGING_PROHIBIT_CHANGING_OF';\nexports[1388] = 'ER_NO_FILE_MAPPING';\nexports[1389] = 'ER_WRONG_MAGIC';\nexports[1390] = 'ER_PS_MANY_PARAM';\nexports[1391] = 'ER_KEY_PART_0';\nexports[1392] = 'ER_VIEW_CHECKSUM';\nexports[1393] = 'ER_VIEW_MULTIUPDATE';\nexports[1394] = 'ER_VIEW_NO_INSERT_FIELD_LIST';\nexports[1395] = 'ER_VIEW_DELETE_MERGE_VIEW';\nexports[1396] = 'ER_CANNOT_USER';\nexports[1397] = 'ER_XAER_NOTA';\nexports[1398] = 'ER_XAER_INVAL';\nexports[1399] = 'ER_XAER_RMFAIL';\nexports[1400] = 'ER_XAER_OUTSIDE';\nexports[1401] = 'ER_XA_RMERR';\nexports[1402] = 'ER_XA_RBROLLBACK';\nexports[1403] = 'ER_NONEXISTING_PROC_GRANT';\nexports[1404] = 'ER_PROC_AUTO_GRANT_FAIL';\nexports[1405] = 'ER_PROC_AUTO_REVOKE_FAIL';\nexports[1406] = 'ER_DATA_TOO_LONG';\nexports[1407] = 'ER_SP_BAD_SQLSTATE';\nexports[1408] = 'ER_STARTUP';\nexports[1409] = 'ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR';\nexports[1410] = 'ER_CANT_CREATE_USER_WITH_GRANT';\nexports[1411] = 'ER_WRONG_VALUE_FOR_TYPE';\nexports[1412] = 'ER_TABLE_DEF_CHANGED';\nexports[1413] = 'ER_SP_DUP_HANDLER';\nexports[1414] = 'ER_SP_NOT_VAR_ARG';\nexports[1415] = 'ER_SP_NO_RETSET';\nexports[1416] = 'ER_CANT_CREATE_GEOMETRY_OBJECT';\nexports[1417] = 'ER_FAILED_ROUTINE_BREAK_BINLOG';\nexports[1418] = 'ER_BINLOG_UNSAFE_ROUTINE';\nexports[1419] = 'ER_BINLOG_CREATE_ROUTINE_NEED_SUPER';\nexports[1420] = 'ER_EXEC_STMT_WITH_OPEN_CURSOR';\nexports[1421] = 'ER_STMT_HAS_NO_OPEN_CURSOR';\nexports[1422] = 'ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG';\nexports[1423] = 'ER_NO_DEFAULT_FOR_VIEW_FIELD';\nexports[1424] = 'ER_SP_NO_RECURSION';\nexports[1425] = 'ER_TOO_BIG_SCALE';\nexports[1426] = 'ER_TOO_BIG_PRECISION';\nexports[1427] = 'ER_M_BIGGER_THAN_D';\nexports[1428] = 'ER_WRONG_LOCK_OF_SYSTEM_TABLE';\nexports[1429] = 'ER_CONNECT_TO_FOREIGN_DATA_SOURCE';\nexports[1430] = 'ER_QUERY_ON_FOREIGN_DATA_SOURCE';\nexports[1431] = 'ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST';\nexports[1432] = 'ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE';\nexports[1433] = 'ER_FOREIGN_DATA_STRING_INVALID';\nexports[1434] = 'ER_CANT_CREATE_FEDERATED_TABLE';\nexports[1435] = 'ER_TRG_IN_WRONG_SCHEMA';\nexports[1436] = 'ER_STACK_OVERRUN_NEED_MORE';\nexports[1437] = 'ER_TOO_LONG_BODY';\nexports[1438] = 'ER_WARN_CANT_DROP_DEFAULT_KEYCACHE';\nexports[1439] = 'ER_TOO_BIG_DISPLAYWIDTH';\nexports[1440] = 'ER_XAER_DUPID';\nexports[1441] = 'ER_DATETIME_FUNCTION_OVERFLOW';\nexports[1442] = 'ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG';\nexports[1443] = 'ER_VIEW_PREVENT_UPDATE';\nexports[1444] = 'ER_PS_NO_RECURSION';\nexports[1445] = 'ER_SP_CANT_SET_AUTOCOMMIT';\nexports[1446] = 'ER_MALFORMED_DEFINER';\nexports[1447] = 'ER_VIEW_FRM_NO_USER';\nexports[1448] = 'ER_VIEW_OTHER_USER';\nexports[1449] = 'ER_NO_SUCH_USER';\nexports[1450] = 'ER_FORBID_SCHEMA_CHANGE';\nexports[1451] = 'ER_ROW_IS_REFERENCED_2';\nexports[1452] = 'ER_NO_REFERENCED_ROW_2';\nexports[1453] = 'ER_SP_BAD_VAR_SHADOW';\nexports[1454] = 'ER_TRG_NO_DEFINER';\nexports[1455] = 'ER_OLD_FILE_FORMAT';\nexports[1456] = 'ER_SP_RECURSION_LIMIT';\nexports[1457] = 'ER_SP_PROC_TABLE_CORRUPT';\nexports[1458] = 'ER_SP_WRONG_NAME';\nexports[1459] = 'ER_TABLE_NEEDS_UPGRADE';\nexports[1460] = 'ER_SP_NO_AGGREGATE';\nexports[1461] = 'ER_MAX_PREPARED_STMT_COUNT_REACHED';\nexports[1462] = 'ER_VIEW_RECURSIVE';\nexports[1463] = 'ER_NON_GROUPING_FIELD_USED';\nexports[1464] = 'ER_TABLE_CANT_HANDLE_SPKEYS';\nexports[1465] = 'ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA';\nexports[1466] = 'ER_REMOVED_SPACES';\nexports[1467] = 'ER_AUTOINC_READ_FAILED';\nexports[1468] = 'ER_USERNAME';\nexports[1469] = 'ER_HOSTNAME';\nexports[1470] = 'ER_WRONG_STRING_LENGTH';\nexports[1471] = 'ER_NON_INSERTABLE_TABLE';\nexports[1472] = 'ER_ADMIN_WRONG_MRG_TABLE';\nexports[1473] = 'ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT';\nexports[1474] = 'ER_NAME_BECOMES_EMPTY';\nexports[1475] = 'ER_AMBIGUOUS_FIELD_TERM';\nexports[1476] = 'ER_FOREIGN_SERVER_EXISTS';\nexports[1477] = 'ER_FOREIGN_SERVER_DOESNT_EXIST';\nexports[1478] = 'ER_ILLEGAL_HA_CREATE_OPTION';\nexports[1479] = 'ER_PARTITION_REQUIRES_VALUES_ERROR';\nexports[1480] = 'ER_PARTITION_WRONG_VALUES_ERROR';\nexports[1481] = 'ER_PARTITION_MAXVALUE_ERROR';\nexports[1482] = 'ER_PARTITION_SUBPARTITION_ERROR';\nexports[1483] = 'ER_PARTITION_SUBPART_MIX_ERROR';\nexports[1484] = 'ER_PARTITION_WRONG_NO_PART_ERROR';\nexports[1485] = 'ER_PARTITION_WRONG_NO_SUBPART_ERROR';\nexports[1486] = 'ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR';\nexports[1487] = 'ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR';\nexports[1488] = 'ER_FIELD_NOT_FOUND_PART_ERROR';\nexports[1489] = 'ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR';\nexports[1490] = 'ER_INCONSISTENT_PARTITION_INFO_ERROR';\nexports[1491] = 'ER_PARTITION_FUNC_NOT_ALLOWED_ERROR';\nexports[1492] = 'ER_PARTITIONS_MUST_BE_DEFINED_ERROR';\nexports[1493] = 'ER_RANGE_NOT_INCREASING_ERROR';\nexports[1494] = 'ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR';\nexports[1495] = 'ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR';\nexports[1496] = 'ER_PARTITION_ENTRY_ERROR';\nexports[1497] = 'ER_MIX_HANDLER_ERROR';\nexports[1498] = 'ER_PARTITION_NOT_DEFINED_ERROR';\nexports[1499] = 'ER_TOO_MANY_PARTITIONS_ERROR';\nexports[1500] = 'ER_SUBPARTITION_ERROR';\nexports[1501] = 'ER_CANT_CREATE_HANDLER_FILE';\nexports[1502] = 'ER_BLOB_FIELD_IN_PART_FUNC_ERROR';\nexports[1503] = 'ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF';\nexports[1504] = 'ER_NO_PARTS_ERROR';\nexports[1505] = 'ER_PARTITION_MGMT_ON_NONPARTITIONED';\nexports[1506] = 'ER_FOREIGN_KEY_ON_PARTITIONED';\nexports[1507] = 'ER_DROP_PARTITION_NON_EXISTENT';\nexports[1508] = 'ER_DROP_LAST_PARTITION';\nexports[1509] = 'ER_COALESCE_ONLY_ON_HASH_PARTITION';\nexports[1510] = 'ER_REORG_HASH_ONLY_ON_SAME_NO';\nexports[1511] = 'ER_REORG_NO_PARAM_ERROR';\nexports[1512] = 'ER_ONLY_ON_RANGE_LIST_PARTITION';\nexports[1513] = 'ER_ADD_PARTITION_SUBPART_ERROR';\nexports[1514] = 'ER_ADD_PARTITION_NO_NEW_PARTITION';\nexports[1515] = 'ER_COALESCE_PARTITION_NO_PARTITION';\nexports[1516] = 'ER_REORG_PARTITION_NOT_EXIST';\nexports[1517] = 'ER_SAME_NAME_PARTITION';\nexports[1518] = 'ER_NO_BINLOG_ERROR';\nexports[1519] = 'ER_CONSECUTIVE_REORG_PARTITIONS';\nexports[1520] = 'ER_REORG_OUTSIDE_RANGE';\nexports[1521] = 'ER_PARTITION_FUNCTION_FAILURE';\nexports[1522] = 'ER_PART_STATE_ERROR';\nexports[1523] = 'ER_LIMITED_PART_RANGE';\nexports[1524] = 'ER_PLUGIN_IS_NOT_LOADED';\nexports[1525] = 'ER_WRONG_VALUE';\nexports[1526] = 'ER_NO_PARTITION_FOR_GIVEN_VALUE';\nexports[1527] = 'ER_FILEGROUP_OPTION_ONLY_ONCE';\nexports[1528] = 'ER_CREATE_FILEGROUP_FAILED';\nexports[1529] = 'ER_DROP_FILEGROUP_FAILED';\nexports[1530] = 'ER_TABLESPACE_AUTO_EXTEND_ERROR';\nexports[1531] = 'ER_WRONG_SIZE_NUMBER';\nexports[1532] = 'ER_SIZE_OVERFLOW_ERROR';\nexports[1533] = 'ER_ALTER_FILEGROUP_FAILED';\nexports[1534] = 'ER_BINLOG_ROW_LOGGING_FAILED';\nexports[1535] = 'ER_BINLOG_ROW_WRONG_TABLE_DEF';\nexports[1536] = 'ER_BINLOG_ROW_RBR_TO_SBR';\nexports[1537] = 'ER_EVENT_ALREADY_EXISTS';\nexports[1538] = 'ER_EVENT_STORE_FAILED';\nexports[1539] = 'ER_EVENT_DOES_NOT_EXIST';\nexports[1540] = 'ER_EVENT_CANT_ALTER';\nexports[1541] = 'ER_EVENT_DROP_FAILED';\nexports[1542] = 'ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG';\nexports[1543] = 'ER_EVENT_ENDS_BEFORE_STARTS';\nexports[1544] = 'ER_EVENT_EXEC_TIME_IN_THE_PAST';\nexports[1545] = 'ER_EVENT_OPEN_TABLE_FAILED';\nexports[1546] = 'ER_EVENT_NEITHER_M_EXPR_NOR_M_AT';\nexports[1547] = 'ER_COL_COUNT_DOESNT_MATCH_CORRUPTED';\nexports[1548] = 'ER_CANNOT_LOAD_FROM_TABLE';\nexports[1549] = 'ER_EVENT_CANNOT_DELETE';\nexports[1550] = 'ER_EVENT_COMPILE_ERROR';\nexports[1551] = 'ER_EVENT_SAME_NAME';\nexports[1552] = 'ER_EVENT_DATA_TOO_LONG';\nexports[1553] = 'ER_DROP_INDEX_FK';\nexports[1554] = 'ER_WARN_DEPRECATED_SYNTAX_WITH_VER';\nexports[1555] = 'ER_CANT_WRITE_LOCK_LOG_TABLE';\nexports[1556] = 'ER_CANT_LOCK_LOG_TABLE';\nexports[1557] = 'ER_FOREIGN_DUPLICATE_KEY';\nexports[1558] = 'ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE';\nexports[1559] = 'ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR';\nexports[1560] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT';\nexports[1561] = 'ER_NDB_CANT_SWITCH_BINLOG_FORMAT';\nexports[1562] = 'ER_PARTITION_NO_TEMPORARY';\nexports[1563] = 'ER_PARTITION_CONST_DOMAIN_ERROR';\nexports[1564] = 'ER_PARTITION_FUNCTION_IS_NOT_ALLOWED';\nexports[1565] = 'ER_DDL_LOG_ERROR';\nexports[1566] = 'ER_NULL_IN_VALUES_LESS_THAN';\nexports[1567] = 'ER_WRONG_PARTITION_NAME';\nexports[1568] = 'ER_CANT_CHANGE_TX_ISOLATION';\nexports[1569] = 'ER_DUP_ENTRY_AUTOINCREMENT_CASE';\nexports[1570] = 'ER_EVENT_MODIFY_QUEUE_ERROR';\nexports[1571] = 'ER_EVENT_SET_VAR_ERROR';\nexports[1572] = 'ER_PARTITION_MERGE_ERROR';\nexports[1573] = 'ER_CANT_ACTIVATE_LOG';\nexports[1574] = 'ER_RBR_NOT_AVAILABLE';\nexports[1575] = 'ER_BASE64_DECODE_ERROR';\nexports[1576] = 'ER_EVENT_RECURSION_FORBIDDEN';\nexports[1577] = 'ER_EVENTS_DB_ERROR';\nexports[1578] = 'ER_ONLY_INTEGERS_ALLOWED';\nexports[1579] = 'ER_UNSUPORTED_LOG_ENGINE';\nexports[1580] = 'ER_BAD_LOG_STATEMENT';\nexports[1581] = 'ER_CANT_RENAME_LOG_TABLE';\nexports[1582] = 'ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT';\nexports[1583] = 'ER_WRONG_PARAMETERS_TO_NATIVE_FCT';\nexports[1584] = 'ER_WRONG_PARAMETERS_TO_STORED_FCT';\nexports[1585] = 'ER_NATIVE_FCT_NAME_COLLISION';\nexports[1586] = 'ER_DUP_ENTRY_WITH_KEY_NAME';\nexports[1587] = 'ER_BINLOG_PURGE_EMFILE';\nexports[1588] = 'ER_EVENT_CANNOT_CREATE_IN_THE_PAST';\nexports[1589] = 'ER_EVENT_CANNOT_ALTER_IN_THE_PAST';\nexports[1590] = 'ER_REPLICA_INCIDENT';\nexports[1591] = 'ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT';\nexports[1592] = 'ER_BINLOG_UNSAFE_STATEMENT';\nexports[1593] = 'ER_REPLICA_FATAL_ERROR';\nexports[1594] = 'ER_REPLICA_RELAY_LOG_READ_FAILURE';\nexports[1595] = 'ER_REPLICA_RELAY_LOG_WRITE_FAILURE';\nexports[1596] = 'ER_REPLICA_CREATE_EVENT_FAILURE';\nexports[1597] = 'ER_REPLICA_SOURCE_COM_FAILURE';\nexports[1598] = 'ER_BINLOG_LOGGING_IMPOSSIBLE';\nexports[1599] = 'ER_VIEW_NO_CREATION_CTX';\nexports[1600] = 'ER_VIEW_INVALID_CREATION_CTX';\nexports[1601] = 'ER_SR_INVALID_CREATION_CTX';\nexports[1602] = 'ER_TRG_CORRUPTED_FILE';\nexports[1603] = 'ER_TRG_NO_CREATION_CTX';\nexports[1604] = 'ER_TRG_INVALID_CREATION_CTX';\nexports[1605] = 'ER_EVENT_INVALID_CREATION_CTX';\nexports[1606] = 'ER_TRG_CANT_OPEN_TABLE';\nexports[1607] = 'ER_CANT_CREATE_SROUTINE';\nexports[1608] = 'ER_NEVER_USED';\nexports[1609] = 'ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT';\nexports[1610] = 'ER_REPLICA_CORRUPT_EVENT';\nexports[1611] = 'ER_LOAD_DATA_INVALID_COLUMN';\nexports[1612] = 'ER_LOG_PURGE_NO_FILE';\nexports[1613] = 'ER_XA_RBTIMEOUT';\nexports[1614] = 'ER_XA_RBDEADLOCK';\nexports[1615] = 'ER_NEED_REPREPARE';\nexports[1616] = 'ER_DELAYED_NOT_SUPPORTED';\nexports[1617] = 'WARN_NO_SOURCE_INFO';\nexports[1618] = 'WARN_OPTION_IGNORED';\nexports[1619] = 'WARN_PLUGIN_DELETE_BUILTIN';\nexports[1620] = 'WARN_PLUGIN_BUSY';\nexports[1621] = 'ER_VARIABLE_IS_READONLY';\nexports[1622] = 'ER_WARN_ENGINE_TRANSACTION_ROLLBACK';\nexports[1623] = 'ER_REPLICA_HEARTBEAT_FAILURE';\nexports[1624] = 'ER_REPLICA_HEARTBEAT_VALUE_OUT_OF_RANGE';\nexports[1625] = 'ER_NDB_REPLICATION_SCHEMA_ERROR';\nexports[1626] = 'ER_CONFLICT_FN_PARSE_ERROR';\nexports[1627] = 'ER_EXCEPTIONS_WRITE_ERROR';\nexports[1628] = 'ER_TOO_LONG_TABLE_COMMENT';\nexports[1629] = 'ER_TOO_LONG_FIELD_COMMENT';\nexports[1630] = 'ER_FUNC_INEXISTENT_NAME_COLLISION';\nexports[1631] = 'ER_DATABASE_NAME';\nexports[1632] = 'ER_TABLE_NAME';\nexports[1633] = 'ER_PARTITION_NAME';\nexports[1634] = 'ER_SUBPARTITION_NAME';\nexports[1635] = 'ER_TEMPORARY_NAME';\nexports[1636] = 'ER_RENAMED_NAME';\nexports[1637] = 'ER_TOO_MANY_CONCURRENT_TRXS';\nexports[1638] = 'WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED';\nexports[1639] = 'ER_DEBUG_SYNC_TIMEOUT';\nexports[1640] = 'ER_DEBUG_SYNC_HIT_LIMIT';\nexports[1641] = 'ER_DUP_SIGNAL_SET';\nexports[1642] = 'ER_SIGNAL_WARN';\nexports[1643] = 'ER_SIGNAL_NOT_FOUND';\nexports[1644] = 'ER_SIGNAL_EXCEPTION';\nexports[1645] = 'ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER';\nexports[1646] = 'ER_SIGNAL_BAD_CONDITION_TYPE';\nexports[1647] = 'WARN_COND_ITEM_TRUNCATED';\nexports[1648] = 'ER_COND_ITEM_TOO_LONG';\nexports[1649] = 'ER_UNKNOWN_LOCALE';\nexports[1650] = 'ER_REPLICA_IGNORE_SERVER_IDS';\nexports[1651] = 'ER_QUERY_CACHE_DISABLED';\nexports[1652] = 'ER_SAME_NAME_PARTITION_FIELD';\nexports[1653] = 'ER_PARTITION_COLUMN_LIST_ERROR';\nexports[1654] = 'ER_WRONG_TYPE_COLUMN_VALUE_ERROR';\nexports[1655] = 'ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR';\nexports[1656] = 'ER_MAXVALUE_IN_VALUES_IN';\nexports[1657] = 'ER_TOO_MANY_VALUES_ERROR';\nexports[1658] = 'ER_ROW_SINGLE_PARTITION_FIELD_ERROR';\nexports[1659] = 'ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD';\nexports[1660] = 'ER_PARTITION_FIELDS_TOO_LONG';\nexports[1661] = 'ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE';\nexports[1662] = 'ER_BINLOG_ROW_MODE_AND_STMT_ENGINE';\nexports[1663] = 'ER_BINLOG_UNSAFE_AND_STMT_ENGINE';\nexports[1664] = 'ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE';\nexports[1665] = 'ER_BINLOG_STMT_MODE_AND_ROW_ENGINE';\nexports[1666] = 'ER_BINLOG_ROW_INJECTION_AND_STMT_MODE';\nexports[1667] = 'ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE';\nexports[1668] = 'ER_BINLOG_UNSAFE_LIMIT';\nexports[1669] = 'ER_BINLOG_UNSAFE_INSERT_DELAYED';\nexports[1670] = 'ER_BINLOG_UNSAFE_SYSTEM_TABLE';\nexports[1671] = 'ER_BINLOG_UNSAFE_AUTOINC_COLUMNS';\nexports[1672] = 'ER_BINLOG_UNSAFE_UDF';\nexports[1673] = 'ER_BINLOG_UNSAFE_SYSTEM_VARIABLE';\nexports[1674] = 'ER_BINLOG_UNSAFE_SYSTEM_FUNCTION';\nexports[1675] = 'ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS';\nexports[1676] = 'ER_MESSAGE_AND_STATEMENT';\nexports[1677] = 'ER_REPLICA_CONVERSION_FAILED';\nexports[1678] = 'ER_REPLICA_CANT_CREATE_CONVERSION';\nexports[1679] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT';\nexports[1680] = 'ER_PATH_LENGTH';\nexports[1681] = 'ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT';\nexports[1682] = 'ER_WRONG_NATIVE_TABLE_STRUCTURE';\nexports[1683] = 'ER_WRONG_PERFSCHEMA_USAGE';\nexports[1684] = 'ER_WARN_I_S_SKIPPED_TABLE';\nexports[1685] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT';\nexports[1686] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT';\nexports[1687] = 'ER_SPATIAL_MUST_HAVE_GEOM_COL';\nexports[1688] = 'ER_TOO_LONG_INDEX_COMMENT';\nexports[1689] = 'ER_LOCK_ABORTED';\nexports[1690] = 'ER_DATA_OUT_OF_RANGE';\nexports[1691] = 'ER_WRONG_SPVAR_TYPE_IN_LIMIT';\nexports[1692] = 'ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE';\nexports[1693] = 'ER_BINLOG_UNSAFE_MIXED_STATEMENT';\nexports[1694] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN';\nexports[1695] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN';\nexports[1696] = 'ER_FAILED_READ_FROM_PAR_FILE';\nexports[1697] = 'ER_VALUES_IS_NOT_INT_TYPE_ERROR';\nexports[1698] = 'ER_ACCESS_DENIED_NO_PASSWORD_ERROR';\nexports[1699] = 'ER_SET_PASSWORD_AUTH_PLUGIN';\nexports[1700] = 'ER_GRANT_PLUGIN_USER_EXISTS';\nexports[1701] = 'ER_TRUNCATE_ILLEGAL_FK';\nexports[1702] = 'ER_PLUGIN_IS_PERMANENT';\nexports[1703] = 'ER_REPLICA_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN';\nexports[1704] = 'ER_REPLICA_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX';\nexports[1705] = 'ER_STMT_CACHE_FULL';\nexports[1706] = 'ER_MULTI_UPDATE_KEY_CONFLICT';\nexports[1707] = 'ER_TABLE_NEEDS_REBUILD';\nexports[1708] = 'WARN_OPTION_BELOW_LIMIT';\nexports[1709] = 'ER_INDEX_COLUMN_TOO_LONG';\nexports[1710] = 'ER_ERROR_IN_TRIGGER_BODY';\nexports[1711] = 'ER_ERROR_IN_UNKNOWN_TRIGGER_BODY';\nexports[1712] = 'ER_INDEX_CORRUPT';\nexports[1713] = 'ER_UNDO_RECORD_TOO_BIG';\nexports[1714] = 'ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT';\nexports[1715] = 'ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE';\nexports[1716] = 'ER_BINLOG_UNSAFE_REPLACE_SELECT';\nexports[1717] = 'ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT';\nexports[1718] = 'ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT';\nexports[1719] = 'ER_BINLOG_UNSAFE_UPDATE_IGNORE';\nexports[1720] = 'ER_PLUGIN_NO_UNINSTALL';\nexports[1721] = 'ER_PLUGIN_NO_INSTALL';\nexports[1722] = 'ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT';\nexports[1723] = 'ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC';\nexports[1724] = 'ER_BINLOG_UNSAFE_INSERT_TWO_KEYS';\nexports[1725] = 'ER_TABLE_IN_FK_CHECK';\nexports[1726] = 'ER_UNSUPPORTED_ENGINE';\nexports[1727] = 'ER_BINLOG_UNSAFE_AUTOINC_NOT_FIRST';\nexports[1728] = 'ER_CANNOT_LOAD_FROM_TABLE_V2';\nexports[1729] = 'ER_SOURCE_DELAY_VALUE_OUT_OF_RANGE';\nexports[1730] = 'ER_ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT';\nexports[1731] = 'ER_PARTITION_EXCHANGE_DIFFERENT_OPTION';\nexports[1732] = 'ER_PARTITION_EXCHANGE_PART_TABLE';\nexports[1733] = 'ER_PARTITION_EXCHANGE_TEMP_TABLE';\nexports[1734] = 'ER_PARTITION_INSTEAD_OF_SUBPARTITION';\nexports[1735] = 'ER_UNKNOWN_PARTITION';\nexports[1736] = 'ER_TABLES_DIFFERENT_METADATA';\nexports[1737] = 'ER_ROW_DOES_NOT_MATCH_PARTITION';\nexports[1738] = 'ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX';\nexports[1739] = 'ER_WARN_INDEX_NOT_APPLICABLE';\nexports[1740] = 'ER_PARTITION_EXCHANGE_FOREIGN_KEY';\nexports[1741] = 'ER_NO_SUCH_KEY_VALUE';\nexports[1742] = 'ER_RPL_INFO_DATA_TOO_LONG';\nexports[1743] = 'ER_NETWORK_READ_EVENT_CHECKSUM_FAILURE';\nexports[1744] = 'ER_BINLOG_READ_EVENT_CHECKSUM_FAILURE';\nexports[1745] = 'ER_BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX';\nexports[1746] = 'ER_CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT';\nexports[1747] = 'ER_PARTITION_CLAUSE_ON_NONPARTITIONED';\nexports[1748] = 'ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET';\nexports[1749] = 'ER_NO_SUCH_PARTITION';\nexports[1750] = 'ER_CHANGE_RPL_INFO_REPOSITORY_FAILURE';\nexports[1751] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE';\nexports[1752] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE';\nexports[1753] = 'ER_MTS_FEATURE_IS_NOT_SUPPORTED';\nexports[1754] = 'ER_MTS_UPDATED_DBS_GREATER_MAX';\nexports[1755] = 'ER_MTS_CANT_PARALLEL';\nexports[1756] = 'ER_MTS_INCONSISTENT_DATA';\nexports[1757] = 'ER_FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING';\nexports[1758] = 'ER_DA_INVALID_CONDITION_NUMBER';\nexports[1759] = 'ER_INSECURE_PLAIN_TEXT';\nexports[1760] = 'ER_INSECURE_CHANGE_SOURCE';\nexports[1761] = 'ER_FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO';\nexports[1762] = 'ER_FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO';\nexports[1763] = 'ER_SQLTHREAD_WITH_SECURE_REPLICA';\nexports[1764] = 'ER_TABLE_HAS_NO_FT';\nexports[1765] = 'ER_VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER';\nexports[1766] = 'ER_VARIABLE_NOT_SETTABLE_IN_TRANSACTION';\nexports[1767] = 'ER_GTID_NEXT_IS_NOT_IN_GTID_NEXT_LIST';\nexports[1768] = 'ER_CANT_CHANGE_GTID_NEXT_IN_TRANSACTION_WHEN_GTID_NEXT_LIST_IS_NULL';\nexports[1769] = 'ER_SET_STATEMENT_CANNOT_INVOKE_FUNCTION';\nexports[1770] = 'ER_GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL';\nexports[1771] = 'ER_SKIPPING_LOGGED_TRANSACTION';\nexports[1772] = 'ER_MALFORMED_GTID_SET_SPECIFICATION';\nexports[1773] = 'ER_MALFORMED_GTID_SET_ENCODING';\nexports[1774] = 'ER_MALFORMED_GTID_SPECIFICATION';\nexports[1775] = 'ER_GNO_EXHAUSTED';\nexports[1776] = 'ER_BAD_REPLICA_AUTO_POSITION';\nexports[1777] = 'ER_AUTO_POSITION_REQUIRES_GTID_MODE_ON';\nexports[1778] = 'ER_CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET';\nexports[1779] = 'ER_GTID_MODE_2_OR_3_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON';\nexports[1780] = 'ER_GTID_MODE_REQUIRES_BINLOG';\nexports[1781] = 'ER_CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF';\nexports[1782] = 'ER_CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON';\nexports[1783] = 'ER_CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF';\nexports[1784] = 'ER_FOUND_GTID_EVENT_WHEN_GTID_MODE_IS_OFF';\nexports[1785] = 'ER_GTID_UNSAFE_NON_TRANSACTIONAL_TABLE';\nexports[1786] = 'ER_GTID_UNSAFE_CREATE_SELECT';\nexports[1787] = 'ER_GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION';\nexports[1788] = 'ER_GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME';\nexports[1789] = 'ER_SOURCE_HAS_PURGED_REQUIRED_GTIDS';\nexports[1790] = 'ER_CANT_SET_GTID_NEXT_WHEN_OWNING_GTID';\nexports[1791] = 'ER_UNKNOWN_EXPLAIN_FORMAT';\nexports[1792] = 'ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION';\nexports[1793] = 'ER_TOO_LONG_TABLE_PARTITION_COMMENT';\nexports[1794] = 'ER_REPLICA_CONFIGURATION';\nexports[1795] = 'ER_INNODB_FT_LIMIT';\nexports[1796] = 'ER_INNODB_NO_FT_TEMP_TABLE';\nexports[1797] = 'ER_INNODB_FT_WRONG_DOCID_COLUMN';\nexports[1798] = 'ER_INNODB_FT_WRONG_DOCID_INDEX';\nexports[1799] = 'ER_INNODB_ONLINE_LOG_TOO_BIG';\nexports[1800] = 'ER_UNKNOWN_ALTER_ALGORITHM';\nexports[1801] = 'ER_UNKNOWN_ALTER_LOCK';\nexports[1802] = 'ER_MTS_CHANGE_SOURCE_CANT_RUN_WITH_GAPS';\nexports[1803] = 'ER_MTS_RECOVERY_FAILURE';\nexports[1804] = 'ER_MTS_RESET_WORKERS';\nexports[1805] = 'ER_COL_COUNT_DOESNT_MATCH_CORRUPTED_V2';\nexports[1806] = 'ER_REPLICA_SILENT_RETRY_TRANSACTION';\nexports[1807] = 'ER_DISCARD_FK_CHECKS_RUNNING';\nexports[1808] = 'ER_TABLE_SCHEMA_MISMATCH';\nexports[1809] = 'ER_TABLE_IN_SYSTEM_TABLESPACE';\nexports[1810] = 'ER_IO_READ_ERROR';\nexports[1811] = 'ER_IO_WRITE_ERROR';\nexports[1812] = 'ER_TABLESPACE_MISSING';\nexports[1813] = 'ER_TABLESPACE_EXISTS';\nexports[1814] = 'ER_TABLESPACE_DISCARDED';\nexports[1815] = 'ER_INTERNAL_ERROR';\nexports[1816] = 'ER_INNODB_IMPORT_ERROR';\nexports[1817] = 'ER_INNODB_INDEX_CORRUPT';\nexports[1818] = 'ER_INVALID_YEAR_COLUMN_LENGTH';\nexports[1819] = 'ER_NOT_VALID_PASSWORD';\nexports[1820] = 'ER_MUST_CHANGE_PASSWORD';\nexports[1821] = 'ER_FK_NO_INDEX_CHILD';\nexports[1822] = 'ER_FK_NO_INDEX_PARENT';\nexports[1823] = 'ER_FK_FAIL_ADD_SYSTEM';\nexports[1824] = 'ER_FK_CANNOT_OPEN_PARENT';\nexports[1825] = 'ER_FK_INCORRECT_OPTION';\nexports[1826] = 'ER_FK_DUP_NAME';\nexports[1827] = 'ER_PASSWORD_FORMAT';\nexports[1828] = 'ER_FK_COLUMN_CANNOT_DROP';\nexports[1829] = 'ER_FK_COLUMN_CANNOT_DROP_CHILD';\nexports[1830] = 'ER_FK_COLUMN_NOT_NULL';\nexports[1831] = 'ER_DUP_INDEX';\nexports[1832] = 'ER_FK_COLUMN_CANNOT_CHANGE';\nexports[1833] = 'ER_FK_COLUMN_CANNOT_CHANGE_CHILD';\nexports[1834] = 'ER_FK_CANNOT_DELETE_PARENT';\nexports[1835] = 'ER_MALFORMED_PACKET';\nexports[1836] = 'ER_READ_ONLY_MODE';\nexports[1837] = 'ER_GTID_NEXT_TYPE_UNDEFINED_GROUP';\nexports[1838] = 'ER_VARIABLE_NOT_SETTABLE_IN_SP';\nexports[1839] = 'ER_CANT_SET_GTID_PURGED_WHEN_GTID_MODE_IS_OFF';\nexports[1840] = 'ER_CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY';\nexports[1841] = 'ER_CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY';\nexports[1842] = 'ER_GTID_PURGED_WAS_CHANGED';\nexports[1843] = 'ER_GTID_EXECUTED_WAS_CHANGED';\nexports[1844] = 'ER_BINLOG_STMT_MODE_AND_NO_REPL_TABLES';\nexports[1845] = 'ER_ALTER_OPERATION_NOT_SUPPORTED';\nexports[1846] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON';\nexports[1847] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY';\nexports[1848] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION';\nexports[1849] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME';\nexports[1850] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE';\nexports[1851] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK';\nexports[1852] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_IGNORE';\nexports[1853] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK';\nexports[1854] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC';\nexports[1855] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS';\nexports[1856] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS';\nexports[1857] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS';\nexports[1858] = 'ER_SQL_REPLICA_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE';\nexports[1859] = 'ER_DUP_UNKNOWN_IN_INDEX';\nexports[1860] = 'ER_IDENT_CAUSES_TOO_LONG_PATH';\nexports[1861] = 'ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL';\nexports[1862] = 'ER_MUST_CHANGE_PASSWORD_LOGIN';\nexports[1863] = 'ER_ROW_IN_WRONG_PARTITION';\nexports[1864] = 'ER_MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX';\nexports[1865] = 'ER_INNODB_NO_FT_USES_PARSER';\nexports[1866] = 'ER_BINLOG_LOGICAL_CORRUPTION';\nexports[1867] = 'ER_WARN_PURGE_LOG_IN_USE';\nexports[1868] = 'ER_WARN_PURGE_LOG_IS_ACTIVE';\nexports[1869] = 'ER_AUTO_INCREMENT_CONFLICT';\nexports[1870] = 'WARN_ON_BLOCKHOLE_IN_RBR';\nexports[1871] = 'ER_REPLICA_MI_INIT_REPOSITORY';\nexports[1872] = 'ER_REPLICA_RLI_INIT_REPOSITORY';\nexports[1873] = 'ER_ACCESS_DENIED_CHANGE_USER_ERROR';\nexports[1874] = 'ER_INNODB_READ_ONLY';\nexports[1875] = 'ER_STOP_REPLICA_SQL_THREAD_TIMEOUT';\nexports[1876] = 'ER_STOP_REPLICA_IO_THREAD_TIMEOUT';\nexports[1877] = 'ER_TABLE_CORRUPT';\nexports[1878] = 'ER_TEMP_FILE_WRITE_FAILURE';\nexports[1879] = 'ER_INNODB_FT_AUX_NOT_HEX_ID';\nexports[1880] = 'ER_OLD_TEMPORALS_UPGRADED';\nexports[1881] = 'ER_INNODB_FORCED_RECOVERY';\nexports[1882] = 'ER_AES_INVALID_IV';\nexports[1883] = 'ER_FILE_CORRUPT';\nexports[1884] = 'ER_ERROR_ON_SOURCE';\nexports[1885] = 'ER_INCONSISTENT_ERROR';\nexports[1886] = 'ER_STORAGE_ENGINE_NOT_LOADED';\nexports[1887] = 'ER_GET_STACKED_DA_WITHOUT_ACTIVE_HANDLER';\nexports[1888] = 'ER_WARN_LEGACY_SYNTAX_CONVERTED';\nexports[1889] = 'ER_BINLOG_UNSAFE_FULLTEXT_PLUGIN';\nexports[1890] = 'ER_CANNOT_DISCARD_TEMPORARY_TABLE';\nexports[1891] = 'ER_FK_DEPTH_EXCEEDED';\nexports[1892] = 'ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE_V2';\nexports[1893] = 'ER_WARN_TRIGGER_DOESNT_HAVE_CREATED';\nexports[1894] = 'ER_REFERENCED_TRG_DOES_NOT_EXIST';\nexports[1895] = 'ER_EXPLAIN_NOT_SUPPORTED';\nexports[1896] = 'ER_INVALID_FIELD_SIZE';\nexports[1897] = 'ER_MISSING_HA_CREATE_OPTION';\nexports[1898] = 'ER_ENGINE_OUT_OF_MEMORY';\nexports[1899] = 'ER_PASSWORD_EXPIRE_ANONYMOUS_USER';\nexports[1900] = 'ER_REPLICA_SQL_THREAD_MUST_STOP';\nexports[1901] = 'ER_NO_FT_MATERIALIZED_SUBQUERY';\nexports[1902] = 'ER_INNODB_UNDO_LOG_FULL';\nexports[1903] = 'ER_INVALID_ARGUMENT_FOR_LOGARITHM';\nexports[1904] = 'ER_REPLICA_IO_THREAD_MUST_STOP';\nexports[1905] = 'ER_WARN_OPEN_TEMP_TABLES_MUST_BE_ZERO';\nexports[1906] = 'ER_WARN_ONLY_SOURCE_LOG_FILE_NO_POS';\nexports[1907] = 'ER_QUERY_TIMEOUT';\nexports[1908] = 'ER_NON_RO_SELECT_DISABLE_TIMER';\nexports[1909] = 'ER_DUP_LIST_ENTRY';\nexports[1910] = 'ER_SQL_MODE_NO_EFFECT';\nexports[3169] = 'ER_SESSION_WAS_KILLED';\nexports[4031] = 'ER_CLIENT_INTERACTION_TIMEOUT';\n","module.exports = require(\"string_decoder\");","'use strict';\n\n// Manually extracted from mysql-5.5.23/include/mysql_com.h\n\n/**\n Is raised when a multi-statement transaction\n has been started, either explicitly, by means\n of BEGIN or COMMIT AND CHAIN, or\n implicitly, by the first transactional\n statement, when autocommit=off.\n*/\nexports.SERVER_STATUS_IN_TRANS = 1;\nexports.SERVER_STATUS_AUTOCOMMIT = 2; /* Server in auto_commit mode */\nexports.SERVER_MORE_RESULTS_EXISTS = 8; /* Multi query - next query exists */\nexports.SERVER_QUERY_NO_GOOD_INDEX_USED = 16;\nexports.SERVER_QUERY_NO_INDEX_USED = 32;\n/**\n The server was able to fulfill the clients request and opened a\n read-only non-scrollable cursor for a query. This flag comes\n in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands.\n*/\nexports.SERVER_STATUS_CURSOR_EXISTS = 64;\n/**\n This flag is sent when a read-only cursor is exhausted, in reply to\n COM_STMT_FETCH command.\n*/\nexports.SERVER_STATUS_LAST_ROW_SENT = 128;\nexports.SERVER_STATUS_DB_DROPPED = 256; /* A database was dropped */\nexports.SERVER_STATUS_NO_BACKSLASH_ESCAPES = 512;\n/**\n Sent to the client if after a prepared statement reprepare\n we discovered that the new statement returns a different\n number of result set columns.\n*/\nexports.SERVER_STATUS_METADATA_CHANGED = 1024;\nexports.SERVER_QUERY_WAS_SLOW = 2048;\n\n/**\n To mark ResultSet containing output parameter values.\n*/\nexports.SERVER_PS_OUT_PARAMS = 4096;\n\nexports.SERVER_STATUS_IN_TRANS_READONLY = 0x2000; // in a read-only transaction\nexports.SERVER_SESSION_STATE_CHANGED = 0x4000;\n","// This file was modified by Oracle on June 17, 2021.\n// Handshake errors are now maked as fatal and the corresponding events are\n// emitted in the command instance itself.\n// Modifications copyright (c) 2021, Oracle and/or its affiliates.\n\n'use strict';\n\nconst Command = require('./command.js');\nconst Packets = require('../packets/index.js');\nconst ClientConstants = require('../constants/client.js');\nconst CharsetToEncoding = require('../constants/charset_encodings.js');\nconst auth41 = require('../auth_41.js');\n\nfunction flagNames(flags) {\n const res = [];\n for (const c in ClientConstants) {\n if (flags & ClientConstants[c]) {\n res.push(c.replace(/_/g, ' ').toLowerCase());\n }\n }\n return res;\n}\n\nclass ClientHandshake extends Command {\n constructor(clientFlags) {\n super();\n this.handshake = null;\n this.clientFlags = clientFlags;\n }\n\n start() {\n return ClientHandshake.prototype.handshakeInit;\n }\n\n sendSSLRequest(connection) {\n const sslRequest = new Packets.SSLRequest(\n this.clientFlags,\n connection.config.charsetNumber\n );\n connection.writePacket(sslRequest.toPacket());\n }\n\n sendCredentials(connection) {\n if (connection.config.debug) {\n // eslint-disable-next-line\n console.log(\n 'Sending handshake packet: flags:%d=(%s)',\n this.clientFlags,\n flagNames(this.clientFlags).join(', ')\n );\n }\n this.user = connection.config.user;\n this.password = connection.config.password;\n this.passwordSha1 = connection.config.passwordSha1;\n this.database = connection.config.database;\n this.autPluginName = this.handshake.autPluginName;\n const handshakeResponse = new Packets.HandshakeResponse({\n flags: this.clientFlags,\n user: this.user,\n database: this.database,\n password: this.password,\n passwordSha1: this.passwordSha1,\n charsetNumber: connection.config.charsetNumber,\n authPluginData1: this.handshake.authPluginData1,\n authPluginData2: this.handshake.authPluginData2,\n compress: connection.config.compress,\n connectAttributes: connection.config.connectAttributes\n });\n connection.writePacket(handshakeResponse.toPacket());\n }\n\n calculateNativePasswordAuthToken(authPluginData) {\n // TODO: dont split into authPluginData1 and authPluginData2, instead join when 1 & 2 received\n const authPluginData1 = authPluginData.slice(0, 8);\n const authPluginData2 = authPluginData.slice(8, 20);\n let authToken;\n if (this.passwordSha1) {\n authToken = auth41.calculateTokenFromPasswordSha(\n this.passwordSha1,\n authPluginData1,\n authPluginData2\n );\n } else {\n authToken = auth41.calculateToken(\n this.password,\n authPluginData1,\n authPluginData2\n );\n }\n return authToken;\n }\n\n handshakeInit(helloPacket, connection) {\n this.on('error', e => {\n connection._fatalError = e;\n connection._protocolError = e;\n });\n this.handshake = Packets.Handshake.fromPacket(helloPacket);\n if (connection.config.debug) {\n // eslint-disable-next-line\n console.log(\n 'Server hello packet: capability flags:%d=(%s)',\n this.handshake.capabilityFlags,\n flagNames(this.handshake.capabilityFlags).join(', ')\n );\n }\n connection.serverCapabilityFlags = this.handshake.capabilityFlags;\n connection.serverEncoding = CharsetToEncoding[this.handshake.characterSet];\n connection.connectionId = this.handshake.connectionId;\n const serverSSLSupport =\n this.handshake.capabilityFlags & ClientConstants.SSL;\n // use compression only if requested by client and supported by server\n connection.config.compress =\n connection.config.compress &&\n this.handshake.capabilityFlags & ClientConstants.COMPRESS;\n this.clientFlags = this.clientFlags | connection.config.compress;\n if (connection.config.ssl) {\n // client requires SSL but server does not support it\n if (!serverSSLSupport) {\n const err = new Error('Server does not support secure connnection');\n err.code = 'HANDSHAKE_NO_SSL_SUPPORT';\n err.fatal = true;\n this.emit('error', err);\n return false;\n }\n // send ssl upgrade request and immediately upgrade connection to secure\n this.clientFlags |= ClientConstants.SSL;\n this.sendSSLRequest(connection);\n connection.startTLS(err => {\n // after connection is secure\n if (err) {\n // SSL negotiation error are fatal\n err.code = 'HANDSHAKE_SSL_ERROR';\n err.fatal = true;\n this.emit('error', err);\n return;\n }\n // rest of communication is encrypted\n this.sendCredentials(connection);\n });\n } else {\n this.sendCredentials(connection);\n }\n return ClientHandshake.prototype.handshakeResult;\n }\n\n handshakeResult(packet, connection) {\n const marker = packet.peekByte();\n if (marker === 0xfe || marker === 1) {\n const authSwitch = require('./auth_switch');\n try {\n if (marker === 1) {\n authSwitch.authSwitchRequestMoreData(packet, connection, this);\n } else {\n authSwitch.authSwitchRequest(packet, connection, this);\n }\n return ClientHandshake.prototype.handshakeResult;\n } catch (err) {\n // Authentication errors are fatal\n err.code = 'AUTH_SWITCH_PLUGIN_ERROR';\n err.fatal = true;\n\n if (this.onResult) {\n this.onResult(err);\n } else {\n this.emit('error', err);\n }\n return null;\n }\n }\n if (marker !== 0) {\n const err = new Error('Unexpected packet during handshake phase');\n // Unknown handshake errors are fatal\n err.code = 'HANDSHAKE_UNKNOWN_ERROR';\n err.fatal = true;\n\n if (this.onResult) {\n this.onResult(err);\n } else {\n this.emit('error', err);\n }\n return null;\n }\n // this should be called from ClientHandshake command only\n // and skipped when called from ChangeUser command\n if (!connection.authorized) {\n connection.authorized = true;\n if (connection.config.compress) {\n const enableCompression = require('../compressed_protocol.js')\n .enableCompression;\n enableCompression(connection);\n }\n }\n if (this.onResult) {\n this.onResult(null);\n }\n return null;\n }\n}\nmodule.exports = ClientHandshake;\n","'use strict';\n\nconst process = require('process');\nconst Timers = require('timers');\n\nconst Readable = require('stream').Readable;\n\nconst Command = require('./command.js');\nconst Packets = require('../packets/index.js');\nconst getTextParser = require('../parsers/text_parser.js');\nconst ServerStatus = require('../constants/server_status.js');\n\nconst EmptyPacket = new Packets.Packet(0, Buffer.allocUnsafe(4), 0, 4);\n\n// http://dev.mysql.com/doc/internals/en/com-query.html\nclass Query extends Command {\n constructor(options, callback) {\n super();\n this.sql = options.sql;\n this.values = options.values;\n this._queryOptions = options;\n this.namedPlaceholders = options.namedPlaceholders || false;\n this.onResult = callback;\n this.timeout = options.timeout;\n this.queryTimeout = null;\n this._fieldCount = 0;\n this._rowParser = null;\n this._fields = [];\n this._rows = [];\n this._receivedFieldsCount = 0;\n this._resultIndex = 0;\n this._localStream = null;\n this._unpipeStream = function() {};\n this._streamFactory = options.infileStreamFactory;\n this._connection = null;\n }\n\n then() {\n const err =\n \"You have tried to call .then(), .catch(), or invoked await on the result of query that is not a promise, which is a programming error. Try calling con.promise().query(), or require('mysql2/promise') instead of 'mysql2' for a promise-compatible version of the query interface. To learn how to use async/await or Promises check out documentation at https://www.npmjs.com/package/mysql2#using-promise-wrapper, or the mysql2 documentation at https://github.com/sidorares/node-mysql2/tree/master/documentation/Promise-Wrapper.md\";\n // eslint-disable-next-line\n console.log(err);\n throw new Error(err);\n }\n\n /* eslint no-unused-vars: [\"error\", { \"argsIgnorePattern\": \"^_\" }] */\n start(_packet, connection) {\n if (connection.config.debug) {\n // eslint-disable-next-line\n console.log(' Sending query command: %s', this.sql);\n }\n this._connection = connection;\n this.options = Object.assign({}, connection.config, this._queryOptions);\n this._setTimeout();\n\n const cmdPacket = new Packets.Query(\n this.sql,\n connection.config.charsetNumber\n );\n connection.writePacket(cmdPacket.toPacket(1));\n return Query.prototype.resultsetHeader;\n }\n\n done() {\n this._unpipeStream();\n // if all ready timeout, return null directly\n if (this.timeout && !this.queryTimeout) {\n return null;\n }\n // else clear timer\n if (this.queryTimeout) {\n Timers.clearTimeout(this.queryTimeout);\n this.queryTimeout = null;\n }\n if (this.onResult) {\n let rows, fields;\n if (this._resultIndex === 0) {\n rows = this._rows[0];\n fields = this._fields[0];\n } else {\n rows = this._rows;\n fields = this._fields;\n }\n if (fields) {\n process.nextTick(() => {\n this.onResult(null, rows, fields);\n });\n } else {\n process.nextTick(() => {\n this.onResult(null, rows);\n });\n }\n }\n return null;\n }\n\n doneInsert(rs) {\n if (this._localStreamError) {\n if (this.onResult) {\n this.onResult(this._localStreamError, rs);\n } else {\n this.emit('error', this._localStreamError);\n }\n return null;\n }\n this._rows.push(rs);\n this._fields.push(void 0);\n this.emit('fields', void 0);\n this.emit('result', rs);\n if (rs.serverStatus & ServerStatus.SERVER_MORE_RESULTS_EXISTS) {\n this._resultIndex++;\n return this.resultsetHeader;\n }\n return this.done();\n }\n\n resultsetHeader(packet, connection) {\n const rs = new Packets.ResultSetHeader(packet, connection);\n this._fieldCount = rs.fieldCount;\n if (connection.config.debug) {\n // eslint-disable-next-line\n console.log(\n ` Resultset header received, expecting ${rs.fieldCount} column definition packets`\n );\n }\n if (this._fieldCount === 0) {\n return this.doneInsert(rs);\n }\n if (this._fieldCount === null) {\n return this._streamLocalInfile(connection, rs.infileName);\n }\n this._receivedFieldsCount = 0;\n this._rows.push([]);\n this._fields.push([]);\n return this.readField;\n }\n\n _streamLocalInfile(connection, path) {\n if (this._streamFactory) {\n this._localStream = this._streamFactory(path);\n } else {\n this._localStreamError = new Error(\n `As a result of LOCAL INFILE command server wants to read ${path} file, but as of v2.0 you must provide streamFactory option returning ReadStream.`\n );\n connection.writePacket(EmptyPacket);\n return this.infileOk;\n }\n\n const onConnectionError = () => {\n this._unpipeStream();\n };\n const onDrain = () => {\n this._localStream.resume();\n };\n const onPause = () => {\n this._localStream.pause();\n };\n const onData = function(data) {\n const dataWithHeader = Buffer.allocUnsafe(data.length + 4);\n data.copy(dataWithHeader, 4);\n connection.writePacket(\n new Packets.Packet(0, dataWithHeader, 0, dataWithHeader.length)\n );\n };\n const onEnd = () => {\n connection.removeListener('error', onConnectionError);\n connection.writePacket(EmptyPacket);\n };\n const onError = err => {\n this._localStreamError = err;\n connection.removeListener('error', onConnectionError);\n connection.writePacket(EmptyPacket);\n };\n this._unpipeStream = () => {\n connection.stream.removeListener('pause', onPause);\n connection.stream.removeListener('drain', onDrain);\n this._localStream.removeListener('data', onData);\n this._localStream.removeListener('end', onEnd);\n this._localStream.removeListener('error', onError);\n };\n connection.stream.on('pause', onPause);\n connection.stream.on('drain', onDrain);\n this._localStream.on('data', onData);\n this._localStream.on('end', onEnd);\n this._localStream.on('error', onError);\n connection.once('error', onConnectionError);\n return this.infileOk;\n }\n\n readField(packet, connection) {\n this._receivedFieldsCount++;\n // Often there is much more data in the column definition than in the row itself\n // If you set manually _fields[0] to array of ColumnDefinition's (from previous call)\n // you can 'cache' result of parsing. Field packets still received, but ignored in that case\n // this is the reason _receivedFieldsCount exist (otherwise we could just use current length of fields array)\n if (this._fields[this._resultIndex].length !== this._fieldCount) {\n const field = new Packets.ColumnDefinition(\n packet,\n connection.clientEncoding\n );\n this._fields[this._resultIndex].push(field);\n if (connection.config.debug) {\n /* eslint-disable no-console */\n console.log(' Column definition:');\n console.log(` name: ${field.name}`);\n console.log(` type: ${field.columnType}`);\n console.log(` flags: ${field.flags}`);\n /* eslint-enable no-console */\n }\n }\n // last field received\n if (this._receivedFieldsCount === this._fieldCount) {\n const fields = this._fields[this._resultIndex];\n this.emit('fields', fields);\n this._rowParser = new (getTextParser(fields, this.options, connection.config))(fields);\n return Query.prototype.fieldsEOF;\n }\n return Query.prototype.readField;\n }\n\n fieldsEOF(packet, connection) {\n // check EOF\n if (!packet.isEOF()) {\n return connection.protocolError('Expected EOF packet');\n }\n return this.row;\n }\n\n /* eslint no-unused-vars: [\"error\", { \"argsIgnorePattern\": \"^_\" }] */\n row(packet, _connection) { \n if (packet.isEOF()) {\n const status = packet.eofStatusFlags();\n const moreResults = status & ServerStatus.SERVER_MORE_RESULTS_EXISTS;\n if (moreResults) {\n this._resultIndex++;\n return Query.prototype.resultsetHeader;\n }\n return this.done();\n }\n let row;\n try {\n row = this._rowParser.next(\n packet,\n this._fields[this._resultIndex],\n this.options\n );\n } catch (err) {\n this._localStreamError = err;\n return this.doneInsert(null);\n }\n if (this.onResult) {\n this._rows[this._resultIndex].push(row);\n } else {\n this.emit('result', row);\n }\n return Query.prototype.row;\n }\n\n infileOk(packet, connection) {\n const rs = new Packets.ResultSetHeader(packet, connection);\n return this.doneInsert(rs);\n }\n\n stream(options) {\n options = options || {};\n options.objectMode = true;\n const stream = new Readable(options);\n stream._read = () => {\n this._connection && this._connection.resume();\n };\n this.on('result', row => {\n if (!stream.push(row)) {\n this._connection.pause();\n }\n stream.emit('result', row); // replicate old emitter\n });\n this.on('error', err => {\n stream.emit('error', err); // Pass on any errors\n });\n this.on('end', () => {\n stream.push(null); // pushing null, indicating EOF\n stream.emit('close'); // notify readers that query has completed\n });\n this.on('fields', fields => {\n stream.emit('fields', fields); // replicate old emitter\n });\n return stream;\n }\n\n _setTimeout() {\n if (this.timeout) {\n const timeoutHandler = this._handleTimeoutError.bind(this);\n this.queryTimeout = Timers.setTimeout(\n timeoutHandler,\n this.timeout\n );\n }\n }\n\n _handleTimeoutError() {\n if (this.queryTimeout) {\n Timers.clearTimeout(this.queryTimeout);\n this.queryTimeout = null;\n }\n \n const err = new Error('Query inactivity timeout');\n err.errorno = 'PROTOCOL_SEQUENCE_TIMEOUT';\n err.code = 'PROTOCOL_SEQUENCE_TIMEOUT';\n err.syscall = 'query';\n\n if (this.onResult) {\n this.onResult(err);\n } else {\n this.emit('error', err);\n }\n }\n}\n\nQuery.prototype.catch = Query.prototype.then;\n\nmodule.exports = Query;\n","'use strict';\n\n/*\n\n this seems to be not only shorter, but faster than\n string.replace(/\\\\/g, '\\\\\\\\').\n replace(/\\u0008/g, '\\\\b').\n replace(/\\t/g, '\\\\t').\n replace(/\\n/g, '\\\\n').\n replace(/\\f/g, '\\\\f').\n replace(/\\r/g, '\\\\r').\n replace(/'/g, '\\\\\\'').\n replace(/\"/g, '\\\\\"');\n or string.replace(/[\\-\\[\\]\\/\\{\\}\\(\\)\\*\\+\\?\\.\\\\\\^\\$\\|]/g, \"\\\\$&\")\n see http://jsperf.com/string-escape-regexp-vs-json-stringify\n */\nfunction srcEscape(str) {\n return JSON.stringify({\n [str]: 1\n }).slice(1, -3);\n}\n\nexports.srcEscape = srcEscape;\n\nlet highlightFn;\nlet cardinalRecommended = false;\ntry {\n highlightFn = require('cardinal').highlight;\n} catch (err) {\n highlightFn = text => {\n if (!cardinalRecommended) {\n // eslint-disable-next-line no-console\n console.log('For nicer debug output consider install cardinal@^2.0.0');\n cardinalRecommended = true;\n }\n return text;\n };\n}\n\n/**\n * Prints debug message with code frame, will try to use `cardinal` if available.\n */\nfunction printDebugWithCode(msg, code) {\n // eslint-disable-next-line no-console\n console.log(`\\n\\n${msg}:\\n`);\n // eslint-disable-next-line no-console\n console.log(`${highlightFn(code)}\\n`);\n}\n\nexports.printDebugWithCode = printDebugWithCode;\n\n/**\n * checks whether the `type` is in the `list`\n */\nfunction typeMatch(type, list, Types) {\n if (Array.isArray(list)) {\n return list.some(t => type === Types[t]);\n }\n\n return !!list;\n}\n\nexports.typeMatch = typeMatch;\n","var util = require('util')\nvar isProperty = require('is-property')\n\nvar INDENT_START = /[\\{\\[]/\nvar INDENT_END = /[\\}\\]]/\n\n// from https://mathiasbynens.be/notes/reserved-keywords\nvar RESERVED = [\n 'do',\n 'if',\n 'in',\n 'for',\n 'let',\n 'new',\n 'try',\n 'var',\n 'case',\n 'else',\n 'enum',\n 'eval',\n 'null',\n 'this',\n 'true',\n 'void',\n 'with',\n 'await',\n 'break',\n 'catch',\n 'class',\n 'const',\n 'false',\n 'super',\n 'throw',\n 'while',\n 'yield',\n 'delete',\n 'export',\n 'import',\n 'public',\n 'return',\n 'static',\n 'switch',\n 'typeof',\n 'default',\n 'extends',\n 'finally',\n 'package',\n 'private',\n 'continue',\n 'debugger',\n 'function',\n 'arguments',\n 'interface',\n 'protected',\n 'implements',\n 'instanceof',\n 'NaN',\n 'undefined'\n]\n\nvar RESERVED_MAP = {}\n\nfor (var i = 0; i < RESERVED.length; i++) {\n RESERVED_MAP[RESERVED[i]] = true\n}\n\nvar isVariable = function (name) {\n return isProperty(name) && !RESERVED_MAP.hasOwnProperty(name)\n}\n\nvar formats = {\n s: function(s) {\n return '' + s\n },\n d: function(d) {\n return '' + Number(d)\n },\n o: function(o) {\n return JSON.stringify(o)\n }\n}\n\nvar genfun = function() {\n var lines = []\n var indent = 0\n var vars = {}\n\n var push = function(str) {\n var spaces = ''\n while (spaces.length < indent*2) spaces += ' '\n lines.push(spaces+str)\n }\n\n var pushLine = function(line) {\n if (INDENT_END.test(line.trim()[0]) && INDENT_START.test(line[line.length-1])) {\n indent--\n push(line)\n indent++\n return\n }\n if (INDENT_START.test(line[line.length-1])) {\n push(line)\n indent++\n return\n }\n if (INDENT_END.test(line.trim()[0])) {\n indent--\n push(line)\n return\n }\n\n push(line)\n }\n\n var line = function(fmt) {\n if (!fmt) return line\n\n if (arguments.length === 1 && fmt.indexOf('\\n') > -1) {\n var lines = fmt.trim().split('\\n')\n for (var i = 0; i < lines.length; i++) {\n pushLine(lines[i].trim())\n }\n } else {\n pushLine(util.format.apply(util, arguments))\n }\n\n return line\n }\n\n line.scope = {}\n line.formats = formats\n\n line.sym = function(name) {\n if (!name || !isVariable(name)) name = 'tmp'\n if (!vars[name]) vars[name] = 0\n return name + (vars[name]++ || '')\n }\n\n line.property = function(obj, name) {\n if (arguments.length === 1) {\n name = obj\n obj = ''\n }\n\n name = name + ''\n\n if (isProperty(name)) return (obj ? obj + '.' + name : name)\n return obj ? obj + '[' + JSON.stringify(name) + ']' : JSON.stringify(name)\n }\n\n line.toString = function() {\n return lines.join('\\n')\n }\n\n line.toFunction = function(scope) {\n if (!scope) scope = {}\n\n var src = 'return ('+line.toString()+')'\n\n Object.keys(line.scope).forEach(function (key) {\n if (!scope[key]) scope[key] = line.scope[key]\n })\n\n var keys = Object.keys(scope).map(function(key) {\n return key\n })\n\n var vals = keys.map(function(key) {\n return scope[key]\n })\n\n return Function.apply(null, keys.concat(src)).apply(null, vals)\n }\n\n if (arguments.length) line.apply(null, arguments)\n\n return line\n}\n\ngenfun.formats = formats\nmodule.exports = genfun\n","'use strict';\n\nconst Command = require('./command');\nconst Packets = require('../packets/index.js');\n\nclass CloseStatement extends Command {\n constructor(id) {\n super();\n this.id = id;\n }\n\n start(packet, connection) {\n connection.writePacket(new Packets.CloseStatement(this.id).toPacket(1));\n return null;\n }\n}\n\nmodule.exports = CloseStatement;\n","'use strict';\n\nconst Command = require('./command.js');\nconst Query = require('./query.js');\nconst Packets = require('../packets/index.js');\n\nconst getBinaryParser = require('../parsers/binary_parser.js');\n\nclass Execute extends Command {\n constructor(options, callback) {\n super();\n this.statement = options.statement;\n this.sql = options.sql;\n this.values = options.values;\n this.onResult = callback;\n this.parameters = options.values;\n this.insertId = 0;\n this.timeout = options.timeout;\n this.queryTimeout = null;\n this._rows = [];\n this._fields = [];\n this._result = [];\n this._fieldCount = 0;\n this._rowParser = null;\n this._executeOptions = options;\n this._resultIndex = 0;\n this._localStream = null;\n this._unpipeStream = function() {};\n this._streamFactory = options.infileStreamFactory;\n this._connection = null;\n }\n\n buildParserFromFields(fields, connection) {\n return getBinaryParser(fields, this.options, connection.config);\n }\n\n start(packet, connection) {\n this._connection = connection;\n this.options = Object.assign({}, connection.config, this._executeOptions);\n this._setTimeout();\n const executePacket = new Packets.Execute(\n this.statement.id,\n this.parameters,\n connection.config.charsetNumber,\n connection.config.timezone\n );\n //For reasons why this try-catch is here, please see\n // https://github.com/sidorares/node-mysql2/pull/689\n //For additional discussion, see\n // 1. https://github.com/sidorares/node-mysql2/issues/493\n // 2. https://github.com/sidorares/node-mysql2/issues/187\n // 3. https://github.com/sidorares/node-mysql2/issues/480\n try {\n connection.writePacket(executePacket.toPacket(1));\n } catch (error) {\n this.onResult(error);\n }\n return Execute.prototype.resultsetHeader;\n }\n\n readField(packet, connection) {\n let fields;\n // disabling for now, but would be great to find reliable way to parse fields only once\n // fields reported by prepare can be empty at all or just incorrect - see #169\n //\n // perfomance optimisation: if we already have this field parsed in statement header, use one from header\n // const field = this.statement.columns.length == this._fieldCount ?\n // this.statement.columns[this._receivedFieldsCount] : new Packets.ColumnDefinition(packet);\n const field = new Packets.ColumnDefinition(\n packet,\n connection.clientEncoding\n );\n this._receivedFieldsCount++;\n this._fields[this._resultIndex].push(field);\n if (this._receivedFieldsCount === this._fieldCount) {\n fields = this._fields[this._resultIndex];\n this.emit('fields', fields, this._resultIndex);\n return Execute.prototype.fieldsEOF;\n }\n return Execute.prototype.readField;\n }\n\n fieldsEOF(packet, connection) {\n // check EOF\n if (!packet.isEOF()) {\n return connection.protocolError('Expected EOF packet');\n }\n this._rowParser = new (this.buildParserFromFields(\n this._fields[this._resultIndex],\n connection\n ))();\n return Execute.prototype.row;\n }\n}\n\nExecute.prototype.done = Query.prototype.done;\nExecute.prototype.doneInsert = Query.prototype.doneInsert;\nExecute.prototype.resultsetHeader = Query.prototype.resultsetHeader;\nExecute.prototype._findOrCreateReadStream =\n Query.prototype._findOrCreateReadStream;\nExecute.prototype._streamLocalInfile = Query.prototype._streamLocalInfile;\nExecute.prototype._setTimeout = Query.prototype._setTimeout;\nExecute.prototype._handleTimeoutError = Query.prototype._handleTimeoutError;\nExecute.prototype.row = Query.prototype.row;\nExecute.prototype.stream = Query.prototype.stream;\n\nmodule.exports = Execute;\n","'use strict';\n\nconst process = require('process');\nconst mysql = require('../index.js');\n\nconst EventEmitter = require('events').EventEmitter;\nconst PoolConnection = require('./pool_connection.js');\nconst Queue = require('denque');\nconst Connection = require('./connection.js');\n\nfunction spliceConnection(queue, connection) {\n const len = queue.length;\n for (let i = 0; i < len; i++) {\n if (queue.get(i) === connection) {\n queue.removeOne(i);\n break;\n }\n }\n}\n\nclass Pool extends EventEmitter {\n constructor(options) {\n super();\n this.config = options.config;\n this.config.connectionConfig.pool = this;\n this._allConnections = new Queue();\n this._freeConnections = new Queue();\n this._connectionQueue = new Queue();\n this._closed = false;\n }\n\n promise(promiseImpl) {\n const PromisePool = require('../promise').PromisePool;\n return new PromisePool(this, promiseImpl);\n }\n\n getConnection(cb) {\n if (this._closed) {\n return process.nextTick(() => cb(new Error('Pool is closed.')));\n }\n let connection;\n if (this._freeConnections.length > 0) {\n connection = this._freeConnections.shift();\n this.emit('acquire', connection);\n return process.nextTick(() => cb(null, connection));\n }\n if (\n this.config.connectionLimit === 0 ||\n this._allConnections.length < this.config.connectionLimit\n ) {\n connection = new PoolConnection(this, {\n config: this.config.connectionConfig\n });\n this._allConnections.push(connection);\n return connection.connect(err => {\n if (this._closed) {\n return cb(new Error('Pool is closed.'));\n }\n if (err) {\n return cb(err);\n }\n this.emit('connection', connection);\n this.emit('acquire', connection);\n return cb(null, connection);\n });\n }\n if (!this.config.waitForConnections) {\n return process.nextTick(() => cb(new Error('No connections available.')));\n }\n if (\n this.config.queueLimit &&\n this._connectionQueue.length >= this.config.queueLimit\n ) {\n return cb(new Error('Queue limit reached.'));\n }\n this.emit('enqueue');\n return this._connectionQueue.push(cb);\n }\n\n releaseConnection(connection) {\n let cb;\n if (!connection._pool) {\n // The connection has been removed from the pool and is no longer good.\n if (this._connectionQueue.length) {\n cb = this._connectionQueue.shift();\n process.nextTick(this.getConnection.bind(this, cb));\n }\n } else if (this._connectionQueue.length) {\n cb = this._connectionQueue.shift();\n process.nextTick(cb.bind(null, null, connection));\n } else {\n this._freeConnections.push(connection);\n this.emit('release', connection);\n }\n }\n\n end(cb) {\n this._closed = true;\n if (typeof cb !== 'function') {\n cb = function(err) {\n if (err) {\n throw err;\n }\n };\n }\n let calledBack = false;\n let closedConnections = 0;\n let connection;\n const endCB = function(err) {\n if (calledBack) {\n return;\n }\n if (err || ++closedConnections >= this._allConnections.length) {\n calledBack = true;\n cb(err);\n return;\n }\n }.bind(this);\n if (this._allConnections.length === 0) {\n endCB();\n return;\n }\n for (let i = 0; i < this._allConnections.length; i++) {\n connection = this._allConnections.get(i);\n connection._realEnd(endCB);\n }\n }\n\n query(sql, values, cb) {\n const cmdQuery = Connection.createQuery(\n sql,\n values,\n cb,\n this.config.connectionConfig\n );\n if (typeof cmdQuery.namedPlaceholders === 'undefined') {\n cmdQuery.namedPlaceholders = this.config.connectionConfig.namedPlaceholders;\n }\n this.getConnection((err, conn) => {\n if (err) {\n if (typeof cmdQuery.onResult === 'function') {\n cmdQuery.onResult(err);\n } else {\n cmdQuery.emit('error', err);\n }\n return;\n }\n try {\n conn.query(cmdQuery).once('end', () => {\n conn.release();\n });\n } catch (e) {\n conn.release();\n throw e;\n }\n });\n return cmdQuery;\n }\n\n execute(sql, values, cb) {\n // TODO construct execute command first here and pass it to connection.execute\n // so that polymorphic arguments logic is there in one place\n if (typeof values === 'function') {\n cb = values;\n values = [];\n }\n this.getConnection((err, conn) => {\n if (err) {\n return cb(err);\n }\n try {\n conn.execute(sql, values, cb).once('end', () => {\n conn.release();\n });\n } catch (e) {\n conn.release();\n throw e;\n }\n });\n }\n\n _removeConnection(connection) {\n // Remove connection from all connections\n spliceConnection(this._allConnections, connection);\n // Remove connection from free connections\n spliceConnection(this._freeConnections, connection);\n this.releaseConnection(connection);\n }\n\n format(sql, values) {\n return mysql.format(\n sql,\n values,\n this.config.connectionConfig.stringifyObjects,\n this.config.connectionConfig.timezone\n );\n }\n\n escape(value) {\n return mysql.escape(\n value,\n this.config.connectionConfig.stringifyObjects,\n this.config.connectionConfig.timezone\n );\n }\n\n escapeId(value) {\n return mysql.escapeId(value, false);\n }\n}\n\nmodule.exports = Pool;\n","'use strict';\n\nconst Connection = require('../index.js').Connection;\n\nclass PoolConnection extends Connection {\n constructor(pool, options) {\n super(options);\n this._pool = pool;\n // When a fatal error occurs the connection's protocol ends, which will cause\n // the connection to end as well, thus we only need to watch for the end event\n // and we will be notified of disconnects.\n // REVIEW: Moved to `once`\n this.once('end', () => {\n this._removeFromPool();\n });\n this.once('error', () => {\n this._removeFromPool();\n });\n }\n\n release() {\n if (!this._pool || this._pool._closed) {\n return;\n }\n this._pool.releaseConnection(this);\n }\n\n promise(promiseImpl) {\n const PromisePoolConnection = require('../promise').PromisePoolConnection;\n return new PromisePoolConnection(this, promiseImpl);\n }\n\n end() {\n const err = new Error(\n 'Calling conn.end() to release a pooled connection is ' +\n 'deprecated. In next version calling conn.end() will be ' +\n 'restored to default conn.end() behavior. Use ' +\n 'conn.release() instead.'\n );\n this.emit('warn', err);\n // eslint-disable-next-line no-console\n console.warn(err.message);\n this.release();\n }\n\n destroy() {\n this._removeFromPool();\n super.destroy();\n }\n\n _removeFromPool() {\n if (!this._pool || this._pool._closed) {\n return;\n }\n const pool = this._pool;\n this._pool = null;\n pool._removeConnection(this);\n }\n}\n\nPoolConnection.statementKey = Connection.statementKey;\nmodule.exports = PoolConnection;\n\n// TODO: Remove this when we are removing PoolConnection#end\nPoolConnection.prototype._realEnd = Connection.prototype.end;\n","'use strict';\n\nconst process = require('process');\n\nconst Pool = require('./pool.js');\nconst PoolConfig = require('./pool_config.js');\nconst Connection = require('./connection.js');\nconst EventEmitter = require('events').EventEmitter;\n\n/**\n * Selector\n */\nconst makeSelector = {\n RR() {\n let index = 0;\n return clusterIds => clusterIds[index++ % clusterIds.length];\n },\n RANDOM() {\n return clusterIds =>\n clusterIds[Math.floor(Math.random() * clusterIds.length)];\n },\n ORDER() {\n return clusterIds => clusterIds[0];\n }\n};\n\nclass PoolNamespace {\n constructor(cluster, pattern, selector) {\n this._cluster = cluster;\n this._pattern = pattern;\n this._selector = makeSelector[selector]();\n }\n\n getConnection(cb) {\n const clusterNode = this._getClusterNode();\n if (clusterNode === null) {\n return cb(new Error('Pool does Not exists.'));\n }\n return this._cluster._getConnection(clusterNode, (err, connection) => {\n if (err) {\n return cb(err);\n }\n if (connection === 'retry') {\n return this.getConnection(cb);\n }\n return cb(null, connection);\n });\n }\n\n /**\n * pool cluster query\n * @param {*} sql\n * @param {*} values\n * @param {*} cb\n * @returns query\n */\n query(sql, values, cb) {\n const query = Connection.createQuery(sql, values, cb, {});\n this.getConnection((err, conn) => {\n if (err) {\n if (typeof query.onResult === 'function') {\n query.onResult(err);\n } else {\n query.emit('error', err);\n }\n return;\n }\n try {\n conn.query(query).once('end', () => {\n conn.release();\n });\n } catch (e) {\n conn.release();\n throw e;\n }\n });\n return query;\n }\n\n /**\n * pool cluster execute\n * @param {*} sql \n * @param {*} values \n * @param {*} cb \n */\n execute(sql, values, cb) {\n if (typeof values === 'function') {\n cb = values;\n values = [];\n }\n this.getConnection((err, conn) => {\n if (err) {\n return cb(err);\n }\n try {\n conn.execute(sql, values, cb).once('end', () => {\n conn.release();\n });\n } catch (e) {\n conn.release();\n throw e;\n }\n });\n }\n\n _getClusterNode() {\n const foundNodeIds = this._cluster._findNodeIds(this._pattern);\n if (foundNodeIds.length === 0) {\n return null;\n }\n const nodeId =\n foundNodeIds.length === 1\n ? foundNodeIds[0]\n : this._selector(foundNodeIds);\n return this._cluster._getNode(nodeId);\n }\n}\n\nclass PoolCluster extends EventEmitter {\n constructor(config) {\n super();\n config = config || {};\n this._canRetry =\n typeof config.canRetry === 'undefined' ? true : config.canRetry;\n this._removeNodeErrorCount = config.removeNodeErrorCount || 5;\n this._defaultSelector = config.defaultSelector || 'RR';\n this._closed = false;\n this._lastId = 0;\n this._nodes = {};\n this._serviceableNodeIds = [];\n this._namespaces = {};\n this._findCaches = {};\n }\n\n of(pattern, selector) {\n pattern = pattern || '*';\n selector = selector || this._defaultSelector;\n selector = selector.toUpperCase();\n if (!makeSelector[selector] === 'undefined') {\n selector = this._defaultSelector;\n }\n const key = pattern + selector;\n if (typeof this._namespaces[key] === 'undefined') {\n this._namespaces[key] = new PoolNamespace(this, pattern, selector);\n }\n return this._namespaces[key];\n }\n\n add(id, config) {\n if (typeof id === 'object') {\n config = id;\n id = `CLUSTER::${++this._lastId}`;\n }\n if (typeof this._nodes[id] === 'undefined') {\n this._nodes[id] = {\n id: id,\n errorCount: 0,\n pool: new Pool({ config: new PoolConfig(config) })\n };\n this._serviceableNodeIds.push(id);\n this._clearFindCaches();\n }\n }\n\n getConnection(pattern, selector, cb) {\n let namespace;\n if (typeof pattern === 'function') {\n cb = pattern;\n namespace = this.of();\n } else {\n if (typeof selector === 'function') {\n cb = selector;\n selector = this._defaultSelector;\n }\n namespace = this.of(pattern, selector);\n }\n namespace.getConnection(cb);\n }\n\n end(callback) {\n const cb =\n callback !== undefined\n ? callback\n : err => {\n if (err) {\n throw err;\n }\n };\n if (this._closed) {\n process.nextTick(cb);\n return;\n }\n this._closed = true;\n\n let calledBack = false;\n let waitingClose = 0;\n const onEnd = err => {\n if (!calledBack && (err || --waitingClose <= 0)) {\n calledBack = true;\n return cb(err);\n }\n };\n\n for (const id in this._nodes) {\n waitingClose++;\n this._nodes[id].pool.end(onEnd);\n }\n if (waitingClose === 0) {\n process.nextTick(onEnd);\n }\n }\n\n _findNodeIds(pattern) {\n if (typeof this._findCaches[pattern] !== 'undefined') {\n return this._findCaches[pattern];\n }\n let foundNodeIds;\n if (pattern === '*') {\n // all\n foundNodeIds = this._serviceableNodeIds;\n } else if (this._serviceableNodeIds.indexOf(pattern) !== -1) {\n // one\n foundNodeIds = [pattern];\n } else {\n // wild matching\n const keyword = pattern.substring(pattern.length - 1, 0);\n foundNodeIds = this._serviceableNodeIds.filter(id =>\n id.startsWith(keyword)\n );\n }\n this._findCaches[pattern] = foundNodeIds;\n return foundNodeIds;\n }\n\n _getNode(id) {\n return this._nodes[id] || null;\n }\n\n _increaseErrorCount(node) {\n if (++node.errorCount >= this._removeNodeErrorCount) {\n const index = this._serviceableNodeIds.indexOf(node.id);\n if (index !== -1) {\n this._serviceableNodeIds.splice(index, 1);\n delete this._nodes[node.id];\n this._clearFindCaches();\n node.pool.end();\n this.emit('remove', node.id);\n }\n }\n }\n\n _decreaseErrorCount(node) {\n if (node.errorCount > 0) {\n --node.errorCount;\n }\n }\n\n _getConnection(node, cb) {\n node.pool.getConnection((err, connection) => {\n if (err) {\n this._increaseErrorCount(node);\n if (this._canRetry) {\n // REVIEW: this seems wrong?\n this.emit('warn', err);\n // eslint-disable-next-line no-console\n console.warn(`[Error] PoolCluster : ${err}`);\n return cb(null, 'retry');\n }\n return cb(err);\n }\n this._decreaseErrorCount(node);\n\n connection._clusterId = node.id;\n return cb(null, connection);\n });\n }\n\n _clearFindCaches() {\n this._findCaches = {};\n }\n}\n\nmodule.exports = PoolCluster;\n","'use strict';\n\nconst ConnectionConfig = require('./connection_config.js');\n\nclass PoolConfig {\n constructor(options) {\n if (typeof options === 'string') {\n options = ConnectionConfig.parseUrl(options);\n }\n this.connectionConfig = new ConnectionConfig(options);\n this.waitForConnections =\n options.waitForConnections === undefined\n ? true\n : Boolean(options.waitForConnections);\n this.connectionLimit = isNaN(options.connectionLimit)\n ? 10\n : Number(options.connectionLimit);\n this.queueLimit = isNaN(options.queueLimit)\n ? 0\n : Number(options.queueLimit);\n }\n}\n\nmodule.exports = PoolConfig;\n","'use strict';\n\nconst format = require('./format');\n\n/*\n * function align (info)\n * Returns a new instance of the align Format which adds a `\\t`\n * delimiter before the message to properly align it in the same place.\n * It was previously { align: true } in winston < 3.0.0\n */\nmodule.exports = format(info => {\n info.message = `\\t${info.message}`;\n return info;\n});\n","'use strict';\n\nconst { Colorizer } = require('./colorize');\nconst { Padder } = require('./pad-levels');\nconst { configs, MESSAGE } = require('triple-beam');\n\n\n/**\n * Cli format class that handles initial state for a a separate\n * Colorizer and Padder instance.\n */\nclass CliFormat {\n constructor(opts = {}) {\n if (!opts.levels) {\n opts.levels = configs.npm.levels;\n }\n\n this.colorizer = new Colorizer(opts);\n this.padder = new Padder(opts);\n this.options = opts;\n }\n\n /*\n * function transform (info, opts)\n * Attempts to both:\n * 1. Pad the { level }\n * 2. Colorize the { level, message }\n * of the given `logform` info object depending on the `opts`.\n */\n transform(info, opts) {\n this.colorizer.transform(\n this.padder.transform(info, opts),\n opts\n );\n\n info[MESSAGE] = `${info.level}:${info.message}`;\n return info;\n }\n}\n\n/*\n * function cli (opts)\n * Returns a new instance of the CLI format that turns a log\n * `info` object into the same format previously available\n * in `winston.cli()` in `winston < 3.0.0`.\n */\nmodule.exports = opts => new CliFormat(opts);\n\n//\n// Attach the CliFormat for registration purposes\n//\nmodule.exports.Format = CliFormat;\n","'use strict';\n\nconst format = require('./format');\n\n/*\n * function cascade(formats)\n * Returns a function that invokes the `._format` function in-order\n * for the specified set of `formats`. In this manner we say that Formats\n * are \"pipe-like\", but not a pure pumpify implementation. Since there is no back\n * pressure we can remove all of the \"readable\" plumbing in Node streams.\n */\nfunction cascade(formats) {\n if (!formats.every(isValidFormat)) {\n return;\n }\n\n return info => {\n let obj = info;\n for (let i = 0; i < formats.length; i++) {\n obj = formats[i].transform(obj, formats[i].options);\n if (!obj) {\n return false;\n }\n }\n\n return obj;\n };\n}\n\n/*\n * function isValidFormat(format)\n * If the format does not define a `transform` function throw an error\n * with more detailed usage.\n */\nfunction isValidFormat(fmt) {\n if (typeof fmt.transform !== 'function') {\n throw new Error([\n 'No transform function found on format. Did you create a format instance?',\n 'const myFormat = format(formatFn);',\n 'const instance = myFormat();'\n ].join('\\n'));\n }\n\n return true;\n}\n\n/*\n * function combine (info)\n * Returns a new instance of the combine Format which combines the specified\n * formats into a new format. This is similar to a pipe-chain in transform streams.\n * We choose to combine the prototypes this way because there is no back pressure in\n * an in-memory transform chain.\n */\nmodule.exports = (...formats) => {\n const combinedFormat = format(cascade(formats));\n const instance = combinedFormat();\n instance.Format = combinedFormat.Format;\n return instance;\n};\n\n//\n// Export the cascade method for use in cli and other\n// combined formats that should not be assumed to be\n// singletons.\n//\nmodule.exports.cascade = cascade;\n","'use strict';\n\nconst format = require('./format');\n\n/*\n * function label (info)\n * Returns a new instance of the label Format which adds the specified\n * `opts.label` before the message. This was previously exposed as\n * { label: 'my label' } to transports in `winston < 3.0.0`.\n */\nmodule.exports = format((info, opts) => {\n if (opts.message) {\n info.message = `[${opts.label}] ${info.message}`;\n return info;\n }\n\n info.label = opts.label;\n return info;\n});\n","'use strict';\n\nconst format = require('./format');\nconst { MESSAGE } = require('triple-beam');\nconst jsonStringify = require('fast-safe-stringify');\n\n/*\n * function logstash (info)\n * Returns a new instance of the LogStash Format that turns a\n * log `info` object into pure JSON with the appropriate logstash\n * options. This was previously exposed as { logstash: true }\n * to transports in `winston < 3.0.0`.\n */\nmodule.exports = format(info => {\n const logstash = {};\n if (info.message) {\n logstash['@message'] = info.message;\n delete info.message;\n }\n\n if (info.timestamp) {\n logstash['@timestamp'] = info.timestamp;\n delete info.timestamp;\n }\n\n logstash['@fields'] = info;\n info[MESSAGE] = jsonStringify(logstash);\n return info;\n});\n","'use strict';\n\nconst format = require('./format');\n\nfunction fillExcept(info, fillExceptKeys, metadataKey) {\n const savedKeys = fillExceptKeys.reduce((acc, key) => {\n acc[key] = info[key];\n delete info[key];\n return acc;\n }, {});\n const metadata = Object.keys(info).reduce((acc, key) => {\n acc[key] = info[key];\n delete info[key];\n return acc;\n }, {});\n\n Object.assign(info, savedKeys, {\n [metadataKey]: metadata\n });\n return info;\n}\n\nfunction fillWith(info, fillWithKeys, metadataKey) {\n info[metadataKey] = fillWithKeys.reduce((acc, key) => {\n acc[key] = info[key];\n delete info[key];\n return acc;\n }, {});\n return info;\n}\n\n/**\n * Adds in a \"metadata\" object to collect extraneous data, similar to the metadata\n * object in winston 2.x.\n */\nmodule.exports = format((info, opts = {}) => {\n let metadataKey = 'metadata';\n if (opts.key) {\n metadataKey = opts.key;\n }\n\n let fillExceptKeys = [];\n if (!opts.fillExcept && !opts.fillWith) {\n fillExceptKeys.push('level');\n fillExceptKeys.push('message');\n }\n\n if (opts.fillExcept) {\n fillExceptKeys = opts.fillExcept;\n }\n\n if (fillExceptKeys.length > 0) {\n return fillExcept(info, fillExceptKeys, metadataKey);\n }\n\n if (opts.fillWith) {\n return fillWith(info, opts.fillWith, metadataKey);\n }\n\n return info;\n});\n","'use strict';\n\nconst inspect = require('util').inspect;\nconst format = require('./format');\nconst { LEVEL, MESSAGE, SPLAT } = require('triple-beam');\n\n/*\n * function prettyPrint (info)\n * Returns a new instance of the prettyPrint Format that \"prettyPrint\"\n * serializes `info` objects. This was previously exposed as\n * { prettyPrint: true } to transports in `winston < 3.0.0`.\n */\nmodule.exports = format((info, opts = {}) => {\n //\n // info[{LEVEL, MESSAGE, SPLAT}] are enumerable here. Since they\n // are internal, we remove them before util.inspect so they\n // are not printed.\n //\n const stripped = Object.assign({}, info);\n\n // Remark (indexzero): update this technique in April 2019\n // when node@6 is EOL\n delete stripped[LEVEL];\n delete stripped[MESSAGE];\n delete stripped[SPLAT];\n\n info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize);\n return info;\n});\n","'use strict';\n\nconst { MESSAGE } = require('triple-beam');\n\nclass Printf {\n constructor(templateFn) {\n this.template = templateFn;\n }\n\n transform(info) {\n info[MESSAGE] = this.template(info);\n return info;\n }\n}\n\n/*\n * function printf (templateFn)\n * Returns a new instance of the printf Format that creates an\n * intermediate prototype to store the template string-based formatter\n * function.\n */\nmodule.exports = opts => new Printf(opts);\n\nmodule.exports.Printf\n = module.exports.Format\n = Printf;\n","/* eslint no-undefined: 0 */\n'use strict';\n\nconst format = require('./format');\nconst { MESSAGE } = require('triple-beam');\nconst jsonStringify = require('fast-safe-stringify');\n\n/*\n * function simple (info)\n * Returns a new instance of the simple format TransformStream\n * which writes a simple representation of logs.\n *\n * const { level, message, splat, ...rest } = info;\n *\n * ${level}: ${message} if rest is empty\n * ${level}: ${message} ${JSON.stringify(rest)} otherwise\n */\nmodule.exports = format(info => {\n const stringifiedRest = jsonStringify(Object.assign({}, info, {\n level: undefined,\n message: undefined,\n splat: undefined\n }));\n\n const padding = info.padding && info.padding[info.level] || '';\n if (stringifiedRest !== '{}') {\n info[MESSAGE] = `${info.level}:${padding} ${info.message} ${stringifiedRest}`;\n } else {\n info[MESSAGE] = `${info.level}:${padding} ${info.message}`;\n }\n\n return info;\n});\n","'use strict';\n\nconst util = require('util');\nconst { SPLAT } = require('triple-beam');\n\n/**\n * Captures the number of format (i.e. %s strings) in a given string.\n * Based on `util.format`, see Node.js source:\n * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230\n * @type {RegExp}\n */\nconst formatRegExp = /%[scdjifoO%]/g;\n\n/**\n * Captures the number of escaped % signs in a format string (i.e. %s strings).\n * @type {RegExp}\n */\nconst escapedPercent = /%%/g;\n\nclass Splatter {\n constructor(opts) {\n this.options = opts;\n }\n\n /**\n * Check to see if tokens <= splat.length, assign { splat, meta } into the\n * `info` accordingly, and write to this instance.\n *\n * @param {Info} info Logform info message.\n * @param {String[]} tokens Set of string interpolation tokens.\n * @returns {Info} Modified info message\n * @private\n */\n _splat(info, tokens) {\n const msg = info.message;\n const splat = info[SPLAT] || info.splat || [];\n const percents = msg.match(escapedPercent);\n const escapes = percents && percents.length || 0;\n\n // The expected splat is the number of tokens minus the number of escapes\n // e.g.\n // - { expectedSplat: 3 } '%d %s %j'\n // - { expectedSplat: 5 } '[%s] %d%% %d%% %s %j'\n //\n // Any \"meta\" will be arugments in addition to the expected splat size\n // regardless of type. e.g.\n //\n // logger.log('info', '%d%% %s %j', 100, 'wow', { such: 'js' }, { thisIsMeta: true });\n // would result in splat of four (4), but only three (3) are expected. Therefore:\n //\n // extraSplat = 3 - 4 = -1\n // metas = [100, 'wow', { such: 'js' }, { thisIsMeta: true }].splice(-1, -1 * -1);\n // splat = [100, 'wow', { such: 'js' }]\n const expectedSplat = tokens.length - escapes;\n const extraSplat = expectedSplat - splat.length;\n const metas = extraSplat < 0\n ? splat.splice(extraSplat, -1 * extraSplat)\n : [];\n\n // Now that { splat } has been separated from any potential { meta }. we\n // can assign this to the `info` object and write it to our format stream.\n // If the additional metas are **NOT** objects or **LACK** enumerable properties\n // you are going to have a bad time.\n const metalen = metas.length;\n if (metalen) {\n for (let i = 0; i < metalen; i++) {\n Object.assign(info, metas[i]);\n }\n }\n\n info.message = util.format(msg, ...splat);\n return info;\n }\n\n /**\n * Transforms the `info` message by using `util.format` to complete\n * any `info.message` provided it has string interpolation tokens.\n * If no tokens exist then `info` is immutable.\n *\n * @param {Info} info Logform info message.\n * @param {Object} opts Options for this instance.\n * @returns {Info} Modified info message\n */\n transform(info) {\n const msg = info.message;\n const splat = info[SPLAT] || info.splat;\n\n // No need to process anything if splat is undefined\n if (!splat || !splat.length) {\n return info;\n }\n\n // Extract tokens, if none available default to empty array to\n // ensure consistancy in expected results\n const tokens = msg && msg.match && msg.match(formatRegExp);\n\n // This condition will take care of inputs with info[SPLAT]\n // but no tokens present\n if (!tokens && (splat || splat.length)) {\n const metas = splat.length > 1\n ? splat.splice(0)\n : splat;\n\n // Now that { splat } has been separated from any potential { meta }. we\n // can assign this to the `info` object and write it to our format stream.\n // If the additional metas are **NOT** objects or **LACK** enumerable properties\n // you are going to have a bad time.\n const metalen = metas.length;\n if (metalen) {\n for (let i = 0; i < metalen; i++) {\n Object.assign(info, metas[i]);\n }\n }\n\n return info;\n }\n\n if (tokens) {\n return this._splat(info, tokens);\n }\n\n return info;\n }\n}\n\n/*\n * function splat (info)\n * Returns a new instance of the splat format TransformStream\n * which performs string interpolation from `info` objects. This was\n * previously exposed implicitly in `winston < 3.0.0`.\n */\nmodule.exports = opts => new Splatter(opts);\n","'use strict';\n\nconst fecha = require('fecha');\nconst format = require('./format');\n\n/*\n * function timestamp (info)\n * Returns a new instance of the timestamp Format which adds a timestamp\n * to the info. It was previously available in winston < 3.0.0 as:\n *\n * - { timestamp: true } // `new Date.toISOString()`\n * - { timestamp: function:String } // Value returned by `timestamp()`\n */\nmodule.exports = format((info, opts = {}) => {\n if (opts.format) {\n info.timestamp = typeof opts.format === 'function'\n ? opts.format()\n : fecha.format(new Date(), opts.format);\n }\n\n if (!info.timestamp) {\n info.timestamp = new Date().toISOString();\n }\n\n if (opts.alias) {\n info[opts.alias] = info.timestamp;\n }\n\n return info;\n});\n","var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\\1?|[aA]|\"[^\"]*\"|'[^']*'/g;\nvar twoDigitsOptional = \"[1-9]\\\\d?\";\nvar twoDigits = \"\\\\d\\\\d\";\nvar threeDigits = \"\\\\d{3}\";\nvar fourDigits = \"\\\\d{4}\";\nvar word = \"[^\\\\s]+\";\nvar literal = /\\[([^]*?)\\]/gm;\nfunction shorten(arr, sLen) {\n var newArr = [];\n for (var i = 0, len = arr.length; i < len; i++) {\n newArr.push(arr[i].substr(0, sLen));\n }\n return newArr;\n}\nvar monthUpdate = function (arrName) { return function (v, i18n) {\n var lowerCaseArr = i18n[arrName].map(function (v) { return v.toLowerCase(); });\n var index = lowerCaseArr.indexOf(v.toLowerCase());\n if (index > -1) {\n return index;\n }\n return null;\n}; };\nfunction assign(origObj) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {\n var obj = args_1[_a];\n for (var key in obj) {\n // @ts-ignore ex\n origObj[key] = obj[key];\n }\n }\n return origObj;\n}\nvar dayNames = [\n \"Sunday\",\n \"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\",\n \"Saturday\"\n];\nvar monthNames = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\"\n];\nvar monthNamesShort = shorten(monthNames, 3);\nvar dayNamesShort = shorten(dayNames, 3);\nvar defaultI18n = {\n dayNamesShort: dayNamesShort,\n dayNames: dayNames,\n monthNamesShort: monthNamesShort,\n monthNames: monthNames,\n amPm: [\"am\", \"pm\"],\n DoFn: function (dayOfMonth) {\n return (dayOfMonth +\n [\"th\", \"st\", \"nd\", \"rd\"][dayOfMonth % 10 > 3\n ? 0\n : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10]);\n }\n};\nvar globalI18n = assign({}, defaultI18n);\nvar setGlobalDateI18n = function (i18n) {\n return (globalI18n = assign(globalI18n, i18n));\n};\nvar regexEscape = function (str) {\n return str.replace(/[|\\\\{()[^$+*?.-]/g, \"\\\\$&\");\n};\nvar pad = function (val, len) {\n if (len === void 0) { len = 2; }\n val = String(val);\n while (val.length < len) {\n val = \"0\" + val;\n }\n return val;\n};\nvar formatFlags = {\n D: function (dateObj) { return String(dateObj.getDate()); },\n DD: function (dateObj) { return pad(dateObj.getDate()); },\n Do: function (dateObj, i18n) {\n return i18n.DoFn(dateObj.getDate());\n },\n d: function (dateObj) { return String(dateObj.getDay()); },\n dd: function (dateObj) { return pad(dateObj.getDay()); },\n ddd: function (dateObj, i18n) {\n return i18n.dayNamesShort[dateObj.getDay()];\n },\n dddd: function (dateObj, i18n) {\n return i18n.dayNames[dateObj.getDay()];\n },\n M: function (dateObj) { return String(dateObj.getMonth() + 1); },\n MM: function (dateObj) { return pad(dateObj.getMonth() + 1); },\n MMM: function (dateObj, i18n) {\n return i18n.monthNamesShort[dateObj.getMonth()];\n },\n MMMM: function (dateObj, i18n) {\n return i18n.monthNames[dateObj.getMonth()];\n },\n YY: function (dateObj) {\n return pad(String(dateObj.getFullYear()), 4).substr(2);\n },\n YYYY: function (dateObj) { return pad(dateObj.getFullYear(), 4); },\n h: function (dateObj) { return String(dateObj.getHours() % 12 || 12); },\n hh: function (dateObj) { return pad(dateObj.getHours() % 12 || 12); },\n H: function (dateObj) { return String(dateObj.getHours()); },\n HH: function (dateObj) { return pad(dateObj.getHours()); },\n m: function (dateObj) { return String(dateObj.getMinutes()); },\n mm: function (dateObj) { return pad(dateObj.getMinutes()); },\n s: function (dateObj) { return String(dateObj.getSeconds()); },\n ss: function (dateObj) { return pad(dateObj.getSeconds()); },\n S: function (dateObj) {\n return String(Math.round(dateObj.getMilliseconds() / 100));\n },\n SS: function (dateObj) {\n return pad(Math.round(dateObj.getMilliseconds() / 10), 2);\n },\n SSS: function (dateObj) { return pad(dateObj.getMilliseconds(), 3); },\n a: function (dateObj, i18n) {\n return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1];\n },\n A: function (dateObj, i18n) {\n return dateObj.getHours() < 12\n ? i18n.amPm[0].toUpperCase()\n : i18n.amPm[1].toUpperCase();\n },\n ZZ: function (dateObj) {\n var offset = dateObj.getTimezoneOffset();\n return ((offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4));\n },\n Z: function (dateObj) {\n var offset = dateObj.getTimezoneOffset();\n return ((offset > 0 ? \"-\" : \"+\") +\n pad(Math.floor(Math.abs(offset) / 60), 2) +\n \":\" +\n pad(Math.abs(offset) % 60, 2));\n }\n};\nvar monthParse = function (v) { return +v - 1; };\nvar emptyDigits = [null, twoDigitsOptional];\nvar emptyWord = [null, word];\nvar amPm = [\n \"isPm\",\n word,\n function (v, i18n) {\n var val = v.toLowerCase();\n if (val === i18n.amPm[0]) {\n return 0;\n }\n else if (val === i18n.amPm[1]) {\n return 1;\n }\n return null;\n }\n];\nvar timezoneOffset = [\n \"timezoneOffset\",\n \"[^\\\\s]*?[\\\\+\\\\-]\\\\d\\\\d:?\\\\d\\\\d|[^\\\\s]*?Z?\",\n function (v) {\n var parts = (v + \"\").match(/([+-]|\\d\\d)/gi);\n if (parts) {\n var minutes = +parts[1] * 60 + parseInt(parts[2], 10);\n return parts[0] === \"+\" ? minutes : -minutes;\n }\n return 0;\n }\n];\nvar parseFlags = {\n D: [\"day\", twoDigitsOptional],\n DD: [\"day\", twoDigits],\n Do: [\"day\", twoDigitsOptional + word, function (v) { return parseInt(v, 10); }],\n M: [\"month\", twoDigitsOptional, monthParse],\n MM: [\"month\", twoDigits, monthParse],\n YY: [\n \"year\",\n twoDigits,\n function (v) {\n var now = new Date();\n var cent = +(\"\" + now.getFullYear()).substr(0, 2);\n return +(\"\" + (+v > 68 ? cent - 1 : cent) + v);\n }\n ],\n h: [\"hour\", twoDigitsOptional, undefined, \"isPm\"],\n hh: [\"hour\", twoDigits, undefined, \"isPm\"],\n H: [\"hour\", twoDigitsOptional],\n HH: [\"hour\", twoDigits],\n m: [\"minute\", twoDigitsOptional],\n mm: [\"minute\", twoDigits],\n s: [\"second\", twoDigitsOptional],\n ss: [\"second\", twoDigits],\n YYYY: [\"year\", fourDigits],\n S: [\"millisecond\", \"\\\\d\", function (v) { return +v * 100; }],\n SS: [\"millisecond\", twoDigits, function (v) { return +v * 10; }],\n SSS: [\"millisecond\", threeDigits],\n d: emptyDigits,\n dd: emptyDigits,\n ddd: emptyWord,\n dddd: emptyWord,\n MMM: [\"month\", word, monthUpdate(\"monthNamesShort\")],\n MMMM: [\"month\", word, monthUpdate(\"monthNames\")],\n a: amPm,\n A: amPm,\n ZZ: timezoneOffset,\n Z: timezoneOffset\n};\n// Some common format strings\nvar globalMasks = {\n default: \"ddd MMM DD YYYY HH:mm:ss\",\n shortDate: \"M/D/YY\",\n mediumDate: \"MMM D, YYYY\",\n longDate: \"MMMM D, YYYY\",\n fullDate: \"dddd, MMMM D, YYYY\",\n isoDate: \"YYYY-MM-DD\",\n isoDateTime: \"YYYY-MM-DDTHH:mm:ssZ\",\n shortTime: \"HH:mm\",\n mediumTime: \"HH:mm:ss\",\n longTime: \"HH:mm:ss.SSS\"\n};\nvar setGlobalDateMasks = function (masks) { return assign(globalMasks, masks); };\n/***\n * Format a date\n * @method format\n * @param {Date|number} dateObj\n * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'\n * @returns {string} Formatted date string\n */\nvar format = function (dateObj, mask, i18n) {\n if (mask === void 0) { mask = globalMasks[\"default\"]; }\n if (i18n === void 0) { i18n = {}; }\n if (typeof dateObj === \"number\") {\n dateObj = new Date(dateObj);\n }\n if (Object.prototype.toString.call(dateObj) !== \"[object Date]\" ||\n isNaN(dateObj.getTime())) {\n throw new Error(\"Invalid Date pass to format\");\n }\n mask = globalMasks[mask] || mask;\n var literals = [];\n // Make literals inactive by replacing them with @@@\n mask = mask.replace(literal, function ($0, $1) {\n literals.push($1);\n return \"@@@\";\n });\n var combinedI18nSettings = assign(assign({}, globalI18n), i18n);\n // Apply formatting rules\n mask = mask.replace(token, function ($0) {\n return formatFlags[$0](dateObj, combinedI18nSettings);\n });\n // Inline literal values back into the formatted value\n return mask.replace(/@@@/g, function () { return literals.shift(); });\n};\n/**\n * Parse a date string into a Javascript Date object /\n * @method parse\n * @param {string} dateStr Date string\n * @param {string} format Date parse format\n * @param {i18n} I18nSettingsOptional Full or subset of I18N settings\n * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format\n */\nfunction parse(dateStr, format, i18n) {\n if (i18n === void 0) { i18n = {}; }\n if (typeof format !== \"string\") {\n throw new Error(\"Invalid format in fecha parse\");\n }\n // Check to see if the format is actually a mask\n format = globalMasks[format] || format;\n // Avoid regular expression denial of service, fail early for really long strings\n // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS\n if (dateStr.length > 1000) {\n return null;\n }\n // Default to the beginning of the year.\n var today = new Date();\n var dateInfo = {\n year: today.getFullYear(),\n month: 0,\n day: 1,\n hour: 0,\n minute: 0,\n second: 0,\n millisecond: 0,\n isPm: null,\n timezoneOffset: null\n };\n var parseInfo = [];\n var literals = [];\n // Replace all the literals with @@@. Hopefully a string that won't exist in the format\n var newFormat = format.replace(literal, function ($0, $1) {\n literals.push(regexEscape($1));\n return \"@@@\";\n });\n var specifiedFields = {};\n var requiredFields = {};\n // Change every token that we find into the correct regex\n newFormat = regexEscape(newFormat).replace(token, function ($0) {\n var info = parseFlags[$0];\n var field = info[0], regex = info[1], requiredField = info[3];\n // Check if the person has specified the same field twice. This will lead to confusing results.\n if (specifiedFields[field]) {\n throw new Error(\"Invalid format. \" + field + \" specified twice in format\");\n }\n specifiedFields[field] = true;\n // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified\n if (requiredField) {\n requiredFields[requiredField] = true;\n }\n parseInfo.push(info);\n return \"(\" + regex + \")\";\n });\n // Check all the required fields are present\n Object.keys(requiredFields).forEach(function (field) {\n if (!specifiedFields[field]) {\n throw new Error(\"Invalid format. \" + field + \" is required in specified format\");\n }\n });\n // Add back all the literals after\n newFormat = newFormat.replace(/@@@/g, function () { return literals.shift(); });\n // Check if the date string matches the format. If it doesn't return null\n var matches = dateStr.match(new RegExp(newFormat, \"i\"));\n if (!matches) {\n return null;\n }\n var combinedI18nSettings = assign(assign({}, globalI18n), i18n);\n // For each match, call the parser function for that date part\n for (var i = 1; i < matches.length; i++) {\n var _a = parseInfo[i - 1], field = _a[0], parser = _a[2];\n var value = parser\n ? parser(matches[i], combinedI18nSettings)\n : +matches[i];\n // If the parser can't make sense of the value, return null\n if (value == null) {\n return null;\n }\n dateInfo[field] = value;\n }\n if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) {\n dateInfo.hour = +dateInfo.hour + 12;\n }\n else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) {\n dateInfo.hour = 0;\n }\n var dateWithoutTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond);\n var validateFields = [\n [\"month\", \"getMonth\"],\n [\"day\", \"getDate\"],\n [\"hour\", \"getHours\"],\n [\"minute\", \"getMinutes\"],\n [\"second\", \"getSeconds\"]\n ];\n for (var i = 0, len = validateFields.length; i < len; i++) {\n // Check to make sure the date field is within the allowed range. Javascript dates allows values\n // outside the allowed range. If the values don't match the value was invalid\n if (specifiedFields[validateFields[i][0]] &&\n dateInfo[validateFields[i][0]] !== dateWithoutTZ[validateFields[i][1]]()) {\n return null;\n }\n }\n if (dateInfo.timezoneOffset == null) {\n return dateWithoutTZ;\n }\n return new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond));\n}\nvar fecha = {\n format: format,\n parse: parse,\n defaultI18n: defaultI18n,\n setGlobalDateI18n: setGlobalDateI18n,\n setGlobalDateMasks: setGlobalDateMasks\n};\n\nexport default fecha;\nexport { assign, format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks };\n//# sourceMappingURL=fecha.js.map\n","'use strict';\n\nconst colors = require('colors/safe');\nconst format = require('./format');\nconst { MESSAGE } = require('triple-beam');\n\n/*\n * function uncolorize (info)\n * Returns a new instance of the uncolorize Format that strips colors\n * from `info` objects. This was previously exposed as { stripColors: true }\n * to transports in `winston < 3.0.0`.\n */\nmodule.exports = format((info, opts) => {\n if (opts.level !== false) {\n info.level = colors.strip(info.level);\n }\n\n if (opts.message !== false) {\n info.message = colors.strip(info.message);\n }\n\n if (opts.raw !== false && info[MESSAGE]) {\n info[MESSAGE] = colors.strip(info[MESSAGE]);\n }\n\n return info;\n});\n","'use strict';\n/*\n * @api public\n * @property {function} format\n * Both the construction method and set of exposed\n * formats.\n */\n\nvar format = exports.format = require('././format');\n/*\n * @api public\n * @method {function} levels\n * Registers the specified levels with logform.\n */\n\n\nexports.levels = require('././levels'); //\n// Setup all transports as eager-loaded exports\n// so that they are static for the bundlers.\n//\n\nObject.defineProperty(format, 'align', {\n value: require('./align')\n});\nObject.defineProperty(format, 'cli', {\n value: require('./cli')\n});\nObject.defineProperty(format, 'combine', {\n value: require('./combine')\n});\nObject.defineProperty(format, 'colorize', {\n value: require('./colorize')\n});\nObject.defineProperty(format, 'json', {\n value: require('./json')\n});\nObject.defineProperty(format, 'label', {\n value: require('./label')\n});\nObject.defineProperty(format, 'logstash', {\n value: require('./logstash')\n});\nObject.defineProperty(format, 'metadata', {\n value: require('./metadata')\n});\nObject.defineProperty(format, 'padLevels', {\n value: require('./pad-levels')\n});\nObject.defineProperty(format, 'prettyPrint', {\n value: require('./pretty-print')\n});\nObject.defineProperty(format, 'printf', {\n value: require('./printf')\n});\nObject.defineProperty(format, 'simple', {\n value: require('./simple')\n});\nObject.defineProperty(format, 'splat', {\n value: require('./splat')\n});\nObject.defineProperty(format, 'timestamp', {\n value: require('./timestamp')\n});\nObject.defineProperty(format, 'uncolorize', {\n value: require('./uncolorize')\n});","/* eslint no-undefined: 0 */\n'use strict';\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nvar format = require('./format');\n\nvar _require = require('triple-beam'),\n LEVEL = _require.LEVEL,\n MESSAGE = _require.MESSAGE;\n/*\n * function errors (info)\n * If the `message` property of the `info` object is an instance of `Error`,\n * replace the `Error` object its own `message` property.\n *\n * Optionally, the Error's `stack` property can also be appended to the `info` object.\n */\n\n\nmodule.exports = format(function (einfo, _ref) {\n var stack = _ref.stack;\n\n if (einfo instanceof Error) {\n var _Object$assign;\n\n var info = Object.assign({}, einfo, (_Object$assign = {\n level: einfo.level\n }, _defineProperty(_Object$assign, LEVEL, einfo[LEVEL] || einfo.level), _defineProperty(_Object$assign, \"message\", einfo.message), _defineProperty(_Object$assign, MESSAGE, einfo[MESSAGE] || einfo.message), _Object$assign));\n if (stack) info.stack = einfo.stack;\n return info;\n }\n\n if (!(einfo.message instanceof Error)) return einfo; // Assign all enumerable properties and the\n // message property from the error provided.\n\n Object.assign(einfo, einfo.message);\n var err = einfo.message;\n einfo.message = err.message;\n einfo[MESSAGE] = err.message; // Assign the stack if requested.\n\n if (stack) einfo.stack = err.stack;\n return einfo;\n});","'use strict';\n/*\n * @api public\n * @property {function} format\n * Both the construction method and set of exposed\n * formats.\n */\n\nvar format = exports.format = require('./format');\n/*\n * @api public\n * @method {function} levels\n * Registers the specified levels with logform.\n */\n\n\nexports.levels = require('./levels');\n/*\n * @api private\n * method {function} exposeFormat\n * Exposes a sub-format on the main format object\n * as a lazy-loaded getter.\n */\n\nfunction exposeFormat(name, path) {\n path = path || name;\n Object.defineProperty(format, name, {\n get: function get() {\n return require(\"./\".concat(path, \".js\"));\n },\n configurable: true\n });\n} //\n// Setup all transports as lazy-loaded getters.\n//\n\n\nexposeFormat('align');\nexposeFormat('errors');\nexposeFormat('cli');\nexposeFormat('combine');\nexposeFormat('colorize');\nexposeFormat('json');\nexposeFormat('label');\nexposeFormat('logstash');\nexposeFormat('metadata');\nexposeFormat('ms');\nexposeFormat('padLevels', 'pad-levels');\nexposeFormat('prettyPrint', 'pretty-print');\nexposeFormat('printf');\nexposeFormat('simple');\nexposeFormat('splat');\nexposeFormat('timestamp');\nexposeFormat('uncolorize');","'use strict';\n\nvar _this = void 0;\n\nvar format = require('./format');\n\nvar ms = require('ms');\n/*\n * function ms (info)\n * Returns an `info` with a `ms` property. The `ms` property holds the Value\n * of the time difference between two calls in milliseconds.\n */\n\n\nmodule.exports = format(function (info) {\n var curr = +new Date();\n _this.diff = curr - (_this.prevTime || curr);\n _this.prevTime = curr;\n info.ms = \"+\".concat(ms(_this.diff));\n return info;\n});","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","/**\n * common.js: Internal helper and utility functions for winston.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst { format } = require('util');\n\n/**\n * Set of simple deprecation notices and a way to expose them for a set of\n * properties.\n * @type {Object}\n * @private\n */\nexports.warn = {\n deprecated(prop) {\n return () => {\n throw new Error(format('{ %s } was removed in winston@3.0.0.', prop));\n };\n },\n useFormat(prop) {\n return () => {\n throw new Error([\n format('{ %s } was removed in winston@3.0.0.', prop),\n 'Use a custom winston.format = winston.format(function) instead.'\n ].join('\\n'));\n };\n },\n forFunctions(obj, type, props) {\n props.forEach(prop => {\n obj[prop] = exports.warn[type](prop);\n });\n },\n moved(obj, movedTo, prop) {\n function movedNotice() {\n return () => {\n throw new Error([\n format('winston.%s was moved in winston@3.0.0.', prop),\n format('Use a winston.%s instead.', movedTo)\n ].join('\\n'));\n };\n }\n\n Object.defineProperty(obj, prop, {\n get: movedNotice,\n set: movedNotice\n });\n },\n forProperties(obj, type, props) {\n props.forEach(prop => {\n const notice = exports.warn[type](prop);\n Object.defineProperty(obj, prop, {\n get: notice,\n set: notice\n });\n });\n }\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Writable;\n\n/* */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /**/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /**/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n if (state.corkedRequestsFree) {\n state.corkedRequestsFree.next = corkReq;\n } else {\n state.corkedRequestsFree = corkReq;\n }\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};","\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n","module.exports = require('stream');\n","'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {\n pna.nextTick(emitErrorNT, this, err);\n }\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n pna.nextTick(emitErrorNT, _this, err);\n if (_this._writableState) {\n _this._writableState.errorEmitted = true;\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","'use strict';\n\nconst util = require('util');\nconst { LEVEL } = require('triple-beam');\nconst TransportStream = require('./');\n\n/**\n * Constructor function for the LegacyTransportStream. This is an internal\n * wrapper `winston >= 3` uses to wrap older transports implementing\n * log(level, message, meta).\n * @param {Object} options - Options for this TransportStream instance.\n * @param {Transpot} options.transport - winston@2 or older Transport to wrap.\n */\n\nconst LegacyTransportStream = module.exports = function LegacyTransportStream(options = {}) {\n TransportStream.call(this, options);\n if (!options.transport || typeof options.transport.log !== 'function') {\n throw new Error('Invalid transport, must be an object with a log method.');\n }\n\n this.transport = options.transport;\n this.level = this.level || options.transport.level;\n this.handleExceptions = this.handleExceptions || options.transport.handleExceptions;\n\n // Display our deprecation notice.\n this._deprecated();\n\n // Properly bubble up errors from the transport to the\n // LegacyTransportStream instance, but only once no matter how many times\n // this transport is shared.\n function transportError(err) {\n this.emit('error', err, this.transport);\n }\n\n if (!this.transport.__winstonError) {\n this.transport.__winstonError = transportError.bind(this);\n this.transport.on('error', this.transport.__winstonError);\n }\n};\n\n/*\n * Inherit from TransportStream using Node.js built-ins\n */\nutil.inherits(LegacyTransportStream, TransportStream);\n\n/**\n * Writes the info object to our transport instance.\n * @param {mixed} info - TODO: add param description.\n * @param {mixed} enc - TODO: add param description.\n * @param {function} callback - TODO: add param description.\n * @returns {undefined}\n * @private\n */\nLegacyTransportStream.prototype._write = function _write(info, enc, callback) {\n if (this.silent || (info.exception === true && !this.handleExceptions)) {\n return callback(null);\n }\n\n // Remark: This has to be handled in the base transport now because we\n // cannot conditionally write to our pipe targets as stream.\n if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) {\n this.transport.log(info[LEVEL], info.message, info, this._nop);\n }\n\n callback(null);\n};\n\n/**\n * Writes the batch of info objects (i.e. \"object chunks\") to our transport\n * instance after performing any necessary filtering.\n * @param {mixed} chunks - TODO: add params description.\n * @param {function} callback - TODO: add params description.\n * @returns {mixed} - TODO: add returns description.\n * @private\n */\nLegacyTransportStream.prototype._writev = function _writev(chunks, callback) {\n for (let i = 0; i < chunks.length; i++) {\n if (this._accept(chunks[i])) {\n this.transport.log(\n chunks[i].chunk[LEVEL],\n chunks[i].chunk.message,\n chunks[i].chunk,\n this._nop\n );\n chunks[i].callback();\n }\n }\n\n return callback(null);\n};\n\n/**\n * Displays a deprecation notice. Defined as a function so it can be\n * overriden in tests.\n * @returns {undefined}\n */\nLegacyTransportStream.prototype._deprecated = function _deprecated() {\n // eslint-disable-next-line no-console\n console.error([\n `${this.transport.name} is a legacy winston transport. Consider upgrading: `,\n '- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md'\n ].join('\\n'));\n};\n\n/**\n * Clean up error handling state on the legacy transport associated\n * with this instance.\n * @returns {undefined}\n */\nLegacyTransportStream.prototype.close = function close() {\n if (this.transport.close) {\n this.transport.close();\n }\n\n if (this.transport.__winstonError) {\n this.transport.removeListener('error', this.transport.__winstonError);\n this.transport.__winstonError = null;\n }\n};\n","'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _eachOfLimit2 = require('./internal/eachOfLimit');\n\nvar _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2);\n\nvar _wrapAsync = require('./internal/wrapAsync');\n\nvar _wrapAsync2 = _interopRequireDefault(_wrapAsync);\n\nvar _awaitify = require('./internal/awaitify');\n\nvar _awaitify2 = _interopRequireDefault(_awaitify);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name eachOfLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.eachOf]{@link module:Collections.eachOf}\n * @alias forEachOfLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each\n * item in `coll`. The `key` is the item's key, or index in the case of an\n * array.\n * Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction eachOfLimit(coll, limit, iteratee, callback) {\n return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback);\n}\n\nexports.default = (0, _awaitify2.default)(eachOfLimit, 4);\nmodule.exports = exports['default'];","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = once;\nfunction once(fn) {\n function wrapper(...args) {\n if (fn === null) return;\n var callFn = fn;\n fn = null;\n callFn.apply(this, args);\n }\n Object.assign(wrapper, fn);\n return wrapper;\n}\nmodule.exports = exports[\"default\"];","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = onlyOnce;\nfunction onlyOnce(fn) {\n return function (...args) {\n if (fn === null) throw new Error(\"Callback was already called.\");\n var callFn = fn;\n fn = null;\n callFn.apply(this, args);\n };\n}\nmodule.exports = exports[\"default\"];","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nmodule.exports = Readable;\n/**/\n\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n/**/\n\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function EElistenerCount(emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\n\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n/**/\n\n\nvar debugUtil = require('util');\n\nvar debug;\n\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function debug() {};\n}\n/**/\n\n\nvar BufferList = require('./internal/streams/buffer_list');\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.\n\n\nvar StringDecoder;\nvar createReadableStreamAsyncIterator;\nvar from;\n\nrequire('inherits')(Readable, Stream);\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n\n this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n\n this.sync = true; // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n this.paused = true; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')\n\n this.autoDestroy = !!options.autoDestroy; // has it been destroyed\n\n this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s\n\n this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled\n\n this.readingMore = false;\n this.decoder = null;\n this.encoding = null;\n\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n this._readableState = new ReadableState(options, this, isDuplex); // legacy\n\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._readableState === undefined) {\n return false;\n }\n\n return this._readableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._readableState.destroyed = value;\n }\n});\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\n\nReadable.prototype._destroy = function (err, cb) {\n cb(err);\n}; // Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\n\n\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n}; // Unshift should *always* be something directly out of read()\n\n\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n debug('readableAddChunk', chunk);\n var state = stream._readableState;\n\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n\n if (er) {\n errorOrDestroy(stream, er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());\n } else if (state.destroyed) {\n return false;\n } else {\n state.reading = false;\n\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n maybeReadMore(stream, state);\n }\n } // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n\n\n return !state.ended && (state.length < state.highWaterMark || state.length === 0);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n state.awaitDrain = 0;\n stream.emit('data', chunk);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n if (state.needReadable) emitReadable(stream);\n }\n\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);\n }\n\n return er;\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n}; // backwards compatibility.\n\n\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n var decoder = new StringDecoder(enc);\n this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8\n\n this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:\n\n var p = this._readableState.buffer.head;\n var content = '';\n\n while (p !== null) {\n content += decoder.write(p.data);\n p = p.next;\n }\n\n this._readableState.buffer.clear();\n\n if (content !== '') this._readableState.buffer.push(content);\n this._readableState.length = content.length;\n return this;\n}; // Don't raise the hwm > 1GB\n\n\nvar MAX_HWM = 0x40000000;\n\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n\n return n;\n} // This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\n\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n } // If we're asking for more than the current hwm, then raise the hwm.\n\n\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n; // Don't have enough\n\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n\n return state.length;\n} // you can override either this method, or the async _read(n) below.\n\n\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n\n if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.\n\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n } // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n // if we need a readable event, then we need to do some reading.\n\n\n var doRead = state.needReadable;\n debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some\n\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n } // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n\n\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true; // if the length is currently zero, then we *need* a readable event.\n\n if (state.length === 0) state.needReadable = true; // call internal read method\n\n this._read(state.highWaterMark);\n\n state.sync = false; // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark;\n n = 0;\n } else {\n state.length -= n;\n state.awaitDrain = 0;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.\n\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n debug('onEofChunk');\n if (state.ended) return;\n\n if (state.decoder) {\n var chunk = state.decoder.end();\n\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n\n state.ended = true;\n\n if (state.sync) {\n // if we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call\n emitReadable(stream);\n } else {\n // emit 'readable' now to make sure it gets picked up.\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n state.emittedReadable = true;\n emitReadable_(stream);\n }\n }\n} // Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\n\n\nfunction emitReadable(stream) {\n var state = stream._readableState;\n debug('emitReadable', state.needReadable, state.emittedReadable);\n state.needReadable = false;\n\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n process.nextTick(emitReadable_, stream);\n }\n}\n\nfunction emitReadable_(stream) {\n var state = stream._readableState;\n debug('emitReadable_', state.destroyed, state.length, state.ended);\n\n if (!state.destroyed && (state.length || state.ended)) {\n stream.emit('readable');\n state.emittedReadable = false;\n } // The stream needs another readable event if\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n\n\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;\n flow(stream);\n} // at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\n\n\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n process.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {\n var len = state.length;\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length) // didn't get any data, stop spinning.\n break;\n }\n\n state.readingMore = false;\n} // abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\n\n\nReadable.prototype._read = function (n) {\n errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n\n default:\n state.pipes.push(dest);\n break;\n }\n\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);\n dest.on('unpipe', onunpipe);\n\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n } // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n\n\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n var cleanedUp = false;\n\n function cleanup() {\n debug('cleanup'); // cleanup event handlers once the pipe is broken\n\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n cleanedUp = true; // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n src.on('data', ondata);\n\n function ondata(chunk) {\n debug('ondata');\n var ret = dest.write(chunk);\n debug('dest.write', ret);\n\n if (ret === false) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n }\n\n src.pause();\n }\n } // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n\n\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);\n } // Make sure our error handler is attached before userland ones.\n\n\n prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.\n\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n\n dest.once('close', onclose);\n\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n } // tell the dest that it's being piped to\n\n\n dest.emit('pipe', src); // start the flow if it hasn't been started already.\n\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function pipeOnDrainFunctionResult() {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = {\n hasUnpiped: false\n }; // if we're not piping anywhere, then do nothing.\n\n if (state.pipesCount === 0) return this; // just one destination. most common case.\n\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n if (!dest) dest = state.pipes; // got a match.\n\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n } // slow case. multiple pipe destinations.\n\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n });\n }\n\n return this;\n } // try to find the right one.\n\n\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n dest.emit('unpipe', this, unpipeInfo);\n return this;\n}; // set up data events if they are asked for\n// Ensure readable listeners eventually get something\n\n\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n var state = this._readableState;\n\n if (ev === 'data') {\n // update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused\n\n if (state.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.flowing = false;\n state.emittedReadable = false;\n debug('on readable', state.length, state.reading);\n\n if (state.length) {\n emitReadable(this);\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this);\n }\n }\n }\n\n return res;\n};\n\nReadable.prototype.addListener = Readable.prototype.on;\n\nReadable.prototype.removeListener = function (ev, fn) {\n var res = Stream.prototype.removeListener.call(this, ev, fn);\n\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nReadable.prototype.removeAllListeners = function (ev) {\n var res = Stream.prototype.removeAllListeners.apply(this, arguments);\n\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this);\n }\n\n return res;\n};\n\nfunction updateReadableListening(self) {\n var state = self._readableState;\n state.readableListening = self.listenerCount('readable') > 0;\n\n if (state.resumeScheduled && !state.paused) {\n // flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true; // crude way to check if we should resume\n } else if (self.listenerCount('data') > 0) {\n self.resume();\n }\n}\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n} // pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\n\n\nReadable.prototype.resume = function () {\n var state = this._readableState;\n\n if (!state.flowing) {\n debug('resume'); // we flow only if there is no one listening\n // for readable, but we still have to call\n // resume()\n\n state.flowing = !state.readableListening;\n resume(this, state);\n }\n\n state.paused = false;\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n process.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n debug('resume', state.reading);\n\n if (!state.reading) {\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n\n if (this._readableState.flowing !== false) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n\n this._readableState.paused = true;\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n\n while (state.flowing && stream.read() !== null) {\n ;\n }\n} // wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\n\n\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n stream.on('end', function () {\n debug('wrapped end');\n\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode\n\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n\n if (!ret) {\n paused = true;\n stream.pause();\n }\n }); // proxy all the other methods.\n // important when wrapping filters and duplexes.\n\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function methodWrap(method) {\n return function methodWrapReturnFunction() {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n } // proxy certain important events.\n\n\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n } // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n\n\n this._read = function (n) {\n debug('wrapped _read', n);\n\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nif (typeof Symbol === 'function') {\n Readable.prototype[Symbol.asyncIterator] = function () {\n if (createReadableStreamAsyncIterator === undefined) {\n createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');\n }\n\n return createReadableStreamAsyncIterator(this);\n };\n}\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.highWaterMark;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState && this._readableState.buffer;\n }\n});\nObject.defineProperty(Readable.prototype, 'readableFlowing', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.flowing;\n },\n set: function set(state) {\n if (this._readableState) {\n this._readableState.flowing = state;\n }\n }\n}); // exposed for testing purposes only.\n\nReadable._fromList = fromList;\nObject.defineProperty(Readable.prototype, 'readableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._readableState.length;\n }\n}); // Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\n\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = state.buffer.consume(n, state.decoder);\n }\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n debug('endReadable', state.endEmitted);\n\n if (!state.endEmitted) {\n state.ended = true;\n process.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.\n\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well\n var wState = stream._writableState;\n\n if (!wState || wState.autoDestroy && wState.finished) {\n stream.destroy();\n }\n }\n }\n}\n\nif (typeof Symbol === 'function') {\n Readable.from = function (iterable, opts) {\n if (from === undefined) {\n from = require('./internal/streams/from');\n }\n\n return from(Readable, iterable, opts);\n };\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n\n return -1;\n}","module.exports = require('stream');\n","'use strict'; // undocumented cb() API, needed for core, not for public API\n\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n process.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n process.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n } // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n } // if this is a duplex stream mark the writable part as destroyed as well\n\n\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n process.nextTick(emitErrorAndCloseNT, _this, err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n } else if (cb) {\n process.nextTick(emitCloseNT, _this);\n cb(err);\n } else {\n process.nextTick(emitCloseNT, _this);\n }\n });\n\n return this;\n}\n\nfunction emitErrorAndCloseNT(self, err) {\n emitErrorNT(self, err);\n emitCloseNT(self);\n}\n\nfunction emitCloseNT(self) {\n if (self._writableState && !self._writableState.emitClose) return;\n if (self._readableState && !self._readableState.emitClose) return;\n self.emit('close');\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nfunction errorOrDestroy(stream, err) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n var rState = stream._readableState;\n var wState = stream._writableState;\n if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy,\n errorOrDestroy: errorOrDestroy\n};","'use strict';\n\nvar ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;\n\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;\n}\n\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);\n\n if (hwm != null) {\n if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {\n var name = isDuplex ? duplexKey : 'highWaterMark';\n throw new ERR_INVALID_OPT_VALUE(name, hwm);\n }\n\n return Math.floor(hwm);\n } // Default value\n\n\n return state.objectMode ? 16 : 16 * 1024;\n}\n\nmodule.exports = {\n getHighWaterMark: getHighWaterMark\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n'use strict';\n\nmodule.exports = Writable;\n/* */\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n} // It seems a linked list but it is not\n// there will be only 2 of these for each stream\n\n\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\n\n\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n/**/\n\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\n\nvar Stream = require('./internal/streams/stream');\n/**/\n\n\nvar Buffer = require('buffer').Buffer;\n\nvar OurUint8Array = global.Uint8Array || function () {};\n\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\n\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nvar _require = require('./internal/streams/state'),\n getHighWaterMark = _require.getHighWaterMark;\n\nvar _require$codes = require('../errors').codes,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,\n ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;\n\nvar errorOrDestroy = destroyImpl.errorOrDestroy;\n\nrequire('inherits')(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream, isDuplex) {\n Duplex = Duplex || require('./_stream_duplex');\n options = options || {}; // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n\n this.objectMode = !!options.objectMode;\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n\n this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called\n\n this.finalCalled = false; // drain event flag.\n\n this.needDrain = false; // at the start of calling end()\n\n this.ending = false; // when end() has been called, and returned\n\n this.ended = false; // when 'finish' is emitted\n\n this.finished = false; // has it been destroyed\n\n this.destroyed = false; // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n\n this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n\n this.length = 0; // a flag to see when we're in the middle of a write.\n\n this.writing = false; // when true all writes will be buffered until .uncork() call\n\n this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n\n this.sync = true; // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n\n this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)\n\n this.onwrite = function (er) {\n onwrite(stream, er);\n }; // the callback that the user supplies to write(chunk,encoding,cb)\n\n\n this.writecb = null; // the amount that is being written when _write is called.\n\n this.writelen = 0;\n this.bufferedRequest = null;\n this.lastBufferedRequest = null; // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n\n this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n\n this.prefinished = false; // True if the error was already emitted and should not be thrown again\n\n this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.\n\n this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')\n\n this.autoDestroy = !!options.autoDestroy; // count buffered requests\n\n this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n\n while (current) {\n out.push(current);\n current = current.next;\n }\n\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function writableStateBufferGetter() {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})(); // Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\n\n\nvar realHasInstance;\n\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function value(object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function realHasInstance(object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5\n\n var isDuplex = this instanceof Duplex;\n if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);\n this._writableState = new WritableState(options, this, isDuplex); // legacy.\n\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n if (typeof options.writev === 'function') this._writev = options.writev;\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n} // Otherwise people can pipe Writable streams, which is just wrong.\n\n\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb\n\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n} // Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\n\n\nfunction validChunk(stream, state, chunk, cb) {\n var er;\n\n if (chunk === null) {\n er = new ERR_STREAM_NULL_VALUES();\n } else if (typeof chunk !== 'string' && !state.objectMode) {\n er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);\n }\n\n if (er) {\n errorOrDestroy(stream, er);\n process.nextTick(cb, er);\n return false;\n }\n\n return true;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n if (typeof cb !== 'function') cb = nop;\n if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n return ret;\n};\n\nWritable.prototype.cork = function () {\n this._writableState.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n 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);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableBuffer', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState && this._writableState.getBuffer();\n }\n});\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.highWaterMark;\n }\n}); // if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\n\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n\n var len = state.objectMode ? 1 : chunk.length;\n state.length += len;\n var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.\n\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n 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);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n process.nextTick(cb, er); // this can emit finish, and it will always happen\n // after error\n\n process.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n errorOrDestroy(stream, er); // this can emit finish, but finish must\n // always follow error\n\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();\n onwriteStateUpdate(state);\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state) || stream.destroyed;\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n process.nextTick(afterWrite, stream, state, finished, cb);\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n} // Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\n\n\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n} // if there's something in the buffer waiting, then process it\n\n\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n var count = 0;\n var allBuffers = true;\n\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n\n buffer.allBuffers = allBuffers;\n doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n\n state.pendingcb++;\n state.lastBufferedRequest = null;\n\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks\n\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n } // ignore unnecessary end() calls.\n\n\n if (!state.ending) endWritable(this, state, cb);\n return this;\n};\n\nObject.defineProperty(Writable.prototype, 'writableLength', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n return this._writableState.length;\n }\n});\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n\n if (err) {\n errorOrDestroy(stream, err);\n }\n\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.pendingcb++;\n state.finalCalled = true;\n process.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n\n if (need) {\n prefinish(stream, state);\n\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well\n var rState = stream._readableState;\n\n if (!rState || rState.autoDestroy && rState.endEmitted) {\n stream.destroy();\n }\n }\n }\n }\n\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n\n if (cb) {\n if (state.finished) process.nextTick(cb);else stream.once('finish', cb);\n }\n\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n } // reuse the free corkReq.\n\n\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function get() {\n if (this._writableState === undefined) {\n return false;\n }\n\n return this._writableState.destroyed;\n },\n set: function set(value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n } // backward compatibility, the user is explicitly\n // managing destroyed\n\n\n this._writableState.destroyed = value;\n }\n});\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\n\nWritable.prototype._destroy = function (err, cb) {\n cb(err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n'use strict';\n\nmodule.exports = Transform;\n\nvar _require$codes = require('../errors').codes,\n ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,\n ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,\n ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;\n\nvar Duplex = require('./_stream_duplex');\n\nrequire('inherits')(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n var cb = ts.writecb;\n\n if (cb === null) {\n return this.emit('error', new ERR_MULTIPLE_CALLBACK());\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n cb(er);\n var rs = this._readableState;\n rs.reading = false;\n\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n Duplex.call(this, options);\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n }; // start out asking for a readable event once data is transformed.\n\n this._readableState.needReadable = true; // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n if (typeof options.flush === 'function') this._flush = options.flush;\n } // When the writable side finishes, then flush out anything remaining.\n\n\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function' && !this._readableState.destroyed) {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n}; // This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\n\n\nTransform.prototype._transform = function (chunk, encoding, cb) {\n cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n}; // Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\n\n\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && !ts.transforming) {\n ts.transforming = true;\n\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data); // TODO(BridgeAR): Write a test for these two error cases\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n\n if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();\n if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();\n return stream.push(null);\n}","'use strict';\n\nconst isStream = stream =>\n\tstream !== null &&\n\ttypeof stream === 'object' &&\n\ttypeof stream.pipe === 'function';\n\nisStream.writable = stream =>\n\tisStream(stream) &&\n\tstream.writable !== false &&\n\ttypeof stream._write === 'function' &&\n\ttypeof stream._writableState === 'object';\n\nisStream.readable = stream =>\n\tisStream(stream) &&\n\tstream.readable !== false &&\n\ttypeof stream._read === 'function' &&\n\ttypeof stream._readableState === 'object';\n\nisStream.duplex = stream =>\n\tisStream.writable(stream) &&\n\tisStream.readable(stream);\n\nisStream.transform = stream =>\n\tisStream.duplex(stream) &&\n\ttypeof stream._transform === 'function';\n\nmodule.exports = isStream;\n","/**\n * create-logger.js: Logger factory for winston logger instances.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst { LEVEL } = require('triple-beam');\nconst config = require('./config');\nconst Logger = require('./logger');\nconst debug = require('@dabh/diagnostics')('winston:create-logger');\n\nfunction isLevelEnabledFunctionName(level) {\n return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled';\n}\n\n/**\n * Create a new instance of a winston Logger. Creates a new\n * prototype for each instance.\n * @param {!Object} opts - Options for the created logger.\n * @returns {Logger} - A newly created logger instance.\n */\nmodule.exports = function (opts = {}) {\n //\n // Default levels: npm\n //\n opts.levels = opts.levels || config.npm.levels;\n\n /**\n * DerivedLogger to attach the logs level methods.\n * @type {DerivedLogger}\n * @extends {Logger}\n */\n class DerivedLogger extends Logger {\n /**\n * Create a new class derived logger for which the levels can be attached to\n * the prototype of. This is a V8 optimization that is well know to increase\n * performance of prototype functions.\n * @param {!Object} options - Options for the created logger.\n */\n constructor(options) {\n super(options);\n }\n }\n\n const logger = new DerivedLogger(opts);\n\n //\n // Create the log level methods for the derived logger.\n //\n Object.keys(opts.levels).forEach(function (level) {\n debug('Define prototype method for \"%s\"', level);\n if (level === 'log') {\n // eslint-disable-next-line no-console\n console.warn('Level \"log\" not defined: conflicts with the method \"log\". Use a different level name.');\n return;\n }\n\n //\n // Define prototype methods for each log level e.g.:\n // logger.log('info', msg) implies these methods are defined:\n // - logger.info(msg)\n // - logger.isInfoEnabled()\n //\n // Remark: to support logger.child this **MUST** be a function\n // so it'll always be called on the instance instead of a fixed\n // place in the prototype chain.\n //\n DerivedLogger.prototype[level] = function (...args) {\n // Prefer any instance scope, but default to \"root\" logger\n const self = this || logger;\n\n // Optimize the hot-path which is the single object.\n if (args.length === 1) {\n const [msg] = args;\n const info = msg && msg.message && msg || { message: msg };\n info.level = info[LEVEL] = level;\n self._addDefaultMeta(info);\n self.write(info);\n return (this || logger);\n }\n\n // When provided nothing assume the empty string\n if (args.length === 0) {\n self.log(level, '');\n return self;\n }\n\n // Otherwise build argument list which could potentially conform to\n // either:\n // . v3 API: log(obj)\n // 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback])\n return self.log(level, ...args);\n };\n\n DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () {\n return (this || logger).isLevelEnabled(level);\n };\n });\n\n return logger;\n};\n","/**\n * exception-handler.js: Object for handling uncaughtException events.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst os = require('os');\nconst asyncForEach = require('async/forEach');\nconst debug = require('@dabh/diagnostics')('winston:exception');\nconst once = require('one-time');\nconst stackTrace = require('stack-trace');\nconst ExceptionStream = require('./exception-stream');\n\n/**\n * Object for handling uncaughtException events.\n * @type {ExceptionHandler}\n */\nmodule.exports = class ExceptionHandler {\n /**\n * TODO: add contructor description\n * @param {!Logger} logger - TODO: add param description\n */\n constructor(logger) {\n if (!logger) {\n throw new Error('Logger is required to handle exceptions');\n }\n\n this.logger = logger;\n this.handlers = new Map();\n }\n\n /**\n * Handles `uncaughtException` events for the current process by adding any\n * handlers passed in.\n * @returns {undefined}\n */\n handle(...args) {\n args.forEach(arg => {\n if (Array.isArray(arg)) {\n return arg.forEach(handler => this._addHandler(handler));\n }\n\n this._addHandler(arg);\n });\n\n if (!this.catcher) {\n this.catcher = this._uncaughtException.bind(this);\n process.on('uncaughtException', this.catcher);\n }\n }\n\n /**\n * Removes any handlers to `uncaughtException` events for the current\n * process. This does not modify the state of the `this.handlers` set.\n * @returns {undefined}\n */\n unhandle() {\n if (this.catcher) {\n process.removeListener('uncaughtException', this.catcher);\n this.catcher = false;\n\n Array.from(this.handlers.values())\n .forEach(wrapper => this.logger.unpipe(wrapper));\n }\n }\n\n /**\n * TODO: add method description\n * @param {Error} err - Error to get information about.\n * @returns {mixed} - TODO: add return description.\n */\n getAllInfo(err) {\n let { message } = err;\n if (!message && typeof err === 'string') {\n message = err;\n }\n\n return {\n error: err,\n // TODO (indexzero): how do we configure this?\n level: 'error',\n message: [\n `uncaughtException: ${(message || '(no error message)')}`,\n err.stack || ' No stack trace'\n ].join('\\n'),\n stack: err.stack,\n exception: true,\n date: new Date().toString(),\n process: this.getProcessInfo(),\n os: this.getOsInfo(),\n trace: this.getTrace(err)\n };\n }\n\n /**\n * Gets all relevant process information for the currently running process.\n * @returns {mixed} - TODO: add return description.\n */\n getProcessInfo() {\n return {\n pid: process.pid,\n uid: process.getuid ? process.getuid() : null,\n gid: process.getgid ? process.getgid() : null,\n cwd: process.cwd(),\n execPath: process.execPath,\n version: process.version,\n argv: process.argv,\n memoryUsage: process.memoryUsage()\n };\n }\n\n /**\n * Gets all relevant OS information for the currently running process.\n * @returns {mixed} - TODO: add return description.\n */\n getOsInfo() {\n return {\n loadavg: os.loadavg(),\n uptime: os.uptime()\n };\n }\n\n /**\n * Gets a stack trace for the specified error.\n * @param {mixed} err - TODO: add param description.\n * @returns {mixed} - TODO: add return description.\n */\n getTrace(err) {\n const trace = err ? stackTrace.parse(err) : stackTrace.get();\n return trace.map(site => {\n return {\n column: site.getColumnNumber(),\n file: site.getFileName(),\n function: site.getFunctionName(),\n line: site.getLineNumber(),\n method: site.getMethodName(),\n native: site.isNative()\n };\n });\n }\n\n /**\n * Helper method to add a transport as an exception handler.\n * @param {Transport} handler - The transport to add as an exception handler.\n * @returns {void}\n */\n _addHandler(handler) {\n if (!this.handlers.has(handler)) {\n handler.handleExceptions = true;\n const wrapper = new ExceptionStream(handler);\n this.handlers.set(handler, wrapper);\n this.logger.pipe(wrapper);\n }\n }\n\n /**\n * Logs all relevant information around the `err` and exits the current\n * process.\n * @param {Error} err - Error to handle\n * @returns {mixed} - TODO: add return description.\n * @private\n */\n _uncaughtException(err) {\n const info = this.getAllInfo(err);\n const handlers = this._getExceptionHandlers();\n // Calculate if we should exit on this error\n let doExit = typeof this.logger.exitOnError === 'function'\n ? this.logger.exitOnError(err)\n : this.logger.exitOnError;\n let timeout;\n\n if (!handlers.length && doExit) {\n // eslint-disable-next-line no-console\n console.warn('winston: exitOnError cannot be true with no exception handlers.');\n // eslint-disable-next-line no-console\n console.warn('winston: not exiting process.');\n doExit = false;\n }\n\n function gracefulExit() {\n debug('doExit', doExit);\n debug('process._exiting', process._exiting);\n\n if (doExit && !process._exiting) {\n // Remark: Currently ignoring any exceptions from transports when\n // catching uncaught exceptions.\n if (timeout) {\n clearTimeout(timeout);\n }\n // eslint-disable-next-line no-process-exit\n process.exit(1);\n }\n }\n\n if (!handlers || handlers.length === 0) {\n return process.nextTick(gracefulExit);\n }\n\n // Log to all transports attempting to listen for when they are completed.\n asyncForEach(handlers, (handler, next) => {\n const done = once(next);\n const transport = handler.transport || handler;\n\n // Debug wrapping so that we can inspect what's going on under the covers.\n function onDone(event) {\n return () => {\n debug(event);\n done();\n };\n }\n\n transport._ending = true;\n transport.once('finish', onDone('finished'));\n transport.once('error', onDone('error'));\n }, () => doExit && gracefulExit());\n\n this.logger.log(info);\n\n // If exitOnError is true, then only allow the logging of exceptions to\n // take up to `3000ms`.\n if (doExit) {\n timeout = setTimeout(gracefulExit, 3000);\n }\n }\n\n /**\n * Returns the list of transports and exceptionHandlers for this instance.\n * @returns {Array} - List of transports and exceptionHandlers for this\n * instance.\n * @private\n */\n _getExceptionHandlers() {\n // Remark (indexzero): since `logger.transports` returns all of the pipes\n // from the _readableState of the stream we actually get the join of the\n // explicit handlers and the implicit transports with\n // `handleExceptions: true`\n return this.logger.transports.filter(wrap => {\n const transport = wrap.transport || wrap;\n return transport.handleExceptions;\n });\n }\n};\n","'use strict';\n\nvar name = require('fn.name');\n\n/**\n * Wrap callbacks to prevent double execution.\n *\n * @param {Function} fn Function that should only be called once.\n * @returns {Function} A wrapped callback which prevents multiple executions.\n * @public\n */\nmodule.exports = function one(fn) {\n var called = 0\n , value;\n\n /**\n * The function that prevents double execution.\n *\n * @private\n */\n function onetime() {\n if (called) return value;\n\n called = 1;\n value = fn.apply(this, arguments);\n fn = null;\n\n return value;\n }\n\n //\n // To make debugging more easy we want to use the name of the supplied\n // function. So when you look at the functions that are assigned to event\n // listeners you don't see a load of `onetime` functions but actually the\n // names of the functions that this module will call.\n //\n // NOTE: We cannot override the `name` property, as that is `readOnly`\n // property, so displayName will have to do.\n //\n onetime.displayName = name(fn);\n return onetime;\n};\n","exports.get = function(belowFn) {\n var oldLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = Infinity;\n\n var dummyObject = {};\n\n var v8Handler = Error.prepareStackTrace;\n Error.prepareStackTrace = function(dummyObject, v8StackTrace) {\n return v8StackTrace;\n };\n Error.captureStackTrace(dummyObject, belowFn || exports.get);\n\n var v8StackTrace = dummyObject.stack;\n Error.prepareStackTrace = v8Handler;\n Error.stackTraceLimit = oldLimit;\n\n return v8StackTrace;\n};\n\nexports.parse = function(err) {\n if (!err.stack) {\n return [];\n }\n\n var self = this;\n var lines = err.stack.split('\\n').slice(1);\n\n return lines\n .map(function(line) {\n if (line.match(/^\\s*[-]{4,}$/)) {\n return self._createParsedCallSite({\n fileName: line,\n lineNumber: null,\n functionName: null,\n typeName: null,\n methodName: null,\n columnNumber: null,\n 'native': null,\n });\n }\n\n var lineMatch = line.match(/at (?:(.+)\\s+\\()?(?:(.+?):(\\d+)(?::(\\d+))?|([^)]+))\\)?/);\n if (!lineMatch) {\n return;\n }\n\n var object = null;\n var method = null;\n var functionName = null;\n var typeName = null;\n var methodName = null;\n var isNative = (lineMatch[5] === 'native');\n\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n var methodStart = functionName.lastIndexOf('.');\n if (functionName[methodStart-1] == '.')\n methodStart--;\n if (methodStart > 0) {\n object = functionName.substr(0, methodStart);\n method = functionName.substr(methodStart + 1);\n var objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.substr(objectEnd + 1);\n object = object.substr(0, objectEnd);\n }\n }\n typeName = null;\n }\n\n if (method) {\n typeName = object;\n methodName = method;\n }\n\n if (method === '') {\n methodName = null;\n functionName = null;\n }\n\n var properties = {\n fileName: lineMatch[2] || null,\n lineNumber: parseInt(lineMatch[3], 10) || null,\n functionName: functionName,\n typeName: typeName,\n methodName: methodName,\n columnNumber: parseInt(lineMatch[4], 10) || null,\n 'native': isNative,\n };\n\n return self._createParsedCallSite(properties);\n })\n .filter(function(callSite) {\n return !!callSite;\n });\n};\n\nfunction CallSite(properties) {\n for (var property in properties) {\n this[property] = properties[property];\n }\n}\n\nvar strProperties = [\n 'this',\n 'typeName',\n 'functionName',\n 'methodName',\n 'fileName',\n 'lineNumber',\n 'columnNumber',\n 'function',\n 'evalOrigin'\n];\nvar boolProperties = [\n 'topLevel',\n 'eval',\n 'native',\n 'constructor'\n];\nstrProperties.forEach(function (property) {\n CallSite.prototype[property] = null;\n CallSite.prototype['get' + property[0].toUpperCase() + property.substr(1)] = function () {\n return this[property];\n }\n});\nboolProperties.forEach(function (property) {\n CallSite.prototype[property] = false;\n CallSite.prototype['is' + property[0].toUpperCase() + property.substr(1)] = function () {\n return this[property];\n }\n});\n\nexports._createParsedCallSite = function(properties) {\n return new CallSite(properties);\n};\n","/**\n * exception-stream.js: TODO: add file header handler.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst { Writable } = require('readable-stream');\n\n/**\n * TODO: add class description.\n * @type {ExceptionStream}\n * @extends {Writable}\n */\nmodule.exports = class ExceptionStream extends Writable {\n /**\n * Constructor function for the ExceptionStream responsible for wrapping a\n * TransportStream; only allowing writes of `info` objects with\n * `info.exception` set to true.\n * @param {!TransportStream} transport - Stream to filter to exceptions\n */\n constructor(transport) {\n super({ objectMode: true });\n\n if (!transport) {\n throw new Error('ExceptionStream requires a TransportStream instance.');\n }\n\n // Remark (indexzero): we set `handleExceptions` here because it's the\n // predicate checked in ExceptionHandler.prototype.__getExceptionHandlers\n this.handleExceptions = true;\n this.transport = transport;\n }\n\n /**\n * Writes the info object to our transport instance if (and only if) the\n * `exception` property is set on the info.\n * @param {mixed} info - TODO: add param description.\n * @param {mixed} enc - TODO: add param description.\n * @param {mixed} callback - TODO: add param description.\n * @returns {mixed} - TODO: add return description.\n * @private\n */\n _write(info, enc, callback) {\n if (info.exception) {\n return this.transport.log(info, callback);\n }\n\n callback();\n return true;\n }\n};\n","/**\n * exception-handler.js: Object for handling uncaughtException events.\n *\n * (C) 2010 Charlie Robbins\n * MIT LICENCE\n */\n\n'use strict';\n\nconst os = require('os');\nconst asyncForEach = require('async/forEach');\nconst debug = require('@dabh/diagnostics')('winston:rejection');\nconst once = require('one-time');\nconst stackTrace = require('stack-trace');\nconst ExceptionStream = require('./exception-stream');\n\n/**\n * Object for handling unhandledRejection events.\n * @type {RejectionHandler}\n */\nmodule.exports = class RejectionHandler {\n /**\n * TODO: add contructor description\n * @param {!Logger} logger - TODO: add param description\n */\n constructor(logger) {\n if (!logger) {\n throw new Error('Logger is required to handle rejections');\n }\n\n this.logger = logger;\n this.handlers = new Map();\n }\n\n /**\n * Handles `unhandledRejection` events for the current process by adding any\n * handlers passed in.\n * @returns {undefined}\n */\n handle(...args) {\n args.forEach(arg => {\n if (Array.isArray(arg)) {\n return arg.forEach(handler => this._addHandler(handler));\n }\n\n this._addHandler(arg);\n });\n\n if (!this.catcher) {\n this.catcher = this._unhandledRejection.bind(this);\n process.on('unhandledRejection', this.catcher);\n }\n }\n\n /**\n * Removes any handlers to `unhandledRejection` events for the current\n * process. This does not modify the state of the `this.handlers` set.\n * @returns {undefined}\n */\n unhandle() {\n if (this.catcher) {\n process.removeListener('unhandledRejection', this.catcher);\n this.catcher = false;\n\n Array.from(this.handlers.values()).forEach(wrapper =>\n this.logger.unpipe(wrapper)\n );\n }\n }\n\n /**\n * TODO: add method description\n * @param {Error} err - Error to get information about.\n * @returns {mixed} - TODO: add return description.\n */\n getAllInfo(err) {\n let { message } = err;\n if (!message && typeof err === 'string') {\n message = err;\n }\n\n return {\n error: err,\n // TODO (indexzero): how do we configure this?\n level: 'error',\n message: [\n `unhandledRejection: ${message || '(no error message)'}`,\n err.stack || ' No stack trace'\n ].join('\\n'),\n stack: err.stack,\n exception: true,\n date: new Date().toString(),\n process: this.getProcessInfo(),\n os: this.getOsInfo(),\n trace: this.getTrace(err)\n };\n }\n\n /**\n * Gets all relevant process information for the currently running process.\n * @returns {mixed} - TODO: add return description.\n */\n getProcessInfo() {\n return {\n pid: process.pid,\n uid: process.getuid ? process.getuid() : null,\n gid: process.getgid ? process.getgid() : null,\n cwd: process.cwd(),\n execPath: process.execPath,\n version: process.version,\n argv: process.argv,\n memoryUsage: process.memoryUsage()\n };\n }\n\n /**\n * Gets all relevant OS information for the currently running process.\n * @returns {mixed} - TODO: add return description.\n */\n getOsInfo() {\n return {\n loadavg: os.loadavg(),\n uptime: os.uptime()\n };\n }\n\n /**\n * Gets a stack trace for the specified error.\n * @param {mixed} err - TODO: add param description.\n * @returns {mixed} - TODO: add return description.\n */\n getTrace(err) {\n const trace = err ? stackTrace.parse(err) : stackTrace.get();\n return trace.map(site => {\n return {\n column: site.getColumnNumber(),\n file: site.getFileName(),\n function: site.getFunctionName(),\n line: site.getLineNumber(),\n method: site.getMethodName(),\n native: site.isNative()\n };\n });\n }\n\n /**\n * Helper method to add a transport as an exception handler.\n * @param {Transport} handler - The transport to add as an exception handler.\n * @returns {void}\n */\n _addHandler(handler) {\n if (!this.handlers.has(handler)) {\n handler.handleRejections = true;\n const wrapper = new ExceptionStream(handler);\n this.handlers.set(handler, wrapper);\n this.logger.pipe(wrapper);\n }\n }\n\n /**\n * Logs all relevant information around the `err` and exits the current\n * process.\n * @param {Error} err - Error to handle\n * @returns {mixed} - TODO: add return description.\n * @private\n */\n _unhandledRejection(err) {\n const info = this.getAllInfo(err);\n const handlers = this._getRejectionHandlers();\n // Calculate if we should exit on this error\n let doExit =\n typeof this.logger.exitOnError === 'function'\n ? this.logger.exitOnError(err)\n : this.logger.exitOnError;\n let timeout;\n\n if (!handlers.length && doExit) {\n // eslint-disable-next-line no-console\n console.warn('winston: exitOnError cannot be true with no rejection handlers.');\n // eslint-disable-next-line no-console\n console.warn('winston: not exiting process.');\n doExit = false;\n }\n\n function gracefulExit() {\n debug('doExit', doExit);\n debug('process._exiting', process._exiting);\n\n if (doExit && !process._exiting) {\n // Remark: Currently ignoring any rejections from transports when\n // catching unhandled rejections.\n if (timeout) {\n clearTimeout(timeout);\n }\n // eslint-disable-next-line no-process-exit\n process.exit(1);\n }\n }\n\n if (!handlers || handlers.length === 0) {\n return process.nextTick(gracefulExit);\n }\n\n // Log to all transports attempting to listen for when they are completed.\n asyncForEach(\n handlers,\n (handler, next) => {\n const done = once(next);\n const transport = handler.transport || handler;\n\n // Debug wrapping so that we can inspect what's going on under the covers.\n function onDone(event) {\n return () => {\n debug(event);\n done();\n };\n }\n\n transport._ending = true;\n transport.once('finish', onDone('finished'));\n transport.once('error', onDone('error'));\n },\n () => doExit && gracefulExit()\n );\n\n this.logger.log(info);\n\n // If exitOnError is true, then only allow the logging of exceptions to\n // take up to `3000ms`.\n if (doExit) {\n timeout = setTimeout(gracefulExit, 3000);\n }\n }\n\n /**\n * Returns the list of transports and exceptionHandlers for this instance.\n * @returns {Array} - List of transports and exceptionHandlers for this\n * instance.\n * @private\n */\n _getRejectionHandlers() {\n // Remark (indexzero): since `logger.transports` returns all of the pipes\n // from the _readableState of the stream we actually get the join of the\n // explicit handlers and the implicit transports with\n // `handleRejections: true`\n return this.logger.transports.filter(wrap => {\n const transport = wrap.transport || wrap;\n return transport.handleRejections;\n });\n }\n};\n","import { config } from '../server';\nimport DbInterface from '../db/db_wrapper';\n\nconst genNumber = (length: number): string => {\n const addAmount = 1;\n let localMax = 11;\n\n if (length > localMax) {\n return genNumber(localMax) + genNumber(length - localMax);\n }\n\n localMax = Math.pow(10, length + addAmount);\n const min = localMax / 10;\n const number = Math.floor(Math.random() * (localMax - min + 1)) + min;\n\n const strNumber = '' + number;\n\n return strNumber.substr(addAmount);\n};\n\nconst generateUsNumber = (): string => {\n const rawNumber = genNumber(10);\n return rawNumber.replace(/(\\d{3})(\\d{3})(\\d{4})/, '$1-$2-$3');\n};\n\n/**/\nexport async function generateUniquePhoneNumber(): Promise {\n const query = `SELECT EXISTS(SELECT * FROM ${config.database.playerTable} WHERE ${config.database.phoneNumberColumn} = ?)`;\n const dashNumber = generateUsNumber();\n\n const [results] = await DbInterface._rawExec(query, dashNumber);\n\n if (!results) return generateUniquePhoneNumber();\n\n return dashNumber;\n}\n","var h=Object.defineProperty;var r=(u,e)=>h(u,\"name\",{value:e,configurable:!0});var o=class extends Map{get(e){return super.get(e)}set(e,i){return super.set(e,i)}has(e){return super.has(e)}delete(e){return super.delete(e)}clear(){return super.clear()}hasAll(...e){return e.every(i=>super.has(i))}hasAny(...e){return e.some(i=>super.has(i))}first(e){if(typeof e==\"undefined\")return this.values().next().value;if(e<0)return this.last(e*-1);e=Math.min(this.size,e);let i=this.values();return Array.from({length:e},()=>i.next().value)}firstKey(e){if(typeof e==\"undefined\")return this.keys().next().value;if(e<0)return this.lastKey(e*-1);e=Math.min(this.size,e);let i=this.keys();return Array.from({length:e},()=>i.next().value)}last(e){let i=[...this.values()];return typeof e==\"undefined\"?i[i.length-1]:e<0?this.first(e*-1):e?i.slice(-e):[]}lastKey(e){let i=[...this.keys()];return typeof e==\"undefined\"?i[i.length-1]:e<0?this.firstKey(e*-1):e?i.slice(-e):[]}random(e){let i=[...this.values()];return typeof e==\"undefined\"?i[Math.floor(Math.random()*i.length)]:!i.length||!e?[]:Array.from({length:Math.min(e,i.length)},()=>i.splice(Math.floor(Math.random()*i.length),1)[0])}randomKey(e){let i=[...this.keys()];return typeof e==\"undefined\"?i[Math.floor(Math.random()*i.length)]:!i.length||!e?[]:Array.from({length:Math.min(e,i.length)},()=>i.splice(Math.floor(Math.random()*i.length),1)[0])}find(e,i){typeof i!=\"undefined\"&&(e=e.bind(i));for(let[t,l]of this)if(e(l,t,this))return l}findKey(e,i){typeof i!=\"undefined\"&&(e=e.bind(i));for(let[t,l]of this)if(e(l,t,this))return t}sweep(e,i){typeof i!=\"undefined\"&&(e=e.bind(i));let t=this.size;for(let[l,n]of this)e(n,l,this)&&this.delete(l);return t-this.size}filter(e,i){typeof i!=\"undefined\"&&(e=e.bind(i));let t=new this.constructor[Symbol.species];for(let[l,n]of this)e(n,l,this)&&t.set(l,n);return t}partition(e,i){typeof i!=\"undefined\"&&(e=e.bind(i));let t=[new this.constructor[Symbol.species],new this.constructor[Symbol.species]];for(let[l,n]of this)e(n,l,this)?t[0].set(l,n):t[1].set(l,n);return t}flatMap(e,i){let t=this.map(e,i);return new this.constructor[Symbol.species]().concat(...t)}map(e,i){typeof i!=\"undefined\"&&(e=e.bind(i));let t=this.entries();return Array.from({length:this.size},()=>{let[l,n]=t.next().value;return e(n,l,this)})}mapValues(e,i){typeof i!=\"undefined\"&&(e=e.bind(i));let t=new this.constructor[Symbol.species];for(let[l,n]of this)t.set(l,e(n,l,this));return t}some(e,i){typeof i!=\"undefined\"&&(e=e.bind(i));for(let[t,l]of this)if(e(l,t,this))return!0;return!1}every(e,i){typeof i!=\"undefined\"&&(e=e.bind(i));for(let[t,l]of this)if(!e(l,t,this))return!1;return!0}reduce(e,i){let t;if(typeof i!=\"undefined\"){t=i;for(let[n,s]of this)t=e(t,s,n,this);return t}let l=!0;for(let[n,s]of this){if(l){t=s,l=!1;continue}t=e(t,s,n,this)}if(l)throw new TypeError(\"Reduce of empty collection with no initial value\");return t}each(e,i){return this.forEach(e,i),this}tap(e,i){return typeof i!=\"undefined\"&&(e=e.bind(i)),e(this),this}clone(){return new this.constructor[Symbol.species](this)}concat(...e){let i=this.clone();for(let t of e)for(let[l,n]of t)i.set(l,n);return i}equals(e){if(!e)return!1;if(this===e)return!0;if(this.size!==e.size)return!1;for(let[i,t]of this)if(!e.has(i)||t!==e.get(i))return!1;return!0}sort(e=o.defaultSort){let i=[...this.entries()];i.sort((t,l)=>e(t[1],l[1],t[0],l[0])),super.clear();for(let[t,l]of i)super.set(t,l);return this}intersect(e){let i=new this.constructor[Symbol.species];for(let[t,l]of e)this.has(t)&&i.set(t,l);return i}difference(e){let i=new this.constructor[Symbol.species];for(let[t,l]of e)this.has(t)||i.set(t,l);for(let[t,l]of this)e.has(t)||i.set(t,l);return i}sorted(e=o.defaultSort){return new this.constructor[Symbol.species](this).sort((i,t,l,n)=>e(i,t,l,n))}toJSON(){return[...this.values()]}static defaultSort(e,i){return Number(e>i)||Number(e===i)-1}},c=o;r(c,\"Collection\"),\"constructor\",c.default=o;var f=c;export{c as Collection,f as default};\n//# sourceMappingURL=index.mjs.map\n","import PlayerService from '../players/player.service';\nimport { marketplaceLogger } from './marketplace.utils';\nimport MarketplaceDB, { _MarketplaceDB } from './marketplace.db';\nimport {\n ListingTypeResp,\n MarketplaceDeleteDTO,\n MarketplaceEvents,\n MarketplaceListing,\n MarketplaceListingBase,\n MarketplaceReportDTO,\n} from '../../../typings/marketplace';\nimport { reportListingToDiscord } from '../misc/discord';\nimport { PromiseEventResp, PromiseRequest } from '../lib/PromiseNetEvents/promise.types';\n\nclass _MarketplaceService {\n private readonly marketplaceDB: _MarketplaceDB;\n\n constructor() {\n this.marketplaceDB = MarketplaceDB;\n marketplaceLogger.debug('Marketplace service started');\n }\n\n async handleAddListing(\n reqObj: PromiseRequest,\n resp: PromiseEventResp,\n ): Promise {\n marketplaceLogger.debug('Handling add listing, listing:');\n marketplaceLogger.debug(reqObj.data);\n\n const player = PlayerService.getPlayer(reqObj.source);\n const identifier = player.getIdentifier();\n\n try {\n const doesListingExist = await this.marketplaceDB.doesListingExist(reqObj.data, identifier);\n if (doesListingExist) return resp({ status: 'error', data: ListingTypeResp.DUPLICATE });\n\n const listingId = await this.marketplaceDB.addListing(\n player.getIdentifier(),\n player.username,\n player.getName(),\n player.getPhoneNumber(),\n reqObj.data,\n );\n // Respond with success to original source\n resp({ status: 'ok' });\n\n const returnObj: MarketplaceListing = {\n id: listingId,\n identifier: player.getIdentifier(),\n name: player.getName(),\n number: player.getPhoneNumber(),\n url: reqObj.data.url,\n username: player.username,\n description: reqObj.data.description,\n title: reqObj.data.title,\n };\n // Broadcast to everyone we are adding a listing\n emitNet(MarketplaceEvents.BROADCAST_ADD, -1, { type: 'ADD', listing: returnObj });\n } catch (e) {\n marketplaceLogger.error(`Failed to add listing ${e.message}`, {\n source: reqObj.source,\n });\n\n resp({ status: 'error', errorMsg: 'DB_ERROR' });\n }\n }\n\n async handleFetchListings(\n req: PromiseRequest,\n resp: PromiseEventResp,\n ) {\n try {\n const listings = await this.marketplaceDB.fetchListings();\n\n resp({ data: listings, status: 'ok' });\n } catch (e) {\n marketplaceLogger.error(`Failed to fetch listings, ${e.message}`, {\n source: req.source,\n });\n resp({ status: 'error', errorMsg: 'DB_ERROR' });\n }\n }\n\n async handleDeleteListing(\n reqObj: PromiseRequest,\n resp: PromiseEventResp,\n ): Promise {\n const identifier = PlayerService.getIdentifier(reqObj.source);\n try {\n await this.marketplaceDB.deleteListing(reqObj.data.id, identifier);\n\n resp({ status: 'ok' });\n\n const returnObj = reqObj.data.id;\n\n emitNet(MarketplaceEvents.BROADCAST_DELETE, -1, [returnObj]);\n } catch (e) {\n marketplaceLogger.error(`Error in handleDeleteListing, ${e.message}`);\n\n resp({ status: 'error', errorMsg: 'DB_ERROR' });\n }\n }\n\n async handleDeleteListingsOnDrop(identifier: string) {\n try {\n const listingIds = await this.marketplaceDB.getListingIdsByIdentifier(identifier);\n\n emitNet(MarketplaceEvents.BROADCAST_DELETE, -1, listingIds);\n\n await this.marketplaceDB.deleteListingsOnDrop(identifier);\n } catch (e) {\n marketplaceLogger.error(`Error when deleting listings on player drop, ${e.message}`);\n }\n }\n\n async handleReportListing(\n reqObj: PromiseRequest,\n resp: PromiseEventResp,\n ): Promise {\n try {\n const rListing = await this.marketplaceDB.getListing(reqObj.data.id);\n const reportExists = await this.marketplaceDB.doesReportExist(\n reqObj.data.id,\n rListing.username,\n );\n\n const reportingPlayer = GetPlayerName(reqObj.source.toString());\n\n if (reportExists) {\n marketplaceLogger.error(`This listing has already been reported`);\n resp({ status: 'error', errorMsg: 'REPORT_EXISTS' });\n return;\n }\n\n await this.marketplaceDB.reportListing(rListing);\n await reportListingToDiscord(rListing, reportingPlayer);\n } catch (e) {\n marketplaceLogger.error(`Failed to report listing ${e.message}`, {\n source: reqObj.source,\n });\n resp({ status: 'error', errorMsg: 'DB_ERROR' });\n }\n }\n}\n\nconst MarketplaceService = new _MarketplaceService();\nexport default MarketplaceService;\n","import { mainLogger } from '../sv_logger';\n\nexport const marketplaceLogger = mainLogger.child({ module: 'marketplace' });\n","export interface MarketplaceListing extends MarketplaceListingBase {\n id: number;\n identifier?: string;\n username: string;\n name: string;\n number: string;\n}\n\nexport interface MarketplaceListingBase {\n title: string;\n url: string;\n description: string;\n}\n\nexport enum MarketplaceDatabaseLimits {\n title = 255,\n description = 255,\n url = 255,\n}\n\nexport enum ListingTypeResp {\n DUPLICATE = 'duplicate',\n}\n\nexport enum MarketplaceEvents {\n ADD_LISTING = 'npwd:addListing',\n FETCH_LISTING = 'npwd:fetchAllListings',\n DELETE_LISTING = 'npwd:marketplaceDeleteListing',\n DELETE_LISTINGS_ON_DROP = 'npwd:marketplaceDeleteListingsOnDrop',\n REPORT_LISTING = 'npwd:reportListing',\n BROADCAST_ADD = 'npwd:sendMarketplaceBroadcastAdd',\n BROADCAST_DELETE = 'npwd:sendMarketplaceBroadcastDelete',\n}\n\nexport interface MarketplaceBroadcastAddDTO {\n listing: MarketplaceListing;\n}\n\nexport interface MarketplaceDeleteDTO {\n id: number;\n}\n\nexport interface MarketplaceReportDTO {\n id: number;\n}\n\nexport type ReportListingDTO = {\n id: number;\n title: string;\n description: string;\n url: string;\n};\n","import axios, { AxiosResponse } from 'axios';\n\nimport { Tweet, Profile } from '../../../typings/twitter';\n\nimport { mainLogger } from '../sv_logger';\nimport { MarketplaceListing } from '../../../typings/marketplace';\n\nconst IMAGE_DELIMITER = '||!||';\nconst discordLogger = mainLogger.child({ module: 'discord' });\n\nconst DISCORD_WEBHOOK = GetConvar('NPWD_DISCORD_TOKEN', '');\n/**\n * https://discord.com/developers/docs/resources/channel#embed-object-embed-field-structure\n */\ninterface DiscordEmbedField {\n name: string;\n value: string;\n inline?: boolean;\n}\n\ninterface DiscordEmbed {\n title: string;\n color: number;\n description: string;\n timestamp: string;\n fields: DiscordEmbedField[];\n}\n\ninterface DiscordMessage {\n username: string;\n embeds: DiscordEmbed[];\n}\n\nconst postToWebhook = async (content: DiscordMessage): Promise => {\n // If convar isnt set\n if (!DISCORD_WEBHOOK) {\n discordLogger.warn(\n 'Got a request to report a listing but discord is not configures. See README on how to configure discord endpoints.',\n );\n return;\n }\n const resp = await axios.post(DISCORD_WEBHOOK, { ...content });\n // If we get a bad request throw error\n if (resp.status < 200 && resp.status >= 300)\n throw new Error(`Discord Error: ${resp.status} Error - ${resp.statusText}`);\n};\n\nconst createDiscordMsgObj = (type: string, message: string, fields: DiscordEmbedField[]) => {\n // Get ISO 8601 as its required by Discord API\n const curTime = new Date().toISOString();\n\n return {\n username: 'NPWD Report',\n embeds: [\n {\n title: `${type} REPORT`,\n color: 0xe74c3c,\n description: message,\n timestamp: curTime,\n fields,\n },\n ],\n };\n};\n\nexport async function reportTweetToDiscord(tweet: Tweet, reportingProfile: Profile): Promise {\n const guaranteedFields = [\n {\n name: 'Reported By:',\n value: `\\`\\`\\`Profile Name: ${reportingProfile.profile_name}\\nProfile ID: ${reportingProfile.id}\\nUser Identifier: ${reportingProfile.identifier}\\`\\`\\``,\n },\n {\n name: 'Reported User Data:',\n value: `\\`\\`\\`Profile Name: ${tweet.profile_name}\\nProfile ID: ${tweet.profile_id}\\nUser Identifier: ${tweet.identifier}\\`\\`\\``,\n },\n {\n name: 'Tweet Message:',\n value: `\\`\\`\\`Message: ${tweet.message}\\`\\`\\``,\n },\n ];\n\n const finalFields = tweet.images\n ? guaranteedFields.concat({\n name: 'Reported Image:',\n value: tweet.images.split(IMAGE_DELIMITER).join('\\n'),\n })\n : guaranteedFields;\n\n const msgObj = createDiscordMsgObj('TWITTER', `Received a report for a tweet`, finalFields);\n try {\n await postToWebhook(msgObj);\n } catch (e) {\n discordLogger.error(e.message);\n }\n}\n\nexport async function reportListingToDiscord(\n listing: MarketplaceListing,\n reportingProfile: string,\n): Promise {\n const guaranteedFields = [\n {\n name: 'Reported By',\n value: `\\`\\`\\`Profile Name: ${reportingProfile}\\`\\`\\``,\n },\n {\n name: 'Reported User Data',\n value: `\\`\\`\\`Profile Name: ${listing.username}\\nProfile ID: ${listing.id}\\nUser Identifier: ${listing.identifier}\\`\\`\\``,\n },\n {\n name: 'Reported Listing Title',\n value: `\\`\\`\\`Title: ${listing.name}\\`\\`\\``,\n },\n {\n name: 'Reported Listing Desc.',\n value: `\\`\\`\\`Description: ${listing.description}\\`\\`\\``,\n },\n ];\n\n const finalFields = listing.url\n ? guaranteedFields.concat({\n name: 'Reported Image:',\n value: listing.url.split(IMAGE_DELIMITER).join('\\n'),\n })\n : guaranteedFields;\n\n const msgObj = createDiscordMsgObj('MARKETPLACE', `Received a report for a listing`, finalFields);\n try {\n await postToWebhook(msgObj);\n } catch (e) {\n discordLogger.error(e.message);\n }\n}\n","'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n","'use strict';\n\nvar createError = require('./createError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(createError(\n 'Request failed with status code ' + response.status,\n response.config,\n null,\n response.request,\n response\n ));\n }\n};\n","'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n","var url = require(\"url\");\nvar URL = url.URL;\nvar http = require(\"http\");\nvar https = require(\"https\");\nvar Writable = require(\"stream\").Writable;\nvar assert = require(\"assert\");\nvar debug = require(\"./debug\");\n\n// Create handlers that pass events from native requests\nvar events = [\"abort\", \"aborted\", \"connect\", \"error\", \"socket\", \"timeout\"];\nvar eventHandlers = Object.create(null);\nevents.forEach(function (event) {\n eventHandlers[event] = function (arg1, arg2, arg3) {\n this._redirectable.emit(event, arg1, arg2, arg3);\n };\n});\n\n// Error types with codes\nvar RedirectionError = createErrorType(\n \"ERR_FR_REDIRECTION_FAILURE\",\n \"Redirected request failed\"\n);\nvar TooManyRedirectsError = createErrorType(\n \"ERR_FR_TOO_MANY_REDIRECTS\",\n \"Maximum number of redirects exceeded\"\n);\nvar MaxBodyLengthExceededError = createErrorType(\n \"ERR_FR_MAX_BODY_LENGTH_EXCEEDED\",\n \"Request body larger than maxBodyLength limit\"\n);\nvar WriteAfterEndError = createErrorType(\n \"ERR_STREAM_WRITE_AFTER_END\",\n \"write after end\"\n);\n\n// An HTTP(S) request that can be redirected\nfunction RedirectableRequest(options, responseCallback) {\n // Initialize the request\n Writable.call(this);\n this._sanitizeOptions(options);\n this._options = options;\n this._ended = false;\n this._ending = false;\n this._redirectCount = 0;\n this._redirects = [];\n this._requestBodyLength = 0;\n this._requestBodyBuffers = [];\n\n // Attach a callback if passed\n if (responseCallback) {\n this.on(\"response\", responseCallback);\n }\n\n // React to responses of native requests\n var self = this;\n this._onNativeResponse = function (response) {\n self._processResponse(response);\n };\n\n // Perform the first request\n this._performRequest();\n}\nRedirectableRequest.prototype = Object.create(Writable.prototype);\n\nRedirectableRequest.prototype.abort = function () {\n abortRequest(this._currentRequest);\n this.emit(\"abort\");\n};\n\n// Writes buffered data to the current native request\nRedirectableRequest.prototype.write = function (data, encoding, callback) {\n // Writing is not allowed if end has been called\n if (this._ending) {\n throw new WriteAfterEndError();\n }\n\n // Validate input and shift parameters if necessary\n if (!(typeof data === \"string\" || typeof data === \"object\" && (\"length\" in data))) {\n throw new TypeError(\"data should be a string, Buffer or Uint8Array\");\n }\n if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n\n // Ignore empty buffers, since writing them doesn't invoke the callback\n // https://github.com/nodejs/node/issues/22066\n if (data.length === 0) {\n if (callback) {\n callback();\n }\n return;\n }\n // Only write when we don't exceed the maximum body length\n if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {\n this._requestBodyLength += data.length;\n this._requestBodyBuffers.push({ data: data, encoding: encoding });\n this._currentRequest.write(data, encoding, callback);\n }\n // Error when we exceed the maximum body length\n else {\n this.emit(\"error\", new MaxBodyLengthExceededError());\n this.abort();\n }\n};\n\n// Ends the current native request\nRedirectableRequest.prototype.end = function (data, encoding, callback) {\n // Shift parameters if necessary\n if (typeof data === \"function\") {\n callback = data;\n data = encoding = null;\n }\n else if (typeof encoding === \"function\") {\n callback = encoding;\n encoding = null;\n }\n\n // Write data if needed and end\n if (!data) {\n this._ended = this._ending = true;\n this._currentRequest.end(null, null, callback);\n }\n else {\n var self = this;\n var currentRequest = this._currentRequest;\n this.write(data, encoding, function () {\n self._ended = true;\n currentRequest.end(null, null, callback);\n });\n this._ending = true;\n }\n};\n\n// Sets a header value on the current native request\nRedirectableRequest.prototype.setHeader = function (name, value) {\n this._options.headers[name] = value;\n this._currentRequest.setHeader(name, value);\n};\n\n// Clears a header value on the current native request\nRedirectableRequest.prototype.removeHeader = function (name) {\n delete this._options.headers[name];\n this._currentRequest.removeHeader(name);\n};\n\n// Global timeout for all underlying requests\nRedirectableRequest.prototype.setTimeout = function (msecs, callback) {\n var self = this;\n\n // Destroys the socket on timeout\n function destroyOnTimeout(socket) {\n socket.setTimeout(msecs);\n socket.removeListener(\"timeout\", socket.destroy);\n socket.addListener(\"timeout\", socket.destroy);\n }\n\n // Sets up a timer to trigger a timeout event\n function startTimer(socket) {\n if (self._timeout) {\n clearTimeout(self._timeout);\n }\n self._timeout = setTimeout(function () {\n self.emit(\"timeout\");\n clearTimer();\n }, msecs);\n destroyOnTimeout(socket);\n }\n\n // Stops a timeout from triggering\n function clearTimer() {\n // Clear the timeout\n if (self._timeout) {\n clearTimeout(self._timeout);\n self._timeout = null;\n }\n\n // Clean up all attached listeners\n self.removeListener(\"abort\", clearTimer);\n self.removeListener(\"error\", clearTimer);\n self.removeListener(\"response\", clearTimer);\n if (callback) {\n self.removeListener(\"timeout\", callback);\n }\n if (!self.socket) {\n self._currentRequest.removeListener(\"socket\", startTimer);\n }\n }\n\n // Attach callback if passed\n if (callback) {\n this.on(\"timeout\", callback);\n }\n\n // Start the timer if or when the socket is opened\n if (this.socket) {\n startTimer(this.socket);\n }\n else {\n this._currentRequest.once(\"socket\", startTimer);\n }\n\n // Clean up on events\n this.on(\"socket\", destroyOnTimeout);\n this.on(\"abort\", clearTimer);\n this.on(\"error\", clearTimer);\n this.on(\"response\", clearTimer);\n\n return this;\n};\n\n// Proxy all other public ClientRequest methods\n[\n \"flushHeaders\", \"getHeader\",\n \"setNoDelay\", \"setSocketKeepAlive\",\n].forEach(function (method) {\n RedirectableRequest.prototype[method] = function (a, b) {\n return this._currentRequest[method](a, b);\n };\n});\n\n// Proxy all public ClientRequest properties\n[\"aborted\", \"connection\", \"socket\"].forEach(function (property) {\n Object.defineProperty(RedirectableRequest.prototype, property, {\n get: function () { return this._currentRequest[property]; },\n });\n});\n\nRedirectableRequest.prototype._sanitizeOptions = function (options) {\n // Ensure headers are always present\n if (!options.headers) {\n options.headers = {};\n }\n\n // Since http.request treats host as an alias of hostname,\n // but the url module interprets host as hostname plus port,\n // eliminate the host property to avoid confusion.\n if (options.host) {\n // Use hostname if set, because it has precedence\n if (!options.hostname) {\n options.hostname = options.host;\n }\n delete options.host;\n }\n\n // Complete the URL object when necessary\n if (!options.pathname && options.path) {\n var searchPos = options.path.indexOf(\"?\");\n if (searchPos < 0) {\n options.pathname = options.path;\n }\n else {\n options.pathname = options.path.substring(0, searchPos);\n options.search = options.path.substring(searchPos);\n }\n }\n};\n\n\n// Executes the next native request (initial or redirect)\nRedirectableRequest.prototype._performRequest = function () {\n // Load the native protocol\n var protocol = this._options.protocol;\n var nativeProtocol = this._options.nativeProtocols[protocol];\n if (!nativeProtocol) {\n this.emit(\"error\", new TypeError(\"Unsupported protocol \" + protocol));\n return;\n }\n\n // If specified, use the agent corresponding to the protocol\n // (HTTP and HTTPS use different types of agents)\n if (this._options.agents) {\n var scheme = protocol.substr(0, protocol.length - 1);\n this._options.agent = this._options.agents[scheme];\n }\n\n // Create the native request\n var request = this._currentRequest =\n nativeProtocol.request(this._options, this._onNativeResponse);\n this._currentUrl = url.format(this._options);\n\n // Set up event handlers\n request._redirectable = this;\n for (var e = 0; e < events.length; e++) {\n request.on(events[e], eventHandlers[events[e]]);\n }\n\n // End a redirected request\n // (The first request must be ended explicitly with RedirectableRequest#end)\n if (this._isRedirect) {\n // Write the request entity and end.\n var i = 0;\n var self = this;\n var buffers = this._requestBodyBuffers;\n (function writeNext(error) {\n // Only write if this request has not been redirected yet\n /* istanbul ignore else */\n if (request === self._currentRequest) {\n // Report any write errors\n /* istanbul ignore if */\n if (error) {\n self.emit(\"error\", error);\n }\n // Write the next buffer if there are still left\n else if (i < buffers.length) {\n var buffer = buffers[i++];\n /* istanbul ignore else */\n if (!request.finished) {\n request.write(buffer.data, buffer.encoding, writeNext);\n }\n }\n // End the request if `end` has been called on us\n else if (self._ended) {\n request.end();\n }\n }\n }());\n }\n};\n\n// Processes a response from the current native request\nRedirectableRequest.prototype._processResponse = function (response) {\n // Store the redirected response\n var statusCode = response.statusCode;\n if (this._options.trackRedirects) {\n this._redirects.push({\n url: this._currentUrl,\n headers: response.headers,\n statusCode: statusCode,\n });\n }\n\n // RFC7231§6.4: The 3xx (Redirection) class of status code indicates\n // that further action needs to be taken by the user agent in order to\n // fulfill the request. If a Location header field is provided,\n // the user agent MAY automatically redirect its request to the URI\n // referenced by the Location field value,\n // even if the specific status code is not understood.\n var location = response.headers.location;\n if (location && this._options.followRedirects !== false &&\n statusCode >= 300 && statusCode < 400) {\n // Abort the current request\n abortRequest(this._currentRequest);\n // Discard the remainder of the response to avoid waiting for data\n response.destroy();\n\n // RFC7231§6.4: A client SHOULD detect and intervene\n // in cyclical redirections (i.e., \"infinite\" redirection loops).\n if (++this._redirectCount > this._options.maxRedirects) {\n this.emit(\"error\", new TooManyRedirectsError());\n return;\n }\n\n // RFC7231§6.4: Automatic redirection needs to done with\n // care for methods not known to be safe, […]\n // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change\n // the request method from POST to GET for the subsequent request.\n if ((statusCode === 301 || statusCode === 302) && this._options.method === \"POST\" ||\n // RFC7231§6.4.4: The 303 (See Other) status code indicates that\n // the server is redirecting the user agent to a different resource […]\n // A user agent can perform a retrieval request targeting that URI\n // (a GET or HEAD request if using HTTP) […]\n (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {\n this._options.method = \"GET\";\n // Drop a possible entity and headers related to it\n this._requestBodyBuffers = [];\n removeMatchingHeaders(/^content-/i, this._options.headers);\n }\n\n // Drop the Host header, as the redirect might lead to a different host\n var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers);\n\n // If the redirect is relative, carry over the host of the last request\n var currentUrlParts = url.parse(this._currentUrl);\n var currentHost = currentHostHeader || currentUrlParts.host;\n var currentUrl = /^\\w+:/.test(location) ? this._currentUrl :\n url.format(Object.assign(currentUrlParts, { host: currentHost }));\n\n // Determine the URL of the redirection\n var redirectUrl;\n try {\n redirectUrl = url.resolve(currentUrl, location);\n }\n catch (cause) {\n this.emit(\"error\", new RedirectionError(cause));\n return;\n }\n\n // Create the redirected request\n debug(\"redirecting to\", redirectUrl);\n this._isRedirect = true;\n var redirectUrlParts = url.parse(redirectUrl);\n Object.assign(this._options, redirectUrlParts);\n\n // Drop the Authorization header if redirecting to another domain\n if (!(redirectUrlParts.host === currentHost || isSubdomainOf(redirectUrlParts.host, currentHost))) {\n removeMatchingHeaders(/^authorization$/i, this._options.headers);\n }\n\n // Evaluate the beforeRedirect callback\n if (typeof this._options.beforeRedirect === \"function\") {\n var responseDetails = { headers: response.headers };\n try {\n this._options.beforeRedirect.call(null, this._options, responseDetails);\n }\n catch (err) {\n this.emit(\"error\", err);\n return;\n }\n this._sanitizeOptions(this._options);\n }\n\n // Perform the redirected request\n try {\n this._performRequest();\n }\n catch (cause) {\n this.emit(\"error\", new RedirectionError(cause));\n }\n }\n else {\n // The response is not a redirect; return it as-is\n response.responseUrl = this._currentUrl;\n response.redirects = this._redirects;\n this.emit(\"response\", response);\n\n // Clean up\n this._requestBodyBuffers = [];\n }\n};\n\n// Wraps the key/value object of protocols with redirect functionality\nfunction wrap(protocols) {\n // Default settings\n var exports = {\n maxRedirects: 21,\n maxBodyLength: 10 * 1024 * 1024,\n };\n\n // Wrap each protocol\n var nativeProtocols = {};\n Object.keys(protocols).forEach(function (scheme) {\n var protocol = scheme + \":\";\n var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];\n var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);\n\n // Executes a request, following redirects\n function request(input, options, callback) {\n // Parse parameters\n if (typeof input === \"string\") {\n var urlStr = input;\n try {\n input = urlToOptions(new URL(urlStr));\n }\n catch (err) {\n /* istanbul ignore next */\n input = url.parse(urlStr);\n }\n }\n else if (URL && (input instanceof URL)) {\n input = urlToOptions(input);\n }\n else {\n callback = options;\n options = input;\n input = { protocol: protocol };\n }\n if (typeof options === \"function\") {\n callback = options;\n options = null;\n }\n\n // Set defaults\n options = Object.assign({\n maxRedirects: exports.maxRedirects,\n maxBodyLength: exports.maxBodyLength,\n }, input, options);\n options.nativeProtocols = nativeProtocols;\n\n assert.equal(options.protocol, protocol, \"protocol mismatch\");\n debug(\"options\", options);\n return new RedirectableRequest(options, callback);\n }\n\n // Executes a GET request, following redirects\n function get(input, options, callback) {\n var wrappedRequest = wrappedProtocol.request(input, options, callback);\n wrappedRequest.end();\n return wrappedRequest;\n }\n\n // Expose the properties on the wrapped protocol\n Object.defineProperties(wrappedProtocol, {\n request: { value: request, configurable: true, enumerable: true, writable: true },\n get: { value: get, configurable: true, enumerable: true, writable: true },\n });\n });\n return exports;\n}\n\n/* istanbul ignore next */\nfunction noop() { /* empty */ }\n\n// from https://github.com/nodejs/node/blob/master/lib/internal/url.js\nfunction urlToOptions(urlObject) {\n var options = {\n protocol: urlObject.protocol,\n hostname: urlObject.hostname.startsWith(\"[\") ?\n /* istanbul ignore next */\n urlObject.hostname.slice(1, -1) :\n urlObject.hostname,\n hash: urlObject.hash,\n search: urlObject.search,\n pathname: urlObject.pathname,\n path: urlObject.pathname + urlObject.search,\n href: urlObject.href,\n };\n if (urlObject.port !== \"\") {\n options.port = Number(urlObject.port);\n }\n return options;\n}\n\nfunction removeMatchingHeaders(regex, headers) {\n var lastValue;\n for (var header in headers) {\n if (regex.test(header)) {\n lastValue = headers[header].toString().trim();\n delete headers[header];\n }\n }\n return lastValue;\n}\n\nfunction createErrorType(code, defaultMessage) {\n function CustomError(cause) {\n Error.captureStackTrace(this, this.constructor);\n if (!cause) {\n this.message = defaultMessage;\n }\n else {\n this.message = defaultMessage + \": \" + cause.message;\n this.cause = cause;\n }\n }\n CustomError.prototype = new Error();\n CustomError.prototype.constructor = CustomError;\n CustomError.prototype.name = \"Error [\" + code + \"]\";\n CustomError.prototype.code = code;\n return CustomError;\n}\n\nfunction abortRequest(request) {\n for (var e = 0; e < events.length; e++) {\n request.removeListener(events[e], eventHandlers[events[e]]);\n }\n request.on(\"error\", noop);\n request.abort();\n}\n\nfunction isSubdomainOf(subdomain, domain) {\n const dot = subdomain.length - domain.length - 1;\n return dot > 0 && subdomain[dot] === \".\" && subdomain.endsWith(domain);\n}\n\n// Exports\nmodule.exports = wrap({ http: http, https: https });\nmodule.exports.wrap = wrap;\n","module.exports = require(\"assert\");","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","module.exports = require(\"tty\");","'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n var valueFromConfig2Keys = ['url', 'method', 'data'];\n var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];\n var defaultToConfig2Keys = [\n 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',\n 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',\n 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',\n 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',\n 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'\n ];\n var directMergeKeys = ['validateStatus'];\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n }\n\n utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(undefined, config2[prop]);\n }\n });\n\n utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);\n\n utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n });\n\n utils.forEach(directMergeKeys, function merge(prop) {\n if (prop in config2) {\n config[prop] = getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n });\n\n var axiosKeys = valueFromConfig2Keys\n .concat(mergeDeepPropertiesKeys)\n .concat(defaultToConfig2Keys)\n .concat(directMergeKeys);\n\n var otherKeys = Object\n .keys(config1)\n .concat(Object.keys(config2))\n .filter(function filterAxiosKeys(key) {\n return axiosKeys.indexOf(key) === -1;\n });\n\n utils.forEach(otherKeys, mergeDeepProperties);\n\n return config;\n};\n","'use strict';\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n","export interface ActiveCall {\n is_accepted: boolean;\n isTransmitter: boolean;\n transmitter: string;\n receiver: string;\n channelId?: number;\n isUnavailable?: boolean;\n}\n\nexport interface InitializeCallDTO {\n receiverNumber: string;\n}\n\nexport interface StartCallEventData {\n transmitter: string;\n receiver: string;\n isTransmitter: boolean;\n isUnavailable?: boolean;\n}\n\nexport interface EndCallDTO {\n transmitterNumber: string;\n isTransmitter: boolean;\n}\n\nexport interface TransmitterNumDTO {\n transmitterNumber: string;\n}\n\nexport interface CallWasAcceptedEvent {\n channelId: number;\n currentCall: CallHistoryItem;\n isTransmitter: boolean;\n}\n\nexport interface ActiveCallRaw {\n identifier: string;\n transmitter: string;\n transmitterSource: number;\n receiver: string;\n receiverSource: number;\n start: string;\n is_accepted: boolean;\n}\n\nexport interface CallHistoryItem {\n id?: number;\n identifier: string;\n transmitter: string;\n transmitterSource?: number;\n receiver: string;\n receiverSource?: number;\n start: string;\n end?: number;\n is_accepted: boolean;\n}\n\nexport enum CallRejectReasons {\n DECLINED,\n BUSY_LINE,\n}\n\nexport enum CallEvents {\n INITIALIZE_CALL = 'npwd:beginCall',\n START_CALL = 'npwd:startCall',\n ACCEPT_CALL = 'npwd:acceptCall',\n END_CALL = 'npwd:endCall',\n WAS_ENDED = 'npwd:callEnded',\n WAS_ACCEPTED = 'npwd:callAccepted',\n REJECTED = 'npwd:rejectCall',\n WAS_REJECTED = 'npwd:callRejected',\n FETCH_CALLS = 'npwd:fetchCalls',\n SET_CALLER = 'npwd:setCaller',\n SET_CALL_MODAL = 'npwd:callModal',\n SEND_ALERT = 'npwd:callSetAlert',\n}\n","import { mainLogger } from '../sv_logger';\n\nexport const callLogger = mainLogger.child({ module: 'calls' });\n","import { mainLogger } from '../sv_logger';\n\nexport const notesLogger = mainLogger.child({ module: 'notes' });\n","import { mainLogger } from '../sv_logger';\n\nexport const contactsLogger = mainLogger.child({ module: 'contact' });\n","import { mainLogger } from '../sv_logger';\n\nexport const photoLogger = mainLogger.child({ module: 'photo' });\n","export interface Message {\n id: number;\n message: string;\n conversation_id?: string;\n author: string;\n}\n\nexport interface PreDBMessage {\n conversationId: string;\n message: string;\n}\n\nexport interface MessageConversation {\n conversation_id: string;\n avatar: string;\n display: string;\n phoneNumber: string;\n unread: number;\n}\n\nexport interface FormattedMessageConversation {\n conversation_id: string;\n phoneNumber: string;\n}\n\n/**\n * Used for the raw npwd_messages_groups row responses\n */\nexport interface UnformattedMessageConversation {\n conversation_id: string;\n user_identifier: string;\n participant_identifier: string;\n phone_number: string;\n avatar?: string;\n display?: string;\n updatedAt?: string;\n unread: number;\n}\n\n/**\n * Used to help consolidate raw npwd_messages_groups rows into\n * a mapping of a single message group\n */\nexport interface MessageGroupMapping {\n [groupId: string]: {\n user_identifier: string;\n // Participant displays\n participants: string[];\n phoneNumbers: string[];\n label?: string;\n avatar?: string;\n updatedAt: string;\n unreadCount: number;\n };\n}\n\nexport interface CreateMessageGroupResult {\n error?: boolean;\n phoneNumber?: string;\n duplicate?: boolean;\n conversationId?: string;\n mine?: boolean;\n participant: string;\n identifiers: string[];\n doesExist: UnformattedMessageConversation | null;\n}\n\nexport interface CreateMessageBroadcast {\n message: string;\n groupName: string;\n groupId: string;\n}\n\nexport interface SetMessageRead {\n groupId: string;\n}\n\nexport interface MessageConversationResponse {\n conversation_id: string;\n phoneNumber: string;\n}\n\nexport enum MessageEvents {\n FETCH_MESSAGE_CONVERSATIONS = 'npwd:fetchMessageGroups',\n FETCH_MESSAGE_GROUPS_SUCCESS = 'npwd:fetchMessageGroupsSuccess',\n FETCH_MESSAGE_GROUPS_FAILED = 'npwd:fetchMessageGroupsFailed',\n CREATE_MESSAGE_CONVERSATION = 'npwd:createMessageGroup',\n CREATE_MESSAGE_CONVERSATION_SUCCESS = 'npwd:createMessageConversationSuccess',\n CREATE_MESSAGE_GROUP_SUCCESS = 'npwd:createMessageGroupSuccess',\n CREATE_MESSAGE_GROUP_FAILED = 'npwd:createMessageGroupFailed',\n SEND_MESSAGE = 'npwd:sendMessage',\n SEND_MESSAGE_SUCCESS = 'npwd:sendMessageSuccess',\n SEND_MESSAGE_FAILED = 'npwd:sendMessageFailed',\n DELETE_MESSAGE = 'npwd:deleteMessage',\n FETCH_MESSAGES = 'npwd:fetchMessages',\n FETCH_MESSAGES_SUCCESS = 'npwd:fetchMessagesSuccess',\n FETCH_MESSAGES_FAILED = 'npwd:fetchMessagesFailed',\n FETCH_INITIAL_MESSAGES = 'npwd:fetchInitialMessages',\n ACTION_RESULT = 'npwd:setMessagesAlert',\n CREATE_MESSAGE_BROADCAST = 'createMessagesBroadcast',\n SET_MESSAGE_READ = 'npwd:setReadMessages',\n DELETE_CONVERSATION = 'nwpd:deleteConversation',\n}\n","import {\n Message,\n MessageConversation,\n UnformattedMessageConversation,\n} from '../../../typings/messages';\nimport { config } from '../server';\nimport { ResultSetHeader } from 'mysql2';\nimport DbInterface from '../db/db_wrapper';\n\nconst MESSAGES_PER_PAGE = 20;\n\n// not sure whats going on here.\nexport class _MessagesDB {\n /**\n * Create a message in the database\n * @param author - the phoneNumber to the player who sent the message\n * @param conversationId - the message conversation ID to attach this message to\n * @param message - content of the message\n */\n async createMessage(\n userIdentifier: string,\n author: string,\n conversationId: string,\n message: string,\n ): Promise {\n const query = `INSERT INTO npwd_messages (user_identifier, author, message, conversation_id)\n VALUES (?, ?, ?, ?)`;\n\n const [results] = await DbInterface._rawExec(query, [\n userIdentifier,\n author,\n message,\n conversationId,\n ]);\n\n return (results).insertId;\n }\n\n // Not sure if we're going to query this exactly as its done here.\n /**\n * Retrieve all message conversations associated with a user. This will\n * populate the list of message conversations on the UI\n * @param phoneNumber - phoneNumber of the user to get message conversations for\n */\n async getMessageConversations(phoneNumber: string): Promise {\n const query = `SELECT npwd_messages_conversations.unread,\n npwd_messages_conversations.conversation_id,\n npwd_messages_conversations.user_identifier,\n npwd_messages_conversations.participant_identifier,\n ${config.database.playerTable}.${config.database.phoneNumberColumn} AS phone_number\n FROM (SELECT conversation_id\n FROM npwd_messages_conversations\n WHERE npwd_messages_conversations.participant_identifier = ?) AS t\n LEFT OUTER JOIN npwd_messages_conversations\n ON npwd_messages_conversations.conversation_id = t.conversation_id\n LEFT OUTER JOIN ${config.database.playerTable}\n ON ${config.database.playerTable}.${config.database.phoneNumberColumn} = npwd_messages_conversations.participant_identifier\n\t\t`;\n\n const [results] = await DbInterface._rawExec(query, [phoneNumber]);\n return results;\n }\n\n async getMessages(conversationId: string, page: number): Promise {\n const offset = page * MESSAGES_PER_PAGE;\n\n const query = `SELECT npwd_messages.id,\n npwd_messages.conversation_id,\n npwd_messages.message,\n npwd_messages.author\n FROM npwd_messages\n WHERE npwd_messages.conversation_id = ?\n ORDER BY id DESC\n LIMIT ? OFFSET ?`;\n\n const [results] = await DbInterface._rawExec(query, [\n conversationId,\n MESSAGES_PER_PAGE,\n offset,\n ]);\n\n return results;\n }\n\n /**\n * Create a message group\n * @param userIdentifier - the user creating the message group\n * @param conversationId - the unique group ID this corresponds to\n * @param participantIdentifier - the participant user identifier. This identifier is what attaches\n * other players to the message group\n */\n async createMessageGroup(\n userIdentifier: string,\n conversationId: string,\n participantIdentifier: string,\n ): Promise {\n const query = `\n INSERT\n INTO npwd_messages_conversations\n (user_identifier, conversation_id, participant_identifier)\n VALUES (?, ?, ?)\n\t\t`;\n await DbInterface._rawExec(query, [userIdentifier, conversationId, participantIdentifier]);\n }\n\n /**\n * Find a players identifier from their phone number\n * @param phoneNumber - the phone number to search for\n */\n async getIdentifierFromPhoneNumber(phoneNumber: string): Promise {\n const query = `\n SELECT ${config.database.identifierColumn}\n FROM ${config.database.playerTable}\n WHERE ${config.database.phoneNumberColumn} = ?\n LIMIT 1\n\t\t`;\n const [results] = await DbInterface._rawExec(query, [phoneNumber]);\n const result = results;\n return result[0].identifier;\n }\n\n /**\n * This method checks if the input groupId already exists in\n * the database. As long as the groupId is derived from the input\n * identifiers this means that the user is trying to create a\n * duplicate!\n * @param groupId - group Id to check that it exists\n */\n async checkIfMessageGroupExists(groupId: string): Promise {\n const query = `\n SELECT COUNT(*) as count\n FROM npwd_messages_conversations\n WHERE conversation_id = ?;\n\t\t`;\n const [results] = await DbInterface._rawExec(query, [groupId]);\n const result = results;\n const count = result[0].count;\n return count > 0;\n }\n\n async getMessageCountByGroup(groupId: string): Promise {\n const query = `\n SELECT COUNT(*) as count\n FROM npwd_messages\n WHERE conversation_id = ?`;\n const [results] = await DbInterface._rawExec(query, [groupId]);\n const result = results;\n return result[0].count;\n }\n\n /**\n * Sets the current message isRead to 0 for said player\n * @param groupId The unique group ID for the message\n * @param identifier The identifier for the player\n */\n async setMessageRead(groupId: string, identifier: string) {\n const query = `UPDATE npwd_messages_conversations\n SET unreadCount = 0\n WHERE conversation_id = ?\n AND participant_identifier = ?`;\n await DbInterface._rawExec(query, [groupId, identifier]);\n }\n\n async deleteConversation(conversationId: string, sourcePhoneNumber: string) {\n const query = `DELETE\n FROM npwd_messages_conversations\n WHERE conversation_id = ?\n AND participant_identifier = ?`;\n await DbInterface._rawExec(query, [conversationId, sourcePhoneNumber]);\n }\n\n async deleteMessage(message: Message) {\n const query = `DELETE\n FROM npwd_messages\n WHERE id = ?\n AND conversation_id = ?`;\n\n await DbInterface._rawExec(query, [message.id, message.conversation_id]);\n }\n\n async doesConversationExist(\n conversationId: string,\n identifier: string,\n ): Promise {\n const query = `SELECT *\n FROM npwd_messages_conversations\n WHERE conversation_id = ?\n AND participant_identifier = ?`;\n const [results] = await DbInterface._rawExec(query, [conversationId, identifier]);\n const conversations = results;\n return conversations[0] || null;\n }\n}\n\nconst MessagesDB = new _MessagesDB();\n\nexport default MessagesDB;\n","import { CreateMessageGroupResult, MessageConversation } from '../../../typings/messages';\nimport { mainLogger } from '../sv_logger';\nimport MessagesDB from './messages.db';\nimport PlayerService from '../players/player.service';\n\nexport const messagesLogger = mainLogger.child({ module: 'messages' });\n\n// Functions\nexport async function getConsolidatedMessageGroups(identifier: string): Promise {\n const messageConversations = await MessagesDB.getMessageConversations(identifier);\n return messageConversations.reduce((mapping: any, conversation: any) => {\n const groupId = conversation.conversation_id;\n\n if (conversation.participant_identifier != identifier) {\n mapping[groupId] = {\n unread: conversation.unread,\n phoneNumber: conversation.phone_number,\n display: conversation.display,\n conversation_id: conversation.conversation_id,\n user_identifier: identifier,\n };\n }\n\n return mapping;\n }, {});\n}\n\nexport async function getFormattedMessageConversations(\n identifier: string,\n): Promise {\n const conversationMapping = await getConsolidatedMessageGroups(identifier);\n const conversationIds = await getGroupIds(identifier, conversationMapping);\n\n return conversationIds.map((conversationId) => {\n const conversation = conversationMapping[conversationId];\n\n return {\n ...conversation,\n };\n });\n}\n\nexport async function getGroupIds(userIdentifier: string, groupMapping: any): Promise {\n const groupIds: string[] = [];\n for (const groupId of Object.keys(groupMapping)) {\n const isMine = (groupMapping[groupId].user_identifier = userIdentifier);\n if (isMine) {\n groupIds.push(groupId);\n }\n }\n return groupIds;\n}\n\n/**\n * Create the same unique ID from an identifiers array.\n * They will be always be sorted to ensure always the same ID.\n * @param participants array of player identifiers\n */\nexport function createGroupHashID(participants: string[]) {\n // make sure we are always in a consistent order. It is very important\n // that this not change! Changing this order can result in the ability\n // of duplicate message groups being created.\n participants.sort();\n return participants.join('+');\n // we don't need this to be secure. Its purpose is to create a unique\n // string derived from the identifiers. In this way we can check\n // that this groupId isn't used before. If it has then it means\n // we are trying to create a duplicate message group!\n}\n\n/**\n * Main method to handle creation of new message groups. First\n * we retrieve identifiers for each submitted phone number and\n * then rows in npwd_messages_groups are created for each of them\n * bound to a unique groupId. The groupId is any unique string - we\n * use hashes here.\n *\n * These queries are batched with a transaction so that if any of\n * them fail the queries are not committed to the database. This helps\n * avoid situations where some participants get added to the group but\n * one fails resulting in a partial group which would be very confusing\n * to the player.\n * @param sourcePhoneNumber - user who is creating the group\n * @param tgtPhoneNumber - list of phone numbers to add to the grup\n */\nexport async function createMessageGroupsFromPhoneNumber(\n sourcePhoneNumber: string,\n tgtPhoneNumber: string,\n): Promise {\n // we check that each phoneNumber exists before we create the group\n\n const tgtIdentifier = await PlayerService.getIdentifierFromPhoneNumber(tgtPhoneNumber, true);\n\n if (!tgtIdentifier) {\n throw new Error('tgtIdentifier was null');\n }\n\n const conversationId = createGroupHashID([sourcePhoneNumber, tgtPhoneNumber]);\n const existingConversation = await MessagesDB.doesConversationExist(\n conversationId,\n tgtPhoneNumber,\n );\n\n if (existingConversation) {\n await MessagesDB.createMessageGroup(\n existingConversation.user_identifier,\n conversationId,\n sourcePhoneNumber,\n );\n } else {\n await MessagesDB.createMessageGroup(sourcePhoneNumber, conversationId, sourcePhoneNumber);\n await MessagesDB.createMessageGroup(sourcePhoneNumber, conversationId, tgtPhoneNumber);\n }\n\n // wrap this in a transaction to make sure ALL of these INSERTs succeed\n // so we are not left in a situation where only some of the member of the\n // group exist while other are left off.\n\n return {\n error: false,\n doesExist: existingConversation,\n conversationId,\n identifiers: [sourcePhoneNumber, tgtPhoneNumber],\n phoneNumber: tgtPhoneNumber,\n participant: tgtIdentifier,\n };\n}\n\n// getting the participants from groupId.\n// this should return the source or and array of identifiers\nexport function getIdentifiersFromParticipants(conversationId: string) {\n return conversationId.split('+');\n}\n","export interface NewTweet {\n message: string;\n images?: string;\n retweet?: number;\n}\n\nexport type SETTING_MENTIONS = 'mentions';\nexport type SETTINGS_ALL_TWEETS = 'all';\n\nexport interface Tweet extends NewTweet {\n profile_name: string;\n profile_id: number;\n id: number;\n identifier: string;\n isMine: boolean;\n isLiked: boolean;\n isReported: boolean;\n avatar_url: string;\n isRetweet: number | boolean;\n isRetweetedByPlayer?: boolean;\n retweetIdentifier: string;\n retweetId: string;\n seconds_since_tweet: number;\n retweetProfileName: string;\n retweetAvatarUrl: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface Image {\n id: string;\n link: string;\n}\nexport interface FormattedTweet extends Omit {\n images: Image[];\n}\n\nexport interface Profile {\n id: number;\n profile_name: string;\n identifier: string;\n avatar_url?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface UpdateProfileProps {\n avatar_url: string;\n profile_name: string;\n}\n\nexport enum TwitterEvents {\n FETCH_TWEETS = 'npwd:fetchTweets',\n FETCH_TWEETS_FILTERED = 'npwd:fetchTweetsFiltered',\n CREATE_PROFILE = 'npwd:createTwitterProfile',\n GET_OR_CREATE_PROFILE = 'npwd:getOrCreateTwitterProfile',\n UPDATE_PROFILE = 'npwd:updateTwitterProfile',\n CREATE_TWEET = 'npwd:createTweet',\n CREATE_TWEET_BROADCAST = 'createTweetBroadcast',\n DELETE_TWEET = 'npwd:deleteTweet',\n TOGGLE_LIKE = 'npwd:toggleLike',\n RETWEET = 'npwd:retweet',\n REPORT = 'npwd:reportTweet',\n}\n","import PlayerService from '../players/player.service';\nimport { clean } from './miscUtils';\n/**\n * Generate a profile name by the player's name and/or phone number\n * @param identifier - player's identifier\n * @param delimiter - What we split the profile name by, defaults to -\n */\nexport async function generateProfileName(\n identifier: string,\n delimiter = '_',\n): Promise {\n const player = PlayerService.getPlayerFromIdentifier(identifier);\n\n const firstname = clean(player.getFirstName());\n const lastname = clean(player.getLastName());\n const phone_number = clean(player.getPhoneNumber());\n\n if (firstname && lastname) {\n return `${firstname}${delimiter}${lastname}`;\n } else if (firstname) {\n return firstname;\n } else if (lastname) {\n return lastname;\n } else if (phone_number) {\n return phone_number;\n }\n return null;\n}\n","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nconst agent_1 = __importDefault(require(\"./agent\"));\nfunction createHttpsProxyAgent(opts) {\n return new agent_1.default(opts);\n}\n(function (createHttpsProxyAgent) {\n createHttpsProxyAgent.HttpsProxyAgent = agent_1.default;\n createHttpsProxyAgent.prototype = agent_1.default.prototype;\n})(createHttpsProxyAgent || (createHttpsProxyAgent = {}));\nmodule.exports = createHttpsProxyAgent;\n//# sourceMappingURL=index.js.map","/*!\n localForage -- Offline Storage, Improved\n Version 1.9.0\n https://localforage.github.io/localForage\n (c) 2013-2017 Mozilla, Apache License 2.0\n*/\n(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw (f.code=\"MODULE_NOT_FOUND\", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var scriptEl = global.document.createElement('script');\n scriptEl.onreadystatechange = function () {\n nextTick();\n\n scriptEl.onreadystatechange = null;\n scriptEl.parentNode.removeChild(scriptEl);\n scriptEl = null;\n };\n global.document.documentElement.appendChild(scriptEl);\n };\n } else {\n scheduleDrain = function () {\n setTimeout(nextTick, 0);\n };\n }\n}\n\nvar draining;\nvar queue = [];\n//named nextTick for less confusing stack traces\nfunction nextTick() {\n draining = true;\n var i, oldQueue;\n var len = queue.length;\n while (len) {\n oldQueue = queue;\n queue = [];\n i = -1;\n while (++i < len) {\n oldQueue[i]();\n }\n len = queue.length;\n }\n draining = false;\n}\n\nmodule.exports = immediate;\nfunction immediate(task) {\n if (queue.push(task) === 1 && !draining) {\n scheduleDrain();\n }\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{}],2:[function(_dereq_,module,exports){\n'use strict';\nvar immediate = _dereq_(1);\n\n/* istanbul ignore next */\nfunction INTERNAL() {}\n\nvar handlers = {};\n\nvar REJECTED = ['REJECTED'];\nvar FULFILLED = ['FULFILLED'];\nvar PENDING = ['PENDING'];\n\nmodule.exports = Promise;\n\nfunction Promise(resolver) {\n if (typeof resolver !== 'function') {\n throw new TypeError('resolver must be a function');\n }\n this.state = PENDING;\n this.queue = [];\n this.outcome = void 0;\n if (resolver !== INTERNAL) {\n safelyResolveThenable(this, resolver);\n }\n}\n\nPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n};\nPromise.prototype.then = function (onFulfilled, onRejected) {\n if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||\n typeof onRejected !== 'function' && this.state === REJECTED) {\n return this;\n }\n var promise = new this.constructor(INTERNAL);\n if (this.state !== PENDING) {\n var resolver = this.state === FULFILLED ? onFulfilled : onRejected;\n unwrap(promise, resolver, this.outcome);\n } else {\n this.queue.push(new QueueItem(promise, onFulfilled, onRejected));\n }\n\n return promise;\n};\nfunction QueueItem(promise, onFulfilled, onRejected) {\n this.promise = promise;\n if (typeof onFulfilled === 'function') {\n this.onFulfilled = onFulfilled;\n this.callFulfilled = this.otherCallFulfilled;\n }\n if (typeof onRejected === 'function') {\n this.onRejected = onRejected;\n this.callRejected = this.otherCallRejected;\n }\n}\nQueueItem.prototype.callFulfilled = function (value) {\n handlers.resolve(this.promise, value);\n};\nQueueItem.prototype.otherCallFulfilled = function (value) {\n unwrap(this.promise, this.onFulfilled, value);\n};\nQueueItem.prototype.callRejected = function (value) {\n handlers.reject(this.promise, value);\n};\nQueueItem.prototype.otherCallRejected = function (value) {\n unwrap(this.promise, this.onRejected, value);\n};\n\nfunction unwrap(promise, func, value) {\n immediate(function () {\n var returnValue;\n try {\n returnValue = func(value);\n } catch (e) {\n return handlers.reject(promise, e);\n }\n if (returnValue === promise) {\n handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));\n } else {\n handlers.resolve(promise, returnValue);\n }\n });\n}\n\nhandlers.resolve = function (self, value) {\n var result = tryCatch(getThen, value);\n if (result.status === 'error') {\n return handlers.reject(self, result.value);\n }\n var thenable = result.value;\n\n if (thenable) {\n safelyResolveThenable(self, thenable);\n } else {\n self.state = FULFILLED;\n self.outcome = value;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callFulfilled(value);\n }\n }\n return self;\n};\nhandlers.reject = function (self, error) {\n self.state = REJECTED;\n self.outcome = error;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callRejected(error);\n }\n return self;\n};\n\nfunction getThen(obj) {\n // Make sure we only access the accessor once as required by the spec\n var then = obj && obj.then;\n if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {\n return function appyThen() {\n then.apply(obj, arguments);\n };\n }\n}\n\nfunction safelyResolveThenable(self, thenable) {\n // Either fulfill, reject or reject with error\n var called = false;\n function onError(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.reject(self, value);\n }\n\n function onSuccess(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.resolve(self, value);\n }\n\n function tryToUnwrap() {\n thenable(onSuccess, onError);\n }\n\n var result = tryCatch(tryToUnwrap);\n if (result.status === 'error') {\n onError(result.value);\n }\n}\n\nfunction tryCatch(func, value) {\n var out = {};\n try {\n out.value = func(value);\n out.status = 'success';\n } catch (e) {\n out.status = 'error';\n out.value = e;\n }\n return out;\n}\n\nPromise.resolve = resolve;\nfunction resolve(value) {\n if (value instanceof this) {\n return value;\n }\n return handlers.resolve(new this(INTERNAL), value);\n}\n\nPromise.reject = reject;\nfunction reject(reason) {\n var promise = new this(INTERNAL);\n return handlers.reject(promise, reason);\n}\n\nPromise.all = all;\nfunction all(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var values = new Array(len);\n var resolved = 0;\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n allResolver(iterable[i], i);\n }\n return promise;\n function allResolver(value, i) {\n self.resolve(value).then(resolveFromAll, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n function resolveFromAll(outValue) {\n values[i] = outValue;\n if (++resolved === len && !called) {\n called = true;\n handlers.resolve(promise, values);\n }\n }\n }\n}\n\nPromise.race = race;\nfunction race(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n resolver(iterable[i]);\n }\n return promise;\n function resolver(value) {\n self.resolve(value).then(function (response) {\n if (!called) {\n called = true;\n handlers.resolve(promise, response);\n }\n }, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n }\n}\n\n},{\"1\":1}],3:[function(_dereq_,module,exports){\n(function (global){\n'use strict';\nif (typeof global.Promise !== 'function') {\n global.Promise = _dereq_(2);\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"2\":2}],4:[function(_dereq_,module,exports){\n'use strict';\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction getIDB() {\n /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */\n try {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof webkitIndexedDB !== 'undefined') {\n return webkitIndexedDB;\n }\n if (typeof mozIndexedDB !== 'undefined') {\n return mozIndexedDB;\n }\n if (typeof OIndexedDB !== 'undefined') {\n return OIndexedDB;\n }\n if (typeof msIndexedDB !== 'undefined') {\n return msIndexedDB;\n }\n } catch (e) {\n return;\n }\n}\n\nvar idb = getIDB();\n\nfunction isIndexedDBValid() {\n try {\n // Initialize IndexedDB; fall back to vendor-prefixed versions\n // if needed.\n if (!idb || !idb.open) {\n return false;\n }\n // We mimic PouchDB here;\n //\n // We test for openDatabase because IE Mobile identifies itself\n // as Safari. Oh the lulz...\n var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);\n\n var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;\n\n // Safari <10.1 does not meet our requirements for IDB support\n // (see: https://github.com/pouchdb/pouchdb/issues/5572).\n // Safari 10.1 shipped with fetch, we can use that to detect it.\n // Note: this creates issues with `window.fetch` polyfills and\n // overrides; see:\n // https://github.com/localForage/localForage/issues/856\n return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&\n // some outdated implementations of IDB that appear on Samsung\n // and HTC Android devices <4.4 are missing IDBKeyRange\n // See: https://github.com/mozilla/localForage/issues/128\n // See: https://github.com/mozilla/localForage/issues/272\n typeof IDBKeyRange !== 'undefined';\n } catch (e) {\n return false;\n }\n}\n\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\nfunction createBlob(parts, properties) {\n /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */\n parts = parts || [];\n properties = properties || {};\n try {\n return new Blob(parts, properties);\n } catch (e) {\n if (e.name !== 'TypeError') {\n throw e;\n }\n var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;\n var builder = new Builder();\n for (var i = 0; i < parts.length; i += 1) {\n builder.append(parts[i]);\n }\n return builder.getBlob(properties.type);\n }\n}\n\n// This is CommonJS because lie is an external dependency, so Rollup\n// can just ignore it.\nif (typeof Promise === 'undefined') {\n // In the \"nopromises\" build this will just throw if you don't have\n // a global promise object, but it would throw anyway later.\n _dereq_(3);\n}\nvar Promise$1 = Promise;\n\nfunction executeCallback(promise, callback) {\n if (callback) {\n promise.then(function (result) {\n callback(null, result);\n }, function (error) {\n callback(error);\n });\n }\n}\n\nfunction executeTwoCallbacks(promise, callback, errorCallback) {\n if (typeof callback === 'function') {\n promise.then(callback);\n }\n\n if (typeof errorCallback === 'function') {\n promise[\"catch\"](errorCallback);\n }\n}\n\nfunction normalizeKey(key) {\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n return key;\n}\n\nfunction getCallback() {\n if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {\n return arguments[arguments.length - 1];\n }\n}\n\n// Some code originally from async_storage.js in\n// [Gaia](https://github.com/mozilla-b2g/gaia).\n\nvar DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';\nvar supportsBlobs = void 0;\nvar dbContexts = {};\nvar toString = Object.prototype.toString;\n\n// Transaction Modes\nvar READ_ONLY = 'readonly';\nvar READ_WRITE = 'readwrite';\n\n// Transform a binary string to an array buffer, because otherwise\n// weird stuff happens when you try to work with the binary string directly.\n// It is known.\n// From http://stackoverflow.com/questions/14967647/ (continues on next line)\n// encode-decode-image-with-base64-breaks-image (2013-04-21)\nfunction _binStringToArrayBuffer(bin) {\n var length = bin.length;\n var buf = new ArrayBuffer(length);\n var arr = new Uint8Array(buf);\n for (var i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\n//\n// Blobs are not supported in all versions of IndexedDB, notably\n// Chrome <37 and Android <5. In those versions, storing a blob will throw.\n//\n// Various other blob bugs exist in Chrome v37-42 (inclusive).\n// Detecting them is expensive and confusing to users, and Chrome 37-42\n// is at very low usage worldwide, so we do a hacky userAgent check instead.\n//\n// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120\n// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916\n// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836\n//\n// Code borrowed from PouchDB. See:\n// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js\n//\nfunction _checkBlobSupportWithoutCaching(idb) {\n return new Promise$1(function (resolve) {\n var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);\n var blob = createBlob(['']);\n txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');\n\n txn.onabort = function (e) {\n // If the transaction aborts now its due to not being able to\n // write to the database, likely due to the disk being full\n e.preventDefault();\n e.stopPropagation();\n resolve(false);\n };\n\n txn.oncomplete = function () {\n var matchedChrome = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n var matchedEdge = navigator.userAgent.match(/Edge\\//);\n // MS Edge pretends to be Chrome 42:\n // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx\n resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);\n };\n })[\"catch\"](function () {\n return false; // error, so assume unsupported\n });\n}\n\nfunction _checkBlobSupport(idb) {\n if (typeof supportsBlobs === 'boolean') {\n return Promise$1.resolve(supportsBlobs);\n }\n return _checkBlobSupportWithoutCaching(idb).then(function (value) {\n supportsBlobs = value;\n return supportsBlobs;\n });\n}\n\nfunction _deferReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Create a deferred object representing the current database operation.\n var deferredOperation = {};\n\n deferredOperation.promise = new Promise$1(function (resolve, reject) {\n deferredOperation.resolve = resolve;\n deferredOperation.reject = reject;\n });\n\n // Enqueue the deferred operation.\n dbContext.deferredOperations.push(deferredOperation);\n\n // Chain its promise to the database readiness.\n if (!dbContext.dbReady) {\n dbContext.dbReady = deferredOperation.promise;\n } else {\n dbContext.dbReady = dbContext.dbReady.then(function () {\n return deferredOperation.promise;\n });\n }\n}\n\nfunction _advanceReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Resolve its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.resolve();\n return deferredOperation.promise;\n }\n}\n\nfunction _rejectReadiness(dbInfo, err) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Reject its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.reject(err);\n return deferredOperation.promise;\n }\n}\n\nfunction _getConnection(dbInfo, upgradeNeeded) {\n return new Promise$1(function (resolve, reject) {\n dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();\n\n if (dbInfo.db) {\n if (upgradeNeeded) {\n _deferReadiness(dbInfo);\n dbInfo.db.close();\n } else {\n return resolve(dbInfo.db);\n }\n }\n\n var dbArgs = [dbInfo.name];\n\n if (upgradeNeeded) {\n dbArgs.push(dbInfo.version);\n }\n\n var openreq = idb.open.apply(idb, dbArgs);\n\n if (upgradeNeeded) {\n openreq.onupgradeneeded = function (e) {\n var db = openreq.result;\n try {\n db.createObjectStore(dbInfo.storeName);\n if (e.oldVersion <= 1) {\n // Added when support for blob shims was added\n db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);\n }\n } catch (ex) {\n if (ex.name === 'ConstraintError') {\n console.warn('The database \"' + dbInfo.name + '\"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage \"' + dbInfo.storeName + '\" already exists.');\n } else {\n throw ex;\n }\n }\n };\n }\n\n openreq.onerror = function (e) {\n e.preventDefault();\n reject(openreq.error);\n };\n\n openreq.onsuccess = function () {\n resolve(openreq.result);\n _advanceReadiness(dbInfo);\n };\n });\n}\n\nfunction _getOriginalConnection(dbInfo) {\n return _getConnection(dbInfo, false);\n}\n\nfunction _getUpgradedConnection(dbInfo) {\n return _getConnection(dbInfo, true);\n}\n\nfunction _isUpgradeNeeded(dbInfo, defaultVersion) {\n if (!dbInfo.db) {\n return true;\n }\n\n var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);\n var isDowngrade = dbInfo.version < dbInfo.db.version;\n var isUpgrade = dbInfo.version > dbInfo.db.version;\n\n if (isDowngrade) {\n // If the version is not the default one\n // then warn for impossible downgrade.\n if (dbInfo.version !== defaultVersion) {\n console.warn('The database \"' + dbInfo.name + '\"' + \" can't be downgraded from version \" + dbInfo.db.version + ' to version ' + dbInfo.version + '.');\n }\n // Align the versions to prevent errors.\n dbInfo.version = dbInfo.db.version;\n }\n\n if (isUpgrade || isNewStore) {\n // If the store is new then increment the version (if needed).\n // This will trigger an \"upgradeneeded\" event which is required\n // for creating a store.\n if (isNewStore) {\n var incVersion = dbInfo.db.version + 1;\n if (incVersion > dbInfo.version) {\n dbInfo.version = incVersion;\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n// encode a blob for indexeddb engines that don't support blobs\nfunction _encodeBlob(blob) {\n return new Promise$1(function (resolve, reject) {\n var reader = new FileReader();\n reader.onerror = reject;\n reader.onloadend = function (e) {\n var base64 = btoa(e.target.result || '');\n resolve({\n __local_forage_encoded_blob: true,\n data: base64,\n type: blob.type\n });\n };\n reader.readAsBinaryString(blob);\n });\n}\n\n// decode an encoded blob\nfunction _decodeBlob(encodedBlob) {\n var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));\n return createBlob([arrayBuff], { type: encodedBlob.type });\n}\n\n// is this one of our fancy encoded blobs?\nfunction _isEncodedBlob(value) {\n return value && value.__local_forage_encoded_blob;\n}\n\n// Specialize the default `ready()` function by making it dependent\n// on the current database operations. Thus, the driver will be actually\n// ready when it's been initialized (default) *and* there are no pending\n// operations on the database (initiated by some other instances).\nfunction _fullyReady(callback) {\n var self = this;\n\n var promise = self._initReady().then(function () {\n var dbContext = dbContexts[self._dbInfo.name];\n\n if (dbContext && dbContext.dbReady) {\n return dbContext.dbReady;\n }\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n}\n\n// Try to establish a new db connection to replace the\n// current one which is broken (i.e. experiencing\n// InvalidStateError while creating a transaction).\nfunction _tryReconnect(dbInfo) {\n _deferReadiness(dbInfo);\n\n var dbContext = dbContexts[dbInfo.name];\n var forages = dbContext.forages;\n\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n if (forage._dbInfo.db) {\n forage._dbInfo.db.close();\n forage._dbInfo.db = null;\n }\n }\n dbInfo.db = null;\n\n return _getOriginalConnection(dbInfo).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n // store the latest db reference\n // in case the db was upgraded\n dbInfo.db = dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n })[\"catch\"](function (err) {\n _rejectReadiness(dbInfo, err);\n throw err;\n });\n}\n\n// FF doesn't like Promises (micro-tasks) and IDDB store operations,\n// so we have to do it with callbacks\nfunction createTransaction(dbInfo, mode, callback, retries) {\n if (retries === undefined) {\n retries = 1;\n }\n\n try {\n var tx = dbInfo.db.transaction(dbInfo.storeName, mode);\n callback(null, tx);\n } catch (err) {\n if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {\n return Promise$1.resolve().then(function () {\n if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {\n // increase the db version, to create the new ObjectStore\n if (dbInfo.db) {\n dbInfo.version = dbInfo.db.version + 1;\n }\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n }).then(function () {\n return _tryReconnect(dbInfo).then(function () {\n createTransaction(dbInfo, mode, callback, retries - 1);\n });\n })[\"catch\"](callback);\n }\n\n callback(err);\n }\n}\n\nfunction createDbContext() {\n return {\n // Running localForages sharing a database.\n forages: [],\n // Shared database.\n db: null,\n // Database readiness (promise).\n dbReady: null,\n // Deferred operations on the database.\n deferredOperations: []\n };\n}\n\n// Open the IndexedDB database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n // Get the current context of the database;\n var dbContext = dbContexts[dbInfo.name];\n\n // ...or create a new context.\n if (!dbContext) {\n dbContext = createDbContext();\n // Register the new context in the global container.\n dbContexts[dbInfo.name] = dbContext;\n }\n\n // Register itself as a running localForage in the current context.\n dbContext.forages.push(self);\n\n // Replace the default `ready()` function with the specialized one.\n if (!self._initReady) {\n self._initReady = self.ready;\n self.ready = _fullyReady;\n }\n\n // Create an array of initialization states of the related localForages.\n var initPromises = [];\n\n function ignoreErrors() {\n // Don't handle errors here,\n // just makes sure related localForages aren't pending.\n return Promise$1.resolve();\n }\n\n for (var j = 0; j < dbContext.forages.length; j++) {\n var forage = dbContext.forages[j];\n if (forage !== self) {\n // Don't wait for itself...\n initPromises.push(forage._initReady()[\"catch\"](ignoreErrors));\n }\n }\n\n // Take a snapshot of the related localForages.\n var forages = dbContext.forages.slice(0);\n\n // Initialize the connection process only when\n // all the related localForages aren't pending.\n return Promise$1.all(initPromises).then(function () {\n dbInfo.db = dbContext.db;\n // Get the connection or open a new one without upgrade.\n return _getOriginalConnection(dbInfo);\n }).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n dbInfo.db = dbContext.db = db;\n self._dbInfo = dbInfo;\n // Share the final connection amongst related localForages.\n for (var k = 0; k < forages.length; k++) {\n var forage = forages[k];\n if (forage !== self) {\n // Self is already up-to-date.\n forage._dbInfo.db = dbInfo.db;\n forage._dbInfo.version = dbInfo.version;\n }\n }\n });\n}\n\nfunction getItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.get(key);\n\n req.onsuccess = function () {\n var value = req.result;\n if (value === undefined) {\n value = null;\n }\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n resolve(value);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items stored in database.\nfunction iterate(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openCursor();\n var iterationNumber = 1;\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (cursor) {\n var value = cursor.value;\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n var result = iterator(value, cursor.key, iterationNumber++);\n\n // when the iterator callback returns any\n // (non-`undefined`) value, then we stop\n // the iteration immediately\n if (result !== void 0) {\n resolve(result);\n } else {\n cursor[\"continue\"]();\n }\n } else {\n resolve();\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n\n return promise;\n}\n\nfunction setItem(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n var dbInfo;\n self.ready().then(function () {\n dbInfo = self._dbInfo;\n if (toString.call(value) === '[object Blob]') {\n return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {\n if (blobSupport) {\n return value;\n }\n return _encodeBlob(value);\n });\n }\n return value;\n }).then(function (value) {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n\n // The reason we don't _save_ null is because IE 10 does\n // not support saving the `null` type in IndexedDB. How\n // ironic, given the bug below!\n // See: https://github.com/mozilla/localForage/issues/161\n if (value === null) {\n value = undefined;\n }\n\n var req = store.put(value, key);\n\n transaction.oncomplete = function () {\n // Cast to undefined so the value passed to\n // callback/promise is the same as what one would get out\n // of `getItem()` later. This leads to some weirdness\n // (setItem('foo', undefined) will return `null`), but\n // it's not my fault localStorage is our baseline and that\n // it's weird.\n if (value === undefined) {\n value = null;\n }\n\n resolve(value);\n };\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction removeItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n // We use a Grunt task to make this safe for IE and some\n // versions of Android (including those used by Cordova).\n // Normally IE won't like `.delete()` and will insist on\n // using `['delete']()`, but we have a build step that\n // fixes this for us now.\n var req = store[\"delete\"](key);\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onerror = function () {\n reject(req.error);\n };\n\n // The request will be also be aborted if we've exceeded our storage\n // space.\n transaction.onabort = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction clear(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.clear();\n\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction length(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.count();\n\n req.onsuccess = function () {\n resolve(req.result);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction key(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n if (n < 0) {\n resolve(null);\n\n return;\n }\n\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var advanced = false;\n var req = store.openKeyCursor();\n\n req.onsuccess = function () {\n var cursor = req.result;\n if (!cursor) {\n // this means there weren't enough keys\n resolve(null);\n\n return;\n }\n\n if (n === 0) {\n // We have the first key, return it if that's what they\n // wanted.\n resolve(cursor.key);\n } else {\n if (!advanced) {\n // Otherwise, ask the cursor to skip ahead n\n // records.\n advanced = true;\n cursor.advance(n);\n } else {\n // When we get here, we've got the nth key.\n resolve(cursor.key);\n }\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openKeyCursor();\n var keys = [];\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (!cursor) {\n resolve(keys);\n return;\n }\n\n keys.push(cursor.key);\n cursor[\"continue\"]();\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;\n\n var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n return db;\n });\n\n if (!options.storeName) {\n promise = dbPromise.then(function (db) {\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n }\n\n var dropDBPromise = new Promise$1(function (resolve, reject) {\n var req = idb.deleteDatabase(options.name);\n\n req.onerror = req.onblocked = function (err) {\n var db = req.result;\n if (db) {\n db.close();\n }\n reject(err);\n };\n\n req.onsuccess = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n resolve(db);\n };\n });\n\n return dropDBPromise.then(function (db) {\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n var _forage = forages[i];\n _advanceReadiness(_forage._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n } else {\n promise = dbPromise.then(function (db) {\n if (!db.objectStoreNames.contains(options.storeName)) {\n return;\n }\n\n var newVersion = db.version + 1;\n\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n forage._dbInfo.version = newVersion;\n }\n\n var dropObjectPromise = new Promise$1(function (resolve, reject) {\n var req = idb.open(options.name, newVersion);\n\n req.onerror = function (err) {\n var db = req.result;\n db.close();\n reject(err);\n };\n\n req.onupgradeneeded = function () {\n var db = req.result;\n db.deleteObjectStore(options.storeName);\n };\n\n req.onsuccess = function () {\n var db = req.result;\n db.close();\n resolve(db);\n };\n });\n\n return dropObjectPromise.then(function (db) {\n dbContext.db = db;\n for (var j = 0; j < forages.length; j++) {\n var _forage2 = forages[j];\n _forage2._dbInfo.db = db;\n _advanceReadiness(_forage2._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n }\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar asyncStorage = {\n _driver: 'asyncStorage',\n _initStorage: _initStorage,\n _support: isIndexedDBValid(),\n iterate: iterate,\n getItem: getItem,\n setItem: setItem,\n removeItem: removeItem,\n clear: clear,\n length: length,\n key: key,\n keys: keys,\n dropInstance: dropInstance\n};\n\nfunction isWebSQLValid() {\n return typeof openDatabase === 'function';\n}\n\n// Sadly, the best way to save binary data in WebSQL/localStorage is serializing\n// it to Base64, so this is how we store it to prevent very strange errors with less\n// verbose ways of binary <-> string data storage.\nvar BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nvar BLOB_TYPE_PREFIX = '~~local_forage_type~';\nvar BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;\n\nvar SERIALIZED_MARKER = '__lfsc__:';\nvar SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;\n\n// OMG the serializations!\nvar TYPE_ARRAYBUFFER = 'arbf';\nvar TYPE_BLOB = 'blob';\nvar TYPE_INT8ARRAY = 'si08';\nvar TYPE_UINT8ARRAY = 'ui08';\nvar TYPE_UINT8CLAMPEDARRAY = 'uic8';\nvar TYPE_INT16ARRAY = 'si16';\nvar TYPE_INT32ARRAY = 'si32';\nvar TYPE_UINT16ARRAY = 'ur16';\nvar TYPE_UINT32ARRAY = 'ui32';\nvar TYPE_FLOAT32ARRAY = 'fl32';\nvar TYPE_FLOAT64ARRAY = 'fl64';\nvar TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;\n\nvar toString$1 = Object.prototype.toString;\n\nfunction stringToBuffer(serializedString) {\n // Fill the string into a ArrayBuffer.\n var bufferLength = serializedString.length * 0.75;\n var len = serializedString.length;\n var i;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (serializedString[serializedString.length - 1] === '=') {\n bufferLength--;\n if (serializedString[serializedString.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var buffer = new ArrayBuffer(bufferLength);\n var bytes = new Uint8Array(buffer);\n\n for (i = 0; i < len; i += 4) {\n encoded1 = BASE_CHARS.indexOf(serializedString[i]);\n encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);\n encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);\n encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);\n\n /*jslint bitwise: true */\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n return buffer;\n}\n\n// Converts a buffer to a string to store, serialized, in the backend\n// storage library.\nfunction bufferToString(buffer) {\n // base64-arraybuffer\n var bytes = new Uint8Array(buffer);\n var base64String = '';\n var i;\n\n for (i = 0; i < bytes.length; i += 3) {\n /*jslint bitwise: true */\n base64String += BASE_CHARS[bytes[i] >> 2];\n base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n base64String += BASE_CHARS[bytes[i + 2] & 63];\n }\n\n if (bytes.length % 3 === 2) {\n base64String = base64String.substring(0, base64String.length - 1) + '=';\n } else if (bytes.length % 3 === 1) {\n base64String = base64String.substring(0, base64String.length - 2) + '==';\n }\n\n return base64String;\n}\n\n// Serialize a value, afterwards executing a callback (which usually\n// instructs the `setItem()` callback/promise to be executed). This is how\n// we store binary data with localStorage.\nfunction serialize(value, callback) {\n var valueType = '';\n if (value) {\n valueType = toString$1.call(value);\n }\n\n // Cannot use `value instanceof ArrayBuffer` or such here, as these\n // checks fail when running the tests using casper.js...\n //\n // TODO: See why those tests fail and use a better solution.\n if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {\n // Convert binary arrays to a string and prefix the string with\n // a special marker.\n var buffer;\n var marker = SERIALIZED_MARKER;\n\n if (value instanceof ArrayBuffer) {\n buffer = value;\n marker += TYPE_ARRAYBUFFER;\n } else {\n buffer = value.buffer;\n\n if (valueType === '[object Int8Array]') {\n marker += TYPE_INT8ARRAY;\n } else if (valueType === '[object Uint8Array]') {\n marker += TYPE_UINT8ARRAY;\n } else if (valueType === '[object Uint8ClampedArray]') {\n marker += TYPE_UINT8CLAMPEDARRAY;\n } else if (valueType === '[object Int16Array]') {\n marker += TYPE_INT16ARRAY;\n } else if (valueType === '[object Uint16Array]') {\n marker += TYPE_UINT16ARRAY;\n } else if (valueType === '[object Int32Array]') {\n marker += TYPE_INT32ARRAY;\n } else if (valueType === '[object Uint32Array]') {\n marker += TYPE_UINT32ARRAY;\n } else if (valueType === '[object Float32Array]') {\n marker += TYPE_FLOAT32ARRAY;\n } else if (valueType === '[object Float64Array]') {\n marker += TYPE_FLOAT64ARRAY;\n } else {\n callback(new Error('Failed to get type for BinaryArray'));\n }\n }\n\n callback(marker + bufferToString(buffer));\n } else if (valueType === '[object Blob]') {\n // Conver the blob to a binaryArray and then to a string.\n var fileReader = new FileReader();\n\n fileReader.onload = function () {\n // Backwards-compatible prefix for the blob type.\n var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);\n\n callback(SERIALIZED_MARKER + TYPE_BLOB + str);\n };\n\n fileReader.readAsArrayBuffer(value);\n } else {\n try {\n callback(JSON.stringify(value));\n } catch (e) {\n console.error(\"Couldn't convert value into a JSON string: \", value);\n\n callback(null, e);\n }\n }\n}\n\n// Deserialize data we've inserted into a value column/field. We place\n// special markers into our strings to mark them as encoded; this isn't\n// as nice as a meta field, but it's the only sane thing we can do whilst\n// keeping localStorage support intact.\n//\n// Oftentimes this will just deserialize JSON content, but if we have a\n// special marker (SERIALIZED_MARKER, defined above), we will extract\n// some kind of arraybuffer/binary data/typed array out of the string.\nfunction deserialize(value) {\n // If we haven't marked this string as being specially serialized (i.e.\n // something other than serialized JSON), we can just return it and be\n // done with it.\n if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {\n return JSON.parse(value);\n }\n\n // The following code deals with deserializing some kind of Blob or\n // TypedArray. First we separate out the type of data we're dealing\n // with from the data itself.\n var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);\n var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);\n\n var blobType;\n // Backwards-compatible blob type serialization strategy.\n // DBs created with older versions of localForage will simply not have the blob type.\n if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {\n var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);\n blobType = matcher[1];\n serializedString = serializedString.substring(matcher[0].length);\n }\n var buffer = stringToBuffer(serializedString);\n\n // Return the right type based on the code/type set during\n // serialization.\n switch (type) {\n case TYPE_ARRAYBUFFER:\n return buffer;\n case TYPE_BLOB:\n return createBlob([buffer], { type: blobType });\n case TYPE_INT8ARRAY:\n return new Int8Array(buffer);\n case TYPE_UINT8ARRAY:\n return new Uint8Array(buffer);\n case TYPE_UINT8CLAMPEDARRAY:\n return new Uint8ClampedArray(buffer);\n case TYPE_INT16ARRAY:\n return new Int16Array(buffer);\n case TYPE_UINT16ARRAY:\n return new Uint16Array(buffer);\n case TYPE_INT32ARRAY:\n return new Int32Array(buffer);\n case TYPE_UINT32ARRAY:\n return new Uint32Array(buffer);\n case TYPE_FLOAT32ARRAY:\n return new Float32Array(buffer);\n case TYPE_FLOAT64ARRAY:\n return new Float64Array(buffer);\n default:\n throw new Error('Unkown type: ' + type);\n }\n}\n\nvar localforageSerializer = {\n serialize: serialize,\n deserialize: deserialize,\n stringToBuffer: stringToBuffer,\n bufferToString: bufferToString\n};\n\n/*\n * Includes code from:\n *\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n\nfunction createDbTable(t, dbInfo, callback, errorCallback) {\n t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);\n}\n\n// Open the WebSQL database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage$1(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];\n }\n }\n\n var dbInfoPromise = new Promise$1(function (resolve, reject) {\n // Open the database; the openDatabase API will automatically\n // create it for us if it doesn't exist.\n try {\n dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);\n } catch (e) {\n return reject(e);\n }\n\n // Create our key/value table if it doesn't exist.\n dbInfo.db.transaction(function (t) {\n createDbTable(t, dbInfo, function () {\n self._dbInfo = dbInfo;\n resolve();\n }, function (t, error) {\n reject(error);\n });\n }, reject);\n });\n\n dbInfo.serializer = localforageSerializer;\n return dbInfoPromise;\n}\n\nfunction tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {\n t.executeSql(sqlStatement, args, callback, function (t, error) {\n if (error.code === error.SYNTAX_ERR) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name = ?\", [dbInfo.storeName], function (t, results) {\n if (!results.rows.length) {\n // if the table is missing (was deleted)\n // re-create it table and retry\n createDbTable(t, dbInfo, function () {\n t.executeSql(sqlStatement, args, callback, errorCallback);\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n}\n\nfunction getItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).value : null;\n\n // Check to see if this is serialized content we need to\n // unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction iterate$1(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {\n var rows = results.rows;\n var length = rows.length;\n\n for (var i = 0; i < length; i++) {\n var item = rows.item(i);\n var result = item.value;\n\n // Check to see if this is serialized content\n // we need to unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n result = iterator(result, item.key, i + 1);\n\n // void(0) prevents problems with redefinition\n // of `undefined`.\n if (result !== void 0) {\n resolve(result);\n return;\n }\n }\n\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction _setItem(key, value, callback, retriesLeft) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n // The localStorage API doesn't return undefined values in an\n // \"expected\" way, so undefined is always cast to null in all\n // drivers. See: https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {\n resolve(originalValue);\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n // The transaction failed; check\n // to see if it's a quota error.\n if (sqlError.code === sqlError.QUOTA_ERR) {\n // We reject the callback outright for now, but\n // it's worth trying to re-run the transaction.\n // Even if the user accepts the prompt to use\n // more storage on Safari, this error will\n // be called.\n //\n // Try to re-run the transaction.\n if (retriesLeft > 0) {\n resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));\n return;\n }\n reject(sqlError);\n }\n });\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction setItem$1(key, value, callback) {\n return _setItem.apply(this, [key, value, callback, 1]);\n}\n\nfunction removeItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Deletes every item in the table.\n// TODO: Find out if this resets the AUTO_INCREMENT number.\nfunction clear$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Does a simple `COUNT(key)` to get the number of items stored in\n// localForage.\nfunction length$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n // Ahhh, SQL makes this one soooooo easy.\n tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {\n var result = results.rows.item(0).c;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Return the key located at key index X; essentially gets the key from a\n// `WHERE id = ?`. This is the most efficient way I can think to implement\n// this rarely-used (in my experience) part of the API, but it can seem\n// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so\n// the ID of each key will change every time it's updated. Perhaps a stored\n// procedure for the `setItem()` SQL would solve this problem?\n// TODO: Don't change ID on `setItem()`.\nfunction key$1(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).key : null;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {\n var keys = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n keys.push(results.rows.item(i).key);\n }\n\n resolve(keys);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// https://www.w3.org/TR/webdatabase/#databases\n// > There is no way to enumerate or delete the databases available for an origin from this API.\nfunction getAllStoreNames(db) {\n return new Promise$1(function (resolve, reject) {\n db.transaction(function (t) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'\", [], function (t, results) {\n var storeNames = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n storeNames.push(results.rows.item(i).name);\n }\n\n resolve({\n db: db,\n storeNames: storeNames\n });\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n}\n\nfunction dropInstance$1(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n var db;\n if (options.name === currentConfig.name) {\n // use the db reference of the current instance\n db = self._dbInfo.db;\n } else {\n db = openDatabase(options.name, '', '', 0);\n }\n\n if (!options.storeName) {\n // drop all database tables\n resolve(getAllStoreNames(db));\n } else {\n resolve({\n db: db,\n storeNames: [options.storeName]\n });\n }\n }).then(function (operationInfo) {\n return new Promise$1(function (resolve, reject) {\n operationInfo.db.transaction(function (t) {\n function dropTable(storeName) {\n return new Promise$1(function (resolve, reject) {\n t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n }\n\n var operations = [];\n for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {\n operations.push(dropTable(operationInfo.storeNames[i]));\n }\n\n Promise$1.all(operations).then(function () {\n resolve();\n })[\"catch\"](function (e) {\n reject(e);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar webSQLStorage = {\n _driver: 'webSQLStorage',\n _initStorage: _initStorage$1,\n _support: isWebSQLValid(),\n iterate: iterate$1,\n getItem: getItem$1,\n setItem: setItem$1,\n removeItem: removeItem$1,\n clear: clear$1,\n length: length$1,\n key: key$1,\n keys: keys$1,\n dropInstance: dropInstance$1\n};\n\nfunction isLocalStorageValid() {\n try {\n return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&\n // in IE8 typeof localStorage.setItem === 'object'\n !!localStorage.setItem;\n } catch (e) {\n return false;\n }\n}\n\nfunction _getKeyPrefix(options, defaultConfig) {\n var keyPrefix = options.name + '/';\n\n if (options.storeName !== defaultConfig.storeName) {\n keyPrefix += options.storeName + '/';\n }\n return keyPrefix;\n}\n\n// Check if localStorage throws when saving an item\nfunction checkIfLocalStorageThrows() {\n var localStorageTestKey = '_localforage_support_test';\n\n try {\n localStorage.setItem(localStorageTestKey, true);\n localStorage.removeItem(localStorageTestKey);\n\n return false;\n } catch (e) {\n return true;\n }\n}\n\n// Check if localStorage is usable and allows to save an item\n// This method checks if localStorage is usable in Safari Private Browsing\n// mode, or in any other case where the available quota for localStorage\n// is 0 and there wasn't any saved items yet.\nfunction _isLocalStorageUsable() {\n return !checkIfLocalStorageThrows() || localStorage.length > 0;\n}\n\n// Config the localStorage backend, using options set in the config.\nfunction _initStorage$2(options) {\n var self = this;\n var dbInfo = {};\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);\n\n if (!_isLocalStorageUsable()) {\n return Promise$1.reject();\n }\n\n self._dbInfo = dbInfo;\n dbInfo.serializer = localforageSerializer;\n\n return Promise$1.resolve();\n}\n\n// Remove all keys from the datastore, effectively destroying all data in\n// the app's key/value store!\nfunction clear$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var keyPrefix = self._dbInfo.keyPrefix;\n\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Retrieve an item from the store. Unlike the original async_storage\n// library in Gaia, we don't modify return values at all. If a key's value\n// is `undefined`, we pass that value to the callback function.\nfunction getItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result = localStorage.getItem(dbInfo.keyPrefix + key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the key\n // is likely undefined and we'll pass it straight to the\n // callback.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items in the store.\nfunction iterate$2(iterator, callback) {\n var self = this;\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var keyPrefix = dbInfo.keyPrefix;\n var keyPrefixLength = keyPrefix.length;\n var length = localStorage.length;\n\n // We use a dedicated iterator instead of the `i` variable below\n // so other keys we fetch in localStorage aren't counted in\n // the `iterationNumber` argument passed to the `iterate()`\n // callback.\n //\n // See: github.com/mozilla/localForage/pull/435#discussion_r38061530\n var iterationNumber = 1;\n\n for (var i = 0; i < length; i++) {\n var key = localStorage.key(i);\n if (key.indexOf(keyPrefix) !== 0) {\n continue;\n }\n var value = localStorage.getItem(key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the\n // key is likely undefined and we'll pass it straight\n // to the iterator.\n if (value) {\n value = dbInfo.serializer.deserialize(value);\n }\n\n value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);\n\n if (value !== void 0) {\n return value;\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Same as localStorage's key() method, except takes a callback.\nfunction key$2(n, callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result;\n try {\n result = localStorage.key(n);\n } catch (error) {\n result = null;\n }\n\n // Remove the prefix from the key, if a key is found.\n if (result) {\n result = result.substring(dbInfo.keyPrefix.length);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var length = localStorage.length;\n var keys = [];\n\n for (var i = 0; i < length; i++) {\n var itemKey = localStorage.key(i);\n if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {\n keys.push(itemKey.substring(dbInfo.keyPrefix.length));\n }\n }\n\n return keys;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Supply the number of keys in the datastore to the callback function.\nfunction length$2(callback) {\n var self = this;\n var promise = self.keys().then(function (keys) {\n return keys.length;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Remove an item from the store, nice and simple.\nfunction removeItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n localStorage.removeItem(dbInfo.keyPrefix + key);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Set a key's value and run an optional callback once the value is set.\n// Unlike Gaia's implementation, the callback function is passed the value,\n// in case you want to operate on that value only after you're sure it\n// saved, or something like that.\nfunction setItem$2(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n // Convert undefined values to null.\n // https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n return new Promise$1(function (resolve, reject) {\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n try {\n localStorage.setItem(dbInfo.keyPrefix + key, value);\n resolve(originalValue);\n } catch (e) {\n // localStorage capacity exceeded.\n // TODO: Make this a specific error/event.\n if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {\n reject(e);\n }\n reject(e);\n }\n }\n });\n });\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance$2(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n var currentConfig = this.config();\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n if (!options.storeName) {\n resolve(options.name + '/');\n } else {\n resolve(_getKeyPrefix(options, self._defaultConfig));\n }\n }).then(function (keyPrefix) {\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar localStorageWrapper = {\n _driver: 'localStorageWrapper',\n _initStorage: _initStorage$2,\n _support: isLocalStorageValid(),\n iterate: iterate$2,\n getItem: getItem$2,\n setItem: setItem$2,\n removeItem: removeItem$2,\n clear: clear$2,\n length: length$2,\n key: key$2,\n keys: keys$2,\n dropInstance: dropInstance$2\n};\n\nvar sameValue = function sameValue(x, y) {\n return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);\n};\n\nvar includes = function includes(array, searchElement) {\n var len = array.length;\n var i = 0;\n while (i < len) {\n if (sameValue(array[i], searchElement)) {\n return true;\n }\n i++;\n }\n\n return false;\n};\n\nvar isArray = Array.isArray || function (arg) {\n return Object.prototype.toString.call(arg) === '[object Array]';\n};\n\n// Drivers are stored here when `defineDriver()` is called.\n// They are shared across all instances of localForage.\nvar DefinedDrivers = {};\n\nvar DriverSupport = {};\n\nvar DefaultDrivers = {\n INDEXEDDB: asyncStorage,\n WEBSQL: webSQLStorage,\n LOCALSTORAGE: localStorageWrapper\n};\n\nvar DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];\n\nvar OptionalDriverMethods = ['dropInstance'];\n\nvar LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);\n\nvar DefaultConfig = {\n description: '',\n driver: DefaultDriverOrder.slice(),\n name: 'localforage',\n // Default DB size is _JUST UNDER_ 5MB, as it's the highest size\n // we can use without a prompt.\n size: 4980736,\n storeName: 'keyvaluepairs',\n version: 1.0\n};\n\nfunction callWhenReady(localForageInstance, libraryMethod) {\n localForageInstance[libraryMethod] = function () {\n var _args = arguments;\n return localForageInstance.ready().then(function () {\n return localForageInstance[libraryMethod].apply(localForageInstance, _args);\n });\n };\n}\n\nfunction extend() {\n for (var i = 1; i < arguments.length; i++) {\n var arg = arguments[i];\n\n if (arg) {\n for (var _key in arg) {\n if (arg.hasOwnProperty(_key)) {\n if (isArray(arg[_key])) {\n arguments[0][_key] = arg[_key].slice();\n } else {\n arguments[0][_key] = arg[_key];\n }\n }\n }\n }\n }\n\n return arguments[0];\n}\n\nvar LocalForage = function () {\n function LocalForage(options) {\n _classCallCheck(this, LocalForage);\n\n for (var driverTypeKey in DefaultDrivers) {\n if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {\n var driver = DefaultDrivers[driverTypeKey];\n var driverName = driver._driver;\n this[driverTypeKey] = driverName;\n\n if (!DefinedDrivers[driverName]) {\n // we don't need to wait for the promise,\n // since the default drivers can be defined\n // in a blocking manner\n this.defineDriver(driver);\n }\n }\n }\n\n this._defaultConfig = extend({}, DefaultConfig);\n this._config = extend({}, this._defaultConfig, options);\n this._driverSet = null;\n this._initDriver = null;\n this._ready = false;\n this._dbInfo = null;\n\n this._wrapLibraryMethodsWithReady();\n this.setDriver(this._config.driver)[\"catch\"](function () {});\n }\n\n // Set any config values for localForage; can be called anytime before\n // the first API call (e.g. `getItem`, `setItem`).\n // We loop through options so we don't overwrite existing config\n // values.\n\n\n LocalForage.prototype.config = function config(options) {\n // If the options argument is an object, we use it to set values.\n // Otherwise, we return either a specified config value or all\n // config values.\n if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {\n // If localforage is ready and fully initialized, we can't set\n // any new configuration values. Instead, we return an error.\n if (this._ready) {\n return new Error(\"Can't call config() after localforage \" + 'has been used.');\n }\n\n for (var i in options) {\n if (i === 'storeName') {\n options[i] = options[i].replace(/\\W/g, '_');\n }\n\n if (i === 'version' && typeof options[i] !== 'number') {\n return new Error('Database version must be a number.');\n }\n\n this._config[i] = options[i];\n }\n\n // after all config options are set and\n // the driver option is used, try setting it\n if ('driver' in options && options.driver) {\n return this.setDriver(this._config.driver);\n }\n\n return true;\n } else if (typeof options === 'string') {\n return this._config[options];\n } else {\n return this._config;\n }\n };\n\n // Used to define a custom driver, shared across all instances of\n // localForage.\n\n\n LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {\n var promise = new Promise$1(function (resolve, reject) {\n try {\n var driverName = driverObject._driver;\n var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');\n\n // A driver name should be defined and not overlap with the\n // library-defined, default drivers.\n if (!driverObject._driver) {\n reject(complianceError);\n return;\n }\n\n var driverMethods = LibraryMethods.concat('_initStorage');\n for (var i = 0, len = driverMethods.length; i < len; i++) {\n var driverMethodName = driverMethods[i];\n\n // when the property is there,\n // it should be a method even when optional\n var isRequired = !includes(OptionalDriverMethods, driverMethodName);\n if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {\n reject(complianceError);\n return;\n }\n }\n\n var configureMissingMethods = function configureMissingMethods() {\n var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {\n return function () {\n var error = new Error('Method ' + methodName + ' is not implemented by the current driver');\n var promise = Promise$1.reject(error);\n executeCallback(promise, arguments[arguments.length - 1]);\n return promise;\n };\n };\n\n for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {\n var optionalDriverMethod = OptionalDriverMethods[_i];\n if (!driverObject[optionalDriverMethod]) {\n driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);\n }\n }\n };\n\n configureMissingMethods();\n\n var setDriverSupport = function setDriverSupport(support) {\n if (DefinedDrivers[driverName]) {\n console.info('Redefining LocalForage driver: ' + driverName);\n }\n DefinedDrivers[driverName] = driverObject;\n DriverSupport[driverName] = support;\n // don't use a then, so that we can define\n // drivers that have simple _support methods\n // in a blocking manner\n resolve();\n };\n\n if ('_support' in driverObject) {\n if (driverObject._support && typeof driverObject._support === 'function') {\n driverObject._support().then(setDriverSupport, reject);\n } else {\n setDriverSupport(!!driverObject._support);\n }\n } else {\n setDriverSupport(true);\n }\n } catch (e) {\n reject(e);\n }\n });\n\n executeTwoCallbacks(promise, callback, errorCallback);\n return promise;\n };\n\n LocalForage.prototype.driver = function driver() {\n return this._driver || null;\n };\n\n LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {\n var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));\n\n executeTwoCallbacks(getDriverPromise, callback, errorCallback);\n return getDriverPromise;\n };\n\n LocalForage.prototype.getSerializer = function getSerializer(callback) {\n var serializerPromise = Promise$1.resolve(localforageSerializer);\n executeTwoCallbacks(serializerPromise, callback);\n return serializerPromise;\n };\n\n LocalForage.prototype.ready = function ready(callback) {\n var self = this;\n\n var promise = self._driverSet.then(function () {\n if (self._ready === null) {\n self._ready = self._initDriver();\n }\n\n return self._ready;\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n };\n\n LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {\n var self = this;\n\n if (!isArray(drivers)) {\n drivers = [drivers];\n }\n\n var supportedDrivers = this._getSupportedDrivers(drivers);\n\n function setDriverToConfig() {\n self._config.driver = self.driver();\n }\n\n function extendSelfWithDriver(driver) {\n self._extend(driver);\n setDriverToConfig();\n\n self._ready = self._initStorage(self._config);\n return self._ready;\n }\n\n function initDriver(supportedDrivers) {\n return function () {\n var currentDriverIndex = 0;\n\n function driverPromiseLoop() {\n while (currentDriverIndex < supportedDrivers.length) {\n var driverName = supportedDrivers[currentDriverIndex];\n currentDriverIndex++;\n\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(extendSelfWithDriver)[\"catch\"](driverPromiseLoop);\n }\n\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n }\n\n return driverPromiseLoop();\n };\n }\n\n // There might be a driver initialization in progress\n // so wait for it to finish in order to avoid a possible\n // race condition to set _dbInfo\n var oldDriverSetDone = this._driverSet !== null ? this._driverSet[\"catch\"](function () {\n return Promise$1.resolve();\n }) : Promise$1.resolve();\n\n this._driverSet = oldDriverSetDone.then(function () {\n var driverName = supportedDrivers[0];\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(function (driver) {\n self._driver = driver._driver;\n setDriverToConfig();\n self._wrapLibraryMethodsWithReady();\n self._initDriver = initDriver(supportedDrivers);\n });\n })[\"catch\"](function () {\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n });\n\n executeTwoCallbacks(this._driverSet, callback, errorCallback);\n return this._driverSet;\n };\n\n LocalForage.prototype.supports = function supports(driverName) {\n return !!DriverSupport[driverName];\n };\n\n LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {\n extend(this, libraryMethodsAndProperties);\n };\n\n LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {\n var supportedDrivers = [];\n for (var i = 0, len = drivers.length; i < len; i++) {\n var driverName = drivers[i];\n if (this.supports(driverName)) {\n supportedDrivers.push(driverName);\n }\n }\n return supportedDrivers;\n };\n\n LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {\n // Add a stub for each driver API method that delays the call to the\n // corresponding driver method until localForage is ready. These stubs\n // will be replaced by the driver methods as soon as the driver is\n // loaded, so there is no performance impact.\n for (var i = 0, len = LibraryMethods.length; i < len; i++) {\n callWhenReady(this, LibraryMethods[i]);\n }\n };\n\n LocalForage.prototype.createInstance = function createInstance(options) {\n return new LocalForage(options);\n };\n\n return LocalForage;\n}();\n\n// The actual localForage object that we expose as a module or via a\n// global. It's extended by pulling in one of our other libraries.\n\n\nvar localforage_js = new LocalForage();\n\nmodule.exports = localforage_js;\n\n},{\"3\":3}]},{},[4])(4)\n});\n","/**\n * A doubly linked list-based Least Recently Used (LRU) cache. Will keep most\n * recently used items while discarding least recently used items when its limit\n * is reached.\n *\n * Licensed under MIT. Copyright (c) 2010 Rasmus Andersson \n * See README.md for details.\n *\n * Illustration of the design:\n *\n * entry entry entry entry\n * ______ ______ ______ ______\n * | head |.newer => | |.newer => | |.newer => | tail |\n * | A | | B | | C | | D |\n * |______| <= older.|______| <= older.|______| <= older.|______|\n *\n * removed <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- added\n */\n(function(g,f){\n const e = typeof exports == 'object' ? exports : typeof g == 'object' ? g : {};\n f(e);\n if (typeof define == 'function' && define.amd) { define('lru', e); }\n})(this, function(exports) {\n\nconst NEWER = Symbol('newer');\nconst OLDER = Symbol('older');\n\nfunction LRUMap(limit, entries) {\n if (typeof limit !== 'number') {\n // called as (entries)\n entries = limit;\n limit = 0;\n }\n\n this.size = 0;\n this.limit = limit;\n this.oldest = this.newest = undefined;\n this._keymap = new Map();\n\n if (entries) {\n this.assign(entries);\n if (limit < 1) {\n this.limit = this.size;\n }\n }\n}\n\nexports.LRUMap = LRUMap;\n\nfunction Entry(key, value) {\n this.key = key;\n this.value = value;\n this[NEWER] = undefined;\n this[OLDER] = undefined;\n}\n\n\nLRUMap.prototype._markEntryAsUsed = function(entry) {\n if (entry === this.newest) {\n // Already the most recenlty used entry, so no need to update the list\n return;\n }\n // HEAD--------------TAIL\n // <.older .newer>\n // <--- add direction --\n // A B C E\n if (entry[NEWER]) {\n if (entry === this.oldest) {\n this.oldest = entry[NEWER];\n }\n entry[NEWER][OLDER] = entry[OLDER]; // C <-- E.\n }\n if (entry[OLDER]) {\n entry[OLDER][NEWER] = entry[NEWER]; // C. --> E\n }\n entry[NEWER] = undefined; // D --x\n entry[OLDER] = this.newest; // D. --> E\n if (this.newest) {\n this.newest[NEWER] = entry; // E. <-- D\n }\n this.newest = entry;\n};\n\nLRUMap.prototype.assign = function(entries) {\n let entry, limit = this.limit || Number.MAX_VALUE;\n this._keymap.clear();\n let it = entries[Symbol.iterator]();\n for (let itv = it.next(); !itv.done; itv = it.next()) {\n let e = new Entry(itv.value[0], itv.value[1]);\n this._keymap.set(e.key, e);\n if (!entry) {\n this.oldest = e;\n } else {\n entry[NEWER] = e;\n e[OLDER] = entry;\n }\n entry = e;\n if (limit-- == 0) {\n throw new Error('overflow');\n }\n }\n this.newest = entry;\n this.size = this._keymap.size;\n};\n\nLRUMap.prototype.get = function(key) {\n // First, find our cache entry\n var entry = this._keymap.get(key);\n if (!entry) return; // Not cached. Sorry.\n // As was found in the cache, register it as being requested recently\n this._markEntryAsUsed(entry);\n return entry.value;\n};\n\nLRUMap.prototype.set = function(key, value) {\n var entry = this._keymap.get(key);\n\n if (entry) {\n // update existing\n entry.value = value;\n this._markEntryAsUsed(entry);\n return this;\n }\n\n // new entry\n this._keymap.set(key, (entry = new Entry(key, value)));\n\n if (this.newest) {\n // link previous tail to the new tail (entry)\n this.newest[NEWER] = entry;\n entry[OLDER] = this.newest;\n } else {\n // we're first in -- yay\n this.oldest = entry;\n }\n\n // add new entry to the end of the linked list -- it's now the freshest entry.\n this.newest = entry;\n ++this.size;\n if (this.size > this.limit) {\n // we hit the limit -- remove the head\n this.shift();\n }\n\n return this;\n};\n\nLRUMap.prototype.shift = function() {\n // todo: handle special case when limit == 1\n var entry = this.oldest;\n if (entry) {\n if (this.oldest[NEWER]) {\n // advance the list\n this.oldest = this.oldest[NEWER];\n this.oldest[OLDER] = undefined;\n } else {\n // the cache is exhausted\n this.oldest = undefined;\n this.newest = undefined;\n }\n // Remove last strong reference to and remove links from the purged\n // entry being returned:\n entry[NEWER] = entry[OLDER] = undefined;\n this._keymap.delete(entry.key);\n --this.size;\n return [entry.key, entry.value];\n }\n};\n\n// ----------------------------------------------------------------------------\n// Following code is optional and can be removed without breaking the core\n// functionality.\n\nLRUMap.prototype.find = function(key) {\n let e = this._keymap.get(key);\n return e ? e.value : undefined;\n};\n\nLRUMap.prototype.has = function(key) {\n return this._keymap.has(key);\n};\n\nLRUMap.prototype['delete'] = function(key) {\n var entry = this._keymap.get(key);\n if (!entry) return;\n this._keymap.delete(entry.key);\n if (entry[NEWER] && entry[OLDER]) {\n // relink the older entry with the newer entry\n entry[OLDER][NEWER] = entry[NEWER];\n entry[NEWER][OLDER] = entry[OLDER];\n } else if (entry[NEWER]) {\n // remove the link to us\n entry[NEWER][OLDER] = undefined;\n // link the newer entry to head\n this.oldest = entry[NEWER];\n } else if (entry[OLDER]) {\n // remove the link to us\n entry[OLDER][NEWER] = undefined;\n // link the newer entry to head\n this.newest = entry[OLDER];\n } else {// if(entry[OLDER] === undefined && entry.newer === undefined) {\n this.oldest = this.newest = undefined;\n }\n\n this.size--;\n return entry.value;\n};\n\nLRUMap.prototype.clear = function() {\n // Not clearing links should be safe, as we don't expose live links to user\n this.oldest = this.newest = undefined;\n this.size = 0;\n this._keymap.clear();\n};\n\n\nfunction EntryIterator(oldestEntry) { this.entry = oldestEntry; }\nEntryIterator.prototype[Symbol.iterator] = function() { return this; }\nEntryIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: [ent.key, ent.value] };\n } else {\n return { done: true, value: undefined };\n }\n};\n\n\nfunction KeyIterator(oldestEntry) { this.entry = oldestEntry; }\nKeyIterator.prototype[Symbol.iterator] = function() { return this; }\nKeyIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: ent.key };\n } else {\n return { done: true, value: undefined };\n }\n};\n\nfunction ValueIterator(oldestEntry) { this.entry = oldestEntry; }\nValueIterator.prototype[Symbol.iterator] = function() { return this; }\nValueIterator.prototype.next = function() {\n let ent = this.entry;\n if (ent) {\n this.entry = ent[NEWER];\n return { done: false, value: ent.value };\n } else {\n return { done: true, value: undefined };\n }\n};\n\n\nLRUMap.prototype.keys = function() {\n return new KeyIterator(this.oldest);\n};\n\nLRUMap.prototype.values = function() {\n return new ValueIterator(this.oldest);\n};\n\nLRUMap.prototype.entries = function() {\n return this;\n};\n\nLRUMap.prototype[Symbol.iterator] = function() {\n return new EntryIterator(this.oldest);\n};\n\nLRUMap.prototype.forEach = function(fun, thisObj) {\n if (typeof thisObj !== 'object') {\n thisObj = this;\n }\n let entry = this.oldest;\n while (entry) {\n fun.call(thisObj, entry.value, entry.key, this);\n entry = entry[NEWER];\n }\n};\n\n/** Returns a JSON (array) representation */\nLRUMap.prototype.toJSON = function() {\n var s = new Array(this.size), i = 0, entry = this.oldest;\n while (entry) {\n s[i++] = { key: entry.key, value: entry.value };\n entry = entry[NEWER];\n }\n return s;\n};\n\n/** Returns a String representation */\nLRUMap.prototype.toString = function() {\n var s = '', entry = this.oldest;\n while (entry) {\n s += String(entry.key)+':'+entry.value;\n entry = entry[NEWER];\n if (entry) {\n s += ' < ';\n }\n }\n return s;\n};\n\n});\n","import { addInstrumentationHandler, logger } from '@sentry/utils';\nimport { SpanStatus } from './spanstatus';\nimport { getActiveTransaction } from './utils';\n/**\n * Configures global error listeners\n */\nexport function registerErrorInstrumentation() {\n addInstrumentationHandler({\n callback: errorCallback,\n type: 'error',\n });\n addInstrumentationHandler({\n callback: errorCallback,\n type: 'unhandledrejection',\n });\n}\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback() {\n var activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n logger.log(\"[Tracing] Transaction: \" + SpanStatus.InternalError + \" -> Global error occured\");\n activeTransaction.setStatus(SpanStatus.InternalError);\n }\n}\n//# sourceMappingURL=errors.js.map","/*!\n * cookie\n * Copyright(c) 2012-2014 Roman Shtylman\n * Copyright(c) 2015 Douglas Christopher Wilson\n * MIT Licensed\n */\n\n'use strict';\n\n/**\n * Module exports.\n * @public\n */\n\nexports.parse = parse;\nexports.serialize = serialize;\n\n/**\n * Module variables.\n * @private\n */\n\nvar decode = decodeURIComponent;\nvar encode = encodeURIComponent;\nvar pairSplitRegExp = /; */;\n\n/**\n * RegExp to match field-content in RFC 7230 sec 3.2\n *\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n * obs-text = %x80-FF\n */\n\nvar fieldContentRegExp = /^[\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+$/;\n\n/**\n * Parse a cookie header.\n *\n * Parse the given cookie header string into an object\n * The object has the various cookies as keys(names) => values\n *\n * @param {string} str\n * @param {object} [options]\n * @return {object}\n * @public\n */\n\nfunction parse(str, options) {\n if (typeof str !== 'string') {\n throw new TypeError('argument str must be a string');\n }\n\n var obj = {}\n var opt = options || {};\n var pairs = str.split(pairSplitRegExp);\n var dec = opt.decode || decode;\n\n for (var i = 0; i < pairs.length; i++) {\n var pair = pairs[i];\n var eq_idx = pair.indexOf('=');\n\n // skip things that don't look like key=value\n if (eq_idx < 0) {\n continue;\n }\n\n var key = pair.substr(0, eq_idx).trim()\n var val = pair.substr(++eq_idx, pair.length).trim();\n\n // quoted values\n if ('\"' == val[0]) {\n val = val.slice(1, -1);\n }\n\n // only assign once\n if (undefined == obj[key]) {\n obj[key] = tryDecode(val, dec);\n }\n }\n\n return obj;\n}\n\n/**\n * Serialize data into a cookie header.\n *\n * Serialize the a name value pair into a cookie string suitable for\n * http headers. An optional options object specified cookie parameters.\n *\n * serialize('foo', 'bar', { httpOnly: true })\n * => \"foo=bar; httpOnly\"\n *\n * @param {string} name\n * @param {string} val\n * @param {object} [options]\n * @return {string}\n * @public\n */\n\nfunction serialize(name, val, options) {\n var opt = options || {};\n var enc = opt.encode || encode;\n\n if (typeof enc !== 'function') {\n throw new TypeError('option encode is invalid');\n }\n\n if (!fieldContentRegExp.test(name)) {\n throw new TypeError('argument name is invalid');\n }\n\n var value = enc(val);\n\n if (value && !fieldContentRegExp.test(value)) {\n throw new TypeError('argument val is invalid');\n }\n\n var str = name + '=' + value;\n\n if (null != opt.maxAge) {\n var maxAge = opt.maxAge - 0;\n\n if (isNaN(maxAge) || !isFinite(maxAge)) {\n throw new TypeError('option maxAge is invalid')\n }\n\n str += '; Max-Age=' + Math.floor(maxAge);\n }\n\n if (opt.domain) {\n if (!fieldContentRegExp.test(opt.domain)) {\n throw new TypeError('option domain is invalid');\n }\n\n str += '; Domain=' + opt.domain;\n }\n\n if (opt.path) {\n if (!fieldContentRegExp.test(opt.path)) {\n throw new TypeError('option path is invalid');\n }\n\n str += '; Path=' + opt.path;\n }\n\n if (opt.expires) {\n if (typeof opt.expires.toUTCString !== 'function') {\n throw new TypeError('option expires is invalid');\n }\n\n str += '; Expires=' + opt.expires.toUTCString();\n }\n\n if (opt.httpOnly) {\n str += '; HttpOnly';\n }\n\n if (opt.secure) {\n str += '; Secure';\n }\n\n if (opt.sameSite) {\n var sameSite = typeof opt.sameSite === 'string'\n ? opt.sameSite.toLowerCase() : opt.sameSite;\n\n switch (sameSite) {\n case true:\n str += '; SameSite=Strict';\n break;\n case 'lax':\n str += '; SameSite=Lax';\n break;\n case 'strict':\n str += '; SameSite=Strict';\n break;\n case 'none':\n str += '; SameSite=None';\n break;\n default:\n throw new TypeError('option sameSite is invalid');\n }\n }\n\n return str;\n}\n\n/**\n * Try decoding a string using a decoding function.\n *\n * @param {string} str\n * @param {function} decode\n * @private\n */\n\nfunction tryDecode(str, decode) {\n try {\n return decode(str);\n } catch (e) {\n return str;\n }\n}\n","import { __assign, __values } from \"tslib\";\nimport { getGlobalObject } from './global';\nimport { isInstanceOf, isString } from './is';\nimport { logger } from './logger';\nimport { fill } from './object';\nimport { getFunctionName } from './stacktrace';\nimport { supportsHistory, supportsNativeFetch } from './supports';\nvar global = getGlobalObject();\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\nvar handlers = {};\nvar instrumented = {};\n/** Instruments given API */\nfunction instrument(type) {\n if (instrumented[type]) {\n return;\n }\n instrumented[type] = true;\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n logger.warn('unknown instrumentation type:', type);\n }\n}\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nexport function addInstrumentationHandler(handler) {\n if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') {\n return;\n }\n handlers[handler.type] = handlers[handler.type] || [];\n handlers[handler.type].push(handler.callback);\n instrument(handler.type);\n}\n/** JSDoc */\nfunction triggerHandlers(type, data) {\n var e_1, _a;\n if (!type || !handlers[type]) {\n return;\n }\n try {\n for (var _b = __values(handlers[type] || []), _c = _b.next(); !_c.done; _c = _b.next()) {\n var handler = _c.value;\n try {\n handler(data);\n }\n catch (e) {\n logger.error(\"Error while triggering instrumentation handler.\\nType: \" + type + \"\\nName: \" + getFunctionName(handler) + \"\\nError: \" + e);\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n}\n/** JSDoc */\nfunction instrumentConsole() {\n if (!('console' in global)) {\n return;\n }\n ['debug', 'info', 'warn', 'error', 'log', 'assert'].forEach(function (level) {\n if (!(level in global.console)) {\n return;\n }\n fill(global.console, level, function (originalConsoleLevel) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n triggerHandlers('console', { args: args, level: level });\n // this fails for some browsers. :(\n if (originalConsoleLevel) {\n Function.prototype.apply.call(originalConsoleLevel, global.console, args);\n }\n };\n });\n });\n}\n/** JSDoc */\nfunction instrumentFetch() {\n if (!supportsNativeFetch()) {\n return;\n }\n fill(global, 'fetch', function (originalFetch) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var handlerData = {\n args: args,\n fetchData: {\n method: getFetchMethod(args),\n url: getFetchUrl(args),\n },\n startTimestamp: Date.now(),\n };\n triggerHandlers('fetch', __assign({}, handlerData));\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(global, args).then(function (response) {\n triggerHandlers('fetch', __assign(__assign({}, handlerData), { endTimestamp: Date.now(), response: response }));\n return response;\n }, function (error) {\n triggerHandlers('fetch', __assign(__assign({}, handlerData), { endTimestamp: Date.now(), error: error }));\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n });\n };\n });\n}\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/** Extract `method` from fetch call arguments */\nfunction getFetchMethod(fetchArgs) {\n if (fetchArgs === void 0) { fetchArgs = []; }\n if ('Request' in global && isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) {\n return String(fetchArgs[0].method).toUpperCase();\n }\n if (fetchArgs[1] && fetchArgs[1].method) {\n return String(fetchArgs[1].method).toUpperCase();\n }\n return 'GET';\n}\n/** Extract `url` from fetch call arguments */\nfunction getFetchUrl(fetchArgs) {\n if (fetchArgs === void 0) { fetchArgs = []; }\n if (typeof fetchArgs[0] === 'string') {\n return fetchArgs[0];\n }\n if ('Request' in global && isInstanceOf(fetchArgs[0], Request)) {\n return fetchArgs[0].url;\n }\n return String(fetchArgs[0]);\n}\n/* eslint-enable @typescript-eslint/no-unsafe-member-access */\n/** JSDoc */\nfunction instrumentXHR() {\n if (!('XMLHttpRequest' in global)) {\n return;\n }\n // Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately.\n var requestKeys = [];\n var requestValues = [];\n var xhrproto = XMLHttpRequest.prototype;\n fill(xhrproto, 'open', function (originalOpen) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n var xhr = this;\n var url = args[1];\n xhr.__sentry_xhr__ = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n };\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhr.__sentry_xhr__.method === 'POST' && url.match(/sentry_key/)) {\n xhr.__sentry_own_request__ = true;\n }\n var onreadystatechangeHandler = function () {\n if (xhr.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n if (xhr.__sentry_xhr__) {\n xhr.__sentry_xhr__.status_code = xhr.status;\n }\n }\n catch (e) {\n /* do nothing */\n }\n try {\n var requestPos = requestKeys.indexOf(xhr);\n if (requestPos !== -1) {\n // Make sure to pop both key and value to keep it in sync.\n requestKeys.splice(requestPos);\n var args_1 = requestValues.splice(requestPos)[0];\n if (xhr.__sentry_xhr__ && args_1[0] !== undefined) {\n xhr.__sentry_xhr__.body = args_1[0];\n }\n }\n }\n catch (e) {\n /* do nothing */\n }\n triggerHandlers('xhr', {\n args: args,\n endTimestamp: Date.now(),\n startTimestamp: Date.now(),\n xhr: xhr,\n });\n }\n };\n if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') {\n fill(xhr, 'onreadystatechange', function (original) {\n return function () {\n var readyStateArgs = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n readyStateArgs[_i] = arguments[_i];\n }\n onreadystatechangeHandler();\n return original.apply(xhr, readyStateArgs);\n };\n });\n }\n else {\n xhr.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n return originalOpen.apply(xhr, args);\n };\n });\n fill(xhrproto, 'send', function (originalSend) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n requestKeys.push(this);\n requestValues.push(args);\n triggerHandlers('xhr', {\n args: args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n return originalSend.apply(this, args);\n };\n });\n}\nvar lastHref;\n/** JSDoc */\nfunction instrumentHistory() {\n if (!supportsHistory()) {\n return;\n }\n var oldOnPopState = global.onpopstate;\n global.onpopstate = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var to = global.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n var from = lastHref;\n lastHref = to;\n triggerHandlers('history', {\n from: from,\n to: to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n }\n catch (_oO) {\n // no-empty\n }\n }\n };\n /** @hidden */\n function historyReplacementFunction(originalHistoryFunction) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n var from = lastHref;\n var to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n triggerHandlers('history', {\n from: from,\n to: to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n fill(global.history, 'pushState', historyReplacementFunction);\n fill(global.history, 'replaceState', historyReplacementFunction);\n}\nvar debounceDuration = 1000;\nvar debounceTimerID;\nvar lastCapturedEvent;\n/**\n * Decide whether the current event should finish the debounce of previously captured one.\n * @param previous previously captured event\n * @param current event to be captured\n */\nfunction shouldShortcircuitPreviousDebounce(previous, current) {\n // If there was no previous event, it should always be swapped for the new one.\n if (!previous) {\n return true;\n }\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (previous.type !== current.type) {\n return true;\n }\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (previous.target !== current.target) {\n return true;\n }\n }\n catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return false;\n}\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(event) {\n // We are only interested in filtering `keypress` events for now.\n if (event.type !== 'keypress') {\n return false;\n }\n try {\n var target = event.target;\n if (!target || !target.tagName) {\n return true;\n }\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n }\n catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n return true;\n}\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler, globalListener) {\n if (globalListener === void 0) { globalListener = false; }\n return function (event) {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || lastCapturedEvent === event) {\n return;\n }\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event)) {\n return;\n }\n var name = event.type === 'keypress' ? 'input' : event.type;\n // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons.\n if (debounceTimerID === undefined) {\n handler({\n event: event,\n name: name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) {\n handler({\n event: event,\n name: name,\n global: globalListener,\n });\n lastCapturedEvent = event;\n }\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = global.setTimeout(function () {\n debounceTimerID = undefined;\n }, debounceDuration);\n };\n}\n/** JSDoc */\nfunction instrumentDOM() {\n if (!('document' in global)) {\n return;\n }\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n var triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n var globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n global.document.addEventListener('click', globalDOMEventHandler, false);\n global.document.addEventListener('keypress', globalDOMEventHandler, false);\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach(function (target) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n var proto = global[target] && global[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n fill(proto, 'addEventListener', function (originalAddEventListener) {\n return function (type, listener, options) {\n if (type === 'click' || type == 'keypress') {\n try {\n var el = this;\n var handlers_1 = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {});\n var handlerForType = (handlers_1[type] = handlers_1[type] || { refCount: 0 });\n if (!handlerForType.handler) {\n var handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n handlerForType.refCount += 1;\n }\n catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n fill(proto, 'removeEventListener', function (originalRemoveEventListener) {\n return function (type, listener, options) {\n if (type === 'click' || type == 'keypress') {\n try {\n var el = this;\n var handlers_2 = el.__sentry_instrumentation_handlers__ || {};\n var handlerForType = handlers_2[type];\n if (handlerForType) {\n handlerForType.refCount -= 1;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers_2[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers_2).length === 0) {\n delete el.__sentry_instrumentation_handlers__;\n }\n }\n }\n catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n });\n });\n}\nvar _oldOnErrorHandler = null;\n/** JSDoc */\nfunction instrumentError() {\n _oldOnErrorHandler = global.onerror;\n global.onerror = function (msg, url, line, column, error) {\n triggerHandlers('error', {\n column: column,\n error: error,\n line: line,\n msg: msg,\n url: url,\n });\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n return false;\n };\n}\nvar _oldOnUnhandledRejectionHandler = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection() {\n _oldOnUnhandledRejectionHandler = global.onunhandledrejection;\n global.onunhandledrejection = function (e) {\n triggerHandlers('unhandledrejection', e);\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n return true;\n };\n}\n//# sourceMappingURL=instrument.js.map","var SqlString = exports;\n\nvar ID_GLOBAL_REGEXP = /`/g;\nvar QUAL_GLOBAL_REGEXP = /\\./g;\nvar CHARS_GLOBAL_REGEXP = /[\\0\\b\\t\\n\\r\\x1a\\\"\\'\\\\]/g; // eslint-disable-line no-control-regex\nvar CHARS_ESCAPE_MAP = {\n '\\0' : '\\\\0',\n '\\b' : '\\\\b',\n '\\t' : '\\\\t',\n '\\n' : '\\\\n',\n '\\r' : '\\\\r',\n '\\x1a' : '\\\\Z',\n '\"' : '\\\\\"',\n '\\'' : '\\\\\\'',\n '\\\\' : '\\\\\\\\'\n};\n\nSqlString.escapeId = function escapeId(val, forbidQualified) {\n if (Array.isArray(val)) {\n var sql = '';\n\n for (var i = 0; i < val.length; i++) {\n sql += (i === 0 ? '' : ', ') + SqlString.escapeId(val[i], forbidQualified);\n }\n\n return sql;\n } else if (forbidQualified) {\n return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``') + '`';\n } else {\n return '`' + String(val).replace(ID_GLOBAL_REGEXP, '``').replace(QUAL_GLOBAL_REGEXP, '`.`') + '`';\n }\n};\n\nSqlString.escape = function escape(val, stringifyObjects, timeZone) {\n if (val === undefined || val === null) {\n return 'NULL';\n }\n\n switch (typeof val) {\n case 'boolean': return (val) ? 'true' : 'false';\n case 'number': return val + '';\n case 'object':\n if (val instanceof Date) {\n return SqlString.dateToString(val, timeZone || 'local');\n } else if (Array.isArray(val)) {\n return SqlString.arrayToList(val, timeZone);\n } else if (Buffer.isBuffer(val)) {\n return SqlString.bufferToString(val);\n } else if (typeof val.toSqlString === 'function') {\n return String(val.toSqlString());\n } else if (stringifyObjects) {\n return escapeString(val.toString());\n } else {\n return SqlString.objectToValues(val, timeZone);\n }\n default: return escapeString(val);\n }\n};\n\nSqlString.arrayToList = function arrayToList(array, timeZone) {\n var sql = '';\n\n for (var i = 0; i < array.length; i++) {\n var val = array[i];\n\n if (Array.isArray(val)) {\n sql += (i === 0 ? '' : ', ') + '(' + SqlString.arrayToList(val, timeZone) + ')';\n } else {\n sql += (i === 0 ? '' : ', ') + SqlString.escape(val, true, timeZone);\n }\n }\n\n return sql;\n};\n\nSqlString.format = function format(sql, values, stringifyObjects, timeZone) {\n if (values == null) {\n return sql;\n }\n\n if (!Array.isArray(values)) {\n values = [values];\n }\n\n var chunkIndex = 0;\n var placeholdersRegex = /\\?+/g;\n var result = '';\n var valuesIndex = 0;\n var match;\n\n while (valuesIndex < values.length && (match = placeholdersRegex.exec(sql))) {\n var len = match[0].length;\n\n if (len > 2) {\n continue;\n }\n\n var value = len === 2\n ? SqlString.escapeId(values[valuesIndex])\n : SqlString.escape(values[valuesIndex], stringifyObjects, timeZone);\n\n result += sql.slice(chunkIndex, match.index) + value;\n chunkIndex = placeholdersRegex.lastIndex;\n valuesIndex++;\n }\n\n if (chunkIndex === 0) {\n // Nothing was replaced\n return sql;\n }\n\n if (chunkIndex < sql.length) {\n return result + sql.slice(chunkIndex);\n }\n\n return result;\n};\n\nSqlString.dateToString = function dateToString(date, timeZone) {\n var dt = new Date(date);\n\n if (isNaN(dt.getTime())) {\n return 'NULL';\n }\n\n var year;\n var month;\n var day;\n var hour;\n var minute;\n var second;\n var millisecond;\n\n if (timeZone === 'local') {\n year = dt.getFullYear();\n month = dt.getMonth() + 1;\n day = dt.getDate();\n hour = dt.getHours();\n minute = dt.getMinutes();\n second = dt.getSeconds();\n millisecond = dt.getMilliseconds();\n } else {\n var tz = convertTimezone(timeZone);\n\n if (tz !== false && tz !== 0) {\n dt.setTime(dt.getTime() + (tz * 60000));\n }\n\n year = dt.getUTCFullYear();\n month = dt.getUTCMonth() + 1;\n day = dt.getUTCDate();\n hour = dt.getUTCHours();\n minute = dt.getUTCMinutes();\n second = dt.getUTCSeconds();\n millisecond = dt.getUTCMilliseconds();\n }\n\n // YYYY-MM-DD HH:mm:ss.mmm\n var str = zeroPad(year, 4) + '-' + zeroPad(month, 2) + '-' + zeroPad(day, 2) + ' ' +\n zeroPad(hour, 2) + ':' + zeroPad(minute, 2) + ':' + zeroPad(second, 2) + '.' +\n zeroPad(millisecond, 3);\n\n return escapeString(str);\n};\n\nSqlString.bufferToString = function bufferToString(buffer) {\n return 'X' + escapeString(buffer.toString('hex'));\n};\n\nSqlString.objectToValues = function objectToValues(object, timeZone) {\n var sql = '';\n\n for (var key in object) {\n var val = object[key];\n\n if (typeof val === 'function') {\n continue;\n }\n\n sql += (sql.length === 0 ? '' : ', ') + SqlString.escapeId(key) + ' = ' + SqlString.escape(val, true, timeZone);\n }\n\n return sql;\n};\n\nSqlString.raw = function raw(sql) {\n if (typeof sql !== 'string') {\n throw new TypeError('argument sql must be a string');\n }\n\n return {\n toSqlString: function toSqlString() { return sql; }\n };\n};\n\nfunction escapeString(val) {\n var chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex = 0;\n var escapedVal = '';\n var match;\n\n while ((match = CHARS_GLOBAL_REGEXP.exec(val))) {\n escapedVal += val.slice(chunkIndex, match.index) + CHARS_ESCAPE_MAP[match[0]];\n chunkIndex = CHARS_GLOBAL_REGEXP.lastIndex;\n }\n\n if (chunkIndex === 0) {\n // Nothing was escaped\n return \"'\" + val + \"'\";\n }\n\n if (chunkIndex < val.length) {\n return \"'\" + escapedVal + val.slice(chunkIndex) + \"'\";\n }\n\n return \"'\" + escapedVal + \"'\";\n}\n\nfunction zeroPad(number, length) {\n number = number.toString();\n while (number.length < length) {\n number = '0' + number;\n }\n\n return number;\n}\n\nfunction convertTimezone(tz) {\n if (tz === 'Z') {\n return 0;\n }\n\n var m = tz.match(/([\\+\\-\\s])(\\d\\d):?(\\d\\d)?/);\n if (m) {\n return (m[1] === '-' ? -1 : 1) * (parseInt(m[2], 10) + ((m[3] ? parseInt(m[3], 10) : 0) / 60)) * 60;\n }\n return false;\n}\n","'use strict'\nmodule.exports = Yallist\n\nYallist.Node = Node\nYallist.create = Yallist\n\nfunction Yallist (list) {\n var self = this\n if (!(self instanceof Yallist)) {\n self = new Yallist()\n }\n\n self.tail = null\n self.head = null\n self.length = 0\n\n if (list && typeof list.forEach === 'function') {\n list.forEach(function (item) {\n self.push(item)\n })\n } else if (arguments.length > 0) {\n for (var i = 0, l = arguments.length; i < l; i++) {\n self.push(arguments[i])\n }\n }\n\n return self\n}\n\nYallist.prototype.removeNode = function (node) {\n if (node.list !== this) {\n throw new Error('removing node which does not belong to this list')\n }\n\n var next = node.next\n var prev = node.prev\n\n if (next) {\n next.prev = prev\n }\n\n if (prev) {\n prev.next = next\n }\n\n if (node === this.head) {\n this.head = next\n }\n if (node === this.tail) {\n this.tail = prev\n }\n\n node.list.length--\n node.next = null\n node.prev = null\n node.list = null\n\n return next\n}\n\nYallist.prototype.unshiftNode = function (node) {\n if (node === this.head) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var head = this.head\n node.list = this\n node.next = head\n if (head) {\n head.prev = node\n }\n\n this.head = node\n if (!this.tail) {\n this.tail = node\n }\n this.length++\n}\n\nYallist.prototype.pushNode = function (node) {\n if (node === this.tail) {\n return\n }\n\n if (node.list) {\n node.list.removeNode(node)\n }\n\n var tail = this.tail\n node.list = this\n node.prev = tail\n if (tail) {\n tail.next = node\n }\n\n this.tail = node\n if (!this.head) {\n this.head = node\n }\n this.length++\n}\n\nYallist.prototype.push = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n push(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.unshift = function () {\n for (var i = 0, l = arguments.length; i < l; i++) {\n unshift(this, arguments[i])\n }\n return this.length\n}\n\nYallist.prototype.pop = function () {\n if (!this.tail) {\n return undefined\n }\n\n var res = this.tail.value\n this.tail = this.tail.prev\n if (this.tail) {\n this.tail.next = null\n } else {\n this.head = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.shift = function () {\n if (!this.head) {\n return undefined\n }\n\n var res = this.head.value\n this.head = this.head.next\n if (this.head) {\n this.head.prev = null\n } else {\n this.tail = null\n }\n this.length--\n return res\n}\n\nYallist.prototype.forEach = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.head, i = 0; walker !== null; i++) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.next\n }\n}\n\nYallist.prototype.forEachReverse = function (fn, thisp) {\n thisp = thisp || this\n for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {\n fn.call(thisp, walker.value, i, this)\n walker = walker.prev\n }\n}\n\nYallist.prototype.get = function (n) {\n for (var i = 0, walker = this.head; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.next\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.getReverse = function (n) {\n for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {\n // abort out of the list early if we hit a cycle\n walker = walker.prev\n }\n if (i === n && walker !== null) {\n return walker.value\n }\n}\n\nYallist.prototype.map = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.head; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.next\n }\n return res\n}\n\nYallist.prototype.mapReverse = function (fn, thisp) {\n thisp = thisp || this\n var res = new Yallist()\n for (var walker = this.tail; walker !== null;) {\n res.push(fn.call(thisp, walker.value, this))\n walker = walker.prev\n }\n return res\n}\n\nYallist.prototype.reduce = function (fn, initial) {\n var acc\n var walker = this.head\n if (arguments.length > 1) {\n acc = initial\n } else if (this.head) {\n walker = this.head.next\n acc = this.head.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = 0; walker !== null; i++) {\n acc = fn(acc, walker.value, i)\n walker = walker.next\n }\n\n return acc\n}\n\nYallist.prototype.reduceReverse = function (fn, initial) {\n var acc\n var walker = this.tail\n if (arguments.length > 1) {\n acc = initial\n } else if (this.tail) {\n walker = this.tail.prev\n acc = this.tail.value\n } else {\n throw new TypeError('Reduce of empty list with no initial value')\n }\n\n for (var i = this.length - 1; walker !== null; i--) {\n acc = fn(acc, walker.value, i)\n walker = walker.prev\n }\n\n return acc\n}\n\nYallist.prototype.toArray = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.head; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.next\n }\n return arr\n}\n\nYallist.prototype.toArrayReverse = function () {\n var arr = new Array(this.length)\n for (var i = 0, walker = this.tail; walker !== null; i++) {\n arr[i] = walker.value\n walker = walker.prev\n }\n return arr\n}\n\nYallist.prototype.slice = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = 0, walker = this.head; walker !== null && i < from; i++) {\n walker = walker.next\n }\n for (; walker !== null && i < to; i++, walker = walker.next) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.sliceReverse = function (from, to) {\n to = to || this.length\n if (to < 0) {\n to += this.length\n }\n from = from || 0\n if (from < 0) {\n from += this.length\n }\n var ret = new Yallist()\n if (to < from || to < 0) {\n return ret\n }\n if (from < 0) {\n from = 0\n }\n if (to > this.length) {\n to = this.length\n }\n for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {\n walker = walker.prev\n }\n for (; walker !== null && i > from; i--, walker = walker.prev) {\n ret.push(walker.value)\n }\n return ret\n}\n\nYallist.prototype.splice = function (start, deleteCount, ...nodes) {\n if (start > this.length) {\n start = this.length - 1\n }\n if (start < 0) {\n start = this.length + start;\n }\n\n for (var i = 0, walker = this.head; walker !== null && i < start; i++) {\n walker = walker.next\n }\n\n var ret = []\n for (var i = 0; walker && i < deleteCount; i++) {\n ret.push(walker.value)\n walker = this.removeNode(walker)\n }\n if (walker === null) {\n walker = this.tail\n }\n\n if (walker !== this.head && walker !== this.tail) {\n walker = walker.prev\n }\n\n for (var i = 0; i < nodes.length; i++) {\n walker = insert(this, walker, nodes[i])\n }\n return ret;\n}\n\nYallist.prototype.reverse = function () {\n var head = this.head\n var tail = this.tail\n for (var walker = head; walker !== null; walker = walker.prev) {\n var p = walker.prev\n walker.prev = walker.next\n walker.next = p\n }\n this.head = tail\n this.tail = head\n return this\n}\n\nfunction insert (self, node, value) {\n var inserted = node === self.head ?\n new Node(value, null, node, self) :\n new Node(value, node, node.next, self)\n\n if (inserted.next === null) {\n self.tail = inserted\n }\n if (inserted.prev === null) {\n self.head = inserted\n }\n\n self.length++\n\n return inserted\n}\n\nfunction push (self, item) {\n self.tail = new Node(item, self.tail, null, self)\n if (!self.head) {\n self.head = self.tail\n }\n self.length++\n}\n\nfunction unshift (self, item) {\n self.head = new Node(item, null, self.head, self)\n if (!self.tail) {\n self.tail = self.head\n }\n self.length++\n}\n\nfunction Node (value, prev, next, list) {\n if (!(this instanceof Node)) {\n return new Node(value, prev, next, list)\n }\n\n this.list = list\n this.value = value\n\n if (prev) {\n prev.next = this\n this.prev = prev\n } else {\n this.prev = null\n }\n\n if (next) {\n next.prev = this\n this.next = next\n } else {\n this.next = null\n }\n}\n\ntry {\n // add if support for Symbol.iterator is present\n require('./iterator.js')(Yallist)\n} catch (er) {}\n","'use strict'\nmodule.exports = function (Yallist) {\n Yallist.prototype[Symbol.iterator] = function* () {\n for (let walker = this.head; walker; walker = walker.next) {\n yield walker.value\n }\n }\n}\n","module.exports = Long;\r\n\r\n/**\r\n * wasm optimizations, to do native i64 multiplication and divide\r\n */\r\nvar wasm = null;\r\n\r\ntry {\r\n wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([\r\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11\r\n ])), {}).exports;\r\n} catch (e) {\r\n // no wasm support :(\r\n}\r\n\r\n/**\r\n * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.\r\n * See the from* functions below for more convenient ways of constructing Longs.\r\n * @exports Long\r\n * @class A Long class for representing a 64 bit two's-complement integer value.\r\n * @param {number} low The low (signed) 32 bits of the long\r\n * @param {number} high The high (signed) 32 bits of the long\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @constructor\r\n */\r\nfunction Long(low, high, unsigned) {\r\n\r\n /**\r\n * The low 32 bits as a signed value.\r\n * @type {number}\r\n */\r\n this.low = low | 0;\r\n\r\n /**\r\n * The high 32 bits as a signed value.\r\n * @type {number}\r\n */\r\n this.high = high | 0;\r\n\r\n /**\r\n * Whether unsigned or not.\r\n * @type {boolean}\r\n */\r\n this.unsigned = !!unsigned;\r\n}\r\n\r\n// The internal representation of a long is the two given signed, 32-bit values.\r\n// We use 32-bit pieces because these are the size of integers on which\r\n// Javascript performs bit-operations. For operations like addition and\r\n// multiplication, we split each number into 16 bit pieces, which can easily be\r\n// multiplied within Javascript's floating-point representation without overflow\r\n// or change in sign.\r\n//\r\n// In the algorithms below, we frequently reduce the negative case to the\r\n// positive case by negating the input(s) and then post-processing the result.\r\n// Note that we must ALWAYS check specially whether those values are MIN_VALUE\r\n// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as\r\n// a positive number, it overflows back into a negative). Not handling this\r\n// case would often result in infinite recursion.\r\n//\r\n// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*\r\n// methods on which they depend.\r\n\r\n/**\r\n * An indicator used to reliably determine if an object is a Long or not.\r\n * @type {boolean}\r\n * @const\r\n * @private\r\n */\r\nLong.prototype.__isLong__;\r\n\r\nObject.defineProperty(Long.prototype, \"__isLong__\", { value: true });\r\n\r\n/**\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n * @inner\r\n */\r\nfunction isLong(obj) {\r\n return (obj && obj[\"__isLong__\"]) === true;\r\n}\r\n\r\n/**\r\n * Tests if the specified object is a Long.\r\n * @function\r\n * @param {*} obj Object\r\n * @returns {boolean}\r\n */\r\nLong.isLong = isLong;\r\n\r\n/**\r\n * A cache of the Long representations of small integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\nvar INT_CACHE = {};\r\n\r\n/**\r\n * A cache of the Long representations of small unsigned integer values.\r\n * @type {!Object}\r\n * @inner\r\n */\r\nvar UINT_CACHE = {};\r\n\r\n/**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromInt(value, unsigned) {\r\n var obj, cachedObj, cache;\r\n if (unsigned) {\r\n value >>>= 0;\r\n if (cache = (0 <= value && value < 256)) {\r\n cachedObj = UINT_CACHE[value];\r\n if (cachedObj)\r\n return cachedObj;\r\n }\r\n obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);\r\n if (cache)\r\n UINT_CACHE[value] = obj;\r\n return obj;\r\n } else {\r\n value |= 0;\r\n if (cache = (-128 <= value && value < 128)) {\r\n cachedObj = INT_CACHE[value];\r\n if (cachedObj)\r\n return cachedObj;\r\n }\r\n obj = fromBits(value, value < 0 ? -1 : 0, false);\r\n if (cache)\r\n INT_CACHE[value] = obj;\r\n return obj;\r\n }\r\n}\r\n\r\n/**\r\n * Returns a Long representing the given 32 bit integer value.\r\n * @function\r\n * @param {number} value The 32 bit integer in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromInt = fromInt;\r\n\r\n/**\r\n * @param {number} value\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromNumber(value, unsigned) {\r\n if (isNaN(value))\r\n return unsigned ? UZERO : ZERO;\r\n if (unsigned) {\r\n if (value < 0)\r\n return UZERO;\r\n if (value >= TWO_PWR_64_DBL)\r\n return MAX_UNSIGNED_VALUE;\r\n } else {\r\n if (value <= -TWO_PWR_63_DBL)\r\n return MIN_VALUE;\r\n if (value + 1 >= TWO_PWR_63_DBL)\r\n return MAX_VALUE;\r\n }\r\n if (value < 0)\r\n return fromNumber(-value, unsigned).neg();\r\n return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);\r\n}\r\n\r\n/**\r\n * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.\r\n * @function\r\n * @param {number} value The number in question\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromNumber = fromNumber;\r\n\r\n/**\r\n * @param {number} lowBits\r\n * @param {number} highBits\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromBits(lowBits, highBits, unsigned) {\r\n return new Long(lowBits, highBits, unsigned);\r\n}\r\n\r\n/**\r\n * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is\r\n * assumed to use 32 bits.\r\n * @function\r\n * @param {number} lowBits The low 32 bits\r\n * @param {number} highBits The high 32 bits\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromBits = fromBits;\r\n\r\n/**\r\n * @function\r\n * @param {number} base\r\n * @param {number} exponent\r\n * @returns {number}\r\n * @inner\r\n */\r\nvar pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)\r\n\r\n/**\r\n * @param {string} str\r\n * @param {(boolean|number)=} unsigned\r\n * @param {number=} radix\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromString(str, unsigned, radix) {\r\n if (str.length === 0)\r\n throw Error('empty string');\r\n if (str === \"NaN\" || str === \"Infinity\" || str === \"+Infinity\" || str === \"-Infinity\")\r\n return ZERO;\r\n if (typeof unsigned === 'number') {\r\n // For goog.math.long compatibility\r\n radix = unsigned,\r\n unsigned = false;\r\n } else {\r\n unsigned = !! unsigned;\r\n }\r\n radix = radix || 10;\r\n if (radix < 2 || 36 < radix)\r\n throw RangeError('radix');\r\n\r\n var p;\r\n if ((p = str.indexOf('-')) > 0)\r\n throw Error('interior hyphen');\r\n else if (p === 0) {\r\n return fromString(str.substring(1), unsigned, radix).neg();\r\n }\r\n\r\n // Do several (8) digits each time through the loop, so as to\r\n // minimize the calls to the very expensive emulated div.\r\n var radixToPower = fromNumber(pow_dbl(radix, 8));\r\n\r\n var result = ZERO;\r\n for (var i = 0; i < str.length; i += 8) {\r\n var size = Math.min(8, str.length - i),\r\n value = parseInt(str.substring(i, i + size), radix);\r\n if (size < 8) {\r\n var power = fromNumber(pow_dbl(radix, size));\r\n result = result.mul(power).add(fromNumber(value));\r\n } else {\r\n result = result.mul(radixToPower);\r\n result = result.add(fromNumber(value));\r\n }\r\n }\r\n result.unsigned = unsigned;\r\n return result;\r\n}\r\n\r\n/**\r\n * Returns a Long representation of the given string, written using the specified radix.\r\n * @function\r\n * @param {string} str The textual representation of the Long\r\n * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed\r\n * @param {number=} radix The radix in which the text is written (2-36), defaults to 10\r\n * @returns {!Long} The corresponding Long value\r\n */\r\nLong.fromString = fromString;\r\n\r\n/**\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val\r\n * @param {boolean=} unsigned\r\n * @returns {!Long}\r\n * @inner\r\n */\r\nfunction fromValue(val, unsigned) {\r\n if (typeof val === 'number')\r\n return fromNumber(val, unsigned);\r\n if (typeof val === 'string')\r\n return fromString(val, unsigned);\r\n // Throws for non-objects, converts non-instanceof Long:\r\n return fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);\r\n}\r\n\r\n/**\r\n * Converts the specified value to a Long using the appropriate from* function for its type.\r\n * @function\r\n * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {!Long}\r\n */\r\nLong.fromValue = fromValue;\r\n\r\n// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be\r\n// no runtime penalty for these.\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_16_DBL = 1 << 16;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_24_DBL = 1 << 24;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\r\n\r\n/**\r\n * @type {number}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;\r\n\r\n/**\r\n * @type {!Long}\r\n * @const\r\n * @inner\r\n */\r\nvar TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar ZERO = fromInt(0);\r\n\r\n/**\r\n * Signed zero.\r\n * @type {!Long}\r\n */\r\nLong.ZERO = ZERO;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar UZERO = fromInt(0, true);\r\n\r\n/**\r\n * Unsigned zero.\r\n * @type {!Long}\r\n */\r\nLong.UZERO = UZERO;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar ONE = fromInt(1);\r\n\r\n/**\r\n * Signed one.\r\n * @type {!Long}\r\n */\r\nLong.ONE = ONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar UONE = fromInt(1, true);\r\n\r\n/**\r\n * Unsigned one.\r\n * @type {!Long}\r\n */\r\nLong.UONE = UONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar NEG_ONE = fromInt(-1);\r\n\r\n/**\r\n * Signed negative one.\r\n * @type {!Long}\r\n */\r\nLong.NEG_ONE = NEG_ONE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);\r\n\r\n/**\r\n * Maximum signed value.\r\n * @type {!Long}\r\n */\r\nLong.MAX_VALUE = MAX_VALUE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);\r\n\r\n/**\r\n * Maximum unsigned value.\r\n * @type {!Long}\r\n */\r\nLong.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;\r\n\r\n/**\r\n * @type {!Long}\r\n * @inner\r\n */\r\nvar MIN_VALUE = fromBits(0, 0x80000000|0, false);\r\n\r\n/**\r\n * Minimum signed value.\r\n * @type {!Long}\r\n */\r\nLong.MIN_VALUE = MIN_VALUE;\r\n\r\n/**\r\n * @alias Long.prototype\r\n * @inner\r\n */\r\nvar LongPrototype = Long.prototype;\r\n\r\n/**\r\n * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.\r\n * @returns {number}\r\n */\r\nLongPrototype.toInt = function toInt() {\r\n return this.unsigned ? this.low >>> 0 : this.low;\r\n};\r\n\r\n/**\r\n * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).\r\n * @returns {number}\r\n */\r\nLongPrototype.toNumber = function toNumber() {\r\n if (this.unsigned)\r\n return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);\r\n return this.high * TWO_PWR_32_DBL + (this.low >>> 0);\r\n};\r\n\r\n/**\r\n * Converts the Long to a string written in the specified radix.\r\n * @param {number=} radix Radix (2-36), defaults to 10\r\n * @returns {string}\r\n * @override\r\n * @throws {RangeError} If `radix` is out of range\r\n */\r\nLongPrototype.toString = function toString(radix) {\r\n radix = radix || 10;\r\n if (radix < 2 || 36 < radix)\r\n throw RangeError('radix');\r\n if (this.isZero())\r\n return '0';\r\n if (this.isNegative()) { // Unsigned Longs are never negative\r\n if (this.eq(MIN_VALUE)) {\r\n // We need to change the Long value before it can be negated, so we remove\r\n // the bottom-most digit in this base and then recurse to do the rest.\r\n var radixLong = fromNumber(radix),\r\n div = this.div(radixLong),\r\n rem1 = div.mul(radixLong).sub(this);\r\n return div.toString(radix) + rem1.toInt().toString(radix);\r\n } else\r\n return '-' + this.neg().toString(radix);\r\n }\r\n\r\n // Do several (6) digits each time through the loop, so as to\r\n // minimize the calls to the very expensive emulated div.\r\n var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),\r\n rem = this;\r\n var result = '';\r\n while (true) {\r\n var remDiv = rem.div(radixToPower),\r\n intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,\r\n digits = intval.toString(radix);\r\n rem = remDiv;\r\n if (rem.isZero())\r\n return digits + result;\r\n else {\r\n while (digits.length < 6)\r\n digits = '0' + digits;\r\n result = '' + digits + result;\r\n }\r\n }\r\n};\r\n\r\n/**\r\n * Gets the high 32 bits as a signed integer.\r\n * @returns {number} Signed high bits\r\n */\r\nLongPrototype.getHighBits = function getHighBits() {\r\n return this.high;\r\n};\r\n\r\n/**\r\n * Gets the high 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned high bits\r\n */\r\nLongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {\r\n return this.high >>> 0;\r\n};\r\n\r\n/**\r\n * Gets the low 32 bits as a signed integer.\r\n * @returns {number} Signed low bits\r\n */\r\nLongPrototype.getLowBits = function getLowBits() {\r\n return this.low;\r\n};\r\n\r\n/**\r\n * Gets the low 32 bits as an unsigned integer.\r\n * @returns {number} Unsigned low bits\r\n */\r\nLongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {\r\n return this.low >>> 0;\r\n};\r\n\r\n/**\r\n * Gets the number of bits needed to represent the absolute value of this Long.\r\n * @returns {number}\r\n */\r\nLongPrototype.getNumBitsAbs = function getNumBitsAbs() {\r\n if (this.isNegative()) // Unsigned Longs are never negative\r\n return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();\r\n var val = this.high != 0 ? this.high : this.low;\r\n for (var bit = 31; bit > 0; bit--)\r\n if ((val & (1 << bit)) != 0)\r\n break;\r\n return this.high != 0 ? bit + 33 : bit + 1;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals zero.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isZero = function isZero() {\r\n return this.high === 0 && this.low === 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.eqz = LongPrototype.isZero;\r\n\r\n/**\r\n * Tests if this Long's value is negative.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isNegative = function isNegative() {\r\n return !this.unsigned && this.high < 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is positive.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isPositive = function isPositive() {\r\n return this.unsigned || this.high >= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is odd.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isOdd = function isOdd() {\r\n return (this.low & 1) === 1;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is even.\r\n * @returns {boolean}\r\n */\r\nLongPrototype.isEven = function isEven() {\r\n return (this.low & 1) === 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.equals = function equals(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)\r\n return false;\r\n return this.high === other.high && this.low === other.low;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.eq = LongPrototype.equals;\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.notEquals = function notEquals(other) {\r\n return !this.eq(/* validates */ other);\r\n};\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.neq = LongPrototype.notEquals;\r\n\r\n/**\r\n * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.ne = LongPrototype.notEquals;\r\n\r\n/**\r\n * Tests if this Long's value is less than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lessThan = function lessThan(other) {\r\n return this.comp(/* validates */ other) < 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lt = LongPrototype.lessThan;\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {\r\n return this.comp(/* validates */ other) <= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.lte = LongPrototype.lessThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.le = LongPrototype.lessThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is greater than the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.greaterThan = function greaterThan(other) {\r\n return this.comp(/* validates */ other) > 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.gt = LongPrototype.greaterThan;\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {\r\n return this.comp(/* validates */ other) >= 0;\r\n};\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.gte = LongPrototype.greaterThanOrEqual;\r\n\r\n/**\r\n * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {boolean}\r\n */\r\nLongPrototype.ge = LongPrototype.greaterThanOrEqual;\r\n\r\n/**\r\n * Compares this Long's value with the specified's.\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n * if the given one is greater\r\n */\r\nLongPrototype.compare = function compare(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n if (this.eq(other))\r\n return 0;\r\n var thisNeg = this.isNegative(),\r\n otherNeg = other.isNegative();\r\n if (thisNeg && !otherNeg)\r\n return -1;\r\n if (!thisNeg && otherNeg)\r\n return 1;\r\n // At this point the sign bits are the same\r\n if (!this.unsigned)\r\n return this.sub(other).isNegative() ? -1 : 1;\r\n // Both are positive if at least one is unsigned\r\n return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;\r\n};\r\n\r\n/**\r\n * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.\r\n * @function\r\n * @param {!Long|number|string} other Other value\r\n * @returns {number} 0 if they are the same, 1 if the this is greater and -1\r\n * if the given one is greater\r\n */\r\nLongPrototype.comp = LongPrototype.compare;\r\n\r\n/**\r\n * Negates this Long's value.\r\n * @returns {!Long} Negated Long\r\n */\r\nLongPrototype.negate = function negate() {\r\n if (!this.unsigned && this.eq(MIN_VALUE))\r\n return MIN_VALUE;\r\n return this.not().add(ONE);\r\n};\r\n\r\n/**\r\n * Negates this Long's value. This is an alias of {@link Long#negate}.\r\n * @function\r\n * @returns {!Long} Negated Long\r\n */\r\nLongPrototype.neg = LongPrototype.negate;\r\n\r\n/**\r\n * Returns the sum of this and the specified Long.\r\n * @param {!Long|number|string} addend Addend\r\n * @returns {!Long} Sum\r\n */\r\nLongPrototype.add = function add(addend) {\r\n if (!isLong(addend))\r\n addend = fromValue(addend);\r\n\r\n // Divide each number into 4 chunks of 16 bits, and then sum the chunks.\r\n\r\n var a48 = this.high >>> 16;\r\n var a32 = this.high & 0xFFFF;\r\n var a16 = this.low >>> 16;\r\n var a00 = this.low & 0xFFFF;\r\n\r\n var b48 = addend.high >>> 16;\r\n var b32 = addend.high & 0xFFFF;\r\n var b16 = addend.low >>> 16;\r\n var b00 = addend.low & 0xFFFF;\r\n\r\n var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n c00 += a00 + b00;\r\n c16 += c00 >>> 16;\r\n c00 &= 0xFFFF;\r\n c16 += a16 + b16;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c32 += a32 + b32;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c48 += a48 + b48;\r\n c48 &= 0xFFFF;\r\n return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the difference of this and the specified Long.\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\nLongPrototype.subtract = function subtract(subtrahend) {\r\n if (!isLong(subtrahend))\r\n subtrahend = fromValue(subtrahend);\r\n return this.add(subtrahend.neg());\r\n};\r\n\r\n/**\r\n * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.\r\n * @function\r\n * @param {!Long|number|string} subtrahend Subtrahend\r\n * @returns {!Long} Difference\r\n */\r\nLongPrototype.sub = LongPrototype.subtract;\r\n\r\n/**\r\n * Returns the product of this and the specified Long.\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\nLongPrototype.multiply = function multiply(multiplier) {\r\n if (this.isZero())\r\n return ZERO;\r\n if (!isLong(multiplier))\r\n multiplier = fromValue(multiplier);\r\n\r\n // use wasm support if present\r\n if (wasm) {\r\n var low = wasm.mul(this.low,\r\n this.high,\r\n multiplier.low,\r\n multiplier.high);\r\n return fromBits(low, wasm.get_high(), this.unsigned);\r\n }\r\n\r\n if (multiplier.isZero())\r\n return ZERO;\r\n if (this.eq(MIN_VALUE))\r\n return multiplier.isOdd() ? MIN_VALUE : ZERO;\r\n if (multiplier.eq(MIN_VALUE))\r\n return this.isOdd() ? MIN_VALUE : ZERO;\r\n\r\n if (this.isNegative()) {\r\n if (multiplier.isNegative())\r\n return this.neg().mul(multiplier.neg());\r\n else\r\n return this.neg().mul(multiplier).neg();\r\n } else if (multiplier.isNegative())\r\n return this.mul(multiplier.neg()).neg();\r\n\r\n // If both longs are small, use float multiplication\r\n if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))\r\n return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);\r\n\r\n // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.\r\n // We can skip products that would overflow.\r\n\r\n var a48 = this.high >>> 16;\r\n var a32 = this.high & 0xFFFF;\r\n var a16 = this.low >>> 16;\r\n var a00 = this.low & 0xFFFF;\r\n\r\n var b48 = multiplier.high >>> 16;\r\n var b32 = multiplier.high & 0xFFFF;\r\n var b16 = multiplier.low >>> 16;\r\n var b00 = multiplier.low & 0xFFFF;\r\n\r\n var c48 = 0, c32 = 0, c16 = 0, c00 = 0;\r\n c00 += a00 * b00;\r\n c16 += c00 >>> 16;\r\n c00 &= 0xFFFF;\r\n c16 += a16 * b00;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c16 += a00 * b16;\r\n c32 += c16 >>> 16;\r\n c16 &= 0xFFFF;\r\n c32 += a32 * b00;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c32 += a16 * b16;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c32 += a00 * b32;\r\n c48 += c32 >>> 16;\r\n c32 &= 0xFFFF;\r\n c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;\r\n c48 &= 0xFFFF;\r\n return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.\r\n * @function\r\n * @param {!Long|number|string} multiplier Multiplier\r\n * @returns {!Long} Product\r\n */\r\nLongPrototype.mul = LongPrototype.multiply;\r\n\r\n/**\r\n * Returns this Long divided by the specified. The result is signed if this Long is signed or\r\n * unsigned if this Long is unsigned.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\nLongPrototype.divide = function divide(divisor) {\r\n if (!isLong(divisor))\r\n divisor = fromValue(divisor);\r\n if (divisor.isZero())\r\n throw Error('division by zero');\r\n\r\n // use wasm support if present\r\n if (wasm) {\r\n // guard against signed division overflow: the largest\r\n // negative number / -1 would be 1 larger than the largest\r\n // positive number, due to two's complement.\r\n if (!this.unsigned &&\r\n this.high === -0x80000000 &&\r\n divisor.low === -1 && divisor.high === -1) {\r\n // be consistent with non-wasm code path\r\n return this;\r\n }\r\n var low = (this.unsigned ? wasm.div_u : wasm.div_s)(\r\n this.low,\r\n this.high,\r\n divisor.low,\r\n divisor.high\r\n );\r\n return fromBits(low, wasm.get_high(), this.unsigned);\r\n }\r\n\r\n if (this.isZero())\r\n return this.unsigned ? UZERO : ZERO;\r\n var approx, rem, res;\r\n if (!this.unsigned) {\r\n // This section is only relevant for signed longs and is derived from the\r\n // closure library as a whole.\r\n if (this.eq(MIN_VALUE)) {\r\n if (divisor.eq(ONE) || divisor.eq(NEG_ONE))\r\n return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE\r\n else if (divisor.eq(MIN_VALUE))\r\n return ONE;\r\n else {\r\n // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.\r\n var halfThis = this.shr(1);\r\n approx = halfThis.div(divisor).shl(1);\r\n if (approx.eq(ZERO)) {\r\n return divisor.isNegative() ? ONE : NEG_ONE;\r\n } else {\r\n rem = this.sub(divisor.mul(approx));\r\n res = approx.add(rem.div(divisor));\r\n return res;\r\n }\r\n }\r\n } else if (divisor.eq(MIN_VALUE))\r\n return this.unsigned ? UZERO : ZERO;\r\n if (this.isNegative()) {\r\n if (divisor.isNegative())\r\n return this.neg().div(divisor.neg());\r\n return this.neg().div(divisor).neg();\r\n } else if (divisor.isNegative())\r\n return this.div(divisor.neg()).neg();\r\n res = ZERO;\r\n } else {\r\n // The algorithm below has not been made for unsigned longs. It's therefore\r\n // required to take special care of the MSB prior to running it.\r\n if (!divisor.unsigned)\r\n divisor = divisor.toUnsigned();\r\n if (divisor.gt(this))\r\n return UZERO;\r\n if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true\r\n return UONE;\r\n res = UZERO;\r\n }\r\n\r\n // Repeat the following until the remainder is less than other: find a\r\n // floating-point that approximates remainder / other *from below*, add this\r\n // into the result, and subtract it from the remainder. It is critical that\r\n // the approximate value is less than or equal to the real value so that the\r\n // remainder never becomes negative.\r\n rem = this;\r\n while (rem.gte(divisor)) {\r\n // Approximate the result of division. This may be a little greater or\r\n // smaller than the actual value.\r\n approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));\r\n\r\n // We will tweak the approximate result by changing it in the 48-th digit or\r\n // the smallest non-fractional digit, whichever is larger.\r\n var log2 = Math.ceil(Math.log(approx) / Math.LN2),\r\n delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),\r\n\r\n // Decrease the approximation until it is smaller than the remainder. Note\r\n // that if it is too large, the product overflows and is negative.\r\n approxRes = fromNumber(approx),\r\n approxRem = approxRes.mul(divisor);\r\n while (approxRem.isNegative() || approxRem.gt(rem)) {\r\n approx -= delta;\r\n approxRes = fromNumber(approx, this.unsigned);\r\n approxRem = approxRes.mul(divisor);\r\n }\r\n\r\n // We know the answer can't be zero... and actually, zero would cause\r\n // infinite recursion since we would make no progress.\r\n if (approxRes.isZero())\r\n approxRes = ONE;\r\n\r\n res = res.add(approxRes);\r\n rem = rem.sub(approxRem);\r\n }\r\n return res;\r\n};\r\n\r\n/**\r\n * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Quotient\r\n */\r\nLongPrototype.div = LongPrototype.divide;\r\n\r\n/**\r\n * Returns this Long modulo the specified.\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.modulo = function modulo(divisor) {\r\n if (!isLong(divisor))\r\n divisor = fromValue(divisor);\r\n\r\n // use wasm support if present\r\n if (wasm) {\r\n var low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(\r\n this.low,\r\n this.high,\r\n divisor.low,\r\n divisor.high\r\n );\r\n return fromBits(low, wasm.get_high(), this.unsigned);\r\n }\r\n\r\n return this.sub(this.div(divisor).mul(divisor));\r\n};\r\n\r\n/**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.mod = LongPrototype.modulo;\r\n\r\n/**\r\n * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.\r\n * @function\r\n * @param {!Long|number|string} divisor Divisor\r\n * @returns {!Long} Remainder\r\n */\r\nLongPrototype.rem = LongPrototype.modulo;\r\n\r\n/**\r\n * Returns the bitwise NOT of this Long.\r\n * @returns {!Long}\r\n */\r\nLongPrototype.not = function not() {\r\n return fromBits(~this.low, ~this.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise AND of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.and = function and(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low & other.low, this.high & other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise OR of this Long and the specified.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.or = function or(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low | other.low, this.high | other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns the bitwise XOR of this Long and the given one.\r\n * @param {!Long|number|string} other Other Long\r\n * @returns {!Long}\r\n */\r\nLongPrototype.xor = function xor(other) {\r\n if (!isLong(other))\r\n other = fromValue(other);\r\n return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits shifted to the left by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftLeft = function shiftLeft(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n if ((numBits &= 63) === 0)\r\n return this;\r\n else if (numBits < 32)\r\n return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);\r\n else\r\n return fromBits(0, this.low << (numBits - 32), this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shl = LongPrototype.shiftLeft;\r\n\r\n/**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftRight = function shiftRight(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n if ((numBits &= 63) === 0)\r\n return this;\r\n else if (numBits < 32)\r\n return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);\r\n else\r\n return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);\r\n};\r\n\r\n/**\r\n * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shr = LongPrototype.shiftRight;\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount.\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {\r\n if (isLong(numBits))\r\n numBits = numBits.toInt();\r\n numBits &= 63;\r\n if (numBits === 0)\r\n return this;\r\n else {\r\n var high = this.high;\r\n if (numBits < 32) {\r\n var low = this.low;\r\n return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);\r\n } else if (numBits === 32)\r\n return fromBits(high, 0, this.unsigned);\r\n else\r\n return fromBits(high >>> (numBits - 32), 0, this.unsigned);\r\n }\r\n};\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shru = LongPrototype.shiftRightUnsigned;\r\n\r\n/**\r\n * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.\r\n * @function\r\n * @param {number|!Long} numBits Number of bits\r\n * @returns {!Long} Shifted Long\r\n */\r\nLongPrototype.shr_u = LongPrototype.shiftRightUnsigned;\r\n\r\n/**\r\n * Converts this Long to signed.\r\n * @returns {!Long} Signed long\r\n */\r\nLongPrototype.toSigned = function toSigned() {\r\n if (!this.unsigned)\r\n return this;\r\n return fromBits(this.low, this.high, false);\r\n};\r\n\r\n/**\r\n * Converts this Long to unsigned.\r\n * @returns {!Long} Unsigned long\r\n */\r\nLongPrototype.toUnsigned = function toUnsigned() {\r\n if (this.unsigned)\r\n return this;\r\n return fromBits(this.low, this.high, true);\r\n};\r\n\r\n/**\r\n * Converts this Long to its byte representation.\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {!Array.} Byte representation\r\n */\r\nLongPrototype.toBytes = function toBytes(le) {\r\n return le ? this.toBytesLE() : this.toBytesBE();\r\n};\r\n\r\n/**\r\n * Converts this Long to its little endian byte representation.\r\n * @returns {!Array.} Little endian byte representation\r\n */\r\nLongPrototype.toBytesLE = function toBytesLE() {\r\n var hi = this.high,\r\n lo = this.low;\r\n return [\r\n lo & 0xff,\r\n lo >>> 8 & 0xff,\r\n lo >>> 16 & 0xff,\r\n lo >>> 24 ,\r\n hi & 0xff,\r\n hi >>> 8 & 0xff,\r\n hi >>> 16 & 0xff,\r\n hi >>> 24\r\n ];\r\n};\r\n\r\n/**\r\n * Converts this Long to its big endian byte representation.\r\n * @returns {!Array.} Big endian byte representation\r\n */\r\nLongPrototype.toBytesBE = function toBytesBE() {\r\n var hi = this.high,\r\n lo = this.low;\r\n return [\r\n hi >>> 24 ,\r\n hi >>> 16 & 0xff,\r\n hi >>> 8 & 0xff,\r\n hi & 0xff,\r\n lo >>> 24 ,\r\n lo >>> 16 & 0xff,\r\n lo >>> 8 & 0xff,\r\n lo & 0xff\r\n ];\r\n};\r\n\r\n/**\r\n * Creates a Long from its byte representation.\r\n * @param {!Array.} bytes Byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @param {boolean=} le Whether little or big endian, defaults to big endian\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytes = function fromBytes(bytes, unsigned, le) {\r\n return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);\r\n};\r\n\r\n/**\r\n * Creates a Long from its little endian byte representation.\r\n * @param {!Array.} bytes Little endian byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytesLE = function fromBytesLE(bytes, unsigned) {\r\n return new Long(\r\n bytes[0] |\r\n bytes[1] << 8 |\r\n bytes[2] << 16 |\r\n bytes[3] << 24,\r\n bytes[4] |\r\n bytes[5] << 8 |\r\n bytes[6] << 16 |\r\n bytes[7] << 24,\r\n unsigned\r\n );\r\n};\r\n\r\n/**\r\n * Creates a Long from its big endian byte representation.\r\n * @param {!Array.} bytes Big endian byte representation\r\n * @param {boolean=} unsigned Whether unsigned or not, defaults to signed\r\n * @returns {Long} The corresponding Long value\r\n */\r\nLong.fromBytesBE = function fromBytesBE(bytes, unsigned) {\r\n return new Long(\r\n bytes[4] << 24 |\r\n bytes[5] << 16 |\r\n bytes[6] << 8 |\r\n bytes[7],\r\n bytes[0] << 24 |\r\n bytes[1] << 16 |\r\n bytes[2] << 8 |\r\n bytes[3],\r\n unsigned\r\n );\r\n};\r\n","\"use strict\";\n\nvar Buffer = require(\"safer-buffer\").Buffer;\n\nvar bomHandling = require(\"./bom-handling\"),\n iconv = module.exports;\n\n// All codecs and aliases are kept here, keyed by encoding name/alias.\n// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`.\niconv.encodings = null;\n\n// Characters emitted in case of error.\niconv.defaultCharUnicode = '�';\niconv.defaultCharSingleByte = '?';\n\n// Public API.\niconv.encode = function encode(str, encoding, options) {\n str = \"\" + (str || \"\"); // Ensure string.\n\n var encoder = iconv.getEncoder(encoding, options);\n\n var res = encoder.write(str);\n var trail = encoder.end();\n \n return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res;\n}\n\niconv.decode = function decode(buf, encoding, options) {\n if (typeof buf === 'string') {\n if (!iconv.skipDecodeWarning) {\n console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding');\n iconv.skipDecodeWarning = true;\n }\n\n buf = Buffer.from(\"\" + (buf || \"\"), \"binary\"); // Ensure buffer.\n }\n\n var decoder = iconv.getDecoder(encoding, options);\n\n var res = decoder.write(buf);\n var trail = decoder.end();\n\n return trail ? (res + trail) : res;\n}\n\niconv.encodingExists = function encodingExists(enc) {\n try {\n iconv.getCodec(enc);\n return true;\n } catch (e) {\n return false;\n }\n}\n\n// Legacy aliases to convert functions\niconv.toEncoding = iconv.encode;\niconv.fromEncoding = iconv.decode;\n\n// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache.\niconv._codecDataCache = {};\niconv.getCodec = function getCodec(encoding) {\n if (!iconv.encodings)\n iconv.encodings = require(\"../encodings\"); // Lazy load all encoding definitions.\n \n // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.\n var enc = iconv._canonicalizeEncoding(encoding);\n\n // Traverse iconv.encodings to find actual codec.\n var codecOptions = {};\n while (true) {\n var codec = iconv._codecDataCache[enc];\n if (codec)\n return codec;\n\n var codecDef = iconv.encodings[enc];\n\n switch (typeof codecDef) {\n case \"string\": // Direct alias to other encoding.\n enc = codecDef;\n break;\n\n case \"object\": // Alias with options. Can be layered.\n for (var key in codecDef)\n codecOptions[key] = codecDef[key];\n\n if (!codecOptions.encodingName)\n codecOptions.encodingName = enc;\n \n enc = codecDef.type;\n break;\n\n case \"function\": // Codec itself.\n if (!codecOptions.encodingName)\n codecOptions.encodingName = enc;\n\n // The codec function must load all tables and return object with .encoder and .decoder methods.\n // It'll be called only once (for each different options object).\n codec = new codecDef(codecOptions, iconv);\n\n iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later.\n return codec;\n\n default:\n throw new Error(\"Encoding not recognized: '\" + encoding + \"' (searched as: '\"+enc+\"')\");\n }\n }\n}\n\niconv._canonicalizeEncoding = function(encoding) {\n // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.\n return (''+encoding).toLowerCase().replace(/:\\d{4}$|[^0-9a-z]/g, \"\");\n}\n\niconv.getEncoder = function getEncoder(encoding, options) {\n var codec = iconv.getCodec(encoding),\n encoder = new codec.encoder(options, codec);\n\n if (codec.bomAware && options && options.addBOM)\n encoder = new bomHandling.PrependBOM(encoder, options);\n\n return encoder;\n}\n\niconv.getDecoder = function getDecoder(encoding, options) {\n var codec = iconv.getCodec(encoding),\n decoder = new codec.decoder(options, codec);\n\n if (codec.bomAware && !(options && options.stripBOM === false))\n decoder = new bomHandling.StripBOM(decoder, options);\n\n return decoder;\n}\n\n// Streaming API\n// NOTE: Streaming API naturally depends on 'stream' module from Node.js. Unfortunately in browser environments this module can add\n// up to 100Kb to the output bundle. To avoid unnecessary code bloat, we don't enable Streaming API in browser by default.\n// If you would like to enable it explicitly, please add the following code to your app:\n// > iconv.enableStreamingAPI(require('stream'));\niconv.enableStreamingAPI = function enableStreamingAPI(stream_module) {\n if (iconv.supportsStreams)\n return;\n\n // Dependency-inject stream module to create IconvLite stream classes.\n var streams = require(\"./streams\")(stream_module);\n\n // Not public API yet, but expose the stream classes.\n iconv.IconvLiteEncoderStream = streams.IconvLiteEncoderStream;\n iconv.IconvLiteDecoderStream = streams.IconvLiteDecoderStream;\n\n // Streaming API.\n iconv.encodeStream = function encodeStream(encoding, options) {\n return new iconv.IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options);\n }\n\n iconv.decodeStream = function decodeStream(encoding, options) {\n return new iconv.IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options);\n }\n\n iconv.supportsStreams = true;\n}\n\n// Enable Streaming API automatically if 'stream' module is available and non-empty (the majority of environments).\nvar stream_module;\ntry {\n stream_module = require(\"stream\");\n} catch (e) {}\n\nif (stream_module && stream_module.Transform) {\n iconv.enableStreamingAPI(stream_module);\n\n} else {\n // In rare cases where 'stream' module is not available by default, throw a helpful exception.\n iconv.encodeStream = iconv.decodeStream = function() {\n throw new Error(\"iconv-lite Streaming API is not enabled. Use iconv.enableStreamingAPI(require('stream')); to enable it.\");\n };\n}\n\nif (\"Ā\" != \"\\u0100\") {\n console.error(\"iconv-lite warning: js files use non-utf8 encoding. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info.\");\n}\n","\"use strict\";\n\nvar BOMChar = '\\uFEFF';\n\nexports.PrependBOM = PrependBOMWrapper\nfunction PrependBOMWrapper(encoder, options) {\n this.encoder = encoder;\n this.addBOM = true;\n}\n\nPrependBOMWrapper.prototype.write = function(str) {\n if (this.addBOM) {\n str = BOMChar + str;\n this.addBOM = false;\n }\n\n return this.encoder.write(str);\n}\n\nPrependBOMWrapper.prototype.end = function() {\n return this.encoder.end();\n}\n\n\n//------------------------------------------------------------------------------\n\nexports.StripBOM = StripBOMWrapper;\nfunction StripBOMWrapper(decoder, options) {\n this.decoder = decoder;\n this.pass = false;\n this.options = options || {};\n}\n\nStripBOMWrapper.prototype.write = function(buf) {\n var res = this.decoder.write(buf);\n if (this.pass || !res)\n return res;\n\n if (res[0] === BOMChar) {\n res = res.slice(1);\n if (typeof this.options.stripBOM === 'function')\n this.options.stripBOM();\n }\n\n this.pass = true;\n return res;\n}\n\nStripBOMWrapper.prototype.end = function() {\n return this.decoder.end();\n}\n\n","\"use strict\";\n\n// Update this array if you add/rename/remove files in this directory.\n// We support Browserify by skipping automatic module discovery and requiring modules directly.\nvar modules = [\n require(\"./internal\"),\n require(\"./utf32\"),\n require(\"./utf16\"),\n require(\"./utf7\"),\n require(\"./sbcs-codec\"),\n require(\"./sbcs-data\"),\n require(\"./sbcs-data-generated\"),\n require(\"./dbcs-codec\"),\n require(\"./dbcs-data\"),\n];\n\n// Put all encoding/alias/codec definitions to single object and export it.\nfor (var i = 0; i < modules.length; i++) {\n var module = modules[i];\n for (var enc in module)\n if (Object.prototype.hasOwnProperty.call(module, enc))\n exports[enc] = module[enc];\n}\n","\"use strict\";\nvar Buffer = require(\"safer-buffer\").Buffer;\n\n// Export Node.js internal encodings.\n\nmodule.exports = {\n // Encodings\n utf8: { type: \"_internal\", bomAware: true},\n cesu8: { type: \"_internal\", bomAware: true},\n unicode11utf8: \"utf8\",\n\n ucs2: { type: \"_internal\", bomAware: true},\n utf16le: \"ucs2\",\n\n binary: { type: \"_internal\" },\n base64: { type: \"_internal\" },\n hex: { type: \"_internal\" },\n\n // Codec.\n _internal: InternalCodec,\n};\n\n//------------------------------------------------------------------------------\n\nfunction InternalCodec(codecOptions, iconv) {\n this.enc = codecOptions.encodingName;\n this.bomAware = codecOptions.bomAware;\n\n if (this.enc === \"base64\")\n this.encoder = InternalEncoderBase64;\n else if (this.enc === \"cesu8\") {\n this.enc = \"utf8\"; // Use utf8 for decoding.\n this.encoder = InternalEncoderCesu8;\n\n // Add decoder for versions of Node not supporting CESU-8\n if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') {\n this.decoder = InternalDecoderCesu8;\n this.defaultCharUnicode = iconv.defaultCharUnicode;\n }\n }\n}\n\nInternalCodec.prototype.encoder = InternalEncoder;\nInternalCodec.prototype.decoder = InternalDecoder;\n\n//------------------------------------------------------------------------------\n\n// We use node.js internal decoder. Its signature is the same as ours.\nvar StringDecoder = require('string_decoder').StringDecoder;\n\nif (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.\n StringDecoder.prototype.end = function() {};\n\n\nfunction InternalDecoder(options, codec) {\n this.decoder = new StringDecoder(codec.enc);\n}\n\nInternalDecoder.prototype.write = function(buf) {\n if (!Buffer.isBuffer(buf)) {\n buf = Buffer.from(buf);\n }\n\n return this.decoder.write(buf);\n}\n\nInternalDecoder.prototype.end = function() {\n return this.decoder.end();\n}\n\n\n//------------------------------------------------------------------------------\n// Encoder is mostly trivial\n\nfunction InternalEncoder(options, codec) {\n this.enc = codec.enc;\n}\n\nInternalEncoder.prototype.write = function(str) {\n return Buffer.from(str, this.enc);\n}\n\nInternalEncoder.prototype.end = function() {\n}\n\n\n//------------------------------------------------------------------------------\n// Except base64 encoder, which must keep its state.\n\nfunction InternalEncoderBase64(options, codec) {\n this.prevStr = '';\n}\n\nInternalEncoderBase64.prototype.write = function(str) {\n str = this.prevStr + str;\n var completeQuads = str.length - (str.length % 4);\n this.prevStr = str.slice(completeQuads);\n str = str.slice(0, completeQuads);\n\n return Buffer.from(str, \"base64\");\n}\n\nInternalEncoderBase64.prototype.end = function() {\n return Buffer.from(this.prevStr, \"base64\");\n}\n\n\n//------------------------------------------------------------------------------\n// CESU-8 encoder is also special.\n\nfunction InternalEncoderCesu8(options, codec) {\n}\n\nInternalEncoderCesu8.prototype.write = function(str) {\n var buf = Buffer.alloc(str.length * 3), bufIdx = 0;\n for (var i = 0; i < str.length; i++) {\n var charCode = str.charCodeAt(i);\n // Naive implementation, but it works because CESU-8 is especially easy\n // to convert from UTF-16 (which all JS strings are encoded in).\n if (charCode < 0x80)\n buf[bufIdx++] = charCode;\n else if (charCode < 0x800) {\n buf[bufIdx++] = 0xC0 + (charCode >>> 6);\n buf[bufIdx++] = 0x80 + (charCode & 0x3f);\n }\n else { // charCode will always be < 0x10000 in javascript.\n buf[bufIdx++] = 0xE0 + (charCode >>> 12);\n buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f);\n buf[bufIdx++] = 0x80 + (charCode & 0x3f);\n }\n }\n return buf.slice(0, bufIdx);\n}\n\nInternalEncoderCesu8.prototype.end = function() {\n}\n\n//------------------------------------------------------------------------------\n// CESU-8 decoder is not implemented in Node v4.0+\n\nfunction InternalDecoderCesu8(options, codec) {\n this.acc = 0;\n this.contBytes = 0;\n this.accBytes = 0;\n this.defaultCharUnicode = codec.defaultCharUnicode;\n}\n\nInternalDecoderCesu8.prototype.write = function(buf) {\n var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, \n res = '';\n for (var i = 0; i < buf.length; i++) {\n var curByte = buf[i];\n if ((curByte & 0xC0) !== 0x80) { // Leading byte\n if (contBytes > 0) { // Previous code is invalid\n res += this.defaultCharUnicode;\n contBytes = 0;\n }\n\n if (curByte < 0x80) { // Single-byte code\n res += String.fromCharCode(curByte);\n } else if (curByte < 0xE0) { // Two-byte code\n acc = curByte & 0x1F;\n contBytes = 1; accBytes = 1;\n } else if (curByte < 0xF0) { // Three-byte code\n acc = curByte & 0x0F;\n contBytes = 2; accBytes = 1;\n } else { // Four or more are not supported for CESU-8.\n res += this.defaultCharUnicode;\n }\n } else { // Continuation byte\n if (contBytes > 0) { // We're waiting for it.\n acc = (acc << 6) | (curByte & 0x3f);\n contBytes--; accBytes++;\n if (contBytes === 0) {\n // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80)\n if (accBytes === 2 && acc < 0x80 && acc > 0)\n res += this.defaultCharUnicode;\n else if (accBytes === 3 && acc < 0x800)\n res += this.defaultCharUnicode;\n else\n // Actually add character.\n res += String.fromCharCode(acc);\n }\n } else { // Unexpected continuation byte\n res += this.defaultCharUnicode;\n }\n }\n }\n this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes;\n return res;\n}\n\nInternalDecoderCesu8.prototype.end = function() {\n var res = 0;\n if (this.contBytes > 0)\n res += this.defaultCharUnicode;\n return res;\n}\n","'use strict';\n\nvar Buffer = require('safer-buffer').Buffer;\n\n// == UTF32-LE/BE codec. ==========================================================\n\nexports._utf32 = Utf32Codec;\n\nfunction Utf32Codec(codecOptions, iconv) {\n this.iconv = iconv;\n this.bomAware = true;\n this.isLE = codecOptions.isLE;\n}\n\nexports.utf32le = { type: '_utf32', isLE: true };\nexports.utf32be = { type: '_utf32', isLE: false };\n\n// Aliases\nexports.ucs4le = 'utf32le';\nexports.ucs4be = 'utf32be';\n\nUtf32Codec.prototype.encoder = Utf32Encoder;\nUtf32Codec.prototype.decoder = Utf32Decoder;\n\n// -- Encoding\n\nfunction Utf32Encoder(options, codec) {\n this.isLE = codec.isLE;\n this.highSurrogate = 0;\n}\n\nUtf32Encoder.prototype.write = function(str) {\n var src = Buffer.from(str, 'ucs2');\n var dst = Buffer.alloc(src.length * 2);\n var write32 = this.isLE ? dst.writeUInt32LE : dst.writeUInt32BE;\n var offset = 0;\n\n for (var i = 0; i < src.length; i += 2) {\n var code = src.readUInt16LE(i);\n var isHighSurrogate = (0xD800 <= code && code < 0xDC00);\n var isLowSurrogate = (0xDC00 <= code && code < 0xE000);\n\n if (this.highSurrogate) {\n if (isHighSurrogate || !isLowSurrogate) {\n // There shouldn't be two high surrogates in a row, nor a high surrogate which isn't followed by a low\n // surrogate. If this happens, keep the pending high surrogate as a stand-alone semi-invalid character\n // (technically wrong, but expected by some applications, like Windows file names).\n write32.call(dst, this.highSurrogate, offset);\n offset += 4;\n }\n else {\n // Create 32-bit value from high and low surrogates;\n var codepoint = (((this.highSurrogate - 0xD800) << 10) | (code - 0xDC00)) + 0x10000;\n\n write32.call(dst, codepoint, offset);\n offset += 4;\n this.highSurrogate = 0;\n\n continue;\n }\n }\n\n if (isHighSurrogate)\n this.highSurrogate = code;\n else {\n // Even if the current character is a low surrogate, with no previous high surrogate, we'll\n // encode it as a semi-invalid stand-alone character for the same reasons expressed above for\n // unpaired high surrogates.\n write32.call(dst, code, offset);\n offset += 4;\n this.highSurrogate = 0;\n }\n }\n\n if (offset < dst.length)\n dst = dst.slice(0, offset);\n\n return dst;\n};\n\nUtf32Encoder.prototype.end = function() {\n // Treat any leftover high surrogate as a semi-valid independent character.\n if (!this.highSurrogate)\n return;\n\n var buf = Buffer.alloc(4);\n\n if (this.isLE)\n buf.writeUInt32LE(this.highSurrogate, 0);\n else\n buf.writeUInt32BE(this.highSurrogate, 0);\n\n this.highSurrogate = 0;\n\n return buf;\n};\n\n// -- Decoding\n\nfunction Utf32Decoder(options, codec) {\n this.isLE = codec.isLE;\n this.badChar = codec.iconv.defaultCharUnicode.charCodeAt(0);\n this.overflow = [];\n}\n\nUtf32Decoder.prototype.write = function(src) {\n if (src.length === 0)\n return '';\n\n var i = 0;\n var codepoint = 0;\n var dst = Buffer.alloc(src.length + 4);\n var offset = 0;\n var isLE = this.isLE;\n var overflow = this.overflow;\n var badChar = this.badChar;\n\n if (overflow.length > 0) {\n for (; i < src.length && overflow.length < 4; i++)\n overflow.push(src[i]);\n \n if (overflow.length === 4) {\n // NOTE: codepoint is a signed int32 and can be negative.\n // NOTE: We copied this block from below to help V8 optimize it (it works with array, not buffer).\n if (isLE) {\n codepoint = overflow[i] | (overflow[i+1] << 8) | (overflow[i+2] << 16) | (overflow[i+3] << 24);\n } else {\n codepoint = overflow[i+3] | (overflow[i+2] << 8) | (overflow[i+1] << 16) | (overflow[i] << 24);\n }\n overflow.length = 0;\n\n offset = _writeCodepoint(dst, offset, codepoint, badChar);\n }\n }\n\n // Main loop. Should be as optimized as possible.\n for (; i < src.length - 3; i += 4) {\n // NOTE: codepoint is a signed int32 and can be negative.\n if (isLE) {\n codepoint = src[i] | (src[i+1] << 8) | (src[i+2] << 16) | (src[i+3] << 24);\n } else {\n codepoint = src[i+3] | (src[i+2] << 8) | (src[i+1] << 16) | (src[i] << 24);\n }\n offset = _writeCodepoint(dst, offset, codepoint, badChar);\n }\n\n // Keep overflowing bytes.\n for (; i < src.length; i++) {\n overflow.push(src[i]);\n }\n\n return dst.slice(0, offset).toString('ucs2');\n};\n\nfunction _writeCodepoint(dst, offset, codepoint, badChar) {\n // NOTE: codepoint is signed int32 and can be negative. We keep it that way to help V8 with optimizations.\n if (codepoint < 0 || codepoint > 0x10FFFF) {\n // Not a valid Unicode codepoint\n codepoint = badChar;\n } \n\n // Ephemeral Planes: Write high surrogate.\n if (codepoint >= 0x10000) {\n codepoint -= 0x10000;\n\n var high = 0xD800 | (codepoint >> 10);\n dst[offset++] = high & 0xff;\n dst[offset++] = high >> 8;\n\n // Low surrogate is written below.\n var codepoint = 0xDC00 | (codepoint & 0x3FF);\n }\n\n // Write BMP char or low surrogate.\n dst[offset++] = codepoint & 0xff;\n dst[offset++] = codepoint >> 8;\n\n return offset;\n};\n\nUtf32Decoder.prototype.end = function() {\n this.overflow.length = 0;\n};\n\n// == UTF-32 Auto codec =============================================================\n// Decoder chooses automatically from UTF-32LE and UTF-32BE using BOM and space-based heuristic.\n// Defaults to UTF-32LE. http://en.wikipedia.org/wiki/UTF-32\n// Encoder/decoder default can be changed: iconv.decode(buf, 'utf32', {defaultEncoding: 'utf-32be'});\n\n// Encoder prepends BOM (which can be overridden with (addBOM: false}).\n\nexports.utf32 = Utf32AutoCodec;\nexports.ucs4 = 'utf32';\n\nfunction Utf32AutoCodec(options, iconv) {\n this.iconv = iconv;\n}\n\nUtf32AutoCodec.prototype.encoder = Utf32AutoEncoder;\nUtf32AutoCodec.prototype.decoder = Utf32AutoDecoder;\n\n// -- Encoding\n\nfunction Utf32AutoEncoder(options, codec) {\n options = options || {};\n\n if (options.addBOM === undefined)\n options.addBOM = true;\n\n this.encoder = codec.iconv.getEncoder(options.defaultEncoding || 'utf-32le', options);\n}\n\nUtf32AutoEncoder.prototype.write = function(str) {\n return this.encoder.write(str);\n};\n\nUtf32AutoEncoder.prototype.end = function() {\n return this.encoder.end();\n};\n\n// -- Decoding\n\nfunction Utf32AutoDecoder(options, codec) {\n this.decoder = null;\n this.initialBufs = [];\n this.initialBufsLen = 0;\n this.options = options || {};\n this.iconv = codec.iconv;\n}\n\nUtf32AutoDecoder.prototype.write = function(buf) {\n if (!this.decoder) { \n // Codec is not chosen yet. Accumulate initial bytes.\n this.initialBufs.push(buf);\n this.initialBufsLen += buf.length;\n\n if (this.initialBufsLen < 32) // We need more bytes to use space heuristic (see below)\n return '';\n\n // We have enough bytes -> detect endianness.\n var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);\n this.decoder = this.iconv.getDecoder(encoding, this.options);\n\n var resStr = '';\n for (var i = 0; i < this.initialBufs.length; i++)\n resStr += this.decoder.write(this.initialBufs[i]);\n\n this.initialBufs.length = this.initialBufsLen = 0;\n return resStr;\n }\n\n return this.decoder.write(buf);\n};\n\nUtf32AutoDecoder.prototype.end = function() {\n if (!this.decoder) {\n var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);\n this.decoder = this.iconv.getDecoder(encoding, this.options);\n\n var resStr = '';\n for (var i = 0; i < this.initialBufs.length; i++)\n resStr += this.decoder.write(this.initialBufs[i]);\n\n var trail = this.decoder.end();\n if (trail)\n resStr += trail;\n\n this.initialBufs.length = this.initialBufsLen = 0;\n return resStr;\n }\n\n return this.decoder.end();\n};\n\nfunction detectEncoding(bufs, defaultEncoding) {\n var b = [];\n var charsProcessed = 0;\n var invalidLE = 0, invalidBE = 0; // Number of invalid chars when decoded as LE or BE.\n var bmpCharsLE = 0, bmpCharsBE = 0; // Number of BMP chars when decoded as LE or BE.\n\n outer_loop:\n for (var i = 0; i < bufs.length; i++) {\n var buf = bufs[i];\n for (var j = 0; j < buf.length; j++) {\n b.push(buf[j]);\n if (b.length === 4) {\n if (charsProcessed === 0) {\n // Check BOM first.\n if (b[0] === 0xFF && b[1] === 0xFE && b[2] === 0 && b[3] === 0) {\n return 'utf-32le';\n }\n if (b[0] === 0 && b[1] === 0 && b[2] === 0xFE && b[3] === 0xFF) {\n return 'utf-32be';\n }\n }\n\n if (b[0] !== 0 || b[1] > 0x10) invalidBE++;\n if (b[3] !== 0 || b[2] > 0x10) invalidLE++;\n\n if (b[0] === 0 && b[1] === 0 && (b[2] !== 0 || b[3] !== 0)) bmpCharsBE++;\n if ((b[0] !== 0 || b[1] !== 0) && b[2] === 0 && b[3] === 0) bmpCharsLE++;\n\n b.length = 0;\n charsProcessed++;\n\n if (charsProcessed >= 100) {\n break outer_loop;\n }\n }\n }\n }\n\n // Make decisions.\n if (bmpCharsBE - invalidBE > bmpCharsLE - invalidLE) return 'utf-32be';\n if (bmpCharsBE - invalidBE < bmpCharsLE - invalidLE) return 'utf-32le';\n\n // Couldn't decide (likely all zeros or not enough data).\n return defaultEncoding || 'utf-32le';\n}\n","\"use strict\";\nvar Buffer = require(\"safer-buffer\").Buffer;\n\n// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js\n\n// == UTF16-BE codec. ==========================================================\n\nexports.utf16be = Utf16BECodec;\nfunction Utf16BECodec() {\n}\n\nUtf16BECodec.prototype.encoder = Utf16BEEncoder;\nUtf16BECodec.prototype.decoder = Utf16BEDecoder;\nUtf16BECodec.prototype.bomAware = true;\n\n\n// -- Encoding\n\nfunction Utf16BEEncoder() {\n}\n\nUtf16BEEncoder.prototype.write = function(str) {\n var buf = Buffer.from(str, 'ucs2');\n for (var i = 0; i < buf.length; i += 2) {\n var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp;\n }\n return buf;\n}\n\nUtf16BEEncoder.prototype.end = function() {\n}\n\n\n// -- Decoding\n\nfunction Utf16BEDecoder() {\n this.overflowByte = -1;\n}\n\nUtf16BEDecoder.prototype.write = function(buf) {\n if (buf.length == 0)\n return '';\n\n var buf2 = Buffer.alloc(buf.length + 1),\n i = 0, j = 0;\n\n if (this.overflowByte !== -1) {\n buf2[0] = buf[0];\n buf2[1] = this.overflowByte;\n i = 1; j = 2;\n }\n\n for (; i < buf.length-1; i += 2, j+= 2) {\n buf2[j] = buf[i+1];\n buf2[j+1] = buf[i];\n }\n\n this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1;\n\n return buf2.slice(0, j).toString('ucs2');\n}\n\nUtf16BEDecoder.prototype.end = function() {\n this.overflowByte = -1;\n}\n\n\n// == UTF-16 codec =============================================================\n// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic.\n// Defaults to UTF-16LE, as it's prevalent and default in Node.\n// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le\n// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'});\n\n// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false).\n\nexports.utf16 = Utf16Codec;\nfunction Utf16Codec(codecOptions, iconv) {\n this.iconv = iconv;\n}\n\nUtf16Codec.prototype.encoder = Utf16Encoder;\nUtf16Codec.prototype.decoder = Utf16Decoder;\n\n\n// -- Encoding (pass-through)\n\nfunction Utf16Encoder(options, codec) {\n options = options || {};\n if (options.addBOM === undefined)\n options.addBOM = true;\n this.encoder = codec.iconv.getEncoder('utf-16le', options);\n}\n\nUtf16Encoder.prototype.write = function(str) {\n return this.encoder.write(str);\n}\n\nUtf16Encoder.prototype.end = function() {\n return this.encoder.end();\n}\n\n\n// -- Decoding\n\nfunction Utf16Decoder(options, codec) {\n this.decoder = null;\n this.initialBufs = [];\n this.initialBufsLen = 0;\n\n this.options = options || {};\n this.iconv = codec.iconv;\n}\n\nUtf16Decoder.prototype.write = function(buf) {\n if (!this.decoder) {\n // Codec is not chosen yet. Accumulate initial bytes.\n this.initialBufs.push(buf);\n this.initialBufsLen += buf.length;\n \n if (this.initialBufsLen < 16) // We need more bytes to use space heuristic (see below)\n return '';\n\n // We have enough bytes -> detect endianness.\n var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);\n this.decoder = this.iconv.getDecoder(encoding, this.options);\n\n var resStr = '';\n for (var i = 0; i < this.initialBufs.length; i++)\n resStr += this.decoder.write(this.initialBufs[i]);\n\n this.initialBufs.length = this.initialBufsLen = 0;\n return resStr;\n }\n\n return this.decoder.write(buf);\n}\n\nUtf16Decoder.prototype.end = function() {\n if (!this.decoder) {\n var encoding = detectEncoding(this.initialBufs, this.options.defaultEncoding);\n this.decoder = this.iconv.getDecoder(encoding, this.options);\n\n var resStr = '';\n for (var i = 0; i < this.initialBufs.length; i++)\n resStr += this.decoder.write(this.initialBufs[i]);\n\n var trail = this.decoder.end();\n if (trail)\n resStr += trail;\n\n this.initialBufs.length = this.initialBufsLen = 0;\n return resStr;\n }\n return this.decoder.end();\n}\n\nfunction detectEncoding(bufs, defaultEncoding) {\n var b = [];\n var charsProcessed = 0;\n var asciiCharsLE = 0, asciiCharsBE = 0; // Number of ASCII chars when decoded as LE or BE.\n\n outer_loop:\n for (var i = 0; i < bufs.length; i++) {\n var buf = bufs[i];\n for (var j = 0; j < buf.length; j++) {\n b.push(buf[j]);\n if (b.length === 2) {\n if (charsProcessed === 0) {\n // Check BOM first.\n if (b[0] === 0xFF && b[1] === 0xFE) return 'utf-16le';\n if (b[0] === 0xFE && b[1] === 0xFF) return 'utf-16be';\n }\n\n if (b[0] === 0 && b[1] !== 0) asciiCharsBE++;\n if (b[0] !== 0 && b[1] === 0) asciiCharsLE++;\n\n b.length = 0;\n charsProcessed++;\n\n if (charsProcessed >= 100) {\n break outer_loop;\n }\n }\n }\n }\n\n // Make decisions.\n // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon.\n // So, we count ASCII as if it was LE or BE, and decide from that.\n if (asciiCharsBE > asciiCharsLE) return 'utf-16be';\n if (asciiCharsBE < asciiCharsLE) return 'utf-16le';\n\n // Couldn't decide (likely all zeros or not enough data).\n return defaultEncoding || 'utf-16le';\n}\n\n\n","\"use strict\";\nvar Buffer = require(\"safer-buffer\").Buffer;\n\n// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152\n// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3\n\nexports.utf7 = Utf7Codec;\nexports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7\nfunction Utf7Codec(codecOptions, iconv) {\n this.iconv = iconv;\n};\n\nUtf7Codec.prototype.encoder = Utf7Encoder;\nUtf7Codec.prototype.decoder = Utf7Decoder;\nUtf7Codec.prototype.bomAware = true;\n\n\n// -- Encoding\n\nvar nonDirectChars = /[^A-Za-z0-9'\\(\\),-\\.\\/:\\? \\n\\r\\t]+/g;\n\nfunction Utf7Encoder(options, codec) {\n this.iconv = codec.iconv;\n}\n\nUtf7Encoder.prototype.write = function(str) {\n // Naive implementation.\n // Non-direct chars are encoded as \"+-\"; single \"+\" char is encoded as \"+-\".\n return Buffer.from(str.replace(nonDirectChars, function(chunk) {\n return \"+\" + (chunk === '+' ? '' : \n this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) \n + \"-\";\n }.bind(this)));\n}\n\nUtf7Encoder.prototype.end = function() {\n}\n\n\n// -- Decoding\n\nfunction Utf7Decoder(options, codec) {\n this.iconv = codec.iconv;\n this.inBase64 = false;\n this.base64Accum = '';\n}\n\nvar base64Regex = /[A-Za-z0-9\\/+]/;\nvar base64Chars = [];\nfor (var i = 0; i < 256; i++)\n base64Chars[i] = base64Regex.test(String.fromCharCode(i));\n\nvar plusChar = '+'.charCodeAt(0), \n minusChar = '-'.charCodeAt(0),\n andChar = '&'.charCodeAt(0);\n\nUtf7Decoder.prototype.write = function(buf) {\n var res = \"\", lastI = 0,\n inBase64 = this.inBase64,\n base64Accum = this.base64Accum;\n\n // The decoder is more involved as we must handle chunks in stream.\n\n for (var i = 0; i < buf.length; i++) {\n if (!inBase64) { // We're in direct mode.\n // Write direct chars until '+'\n if (buf[i] == plusChar) {\n res += this.iconv.decode(buf.slice(lastI, i), \"ascii\"); // Write direct chars.\n lastI = i+1;\n inBase64 = true;\n }\n } else { // We decode base64.\n if (!base64Chars[buf[i]]) { // Base64 ended.\n if (i == lastI && buf[i] == minusChar) {// \"+-\" -> \"+\"\n res += \"+\";\n } else {\n var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), \"ascii\");\n res += this.iconv.decode(Buffer.from(b64str, 'base64'), \"utf16-be\");\n }\n\n if (buf[i] != minusChar) // Minus is absorbed after base64.\n i--;\n\n lastI = i+1;\n inBase64 = false;\n base64Accum = '';\n }\n }\n }\n\n if (!inBase64) {\n res += this.iconv.decode(buf.slice(lastI), \"ascii\"); // Write direct chars.\n } else {\n var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), \"ascii\");\n\n var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.\n base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.\n b64str = b64str.slice(0, canBeDecoded);\n\n res += this.iconv.decode(Buffer.from(b64str, 'base64'), \"utf16-be\");\n }\n\n this.inBase64 = inBase64;\n this.base64Accum = base64Accum;\n\n return res;\n}\n\nUtf7Decoder.prototype.end = function() {\n var res = \"\";\n if (this.inBase64 && this.base64Accum.length > 0)\n res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), \"utf16-be\");\n\n this.inBase64 = false;\n this.base64Accum = '';\n return res;\n}\n\n\n// UTF-7-IMAP codec.\n// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3)\n// Differences:\n// * Base64 part is started by \"&\" instead of \"+\"\n// * Direct characters are 0x20-0x7E, except \"&\" (0x26)\n// * In Base64, \",\" is used instead of \"/\"\n// * Base64 must not be used to represent direct characters.\n// * No implicit shift back from Base64 (should always end with '-')\n// * String must end in non-shifted position.\n// * \"-&\" while in base64 is not allowed.\n\n\nexports.utf7imap = Utf7IMAPCodec;\nfunction Utf7IMAPCodec(codecOptions, iconv) {\n this.iconv = iconv;\n};\n\nUtf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;\nUtf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;\nUtf7IMAPCodec.prototype.bomAware = true;\n\n\n// -- Encoding\n\nfunction Utf7IMAPEncoder(options, codec) {\n this.iconv = codec.iconv;\n this.inBase64 = false;\n this.base64Accum = Buffer.alloc(6);\n this.base64AccumIdx = 0;\n}\n\nUtf7IMAPEncoder.prototype.write = function(str) {\n var inBase64 = this.inBase64,\n base64Accum = this.base64Accum,\n base64AccumIdx = this.base64AccumIdx,\n buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0;\n\n for (var i = 0; i < str.length; i++) {\n var uChar = str.charCodeAt(i);\n if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'.\n if (inBase64) {\n if (base64AccumIdx > 0) {\n bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\\//g, ',').replace(/=+$/, ''), bufIdx);\n base64AccumIdx = 0;\n }\n\n buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.\n inBase64 = false;\n }\n\n if (!inBase64) {\n buf[bufIdx++] = uChar; // Write direct character\n\n if (uChar === andChar) // Ampersand -> '&-'\n buf[bufIdx++] = minusChar;\n }\n\n } else { // Non-direct character\n if (!inBase64) {\n buf[bufIdx++] = andChar; // Write '&', then go to base64 mode.\n inBase64 = true;\n }\n if (inBase64) {\n base64Accum[base64AccumIdx++] = uChar >> 8;\n base64Accum[base64AccumIdx++] = uChar & 0xFF;\n\n if (base64AccumIdx == base64Accum.length) {\n bufIdx += buf.write(base64Accum.toString('base64').replace(/\\//g, ','), bufIdx);\n base64AccumIdx = 0;\n }\n }\n }\n }\n\n this.inBase64 = inBase64;\n this.base64AccumIdx = base64AccumIdx;\n\n return buf.slice(0, bufIdx);\n}\n\nUtf7IMAPEncoder.prototype.end = function() {\n var buf = Buffer.alloc(10), bufIdx = 0;\n if (this.inBase64) {\n if (this.base64AccumIdx > 0) {\n bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\\//g, ',').replace(/=+$/, ''), bufIdx);\n this.base64AccumIdx = 0;\n }\n\n buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.\n this.inBase64 = false;\n }\n\n return buf.slice(0, bufIdx);\n}\n\n\n// -- Decoding\n\nfunction Utf7IMAPDecoder(options, codec) {\n this.iconv = codec.iconv;\n this.inBase64 = false;\n this.base64Accum = '';\n}\n\nvar base64IMAPChars = base64Chars.slice();\nbase64IMAPChars[','.charCodeAt(0)] = true;\n\nUtf7IMAPDecoder.prototype.write = function(buf) {\n var res = \"\", lastI = 0,\n inBase64 = this.inBase64,\n base64Accum = this.base64Accum;\n\n // The decoder is more involved as we must handle chunks in stream.\n // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end).\n\n for (var i = 0; i < buf.length; i++) {\n if (!inBase64) { // We're in direct mode.\n // Write direct chars until '&'\n if (buf[i] == andChar) {\n res += this.iconv.decode(buf.slice(lastI, i), \"ascii\"); // Write direct chars.\n lastI = i+1;\n inBase64 = true;\n }\n } else { // We decode base64.\n if (!base64IMAPChars[buf[i]]) { // Base64 ended.\n if (i == lastI && buf[i] == minusChar) { // \"&-\" -> \"&\"\n res += \"&\";\n } else {\n var b64str = base64Accum + this.iconv.decode(buf.slice(lastI, i), \"ascii\").replace(/,/g, '/');\n res += this.iconv.decode(Buffer.from(b64str, 'base64'), \"utf16-be\");\n }\n\n if (buf[i] != minusChar) // Minus may be absorbed after base64.\n i--;\n\n lastI = i+1;\n inBase64 = false;\n base64Accum = '';\n }\n }\n }\n\n if (!inBase64) {\n res += this.iconv.decode(buf.slice(lastI), \"ascii\"); // Write direct chars.\n } else {\n var b64str = base64Accum + this.iconv.decode(buf.slice(lastI), \"ascii\").replace(/,/g, '/');\n\n var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.\n base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.\n b64str = b64str.slice(0, canBeDecoded);\n\n res += this.iconv.decode(Buffer.from(b64str, 'base64'), \"utf16-be\");\n }\n\n this.inBase64 = inBase64;\n this.base64Accum = base64Accum;\n\n return res;\n}\n\nUtf7IMAPDecoder.prototype.end = function() {\n var res = \"\";\n if (this.inBase64 && this.base64Accum.length > 0)\n res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), \"utf16-be\");\n\n this.inBase64 = false;\n this.base64Accum = '';\n return res;\n}\n\n\n","\"use strict\";\nvar Buffer = require(\"safer-buffer\").Buffer;\n\n// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that\n// correspond to encoded bytes (if 128 - then lower half is ASCII). \n\nexports._sbcs = SBCSCodec;\nfunction SBCSCodec(codecOptions, iconv) {\n if (!codecOptions)\n throw new Error(\"SBCS codec is called without the data.\")\n \n // Prepare char buffer for decoding.\n if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))\n throw new Error(\"Encoding '\"+codecOptions.type+\"' has incorrect 'chars' (must be of len 128 or 256)\");\n \n if (codecOptions.chars.length === 128) {\n var asciiString = \"\";\n for (var i = 0; i < 128; i++)\n asciiString += String.fromCharCode(i);\n codecOptions.chars = asciiString + codecOptions.chars;\n }\n\n this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');\n \n // Encoding buffer.\n var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));\n\n for (var i = 0; i < codecOptions.chars.length; i++)\n encodeBuf[codecOptions.chars.charCodeAt(i)] = i;\n\n this.encodeBuf = encodeBuf;\n}\n\nSBCSCodec.prototype.encoder = SBCSEncoder;\nSBCSCodec.prototype.decoder = SBCSDecoder;\n\n\nfunction SBCSEncoder(options, codec) {\n this.encodeBuf = codec.encodeBuf;\n}\n\nSBCSEncoder.prototype.write = function(str) {\n var buf = Buffer.alloc(str.length);\n for (var i = 0; i < str.length; i++)\n buf[i] = this.encodeBuf[str.charCodeAt(i)];\n \n return buf;\n}\n\nSBCSEncoder.prototype.end = function() {\n}\n\n\nfunction SBCSDecoder(options, codec) {\n this.decodeBuf = codec.decodeBuf;\n}\n\nSBCSDecoder.prototype.write = function(buf) {\n // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.\n var decodeBuf = this.decodeBuf;\n var newBuf = Buffer.alloc(buf.length*2);\n var idx1 = 0, idx2 = 0;\n for (var i = 0; i < buf.length; i++) {\n idx1 = buf[i]*2; idx2 = i*2;\n newBuf[idx2] = decodeBuf[idx1];\n newBuf[idx2+1] = decodeBuf[idx1+1];\n }\n return newBuf.toString('ucs2');\n}\n\nSBCSDecoder.prototype.end = function() {\n}\n","\"use strict\";\n\n// Manually added data to be used by sbcs codec in addition to generated one.\n\nmodule.exports = {\n // Not supported by iconv, not sure why.\n \"10029\": \"maccenteuro\",\n \"maccenteuro\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ\"\n },\n\n \"808\": \"cp808\",\n \"ibm808\": \"cp808\",\n \"cp808\": {\n \"type\": \"_sbcs\",\n \"chars\": \"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ \"\n },\n\n \"mik\": {\n \"type\": \"_sbcs\",\n \"chars\": \"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ \"\n },\n\n \"cp720\": {\n \"type\": \"_sbcs\",\n \"chars\": \"\\x80\\x81éâ\\x84à\\x86çêëèïî\\x8d\\x8e\\x8f\\x90\\u0651\\u0652ô¤ـûùءآأؤ£إئابةتثجحخدذرزسشص«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ضطظعغفµقكلمنهوىي≡\\u064b\\u064c\\u064d\\u064e\\u064f\\u0650≈°∙·√ⁿ²■\\u00a0\"\n },\n\n // Aliases of generated encodings.\n \"ascii8bit\": \"ascii\",\n \"usascii\": \"ascii\",\n \"ansix34\": \"ascii\",\n \"ansix341968\": \"ascii\",\n \"ansix341986\": \"ascii\",\n \"csascii\": \"ascii\",\n \"cp367\": \"ascii\",\n \"ibm367\": \"ascii\",\n \"isoir6\": \"ascii\",\n \"iso646us\": \"ascii\",\n \"iso646irv\": \"ascii\",\n \"us\": \"ascii\",\n\n \"latin1\": \"iso88591\",\n \"latin2\": \"iso88592\",\n \"latin3\": \"iso88593\",\n \"latin4\": \"iso88594\",\n \"latin5\": \"iso88599\",\n \"latin6\": \"iso885910\",\n \"latin7\": \"iso885913\",\n \"latin8\": \"iso885914\",\n \"latin9\": \"iso885915\",\n \"latin10\": \"iso885916\",\n\n \"csisolatin1\": \"iso88591\",\n \"csisolatin2\": \"iso88592\",\n \"csisolatin3\": \"iso88593\",\n \"csisolatin4\": \"iso88594\",\n \"csisolatincyrillic\": \"iso88595\",\n \"csisolatinarabic\": \"iso88596\",\n \"csisolatingreek\" : \"iso88597\",\n \"csisolatinhebrew\": \"iso88598\",\n \"csisolatin5\": \"iso88599\",\n \"csisolatin6\": \"iso885910\",\n\n \"l1\": \"iso88591\",\n \"l2\": \"iso88592\",\n \"l3\": \"iso88593\",\n \"l4\": \"iso88594\",\n \"l5\": \"iso88599\",\n \"l6\": \"iso885910\",\n \"l7\": \"iso885913\",\n \"l8\": \"iso885914\",\n \"l9\": \"iso885915\",\n \"l10\": \"iso885916\",\n\n \"isoir14\": \"iso646jp\",\n \"isoir57\": \"iso646cn\",\n \"isoir100\": \"iso88591\",\n \"isoir101\": \"iso88592\",\n \"isoir109\": \"iso88593\",\n \"isoir110\": \"iso88594\",\n \"isoir144\": \"iso88595\",\n \"isoir127\": \"iso88596\",\n \"isoir126\": \"iso88597\",\n \"isoir138\": \"iso88598\",\n \"isoir148\": \"iso88599\",\n \"isoir157\": \"iso885910\",\n \"isoir166\": \"tis620\",\n \"isoir179\": \"iso885913\",\n \"isoir199\": \"iso885914\",\n \"isoir203\": \"iso885915\",\n \"isoir226\": \"iso885916\",\n\n \"cp819\": \"iso88591\",\n \"ibm819\": \"iso88591\",\n\n \"cyrillic\": \"iso88595\",\n\n \"arabic\": \"iso88596\",\n \"arabic8\": \"iso88596\",\n \"ecma114\": \"iso88596\",\n \"asmo708\": \"iso88596\",\n\n \"greek\" : \"iso88597\",\n \"greek8\" : \"iso88597\",\n \"ecma118\" : \"iso88597\",\n \"elot928\" : \"iso88597\",\n\n \"hebrew\": \"iso88598\",\n \"hebrew8\": \"iso88598\",\n\n \"turkish\": \"iso88599\",\n \"turkish8\": \"iso88599\",\n\n \"thai\": \"iso885911\",\n \"thai8\": \"iso885911\",\n\n \"celtic\": \"iso885914\",\n \"celtic8\": \"iso885914\",\n \"isoceltic\": \"iso885914\",\n\n \"tis6200\": \"tis620\",\n \"tis62025291\": \"tis620\",\n \"tis62025330\": \"tis620\",\n\n \"10000\": \"macroman\",\n \"10006\": \"macgreek\",\n \"10007\": \"maccyrillic\",\n \"10079\": \"maciceland\",\n \"10081\": \"macturkish\",\n\n \"cspc8codepage437\": \"cp437\",\n \"cspc775baltic\": \"cp775\",\n \"cspc850multilingual\": \"cp850\",\n \"cspcp852\": \"cp852\",\n \"cspc862latinhebrew\": \"cp862\",\n \"cpgr\": \"cp869\",\n\n \"msee\": \"cp1250\",\n \"mscyrl\": \"cp1251\",\n \"msansi\": \"cp1252\",\n \"msgreek\": \"cp1253\",\n \"msturk\": \"cp1254\",\n \"mshebr\": \"cp1255\",\n \"msarab\": \"cp1256\",\n \"winbaltrim\": \"cp1257\",\n\n \"cp20866\": \"koi8r\",\n \"20866\": \"koi8r\",\n \"ibm878\": \"koi8r\",\n \"cskoi8r\": \"koi8r\",\n\n \"cp21866\": \"koi8u\",\n \"21866\": \"koi8u\",\n \"ibm1168\": \"koi8u\",\n\n \"strk10482002\": \"rk1048\",\n\n \"tcvn5712\": \"tcvn\",\n \"tcvn57121\": \"tcvn\",\n\n \"gb198880\": \"iso646cn\",\n \"cn\": \"iso646cn\",\n\n \"csiso14jisc6220ro\": \"iso646jp\",\n \"jisc62201969ro\": \"iso646jp\",\n \"jp\": \"iso646jp\",\n\n \"cshproman8\": \"hproman8\",\n \"r8\": \"hproman8\",\n \"roman8\": \"hproman8\",\n \"xroman8\": \"hproman8\",\n \"ibm1051\": \"hproman8\",\n\n \"mac\": \"macintosh\",\n \"csmacintosh\": \"macintosh\",\n};\n\n","\"use strict\";\n\n// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script.\nmodule.exports = {\n \"437\": \"cp437\",\n \"737\": \"cp737\",\n \"775\": \"cp775\",\n \"850\": \"cp850\",\n \"852\": \"cp852\",\n \"855\": \"cp855\",\n \"856\": \"cp856\",\n \"857\": \"cp857\",\n \"858\": \"cp858\",\n \"860\": \"cp860\",\n \"861\": \"cp861\",\n \"862\": \"cp862\",\n \"863\": \"cp863\",\n \"864\": \"cp864\",\n \"865\": \"cp865\",\n \"866\": \"cp866\",\n \"869\": \"cp869\",\n \"874\": \"windows874\",\n \"922\": \"cp922\",\n \"1046\": \"cp1046\",\n \"1124\": \"cp1124\",\n \"1125\": \"cp1125\",\n \"1129\": \"cp1129\",\n \"1133\": \"cp1133\",\n \"1161\": \"cp1161\",\n \"1162\": \"cp1162\",\n \"1163\": \"cp1163\",\n \"1250\": \"windows1250\",\n \"1251\": \"windows1251\",\n \"1252\": \"windows1252\",\n \"1253\": \"windows1253\",\n \"1254\": \"windows1254\",\n \"1255\": \"windows1255\",\n \"1256\": \"windows1256\",\n \"1257\": \"windows1257\",\n \"1258\": \"windows1258\",\n \"28591\": \"iso88591\",\n \"28592\": \"iso88592\",\n \"28593\": \"iso88593\",\n \"28594\": \"iso88594\",\n \"28595\": \"iso88595\",\n \"28596\": \"iso88596\",\n \"28597\": \"iso88597\",\n \"28598\": \"iso88598\",\n \"28599\": \"iso88599\",\n \"28600\": \"iso885910\",\n \"28601\": \"iso885911\",\n \"28603\": \"iso885913\",\n \"28604\": \"iso885914\",\n \"28605\": \"iso885915\",\n \"28606\": \"iso885916\",\n \"windows874\": {\n \"type\": \"_sbcs\",\n \"chars\": \"€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����\"\n },\n \"win874\": \"windows874\",\n \"cp874\": \"windows874\",\n \"windows1250\": {\n \"type\": \"_sbcs\",\n \"chars\": \"€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙\"\n },\n \"win1250\": \"windows1250\",\n \"cp1250\": \"windows1250\",\n \"windows1251\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя\"\n },\n \"win1251\": \"windows1251\",\n \"cp1251\": \"windows1251\",\n \"windows1252\": {\n \"type\": \"_sbcs\",\n \"chars\": \"€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ\"\n },\n \"win1252\": \"windows1252\",\n \"cp1252\": \"windows1252\",\n \"windows1253\": {\n \"type\": \"_sbcs\",\n \"chars\": \"€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�\"\n },\n \"win1253\": \"windows1253\",\n \"cp1253\": \"windows1253\",\n \"windows1254\": {\n \"type\": \"_sbcs\",\n \"chars\": \"€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ\"\n },\n \"win1254\": \"windows1254\",\n \"cp1254\": \"windows1254\",\n \"windows1255\": {\n \"type\": \"_sbcs\",\n \"chars\": \"€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת���\"\n },\n \"win1255\": \"windows1255\",\n \"cp1255\": \"windows1255\",\n \"windows1256\": {\n \"type\": \"_sbcs\",\n \"chars\": \"€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œں ،¢£¤¥¦§¨©ھ«¬®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûüے\"\n },\n \"win1256\": \"windows1256\",\n \"cp1256\": \"windows1256\",\n \"windows1257\": {\n \"type\": \"_sbcs\",\n \"chars\": \"€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙\"\n },\n \"win1257\": \"windows1257\",\n \"cp1257\": \"windows1257\",\n \"windows1258\": {\n \"type\": \"_sbcs\",\n \"chars\": \"€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ\"\n },\n \"win1258\": \"windows1258\",\n \"cp1258\": \"windows1258\",\n \"iso88591\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ\"\n },\n \"cp28591\": \"iso88591\",\n \"iso88592\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
Ą˘Ł¤ĽŚ§¨ŠŞŤŹŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙\"\n },\n \"cp28592\": \"iso88592\",\n \"iso88593\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
Ħ˘£¤�Ĥ§¨İŞĞĴ�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙\"\n },\n \"cp28593\": \"iso88593\",\n \"iso88594\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
ĄĸŖ¤Ĩϧ¨ŠĒĢŦޝ°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙\"\n },\n \"cp28594\": \"iso88594\",\n \"iso88595\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
ЁЂЃЄЅІЇЈЉЊЋЌЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ\"\n },\n \"cp28595\": \"iso88595\",\n \"iso88596\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
���¤�������،�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������\"\n },\n \"cp28596\": \"iso88596\",\n \"iso88597\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
‘’£€₯¦§¨©ͺ«¬�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�\"\n },\n \"cp28597\": \"iso88597\",\n \"iso88598\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
�¢£¤¥¦§¨©×«¬®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת���\"\n },\n \"cp28598\": \"iso88598\",\n \"iso88599\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ\"\n },\n \"cp28599\": \"iso88599\",\n \"iso885910\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
ĄĒĢĪĨͧĻĐŠŦŽŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ\"\n },\n \"cp28600\": \"iso885910\",\n \"iso885911\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����\"\n },\n \"cp28601\": \"iso885911\",\n \"iso885913\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
”¢£¤„¦§Ø©Ŗ«¬®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’\"\n },\n \"cp28603\": \"iso885913\",\n \"iso885914\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ\"\n },\n \"cp28604\": \"iso885914\",\n \"iso885915\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
¡¢£€¥Š§š©ª«¬®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ\"\n },\n \"cp28605\": \"iso885915\",\n \"iso885916\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
ĄąŁ€„Чš©Ș«ŹźŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ\"\n },\n \"cp28606\": \"iso885916\",\n \"cp437\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ \"\n },\n \"ibm437\": \"cp437\",\n \"csibm437\": \"cp437\",\n \"cp737\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ \"\n },\n \"ibm737\": \"cp737\",\n \"csibm737\": \"cp737\",\n \"cp775\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’±“¾¶§÷„°∙·¹³²■ \"\n },\n \"ibm775\": \"cp775\",\n \"csibm775\": \"cp775\",\n \"cp850\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´±‗¾¶§÷¸°¨·¹³²■ \"\n },\n \"ibm850\": \"cp850\",\n \"csibm850\": \"cp850\",\n \"cp852\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´˝˛ˇ˘§÷¸°¨˙űŘř■ \"\n },\n \"ibm852\": \"cp852\",\n \"csibm852\": \"cp852\",\n \"cp855\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№ыЫзЗшШэЭщЩчЧ§■ \"\n },\n \"ibm855\": \"cp855\",\n \"csibm855\": \"cp855\",\n \"cp856\": {\n \"type\": \"_sbcs\",\n \"chars\": \"אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´±‗¾¶§÷¸°¨·¹³²■ \"\n },\n \"ibm856\": \"cp856\",\n \"csibm856\": \"cp856\",\n \"cp857\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´±�¾¶§÷¸°¨·¹³²■ \"\n },\n \"ibm857\": \"cp857\",\n \"csibm857\": \"cp857\",\n \"cp858\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´±‗¾¶§÷¸°¨·¹³²■ \"\n },\n \"ibm858\": \"cp858\",\n \"csibm858\": \"cp858\",\n \"cp860\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ \"\n },\n \"ibm860\": \"cp860\",\n \"csibm860\": \"cp860\",\n \"cp861\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ \"\n },\n \"ibm861\": \"cp861\",\n \"csibm861\": \"cp861\",\n \"cp862\": {\n \"type\": \"_sbcs\",\n \"chars\": \"אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ \"\n },\n \"ibm862\": \"cp862\",\n \"csibm862\": \"cp862\",\n \"cp863\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ \"\n },\n \"ibm863\": \"cp863\",\n \"csibm863\": \"cp863\",\n \"cp864\": {\n \"type\": \"_sbcs\",\n \"chars\": \"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f !\\\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�\"\n },\n \"ibm864\": \"cp864\",\n \"csibm864\": \"cp864\",\n \"cp865\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ \"\n },\n \"ibm865\": \"cp865\",\n \"csibm865\": \"cp865\",\n \"cp866\": {\n \"type\": \"_sbcs\",\n \"chars\": \"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ \"\n },\n \"ibm866\": \"cp866\",\n \"csibm866\": \"cp866\",\n \"cp869\": {\n \"type\": \"_sbcs\",\n \"chars\": \"������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄±υφχ§ψ΅°¨ωϋΰώ■ \"\n },\n \"ibm869\": \"cp869\",\n \"csibm869\": \"cp869\",\n \"cp922\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
¡¢£¤¥¦§¨©ª«¬®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ\"\n },\n \"ibm922\": \"cp922\",\n \"csibm922\": \"cp922\",\n \"cp1046\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ﺈ×÷ﹱ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�\"\n },\n \"ibm1046\": \"cp1046\",\n \"csibm1046\": \"cp1046\",\n \"cp1124\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
ЁЂҐЄЅІЇЈЉЊЋЌЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ\"\n },\n \"ibm1124\": \"cp1124\",\n \"csibm1124\": \"cp1124\",\n \"cp1125\": {\n \"type\": \"_sbcs\",\n \"chars\": \"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ \"\n },\n \"ibm1125\": \"cp1125\",\n \"csibm1125\": \"cp1125\",\n \"cp1129\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
¡¢£¤¥¦§œ©ª«¬®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ\"\n },\n \"ibm1129\": \"cp1129\",\n \"csibm1129\": \"cp1129\",\n \"cp1133\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�\"\n },\n \"ibm1133\": \"cp1133\",\n \"csibm1133\": \"cp1133\",\n \"cp1161\": {\n \"type\": \"_sbcs\",\n \"chars\": \"��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ \"\n },\n \"ibm1161\": \"cp1161\",\n \"csibm1161\": \"cp1161\",\n \"cp1162\": {\n \"type\": \"_sbcs\",\n \"chars\": \"€…‘’“”•–— กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����\"\n },\n \"ibm1162\": \"cp1162\",\n \"csibm1162\": \"cp1162\",\n \"cp1163\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
¡¢£€¥¦§œ©ª«¬®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ\"\n },\n \"ibm1163\": \"cp1163\",\n \"csibm1163\": \"cp1163\",\n \"maccroatian\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ\"\n },\n \"maccyrillic\": {\n \"type\": \"_sbcs\",\n \"chars\": \"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤\"\n },\n \"macgreek\": {\n \"type\": \"_sbcs\",\n \"chars\": \"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�\"\n },\n \"maciceland\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ\"\n },\n \"macroman\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ\"\n },\n \"macromania\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ\"\n },\n \"macthai\": {\n \"type\": \"_sbcs\",\n \"chars\": \"«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����\"\n },\n \"macturkish\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ\"\n },\n \"macukraine\": {\n \"type\": \"_sbcs\",\n \"chars\": \"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤\"\n },\n \"koi8r\": {\n \"type\": \"_sbcs\",\n \"chars\": \"─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ\"\n },\n \"koi8u\": {\n \"type\": \"_sbcs\",\n \"chars\": \"─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ\"\n },\n \"koi8ru\": {\n \"type\": \"_sbcs\",\n \"chars\": \"─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ\"\n },\n \"koi8t\": {\n \"type\": \"_sbcs\",\n \"chars\": \"қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ\"\n },\n \"armscii8\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
�և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�\"\n },\n \"rk1048\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя\"\n },\n \"tcvn\": {\n \"type\": \"_sbcs\",\n \"chars\": \"\\u0000ÚỤ\\u0003ỪỬỮ\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010ỨỰỲỶỸÝỴ\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ\"\n },\n \"georgianacademy\": {\n \"type\": \"_sbcs\",\n \"chars\": \"‚ƒ„…†‡ˆ‰Š‹Œ‘’“”•–—˜™š›œŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ\"\n },\n \"georgianps\": {\n \"type\": \"_sbcs\",\n \"chars\": \"‚ƒ„…†‡ˆ‰Š‹Œ‘’“”•–—˜™š›œŸ ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ\"\n },\n \"pt154\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя\"\n },\n \"viscii\": {\n \"type\": \"_sbcs\",\n \"chars\": \"\\u0000\\u0001Ẳ\\u0003\\u0004ẴẪ\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013Ỷ\\u0015\\u0016\\u0017\\u0018Ỹ\\u001a\\u001b\\u001c\\u001dỴ\\u001f !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ\"\n },\n \"iso646cn\": {\n \"type\": \"_sbcs\",\n \"chars\": \"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f !\\\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������\"\n },\n \"iso646jp\": {\n \"type\": \"_sbcs\",\n \"chars\": \"\\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f !\\\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������\"\n },\n \"hproman8\": {\n \"type\": \"_sbcs\",\n \"chars\": \"
ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�\"\n },\n \"macintosh\": {\n \"type\": \"_sbcs\",\n \"chars\": \"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ\"\n },\n \"ascii\": {\n \"type\": \"_sbcs\",\n \"chars\": \"��������������������������������������������������������������������������������������������������������������������������������\"\n },\n \"tis620\": {\n \"type\": \"_sbcs\",\n \"chars\": \"���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����\"\n }\n}","\"use strict\";\nvar Buffer = require(\"safer-buffer\").Buffer;\n\n// Multibyte codec. In this scheme, a character is represented by 1 or more bytes.\n// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.\n// To save memory and loading time, we read table files only when requested.\n\nexports._dbcs = DBCSCodec;\n\nvar UNASSIGNED = -1,\n GB18030_CODE = -2,\n SEQ_START = -10,\n NODE_START = -1000,\n UNASSIGNED_NODE = new Array(0x100),\n DEF_CHAR = -1;\n\nfor (var i = 0; i < 0x100; i++)\n UNASSIGNED_NODE[i] = UNASSIGNED;\n\n\n// Class DBCSCodec reads and initializes mapping tables.\nfunction DBCSCodec(codecOptions, iconv) {\n this.encodingName = codecOptions.encodingName;\n if (!codecOptions)\n throw new Error(\"DBCS codec is called without the data.\")\n if (!codecOptions.table)\n throw new Error(\"Encoding '\" + this.encodingName + \"' has no data.\");\n\n // Load tables.\n var mappingTable = codecOptions.table();\n\n\n // Decode tables: MBCS -> Unicode.\n\n // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.\n // Trie root is decodeTables[0].\n // Values: >= 0 -> unicode character code. can be > 0xFFFF\n // == UNASSIGNED -> unknown/unassigned sequence.\n // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.\n // <= NODE_START -> index of the next node in our trie to process next byte.\n // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq.\n this.decodeTables = [];\n this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.\n\n // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. \n this.decodeTableSeq = [];\n\n // Actual mapping tables consist of chunks. Use them to fill up decode tables.\n for (var i = 0; i < mappingTable.length; i++)\n this._addDecodeChunk(mappingTable[i]);\n\n // Load & create GB18030 tables when needed.\n if (typeof codecOptions.gb18030 === 'function') {\n this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.\n\n // Add GB18030 common decode nodes.\n var commonThirdByteNodeIdx = this.decodeTables.length;\n this.decodeTables.push(UNASSIGNED_NODE.slice(0));\n\n var commonFourthByteNodeIdx = this.decodeTables.length;\n this.decodeTables.push(UNASSIGNED_NODE.slice(0));\n\n // Fill out the tree\n var firstByteNode = this.decodeTables[0];\n for (var i = 0x81; i <= 0xFE; i++) {\n var secondByteNode = this.decodeTables[NODE_START - firstByteNode[i]];\n for (var j = 0x30; j <= 0x39; j++) {\n if (secondByteNode[j] === UNASSIGNED) {\n secondByteNode[j] = NODE_START - commonThirdByteNodeIdx;\n } else if (secondByteNode[j] > NODE_START) {\n throw new Error(\"gb18030 decode tables conflict at byte 2\");\n }\n\n var thirdByteNode = this.decodeTables[NODE_START - secondByteNode[j]];\n for (var k = 0x81; k <= 0xFE; k++) {\n if (thirdByteNode[k] === UNASSIGNED) {\n thirdByteNode[k] = NODE_START - commonFourthByteNodeIdx;\n } else if (thirdByteNode[k] === NODE_START - commonFourthByteNodeIdx) {\n continue;\n } else if (thirdByteNode[k] > NODE_START) {\n throw new Error(\"gb18030 decode tables conflict at byte 3\");\n }\n\n var fourthByteNode = this.decodeTables[NODE_START - thirdByteNode[k]];\n for (var l = 0x30; l <= 0x39; l++) {\n if (fourthByteNode[l] === UNASSIGNED)\n fourthByteNode[l] = GB18030_CODE;\n }\n }\n }\n }\n }\n\n this.defaultCharUnicode = iconv.defaultCharUnicode;\n\n \n // Encode tables: Unicode -> DBCS.\n\n // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.\n // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.\n // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).\n // == UNASSIGNED -> no conversion found. Output a default char.\n // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence.\n this.encodeTable = [];\n \n // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of\n // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key\n // means end of sequence (needed when one sequence is a strict subsequence of another).\n // Objects are kept separately from encodeTable to increase performance.\n this.encodeTableSeq = [];\n\n // Some chars can be decoded, but need not be encoded.\n var skipEncodeChars = {};\n if (codecOptions.encodeSkipVals)\n for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {\n var val = codecOptions.encodeSkipVals[i];\n if (typeof val === 'number')\n skipEncodeChars[val] = true;\n else\n for (var j = val.from; j <= val.to; j++)\n skipEncodeChars[j] = true;\n }\n \n // Use decode trie to recursively fill out encode tables.\n this._fillEncodeTable(0, 0, skipEncodeChars);\n\n // Add more encoding pairs when needed.\n if (codecOptions.encodeAdd) {\n for (var uChar in codecOptions.encodeAdd)\n if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))\n this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);\n }\n\n this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];\n if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];\n if (this.defCharSB === UNASSIGNED) this.defCharSB = \"?\".charCodeAt(0);\n}\n\nDBCSCodec.prototype.encoder = DBCSEncoder;\nDBCSCodec.prototype.decoder = DBCSDecoder;\n\n// Decoder helpers\nDBCSCodec.prototype._getDecodeTrieNode = function(addr) {\n var bytes = [];\n for (; addr > 0; addr >>>= 8)\n bytes.push(addr & 0xFF);\n if (bytes.length == 0)\n bytes.push(0);\n\n var node = this.decodeTables[0];\n for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.\n var val = node[bytes[i]];\n\n if (val == UNASSIGNED) { // Create new node.\n node[bytes[i]] = NODE_START - this.decodeTables.length;\n this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));\n }\n else if (val <= NODE_START) { // Existing node.\n node = this.decodeTables[NODE_START - val];\n }\n else\n throw new Error(\"Overwrite byte in \" + this.encodingName + \", addr: \" + addr.toString(16));\n }\n return node;\n}\n\n\nDBCSCodec.prototype._addDecodeChunk = function(chunk) {\n // First element of chunk is the hex mbcs code where we start.\n var curAddr = parseInt(chunk[0], 16);\n\n // Choose the decoding node where we'll write our chars.\n var writeTable = this._getDecodeTrieNode(curAddr);\n curAddr = curAddr & 0xFF;\n\n // Write all other elements of the chunk to the table.\n for (var k = 1; k < chunk.length; k++) {\n var part = chunk[k];\n if (typeof part === \"string\") { // String, write as-is.\n for (var l = 0; l < part.length;) {\n var code = part.charCodeAt(l++);\n if (0xD800 <= code && code < 0xDC00) { // Decode surrogate\n var codeTrail = part.charCodeAt(l++);\n if (0xDC00 <= codeTrail && codeTrail < 0xE000)\n writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);\n else\n throw new Error(\"Incorrect surrogate pair in \" + this.encodingName + \" at chunk \" + chunk[0]);\n }\n else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)\n var len = 0xFFF - code + 2;\n var seq = [];\n for (var m = 0; m < len; m++)\n seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.\n\n writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;\n this.decodeTableSeq.push(seq);\n }\n else\n writeTable[curAddr++] = code; // Basic char\n }\n } \n else if (typeof part === \"number\") { // Integer, meaning increasing sequence starting with prev character.\n var charCode = writeTable[curAddr - 1] + 1;\n for (var l = 0; l < part; l++)\n writeTable[curAddr++] = charCode++;\n }\n else\n throw new Error(\"Incorrect type '\" + typeof part + \"' given in \" + this.encodingName + \" at chunk \" + chunk[0]);\n }\n if (curAddr > 0xFF)\n throw new Error(\"Incorrect chunk in \" + this.encodingName + \" at addr \" + chunk[0] + \": too long\" + curAddr);\n}\n\n// Encoder helpers\nDBCSCodec.prototype._getEncodeBucket = function(uCode) {\n var high = uCode >> 8; // This could be > 0xFF because of astral characters.\n if (this.encodeTable[high] === undefined)\n this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.\n return this.encodeTable[high];\n}\n\nDBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {\n var bucket = this._getEncodeBucket(uCode);\n var low = uCode & 0xFF;\n if (bucket[low] <= SEQ_START)\n this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.\n else if (bucket[low] == UNASSIGNED)\n bucket[low] = dbcsCode;\n}\n\nDBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {\n \n // Get the root of character tree according to first character of the sequence.\n var uCode = seq[0];\n var bucket = this._getEncodeBucket(uCode);\n var low = uCode & 0xFF;\n\n var node;\n if (bucket[low] <= SEQ_START) {\n // There's already a sequence with - use it.\n node = this.encodeTableSeq[SEQ_START-bucket[low]];\n }\n else {\n // There was no sequence object - allocate a new one.\n node = {};\n if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.\n bucket[low] = SEQ_START - this.encodeTableSeq.length;\n this.encodeTableSeq.push(node);\n }\n\n // Traverse the character tree, allocating new nodes as needed.\n for (var j = 1; j < seq.length-1; j++) {\n var oldVal = node[uCode];\n if (typeof oldVal === 'object')\n node = oldVal;\n else {\n node = node[uCode] = {}\n if (oldVal !== undefined)\n node[DEF_CHAR] = oldVal\n }\n }\n\n // Set the leaf to given dbcsCode.\n uCode = seq[seq.length-1];\n node[uCode] = dbcsCode;\n}\n\nDBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {\n var node = this.decodeTables[nodeIdx];\n var hasValues = false;\n var subNodeEmpty = {};\n for (var i = 0; i < 0x100; i++) {\n var uCode = node[i];\n var mbCode = prefix + i;\n if (skipEncodeChars[mbCode])\n continue;\n\n if (uCode >= 0) {\n this._setEncodeChar(uCode, mbCode);\n hasValues = true;\n } else if (uCode <= NODE_START) {\n var subNodeIdx = NODE_START - uCode;\n if (!subNodeEmpty[subNodeIdx]) { // Skip empty subtrees (they are too large in gb18030).\n var newPrefix = (mbCode << 8) >>> 0; // NOTE: '>>> 0' keeps 32-bit num positive.\n if (this._fillEncodeTable(subNodeIdx, newPrefix, skipEncodeChars))\n hasValues = true;\n else\n subNodeEmpty[subNodeIdx] = true;\n }\n } else if (uCode <= SEQ_START) {\n this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);\n hasValues = true;\n }\n }\n return hasValues;\n}\n\n\n\n// == Encoder ==================================================================\n\nfunction DBCSEncoder(options, codec) {\n // Encoder state\n this.leadSurrogate = -1;\n this.seqObj = undefined;\n \n // Static data\n this.encodeTable = codec.encodeTable;\n this.encodeTableSeq = codec.encodeTableSeq;\n this.defaultCharSingleByte = codec.defCharSB;\n this.gb18030 = codec.gb18030;\n}\n\nDBCSEncoder.prototype.write = function(str) {\n var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)),\n leadSurrogate = this.leadSurrogate,\n seqObj = this.seqObj, nextChar = -1,\n i = 0, j = 0;\n\n while (true) {\n // 0. Get next character.\n if (nextChar === -1) {\n if (i == str.length) break;\n var uCode = str.charCodeAt(i++);\n }\n else {\n var uCode = nextChar;\n nextChar = -1; \n }\n\n // 1. Handle surrogates.\n if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.\n if (uCode < 0xDC00) { // We've got lead surrogate.\n if (leadSurrogate === -1) {\n leadSurrogate = uCode;\n continue;\n } else {\n leadSurrogate = uCode;\n // Double lead surrogate found.\n uCode = UNASSIGNED;\n }\n } else { // We've got trail surrogate.\n if (leadSurrogate !== -1) {\n uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);\n leadSurrogate = -1;\n } else {\n // Incomplete surrogate pair - only trail surrogate found.\n uCode = UNASSIGNED;\n }\n \n }\n }\n else if (leadSurrogate !== -1) {\n // Incomplete surrogate pair - only lead surrogate found.\n nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.\n leadSurrogate = -1;\n }\n\n // 2. Convert uCode character.\n var dbcsCode = UNASSIGNED;\n if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence\n var resCode = seqObj[uCode];\n if (typeof resCode === 'object') { // Sequence continues.\n seqObj = resCode;\n continue;\n\n } else if (typeof resCode == 'number') { // Sequence finished. Write it.\n dbcsCode = resCode;\n\n } else if (resCode == undefined) { // Current character is not part of the sequence.\n\n // Try default character for this sequence\n resCode = seqObj[DEF_CHAR];\n if (resCode !== undefined) {\n dbcsCode = resCode; // Found. Write it.\n nextChar = uCode; // Current character will be written too in the next iteration.\n\n } else {\n // TODO: What if we have no default? (resCode == undefined)\n // Then, we should write first char of the sequence as-is and try the rest recursively.\n // Didn't do it for now because no encoding has this situation yet.\n // Currently, just skip the sequence and write current char.\n }\n }\n seqObj = undefined;\n }\n else if (uCode >= 0) { // Regular character\n var subtable = this.encodeTable[uCode >> 8];\n if (subtable !== undefined)\n dbcsCode = subtable[uCode & 0xFF];\n \n if (dbcsCode <= SEQ_START) { // Sequence start\n seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];\n continue;\n }\n\n if (dbcsCode == UNASSIGNED && this.gb18030) {\n // Use GB18030 algorithm to find character(s) to write.\n var idx = findIdx(this.gb18030.uChars, uCode);\n if (idx != -1) {\n var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);\n newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;\n newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;\n newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;\n newBuf[j++] = 0x30 + dbcsCode;\n continue;\n }\n }\n }\n\n // 3. Write dbcsCode character.\n if (dbcsCode === UNASSIGNED)\n dbcsCode = this.defaultCharSingleByte;\n \n if (dbcsCode < 0x100) {\n newBuf[j++] = dbcsCode;\n }\n else if (dbcsCode < 0x10000) {\n newBuf[j++] = dbcsCode >> 8; // high byte\n newBuf[j++] = dbcsCode & 0xFF; // low byte\n }\n else if (dbcsCode < 0x1000000) {\n newBuf[j++] = dbcsCode >> 16;\n newBuf[j++] = (dbcsCode >> 8) & 0xFF;\n newBuf[j++] = dbcsCode & 0xFF;\n } else {\n newBuf[j++] = dbcsCode >>> 24;\n newBuf[j++] = (dbcsCode >>> 16) & 0xFF;\n newBuf[j++] = (dbcsCode >>> 8) & 0xFF;\n newBuf[j++] = dbcsCode & 0xFF;\n }\n }\n\n this.seqObj = seqObj;\n this.leadSurrogate = leadSurrogate;\n return newBuf.slice(0, j);\n}\n\nDBCSEncoder.prototype.end = function() {\n if (this.leadSurrogate === -1 && this.seqObj === undefined)\n return; // All clean. Most often case.\n\n var newBuf = Buffer.alloc(10), j = 0;\n\n if (this.seqObj) { // We're in the sequence.\n var dbcsCode = this.seqObj[DEF_CHAR];\n if (dbcsCode !== undefined) { // Write beginning of the sequence.\n if (dbcsCode < 0x100) {\n newBuf[j++] = dbcsCode;\n }\n else {\n newBuf[j++] = dbcsCode >> 8; // high byte\n newBuf[j++] = dbcsCode & 0xFF; // low byte\n }\n } else {\n // See todo above.\n }\n this.seqObj = undefined;\n }\n\n if (this.leadSurrogate !== -1) {\n // Incomplete surrogate pair - only lead surrogate found.\n newBuf[j++] = this.defaultCharSingleByte;\n this.leadSurrogate = -1;\n }\n \n return newBuf.slice(0, j);\n}\n\n// Export for testing\nDBCSEncoder.prototype.findIdx = findIdx;\n\n\n// == Decoder ==================================================================\n\nfunction DBCSDecoder(options, codec) {\n // Decoder state\n this.nodeIdx = 0;\n this.prevBytes = [];\n\n // Static data\n this.decodeTables = codec.decodeTables;\n this.decodeTableSeq = codec.decodeTableSeq;\n this.defaultCharUnicode = codec.defaultCharUnicode;\n this.gb18030 = codec.gb18030;\n}\n\nDBCSDecoder.prototype.write = function(buf) {\n var newBuf = Buffer.alloc(buf.length*2),\n nodeIdx = this.nodeIdx, \n prevBytes = this.prevBytes, prevOffset = this.prevBytes.length,\n seqStart = -this.prevBytes.length, // idx of the start of current parsed sequence.\n uCode;\n\n for (var i = 0, j = 0; i < buf.length; i++) {\n var curByte = (i >= 0) ? buf[i] : prevBytes[i + prevOffset];\n\n // Lookup in current trie node.\n var uCode = this.decodeTables[nodeIdx][curByte];\n\n if (uCode >= 0) { \n // Normal character, just use it.\n }\n else if (uCode === UNASSIGNED) { // Unknown char.\n // TODO: Callback with seq.\n uCode = this.defaultCharUnicode.charCodeAt(0);\n i = seqStart; // Skip one byte ('i' will be incremented by the for loop) and try to parse again.\n }\n else if (uCode === GB18030_CODE) {\n if (i >= 3) {\n var ptr = (buf[i-3]-0x81)*12600 + (buf[i-2]-0x30)*1260 + (buf[i-1]-0x81)*10 + (curByte-0x30);\n } else {\n var ptr = (prevBytes[i-3+prevOffset]-0x81)*12600 + \n (((i-2 >= 0) ? buf[i-2] : prevBytes[i-2+prevOffset])-0x30)*1260 + \n (((i-1 >= 0) ? buf[i-1] : prevBytes[i-1+prevOffset])-0x81)*10 + \n (curByte-0x30);\n }\n var idx = findIdx(this.gb18030.gbChars, ptr);\n uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];\n }\n else if (uCode <= NODE_START) { // Go to next trie node.\n nodeIdx = NODE_START - uCode;\n continue;\n }\n else if (uCode <= SEQ_START) { // Output a sequence of chars.\n var seq = this.decodeTableSeq[SEQ_START - uCode];\n for (var k = 0; k < seq.length - 1; k++) {\n uCode = seq[k];\n newBuf[j++] = uCode & 0xFF;\n newBuf[j++] = uCode >> 8;\n }\n uCode = seq[seq.length-1];\n }\n else\n throw new Error(\"iconv-lite internal error: invalid decoding table value \" + uCode + \" at \" + nodeIdx + \"/\" + curByte);\n\n // Write the character to buffer, handling higher planes using surrogate pair.\n if (uCode >= 0x10000) { \n uCode -= 0x10000;\n var uCodeLead = 0xD800 | (uCode >> 10);\n newBuf[j++] = uCodeLead & 0xFF;\n newBuf[j++] = uCodeLead >> 8;\n\n uCode = 0xDC00 | (uCode & 0x3FF);\n }\n newBuf[j++] = uCode & 0xFF;\n newBuf[j++] = uCode >> 8;\n\n // Reset trie node.\n nodeIdx = 0; seqStart = i+1;\n }\n\n this.nodeIdx = nodeIdx;\n this.prevBytes = (seqStart >= 0)\n ? Array.prototype.slice.call(buf, seqStart)\n : prevBytes.slice(seqStart + prevOffset).concat(Array.prototype.slice.call(buf));\n\n return newBuf.slice(0, j).toString('ucs2');\n}\n\nDBCSDecoder.prototype.end = function() {\n var ret = '';\n\n // Try to parse all remaining chars.\n while (this.prevBytes.length > 0) {\n // Skip 1 character in the buffer.\n ret += this.defaultCharUnicode;\n var bytesArr = this.prevBytes.slice(1);\n\n // Parse remaining as usual.\n this.prevBytes = [];\n this.nodeIdx = 0;\n if (bytesArr.length > 0)\n ret += this.write(bytesArr);\n }\n\n this.prevBytes = [];\n this.nodeIdx = 0;\n return ret;\n}\n\n// Binary search for GB18030. Returns largest i such that table[i] <= val.\nfunction findIdx(table, val) {\n if (table[0] > val)\n return -1;\n\n var l = 0, r = table.length;\n while (l < r-1) { // always table[l] <= val < table[r]\n var mid = l + ((r-l+1) >> 1);\n if (table[mid] <= val)\n l = mid;\n else\n r = mid;\n }\n return l;\n}\n\n","\"use strict\";\n\n// Description of supported double byte encodings and aliases.\n// Tables are not require()-d until they are needed to speed up library load.\n// require()-s are direct to support Browserify.\n\nmodule.exports = {\n \n // == Japanese/ShiftJIS ====================================================\n // All japanese encodings are based on JIS X set of standards:\n // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.\n // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. \n // Has several variations in 1978, 1983, 1990 and 1997.\n // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.\n // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.\n // 2 planes, first is superset of 0208, second - revised 0212.\n // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)\n\n // Byte encodings are:\n // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte\n // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.\n // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.\n // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes.\n // 0x00-0x7F - lower part of 0201\n // 0x8E, 0xA1-0xDF - upper part of 0201\n // (0xA1-0xFE)x2 - 0208 plane (94x94).\n // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).\n // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.\n // Used as-is in ISO2022 family.\n // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, \n // 0201-1976 Roman, 0208-1978, 0208-1983.\n // * ISO2022-JP-1: Adds esc seq for 0212-1990.\n // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.\n // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.\n // * ISO2022-JP-2004: Adds 0213-2004 Plane 1.\n //\n // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.\n //\n // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html\n\n 'shiftjis': {\n type: '_dbcs',\n table: function() { return require('./tables/shiftjis.json') },\n encodeAdd: {'\\u00a5': 0x5C, '\\u203E': 0x7E},\n encodeSkipVals: [{from: 0xED40, to: 0xF940}],\n },\n 'csshiftjis': 'shiftjis',\n 'mskanji': 'shiftjis',\n 'sjis': 'shiftjis',\n 'windows31j': 'shiftjis',\n 'ms31j': 'shiftjis',\n 'xsjis': 'shiftjis',\n 'windows932': 'shiftjis',\n 'ms932': 'shiftjis',\n '932': 'shiftjis',\n 'cp932': 'shiftjis',\n\n 'eucjp': {\n type: '_dbcs',\n table: function() { return require('./tables/eucjp.json') },\n encodeAdd: {'\\u00a5': 0x5C, '\\u203E': 0x7E},\n },\n\n // TODO: KDDI extension to Shift_JIS\n // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.\n // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.\n\n\n // == Chinese/GBK ==========================================================\n // http://en.wikipedia.org/wiki/GBK\n // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder\n\n // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936\n 'gb2312': 'cp936',\n 'gb231280': 'cp936',\n 'gb23121980': 'cp936',\n 'csgb2312': 'cp936',\n 'csiso58gb231280': 'cp936',\n 'euccn': 'cp936',\n\n // Microsoft's CP936 is a subset and approximation of GBK.\n 'windows936': 'cp936',\n 'ms936': 'cp936',\n '936': 'cp936',\n 'cp936': {\n type: '_dbcs',\n table: function() { return require('./tables/cp936.json') },\n },\n\n // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.\n 'gbk': {\n type: '_dbcs',\n table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },\n },\n 'xgbk': 'gbk',\n 'isoir58': 'gbk',\n\n // GB18030 is an algorithmic extension of GBK.\n // Main source: https://www.w3.org/TR/encoding/#gbk-encoder\n // http://icu-project.org/docs/papers/gb18030.html\n // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml\n // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0\n 'gb18030': {\n type: '_dbcs',\n table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },\n gb18030: function() { return require('./tables/gb18030-ranges.json') },\n encodeSkipVals: [0x80],\n encodeAdd: {'€': 0xA2E3},\n },\n\n 'chinese': 'gb18030',\n\n\n // == Korean ===============================================================\n // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.\n 'windows949': 'cp949',\n 'ms949': 'cp949',\n '949': 'cp949',\n 'cp949': {\n type: '_dbcs',\n table: function() { return require('./tables/cp949.json') },\n },\n\n 'cseuckr': 'cp949',\n 'csksc56011987': 'cp949',\n 'euckr': 'cp949',\n 'isoir149': 'cp949',\n 'korean': 'cp949',\n 'ksc56011987': 'cp949',\n 'ksc56011989': 'cp949',\n 'ksc5601': 'cp949',\n\n\n // == Big5/Taiwan/Hong Kong ================================================\n // There are lots of tables for Big5 and cp950. Please see the following links for history:\n // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html\n // Variations, in roughly number of defined chars:\n // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT\n // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/\n // * Big5-2003 (Taiwan standard) almost superset of cp950.\n // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.\n // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. \n // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.\n // Plus, it has 4 combining sequences.\n // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299\n // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.\n // Implementations are not consistent within browsers; sometimes labeled as just big5.\n // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.\n // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31\n // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.\n // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt\n // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt\n // \n // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder\n // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.\n\n 'windows950': 'cp950',\n 'ms950': 'cp950',\n '950': 'cp950',\n 'cp950': {\n type: '_dbcs',\n table: function() { return require('./tables/cp950.json') },\n },\n\n // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.\n 'big5': 'big5hkscs',\n 'big5hkscs': {\n type: '_dbcs',\n table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) },\n encodeSkipVals: [\n // Although Encoding Standard says we should avoid encoding to HKSCS area (See Step 1 of\n // https://encoding.spec.whatwg.org/#index-big5-pointer), we still do it to increase compatibility with ICU.\n // But if a single unicode point can be encoded both as HKSCS and regular Big5, we prefer the latter.\n 0x8e69, 0x8e6f, 0x8e7e, 0x8eab, 0x8eb4, 0x8ecd, 0x8ed0, 0x8f57, 0x8f69, 0x8f6e, 0x8fcb, 0x8ffe,\n 0x906d, 0x907a, 0x90c4, 0x90dc, 0x90f1, 0x91bf, 0x92af, 0x92b0, 0x92b1, 0x92b2, 0x92d1, 0x9447, 0x94ca,\n 0x95d9, 0x96fc, 0x9975, 0x9b76, 0x9b78, 0x9b7b, 0x9bc6, 0x9bde, 0x9bec, 0x9bf6, 0x9c42, 0x9c53, 0x9c62,\n 0x9c68, 0x9c6b, 0x9c77, 0x9cbc, 0x9cbd, 0x9cd0, 0x9d57, 0x9d5a, 0x9dc4, 0x9def, 0x9dfb, 0x9ea9, 0x9eef,\n 0x9efd, 0x9f60, 0x9fcb, 0xa077, 0xa0dc, 0xa0df, 0x8fcc, 0x92c8, 0x9644, 0x96ed,\n\n // Step 2 of https://encoding.spec.whatwg.org/#index-big5-pointer: Use last pointer for U+2550, U+255E, U+2561, U+256A, U+5341, or U+5345\n 0xa2a4, 0xa2a5, 0xa2a7, 0xa2a6, 0xa2cc, 0xa2ce,\n ],\n },\n\n 'cnbig5': 'big5hkscs',\n 'csbig5': 'big5hkscs',\n 'xxbig5': 'big5hkscs',\n};\n","\"use strict\";\n\nvar Buffer = require(\"safer-buffer\").Buffer;\n\n// NOTE: Due to 'stream' module being pretty large (~100Kb, significant in browser environments), \n// we opt to dependency-inject it instead of creating a hard dependency.\nmodule.exports = function(stream_module) {\n var Transform = stream_module.Transform;\n\n // == Encoder stream =======================================================\n\n function IconvLiteEncoderStream(conv, options) {\n this.conv = conv;\n options = options || {};\n options.decodeStrings = false; // We accept only strings, so we don't need to decode them.\n Transform.call(this, options);\n }\n\n IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {\n constructor: { value: IconvLiteEncoderStream }\n });\n\n IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {\n if (typeof chunk != 'string')\n return done(new Error(\"Iconv encoding stream needs strings as its input.\"));\n try {\n var res = this.conv.write(chunk);\n if (res && res.length) this.push(res);\n done();\n }\n catch (e) {\n done(e);\n }\n }\n\n IconvLiteEncoderStream.prototype._flush = function(done) {\n try {\n var res = this.conv.end();\n if (res && res.length) this.push(res);\n done();\n }\n catch (e) {\n done(e);\n }\n }\n\n IconvLiteEncoderStream.prototype.collect = function(cb) {\n var chunks = [];\n this.on('error', cb);\n this.on('data', function(chunk) { chunks.push(chunk); });\n this.on('end', function() {\n cb(null, Buffer.concat(chunks));\n });\n return this;\n }\n\n\n // == Decoder stream =======================================================\n\n function IconvLiteDecoderStream(conv, options) {\n this.conv = conv;\n options = options || {};\n options.encoding = this.encoding = 'utf8'; // We output strings.\n Transform.call(this, options);\n }\n\n IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {\n constructor: { value: IconvLiteDecoderStream }\n });\n\n IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {\n if (!Buffer.isBuffer(chunk) && !(chunk instanceof Uint8Array))\n return done(new Error(\"Iconv decoding stream needs buffers as its input.\"));\n try {\n var res = this.conv.write(chunk);\n if (res && res.length) this.push(res, this.encoding);\n done();\n }\n catch (e) {\n done(e);\n }\n }\n\n IconvLiteDecoderStream.prototype._flush = function(done) {\n try {\n var res = this.conv.end();\n if (res && res.length) this.push(res, this.encoding); \n done();\n }\n catch (e) {\n done(e);\n }\n }\n\n IconvLiteDecoderStream.prototype.collect = function(cb) {\n var res = '';\n this.on('error', cb);\n this.on('data', function(chunk) { res += chunk; });\n this.on('end', function() {\n cb(null, res);\n });\n return this;\n }\n\n return {\n IconvLiteEncoderStream: IconvLiteEncoderStream,\n IconvLiteDecoderStream: IconvLiteDecoderStream,\n };\n};\n","'use strict';\n\n// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchRequest\n\nconst Packet = require('../packets/packet');\n\nclass AuthSwitchRequest {\n constructor(opts) {\n this.pluginName = opts.pluginName;\n this.pluginData = opts.pluginData;\n }\n\n toPacket() {\n const length = 6 + this.pluginName.length + this.pluginData.length;\n const buffer = Buffer.allocUnsafe(length);\n const packet = new Packet(0, buffer, 0, length);\n packet.offset = 4;\n packet.writeInt8(0xfe);\n // TODO: use server encoding\n packet.writeNullTerminatedString(this.pluginName, 'cesu8');\n packet.writeBuffer(this.pluginData);\n return packet;\n }\n\n static fromPacket(packet) {\n packet.readInt8(); // marker\n // assert marker == 0xfe?\n // TODO: use server encoding\n const name = packet.readNullTerminatedString('cesu8');\n const data = packet.readBuffer();\n return new AuthSwitchRequest({\n pluginName: name,\n pluginData: data\n });\n }\n}\n\nmodule.exports = AuthSwitchRequest;\n","'use strict';\n\n// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchRequest\n\nconst Packet = require('../packets/packet');\n\nclass AuthSwitchRequestMoreData {\n constructor(data) {\n this.data = data;\n }\n\n toPacket() {\n const length = 5 + this.data.length;\n const buffer = Buffer.allocUnsafe(length);\n const packet = new Packet(0, buffer, 0, length);\n packet.offset = 4;\n packet.writeInt8(0x01);\n packet.writeBuffer(this.data);\n return packet;\n }\n\n static fromPacket(packet) {\n packet.readInt8(); // marker\n const data = packet.readBuffer();\n return new AuthSwitchRequestMoreData(data);\n }\n\n static verifyMarker(packet) {\n return packet.peekByte() === 0x01;\n }\n}\n\nmodule.exports = AuthSwitchRequestMoreData;\n","'use strict';\n\n// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchRequest\n\nconst Packet = require('../packets/packet');\n\nclass AuthSwitchResponse {\n constructor(data) {\n if (!Buffer.isBuffer(data)) {\n data = Buffer.from(data);\n }\n this.data = data;\n }\n\n toPacket() {\n const length = 4 + this.data.length;\n const buffer = Buffer.allocUnsafe(length);\n const packet = new Packet(0, buffer, 0, length);\n packet.offset = 4;\n packet.writeBuffer(this.data);\n return packet;\n }\n\n static fromPacket(packet) {\n const data = packet.readBuffer();\n return new AuthSwitchResponse(data);\n }\n}\n\nmodule.exports = AuthSwitchResponse;\n","'use strict';\n\nconst Types = require('../constants/types');\nconst Packet = require('../packets/packet');\n\nconst binaryReader = new Array(256);\n\nclass BinaryRow {\n constructor(columns) {\n this.columns = columns || [];\n }\n\n toPacket() {\n throw new Error('Not implemented');\n }\n\n // TODO: complete list of types...\n static fromPacket(fields, packet) {\n const columns = new Array(fields.length);\n packet.readInt8(); // TODO check it's 0\n const nullBitmapLength = Math.floor((fields.length + 7 + 2) / 8);\n // TODO: read and interpret null bitmap\n packet.skip(nullBitmapLength);\n for (let i = 0; i < columns.length; ++i) {\n columns[i] = binaryReader[fields[i].columnType].apply(packet);\n }\n return new BinaryRow(columns);\n }\n}\n\n// TODO: replace with constants.MYSQL_TYPE_*\nbinaryReader[Types.DECIMAL] = Packet.prototype.readLengthCodedString;\nbinaryReader[1] = Packet.prototype.readInt8; // tiny\nbinaryReader[2] = Packet.prototype.readInt16; // short\nbinaryReader[3] = Packet.prototype.readInt32; // long\nbinaryReader[4] = Packet.prototype.readFloat; // float\nbinaryReader[5] = Packet.prototype.readDouble; // double\nbinaryReader[6] = Packet.prototype.assertInvalid; // null, should be skipped vie null bitmap\nbinaryReader[7] = Packet.prototype.readTimestamp; // timestamp, http://dev.mysql.com/doc/internals/en/prepared-statements.html#packet-ProtocolBinary::MYSQL_TYPE_TIMESTAMP\nbinaryReader[8] = Packet.prototype.readInt64; // long long\nbinaryReader[9] = Packet.prototype.readInt32; // int24\nbinaryReader[10] = Packet.prototype.readTimestamp; // date\nbinaryReader[11] = Packet.prototype.readTime; // time, http://dev.mysql.com/doc/internals/en/prepared-statements.html#packet-ProtocolBinary::MYSQL_TYPE_TIME\nbinaryReader[12] = Packet.prototype.readDateTime; // datetime, http://dev.mysql.com/doc/internals/en/prepared-statements.html#packet-ProtocolBinary::MYSQL_TYPE_DATETIME\nbinaryReader[13] = Packet.prototype.readInt16; // year\nbinaryReader[Types.VAR_STRING] = Packet.prototype.readLengthCodedString; // var string\n\nmodule.exports = BinaryRow;\n","'use strict';\n\n// http://dev.mysql.com/doc/internals/en/com-binlog-dump.html#packet-COM_BINLOG_DUMP\n\nconst Packet = require('../packets/packet');\nconst CommandCodes = require('../constants/commands');\n\n// TODO: add flag to constants\n// 0x01 - BINLOG_DUMP_NON_BLOCK\n// send EOF instead of blocking\nclass BinlogDump {\n constructor(opts) {\n this.binlogPos = opts.binlogPos || 0;\n this.serverId = opts.serverId || 0;\n this.flags = opts.flags || 0;\n this.filename = opts.filename || '';\n }\n\n toPacket() {\n const length = 15 + Buffer.byteLength(this.filename, 'utf8'); // TODO: should be ascii?\n const buffer = Buffer.allocUnsafe(length);\n const packet = new Packet(0, buffer, 0, length);\n packet.offset = 4;\n packet.writeInt8(CommandCodes.BINLOG_DUMP);\n packet.writeInt32(this.binlogPos);\n packet.writeInt16(this.flags);\n packet.writeInt32(this.serverId);\n packet.writeString(this.filename);\n return packet;\n }\n}\n\nmodule.exports = BinlogDump;\n","'use strict';\n\nconst CommandCode = require('../constants/commands.js');\nconst ClientConstants = require('../constants/client.js');\nconst Packet = require('../packets/packet.js');\nconst auth41 = require('../auth_41.js');\nconst CharsetToEncoding = require('../constants/charset_encodings.js');\n\n// https://dev.mysql.com/doc/internals/en/com-change-user.html#packet-COM_CHANGE_USER\nclass ChangeUser {\n constructor(opts) {\n this.flags = opts.flags;\n this.user = opts.user || '';\n this.database = opts.database || '';\n this.password = opts.password || '';\n this.passwordSha1 = opts.passwordSha1;\n this.authPluginData1 = opts.authPluginData1;\n this.authPluginData2 = opts.authPluginData2;\n this.connectAttributes = opts.connectAttrinutes || {};\n let authToken;\n if (this.passwordSha1) {\n authToken = auth41.calculateTokenFromPasswordSha(\n this.passwordSha1,\n this.authPluginData1,\n this.authPluginData2\n );\n } else {\n authToken = auth41.calculateToken(\n this.password,\n this.authPluginData1,\n this.authPluginData2\n );\n }\n this.authToken = authToken;\n this.charsetNumber = opts.charsetNumber;\n }\n\n // TODO\n // ChangeUser.fromPacket = function(packet)\n // };\n serializeToBuffer(buffer) {\n const isSet = flag => this.flags & ClientConstants[flag];\n const packet = new Packet(0, buffer, 0, buffer.length);\n packet.offset = 4;\n const encoding = CharsetToEncoding[this.charsetNumber];\n packet.writeInt8(CommandCode.CHANGE_USER);\n packet.writeNullTerminatedString(this.user, encoding);\n if (isSet('SECURE_CONNECTION')) {\n packet.writeInt8(this.authToken.length);\n packet.writeBuffer(this.authToken);\n } else {\n packet.writeBuffer(this.authToken);\n packet.writeInt8(0);\n }\n packet.writeNullTerminatedString(this.database, encoding);\n packet.writeInt16(this.charsetNumber);\n if (isSet('PLUGIN_AUTH')) {\n // TODO: read this from parameters\n packet.writeNullTerminatedString('mysql_native_password', 'latin1');\n }\n if (isSet('CONNECT_ATTRS')) {\n const connectAttributes = this.connectAttributes;\n const attrNames = Object.keys(connectAttributes);\n let keysLength = 0;\n for (let k = 0; k < attrNames.length; ++k) {\n keysLength += Packet.lengthCodedStringLength(attrNames[k], encoding);\n keysLength += Packet.lengthCodedStringLength(\n connectAttributes[attrNames[k]],\n encoding\n );\n }\n packet.writeLengthCodedNumber(keysLength);\n for (let k = 0; k < attrNames.length; ++k) {\n packet.writeLengthCodedString(attrNames[k], encoding);\n packet.writeLengthCodedString(\n connectAttributes[attrNames[k]],\n encoding\n );\n }\n }\n return packet;\n }\n\n toPacket() {\n if (typeof this.user !== 'string') {\n throw new Error('\"user\" connection config property must be a string');\n }\n if (typeof this.database !== 'string') {\n throw new Error('\"database\" connection config property must be a string');\n }\n // dry run: calculate resulting packet length\n const p = this.serializeToBuffer(Packet.MockBuffer());\n return this.serializeToBuffer(Buffer.allocUnsafe(p.offset));\n }\n}\n\nmodule.exports = ChangeUser;\n","'use strict';\n\nconst Packet = require('../packets/packet');\nconst CommandCodes = require('../constants/commands');\n\nclass CloseStatement {\n constructor(id) {\n this.id = id;\n }\n\n // note: no response sent back\n toPacket() {\n const packet = new Packet(0, Buffer.allocUnsafe(9), 0, 9);\n packet.offset = 4;\n packet.writeInt8(CommandCodes.STMT_CLOSE);\n packet.writeInt32(this.id);\n return packet;\n }\n}\n\nmodule.exports = CloseStatement;\n","'use strict';\n\nconst Packet = require('../packets/packet');\nconst StringParser = require('../parsers/string');\nconst CharsetToEncoding = require('../constants/charset_encodings.js');\n\nconst fields = ['catalog', 'schema', 'table', 'orgTable', 'name', 'orgName'];\n\n// creating JS string is relatively expensive (compared to\n// reading few bytes from buffer) because all string properties\n// except for name are unlikely to be used we postpone\n// string conversion until property access\n//\n// TODO: watch for integration benchmarks (one with real network buffer)\n// there could be bad side effect as keeping reference to a buffer makes it\n// sit in the memory longer (usually until final .query() callback)\n// Latest v8 perform much better in regard to bufferer -> string conversion,\n// at some point of time this optimisation might become unnecessary\n// see https://github.com/sidorares/node-mysql2/pull/137\n//\nclass ColumnDefinition {\n constructor(packet, clientEncoding) {\n this._buf = packet.buffer;\n this._clientEncoding = clientEncoding;\n this._catalogLength = packet.readLengthCodedNumber();\n this._catalogStart = packet.offset;\n packet.offset += this._catalogLength;\n this._schemaLength = packet.readLengthCodedNumber();\n this._schemaStart = packet.offset;\n packet.offset += this._schemaLength;\n this._tableLength = packet.readLengthCodedNumber();\n this._tableStart = packet.offset;\n packet.offset += this._tableLength;\n this._orgTableLength = packet.readLengthCodedNumber();\n this._orgTableStart = packet.offset;\n packet.offset += this._orgTableLength;\n // name is always used, don't make it lazy\n const _nameLength = packet.readLengthCodedNumber();\n const _nameStart = packet.offset;\n packet.offset += _nameLength;\n this._orgNameLength = packet.readLengthCodedNumber();\n this._orgNameStart = packet.offset;\n packet.offset += this._orgNameLength;\n packet.skip(1); // length of the following fields (always 0x0c)\n this.characterSet = packet.readInt16();\n this.encoding = CharsetToEncoding[this.characterSet];\n this.name = StringParser.decode(\n this._buf,\n this.encoding === 'binary' ? this._clientEncoding : this.encoding,\n _nameStart, \n _nameStart + _nameLength\n );\n this.columnLength = packet.readInt32();\n this.columnType = packet.readInt8();\n this.flags = packet.readInt16();\n this.decimals = packet.readInt8();\n }\n\n inspect() {\n return {\n catalog: this.catalog,\n schema: this.schema,\n name: this.name,\n orgName: this.orgName,\n table: this.table,\n orgTable: this.orgTable,\n characterSet: this.characterSet,\n columnLength: this.columnLength,\n columnType: this.columnType,\n flags: this.flags,\n decimals: this.decimals\n };\n }\n\n static toPacket(column, sequenceId) {\n let length = 17; // = 4 padding + 1 + 12 for the rest\n fields.forEach(field => {\n length += Packet.lengthCodedStringLength(\n column[field],\n CharsetToEncoding[column.characterSet]\n );\n });\n const buffer = Buffer.allocUnsafe(length);\n\n const packet = new Packet(sequenceId, buffer, 0, length);\n function writeField(name) {\n packet.writeLengthCodedString(\n column[name],\n CharsetToEncoding[column.characterSet]\n );\n }\n packet.offset = 4;\n fields.forEach(writeField);\n packet.writeInt8(0x0c);\n packet.writeInt16(column.characterSet);\n packet.writeInt32(column.columnLength);\n packet.writeInt8(column.columnType);\n packet.writeInt16(column.flags);\n packet.writeInt8(column.decimals);\n packet.writeInt16(0); // filler\n return packet;\n }\n\n // node-mysql compatibility: alias \"db\" to \"schema\"\n get db() {\n return this.schema;\n }\n}\n\nconst addString = function(name) {\n Object.defineProperty(ColumnDefinition.prototype, name, {\n get: function() {\n const start = this[`_${name}Start`];\n const end = start + this[`_${name}Length`];\n const val = StringParser.decode(\n this._buf,\n this.encoding === 'binary' ? this._clientEncoding : this.encoding,\n start, \n end\n );\n \n Object.defineProperty(this, name, {\n value: val,\n writable: false,\n configurable: false,\n enumerable: false\n });\n\n return val;\n }\n });\n};\n\naddString('catalog');\naddString('schema');\naddString('table');\naddString('orgTable');\naddString('orgName');\n\nmodule.exports = ColumnDefinition;\n","'use strict';\n\nconst CursorType = require('../constants/cursor');\nconst CommandCodes = require('../constants/commands');\nconst Types = require('../constants/types');\nconst Packet = require('../packets/packet');\nconst CharsetToEncoding = require('../constants/charset_encodings.js');\n\nfunction isJSON(value) {\n return (\n Array.isArray(value) ||\n value.constructor === Object ||\n (typeof value.toJSON === 'function' && !Buffer.isBuffer(value))\n );\n}\n\n/**\n * Converts a value to an object describing type, String/Buffer representation and length\n * @param {*} value\n */\nfunction toParameter(value, encoding, timezone) {\n let type = Types.VAR_STRING;\n let length;\n let writer = function(value) {\n // eslint-disable-next-line no-invalid-this\n return Packet.prototype.writeLengthCodedString.call(this, value, encoding);\n };\n if (value !== null) {\n switch (typeof value) {\n case 'undefined':\n throw new TypeError('Bind parameters must not contain undefined');\n\n case 'number':\n type = Types.DOUBLE;\n length = 8;\n writer = Packet.prototype.writeDouble;\n break;\n\n case 'boolean':\n value = value | 0;\n type = Types.TINY;\n length = 1;\n writer = Packet.prototype.writeInt8;\n break;\n\n case 'object':\n if (Object.prototype.toString.call(value) === '[object Date]') {\n type = Types.DATETIME;\n length = 12;\n writer = function(value) {\n // eslint-disable-next-line no-invalid-this\n return Packet.prototype.writeDate.call(this, value, timezone);\n };\n } else if (isJSON(value)) {\n value = JSON.stringify(value);\n type = Types.JSON;\n } else if (Buffer.isBuffer(value)) {\n length = Packet.lengthCodedNumberLength(value.length) + value.length;\n writer = Packet.prototype.writeLengthCodedBuffer;\n }\n break;\n\n default:\n value = value.toString();\n }\n } else {\n value = '';\n type = Types.NULL;\n }\n if (!length) {\n length = Packet.lengthCodedStringLength(value, encoding);\n }\n return { value, type, length, writer };\n}\n\nclass Execute {\n constructor(id, parameters, charsetNumber, timezone) {\n this.id = id;\n this.parameters = parameters;\n this.encoding = CharsetToEncoding[charsetNumber];\n this.timezone = timezone;\n }\n\n toPacket() {\n // TODO: don't try to calculate packet length in advance, allocate some big buffer in advance (header + 256 bytes?)\n // and copy + reallocate if not enough\n // 0 + 4 - length, seqId\n // 4 + 1 - COM_EXECUTE\n // 5 + 4 - stmtId\n // 9 + 1 - flags\n // 10 + 4 - iteration-count (always 1)\n let length = 14;\n let parameters;\n if (this.parameters && this.parameters.length > 0) {\n length += Math.floor((this.parameters.length + 7) / 8);\n length += 1; // new-params-bound-flag\n length += 2 * this.parameters.length; // type byte for each parameter if new-params-bound-flag is set\n parameters = this.parameters.map(value =>\n toParameter(value, this.encoding, this.timezone)\n );\n length += parameters.reduce(\n (accumulator, parameter) => accumulator + parameter.length,\n 0\n );\n }\n const buffer = Buffer.allocUnsafe(length);\n const packet = new Packet(0, buffer, 0, length);\n packet.offset = 4;\n packet.writeInt8(CommandCodes.STMT_EXECUTE);\n packet.writeInt32(this.id);\n packet.writeInt8(CursorType.NO_CURSOR); // flags\n packet.writeInt32(1); // iteration-count, always 1\n if (parameters) {\n let bitmap = 0;\n let bitValue = 1;\n parameters.forEach(parameter => {\n if (parameter.type === Types.NULL) {\n bitmap += bitValue;\n }\n bitValue *= 2;\n if (bitValue === 256) {\n packet.writeInt8(bitmap);\n bitmap = 0;\n bitValue = 1;\n }\n });\n if (bitValue !== 1) {\n packet.writeInt8(bitmap);\n }\n // TODO: explain meaning of the flag\n // afaik, if set n*2 bytes with type of parameter are sent before parameters\n // if not, previous execution types are used (TODO prooflink)\n packet.writeInt8(1); // new-params-bound-flag\n // Write parameter types\n parameters.forEach(parameter => {\n packet.writeInt8(parameter.type); // field type\n packet.writeInt8(0); // parameter flag\n });\n // Write parameter values\n parameters.forEach(parameter => {\n if (parameter.type !== Types.NULL) {\n parameter.writer.call(packet, parameter.value);\n }\n });\n }\n return packet;\n }\n}\n\nmodule.exports = Execute;\n","'use strict';\n\nmodule.exports = {\n NO_CURSOR: 0,\n READ_ONLY: 1,\n FOR_UPDATE: 2,\n SCROLLABLE: 3\n};\n","'use strict';\n\nconst Packet = require('../packets/packet');\nconst ClientConstants = require('../constants/client.js');\n\n// https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::Handshake\n\nclass Handshake {\n constructor(args) {\n this.protocolVersion = args.protocolVersion;\n this.serverVersion = args.serverVersion;\n this.capabilityFlags = args.capabilityFlags;\n this.connectionId = args.connectionId;\n this.authPluginData1 = args.authPluginData1;\n this.authPluginData2 = args.authPluginData2;\n this.characterSet = args.characterSet;\n this.statusFlags = args.statusFlags;\n this.autPluginName = args.autPluginName;\n }\n\n setScrambleData(cb) {\n require('crypto').randomBytes(20, (err, data) => {\n if (err) {\n cb(err);\n return;\n }\n this.authPluginData1 = data.slice(0, 8);\n this.authPluginData2 = data.slice(8, 20);\n cb();\n });\n }\n\n toPacket(sequenceId) {\n const length = 68 + Buffer.byteLength(this.serverVersion, 'utf8');\n const buffer = Buffer.alloc(length + 4, 0); // zero fill, 10 bytes filler later needs to contain zeros\n const packet = new Packet(sequenceId, buffer, 0, length + 4);\n packet.offset = 4;\n packet.writeInt8(this.protocolVersion);\n packet.writeString(this.serverVersion, 'cesu8');\n packet.writeInt8(0);\n packet.writeInt32(this.connectionId);\n packet.writeBuffer(this.authPluginData1);\n packet.writeInt8(0);\n const capabilityFlagsBuffer = Buffer.allocUnsafe(4);\n capabilityFlagsBuffer.writeUInt32LE(this.capabilityFlags, 0);\n packet.writeBuffer(capabilityFlagsBuffer.slice(0, 2));\n packet.writeInt8(this.characterSet);\n packet.writeInt16(this.statusFlags);\n packet.writeBuffer(capabilityFlagsBuffer.slice(2, 4));\n packet.writeInt8(21); // authPluginDataLength\n packet.skip(10);\n packet.writeBuffer(this.authPluginData2);\n packet.writeInt8(0);\n packet.writeString('mysql_native_password', 'latin1');\n packet.writeInt8(0);\n return packet;\n }\n\n static fromPacket(packet) {\n const args = {};\n args.protocolVersion = packet.readInt8();\n args.serverVersion = packet.readNullTerminatedString('cesu8');\n args.connectionId = packet.readInt32();\n args.authPluginData1 = packet.readBuffer(8);\n packet.skip(1);\n const capabilityFlagsBuffer = Buffer.allocUnsafe(4);\n capabilityFlagsBuffer[0] = packet.readInt8();\n capabilityFlagsBuffer[1] = packet.readInt8();\n if (packet.haveMoreData()) {\n args.characterSet = packet.readInt8();\n args.statusFlags = packet.readInt16();\n // upper 2 bytes\n capabilityFlagsBuffer[2] = packet.readInt8();\n capabilityFlagsBuffer[3] = packet.readInt8();\n args.capabilityFlags = capabilityFlagsBuffer.readUInt32LE(0);\n if (args.capabilityFlags & ClientConstants.PLUGIN_AUTH) {\n args.authPluginDataLength = packet.readInt8();\n } else {\n args.authPluginDataLength = 0;\n packet.skip(1);\n }\n packet.skip(10);\n } else {\n args.capabilityFlags = capabilityFlagsBuffer.readUInt16LE(0);\n }\n\n const isSecureConnection =\n args.capabilityFlags & ClientConstants.SECURE_CONNECTION;\n if (isSecureConnection) {\n const authPluginDataLength = args.authPluginDataLength;\n if (authPluginDataLength === 0) {\n // for Secure Password Authentication\n args.authPluginDataLength = 20;\n args.authPluginData2 = packet.readBuffer(12);\n packet.skip(1);\n } else {\n // length > 0\n // for Custom Auth Plugin (PLUGIN_AUTH)\n const len = Math.max(13, authPluginDataLength - 8);\n args.authPluginData2 = packet.readBuffer(len);\n }\n }\n\n if (args.capabilityFlags & ClientConstants.PLUGIN_AUTH) {\n args.autPluginName = packet.readNullTerminatedString('ascii');\n }\n\n return new Handshake(args);\n }\n}\n\nmodule.exports = Handshake;\n","'use strict';\n\nconst ClientConstants = require('../constants/client.js');\nconst CharsetToEncoding = require('../constants/charset_encodings.js');\nconst Packet = require('../packets/packet.js');\n\nconst auth41 = require('../auth_41.js');\n\nclass HandshakeResponse {\n constructor(handshake) {\n this.user = handshake.user || '';\n this.database = handshake.database || '';\n this.password = handshake.password || '';\n this.passwordSha1 = handshake.passwordSha1;\n this.authPluginData1 = handshake.authPluginData1;\n this.authPluginData2 = handshake.authPluginData2;\n this.compress = handshake.compress;\n this.clientFlags = handshake.flags;\n // TODO: pre-4.1 auth support\n let authToken;\n if (this.passwordSha1) {\n authToken = auth41.calculateTokenFromPasswordSha(\n this.passwordSha1,\n this.authPluginData1,\n this.authPluginData2\n );\n } else {\n authToken = auth41.calculateToken(\n this.password,\n this.authPluginData1,\n this.authPluginData2\n );\n }\n this.authToken = authToken;\n this.charsetNumber = handshake.charsetNumber;\n this.encoding = CharsetToEncoding[handshake.charsetNumber];\n this.connectAttributes = handshake.connectAttributes;\n }\n\n serializeResponse(buffer) {\n const isSet = flag => this.clientFlags & ClientConstants[flag];\n const packet = new Packet(0, buffer, 0, buffer.length);\n packet.offset = 4;\n packet.writeInt32(this.clientFlags);\n packet.writeInt32(0); // max packet size. todo: move to config\n packet.writeInt8(this.charsetNumber);\n packet.skip(23);\n const encoding = this.encoding;\n packet.writeNullTerminatedString(this.user, encoding);\n let k;\n if (isSet('PLUGIN_AUTH_LENENC_CLIENT_DATA')) {\n packet.writeLengthCodedNumber(this.authToken.length);\n packet.writeBuffer(this.authToken);\n } else if (isSet('SECURE_CONNECTION')) {\n packet.writeInt8(this.authToken.length);\n packet.writeBuffer(this.authToken);\n } else {\n packet.writeBuffer(this.authToken);\n packet.writeInt8(0);\n }\n if (isSet('CONNECT_WITH_DB')) {\n packet.writeNullTerminatedString(this.database, encoding);\n }\n if (isSet('PLUGIN_AUTH')) {\n // TODO: pass from config\n packet.writeNullTerminatedString('mysql_native_password', 'latin1');\n }\n if (isSet('CONNECT_ATTRS')) {\n const connectAttributes = this.connectAttributes || {};\n const attrNames = Object.keys(connectAttributes);\n let keysLength = 0;\n for (k = 0; k < attrNames.length; ++k) {\n keysLength += Packet.lengthCodedStringLength(attrNames[k], encoding);\n keysLength += Packet.lengthCodedStringLength(\n connectAttributes[attrNames[k]],\n encoding\n );\n }\n packet.writeLengthCodedNumber(keysLength);\n for (k = 0; k < attrNames.length; ++k) {\n packet.writeLengthCodedString(attrNames[k], encoding);\n packet.writeLengthCodedString(\n connectAttributes[attrNames[k]],\n encoding\n );\n }\n }\n return packet;\n }\n\n toPacket() {\n if (typeof this.user !== 'string') {\n throw new Error('\"user\" connection config property must be a string');\n }\n if (typeof this.database !== 'string') {\n throw new Error('\"database\" connection config property must be a string');\n }\n // dry run: calculate resulting packet length\n const p = this.serializeResponse(Packet.MockBuffer());\n return this.serializeResponse(Buffer.alloc(p.offset));\n }\n static fromPacket(packet) {\n const args = {};\n args.clientFlags = packet.readInt32();\n function isSet(flag) {\n return args.clientFlags & ClientConstants[flag];\n }\n args.maxPacketSize = packet.readInt32();\n args.charsetNumber = packet.readInt8();\n const encoding = CharsetToEncoding[args.charsetNumber];\n args.encoding = encoding;\n packet.skip(23);\n args.user = packet.readNullTerminatedString(encoding);\n let authTokenLength;\n if (isSet('PLUGIN_AUTH_LENENC_CLIENT_DATA')) {\n authTokenLength = packet.readLengthCodedNumber(encoding);\n args.authToken = packet.readBuffer(authTokenLength);\n } else if (isSet('SECURE_CONNECTION')) {\n authTokenLength = packet.readInt8();\n args.authToken = packet.readBuffer(authTokenLength);\n } else {\n args.authToken = packet.readNullTerminatedString(encoding);\n }\n if (isSet('CONNECT_WITH_DB')) {\n args.database = packet.readNullTerminatedString(encoding);\n }\n if (isSet('PLUGIN_AUTH')) {\n args.authPluginName = packet.readNullTerminatedString(encoding);\n }\n if (isSet('CONNECT_ATTRS')) {\n const keysLength = packet.readLengthCodedNumber(encoding);\n const keysEnd = packet.offset + keysLength;\n const attrs = {};\n while (packet.offset < keysEnd) {\n attrs[\n packet.readLengthCodedString(encoding)\n ] = packet.readLengthCodedString(encoding);\n }\n args.connectAttributes = attrs;\n }\n return args;\n }\n}\n\nmodule.exports = HandshakeResponse;\n","'use strict';\n\nconst Packet = require('../packets/packet');\nconst CommandCodes = require('../constants/commands');\nconst StringParser = require('../parsers/string.js');\nconst CharsetToEncoding = require('../constants/charset_encodings.js');\n\nclass PrepareStatement {\n constructor(sql, charsetNumber) {\n this.query = sql;\n this.charsetNumber = charsetNumber;\n this.encoding = CharsetToEncoding[charsetNumber];\n }\n\n toPacket() {\n const buf = StringParser.encode(this.query, this.encoding);\n const length = 5 + buf.length;\n const buffer = Buffer.allocUnsafe(length);\n const packet = new Packet(0, buffer, 0, length);\n packet.offset = 4;\n packet.writeInt8(CommandCodes.STMT_PREPARE);\n packet.writeBuffer(buf);\n return packet;\n }\n}\n\nmodule.exports = PrepareStatement;\n","'use strict';\n\nclass PreparedStatementHeader {\n constructor(packet) {\n packet.skip(1); // should be 0\n this.id = packet.readInt32();\n this.fieldCount = packet.readInt16();\n this.parameterCount = packet.readInt16();\n packet.skip(1); // should be 0\n this.warningCount = packet.readInt16();\n }\n}\n\n// TODO: toPacket\n\nmodule.exports = PreparedStatementHeader;\n","'use strict';\n\nconst Packet = require('../packets/packet.js');\nconst CommandCode = require('../constants/commands.js');\nconst StringParser = require('../parsers/string.js');\nconst CharsetToEncoding = require('../constants/charset_encodings.js');\n\nclass Query {\n constructor(sql, charsetNumber) {\n this.query = sql;\n this.charsetNumber = charsetNumber;\n this.encoding = CharsetToEncoding[charsetNumber];\n }\n\n toPacket() {\n const buf = StringParser.encode(this.query, this.encoding);\n const length = 5 + buf.length;\n const buffer = Buffer.allocUnsafe(length);\n const packet = new Packet(0, buffer, 0, length);\n packet.offset = 4;\n packet.writeInt8(CommandCode.QUERY);\n packet.writeBuffer(buf);\n return packet;\n }\n}\n\nmodule.exports = Query;\n","'use strict';\n\n// http://dev.mysql.com/doc/internals/en/com-register-slave.html\n// note that documentation is incorrect, for example command code is actually 0x15 but documented as 0x14\n\nconst Packet = require('../packets/packet');\nconst CommandCodes = require('../constants/commands');\n\nclass RegisterSlave {\n constructor(opts) {\n this.serverId = opts.serverId || 0;\n this.slaveHostname = opts.slaveHostname || '';\n this.slaveUser = opts.slaveUser || '';\n this.slavePassword = opts.slavePassword || '';\n this.slavePort = opts.slavePort || 0;\n this.replicationRank = opts.replicationRank || 0;\n this.masterId = opts.masterId || 0;\n }\n\n toPacket() {\n const length =\n 15 + // TODO: should be ascii?\n Buffer.byteLength(this.slaveHostname, 'utf8') +\n Buffer.byteLength(this.slaveUser, 'utf8') +\n Buffer.byteLength(this.slavePassword, 'utf8') +\n 3 +\n 4;\n const buffer = Buffer.allocUnsafe(length);\n const packet = new Packet(0, buffer, 0, length);\n packet.offset = 4;\n packet.writeInt8(CommandCodes.REGISTER_SLAVE);\n packet.writeInt32(this.serverId);\n packet.writeInt8(Buffer.byteLength(this.slaveHostname, 'utf8'));\n packet.writeString(this.slaveHostname);\n packet.writeInt8(Buffer.byteLength(this.slaveUser, 'utf8'));\n packet.writeString(this.slaveUser);\n packet.writeInt8(Buffer.byteLength(this.slavePassword, 'utf8'));\n packet.writeString(this.slavePassword);\n packet.writeInt16(this.slavePort);\n packet.writeInt32(this.replicationRank);\n packet.writeInt32(this.masterId);\n return packet;\n }\n}\n\nmodule.exports = RegisterSlave;\n","'use strict';\n\n// TODO: rename to OK packet\n// https://dev.mysql.com/doc/internals/en/packet-OK_Packet.html\n\nconst Packet = require('./packet.js');\nconst ClientConstants = require('../constants/client.js');\nconst ServerSatusFlags = require('../constants/server_status.js');\n\nconst EncodingToCharset = require('../constants/encoding_charset.js');\nconst sessionInfoTypes = require('../constants/session_track.js');\n\nclass ResultSetHeader {\n constructor(packet, connection) {\n const bigNumberStrings = connection.config.bigNumberStrings;\n const encoding = connection.serverEncoding;\n const flags = connection._handshakePacket.capabilityFlags;\n const isSet = function(flag) {\n return flags & ClientConstants[flag];\n };\n if (packet.buffer[packet.offset] !== 0) {\n this.fieldCount = packet.readLengthCodedNumber();\n if (this.fieldCount === null) {\n this.infileName = packet.readString(undefined, encoding);\n }\n return;\n }\n this.fieldCount = packet.readInt8(); // skip OK byte\n this.affectedRows = packet.readLengthCodedNumber(bigNumberStrings);\n this.insertId = packet.readLengthCodedNumberSigned(bigNumberStrings);\n this.info = '';\n if (isSet('PROTOCOL_41')) {\n this.serverStatus = packet.readInt16();\n this.warningStatus = packet.readInt16();\n } else if (isSet('TRANSACTIONS')) {\n this.serverStatus = packet.readInt16();\n }\n let stateChanges = null;\n if (isSet('SESSION_TRACK') && packet.offset < packet.end) {\n this.info = packet.readLengthCodedString(encoding);\n\n if (this.serverStatus && ServerSatusFlags.SERVER_SESSION_STATE_CHANGED) {\n // session change info record - see\n // https://dev.mysql.com/doc/internals/en/packet-OK_Packet.html#cs-sect-packet-ok-sessioninfo\n let len =\n packet.offset < packet.end ? packet.readLengthCodedNumber() : 0;\n const end = packet.offset + len;\n let type, key, stateEnd;\n if (len > 0) {\n stateChanges = {\n systemVariables: {},\n schema: null,\n trackStateChange: null\n };\n }\n while (packet.offset < end) {\n type = packet.readInt8();\n len = packet.readLengthCodedNumber();\n stateEnd = packet.offset + len;\n if (type === sessionInfoTypes.SYSTEM_VARIABLES) {\n key = packet.readLengthCodedString(encoding);\n const val = packet.readLengthCodedString(encoding);\n stateChanges.systemVariables[key] = val;\n if (key === 'character_set_client') {\n const charsetNumber = EncodingToCharset[val];\n connection.config.charsetNumber = charsetNumber;\n }\n } else if (type === sessionInfoTypes.SCHEMA) {\n key = packet.readLengthCodedString(encoding);\n stateChanges.schema = key;\n } else if (type === sessionInfoTypes.STATE_CHANGE) {\n stateChanges.trackStateChange = packet.readLengthCodedString(\n encoding\n );\n } else {\n // unsupported session track type. For now just ignore\n }\n packet.offset = stateEnd;\n }\n }\n } else {\n this.info = packet.readString(undefined, encoding);\n }\n if (stateChanges) {\n this.stateChanges = stateChanges;\n }\n const m = this.info.match(/\\schanged:\\s*(\\d+)/i);\n if (m !== null) {\n this.changedRows = parseInt(m[1], 10);\n }\n }\n\n // TODO: should be consistent instance member, but it's just easier here to have just function\n static toPacket(fieldCount, insertId) {\n let length = 4 + Packet.lengthCodedNumberLength(fieldCount);\n if (typeof insertId !== 'undefined') {\n length += Packet.lengthCodedNumberLength(insertId);\n }\n const buffer = Buffer.allocUnsafe(length);\n const packet = new Packet(0, buffer, 0, length);\n packet.offset = 4;\n packet.writeLengthCodedNumber(fieldCount);\n if (typeof insertId !== 'undefined') {\n packet.writeLengthCodedNumber(insertId);\n }\n return packet;\n }\n}\n\nmodule.exports = ResultSetHeader;\n","'use strict';\n\n// inverse of charset_encodings\n// given encoding, get matching mysql charset number\n\nmodule.exports = {\n big5: 1,\n latin2: 2,\n dec8: 3,\n cp850: 4,\n latin1: 5,\n hp8: 6,\n koi8r: 7,\n swe7: 10,\n ascii: 11,\n eucjp: 12,\n sjis: 13,\n cp1251: 14,\n hebrew: 16,\n tis620: 18,\n euckr: 19,\n latin7: 20,\n koi8u: 22,\n gb2312: 24,\n greek: 25,\n cp1250: 26,\n gbk: 28,\n cp1257: 29,\n latin5: 30,\n armscii8: 32,\n cesu8: 33,\n ucs2: 35,\n cp866: 36,\n keybcs2: 37,\n macintosh: 38,\n macroman: 39,\n cp852: 40,\n utf8: 45,\n utf8mb4: 45,\n utf16: 54,\n utf16le: 56,\n cp1256: 57,\n utf32: 60,\n binary: 63,\n geostd8: 92,\n cp932: 95,\n eucjpms: 97,\n gb18030: 248\n};\n","'use strict';\n\nexports.SYSTEM_VARIABLES = 0;\nexports.SCHEMA = 1;\nexports.STATE_CHANGE = 2;\nexports.STATE_GTIDS = 3;\nexports.TRANSACTION_CHARACTERISTICS = 4;\nexports.TRANSACTION_STATE = 5;\n\nexports.FIRST_KEY = exports.SYSTEM_VARIABLES;\nexports.LAST_KEY = exports.TRANSACTION_STATE;\n","'use strict';\n\nconst ClientConstants = require('../constants/client');\nconst Packet = require('../packets/packet');\n\nclass SSLRequest {\n constructor(flags, charset) {\n this.clientFlags = flags | ClientConstants.SSL;\n this.charset = charset;\n }\n\n toPacket() {\n const length = 36;\n const buffer = Buffer.allocUnsafe(length);\n const packet = new Packet(0, buffer, 0, length);\n buffer.fill(0);\n packet.offset = 4;\n packet.writeInt32(this.clientFlags);\n packet.writeInt32(0); // max packet size. todo: move to config\n packet.writeInt8(this.charset);\n return packet;\n }\n}\n\nmodule.exports = SSLRequest;\n","'use strict';\n\nconst Packet = require('../packets/packet');\n\nclass TextRow {\n constructor(columns) {\n this.columns = columns || [];\n }\n\n static fromPacket(packet) {\n // packet.reset(); // set offset to starting point?\n const columns = [];\n while (packet.haveMoreData()) {\n columns.push(packet.readLengthCodedString());\n }\n return new TextRow(columns);\n }\n\n static toPacket(columns, encoding) {\n const sequenceId = 0; // TODO remove, this is calculated now in connecton\n let length = 0;\n columns.forEach(val => {\n if (val === null || typeof val === 'undefined') {\n ++length;\n return;\n }\n length += Packet.lengthCodedStringLength(val.toString(10), encoding);\n });\n const buffer = Buffer.allocUnsafe(length + 4);\n const packet = new Packet(sequenceId, buffer, 0, length + 4);\n packet.offset = 4;\n columns.forEach(val => {\n if (val === null) {\n packet.writeNull();\n return;\n }\n if (typeof val === 'undefined') {\n packet.writeInt8(0);\n return;\n }\n packet.writeLengthCodedString(val.toString(10), encoding);\n });\n return packet;\n }\n}\n\nmodule.exports = TextRow;\n","'use strict';\n\nconst ClientHandshake = require('./client_handshake.js');\nconst ServerHandshake = require('./server_handshake.js');\nconst Query = require('./query.js');\nconst Prepare = require('./prepare.js');\nconst CloseStatement = require('./close_statement.js');\nconst Execute = require('./execute.js');\nconst Ping = require('./ping.js');\nconst RegisterSlave = require('./register_slave.js');\nconst BinlogDump = require('./binlog_dump.js');\nconst ChangeUser = require('./change_user.js');\nconst Quit = require('./quit.js');\n\nmodule.exports = {\n ClientHandshake,\n ServerHandshake,\n Query,\n Prepare,\n CloseStatement,\n Execute,\n Ping,\n RegisterSlave,\n BinlogDump,\n ChangeUser,\n Quit\n};\n","// This file was modified by Oracle on July 5, 2021.\n// Errors generated by asynchronous authentication plugins are now being\n// handled and subsequently emitted at the command level.\n// Modifications copyright (c) 2021, Oracle and/or its affiliates.\n\n'use strict';\n\nconst Packets = require('../packets/index.js');\nconst sha256_password = require('../auth_plugins/sha256_password');\nconst caching_sha2_password = require('../auth_plugins/caching_sha2_password.js');\nconst mysql_native_password = require('../auth_plugins/mysql_native_password.js');\n\nconst standardAuthPlugins = {\n sha256_password: sha256_password({}),\n caching_sha2_password: caching_sha2_password({}),\n mysql_native_password: mysql_native_password({})\n};\n\nfunction warnLegacyAuthSwitch() {\n console.warn(\n 'WARNING! authSwitchHandler api is deprecated, please use new authPlugins api'\n );\n}\n\nfunction authSwitchPluginError(error, command) {\n // Authentication errors are fatal\n error.code = 'AUTH_SWITCH_PLUGIN_ERROR';\n error.fatal = true;\n\n command.emit('error', error);\n}\n\nfunction authSwitchRequest(packet, connection, command) {\n const { pluginName, pluginData } = Packets.AuthSwitchRequest.fromPacket(\n packet\n );\n let authPlugin =\n connection.config.authPlugins && connection.config.authPlugins[pluginName];\n\n // legacy plugin api don't allow to override mysql_native_password\n // if pluginName is mysql_native_password it's using standard auth4.1 auth\n if (\n connection.config.authSwitchHandler &&\n pluginName !== 'mysql_native_password'\n ) {\n const legacySwitchHandler = connection.config.authSwitchHandler;\n warnLegacyAuthSwitch();\n legacySwitchHandler({ pluginName, pluginData }, (err, data) => {\n if (err) {\n return authSwitchPluginError(err, command);\n }\n connection.writePacket(new Packets.AuthSwitchResponse(data).toPacket());\n });\n return;\n }\n if (!authPlugin) {\n authPlugin = standardAuthPlugins[pluginName];\n }\n if (!authPlugin) {\n throw new Error(\n `Server requests authentication using unknown plugin ${pluginName}. See ${'TODO: add plugins doco here'} on how to configure or author authentication plugins.`\n );\n }\n connection._authPlugin = authPlugin({ connection, command });\n Promise.resolve(connection._authPlugin(pluginData)).then(data => {\n if (data) {\n connection.writePacket(new Packets.AuthSwitchResponse(data).toPacket());\n }\n }).catch(err => {\n authSwitchPluginError(err, command);\n });\n}\n\nfunction authSwitchRequestMoreData(packet, connection, command) {\n const { data } = Packets.AuthSwitchRequestMoreData.fromPacket(packet);\n\n if (connection.config.authSwitchHandler) {\n const legacySwitchHandler = connection.config.authSwitchHandler;\n warnLegacyAuthSwitch();\n legacySwitchHandler({ pluginData: data }, (err, data) => {\n if (err) {\n return authSwitchPluginError(err, command);\n }\n connection.writePacket(new Packets.AuthSwitchResponse(data).toPacket());\n });\n return;\n }\n\n if (!connection._authPlugin) {\n throw new Error(\n 'AuthPluginMoreData received but no auth plugin instance found'\n );\n }\n Promise.resolve(connection._authPlugin(data)).then(data => {\n if (data) {\n connection.writePacket(new Packets.AuthSwitchResponse(data).toPacket());\n }\n }).catch(err => {\n authSwitchPluginError(err, command);\n });\n}\n\nmodule.exports = {\n authSwitchRequest,\n authSwitchRequestMoreData\n};\n","'use strict';\n\nconst PLUGIN_NAME = 'sha256_password';\nconst crypto = require('crypto');\nconst { xor } = require('../auth_41');\n\nconst REQUEST_SERVER_KEY_PACKET = Buffer.from([1]);\n\nconst STATE_INITIAL = 0;\nconst STATE_WAIT_SERVER_KEY = 1;\nconst STATE_FINAL = -1;\n\nfunction encrypt(password, scramble, key) {\n const stage1 = xor(\n Buffer.from(`${password}\\0`, 'utf8').toString('binary'),\n scramble.toString('binary')\n );\n return crypto.publicEncrypt(key, stage1);\n}\n\nmodule.exports = (pluginOptions = {}) => ({ connection }) => {\n let state = 0;\n let scramble = null;\n\n const password = connection.config.password;\n\n const authWithKey = serverKey => {\n const _password = encrypt(password, scramble, serverKey);\n state = STATE_FINAL;\n return _password;\n };\n\n return data => {\n switch (state) {\n case STATE_INITIAL:\n scramble = data.slice(0, 20);\n // if client provides key we can save one extra roundrip on first connection\n if (pluginOptions.serverPublicKey) {\n return authWithKey(pluginOptions.serverPublicKey);\n }\n\n state = STATE_WAIT_SERVER_KEY;\n return REQUEST_SERVER_KEY_PACKET;\n\n case STATE_WAIT_SERVER_KEY:\n if (pluginOptions.onServerPublicKey) {\n pluginOptions.onServerPublicKey(data);\n }\n return authWithKey(data);\n case STATE_FINAL:\n throw new Error(\n `Unexpected data in AuthMoreData packet received by ${PLUGIN_NAME} plugin in STATE_FINAL state.`\n );\n }\n\n throw new Error(\n `Unexpected data in AuthMoreData packet received by ${PLUGIN_NAME} plugin in state ${state}`\n );\n };\n};\n","'use strict';\n\n// https://mysqlserverteam.com/mysql-8-0-4-new-default-authentication-plugin-caching_sha2_password/\n\nconst PLUGIN_NAME = 'caching_sha2_password';\nconst crypto = require('crypto');\nconst { xor, xorRotating } = require('../auth_41');\n\nconst REQUEST_SERVER_KEY_PACKET = Buffer.from([2]);\nconst FAST_AUTH_SUCCESS_PACKET = Buffer.from([3]);\nconst PERFORM_FULL_AUTHENTICATION_PACKET = Buffer.from([4]);\n\nconst STATE_INITIAL = 0;\nconst STATE_TOKEN_SENT = 1;\nconst STATE_WAIT_SERVER_KEY = 2;\nconst STATE_FINAL = -1;\n\nfunction sha256(msg) {\n const hash = crypto.createHash('sha256');\n hash.update(msg, 'binary');\n return hash.digest('binary');\n}\n\nfunction calculateToken(password, scramble) {\n if (!password) {\n return Buffer.alloc(0);\n }\n const stage1 = sha256(Buffer.from(password, 'utf8').toString('binary'));\n const stage2 = sha256(stage1);\n const stage3 = sha256(stage2 + scramble.toString('binary'));\n return xor(stage1, stage3);\n}\n\nfunction encrypt(password, scramble, key) {\n const stage1 = xorRotating(\n Buffer.from(`${password}\\0`, 'utf8').toString('binary'),\n scramble.toString('binary')\n );\n return crypto.publicEncrypt(key, stage1);\n}\n\nmodule.exports = (pluginOptions = {}) => ({ connection }) => {\n let state = 0;\n let scramble = null;\n\n const password = connection.config.password;\n\n const authWithKey = serverKey => {\n const _password = encrypt(password, scramble, serverKey);\n state = STATE_FINAL;\n return _password;\n };\n\n return data => {\n switch (state) {\n case STATE_INITIAL:\n scramble = data.slice(0, 20);\n state = STATE_TOKEN_SENT;\n return calculateToken(password, scramble);\n\n case STATE_TOKEN_SENT:\n if (FAST_AUTH_SUCCESS_PACKET.equals(data)) {\n state = STATE_FINAL;\n return null;\n }\n\n if (PERFORM_FULL_AUTHENTICATION_PACKET.equals(data)) {\n const isSecureConnection =\n typeof pluginOptions.overrideIsSecure === 'undefined'\n ? connection.config.ssl || connection.config.socketPath\n : pluginOptions.overrideIsSecure;\n if (isSecureConnection) {\n state = STATE_FINAL;\n return Buffer.from(`${password}\\0`, 'utf8');\n }\n\n // if client provides key we can save one extra roundrip on first connection\n if (pluginOptions.serverPublicKey) {\n return authWithKey(pluginOptions.serverPublicKey);\n }\n\n state = STATE_WAIT_SERVER_KEY;\n return REQUEST_SERVER_KEY_PACKET;\n }\n throw new Error(\n `Invalid AuthMoreData packet received by ${PLUGIN_NAME} plugin in STATE_TOKEN_SENT state.`\n );\n case STATE_WAIT_SERVER_KEY:\n if (pluginOptions.onServerPublicKey) {\n pluginOptions.onServerPublicKey(data);\n }\n return authWithKey(data);\n case STATE_FINAL:\n throw new Error(\n `Unexpected data in AuthMoreData packet received by ${PLUGIN_NAME} plugin in STATE_FINAL state.`\n );\n }\n\n throw new Error(\n `Unexpected data in AuthMoreData packet received by ${PLUGIN_NAME} plugin in state ${state}`\n );\n };\n};\n","'use strict';\n\n//const PLUGIN_NAME = 'mysql_native_password';\nconst auth41 = require('../auth_41.js');\n\nmodule.exports = pluginOptions => ({ connection, command }) => {\n const password =\n command.password || pluginOptions.password || connection.config.password;\n const passwordSha1 =\n command.passwordSha1 ||\n pluginOptions.passwordSha1 ||\n connection.config.passwordSha1;\n return data => {\n const authPluginData1 = data.slice(0, 8);\n const authPluginData2 = data.slice(8, 20);\n let authToken;\n if (passwordSha1) {\n authToken = auth41.calculateTokenFromPasswordSha(\n passwordSha1,\n authPluginData1,\n authPluginData2\n );\n } else {\n authToken = auth41.calculateToken(\n password,\n authPluginData1,\n authPluginData2\n );\n }\n return authToken;\n };\n};\n","'use strict';\n\n// connection mixins\n// implementation of http://dev.mysql.com/doc/internals/en/compression.html\n\nconst zlib = require('zlib');\nconst PacketParser = require('./packet_parser.js');\n\nfunction handleCompressedPacket(packet) {\n // eslint-disable-next-line consistent-this, no-invalid-this\n const connection = this;\n const deflatedLength = packet.readInt24();\n const body = packet.readBuffer();\n\n if (deflatedLength !== 0) {\n connection.inflateQueue.push(task => {\n zlib.inflate(body, (err, data) => {\n if (err) {\n connection._handleNetworkError(err);\n return;\n }\n connection._bumpCompressedSequenceId(packet.numPackets);\n connection._inflatedPacketsParser.execute(data);\n task.done();\n });\n });\n } else {\n connection.inflateQueue.push(task => {\n connection._bumpCompressedSequenceId(packet.numPackets);\n connection._inflatedPacketsParser.execute(body);\n task.done();\n });\n }\n}\n\nfunction writeCompressed(buffer) {\n // http://dev.mysql.com/doc/internals/en/example-several-mysql-packets.html\n // note: sending a MySQL Packet of the size 2^24−5 to 2^24−1 via compression\n // leads to at least one extra compressed packet.\n // (this is because \"length of the packet before compression\" need to fit\n // into 3 byte unsigned int. \"length of the packet before compression\" includes\n // 4 byte packet header, hence 2^24−5)\n const MAX_COMPRESSED_LENGTH = 16777210;\n let start;\n if (buffer.length > MAX_COMPRESSED_LENGTH) {\n for (start = 0; start < buffer.length; start += MAX_COMPRESSED_LENGTH) {\n writeCompressed.call(\n // eslint-disable-next-line no-invalid-this\n this,\n buffer.slice(start, start + MAX_COMPRESSED_LENGTH)\n );\n }\n return;\n }\n\n // eslint-disable-next-line no-invalid-this, consistent-this\n const connection = this;\n\n let packetLen = buffer.length;\n const compressHeader = Buffer.allocUnsafe(7);\n\n // seqqueue is used here because zlib async execution is routed via thread pool\n // internally and when we have multiple compressed packets arriving we need\n // to assemble uncompressed result sequentially\n (function(seqId) {\n connection.deflateQueue.push(task => {\n zlib.deflate(buffer, (err, compressed) => {\n if (err) {\n connection._handleFatalError(err);\n return;\n }\n let compressedLength = compressed.length;\n\n if (compressedLength < packetLen) {\n compressHeader.writeUInt8(compressedLength & 0xff, 0);\n compressHeader.writeUInt16LE(compressedLength >> 8, 1);\n compressHeader.writeUInt8(seqId, 3);\n compressHeader.writeUInt8(packetLen & 0xff, 4);\n compressHeader.writeUInt16LE(packetLen >> 8, 5);\n connection.writeUncompressed(compressHeader);\n connection.writeUncompressed(compressed);\n } else {\n // http://dev.mysql.com/doc/internals/en/uncompressed-payload.html\n // To send an uncompressed payload:\n // - set length of payload before compression to 0\n // - the compressed payload contains the uncompressed payload instead.\n compressedLength = packetLen;\n packetLen = 0;\n compressHeader.writeUInt8(compressedLength & 0xff, 0);\n compressHeader.writeUInt16LE(compressedLength >> 8, 1);\n compressHeader.writeUInt8(seqId, 3);\n compressHeader.writeUInt8(packetLen & 0xff, 4);\n compressHeader.writeUInt16LE(packetLen >> 8, 5);\n connection.writeUncompressed(compressHeader);\n connection.writeUncompressed(buffer);\n }\n task.done();\n });\n });\n })(connection.compressedSequenceId);\n connection._bumpCompressedSequenceId(1);\n}\n\nfunction enableCompression(connection) {\n connection._lastWrittenPacketId = 0;\n connection._lastReceivedPacketId = 0;\n\n connection._handleCompressedPacket = handleCompressedPacket;\n connection._inflatedPacketsParser = new PacketParser(p => {\n connection.handlePacket(p);\n }, 4);\n connection._inflatedPacketsParser._lastPacket = 0;\n connection.packetParser = new PacketParser(packet => {\n connection._handleCompressedPacket(packet);\n }, 7);\n\n connection.writeUncompressed = connection.write;\n connection.write = writeCompressed;\n\n const seqqueue = require('seq-queue');\n connection.inflateQueue = seqqueue.createQueue();\n connection.deflateQueue = seqqueue.createQueue();\n}\n\nmodule.exports = {\n enableCompression: enableCompression\n};\n","module.exports = require('./lib/seq-queue');","var EventEmitter = require('events').EventEmitter;\nvar util = require('util');\n\nvar DEFAULT_TIMEOUT = 3000;\nvar INIT_ID = 0;\nvar EVENT_CLOSED = 'closed';\nvar EVENT_DRAINED = 'drained';\n\n/**\n * Instance a new queue\n *\n * @param {Number} timeout a global timeout for new queue\n * @class\n * @constructor\n */\nvar SeqQueue = function(timeout) {\n\tEventEmitter.call(this);\n\t\n\tif(timeout && timeout > 0) {\n\t\tthis.timeout = timeout;\n\t} else {\n\t\tthis.timeout = DEFAULT_TIMEOUT;\n\t}\n\t\n\tthis.status = SeqQueueManager.STATUS_IDLE;\n\tthis.curId = INIT_ID;\n\tthis.queue = [];\n};\nutil.inherits(SeqQueue, EventEmitter);\n\n/**\n * Add a task into queue.\n * \n * @param fn new request\n * @param ontimeout callback when task timeout\n * @param timeout timeout for current request. take the global timeout if this is invalid\n * @returns true or false\n */\nSeqQueue.prototype.push = function(fn, ontimeout, timeout) {\n\tif(this.status !== SeqQueueManager.STATUS_IDLE && this.status !== SeqQueueManager.STATUS_BUSY) {\n\t\t//ignore invalid status\n\t\treturn false;\n\t}\n\t\n\tif(typeof fn !== 'function') {\n\t\tthrow new Error('fn should be a function.');\n\t}\n\tthis.queue.push({fn: fn, ontimeout: ontimeout, timeout: timeout});\n\n\tif(this.status === SeqQueueManager.STATUS_IDLE) {\n\t\tthis.status = SeqQueueManager.STATUS_BUSY;\n\t\tvar self = this;\n\t\tprocess.nextTick(function() {\n\t\t\tself._next(self.curId);\n\t\t});\n\t}\n\treturn true;\n};\n\n/**\n * Close queue\n * \n * @param {Boolean} force if true will close the queue immediately else will execute the rest task in queue\n */\nSeqQueue.prototype.close = function(force) {\n\tif(this.status !== SeqQueueManager.STATUS_IDLE && this.status !== SeqQueueManager.STATUS_BUSY) {\n\t\t//ignore invalid status\n\t\treturn;\n\t}\n\t\n\tif(force) {\n\t\tthis.status = SeqQueueManager.STATUS_DRAINED;\n\t\tif(this.timerId) {\n\t\t\tclearTimeout(this.timerId);\n\t\t\tthis.timerId = undefined;\n\t\t}\n\t\tthis.emit(EVENT_DRAINED);\n\t} else {\n\t\tthis.status = SeqQueueManager.STATUS_CLOSED;\n\t\tthis.emit(EVENT_CLOSED);\n\t}\n};\n\n/**\n * Invoke next task\n * \n * @param {String|Number} tid last executed task id\n * @api private\n */\nSeqQueue.prototype._next = function(tid) {\n\tif(tid !== this.curId || this.status !== SeqQueueManager.STATUS_BUSY && this.status !== SeqQueueManager.STATUS_CLOSED) {\n\t\t//ignore invalid next call\n\t\treturn;\n\t}\n\t\n\tif(this.timerId) {\n\t\tclearTimeout(this.timerId);\n\t\tthis.timerId = undefined;\n\t}\n\t\n\tvar task = this.queue.shift();\n\tif(!task) {\n\t\tif(this.status === SeqQueueManager.STATUS_BUSY) {\n\t\t\tthis.status = SeqQueueManager.STATUS_IDLE;\n\t\t\tthis.curId++;\t//modify curId to invalidate timeout task\n\t\t} else {\n\t\t\tthis.status = SeqQueueManager.STATUS_DRAINED;\n\t\t\tthis.emit(EVENT_DRAINED);\n\t\t}\n\t\treturn;\n\t}\n\t\n\tvar self = this;\n\ttask.id = ++this.curId;\n\n\tvar timeout = task.timeout > 0 ? task.timeout : this.timeout;\n\ttimeout = timeout > 0 ? timeout : DEFAULT_TIMEOUT;\n\tthis.timerId = setTimeout(function() {\n\t\tprocess.nextTick(function() {\n\t\t\tself._next(task.id);\n\t\t});\n\t\tself.emit('timeout', task);\n\t\tif(task.ontimeout) {\n\t\t\ttask.ontimeout();\n\t\t}\n\t}, timeout);\n\n\ttry {\n\t\ttask.fn({\n\t\t\tdone: function() {\n\t\t\t\tvar res = task.id === self.curId;\n\t\t\t\tprocess.nextTick(function() {\n\t\t\t\t\tself._next(task.id);\n\t\t\t\t});\n\t\t\t\treturn res;\n\t\t\t}\n\t\t});\n\t} catch(err) {\n\t\tself.emit('error', err, task);\n\t\tprocess.nextTick(function() {\n\t\t\tself._next(task.id);\n\t\t});\n\t}\n};\n\n/**\n * Queue manager.\n * \n * @module\n */\nvar SeqQueueManager = module.exports;\n\n/**\n * Queue status: idle, welcome new tasks\n *\n * @const\n * @type {Number}\n * @memberOf SeqQueueManager\n */\nSeqQueueManager.STATUS_IDLE = 0;\n\n/**\n * Queue status: busy, queue is working for some tasks now\n *\n * @const\n * @type {Number}\n * @memberOf SeqQueueManager\n */\nSeqQueueManager.STATUS_BUSY = 1;\n\n/**\n * Queue status: closed, queue has closed and would not receive task any more \n * \t\t\t\t\tand is processing the remaining tasks now.\n *\n * @const\n * @type {Number}\n * @memberOf SeqQueueManager\n */\nSeqQueueManager.STATUS_CLOSED = 2; \n\n/**\n * Queue status: drained, queue is ready to be destroy\n *\n * @const\n * @type {Number}\n * @memberOf SeqQueueManager\n */\nSeqQueueManager.STATUS_DRAINED = 3;\n\n/**\n * Create Sequence queue\n * \n * @param {Number} timeout a global timeout for the new queue instance\n * @return {Object} new queue instance\n * @memberOf SeqQueueManager\n */\nSeqQueueManager.createQueue = function(timeout) {\n\treturn new SeqQueue(timeout);\n};","'use strict';\n\nconst CommandCode = require('../constants/commands.js');\nconst Errors = require('../constants/errors.js');\n\nconst Command = require('./command.js');\nconst Packets = require('../packets/index.js');\n\nclass ServerHandshake extends Command {\n constructor(args) {\n super();\n this.args = args;\n /*\n this.protocolVersion = args.protocolVersion || 10;\n this.serverVersion = args.serverVersion;\n this.connectionId = args.connectionId,\n this.statusFlags = args.statusFlags,\n this.characterSet = args.characterSet,\n this.capabilityFlags = args.capabilityFlags || 512;\n */\n }\n\n start(packet, connection) {\n const serverHelloPacket = new Packets.Handshake(this.args);\n this.serverHello = serverHelloPacket;\n serverHelloPacket.setScrambleData(err => {\n if (err) {\n connection.emit('error', new Error('Error generating random bytes'));\n return;\n }\n connection.writePacket(serverHelloPacket.toPacket(0));\n });\n return ServerHandshake.prototype.readClientReply;\n }\n\n readClientReply(packet, connection) {\n // check auth here\n const clientHelloReply = Packets.HandshakeResponse.fromPacket(packet);\n // TODO check we don't have something similar already\n connection.clientHelloReply = clientHelloReply;\n if (this.args.authCallback) {\n this.args.authCallback(\n {\n user: clientHelloReply.user,\n database: clientHelloReply.database,\n address: connection.stream.remoteAddress,\n authPluginData1: this.serverHello.authPluginData1,\n authPluginData2: this.serverHello.authPluginData2,\n authToken: clientHelloReply.authToken\n },\n (err, mysqlError) => {\n // if (err)\n if (!mysqlError) {\n connection.writeOk();\n } else {\n // TODO create constants / errorToCode\n // 1045 = ER_ACCESS_DENIED_ERROR\n connection.writeError({\n message: mysqlError.message || '',\n code: mysqlError.code || 1045\n });\n connection.close();\n }\n }\n );\n } else {\n connection.writeOk();\n }\n return ServerHandshake.prototype.dispatchCommands;\n }\n\n dispatchCommands(packet, connection) {\n // command from client to server\n let knownCommand = true;\n const encoding = connection.clientHelloReply.encoding;\n const commandCode = packet.readInt8();\n switch (commandCode) {\n case CommandCode.QUIT:\n if (connection.listeners('quit').length) {\n connection.emit('quit');\n } else {\n connection.stream.end();\n }\n break;\n case CommandCode.INIT_DB:\n if (connection.listeners('init_db').length) {\n const schemaName = packet.readString(undefined, encoding);\n connection.emit('init_db', schemaName);\n } else {\n connection.writeOk();\n }\n break;\n case CommandCode.QUERY:\n if (connection.listeners('query').length) {\n const query = packet.readString(undefined, encoding);\n connection.emit('query', query);\n } else {\n connection.writeError({\n code: Errors.HA_ERR_INTERNAL_ERROR,\n message: 'No query handler'\n });\n }\n break;\n case CommandCode.FIELD_LIST:\n if (connection.listeners('field_list').length) {\n const table = packet.readNullTerminatedString();\n const fields = packet.readString(undefined, encoding);\n connection.emit('field_list', table, fields);\n } else {\n connection.writeError({\n code: Errors.ER_WARN_DEPRECATED_SYNTAX,\n message:\n 'As of MySQL 5.7.11, COM_FIELD_LIST is deprecated and will be removed in a future version of MySQL.'\n });\n }\n break;\n case CommandCode.PING:\n if (connection.listeners('ping').length) {\n connection.emit('ping');\n } else {\n connection.writeOk();\n }\n break;\n default:\n knownCommand = false;\n }\n if (connection.listeners('packet').length) {\n connection.emit('packet', packet.clone(), knownCommand, commandCode);\n } else if (!knownCommand) {\n // eslint-disable-next-line no-console\n console.log('Unknown command:', commandCode);\n }\n return ServerHandshake.prototype.dispatchCommands;\n }\n}\n\nmodule.exports = ServerHandshake;\n\n// TODO: implement server-side 4.1 authentication\n/*\n4.1 authentication: (http://bazaar.launchpad.net/~mysql/mysql-server/5.5/view/head:/sql/password.c)\n\n SERVER: public_seed=create_random_string()\n send(public_seed)\n\n CLIENT: recv(public_seed)\n hash_stage1=sha1(\"password\")\n hash_stage2=sha1(hash_stage1)\n reply=xor(hash_stage1, sha1(public_seed,hash_stage2)\n\n // this three steps are done in scramble()\n\n send(reply)\n\n\n SERVER: recv(reply)\n hash_stage1=xor(reply, sha1(public_seed,hash_stage2))\n candidate_hash2=sha1(hash_stage1)\n check(candidate_hash2==hash_stage2)\n\nserver stores sha1(sha1(password)) ( hash_stag2)\n*/\n","'use strict';\n\nconst Types = require('../constants/types.js');\nconst Charsets = require('../constants/charsets.js');\nconst helpers = require('../helpers');\nconst genFunc = require('generate-function');\nconst parserCache = require('./parser_cache.js');\n\nconst typeNames = [];\nfor (const t in Types) {\n typeNames[Types[t]] = t;\n}\n\nfunction readCodeFor(type, charset, encodingExpr, config, options) {\n const supportBigNumbers =\n options.supportBigNumbers || config.supportBigNumbers;\n const bigNumberStrings = options.bigNumberStrings || config.bigNumberStrings;\n const timezone = options.timezone || config.timezone;\n const dateStrings = options.dateStrings || config.dateStrings;\n\n switch (type) {\n case Types.TINY:\n case Types.SHORT:\n case Types.LONG:\n case Types.INT24:\n case Types.YEAR:\n return 'packet.parseLengthCodedIntNoBigCheck()';\n case Types.LONGLONG:\n if (supportBigNumbers && bigNumberStrings) {\n return 'packet.parseLengthCodedIntString()';\n }\n return `packet.parseLengthCodedInt(${supportBigNumbers})`;\n case Types.FLOAT:\n case Types.DOUBLE:\n return 'packet.parseLengthCodedFloat()';\n case Types.NULL:\n return 'packet.readLengthCodedNumber()';\n case Types.DECIMAL:\n case Types.NEWDECIMAL:\n if (config.decimalNumbers) {\n return 'packet.parseLengthCodedFloat()';\n }\n return 'packet.readLengthCodedString(\"ascii\")';\n case Types.DATE:\n if (helpers.typeMatch(type, dateStrings, Types)) {\n return 'packet.readLengthCodedString(\"ascii\")';\n }\n return `packet.parseDate('${timezone}')`;\n case Types.DATETIME:\n case Types.TIMESTAMP:\n if (helpers.typeMatch(type, dateStrings, Types)) {\n return 'packet.readLengthCodedString(\"ascii\")';\n }\n return `packet.parseDateTime('${timezone}')`;\n case Types.TIME:\n return 'packet.readLengthCodedString(\"ascii\")';\n case Types.GEOMETRY:\n return 'packet.parseGeometryValue()';\n case Types.JSON:\n // Since for JSON columns mysql always returns charset 63 (BINARY),\n // we have to handle it according to JSON specs and use \"utf8\",\n // see https://github.com/sidorares/node-mysql2/issues/409\n return 'JSON.parse(packet.readLengthCodedString(\"utf8\"))';\n default:\n if (charset === Charsets.BINARY) {\n return 'packet.readLengthCodedBuffer()';\n }\n return `packet.readLengthCodedString(${encodingExpr})`;\n }\n}\n\nfunction compile(fields, options, config) {\n // use global typeCast if current query doesn't specify one\n if (\n typeof config.typeCast === 'function' &&\n typeof options.typeCast !== 'function'\n ) {\n options.typeCast = config.typeCast;\n }\n\n function wrap(field, _this) {\n return {\n type: typeNames[field.columnType],\n length: field.columnLength,\n db: field.schema,\n table: field.table,\n name: field.name,\n string: function() {\n return _this.packet.readLengthCodedString(field.encoding);\n },\n buffer: function() {\n return _this.packet.readLengthCodedBuffer();\n },\n geometry: function() {\n return _this.packet.parseGeometryValue();\n }\n };\n }\n\n const parserFn = genFunc();\n\n /* eslint-disable no-trailing-spaces */\n /* eslint-disable no-spaced-func */\n /* eslint-disable no-unexpected-multiline */\n parserFn('(function () {')(\n 'return class TextRow {'\n );\n\n // constructor method\n parserFn('constructor(fields) {');\n // node-mysql typeCast compatibility wrapper\n // see https://github.com/mysqljs/mysql/blob/96fdd0566b654436624e2375c7b6604b1f50f825/lib/protocol/packets/Field.js\n if (typeof options.typeCast === 'function') {\n parserFn('const _this = this;');\n parserFn('for(let i=0; i