UNPKG

keep-observers

Version:

This is a monitoring service applied to the web side Support Elasticsearch+kiban The middleware extension interface is provided by means of plug-in service compositionkeep-observers

1,552 lines (1,326 loc) 161 kB
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("@util/index")); else if(typeof define === 'function' && define.amd) define(["@util/index"], factory); else { var a = typeof exports === 'object' ? factory(require("@util/index")) : factory(root["@util/index"]); for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i]; } })(this, function(__WEBPACK_EXTERNAL_MODULE__util_index__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = "./src/services/report/kibanaApm/index.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "./node_modules/elastic-apm-js-core/node_modules/error-stack-parser/error-stack-parser.js": /*!************************************************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/node_modules/error-stack-parser/error-stack-parser.js ***! \************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers. /* istanbul ignore next */ if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! stackframe */ "./node_modules/elastic-apm-js-core/node_modules/stackframe/stackframe.js")], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} })(this, function ErrorStackParser(StackFrame) { 'use strict'; var FIREFOX_SAFARI_STACK_REGEXP = /(^|@)\S+\:\d+/; var CHROME_IE_STACK_REGEXP = /^\s*at .*(\S+\:\d+|\(native\))/m; var SAFARI_NATIVE_CODE_REGEXP = /^(eval@)?(\[native code\])?$/; function _map(array, fn, thisArg) { if (typeof Array.prototype.map === 'function') { return array.map(fn, thisArg); } else { var output = new Array(array.length); for (var i = 0; i < array.length; i++) { output[i] = fn.call(thisArg, array[i]); } return output; } } function _filter(array, fn, thisArg) { if (typeof Array.prototype.filter === 'function') { return array.filter(fn, thisArg); } else { var output = []; for (var i = 0; i < array.length; i++) { if (fn.call(thisArg, array[i])) { output.push(array[i]); } } return output; } } function _indexOf(array, target) { if (typeof Array.prototype.indexOf === 'function') { return array.indexOf(target); } else { for (var i = 0; i < array.length; i++) { if (array[i] === target) { return i; } } return -1; } } return { /** * Given an Error object, extract the most information from it. * * @param {Error} error object * @return {Array} of StackFrames */ parse: function ErrorStackParser$$parse(error) { if (typeof error.stacktrace !== 'undefined' || typeof error['opera#sourceloc'] !== 'undefined') { return this.parseOpera(error); } else if (error.stack && error.stack.match(CHROME_IE_STACK_REGEXP)) { return this.parseV8OrIE(error); } else if (error.stack) { return this.parseFFOrSafari(error); } else { throw new Error('Cannot parse given Error object'); } }, // Separate line and column numbers from a string of the form: (URI:Line:Column) extractLocation: function ErrorStackParser$$extractLocation(urlLike) { // Fail-fast but return locations like "(native)" if (urlLike.indexOf(':') === -1) { return [urlLike]; } var regExp = /(.+?)(?:\:(\d+))?(?:\:(\d+))?$/; var parts = regExp.exec(urlLike.replace(/[\(\)]/g, '')); return [parts[1], parts[2] || undefined, parts[3] || undefined]; }, parseV8OrIE: function ErrorStackParser$$parseV8OrIE(error) { var filtered = _filter(error.stack.split('\n'), function (line) { return !!line.match(CHROME_IE_STACK_REGEXP); }, this); return _map(filtered, function (line) { if (line.indexOf('(eval ') > -1) { // Throw away eval information until we implement stacktrace.js/stackframe#8 line = line.replace(/eval code/g, 'eval').replace(/(\(eval at [^\()]*)|(\)\,.*$)/g, ''); } var tokens = line.replace(/^\s+/, '').replace(/\(eval code/g, '(').split(/\s+/).slice(1); var locationParts = this.extractLocation(tokens.pop()); var functionName = tokens.join(' ') || undefined; var fileName = _indexOf(['eval', '<anonymous>'], locationParts[0]) > -1 ? undefined : locationParts[0]; return new StackFrame(functionName, undefined, fileName, locationParts[1], locationParts[2], line); }, this); }, parseFFOrSafari: function ErrorStackParser$$parseFFOrSafari(error) { var filtered = _filter(error.stack.split('\n'), function (line) { return !line.match(SAFARI_NATIVE_CODE_REGEXP); }, this); return _map(filtered, function (line) { // Throw away eval information until we implement stacktrace.js/stackframe#8 if (line.indexOf(' > eval') > -1) { line = line.replace(/ line (\d+)(?: > eval line \d+)* > eval\:\d+\:\d+/g, ':$1'); } if (line.indexOf('@') === -1 && line.indexOf(':') === -1) { // Safari eval frames only have function names and nothing else return new StackFrame(line); } else { var tokens = line.split('@'); var locationParts = this.extractLocation(tokens.pop()); var functionName = tokens.join('@') || undefined; return new StackFrame(functionName, undefined, locationParts[0], locationParts[1], locationParts[2], line); } }, this); }, parseOpera: function ErrorStackParser$$parseOpera(e) { if (!e.stacktrace || e.message.indexOf('\n') > -1 && e.message.split('\n').length > e.stacktrace.split('\n').length) { return this.parseOpera9(e); } else if (!e.stack) { return this.parseOpera10(e); } else { return this.parseOpera11(e); } }, parseOpera9: function ErrorStackParser$$parseOpera9(e) { var lineRE = /Line (\d+).*script (?:in )?(\S+)/i; var lines = e.message.split('\n'); var result = []; for (var i = 2, len = lines.length; i < len; i += 2) { var match = lineRE.exec(lines[i]); if (match) { result.push(new StackFrame(undefined, undefined, match[2], match[1], undefined, lines[i])); } } return result; }, parseOpera10: function ErrorStackParser$$parseOpera10(e) { var lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i; var lines = e.stacktrace.split('\n'); var result = []; for (var i = 0, len = lines.length; i < len; i += 2) { var match = lineRE.exec(lines[i]); if (match) { result.push(new StackFrame(match[3] || undefined, undefined, match[2], match[1], undefined, lines[i])); } } return result; }, // Opera 10.65+ Error.stack very similar to FF/Safari parseOpera11: function ErrorStackParser$$parseOpera11(error) { var filtered = _filter(error.stack.split('\n'), function (line) { return !!line.match(FIREFOX_SAFARI_STACK_REGEXP) && !line.match(/^Error created at/); }, this); return _map(filtered, function (line) { var tokens = line.split('@'); var locationParts = this.extractLocation(tokens.pop()); var functionCall = tokens.shift() || ''; var functionName = functionCall.replace(/<anonymous function(: (\w+))?>/, '$2').replace(/\([^\)]*\)/g, '') || undefined; var argsRaw; if (functionCall.match(/\(([^\)]*)\)/)) { argsRaw = functionCall.replace(/^[^\(]+\(([^\)]*)\)$/, '$1'); } var args = argsRaw === undefined || argsRaw === '[arguments not available]' ? undefined : argsRaw.split(','); return new StackFrame(functionName, args, locationParts[0], locationParts[1], locationParts[2], line); }, this); } }; }); /***/ }), /***/ "./node_modules/elastic-apm-js-core/node_modules/stackframe/stackframe.js": /*!********************************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/node_modules/stackframe/stackframe.js ***! \********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, Rhino, and browsers. /* istanbul ignore next */ if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} })(this, function () { 'use strict'; function _isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function StackFrame(functionName, args, fileName, lineNumber, columnNumber, source) { if (functionName !== undefined) { this.setFunctionName(functionName); } if (args !== undefined) { this.setArgs(args); } if (fileName !== undefined) { this.setFileName(fileName); } if (lineNumber !== undefined) { this.setLineNumber(lineNumber); } if (columnNumber !== undefined) { this.setColumnNumber(columnNumber); } if (source !== undefined) { this.setSource(source); } } StackFrame.prototype = { getFunctionName: function () { return this.functionName; }, setFunctionName: function (v) { this.functionName = String(v); }, getArgs: function () { return this.args; }, setArgs: function (v) { if (Object.prototype.toString.call(v) !== '[object Array]') { throw new TypeError('Args must be an Array'); } this.args = v; }, // NOTE: Property name may be misleading as it includes the path, // but it somewhat mirrors V8's JavaScriptStackTraceApi // https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi and Gecko's // http://mxr.mozilla.org/mozilla-central/source/xpcom/base/nsIException.idl#14 getFileName: function () { return this.fileName; }, setFileName: function (v) { this.fileName = String(v); }, getLineNumber: function () { return this.lineNumber; }, setLineNumber: function (v) { if (!_isNumber(v)) { throw new TypeError('Line Number must be a Number'); } this.lineNumber = Number(v); }, getColumnNumber: function () { return this.columnNumber; }, setColumnNumber: function (v) { if (!_isNumber(v)) { throw new TypeError('Column Number must be a Number'); } this.columnNumber = Number(v); }, getSource: function () { return this.source; }, setSource: function (v) { this.source = String(v); }, toString: function () { var functionName = this.getFunctionName() || '{anonymous}'; var args = '(' + (this.getArgs() || []).join(',') + ')'; var fileName = this.getFileName() ? '@' + this.getFileName() : ''; var lineNumber = _isNumber(this.getLineNumber()) ? ':' + this.getLineNumber() : ''; var columnNumber = _isNumber(this.getColumnNumber()) ? ':' + this.getColumnNumber() : ''; return functionName + args + fileName + lineNumber + columnNumber; } }; return StackFrame; }); /***/ }), /***/ "./node_modules/elastic-apm-js-core/src/common/apm-server.js": /*!*******************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/src/common/apm-server.js ***! \*******************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * MIT License * * Copyright (c) 2017-present, Elasticsearch BV * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ var Queue = __webpack_require__(/*! ./queue */ "./node_modules/elastic-apm-js-core/src/common/queue.js"); var throttle = __webpack_require__(/*! ./throttle */ "./node_modules/elastic-apm-js-core/src/common/throttle.js"); var utils = __webpack_require__(/*! ./utils */ "./node_modules/elastic-apm-js-core/src/common/utils.js"); var NDJSON = __webpack_require__(/*! ./ndjson */ "./node_modules/elastic-apm-js-core/src/common/ndjson.js"); var xhrIgnore = __webpack_require__(/*! ./patching/patch-utils */ "./node_modules/elastic-apm-js-core/src/common/patching/patch-utils.js").XHR_IGNORE; class ApmServer { constructor(configService, loggingService) { this._configService = configService; this._loggingService = loggingService; this.logMessages = { invalidConfig: { message: 'Configuration is invalid!', level: 'warn' } }; this.errorQueue = undefined; this.transactionQueue = undefined; this.throttleAddError = undefined; this.throttleAddTransaction = undefined; this.initialized = false; this.ndjsonSpan = {}; } init() { if (this.initialized) { return; } this.initialized = true; this.initErrorQueue(); this.initTransactionQueue(); } createServiceObject() { var cfg = this._configService; var stringLimit = cfg.get('serverStringLimit'); var serviceObject = { name: utils.sanitizeString(cfg.get('serviceName'), stringLimit, true), version: utils.sanitizeString(cfg.get('serviceVersion'), stringLimit, false), agent: { name: cfg.get('agentName'), version: cfg.get('agentVersion') }, language: { name: 'javascript' } }; return serviceObject; } _postJson(endPoint, payload) { return this._makeHttpRequest('POST', endPoint, payload, { 'Content-Type': 'application/x-ndjson' }); } _makeHttpRequest(method, url, payload, headers) { return new Promise(function (resolve, reject) { var xhr = new window.XMLHttpRequest(); xhr[xhrIgnore] = true; xhr.open(method, url, true); xhr.timeout = 10000; if (headers) { for (var header in headers) { if (headers.hasOwnProperty(header)) { xhr.setRequestHeader(header, headers[header]); } } } xhr.onreadystatechange = function () { if (xhr.readyState === 4) { var status = xhr.status; if (status === 0 || status > 399 && status < 600) { // An http 4xx or 5xx error. Signal an error. var err = new Error(url + ' HTTP status: ' + status); err.xhr = xhr; reject(err); } else { resolve(xhr.responseText); } } }; xhr.onerror = function (err) { reject(err); }; xhr.send(payload); }); } _createQueue(onFlush) { var queueLimit = this._configService.get('queueLimit'); var flushInterval = this._configService.get('flushInterval'); return new Queue(onFlush, { queueLimit: queueLimit, flushInterval: flushInterval }); } initErrorQueue() { var apmServer = this; if (this.errorQueue) { this.errorQueue.flush(); } this.errorQueue = this._createQueue(function (errors) { var p = apmServer.sendErrors(errors); if (p) { p.then(undefined, function (reason) { apmServer._loggingService.warn('Failed sending errors!', reason); }); } }); var limit = apmServer._configService.get('errorThrottleLimit'); var interval = apmServer._configService.get('errorThrottleInterval'); this.throttleAddError = throttle(this.errorQueue.add.bind(this.errorQueue), function () { apmServer._loggingService.warn('Dropped error due to throttling!'); }, { limit: limit, interval: interval }); } initTransactionQueue() { var apmServer = this; if (this.transactionQueue) { this.transactionQueue.flush(); } this.transactionQueue = this._createQueue(function (transactions) { var p = apmServer.sendTransactions(transactions); if (p) { p.then(undefined, function (reason) { apmServer._loggingService.warn('Failed sending transactions!', reason); }); } }); var limit = apmServer._configService.get('transactionThrottleLimit'); var interval = apmServer._configService.get('transactionThrottleInterval'); this.throttleAddTransaction = throttle(this.transactionQueue.add.bind(this.transactionQueue), function () { apmServer._loggingService.warn('Dropped transaction due to throttling!'); }, { limit: limit, interval: interval }); } addError(error) { if (this._configService.isActive()) { if (!this.errorQueue) { this.initErrorQueue(); } this.throttleAddError(error); } } addTransaction(transaction) { if (this._configService.isActive()) { if (!this.transactionQueue) { this.initTransactionQueue(); } this.throttleAddTransaction(transaction); } } warnOnce(logObject) { if (logObject.level === 'warn') { logObject.level = 'debug'; this._loggingService.warn(logObject.message); } else { this._loggingService.debug(logObject.message); } } ndjsonErrors(errors) { return errors.map(function (error) { return NDJSON.stringify({ error: error }); }); } sendErrors(errors) { if (this._configService.isValid() && this._configService.isActive()) { if (errors && errors.length > 0) { var payload = { service: this.createServiceObject(), errors: errors }; payload = this._configService.applyFilters(payload); if (payload) { var endPoint = this._configService.getEndpointUrl('errors'); var ndjson = this.ndjsonErrors(payload.errors); ndjson.unshift(NDJSON.stringify({ metadata: { service: payload.service } })); var ndjsonPayload = ndjson.join(''); return this._postJson(endPoint, ndjsonPayload); } else { this._loggingService.warn('Dropped payload due to filtering!'); } } } else { this.warnOnce(this.logMessages.invalidConfig); } } ndjsonTransactions(transactions) { var ndjsonSpan = this.ndjsonSpan; return transactions.map(function (tr) { var spans = ''; if (tr.spans) { spans = tr.spans.map(function (sp) { ndjsonSpan.span = sp; return NDJSON.stringify(ndjsonSpan); }).join(''); delete tr.spans; } return NDJSON.stringify({ transaction: tr }) + spans; }); } sendTransactions(transactions) { if (this._configService.isValid() && this._configService.isActive()) { if (transactions && transactions.length > 0) { var payload = { service: this.createServiceObject(), transactions: transactions }; payload = this._configService.applyFilters(payload); if (payload) { var endPoint = this._configService.getEndpointUrl('transactions'); var ndjson = this.ndjsonTransactions(payload.transactions); ndjson.unshift(NDJSON.stringify({ metadata: { service: payload.service } })); var ndjsonPayload = ndjson.join(''); return this._postJson(endPoint, ndjsonPayload); } else { this._loggingService.warn('Dropped payload due to filtering!'); } } } else { this.warnOnce(this.logMessages.invalidConfig); } } } module.exports = ApmServer; /***/ }), /***/ "./node_modules/elastic-apm-js-core/src/common/config-service.js": /*!***********************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/src/common/config-service.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * MIT License * * Copyright (c) 2017-present, Elasticsearch BV * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ const { getCurrentScript, sanitizeString, setTag, merge } = __webpack_require__(/*! ./utils */ "./node_modules/elastic-apm-js-core/src/common/utils.js"); const Subscription = __webpack_require__(/*! ../common/subscription */ "./node_modules/elastic-apm-js-core/src/common/subscription.js"); const constants = __webpack_require__(/*! ./constants */ "./node_modules/elastic-apm-js-core/src/common/constants.js"); function getConfigFromScript() { var script = getCurrentScript(); var config = getDataAttributesFromNode(script); return config; } function getDataAttributesFromNode(node) { if (!node) { return {}; } var dataAttrs = {}; var dataRegex = /^data-([\w-]+)$/; var attrs = node.attributes; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (dataRegex.test(attr.nodeName)) { var key = attr.nodeName.match(dataRegex)[1]; // camelCase key var camelCasedkey = key.split('-').map((value, index) => { return index > 0 ? value.charAt(0).toUpperCase() + value.substring(1) : value; }).join(''); dataAttrs[camelCasedkey] = attr.value || attr.nodeValue; } } return dataAttrs; } class Config { constructor() { this.config = {}; this.defaults = { serviceName: '', serviceVersion: '', agentName: 'js-base', agentVersion: '%%agent-version%%', serverUrl: 'http://localhost:8200', serverUrlPrefix: '/intake/v2/rum/events', active: true, debug: false, logLevel: 'warn', browserResponsivenessInterval: 500, browserResponsivenessBuffer: 3, checkBrowserResponsiveness: true, groupSimilarSpans: true, similarSpanThreshold: 0.05, capturePageLoad: true, ignoreTransactions: [], // throttlingRequestLimit: 20, // throttlingInterval: 30000, // 30s errorThrottleLimit: 20, errorThrottleInterval: 30000, transactionThrottleLimit: 20, transactionThrottleInterval: 30000, transactionDurationThreshold: 60000, queueLimit: -1, flushInterval: 500, sendPageLoadTransaction: true, serverStringLimit: constants.serverStringLimit, distributedTracing: true, distributedTracingOrigins: [], distributedTracingHeaderValueCallback: undefined, distributedTracingHeaderName: 'elastic-apm-traceparent', pageLoadTraceId: undefined, pageLoadSpanId: undefined, pageLoadSampled: undefined, pageLoadTransactionName: undefined, transactionSampleRate: 1.0, context: {}, platform: {} }; this._changeSubscription = new Subscription(); this.filters = []; } init() { var scriptData = getConfigFromScript(); this.setConfig(scriptData); } isActive() { return this.get('active'); } addFilter(cb) { if (typeof cb !== 'function') { throw new Error('Argument to must be function'); } this.filters.push(cb); } applyFilters(data) { for (var i = 0; i < this.filters.length; i++) { data = this.filters[i](data); if (!data) { return; } } return data; } get(key) { return key.split('.').reduce((obj, objKey) => { return obj && obj[objKey]; }, this.config); } getEndpointUrl() { var url = this.get('serverUrl') + this.get('serverUrlPrefix'); return url; } set(key, value) { var levels = key.split('.'); var maxLevel = levels.length - 1; var target = this.config; for (let i = 0; i < maxLevel + 1; i++) { const level = levels[i]; if (!level) { continue; } if (i === maxLevel) { target[level] = value; } else { var obj = target[level] || {}; target[level] = obj; target = obj; } } } setUserContext(userContext) { var context = {}; if (typeof userContext.id === 'number') { context.id = userContext.id; } if (typeof userContext.id === 'string') { context.id = sanitizeString(userContext.id, this.get('serverStringLimit')); } if (typeof userContext.username === 'string') { context.username = sanitizeString(userContext.username, this.get('serverStringLimit')); } if (typeof userContext.email === 'string') { context.email = sanitizeString(userContext.email, this.get('serverStringLimit')); } this.set('context.user', context); } setCustomContext(customContext) { if (customContext && typeof customContext === 'object') { this.set('context.custom', customContext); } } setTag(key, value) { if (!key) return; if (!this.config.context.tags) { this.config.context.tags = {}; } setTag(key, value, this.config.context.tags); } addTags(tags) { var keys = Object.keys(tags); keys.forEach(k => { this.setTag(k, tags[k]); }); } setConfig(properties) { properties = properties || {}; this.config = merge({}, this.defaults, this.config, properties); this._changeSubscription.applyAll(this, [this.config]); } subscribeToChange(fn) { return this._changeSubscription.subscribe(fn); } isValid() { const requiredKeys = ['serviceName', 'serverUrl']; for (let i = 0; i < requiredKeys.length; i++) { const key = requiredKeys[i]; if (this.config[key] == null || this.config[key] === '') { return false; } } return true; } } module.exports = Config; /***/ }), /***/ "./node_modules/elastic-apm-js-core/src/common/constants.js": /*!******************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/src/common/constants.js ***! \******************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** * MIT License * * Copyright (c) 2017-present, Elasticsearch BV * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ /** * Task States */ const SCHEDULE = 'schedule'; const INVOKE = 'invoke'; const CLEAR = 'clear'; /** * Request Sources */ const FETCH_SOURCE = 'fetch'; const XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send'; /** * Event listener methods */ const ADD_EVENT_LISTENER_STR = 'addEventListener'; const REMOVE_EVENT_LISTENER_STR = 'removeEventListener'; /** * Others */ const serverStringLimit = 1024; module.exports = { SCHEDULE, INVOKE, CLEAR, FETCH_SOURCE, XMLHTTPREQUEST_SOURCE, ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, serverStringLimit }; /***/ }), /***/ "./node_modules/elastic-apm-js-core/src/common/logging-service.js": /*!************************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/src/common/logging-service.js ***! \************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * MIT License * * Copyright (c) 2017-present, Elasticsearch BV * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ const { noop } = __webpack_require__(/*! ./utils */ "./node_modules/elastic-apm-js-core/src/common/utils.js"); class LoggingService { constructor(spec) { if (!spec) spec = {}; this.levels = ['trace', 'debug', 'info', 'warn', 'error']; this.level = spec.level || 'info'; this.prefix = spec.prefix || ''; this.resetLogMethods(); } shouldLog(level) { return this.levels.indexOf(level) >= this.levels.indexOf(this.level); } setLevel(level) { this.level = level; this.resetLogMethods(); } resetLogMethods() { var loggingService = this; this.levels.forEach(function (level) { loggingService[level] = loggingService.shouldLog(level) ? log : noop; function log() { var prefix = loggingService.prefix; var normalizedLevel; switch (level) { case 'trace': normalizedLevel = 'info'; break; case 'debug': normalizedLevel = 'info'; break; default: normalizedLevel = level; } var args = arguments; if (prefix) { if (typeof prefix === 'function') prefix = prefix(level); args[0] = prefix + args[0]; } if (console) { var realMethod = console[normalizedLevel] ? console[normalizedLevel] : console.log; if (typeof realMethod === 'function') { realMethod.apply(console, args); } } } }); } } module.exports = LoggingService; /***/ }), /***/ "./node_modules/elastic-apm-js-core/src/common/ndjson.js": /*!***************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/src/common/ndjson.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** * MIT License * * Copyright (c) 2017-present, Elasticsearch BV * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ class NDJSON { static stringify(object) { return JSON.stringify(object) + '\n'; } } module.exports = NDJSON; /***/ }), /***/ "./node_modules/elastic-apm-js-core/src/common/patching/fetch-patch.js": /*!*****************************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/src/common/patching/fetch-patch.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * MIT License * * Copyright (c) 2017-present, Elasticsearch BV * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ const { globalState } = __webpack_require__(/*! ./patch-utils */ "./node_modules/elastic-apm-js-core/src/common/patching/patch-utils.js"); const { SCHEDULE, INVOKE, FETCH_SOURCE } = __webpack_require__(/*! ../constants */ "./node_modules/elastic-apm-js-core/src/common/constants.js"); var alreadyPatched = false; function patchFetch(callback) { if (alreadyPatched) { return; } alreadyPatched = true; if (!window.fetch || !window.Request) { return; } function scheduleTask(task) { task.state = SCHEDULE; callback(SCHEDULE, task); } function invokeTask(task) { task.state = INVOKE; callback(INVOKE, task); } var nativeFetch = window.fetch; window.fetch = function (input, init) { var fetchSelf = this; var args = arguments; var request, url; if (typeof input === 'string') { request = new Request(input, init); url = input; } else if (input) { request = input; url = request.url; } else { return nativeFetch.apply(fetchSelf, args); } const task = { source: FETCH_SOURCE, state: '', type: 'macroTask', data: { target: request, method: request.method, sync: false, url: url, args: arguments, aborted: false } }; return new Promise(function (resolve, reject) { globalState.fetchInProgress = true; scheduleTask(task); var promise; try { promise = nativeFetch.apply(fetchSelf, [request]); } catch (error) { reject(error); task.data.error = error; invokeTask(task); globalState.fetchInProgress = false; return; } promise.then(function (response) { resolve(response); task.data.response = response; invokeTask(task); }, function (error) { reject(error); task.data.error = error; invokeTask(task); }); globalState.fetchInProgress = false; }); }; } module.exports = { patchFetch: patchFetch }; /***/ }), /***/ "./node_modules/elastic-apm-js-core/src/common/patching/index.js": /*!***********************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/src/common/patching/index.js ***! \***********************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * MIT License * * Copyright (c) 2017-present, Elasticsearch BV * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ var patchXMLHttpRequest = __webpack_require__(/*! ./xhr-patch */ "./node_modules/elastic-apm-js-core/src/common/patching/xhr-patch.js").patchXMLHttpRequest; var patchFetch = __webpack_require__(/*! ./fetch-patch */ "./node_modules/elastic-apm-js-core/src/common/patching/fetch-patch.js").patchFetch; var Subscription = __webpack_require__(/*! ../subscription */ "./node_modules/elastic-apm-js-core/src/common/subscription.js"); var subscription = new Subscription(); var alreadyPatched = false; function patchAll() { if (!alreadyPatched) { alreadyPatched = true; patchXMLHttpRequest(function (event, task) { subscription.applyAll(this, [event, task]); }); patchFetch(function (event, task) { subscription.applyAll(this, [event, task]); }); } return subscription; } module.exports = { patchAll, subscription }; /***/ }), /***/ "./node_modules/elastic-apm-js-core/src/common/patching/patch-utils.js": /*!*****************************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/src/common/patching/patch-utils.js ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { /** * MIT License * * Copyright (c) 2017-present, Elasticsearch BV * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ var globalState = { fetchInProgress: false }; function apmSymbol(name) { return '__apm_symbol__' + name; } function isPropertyWritable(propertyDesc) { if (!propertyDesc) { return true; } if (propertyDesc.writable === false) { return false; } return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined'); } function attachOriginToPatched(patched, original) { patched[apmSymbol('OriginalDelegate')] = original; } function patchMethod(target, name, patchFn) { var proto = target; while (proto && !proto.hasOwnProperty(name)) { proto = Object.getPrototypeOf(proto); } if (!proto && target[name]) { // somehow we did not find it, but we can see it. This happens on IE for Window properties. proto = target; } const delegateName = apmSymbol(name); var delegate; if (proto && !(delegate = proto[delegateName])) { delegate = proto[delegateName] = proto[name]; // check whether proto[name] is writable // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob const desc = proto && Object.getOwnPropertyDescriptor(proto, name); if (isPropertyWritable(desc)) { const patchDelegate = patchFn(delegate, delegateName, name); proto[name] = function () { return patchDelegate(this, arguments); }; attachOriginToPatched(proto[name], delegate); } } return delegate; } module.exports = { apmSymbol, patchMethod, globalState, XHR_IGNORE: apmSymbol('xhrIgnore'), XHR_SYNC: apmSymbol('xhrSync'), XHR_URL: apmSymbol('xhrURL'), XHR_METHOD: apmSymbol('xhrMethod') }; /***/ }), /***/ "./node_modules/elastic-apm-js-core/src/common/patching/xhr-patch.js": /*!***************************************************************************!*\ !*** ./node_modules/elastic-apm-js-core/src/common/patching/xhr-patch.js ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /** * MIT License * * Copyright (c) 2017-present, Elasticsearch BV * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ const { apmSymbol, patchMethod, XHR_SYNC, XHR_URL, XHR_METHOD, XHR_IGNORE } = __webpack_require__(/*! ./patch-utils */ "./node_modules/elastic-apm-js-core/src/common/patching/patch-utils.js"); const { SCHEDULE, INVOKE, CLEAR, XMLHTTPREQUEST_SOURCE, ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR } = __webpack_require__(/*! ../constants */ "./node_modules/elastic-apm-js-core/src/common/constants.js"); const XHR_TASK = apmSymbol('xhrTask'); const XHR_LISTENER = apmSymbol('xhrListener'); const XHR_SCHEDULED = apmSymbol('xhrScheduled'); var alreadyPatched = false; function patchXMLHttpRequest(callback) { if (alreadyPatched) { return; } alreadyPatched = true; const XMLHttpRequestPrototype = XMLHttpRequest.prototype; let oriAddListener = XMLHttpRequestPrototype[ADD_EVENT_LISTENER_STR]; let oriRemoveListener = XMLHttpRequestPrototype[REMOVE_EVENT_LISTENER_STR]; if (!oriAddListener) { const XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget']; if (XMLHttpRequestEventTarget) { const XMLHttpRequestEve